MainViewModel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using System.Collections.ObjectModel;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Windows.Input;
  5. using AGEHAB.RelatorioSeadIpasgo.Application.DTOs;
  6. using AGEHAB.RelatorioSeadIpasgo.Application.UseCases;
  7. using AGEHAB.RelatorioSeadIpasgo.Domain.Entities;
  8. using AGEHAB.RelatorioSeadIpasgo.Domain.ValueObjects;
  9. using AGEHAB.RelatorioSeadIpasgo.Presentation.Commands;
  10. using AGEHAB.RelatorioSeadIpasgo.Presentation.Services;
  11. namespace AGEHAB.RelatorioSeadIpasgo.Presentation.ViewModels;
  12. public class MainViewModel : ViewModelBase
  13. {
  14. private readonly CarregarCompetenciasUseCase _carregarCompetenciasUseCase;
  15. private readonly GerarRelatorioUseCase _gerarRelatorioUseCase;
  16. private readonly IUserDialogService _dialogService;
  17. private readonly RelayCommand _escolherZipCommand;
  18. private readonly RelayCommand _escolherExcelCommand;
  19. private readonly RelayCommand _escolherPastaCommand;
  20. private readonly RelayCommand _abrirPastaCommand;
  21. private readonly RelayCommand _cancelarCommand;
  22. private readonly AsyncRelayCommand _gerarArquivosCommand;
  23. private CancellationTokenSource? _cancellationTokenSource;
  24. private TipoRelatorioOpcao? _relatorioSelecionado;
  25. private Competencia? _competenciaSelecionada;
  26. private TipoCalculo? _tipoCalculoSelecionado;
  27. private string _zipPath;
  28. private string _excelPath;
  29. private string _pastaDestino;
  30. private string _status = "Pronto para gerar.";
  31. private bool _estaOcupado;
  32. public MainViewModel(
  33. CarregarCompetenciasUseCase carregarCompetenciasUseCase,
  34. GerarRelatorioUseCase gerarRelatorioUseCase,
  35. IUserDialogService dialogService)
  36. {
  37. _carregarCompetenciasUseCase = carregarCompetenciasUseCase;
  38. _gerarRelatorioUseCase = gerarRelatorioUseCase;
  39. _dialogService = dialogService;
  40. var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  41. _pastaDestino = desktop;
  42. _zipPath = Path.Combine(desktop, "REM202606.zip");
  43. _excelPath = Path.Combine(desktop, "Relatorio_SEAD_202606.xlsx");
  44. Relatorios = new ObservableCollection<TipoRelatorioOpcao>(TipoRelatorioOpcao.Opcoes);
  45. TiposCalculo = new ObservableCollection<TipoCalculo>(TipoCalculo.Opcoes);
  46. CarregarCommand = new AsyncRelayCommand(CarregarAsync);
  47. _gerarArquivosCommand = new AsyncRelayCommand(GerarArquivosAsync, PodeGerar);
  48. GerarArquivosCommand = _gerarArquivosCommand;
  49. _escolherZipCommand = new RelayCommand(EscolherZip, () => !EstaOcupado && ZipHabilitado);
  50. EscolherZipCommand = _escolherZipCommand;
  51. _escolherExcelCommand = new RelayCommand(EscolherExcel, () => !EstaOcupado);
  52. EscolherExcelCommand = _escolherExcelCommand;
  53. _escolherPastaCommand = new RelayCommand(EscolherPasta, () => !EstaOcupado);
  54. EscolherPastaCommand = _escolherPastaCommand;
  55. _abrirPastaCommand = new RelayCommand(AbrirPastaArquivos, () => !EstaOcupado);
  56. AbrirPastaCommand = _abrirPastaCommand;
  57. _cancelarCommand = new RelayCommand(CancelarOperacao, () => EstaOcupado);
  58. CancelarCommand = _cancelarCommand;
  59. RelatorioSelecionado = Relatorios.FirstOrDefault();
  60. TipoCalculoSelecionado = TiposCalculo.FirstOrDefault(tipoCalculo => tipoCalculo.Valor == "1,2,3");
  61. }
  62. public ObservableCollection<TipoRelatorioOpcao> Relatorios { get; }
  63. public ObservableCollection<Competencia> Competencias { get; } = [];
  64. public ObservableCollection<TipoCalculo> TiposCalculo { get; }
  65. public TipoRelatorioOpcao? RelatorioSelecionado
  66. {
  67. get => _relatorioSelecionado;
  68. set
  69. {
  70. if (SetProperty(ref _relatorioSelecionado, value))
  71. {
  72. OnPropertyChanged(nameof(ZipHabilitado));
  73. OnPropertyChanged(nameof(IpasgoSelecionado));
  74. OnPropertyChanged(nameof(AlturaJanela));
  75. AtualizarNomeArquivos();
  76. AtualizarComandos();
  77. }
  78. }
  79. }
  80. public Competencia? CompetenciaSelecionada
  81. {
  82. get => _competenciaSelecionada;
  83. set
  84. {
  85. if (SetProperty(ref _competenciaSelecionada, value))
  86. {
  87. AtualizarNomeArquivos();
  88. AtualizarComandos();
  89. }
  90. }
  91. }
  92. public TipoCalculo? TipoCalculoSelecionado
  93. {
  94. get => _tipoCalculoSelecionado;
  95. set
  96. {
  97. if (SetProperty(ref _tipoCalculoSelecionado, value))
  98. {
  99. AtualizarNomeArquivos();
  100. AtualizarComandos();
  101. }
  102. }
  103. }
  104. public string ZipPath
  105. {
  106. get => _zipPath;
  107. set => SetProperty(ref _zipPath, value);
  108. }
  109. public string ExcelPath
  110. {
  111. get => _excelPath;
  112. set => SetProperty(ref _excelPath, value);
  113. }
  114. public string PastaDestino
  115. {
  116. get => _pastaDestino;
  117. set
  118. {
  119. if (SetProperty(ref _pastaDestino, value))
  120. {
  121. AtualizarNomeArquivos();
  122. }
  123. }
  124. }
  125. public string Status
  126. {
  127. get => _status;
  128. set => SetProperty(ref _status, value);
  129. }
  130. public bool EstaOcupado
  131. {
  132. get => _estaOcupado;
  133. set
  134. {
  135. if (SetProperty(ref _estaOcupado, value))
  136. {
  137. OnPropertyChanged(nameof(ZipHabilitado));
  138. OnPropertyChanged(nameof(CursorAtual));
  139. AtualizarComandos();
  140. }
  141. }
  142. }
  143. public bool ZipHabilitado => !EstaOcupado && RelatorioSelecionado?.EhIpasgo == true;
  144. public bool CamposHabilitados => !EstaOcupado;
  145. public bool CancelamentoHabilitado => EstaOcupado;
  146. public bool IpasgoSelecionado => RelatorioSelecionado?.EhIpasgo == true;
  147. public double AlturaJanela => IpasgoSelecionado ? 640 : 560;
  148. public Cursor CursorAtual => EstaOcupado ? Cursors.Wait : Cursors.Arrow;
  149. public ICommand CarregarCommand { get; }
  150. public ICommand GerarArquivosCommand { get; }
  151. public ICommand EscolherZipCommand { get; }
  152. public ICommand EscolherExcelCommand { get; }
  153. public ICommand EscolherPastaCommand { get; }
  154. public ICommand AbrirPastaCommand { get; }
  155. public ICommand CancelarCommand { get; }
  156. private async Task CarregarAsync()
  157. {
  158. _cancellationTokenSource?.Dispose();
  159. _cancellationTokenSource = new CancellationTokenSource();
  160. EstaOcupado = true;
  161. Status = "Carregando competências...";
  162. try
  163. {
  164. var competencias = await _carregarCompetenciasUseCase.ExecutarAsync(_cancellationTokenSource.Token);
  165. Competencias.Clear();
  166. foreach (var competencia in competencias)
  167. {
  168. Competencias.Add(competencia);
  169. }
  170. CompetenciaSelecionada = Competencias.FirstOrDefault();
  171. Status = Competencias.Count > 0 ? "Pronto para gerar." : "Nenhuma competência encontrada.";
  172. if (Competencias.Count == 0)
  173. {
  174. _dialogService.Alertar("Nenhuma competência foi encontrada em FP_COMPETENCIAS.", "Competências");
  175. }
  176. }
  177. catch (OperationCanceledException)
  178. {
  179. Status = "Operação cancelada pelo usuário.";
  180. }
  181. catch (Exception ex)
  182. {
  183. Status = "Erro ao carregar competências.";
  184. _dialogService.ExibirErro(ex.Message);
  185. }
  186. finally
  187. {
  188. _cancellationTokenSource?.Dispose();
  189. _cancellationTokenSource = null;
  190. EstaOcupado = false;
  191. }
  192. }
  193. private async Task GerarArquivosAsync()
  194. {
  195. if (!ValidarCampos())
  196. {
  197. return;
  198. }
  199. if (!ConfirmarSubstituicoes())
  200. {
  201. return;
  202. }
  203. _cancellationTokenSource?.Dispose();
  204. _cancellationTokenSource = new CancellationTokenSource();
  205. EstaOcupado = true;
  206. Status = "Gerando arquivos...";
  207. try
  208. {
  209. var request = new GerarRelatorioRequest(
  210. CompetenciaSelecionada!,
  211. RelatorioSelecionado!,
  212. TipoCalculoSelecionado!,
  213. ZipPath,
  214. ExcelPath);
  215. await _gerarRelatorioUseCase.ExecutarAsync(request, _cancellationTokenSource.Token);
  216. Status = "Arquivos gerados com sucesso.";
  217. _dialogService.Informar("Arquivos gerados com sucesso.", "Concluído");
  218. }
  219. catch (OperationCanceledException)
  220. {
  221. Status = "Operação cancelada pelo usuário.";
  222. }
  223. catch (Exception ex)
  224. {
  225. if (EhCancelamentoSolicitado(ex))
  226. {
  227. Status = "Operação cancelada pelo usuário.";
  228. return;
  229. }
  230. Status = "Erro ao gerar arquivos.";
  231. _dialogService.ExibirErro(ex.Message);
  232. }
  233. finally
  234. {
  235. _cancellationTokenSource?.Dispose();
  236. _cancellationTokenSource = null;
  237. EstaOcupado = false;
  238. }
  239. }
  240. private void CancelarOperacao()
  241. {
  242. Status = "Cancelando...";
  243. _cancellationTokenSource?.Cancel();
  244. }
  245. private void EscolherZip()
  246. {
  247. var fileName = _dialogService.EscolherArquivoParaSalvar("Salvar arquivo ZIP", "Arquivo ZIP (*.zip)|*.zip", ".zip", ZipPath);
  248. if (fileName != null)
  249. {
  250. ZipPath = fileName;
  251. }
  252. }
  253. private void EscolherExcel()
  254. {
  255. var fileName = _dialogService.EscolherArquivoParaSalvar("Salvar arquivo Excel", "Arquivo Excel (*.xlsx)|*.xlsx", ".xlsx", ExcelPath);
  256. if (fileName != null)
  257. {
  258. ExcelPath = fileName;
  259. }
  260. }
  261. private void EscolherPasta()
  262. {
  263. var pasta = _dialogService.EscolherPasta("Selecionar pasta de destino", PastaDestino);
  264. if (pasta != null)
  265. {
  266. PastaDestino = pasta;
  267. }
  268. }
  269. private void AbrirPastaArquivos()
  270. {
  271. if (!Directory.Exists(PastaDestino))
  272. {
  273. _dialogService.Alertar("Nenhuma pasta foi encontrada para abrir.", "Pastas");
  274. return;
  275. }
  276. AbrirCaminho(PastaDestino);
  277. }
  278. private bool ValidarCampos()
  279. {
  280. if (RelatorioSelecionado == null)
  281. {
  282. _dialogService.Alertar("Selecione o relatório.", "Validação");
  283. return false;
  284. }
  285. if (CompetenciaSelecionada == null)
  286. {
  287. _dialogService.Alertar("Selecione uma competência.", "Validação");
  288. return false;
  289. }
  290. if (TipoCalculoSelecionado == null)
  291. {
  292. _dialogService.Alertar("Selecione um tipo de cálculo.", "Validação");
  293. return false;
  294. }
  295. if (RelatorioSelecionado.EhIpasgo && string.IsNullOrWhiteSpace(ZipPath))
  296. {
  297. _dialogService.Alertar("Escolha onde salvar o ZIP do IPASGO.", "Validação");
  298. return false;
  299. }
  300. if (string.IsNullOrWhiteSpace(ExcelPath))
  301. {
  302. _dialogService.Alertar("Escolha onde salvar o Excel.", "Validação");
  303. return false;
  304. }
  305. return true;
  306. }
  307. private bool ConfirmarSubstituicoes()
  308. {
  309. if (RelatorioSelecionado?.EhIpasgo == true && File.Exists(ZipPath) && !_dialogService.ConfirmarSubstituicao(ZipPath))
  310. {
  311. return false;
  312. }
  313. if (File.Exists(ExcelPath) && !_dialogService.ConfirmarSubstituicao(ExcelPath))
  314. {
  315. return false;
  316. }
  317. return true;
  318. }
  319. private bool PodeGerar()
  320. {
  321. return !EstaOcupado && RelatorioSelecionado != null && CompetenciaSelecionada != null && TipoCalculoSelecionado != null;
  322. }
  323. private static bool EhCancelamentoSolicitado(Exception ex)
  324. {
  325. return ex.Message.Contains("Operação cancelada pelo usuário", StringComparison.OrdinalIgnoreCase) ||
  326. ex.Message.Contains("Operation cancelled", StringComparison.OrdinalIgnoreCase) ||
  327. ex.Message.Contains("Operation canceled", StringComparison.OrdinalIgnoreCase);
  328. }
  329. private void AtualizarNomeArquivos()
  330. {
  331. if (CompetenciaSelecionada == null || RelatorioSelecionado == null || TipoCalculoSelecionado == null)
  332. {
  333. return;
  334. }
  335. ZipPath = Path.Combine(PastaDestino, $"REM{CompetenciaSelecionada.Referencia}.zip");
  336. ExcelPath = Path.Combine(PastaDestino, $"Relatorio_{RelatorioSelecionado.PrefixoArquivo}_{CompetenciaSelecionada.Referencia}_{TipoCalculoSelecionado.NomeArquivo}.xlsx");
  337. }
  338. private void AtualizarComandos()
  339. {
  340. _gerarArquivosCommand.RaiseCanExecuteChanged();
  341. _escolherZipCommand.RaiseCanExecuteChanged();
  342. _escolherExcelCommand.RaiseCanExecuteChanged();
  343. _escolherPastaCommand.RaiseCanExecuteChanged();
  344. _abrirPastaCommand.RaiseCanExecuteChanged();
  345. _cancelarCommand.RaiseCanExecuteChanged();
  346. OnPropertyChanged(nameof(ZipHabilitado));
  347. OnPropertyChanged(nameof(CamposHabilitados));
  348. OnPropertyChanged(nameof(CancelamentoHabilitado));
  349. OnPropertyChanged(nameof(CursorAtual));
  350. OnPropertyChanged(nameof(IpasgoSelecionado));
  351. OnPropertyChanged(nameof(AlturaJanela));
  352. }
  353. private static void AbrirCaminho(string caminho)
  354. {
  355. Process.Start(new ProcessStartInfo(caminho)
  356. {
  357. UseShellExecute = true
  358. });
  359. }
  360. private static void AdicionarPastaSeExistir(HashSet<string> pastas, string caminhoArquivo)
  361. {
  362. var pasta = Path.GetDirectoryName(caminhoArquivo);
  363. if (!string.IsNullOrWhiteSpace(pasta) && Directory.Exists(pasta))
  364. {
  365. pastas.Add(pasta);
  366. }
  367. }
  368. private static string ObterDiretorioInicial(string caminhoAtual)
  369. {
  370. var diretorio = Path.GetDirectoryName(caminhoAtual);
  371. if (!string.IsNullOrWhiteSpace(diretorio) && Directory.Exists(diretorio))
  372. {
  373. return diretorio;
  374. }
  375. return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  376. }
  377. }