using System; using System.Collections.Generic; using System.IO; using System.Linq; using LCU.Shared.Collections.RepoApiLib.Models; using NotVisualBasic.FileIO; using Serilog; namespace LCU.API.Collections.RepoApi.Services.AutoIms { public class ImsAutoFileNoteConverter : IImsAutoFileNoteConverter { public ImsAutoFileNoteConverter() { } public IEnumerable CsvToImsAutoFileNotes(Stream file) { List listOfObjects = new List(); using (CsvTextFieldParser tfp = new CsvTextFieldParser(file)) { // Get Some Column Names string[] columns = tfp.ReadFields(); while (!tfp.EndOfData) { var fields = tfp.ReadFields(); if (!fields[0].Contains("------") && (fields.Any(x => x.Trim().Length > 0))) { var obj = new AuctionAssignmentNote(); for (var i = 0; i < fields.Length; i++) { obj = SetFieldByName(obj, columns[i].Trim(), fields[i].Trim()); } listOfObjects.Add(obj); } } } return listOfObjects; } /** * Take the rows with only account and discard them, using the account no to update the other rows. * Each row in the CSV does not have CustomerAccountNo, only the first row of each set. * Further, if a row has a customer account no, it has nothing else. */ public IEnumerable CompressIdentifyingRows(IEnumerable csvNotes) { List data = new List(); string accountNo = String.Empty; foreach (var item in csvNotes) { try { if (!string.IsNullOrWhiteSpace(item.AuctionCustomerNo) && item.AuctionCustomerNo != accountNo) { accountNo = item.AuctionCustomerNo; // Skip account rows, unless they start showing up with data. if (string.IsNullOrWhiteSpace(item.Text)) { continue; } } if (string.IsNullOrWhiteSpace(accountNo)) { Log.Error($"No Account Number when processing notes row, {item.Text}"); return null; } item.AuctionCustomerNo = accountNo; data.Add(item); } catch (Exception ex) { Log.Error(ex, $"Error compressing notes for auction accountNo: {accountNo}"); } } return data; } public AuctionAssignmentNote SetFieldByName(AuctionAssignmentNote input, string fieldName, string value) { try { switch (fieldName) { case "Cn. Acc. #": input.AuctionCustomerNo = value; break; case "Origin": input.Origin = value; break; case "Writer": input.Writer = value; break; case "Type": input.Type = value; break; case "Text": input.Text = value; break; case "Date Written": input.DateWritten = !string.IsNullOrWhiteSpace(value) ? DateTime.Parse(value.Substring(0, value.Trim().Length - 4)) : (DateTime?) null; break; default: Log.Error("Got unknown field {fieldName} with value {value} for AuctionAssignmentNote"); break; } } catch (Exception ex) { Log.Error(ex, "Failed to set field {fieldName} with value {value} for AuctionAssignmentNote."); } return input; } } }