Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 35.76 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using StructureMap;
  7. using Uon.Log.Interfaces;
  8. using System.IO;
  9. using LusoRouxTI.IO;
  10. using LusoRouxTI.Xml.Serialization;
  11. using LusoRouxTI.Extensions;
  12. using LusoRouxTI.IO.Compression;
  13. using System.Xml.Serialization;
  14. using Uon.UonDateTime;
  15. using Uon.Portal.UnitOfWork;
  16. using Uon.Portal.Business.BPM;
  17. using Uon.Data.UnitOfWork.Interfaces;
  18. using Uon.Portal.Entities;
  19. using LusoRouxTI.Doc.Excel.AsposeExcel;
  20. using System.Globalization;
  21. using Uon.Portal.Business.Core;
  22. using LusoRouxTI.Sms;
  23. using LuxoRouxTI.Sms.Factory;
  24. using SMS.UnitOfWork;
  25. using Uon.Portal.Business.Comm;
  26.  
  27. namespace Uon.Portal.Integration.Generali.Cobranca
  28. {
  29. class Program
  30. {
  31. private enum FileExtensions
  32. {
  33. [XmlEnum(".rar")]
  34. Rar,
  35. [XmlEnum(".zip")]
  36. Zip
  37. }
  38.  
  39. private enum LembreteAtraso
  40. {
  41. Lembrete,
  42. Atraso
  43. }
  44.  
  45. private enum IntegracaoLogMessage
  46. {
  47. [XmlEnum("GeneraliCobrança - File Downloaded")]
  48. DownloadFile,
  49. [XmlEnum("GeneraliCobrança - Start processing the file")]
  50. StartProcessingFile,
  51. [XmlEnum("GeneraliCobrança - File Processed with Success")]
  52. ProcessedFile,
  53. [XmlEnum("GeneraliCobrança - Error after try processing the file")]
  54. ErrorFile
  55. }
  56.  
  57. private enum UonState
  58. {
  59. Processado = 1,
  60. Ignorar = 0,
  61. Erro = -1,
  62. ErroSms = -2,
  63. ErroEmail = -3
  64. }
  65.  
  66. //Log variable
  67. private static ILog log;
  68.  
  69. //Paths
  70. private static IEnumerable<string> storageWritePaths;
  71. private static string originalLocationOfFiles;
  72. private static string locationDownloadedFiles;
  73. private static string locationProcessedFiles;
  74. private static string locationErrorFiles;
  75.  
  76. private static List<string> listOfCodeProducts;
  77. private static int daysBefore, daysAfter;
  78. private static int? columnCodigoProdutoIndex, columnDataVencimentoIndex, columnEmailIndex;
  79.  
  80. private static Dictionary<int, Tuple<int, int>> dictionaryTel; //contem os indices das colunas
  81. private static int processId;
  82. private static int errorCounter;
  83.  
  84.  
  85. static void Main(string[] args)
  86. {
  87. // Initialize the Log 4 Net
  88. ObjectFactory.Initialize(x => x.PullConfigurationFromAppConfig = true);
  89. log = ObjectFactory.GetInstance<ILog>();
  90.  
  91. try
  92. {
  93. processId = GetProcessId();
  94.  
  95. // Get the value of paths or return exception
  96. GetPaths(out storageWritePaths, out originalLocationOfFiles, out locationDownloadedFiles, out locationProcessedFiles, out locationErrorFiles);
  97.  
  98. // create directories for download, processed and error files.
  99. CreateFoldersDownloadAndProcessedAndError(storageWritePaths, locationDownloadedFiles, locationProcessedFiles, locationErrorFiles);
  100.  
  101. // The path correspond a file path
  102. if (File.Exists(originalLocationOfFiles))
  103. {
  104. ProcessFile(originalLocationOfFiles);
  105. }
  106. // The path is from a directory
  107. else if (Directory.Exists(originalLocationOfFiles))
  108. {
  109. // get file paths in folder
  110. var filePaths = GetFilesPathFromDirectory(originalLocationOfFiles);
  111. foreach (string file in filePaths)
  112. {
  113. try
  114. {
  115. ProcessFile(originalLocationOfFiles);
  116. }
  117. catch (Exception ex)
  118. {
  119. try { log.Error(new LogEntry { Exception = ex, Tag = "GeneraliCobrança" }); }
  120. catch { }
  121. }
  122. }
  123. }
  124. else
  125. {
  126. try
  127. {
  128. log.Error(new LogEntry { Message = "O caminho do ficheiro ou do diretório a processar não é válido.", Tag = "GeneraliCobrança" });
  129. }
  130. catch { }
  131. }
  132. }
  133. catch (Exception ex)
  134. {
  135. try { log.Error(new LogEntry { Exception = ex, Tag = "GeneraliCobrança" }); }
  136. catch { }
  137. }
  138. }
  139.  
  140.  
  141. private static int GetProcessId()
  142. {
  143. using (var uow = new UnitOfWorkPortal())
  144. {
  145. int objSubCategoriaIdOfProcess = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"]);
  146. string refExternaOfProcess = System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"];
  147. int processoId = new ObjProcessoService(uow).Get().Where(x => x.ObjSubCategoriaId == objSubCategoriaIdOfProcess && x.ObjRefExterna == refExternaOfProcess).Select(x => x.Id).FirstOrDefault();
  148. if (processoId == 0)
  149. {
  150. throw new ArgumentException("Não foi encontrado um processoId referente ao obj que contem a subCategoriaId: " + System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"] + ", e, com a refExterna: " + System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"]);
  151. }
  152. return processoId;
  153. }
  154. }
  155.  
  156.  
  157. private static void GetPaths(out IEnumerable<string> storageWritePaths, out string originalLocationOfFiles, out string locationDownloadedFiles, out string locationProcessedFiles, out string locationErrorFiles)
  158. {
  159. storageWritePaths = (System.Configuration.ConfigurationManager.AppSettings["StorageWritePaths"] ?? string.Empty).Split(',', ';');
  160. if (string.IsNullOrWhiteSpace(storageWritePaths.FirstOrDefault()))
  161. {
  162. storageWritePaths = null;
  163. }
  164. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationToGetFiles"]))
  165. {
  166. throw new ArgumentException("FolderLocationToGetFiles in app.config is null or empty");
  167. }
  168. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocatioOfDownloadedFiles"]))
  169. {
  170. throw new ArgumentException("FolderLocationOfDownloadedFiles in app.config is null or empty");
  171. }
  172. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfProcessedFiles"]))
  173. {
  174. throw new ArgumentException("FolderLocationOfProcessedFiles in app.config is null or empty");
  175. }
  176. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfErrorFile"]))
  177. {
  178. throw new ArgumentException("FolderLocationOfErrorFile in app.config is null or empty");
  179. }
  180. originalLocationOfFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationToGetFiles"];
  181. locationDownloadedFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocatioOfDownloadedFiles"];
  182. locationProcessedFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfProcessedFiles"];
  183. locationErrorFiles = System.Configuration.ConfigurationManager.AppSettings["FolderLocationOfErrorFiles"];
  184. }
  185.  
  186.  
  187. private static void CreateFoldersDownloadAndProcessedAndError(IEnumerable<string> storageWritePaths, string locationDownloadedFiles, string locationProcessedFiles, string locationErrorFiles)
  188. {
  189. string downloadedFolder = new StorageManager().GetAvailableWritePath(locationDownloadedFiles, storageWritePaths);
  190. Directory.CreateDirectory(downloadedFolder);
  191. string processedFolder = new StorageManager().GetAvailableWritePath(locationProcessedFiles, storageWritePaths);
  192. Directory.CreateDirectory(processedFolder);
  193. string errorFolder = new StorageManager().GetAvailableWritePath(locationErrorFiles, storageWritePaths);
  194. Directory.CreateDirectory(errorFolder);
  195. }
  196.  
  197. private static IntegracaoLog GetIntegracaoLog( IntegracaoLogService integracaoLogService, string filename)
  198. {
  199. var integracaoLog = integracaoLogService.GetByCliExternalId(Path.GetFileName(filename)).OrderByDescending(x => x.Id).FirstOrDefault();
  200.  
  201. if (integracaoLog == null)
  202. {
  203. integracaoLog = GetNewIntegracaoLog(2, filename, processId, IntegracaoLogMessage.DownloadFile.ReadXmlEnumAttribute(), null, null, null, null, null);
  204. integracaoLogService.Add(integracaoLog);
  205. }
  206. return integracaoLog;
  207. }
  208.  
  209.  
  210. private static void ProcessFile(string pathFile)
  211. {
  212. string fileExtension = Path.GetExtension(pathFile);
  213. string filenameWithoutExtension = Path.GetFileNameWithoutExtension(pathFile);
  214. string datetimeNow = UONDateTime.Now.Ticks.ToString();
  215.  
  216. //Rename current file
  217. string newNameWithCurrentTicks = Path.ChangeExtension(Path.Combine(filenameWithoutExtension, "_" + datetimeNow), fileExtension);
  218. System.IO.File.Move(pathFile, newNameWithCurrentTicks);
  219.  
  220. //Copy file to folder of dowload
  221. string newPathDowloadedFile = Path.Combine(locationDownloadedFiles, Path.GetFileName(newNameWithCurrentTicks));
  222. System.IO.File.Copy(newNameWithCurrentTicks, newPathDowloadedFile);
  223.  
  224. //Protect and verify value of objSubCategoriaId and refExterna in app.config. Its necessary your values, to get the processId.
  225. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ObjSubCategoriaIdOfProcess"]))
  226. {
  227. throw new ArgumentException("ObjSubCategoriaIdOfProcess in app.config is null or empty");
  228. }
  229. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["RefExternaOfProcess"]))
  230. {
  231. throw new ArgumentException("RefExternaOfProcess in app.config is null or empty");
  232. }
  233.  
  234. using (var uow = new UnitOfWorkPortal())
  235. {
  236. var integracaoLogService = new IntegracaoLogService(uow);
  237. GetIntegracaoLog(integracaoLogService, newNameWithCurrentTicks);
  238. uow.Commit();
  239.  
  240. //Delete original file
  241. System.IO.File.Delete(newNameWithCurrentTicks);
  242.  
  243. // Verify if extension is zip or rar. If true, is necessary unzip and get the file.
  244. // in this case, each zip is a single file compressed.
  245. if (fileExtension.Equals(FileExtensions.Rar.ReadXmlEnumAttribute()) || fileExtension.Equals(FileExtensions.Zip.ReadXmlEnumAttribute()))
  246. {
  247. //unizp the file
  248. LusoRouxTI.IO.Compression.Compressor.UnzipFile(newPathDowloadedFile, locationDownloadedFiles);
  249. //delete zip file
  250. System.IO.File.Delete(newPathDowloadedFile);
  251. }
  252.  
  253. // only get files that finish with .csv
  254. string[] csvFiles = Directory.GetFiles(locationDownloadedFiles, "*.csv");
  255.  
  256. //Process/read csv files in location
  257. foreach (string csvFilePath in csvFiles)
  258. {
  259. ReadAndProcessCSVFile(csvFilePath);
  260. }
  261.  
  262. // Obtenho o numero de erros para este ficheiro, de acordo com o id maior, ou seja o ultimo a ser adicionado (mais recente).
  263. var numberOfErrors = integracaoLogService.GetByCliExternalId(Path.GetFileName(newNameWithCurrentTicks)).OrderByDescending(x => x.Id).Select(x => x.ErrorCounter).FirstOrDefault();
  264.  
  265. // Verificar se error counter deste ficheiro existe e é menor que o numero de erros permitido na app.config.
  266. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ErrorCounter"]))
  267. {
  268. throw new ArgumentException("ErrorCounter in app.config is null or empty");
  269. }
  270. if (numberOfErrors < int.Parse(System.Configuration.ConfigurationManager.AppSettings["ErrorCounter"]))
  271. {
  272. //Mover para pasta de erro
  273. //string newNameWithCurrentTicks = Path.Combine(filenameWithoutExtension, "_" + datetimeNow + fileExtension);
  274. //System.IO.File.Move(pathFile, newNameWithCurrentTicks);
  275. }
  276. }
  277. }
  278.  
  279.  
  280. /// <summary>
  281. /// Devolve um objeto IntegracaoLog.
  282. /// </summary>
  283. /// <param name="integracaoLogEstadoId">Correpsonde ao estado do ficheiro, possuindo um dos valores da tabela integracaoLogEstadoId</param>
  284. /// <param name="fullPath">Corresponde ao caminho completo do ficheiro.</param>
  285. /// <param name="processoId">Corresponde ao processoId a que este ficheiro pertence</param>
  286. /// <param name="obs">Contem uma mensagem do Enum IntegracaoLogMessage para compreender o estado do ficheiro.</param>
  287. /// <param name="errorCounter">Contador de erros, podendo ir no maximo ate 5.</param>
  288. /// <param name="errorDate">Corresponde à data do fim de qualquer processamento e possuir um erro.</param>
  289. /// <param name="errorMessage">Corresponde à mensagem de erro.</param>
  290. /// <param name="dataConfirmacao">Corresponde à data de processamento com sucesso.</param>
  291. /// <param name="finalPath"> Contém o valor que será guardado em XML Response, que corresponde ao caminho final do ficheiro. Seja ao fim de 5 tentativas e dando erro, ou no caso de sucesso.</param>
  292. /// <returns></returns>
  293. private static IntegracaoLog GetNewIntegracaoLog(int integracaoLogEstadoId, string fullPath, int processoId, string obs, int? errorCounter, DateTime? errorDate, string errorMessage, DateTime? dataConfirmacao, string finalPath)
  294. {
  295. var integracaoLog = new IntegracaoLog();
  296. integracaoLog.UtilizadorId = 1;
  297. integracaoLog.Data = UONDateTime.Now;
  298. integracaoLog.IntegracaoLogEstadoId = integracaoLogEstadoId;
  299. integracaoLog.ObjProcessoObjId = processoId;
  300. integracaoLog.XmlFicheiro = fullPath;
  301. integracaoLog.CliExternalID = Path.GetFileName(fullPath);
  302. integracaoLog.Obs = obs;
  303. integracaoLog.ErrorCounter = errorCounter;
  304. integracaoLog.ErrorDate = errorDate;
  305. integracaoLog.ErrorMessage = errorMessage;
  306. integracaoLog.DataConfirmacao = dataConfirmacao;
  307. integracaoLog.XMLResponse = finalPath;
  308. return integracaoLog;
  309. }
  310.  
  311. // TODO -> INCREMETNAR error COUNTER DO INTEGRACAO LOG-> usar getvalueordefault +1
  312. // TODO -> GETBYNOME DO FICHEIRO (cleExternalid (ex: test.txt)) -> path.getfilename()
  313. // TODO -> adicionar o path total no xmlFicheiro (do file)
  314. // TODO -> data confirmacao -> datas de sucesso
  315.  
  316. // TODO -> data erro -> data quanto acabar o processamento e tiver algum erro
  317. // TODO -> xml response -> vai ter o caminho quando atingir as 5 tentativas de erro, ou sucesso
  318.  
  319.  
  320.  
  321.  
  322. private static void ReadAndProcessCSVFile(string csvFilePath)
  323. {
  324. try
  325. {
  326. // Verify if name of columns to be considered is defined
  327. VerifyColumnsForConsideration();
  328.  
  329. // Add information in integrationLog about start processing the file
  330. using (IUnitOfWork uow = new UnitOfWorkPortal())
  331. {
  332. IntegracaoLogService currentIntegracaoLogService = new IntegracaoLogService(uow);
  333.  
  334. var integracaoLog = GetIntegracaoLog(currentIntegracaoLogService, csvFilePath);
  335. integracaoLog.IntegracaoLogEstadoId = 4;
  336. integracaoLog.Obs = IntegracaoLogMessage.StartProcessingFile.ReadXmlEnumAttribute();
  337. uow.Commit();
  338. }
  339.  
  340. var fileAspose = new AsposeExcel(csvFilePath);
  341.  
  342. // Get column index where is null ,and get the index of necessary columns.
  343. int columnIndex = 0;
  344.  
  345. int columnStateCode1, columnStateCode2, columnStateCode3, columnStateCode4, columnNumeroTel1, columnNumeroTel2, columnNumeroTel3, columnNumeroTel4 = null;
  346.  
  347.  
  348. while (true)
  349. {
  350. string columnName = (fileAspose.ReadCell(0, 0, columnIndex) ?? string.Empty).ToString();
  351. if (string.IsNullOrWhiteSpace(columnName))
  352. {
  353. break;
  354. }
  355.  
  356. if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"]))
  357. {
  358. columnCodigoProdutoIndex = columnIndex;
  359. }
  360. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnDataVencimento"]))
  361. {
  362. columnDataVencimentoIndex = columnIndex;
  363. }
  364. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnEmail"]))
  365. {
  366. columnEmailIndex = columnIndex;
  367. }
  368. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel1"]))
  369. {
  370. columnNumeroTel1 = columnIndex;
  371. }
  372. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel2"]))
  373. {
  374. columnNumeroTel2 = columnIndex;
  375. }
  376. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel3"]))
  377. {
  378. columnNumeroTel3 = columnIndex;
  379. }
  380. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel4"]))
  381. {
  382. columnNumeroTel4 = columnIndex;
  383. }
  384. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode1"]))
  385. {
  386. columnStateCode1 = columnIndex;
  387. }
  388. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode2"]))
  389. {
  390. columnStateCode2 = columnIndex;
  391. }
  392. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode3"]))
  393. {
  394. columnStateCode3 = columnIndex;
  395. }
  396. else if (columnName.Equals(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode4"]))
  397. {
  398. columnStateCode4 = columnIndex;
  399. }
  400.  
  401. columnIndex++;
  402. }
  403.  
  404. // TODO protection of columnStateCode and columnNumeroTel -> try catch
  405.  
  406. dictionaryTel.Add(1, new Tuple<int,int>(columnStateCode1, columnNumeroTel1));
  407. dictionaryTel.Add(2, new Tuple<int, int>(columnStateCode2, columnNumeroTel2));
  408. dictionaryTel.Add(3, new Tuple<int, int>(columnStateCode3, columnNumeroTel3));
  409. dictionaryTel.Add(4, new Tuple<int, int>(columnStateCode4, columnNumeroTel4));
  410.  
  411. if (columnCodigoProdutoIndex == null)
  412. {
  413. throw new Exception("O indice da coluna com o Codigo do Produto não foi identificado. Nome da coluna: ColumnCodigoProduto");
  414. }
  415. if (columnDataVencimentoIndex == null)
  416. {
  417. throw new Exception("O indice da coluna com a Data de Vencimento não foi identificado. Nome da coluna: ColumnDataVencimento");
  418. }
  419. if (columnEmailIndex == null)
  420. {
  421. throw new Exception("O indice da coluna com a Email não foi identificado. Nome da coluna: ColumnEmail");
  422. }
  423.  
  424. //TODO codigo produto para lista
  425. listOfCodeProducts = System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"].Split(',').ToList();
  426.  
  427. //TODO lembrete days before e lembrete days after
  428. daysBefore = int.Parse(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysBefore"]);
  429. daysAfter = int.Parse(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysAfter"]);
  430.  
  431. //Verificar se existem as configuracoes necessárias no app.config para a coluna de estado.
  432. //Verificar se existe a coluna de estado criada no ficheiro csv e, se existir, está definido como sendo a ultima coluna.
  433. int columnStateIndex = columnIndex - 1;
  434. string columnNameLastColumnWithValue = (fileAspose.ReadCell(0, 0, columnIndex - 1) ?? string.Empty).ToString();
  435. VerifyColumnUonStateSettings();
  436. if (!columnNameLastColumnWithValue.Equals(System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]))
  437. {
  438. // Set column name (in first row)
  439. fileAspose.WriteCell(0, 0, columnIndex, System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]);
  440. columnStateIndex = columnIndex;
  441. }
  442.  
  443. //Process each row
  444. for (int rowIndex = 1; rowIndex < fileAspose.TotalRows(0); rowIndex++)
  445. {
  446. ProcessRow(fileAspose, rowIndex, columnStateIndex);
  447. }
  448.  
  449.  
  450.  
  451. // Verificar se coluna _UON_STATE_ existe
  452. // Se nao existir, criar/adicionar na posicao 0
  453. //
  454. // --> Processa uma linha:
  455. // -> usar metodo ReadCell
  456. // ver se coluna CD_PRODUTO com 31501 e 31522
  457. // e coluna DT_VENCIMENTO compreendido entre UONDateTime.Now - 10 dias e UONDateTime.Now +5 dias -> Tempos são configurados no appconfig
  458. // Enviar email ou sms
  459. // Inserir ERRO na coluna se houver algum erro.
  460. // Ou Inserir IGNORAR se nao se verificar condicao cd_produto e dt_vencimento.
  461. // Ou Inserir PROCESSADO na coluna se tudo correr bem.
  462. //
  463. // Se existir
  464. // ver se celula da coluna 0 é vazia ou com erro
  465. // se sim, processar linha
  466. //No fim ver se ha alguma coluna com ERRO, ou ter um contador que contabiliza o numero de erros.
  467. // Caso tenha erros incrementa error counter e regista na integracaolog. Se counter ficar a 5, mover para erro.
  468.  
  469.  
  470.  
  471. // 2 -> receçao documentos
  472. //integracaologestadoid = 4 -> atualizacao de estado
  473. //integracaologestadoid = 9 -> envio mensagens
  474. // integracaologestadoid = 99 ->erro
  475. // Read each line of csv
  476. }catch(Exception ex){
  477. ProcessErrorOfFile(ex, csvFilePath);
  478. }
  479. }
  480.  
  481. private static void ProcessErrorOfFile(Exception ex, string csvFilePath)
  482. {
  483. try
  484. {
  485. using (IUnitOfWork uow = new UnitOfWorkPortal())
  486. {
  487. IntegracaoLogService currentIntegracaoLogService = new IntegracaoLogService(uow);
  488. var newIntegracaoLog = GetNewIntegracaoLog(4, csvFilePath, processId, IntegracaoLogMessage.ErrorFile.ReadXmlEnumAttribute(), null, null, null, null, null);
  489. var currentIntegracaoLog = GetIntegracaoLog(currentIntegracaoLogService, csvFilePath);
  490. currentIntegracaoLog.IntegracaoLogEstadoId = 99;
  491. currentIntegracaoLog.ErrorCounter = currentIntegracaoLog.ErrorCounter.GetValueOrDefault() + 1;
  492.  
  493. if(currentIntegracaoLog.ErrorCounter >= 5){
  494. string newFileName = Path.Combine(locationErrorFiles, Path.GetFileName(csvFilePath));
  495. System.IO.File.Move(csvFilePath, newFileName);
  496. }
  497.  
  498. currentIntegracaoLog.ErrorDate = UONDateTime.Now;
  499. currentIntegracaoLog.ErrorMessage = ex.GetInnerException().Message;
  500. uow.Commit();
  501. }
  502.  
  503. }
  504. catch (Exception newEx){
  505. try
  506. {
  507. log.Error(new LogEntry { Exception = newEx, Tag = "GeneraliCobrança" });
  508. }
  509. catch { }
  510. }
  511. }
  512.  
  513. // if estado 4, estado 99, move para location error.
  514.  
  515. private static bool ProcessRow(AsposeExcel fileAspose, int rowIndex, int columnStateIndex)
  516. {
  517. try
  518. {
  519. if ((fileAspose.ReadCell(0, rowIndex, columnStateIndex) ?? string.Empty).ToString().Equals(UonState.Ignorar.ToString()))
  520. {
  521. return true;
  522. }
  523.  
  524. if (listOfCodeProducts.Contains((fileAspose.ReadCell(0, rowIndex, columnCodigoProdutoIndex.Value) ?? string.Empty).ToString()))
  525. {
  526. var dataVencimento = GetDateTimeFromObject(fileAspose.ReadCell(0, rowIndex, columnDataVencimentoIndex.Value));
  527. if (dataVencimento.HasValue)
  528. {
  529. var now = UONDateTime.Now;
  530. // Lembrete
  531. if ((dataVencimento.Value - now).Days <= daysBefore)
  532. {
  533. return SendEmailAndOrSMS(fileAspose, rowIndex, columnStateIndex, LembreteAtraso.Lembrete);
  534. }
  535. // Atraso
  536. else if ((now - dataVencimento.Value).Days <= daysAfter)
  537. {
  538. return SendEmailAndOrSMS(fileAspose, rowIndex, columnStateIndex, LembreteAtraso.Atraso);
  539. }
  540. // Não interessa
  541. else
  542. {
  543. fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
  544. return true;
  545. }
  546. }
  547. else
  548. {
  549. fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
  550. return true;
  551. }
  552. }
  553. else
  554. {
  555. fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Ignorar.ToString());
  556. return true;
  557. }
  558.  
  559. }
  560. catch (Exception ex)
  561. {
  562. fileAspose.WriteCell(0, rowIndex, columnStateIndex, UonState.Erro.ToString());
  563. return false;
  564. }
  565. }
  566.  
  567. private static bool SendEmailAndOrSMS(AsposeExcel fileAspose, int rowIndex, int columnStateIndex, LembreteAtraso lembreteOuAtraso)
  568. {
  569. //columnCodigoProdutoIndex, columnDataVencimentoIndex, columnEmailIndex
  570.  
  571. // se coluna de email diferent null
  572.  
  573. // ir buscar formulario e substituir os valores
  574.  
  575. // envia email
  576.  
  577. var emailProcessed = SendEmail();
  578.  
  579.  
  580.  
  581.  
  582. // metodo que devolve um numero
  583.  
  584. // get valid number
  585.  
  586. // se numero diferente de null, envio
  587.  
  588. // ir buscar a formulario e fazer replace
  589.  
  590. // envia sms
  591.  
  592. var smsProcessed = SendSMS(processId, message, number);
  593.  
  594. UonState state = UonState.Erro;
  595. if (emailProcessed && smsProcessed)
  596. {
  597. state = UonState.Processado;
  598.  
  599. }
  600. else if (emailProcessed)
  601. {
  602. state = UonState.ErroSms;
  603. }
  604. else if (smsProcessed)
  605. {
  606. state = UonState.ErroEmail;
  607. }
  608.  
  609. fileAspose.WriteCell(0, rowIndex, columnStateIndex, state);
  610. return state == UonState.Processado;
  611. }
  612.  
  613. private static string GetValidPhoneNumber(Dictionary<int, int> dictionaryTel)
  614. {
  615. if (dictionaryTel != null)
  616. {
  617. foreach (var item in dictionaryTel)
  618. {
  619. item.Value
  620. }
  621. }
  622.  
  623. }
  624.  
  625. private static void SendSMS(int processId, string message, string number)
  626. {
  627. using (var uow = new UnitOfWorkPortal())
  628. {
  629. SettingService currentSettingService = new SettingService(uow);
  630.  
  631. using (ISmsProvider smsProvider = Provider.OpenComm(currentSettingService.SmsProviderName, currentSettingService.GetPropValues(currentSettingService.SmsProviderName)))
  632. {
  633. using (var uowSms = new UnitOfWorkSMS())
  634. {
  635. int serie = new SMS.Business.ServiceProviderService(uowSms).GetSeriesById(smsProvider.Id);
  636. SmsSendResponse response = smsProvider.Send("Provider Number", number, message, serie);
  637. new SMS.Business.SmsService(uowSms).Add(response.SmsMessage, processId, null, 1, smsProvider.Id);
  638. uowSms.Commit();
  639. }
  640. }
  641. }
  642. }
  643.  
  644. private static bool SendEmail()
  645. {
  646. return true;
  647. }
  648.  
  649. private static DateTime? GetDateTimeFromObject(object value)
  650. {
  651. DateTime result;
  652. return DateTime.TryParse((value ?? string.Empty).ToString(), CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.None, out result) ? result : (DateTime?)null;
  653. }
  654.  
  655. private static string[] GetFilesPathFromDirectory(string targetDirectory)
  656. {
  657. string[] fileEntries = Directory.GetFiles(targetDirectory);
  658. return fileEntries;
  659. }
  660.  
  661.  
  662. private static void VerifyColumnUonStateSettings()
  663. {
  664. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateColumnName"]))
  665. {
  666. throw new ArgumentException("A configuracao UonStateColumnName do ficheiro App.config é vazio ou nulo.");
  667. }
  668. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateErro"]))
  669. {
  670. throw new ArgumentException("A configuracao UonStateErro do ficheiro App.config é vazio ou nulo.");
  671. }
  672. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateProcessado"]))
  673. {
  674. throw new ArgumentException("A configuracao UonStateProcessado do ficheiro App.config é vazio ou nulo.");
  675. }
  676. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["UonStateIgnorar"]))
  677. {
  678. throw new ArgumentException("A configuracao UonStateIgnorar do ficheiro App.config é vazio ou nulo.");
  679. }
  680. }
  681.  
  682. private static void VerifyColumnsForConsideration()
  683. {
  684. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnCodigoProduto"]))
  685. {
  686. throw new Exception("A configuracao ColumnCodigoProduto do ficheiro App.config é vazio ou nulo.");
  687. }
  688. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnDataVencimento"]))
  689. {
  690. throw new Exception("A configuracao ColumnDataVencimento do ficheiro App.config é vazio ou nulo.");
  691. }
  692. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysBefore"]))
  693. {
  694. throw new Exception("A configuracao LembreteDaysBefore do ficheiro App.config é vazio ou nulo.");
  695. }
  696. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["LembreteDaysAfter"]))
  697. {
  698. throw new Exception("A configuracao LembreteDaysAfter do ficheiro App.config é vazio ou nulo.");
  699. }
  700. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["CodigosProduto"]))
  701. {
  702. throw new Exception("A configuracao CodigosProduto do ficheiro App.config é vazio ou nulo.");
  703. }
  704. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnEmail"]))
  705. {
  706. throw new Exception("A configuracao ColumnEmail do ficheiro App.config é vazio ou nulo.");
  707. }
  708. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel1"]))
  709. {
  710. throw new Exception("A configuracao UColumnNumeroTel1 do ficheiro App.config é vazio ou nulo.");
  711. }
  712. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel2"]))
  713. {
  714. throw new Exception("A configuracao ColumnNumeroTel2 do ficheiro App.config é vazio ou nulo.");
  715. }
  716. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel3"]))
  717. {
  718. throw new Exception("A configuracao ColumnNumeroTel3 do ficheiro App.config é vazio ou nulo.");
  719. }
  720. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnNumeroTel4"]))
  721. {
  722. throw new Exception("A configuracao ColumnNumeroTel4 do ficheiro App.config é vazio ou nulo.");
  723. }
  724. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode1"]))
  725. {
  726. throw new Exception("A configuracao ColumnStateCode1 do ficheiro App.config é vazio ou nulo.");
  727. }
  728. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode2"]))
  729. {
  730. throw new Exception("A configuracao ColumnStateCode2 do ficheiro App.config é vazio ou nulo.");
  731. }
  732. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode3"]))
  733. {
  734. throw new Exception("A configuracao ColumnStateCode3 do ficheiro App.config é vazio ou nulo.");
  735. }
  736. if (string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["ColumnStateCode4"]))
  737. {
  738. throw new Exception("A configuracao ColumnStateCode4 do ficheiro App.config é vazio ou nulo.");
  739. }
  740. }
  741. }
  742. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement