using bnhtrade.Core.Data.Amazon.Report; using bnhtrade.Core.Data.Database.UnitOfWork; using System; using System.Linq; namespace bnhtrade.Core.Logic.Import { public class AmazonSettlement { private readonly IUnitOfWork _providedUnitOfWork = null; private readonly bool _ownsUnitOfWork = false; private Data.Amazon.Report.SettlementReport amazonReport; private Logic.Log.LogEvent log = new Log.LogEvent(); public AmazonSettlement() { _ownsUnitOfWork = true; } internal AmazonSettlement(IUnitOfWork unitOfWork) { _providedUnitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork)); _ownsUnitOfWork = false; } public void SyncDatabase() { string operation = "Import Amazon Settlement Reports"; log.LogInformation("Started '" + operation + "' operation."); // get avaiable reports from amazon api IUnitOfWork currentUow = null; if (_ownsUnitOfWork) { currentUow = new UnitOfWork(); } else { currentUow = _providedUnitOfWork; } using (currentUow != null && _ownsUnitOfWork ? currentUow : null) { // get avaiable reports from amazon api var spapiReportIdList = amazonReport.ListAvaliableReports(); int reportCount = spapiReportIdList.Count(); if (reportCount == 0) { log.LogInformation("Exiting '" + operation + "' operation. No settlement reports availble on Amazon SP-API."); return; } // query db and remove reports that have already been imported var dbReportList = currentUow.ImportAmazonRepository.ReadAmazonSettlementHeaderInfoBySpapiReportId(spapiReportIdList); foreach (var dbReport in dbReportList) { if (dbReport.SpapiReportIdIsSet) { for (int i = 0; i < spapiReportIdList.Count; i++) { if (spapiReportIdList[i] == dbReport.SpapiReportId) { spapiReportIdList.RemoveAt(i); i--; break; } } } } if (!spapiReportIdList.Any()) { log.LogInformation("Exiting '" + operation + "' operation. No new reports to import (" + reportCount + " avaibale)."); return; } // import into database for (int i = 0; i < spapiReportIdList.Count(); i++) { UI.Console.WriteLine("Importing settlement report " + (i + 1) + " of " + spapiReportIdList.Count() + " (ReportID:" + spapiReportIdList[i] + ")."); var filePath = amazonReport.GetReportFile(spapiReportIdList[i]); bool ack = currentUow.ImportAmazonRepository.CreateAmazonSettlements(filePath, spapiReportIdList[i]); log.LogInformation("Settlment Report imported (ReportID:" + spapiReportIdList[i] + ")."); } if (_ownsUnitOfWork) { currentUow.Commit(); } return; } } } }