diff --git a/src/bnhtrade.ComTypeLib/Account/Account.cs b/src/bnhtrade.ComTypeLib/Account/Account.cs
index 491ac29..bf784bc 100644
--- a/src/bnhtrade.ComTypeLib/Account/Account.cs
+++ b/src/bnhtrade.ComTypeLib/Account/Account.cs
@@ -48,7 +48,7 @@ namespace bnhtrade.ComTypeLib
public decimal CurrencyConvertToGbp(ConnectionCredential sqlConnCred, string currencyCode,
[MarshalAs(UnmanagedType.Currency)] decimal amount, DateTime conversionDate)
{
- return new Core.Logic.Account.Currency().CurrencyConvertToGbp(currencyCode, amount, conversionDate);
+ return new Core.Logic.Account.CurrencyService().CurrencyConvertToGbp(currencyCode, amount, conversionDate);
}
public int CurrencyExchangeRateInsert(ConnectionCredential sqlConnCred, int exchangeRateSource, string currencyCode,
diff --git a/src/bnhtrade.Core/Data/Amazon/Feeds/SampleFeeds.cs b/src/bnhtrade.Core/Data/Amazon/Feeds/SampleFeeds.cs
index ec09606..c3f3de1 100644
--- a/src/bnhtrade.Core/Data/Amazon/Feeds/SampleFeeds.cs
+++ b/src/bnhtrade.Core/Data/Amazon/Feeds/SampleFeeds.cs
@@ -163,7 +163,7 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
GetFeedDetails(feedID);
}
- public void SubmitFeedPRICING(double PRICE, string SKU)
+ public void SubmitFeedPRICING(decimal price, string SKU)
{
ConstructFeedService createDocument = new ConstructFeedService(amazonConnection.GetCurrentSellerID, "1.02");
@@ -175,7 +175,7 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
StandardPrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
- Value = (PRICE).ToString("0.00")
+ Value = price
}
});
createDocument.AddPriceMessage(list);
@@ -201,14 +201,14 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
StandardPrice = new StandardPrice
{
currency = currencyCode,
- Value = price.ToString("0.00")
+ Value = price
},
Sale = new Sale
{
SalePrice = new StandardPrice
{
currency = currencyCode,
- Value = salePrice.ToString("0.00")
+ Value = salePrice
},
StartDate = startDate.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
EndDate = endDate.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")
@@ -224,7 +224,7 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
}
- public void SubmitFeedSale(double PRICE, string SKU)
+ public void SubmitFeedSale(decimal price, string SKU)
{
ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
@@ -236,7 +236,7 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
StandardPrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
- Value = (PRICE).ToString("0.00")
+ Value = price
},
Sale = new Sale()
{
@@ -245,7 +245,7 @@ namespace bnhtrade.Core.Data.Amazon.Feeds
SalePrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
- Value = (PRICE - 10).ToString("0.00")
+ Value = price
}
}
});
diff --git a/src/bnhtrade.Core/Data/Amazon/Report/SettlementReport.cs b/src/bnhtrade.Core/Data/Amazon/Report/SettlementReport.cs
index 5fc4edb..bbe7e9e 100644
--- a/src/bnhtrade.Core/Data/Amazon/Report/SettlementReport.cs
+++ b/src/bnhtrade.Core/Data/Amazon/Report/SettlementReport.cs
@@ -32,7 +32,7 @@ namespace bnhtrade.Core.Data.Amazon.Report
reportIdList.Add(report.ReportId);
}
- UI.Console.WriteLine("{0} Settlement reports avaible on Amazon SP-API");
+ UI.Console.WriteLine(reportIdList.Count().ToString() + " Settlement reports avaible on Amazon SP-API");
return reportIdList;
}
diff --git a/src/bnhtrade.Core/Data/Database/Account/CreateJournal.cs b/src/bnhtrade.Core/Data/Database/Account/CreateJournal.cs
index a149dbf..bfbb086 100644
--- a/src/bnhtrade.Core/Data/Database/Account/CreateJournal.cs
+++ b/src/bnhtrade.Core/Data/Database/Account/CreateJournal.cs
@@ -162,7 +162,7 @@ namespace bnhtrade.Core.Data.Database.Account
// currency conversion
if (currencyCode != "GBP")
{
- amount = new Logic.Account.Currency().CurrencyConvertToGbp(currencyCode, amount, entryDate);
+ amount = new Logic.Account.CurrencyService().CurrencyConvertToGbp(currencyCode, amount, entryDate);
}
// ensure decimal is rounded
diff --git a/src/bnhtrade.Core/Data/Database/Account/Currency.cs b/src/bnhtrade.Core/Data/Database/Account/Currency.cs
deleted file mode 100644
index f2ed460..0000000
--- a/src/bnhtrade.Core/Data/Database/Account/Currency.cs
+++ /dev/null
@@ -1,262 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Microsoft.Data.SqlClient;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Collections;
-using FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentOutbound;
-using System.Data;
-
-namespace bnhtrade.Core.Data.Database.Account
-{
- internal class Currency : Connection
- {
- ///
- /// Returns excahnge rate, in decimal format, for a given currency and datetime
- ///
- /// currency code
- /// dat and time
- ///
- public decimal? ReadExchangeRate(string currencyCode, DateTime date)
- {
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- using (SqlCommand cmd = new SqlCommand(@"
- SELECT CurrencyUnitsPerGBP
- FROM tblAccountExchangeRate
- WHERE CurrencyCode=@currencyCode AND StartDate<=@conversionDate AND EndDate>@conversionDate
- ", sqlConn))
- {
- cmd.Parameters.AddWithValue("@currencyCode", currencyCode);
- cmd.Parameters.AddWithValue("@conversionDate", date);
-
- object result = cmd.ExecuteScalar();
- if (result != null)
- {
- return Convert.ToDecimal(result);
- }
- else
- {
- return null;
- }
- }
- }
- }
-
- public List ReadExchangeRate(List currencyCodeList = null, DateTime date = default(DateTime))
- {
- throw new NotImplementedException("Complete, but untested");
-
- var returnList = new List();
-
- string sql = @"
- SELECT AccountEchangeRateID, ExchangeRateSource, CurrencyCode, CurrencyUnitsPerGBP, StartDate, EndDate
- FROM tblAccountExchangeRate
- WHERE 1=1 ";
-
- if (date != default(DateTime))
- {
- sql = sql + " AND (@dateTime >= StartDate AND @dateTime < endDate) ";
- }
-
- var sqlWhere = new Data.Database.SqlWhereBuilder();
-
- // create string list
- List stringList = new List();
- if (currencyCodeList != null)
- {
- stringList = currencyCodeList.ConvertAll(f => f.ToString());
- if (stringList.Any())
- {
- sqlWhere.In("CurrencyCode", stringList, "AND");
- }
- }
-
- sql = sql + sqlWhere.SqlWhereString;
-
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sql))
- {
- if (date != default(DateTime))
- {
- cmd.Parameters.AddWithValue("@dateTime", date);
- }
- if (stringList.Any())
- {
- sqlWhere.AddParametersToSqlCommand(cmd);
- }
-
- using (var reader = cmd.ExecuteReader())
- {
- while (reader.Read())
- {
- int id = reader.GetInt32(0);
- int exchangeRateSource = reader.GetInt32(1);
- string currencyCodeString = reader.GetString(2);
- decimal currencyUnitsPerGBP = reader.GetDecimal(3);
- DateTime startDate = DateTime.SpecifyKind( reader.GetDateTime(4), DateTimeKind.Utc);
- DateTime endDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
-
-
- // convert string to enum
- if (Enum.TryParse(currencyCodeString, out Model.Account.CurrencyCode currencyCode) == false)
- {
- throw new Exception("Failed converting database string to enum");
- }
-
- var item = new Model.Account.CurrencyExchangeRate(
- currencyCode
- , exchangeRateSource
- , startDate
- , endDate
- );
-
- returnList.Add(item);
- }
- }
- }
- }
- return returnList;
- }
-
- public List ReadExchangeRateLatest(List currencyCodeList = null)
- {
- var returnList = new List();
-
- string sql = @"
- SELECT t1.AccountExchangeRateID, t1.ExchangeRateSource, t1.CurrencyCode, t1.CurrencyUnitsPerGBP, t1.StartDate, t1.EndDate,
- t2.maxdate
- FROM tblAccountExchangeRate AS t1
- INNER JOIN
- (SELECT max(StartDate) AS maxdate,
- CurrencyCode
- FROM tblAccountExchangeRate
- GROUP BY CurrencyCode
- ";
-
- // add any filters
- var sqlWhere = new Data.Database.SqlWhereBuilder();
- var codeStringList = new List();
- if (currencyCodeList != null && currencyCodeList.Any() == true)
- {
- // convert to string list
- foreach ( var currencyCode in currencyCodeList)
- {
- codeStringList.Add(currencyCode.ToString());
- }
-
- // add to where statement
- sqlWhere.In("CurrencyCode", codeStringList, "HAVING");
- sql = sql + sqlWhere.SqlWhereString;
- }
-
- sql = sql + @" ) AS t2
- ON t1.CurrencyCode = t2.CurrencyCode
- AND t1.StartDate = t2.maxdate
- ORDER BY t1.CurrencyCode;";
-
- //query db
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sql, sqlConn))
- {
- if (codeStringList.Any())
- {
- sqlWhere.AddParametersToSqlCommand(cmd);
- }
-
- using (var reader = cmd.ExecuteReader())
- {
- while (reader.Read())
- {
- int id = reader.GetInt32(0);
- int exchangeRateSource = reader.GetInt32(1);
- string currencyCodeString = reader.GetString(2);
- decimal currencyUnitsPerGBP = reader.GetDecimal(3);
- DateTime startDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
- DateTime endDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
-
-
- // convert string to enum
- if (Enum.TryParse(currencyCodeString, out Model.Account.CurrencyCode currencyCode) == false)
- {
- throw new Exception("Failed converting database string to enum");
- }
-
- var item = new Model.Account.CurrencyExchangeRate(
- currencyCode
- , exchangeRateSource
- , startDate
- , endDate
- );
-
- returnList.Add(item);
- }
- }
- }
- }
- return returnList;
- }
-
- public int InsertExchangeRate(int exchangeRateSource, Model.Account.CurrencyCode currencyCode,
- decimal currencyUnitsPerGbp, DateTime periodStartUtc, DateTime periodEnd, bool checkOverride = false)
- {
- // checks
- if (periodStartUtc.Kind != DateTimeKind.Utc || periodEnd.Kind != DateTimeKind.Utc)
- {
- throw new FormatException("Currency date time kind must be UTC");
- }
-
- currencyUnitsPerGbp = decimal.Round(currencyUnitsPerGbp, 4);
-
- // CHECKS
- if (periodEnd <= periodStartUtc)
- {
- throw new Exception("Invalid date period.");
- }
-
- if (checkOverride == false && (periodEnd - periodStartUtc).Days > 31)
- {
- throw new Exception("Date period is greater than 31 days.");
- }
-
- // make the insert
- DateTime? periodEndLast = null;
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- int recordId = 0;
- using (SqlCommand cmd = new SqlCommand(@"
- INSERT INTO tblAccountExchangeRate (ExchangeRateSource, CurrencyCode, CurrencyUnitsPerGBP, StartDate, EndDate)
- OUTPUT INSERTED.AccountExchangeRateID
- VALUES (@exchangeRateSource, @currencyCode, @currencyUnitsPerGbp, @periodStart, @periodEnd);
- ", sqlConn))
- {
- cmd.Parameters.AddWithValue("@exchangeRateSource", exchangeRateSource);
- cmd.Parameters.AddWithValue("@currencyCode", currencyCode.ToString());
- cmd.Parameters.AddWithValue("@currencyUnitsPerGbp", currencyUnitsPerGbp);
- cmd.Parameters.AddWithValue("@periodStart", periodStartUtc);
- cmd.Parameters.AddWithValue("@periodEnd", periodEnd);
-
- recordId = (int)cmd.ExecuteScalar();
-
- if (recordId < 1)
- {
- throw new Exception("Error inserting record, did not retrive new record ID.");
- }
- }
-
- return recordId;
- }
- }
- }
-}
diff --git a/src/bnhtrade.Core/Data/Database/Account/ReadAccountCode.cs b/src/bnhtrade.Core/Data/Database/Account/ReadAccountCode.cs
index ba238a7..4d808f3 100644
--- a/src/bnhtrade.Core/Data/Database/Account/ReadAccountCode.cs
+++ b/src/bnhtrade.Core/Data/Database/Account/ReadAccountCode.cs
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
diff --git a/src/bnhtrade.Core/Data/Database/Account/ReadInvoiceLineItem.cs b/src/bnhtrade.Core/Data/Database/Account/ReadInvoiceLineItem.cs
index 07482f0..9164335 100644
--- a/src/bnhtrade.Core/Data/Database/Account/ReadInvoiceLineItem.cs
+++ b/src/bnhtrade.Core/Data/Database/Account/ReadInvoiceLineItem.cs
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -8,63 +8,61 @@ using System.Transactions;
namespace bnhtrade.Core.Data.Database.Account
{
- public class ReadInvoiceLineItem : Connection
+ internal class ReadInvoiceLineItem : Connection
{
public ReadInvoiceLineItem()
{
- Innit();
}
- public Dictionary AccountCodeList { get; private set; }
-
- public Dictionary TaxCodeList { get; private set; }
-
- private void Innit()
+ ///
+ /// Reads all invoice line items from the database.
+ ///
+ /// dictionary where key=id, value=object
+ internal Dictionary All()
{
- AccountCodeList = new Dictionary();
- TaxCodeList = new Dictionary();
+ return Execute();
}
- public Model.Account.InvoiceLineItem ByItemCode(string itemCode)
+ ///
+ /// Read list of invoice line items by item code.
+ ///
+ /// List of item coeds to query db against
+ /// dictionary where key=id, value=object
+ ///
+ internal Dictionary ByItemCode(List itemCodes)
{
- if (string.IsNullOrWhiteSpace(itemCode)) { return null; }
-
- var result = ByItemCode(new List{ itemCode });
-
- if (!result.Any())
- {
- return null;
- }
- else
- {
- return result[itemCode];
+ if (itemCodes == null || !itemCodes.Any())
+ {
+ throw new ArgumentException("Item codes list cannot be null or empty.");
}
+
+ var sqlwhere = new SqlWhereBuilder();
+ sqlwhere.In("ItemCode", itemCodes, "AND");
+ return Execute(sqlwhere);
}
- public Dictionary ByItemCode(List itemCodeList)
+ private Dictionary Execute(SqlWhereBuilder sqlwhere = null)
{
- Innit();
- var resultList = new Dictionary();
-
- if (itemCodeList == null || !itemCodeList.Any())
- { return resultList; }
+ var resultList = new Dictionary();
+ var accountCodeIdList = new Dictionary(); // key=LineItemID, value=AccountChartOfID
+ var taxCodeIdList = new Dictionary(); // key=LineItemID, value=AccountTaxCodeID
string sql = @"
- SELECT tblAccountInvoiceLineItem.ItemCode
- ,tblAccountInvoiceLineItem.ItemName
- ,tblAccountInvoiceLineItem.ItemDescription
- ,tblAccountInvoiceLineItem.IsNewReviewRequired
- ,tblAccountInvoiceLineItem.InvoiceLineEntryEnable
- ,tblAccountChartOf.AccountCode
- ,tblAccountTaxCode.TaxCode
- FROM tblAccountInvoiceLineItem
- LEFT OUTER JOIN tblAccountTaxCode ON tblAccountInvoiceLineItem.AccountTaxCodeID_Default = tblAccountTaxCode.AccountTaxCodeID
- LEFT OUTER JOIN tblAccountChartOf ON tblAccountInvoiceLineItem.AccountChartOfID_Default = tblAccountChartOf.AccountChartOfID
- WHERE ";
+ SELECT [AccountInvoiceLineItemID]
+ ,[ItemName]
+ ,[ItemCode]
+ ,[ItemDescription]
+ ,[IsNewReviewRequired]
+ ,[InvoiceLineEntryEnable]
+ ,[AccountChartOfID_Default]
+ ,[AccountTaxCodeID_Default]
+ FROM [e2A].[dbo].[tblAccountInvoiceLineItem]
+ WHERE 1=1 ";
- var whereBuilder = new SqlWhereBuilder();
- whereBuilder.In("tblAccountInvoiceLineItem.ItemCode", itemCodeList);
- sql += whereBuilder.SqlWhereString;
+ if (sqlwhere != null)
+ {
+ sql += sqlwhere.SqlWhereString;
+ }
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
@@ -72,41 +70,53 @@ namespace bnhtrade.Core.Data.Database.Account
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
- foreach (var param in whereBuilder.ParameterList)
+ if (sqlwhere != null)
{
- cmd.Parameters.AddWithValue(param.Key, param.Value);
+ sqlwhere.AddParametersToSqlCommand(cmd);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
- if (reader.HasRows)
+ while (reader.Read())
{
- while (reader.Read())
+ var lineItem = new Model.Account.InvoiceLineItem();
+
+ int lineItemId = reader.GetInt32(0);
+ lineItem.Name = reader.GetString(1);
+ lineItem.ItemCode = reader.GetString(2);
+ if (!reader.IsDBNull(3)) { lineItem.Description = reader.GetString(3); }
+ lineItem.IsNewReviewRequired = reader.GetBoolean(4);
+ lineItem.InvoiceLineEntryEnabled = reader.GetBoolean(5);
+
+ if (!reader.IsDBNull(6))
{
- var result = new Model.Account.InvoiceLineItem();
-
- result.ItemCode = reader.GetString(0);
- result.Name = reader.GetString(1);
- if (!reader.IsDBNull(2)) { result.Description = reader.GetString(2); }
- result.IsNewReviewRequired = reader.GetBoolean(3);
- result.InvoiceLineEntryEnabled = reader.GetBoolean(4);
-
- if (!reader.IsDBNull(5))
- {
- AccountCodeList.Add(result.ItemCode, reader.GetInt32(5));
- }
- if (!reader.IsDBNull(6))
- {
- TaxCodeList.Add(result.ItemCode, reader.GetString(6));
- }
-
- resultList.Add(result.ItemCode, result);
+ accountCodeIdList.Add(lineItemId, (uint)reader.GetInt32(6));
+ }
+ if (!reader.IsDBNull(7))
+ {
+ taxCodeIdList.Add(lineItemId, reader.GetInt32(7));
}
- }
- return resultList;
+ resultList.Add(lineItemId, lineItem);
+ }
}
}
+
+ // get account codes and add to result list
+ var accountCodeDictionary = new Data.Database.Account.ReadAccountCode().ByAccountId(accountCodeIdList.Values.ToList());
+ foreach (var accountCode in accountCodeIdList)
+ {
+ resultList[accountCode.Key].DefaultAccountCode = accountCodeDictionary[accountCode.Value];
+ }
+
+ // get tax codes
+ var taxCodeDictionary = new Data.Database.Account.ReadTaxCode().GetByTaxCodeId(taxCodeIdList.Values.ToList());
+ foreach (var taxCode in taxCodeIdList)
+ {
+ resultList[taxCode.Key].DefaultTaxCode = taxCodeDictionary[taxCode.Value];
+ }
+
+ return resultList;
}
}
}
diff --git a/src/bnhtrade.Core/Data/Database/Account/ReadPurchaseInvoice.cs b/src/bnhtrade.Core/Data/Database/Account/ReadPurchaseInvoice.cs
index f9442ff..97b608a 100644
--- a/src/bnhtrade.Core/Data/Database/Account/ReadPurchaseInvoice.cs
+++ b/src/bnhtrade.Core/Data/Database/Account/ReadPurchaseInvoice.cs
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -8,11 +8,11 @@ using static System.ComponentModel.Design.ObjectSelectorEditor;
namespace bnhtrade.Core.Data.Database.Account
{
- public class ReadPurchaseInvoice : Connection
+ internal class ReadPurchaseInvoice : Connection
{
private bnhtrade.Core.Data.Database.SqlWhereBuilder sqlBuilder;
- public List PurchaseInvoiceIdList { get; set; }
+ public IEnumerable PurchaseInvoiceIdList { get; set; }
public ReadPurchaseInvoice()
{
diff --git a/src/bnhtrade.Core/Data/Database/Account/ReadTaxCode.cs b/src/bnhtrade.Core/Data/Database/Account/ReadTaxCode.cs
index dd285c2..cd9f031 100644
--- a/src/bnhtrade.Core/Data/Database/Account/ReadTaxCode.cs
+++ b/src/bnhtrade.Core/Data/Database/Account/ReadTaxCode.cs
@@ -1,13 +1,13 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Account
{
- public class ReadTaxCode : Connection
+ internal class ReadTaxCode : Connection
{
private Data.Database.SqlWhereBuilder whereBuilder = new SqlWhereBuilder();
@@ -15,14 +15,15 @@ namespace bnhtrade.Core.Data.Database.Account
{
}
- private List Execute(string sqlWhere, Dictionary parameters)
+ private Dictionary Execute(string sqlWhere, Dictionary parameters)
{
- var resultList = new List();
+ var resultList = new Dictionary();
//build sql query
string sqlString = @"
SELECT
- TaxCode
+ AccountTaxCodeID
+ ,TaxCode
,TaxCodeName
,TaxCodeDescription
,TaxRatePercent
@@ -52,19 +53,20 @@ namespace bnhtrade.Core.Data.Database.Account
{
while (reader.Read())
{
- string taxCodeId = reader.GetString(0);
- string name = reader.GetString(1);
+ int taxCodeId = reader.GetByte(0);
+ string taxCode = reader.GetString(1);
+ string name = reader.GetString(2);
string description = null;
- if (!reader.IsDBNull(2)) { description = reader.GetString(2); }
- decimal rate = reader.GetDecimal(3);
- bool isMargin = reader.GetBoolean(4);
- bool isValidOnExpense = reader.GetBoolean(5);
- bool isValidOnIncome = reader.GetBoolean(6);
- bool isActive = reader.GetBoolean(7);
- string taxType = reader.GetString(8);
+ if (!reader.IsDBNull(3)) { description = reader.GetString(3); }
+ decimal rate = reader.GetDecimal(4);
+ bool isMargin = reader.GetBoolean(5);
+ bool isValidOnExpense = reader.GetBoolean(6);
+ bool isValidOnIncome = reader.GetBoolean(7);
+ bool isActive = reader.GetBoolean(8);
+ string taxType = reader.GetString(9);
var result = new Model.Account.TaxCodeInfo(
- taxCodeId,
+ taxCode,
name,
description,
rate,
@@ -74,7 +76,7 @@ namespace bnhtrade.Core.Data.Database.Account
taxType,
isActive);
- resultList.Add(result);
+ resultList.Add(taxCodeId, result);
}
}
}
@@ -97,12 +99,13 @@ namespace bnhtrade.Core.Data.Database.Account
whereBuilder.Init();
whereBuilder.In("TaxCode", taxcodeList, "WHERE");
- return Execute(whereBuilder.SqlWhereString, whereBuilder.ParameterList);
+ var dic = Execute(whereBuilder.SqlWhereString, whereBuilder.ParameterList);
+ return dic.Values.ToList();
}
- public List GetByTaxCodeId(List taxcodeIdList)
+ public Dictionary GetByTaxCodeId(List taxcodeIdList)
{
- var resultList = new List();
+ var resultList = new Dictionary();
if (taxcodeIdList == null || !taxcodeIdList.Any())
{
@@ -117,7 +120,12 @@ namespace bnhtrade.Core.Data.Database.Account
return Execute(whereBuilder.SqlWhereString, whereBuilder.ParameterList);
}
- public List GetAllActive()
+
+ ///
+ /// Gets all active Tax Code objects
+ ///
+ /// Dictionary where database record ID is the key
+ public Dictionary GetAllActive()
{
string sqlWhere = @"
WHERE IsActive=@isActive;";
diff --git a/src/bnhtrade.Core/Data/Database/Connection.cs b/src/bnhtrade.Core/Data/Database/Connection.cs
index 53f29d9..c97c0e8 100644
--- a/src/bnhtrade.Core/Data/Database/Connection.cs
+++ b/src/bnhtrade.Core/Data/Database/Connection.cs
@@ -11,11 +11,11 @@ namespace bnhtrade.Core.Data.Database
public class Connection
{
//protected readonly string SqlConnectionString;
- private Model.Credentials.bnhtradeDB dbCredentials;
+ private Model.Credentials.bnhtradeDB _dbCredentials;
protected string SqlConnectionString
{
- get { return dbCredentials.ConnectionString; }
+ get { return _dbCredentials.ConnectionString; }
}
public Connection()
@@ -44,7 +44,7 @@ namespace bnhtrade.Core.Data.Database
}
var dbCredentials = new bnhtrade.Core.Model.Credentials.bnhtradeDB(dataSource, userId, pass);
- this.dbCredentials = dbCredentials;
+ this._dbCredentials = dbCredentials;
}
catch (Exception ex)
{
@@ -76,7 +76,7 @@ namespace bnhtrade.Core.Data.Database
}
var dbCredentials = new bnhtrade.Core.Model.Credentials.bnhtradeDB(dataSource, userId, pass);
- this.dbCredentials = dbCredentials;
+ this._dbCredentials = dbCredentials;
}
catch(Exception ex)
{
@@ -91,7 +91,7 @@ namespace bnhtrade.Core.Data.Database
{
throw new Exception("DB credentials object is null");
}
- this.dbCredentials = dbCredentials;
+ this._dbCredentials = dbCredentials;
}
}
}
diff --git a/src/bnhtrade.Core/Data/Database/Consistency/ImportAmazonSettlement.cs b/src/bnhtrade.Core/Data/Database/Consistency/ImportAmazonSettlement.cs
deleted file mode 100644
index ece367b..0000000
--- a/src/bnhtrade.Core/Data/Database/Consistency/ImportAmazonSettlement.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace bnhtrade.Core.Data.Database.Consistency
-{
- public class ImportAmazonSettlement : Connection
- {
- public ImportAmazonSettlement()
- {
-
- }
-
- public List ErrorMessage { get; private set; }
-
- public bool ErrorMessageIsSet
- {
- get
- {
- if (ErrorMessage == null || !ErrorMessage.Any()) { return false; }
- else { return true; }
- }
- }
-
- public bool PeriodDateGaps()
- {
- ErrorMessage = null;
-
- using (var sqlConn = new SqlConnection(SqlConnectionString))
- {
- var log = new Logic.Log.LogEvent();
- sqlConn.Open();
-
- // get list of marketplace names
- var marketplaces = new List();
- using (SqlCommand cmd = new SqlCommand(@"
- SELECT DISTINCT tblImportAmazonSettlementReport.ImportAmazonSettlementReportID
- ,tblImportAmazonSettlementReport.[marketplace-name]
- ,tblImportAmazonSettlementReport.[settlement-start-date]
- ,tblImportAmazonSettlementReport.[settlement-end-date]
- FROM tblImportAmazonSettlementReport
- ORDER BY tblImportAmazonSettlementReport.[marketplace-name]
- ,tblImportAmazonSettlementReport.[settlement-start-date]
- ,tblImportAmazonSettlementReport.[settlement-end-date];
- ", sqlConn))
- {
- using(var reader = cmd.ExecuteReader())
- {
- if (!reader.HasRows)
- {
- ErrorMessage.Add("No data found. Is the table empty?");
- return false;
- }
-
- int i = 0;
- string marketplace = "some-random-string-7posadlnvl2oaweoh3amol5o5irv8nl2aoqefl";
- DateTime endDate = DateTime.SpecifyKind(default(DateTime), DateTimeKind.Utc);
- while (reader.Read())
- {
- if (reader.IsDBNull(1))
- {
- log.LogError(
- "Action required: Enter market place name for settlelment report id " + reader.GetInt32(0) + "."
- , "Unable to process settlement data from one settlement report '" + reader.GetInt32(0) +
- "'. Report header table requires a market place name, which is not supplied in original " +
- "report from Amazon. This is useually inferred from settlement lines. " +
- "However, in this case, it was not not possible. Manual edit/entry for database table required."
- );
- return false;
- }
-
- string newMarketPlace = reader.GetString(1);
- DateTime startDate = DateTime.SpecifyKind( reader.GetDateTime(2), DateTimeKind.Utc);
-
- if (marketplace != newMarketPlace)
- {
- marketplace = newMarketPlace;
- i = 0;
- }
-
- if (i > 0 && startDate != endDate)
- {
- log.LogError("Inconsistancy in DB data found, break in settlement period dates.",
- marketplace + " at ID=" + reader.GetInt32(0) + " start-date is not the same as the previous period end-date."
- + Environment.NewLine + "If it's a missing settlement report and it's over 90 days ago, you may need to go to"
- + " 'Seller Central' > 'Payments' > 'All Statements' and manually 'Request Report' for each missing settlement.");
- return false;
- }
-
- endDate = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc);
- i++;
- }
- }
- }
- }
- return true;
- }
- }
-}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Export/CreateAmazonFeedSubmission.cs b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionInsert.cs
similarity index 95%
rename from src/bnhtrade.Core/Data/Database/Export/CreateAmazonFeedSubmission.cs
rename to src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionInsert.cs
index 4145fb3..8e12ffd 100644
--- a/src/bnhtrade.Core/Data/Database/Export/CreateAmazonFeedSubmission.cs
+++ b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionInsert.cs
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
@@ -8,9 +8,9 @@ using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Export
{
- public class CreateAmazonFeedSubmission : Connection
+ internal class AmazonFeedSubmissionInsert : Connection
{
- public CreateAmazonFeedSubmission ()
+ public AmazonFeedSubmissionInsert ()
{
}
diff --git a/src/bnhtrade.Core/Data/Database/Export/ReadAmazonFeedSubmission.cs b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionRead.cs
similarity index 97%
rename from src/bnhtrade.Core/Data/Database/Export/ReadAmazonFeedSubmission.cs
rename to src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionRead.cs
index d5768bf..0a122fd 100644
--- a/src/bnhtrade.Core/Data/Database/Export/ReadAmazonFeedSubmission.cs
+++ b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionRead.cs
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -8,9 +8,9 @@ using Dapper;
namespace bnhtrade.Core.Data.Database.Export
{
- public class ReadAmazonFeedSubmission : Connection
+ internal class AmazonFeedSubmissionRead : Connection
{
- public ReadAmazonFeedSubmission()
+ public AmazonFeedSubmissionRead()
{
}
diff --git a/src/bnhtrade.Core/Data/Database/Export/UpdateAmazonFeedSubmission.cs b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionUpdate.cs
similarity index 97%
rename from src/bnhtrade.Core/Data/Database/Export/UpdateAmazonFeedSubmission.cs
rename to src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionUpdate.cs
index acd001e..0f4ef07 100644
--- a/src/bnhtrade.Core/Data/Database/Export/UpdateAmazonFeedSubmission.cs
+++ b/src/bnhtrade.Core/Data/Database/Export/AmazonFeedSubmissionUpdate.cs
@@ -1,15 +1,15 @@
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Export
{
- public class UpdateAmazonFeedSubmission : Connection
+ internal class AmazonFeedSubmissionUpdate : Connection
{
- public UpdateAmazonFeedSubmission()
+ public AmazonFeedSubmissionUpdate()
{
}
diff --git a/src/bnhtrade.Core/Data/Database/Export/CreateSalesInvoice.cs b/src/bnhtrade.Core/Data/Database/Export/CreateSalesInvoice.cs
deleted file mode 100644
index 38354b7..0000000
--- a/src/bnhtrade.Core/Data/Database/Export/CreateSalesInvoice.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Transactions;
-
-namespace bnhtrade.Core.Data.Database.Export
-{
- public class CreateSalesInvoice : Connection
- {
- public CreateSalesInvoice()
- {
-
- }
-
- public void Execute(List invoiceList)
- {
- using (TransactionScope scope = new TransactionScope())
- {
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- // make the inserts
- for (int i = 0; i < invoiceList.Count(); i++)
- {
- int invoiceId = 0;
- using (SqlCommand cmd = new SqlCommand(@"
- INSERT INTO tblExportAccountInvoice (
- ExportAccountInvoiceTypeID
- ,Contact
- ,InvoiceDate
- ,InvoiceDueDate
- ,InvoiceNumber
- ,Reference
- ,CurrencyCode
- ,InvoiceAmount
- ,IsComplete
- )
- OUTPUT INSERTED.ExportAccountInvoiceID
- VALUES (
- @invoiceTypeId
- ,@contact
- ,@invoiceDate
- ,@invoiceDueDate
- ,@invoiceNumber
- ,@reference
- ,@currencyCode
- ,@invoiceAmount
- ,@markComplete
- );
- ", sqlConn))
- {
- cmd.Parameters.AddWithValue("@invoiceTypeId", 2);
- cmd.Parameters.AddWithValue("@contact", invoiceList[i].ContactName);
- cmd.Parameters.AddWithValue("@invoiceDate", invoiceList[i].InvoiceDate);
- cmd.Parameters.AddWithValue("@invoiceDueDate", invoiceList[i].InvoiceDueDate);
- cmd.Parameters.AddWithValue("@reference", invoiceList[i].InvoiceReference);
- cmd.Parameters.AddWithValue("@currencyCode", invoiceList[i].InvoiceCurrencyCode);
- cmd.Parameters.AddWithValue("@markComplete", false);
- cmd.Parameters.AddWithValue("@invoiceNumber", invoiceList[i].InvoiceNumber);
- cmd.Parameters.AddWithValue("@invoiceAmount", invoiceList[i].InvoiceTotalAmount);
-
- invoiceId = (int)cmd.ExecuteScalar();
- }
-
- for (int j = 0; j < invoiceList[i].InvoiceLineList.Count(); j++)
- {
- // insert record
- using (SqlCommand cmd = new SqlCommand(@"
- INSERT INTO tblExportAccountInvoiceLine (
- ExportAccountInvoiceID
- ,AccountInvoiceLineItemID
- ,NetAmount
- ,AccountChartOfID
- ,TaxAmount
- ,AccountTaxCodeID
- )
- OUTPUT INSERTED.ExportAccountInvoiceLineID
- VALUES (
- @invoiceId
- ,(
- SELECT AccountInvoiceLineItemID
- FROM tblAccountInvoiceLineItem
- WHERE ItemCode = @itemCode
- )
- ,@netAmount
- ,(
- SELECT AccountChartOfID
- FROM tblAccountChartOf
- WHERE AccountCode = @accountCode
- )
- ,@taxAmount
- ,(
- SELECT AccountTaxCodeID
- FROM tblAccountTaxCode
- WHERE TaxCode = @taxCode
- )
- );
- ", sqlConn))
- {
- cmd.Parameters.AddWithValue("@invoiceID", invoiceId);
- cmd.Parameters.AddWithValue("@itemCode", invoiceList[i].InvoiceLineList[j].ItemCode);
- cmd.Parameters.AddWithValue("@netAmount", invoiceList[i].InvoiceLineList[j].UnitAmount);
- cmd.Parameters.AddWithValue("@accountCode", (int)invoiceList[i].InvoiceLineList[j].AccountCode.AccountCode);
- cmd.Parameters.AddWithValue("@taxAmount", invoiceList[i].InvoiceLineList[j].TaxAmount);
- cmd.Parameters.AddWithValue("@taxCode", invoiceList[i].InvoiceLineList[j].TaxCode.TaxCode);
-
- int lineId = (int)cmd.ExecuteScalar();
- }
- }
- }
- }
- scope.Complete();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementHeaderRead.cs b/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementHeaderRead.cs
deleted file mode 100644
index 02f1f23..0000000
--- a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementHeaderRead.cs
+++ /dev/null
@@ -1,294 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Data.SqlClient;
-
-namespace bnhtrade.Core.Data.Database.Import
-{
- public class AmazonSettlementHeaderRead : Connection
- {
- private Dictionary dicTablePkBySettlementId = new Dictionary();
- private int? returnTop = null;
- private List settlementIdList;
- private List spapiReportId;
-
- protected bool FilterOutIsProcessed { get; set; }
-
- public bool DescendingOrder { get; set; }
-
- public int ReturnTop
- {
- get { return (int)returnTop; }
- set
- {
- if (value > 0)
- { returnTop = value; }
- else
- { returnTop = null; }
- }
- }
-
- public bool ReturnTopIsSet
- {
- get { return returnTop != null; }
- }
-
- private List SettlementIdList
- {
- get { return settlementIdList; }
- set
- {
- if (value.Any())
- { settlementIdList = value; }
- }
-
- }
-
- private List SpapiReportIdList
- {
- get { return spapiReportId; }
- set
- {
- if (value.Any())
- { spapiReportId = value; }
- }
-
- }
-
- private bool SettlementIdListIsSet
- {
- get { return SettlementIdList != null; }
- }
-
- private bool SpapiReportIdIsSet
- {
- get { return SpapiReportIdList != null; }
- }
-
- public AmazonSettlementHeaderRead()
- {
- Innit();
- }
-
- private void Innit()
- {
- DescendingOrder = false;
- FilterOutIsProcessed = false;
- ReturnTop = 0;
- settlementIdList = null;
- spapiReportId = null;
- }
-
- public List AllUnprocessed()
- {
- Innit();
- FilterOutIsProcessed = true;
- return ReadHeaderList();
- }
-
- public Model.Import.AmazonSettlementHeader BySettlementId(string settlementId)
- {
- Innit();
-
- // create settlement list
- var idList = new List();
- idList.Add(settlementId);
- var settlementList = BySettlementId(idList);
-
- // return answer
- if (settlementList == null || !settlementList.Any())
- { return null; }
- else
- { return settlementList.First(); }
- }
-
- public List BySettlementId(List settlementIdList)
- {
- Innit();
-
- if (settlementIdList == null || !settlementIdList.Any())
- { return new List(); }
-
- SettlementIdList = settlementIdList;
-
- return ReadHeaderList();
- }
-
- public List BySpapiReportId(List spapiReportIdList)
- {
- Innit();
-
- if (spapiReportIdList == null || !spapiReportIdList.Any())
- { return new List(); }
-
- SpapiReportIdList = spapiReportIdList;
-
- return ReadHeaderList();
- }
-
- private List ReadHeaderList()
- {
- var returnHeaderList = new List();
-
- // build the sql string
- string sqlString = "SELECT ";
-
- if (ReturnTopIsSet)
- {
- sqlString = sqlString + "TOP " + ReturnTop + " ";
- }
-
- sqlString = sqlString + @"
- ImportAmazonSettlementReportID
- ,[marketplace-name]
- ,[settlement-id]
- ,[settlement-start-date]
- ,[settlement-end-date]
- ,[deposit-date]
- ,[total-amount]
- ,currency
- ,IsProcessed
- ,SpapiReportId
- FROM tblImportAmazonSettlementReport
- WHERE 1 = 1";
-
- if (FilterOutIsProcessed)
- {
- sqlString = sqlString + @"
- AND IsProcessed = 0";
- }
-
- // build dictionary of parameter and values for settlementid
- var dicSettlementIdByParameterString = new Dictionary();
- if (SettlementIdListIsSet)
- {
- int count = 0;
- foreach (string item in SettlementIdList)
- {
- if (!string.IsNullOrWhiteSpace(item))
- {
- count = count + 1;
- string parameterString = "@settlementId" + count;
- dicSettlementIdByParameterString.Add(parameterString, item);
- }
- }
- }
-
- if (dicSettlementIdByParameterString.Any())
- {
- int count = 0;
- foreach (var item in dicSettlementIdByParameterString)
- {
- count = count + 1;
- if (count == 1)
- {
- sqlString = sqlString + @"
- AND ( [settlement-id] = " + item.Key;
- }
- else
- {
- sqlString = sqlString + @"
- OR [settlement-id] = " + item.Key;
- }
- }
- sqlString = sqlString + " )";
- }
-
- // build dictionary of parameter and values for SP-API Report Id
- var dicSpapiReportIdByParameterString = new Dictionary();
- if (SpapiReportIdIsSet)
- {
- int count = 0;
- foreach (string item in SpapiReportIdList)
- {
- if (!string.IsNullOrWhiteSpace(item))
- {
- count = count + 1;
- string parameterString = "@SpapiReportId" + count;
- dicSpapiReportIdByParameterString.Add(parameterString, item);
- }
- }
- }
-
- if (dicSpapiReportIdByParameterString.Any())
- {
- int count = 0;
- foreach (var item in dicSpapiReportIdByParameterString)
- {
- count = count + 1;
- if (count == 1)
- {
- sqlString = sqlString + @"
- AND ( SpapiReportId = " + item.Key;
- }
- else
- {
- sqlString = sqlString + @"
- OR SpapiReportId = " + item.Key;
- }
- }
- sqlString = sqlString + " )";
- }
-
-
- sqlString = sqlString + @"
- ORDER BY [settlement-start-date] ";
- if (DescendingOrder) { sqlString = sqlString + " DESC"; }
-
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sqlString, conn))
- {
- if (dicSettlementIdByParameterString.Any())
- {
- foreach (var item in dicSettlementIdByParameterString)
- {
- cmd.Parameters.AddWithValue(item.Key, item.Value);
- }
- }
-
- if (dicSpapiReportIdByParameterString.Any())
- {
- foreach (var item in dicSpapiReportIdByParameterString)
- {
- cmd.Parameters.AddWithValue(item.Key, item.Value);
- }
- }
-
- using (var reader = cmd.ExecuteReader())
- {
- while (reader.Read())
- {
- var header = new Model.Import.AmazonSettlementHeader();
-
- int tablePk = reader.GetInt32(0);
- if (!reader.IsDBNull(1)) { header.MarketPlaceName = reader.GetString(1); }
- header.SettlementId = reader.GetString(2);
- header.StartDate = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc);
- header.EndDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
- header.DepositDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
- header.TotalAmount = reader.GetDecimal(6);
- header.CurrencyCode = reader.GetString(7);
- header.IsProcessed = reader.GetBoolean(8);
- if (!reader.IsDBNull(9)) { header.SpapiReportId = reader.GetString(9); }
-
- // update dictionary
- if (!dicTablePkBySettlementId.ContainsKey(header.SettlementId))
- {
- dicTablePkBySettlementId.Add(header.SettlementId, tablePk);
- }
-
- // add header to list
- returnHeaderList.Add(header);
- }
- }
- }
- }
- return returnHeaderList;
- }
- }
-}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementInsert.cs b/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementInsert.cs
deleted file mode 100644
index 778368b..0000000
--- a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementInsert.cs
+++ /dev/null
@@ -1,330 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.SqlClient;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Transactions;
-
-namespace bnhtrade.Core.Data.Database.Import
-{
- public class AmazonSettlementInsert : Connection
- {
- Logic.Log.LogEvent log = new Logic.Log.LogEvent();
-
- public AmazonSettlementInsert ()
- {
-
- }
-
- ///
- ///
- ///
- ///
- /// The unique Amazon SP-API report id (not settlement id)
- ///
- public bool ByFlatFile(string filePath, string reportId)
- {
- using (TransactionScope scope = new TransactionScope())
- {
- using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
- {
- sqlConn.Open();
-
- int settlementReportId = 0;
- string settlementRef = "";
- bool marketPlaceUpdated = false;
- decimal settlementAmount = 0m;
- int lineNumber = 2;
- int lineSkip = 0;
-
- using (var reader = new StreamReader(filePath))
- {
- //read file one line at a time and insert data into table if required
-
- // read header and retrive information
- string headerRow = reader.ReadLine();
- string[] headers = headerRow.Split('\t');
-
- int columnCount = headers.Length;
-
- int indexSettlementId = Array.IndexOf(headers, "settlement-id");
- int indexSettlementStartDate = Array.IndexOf(headers, "settlement-start-date");
- int indexSettlementEndDate = Array.IndexOf(headers, "settlement-end-date");
- int indexDepositDate = Array.IndexOf(headers, "deposit-date");
- int indexTotalAmount = Array.IndexOf(headers, "total-amount");
- int indexCurrency = Array.IndexOf(headers, "currency");
- int indexTransactionType = Array.IndexOf(headers, "transaction-type");
- int indexOrderId = Array.IndexOf(headers, "order-id");
- int indexMerchantOrderId = Array.IndexOf(headers, "merchant-order-id");
- int indexAdjustmentId = Array.IndexOf(headers, "adjustment-id");
- int indexShipmentId = Array.IndexOf(headers, "shipment-id");
- int indexMarketplaceName = Array.IndexOf(headers, "marketplace-name");
- int indexAmountType = Array.IndexOf(headers, "amount-type");
- int indexAmountDescription = Array.IndexOf(headers, "amount-description");
- int indexAmount = Array.IndexOf(headers, "amount");
- int indexFulfillmentId = Array.IndexOf(headers, "fulfillment-id");
- // int indexPostedDate = Array.IndexOf(headers, "posted-date");
- int indexPostedDateTime = Array.IndexOf(headers, "posted-date-time");
- int indexOrderItemCode = Array.IndexOf(headers, "order-item-code");
- int indexMerchantOrderItemId = Array.IndexOf(headers, "merchant-order-item-id");
- int indexMerchantAdjustmentItemId = Array.IndexOf(headers, "merchant-adjustment-item-id");
- int indexSku = Array.IndexOf(headers, "sku");
- int indexQuantityPurchased = Array.IndexOf(headers, "quantity-purchased");
- int indexPromotionId = Array.IndexOf(headers, "promotion-id");
-
- string currency = "";
-
- string fileRow;
- while ((fileRow = reader.ReadLine()) != null)
- {
- Console.Write("\rParsing record: " + lineNumber);
- //split line into array
- string[] items = fileRow.Split('\t');
- if (items.Length != columnCount)
- {
- // skip line
- lineSkip = lineSkip + 1;
- log.LogWarning(
- "Line #" + lineNumber + " skipped due to no enough element in row.",
- filePath
- );
- }
- else if (lineNumber == 2)
- {
- // check if settlement has already been imported
- using (SqlCommand sqlCommand = new SqlCommand(
- "SELECT COUNT(*) FROM tblImportAmazonSettlementReport WHERE [settlement-id]=@settlementId;"
- , sqlConn))
- {
- sqlCommand.Parameters.AddWithValue("@settlementId", items[indexSettlementId]);
- int recordCount = (int)sqlCommand.ExecuteScalar();
- if (recordCount > 0)
- {
- UpdateSpapiReportId(items[indexSettlementId], reportId);
- log.LogInformation("Settlement report already imported, skipping...");
- scope.Complete();
- return true;
- }
- }
- //set currencyId
- //currencyId = GeneralQueries.GetCurrencyId(items[5]);
-
- //set currency
- currency = items[indexCurrency];
- settlementAmount = decimal.Parse(items[indexTotalAmount].Replace(",", "."));
-
- // insert
- using (SqlCommand sqlCommand = new SqlCommand(@"
- INSERT INTO tblImportAmazonSettlementReport (
- [settlement-id]
- ,[settlement-start-date]
- ,[settlement-end-date]
- ,[deposit-date]
- ,[total-amount]
- ,[currency]
- ,SpapiReportId
- )
- OUTPUT INSERTED.ImportAmazonSettlementReportID
- VALUES (
- @settlementId
- ,@settlementStartDate
- ,@settlementEndDate
- ,@depositDate
- ,@settlementotalAmounttId
- ,@currency
- ,@reportId
- );
- ", sqlConn))
- {
- // add parameters
- if (indexSettlementId == -1 || items[indexSettlementId].Length == 0) { sqlCommand.Parameters.AddWithValue("@settlementId", DBNull.Value); }
- else
- {
- settlementRef = items[indexSettlementId];
- sqlCommand.Parameters.AddWithValue("@settlementId", settlementRef);
- }
-
- var parseDateTime = new Core.Logic.Utilities.DateTime();
-
- if (indexSettlementStartDate == -1 || items[indexSettlementStartDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@settlementStartDate", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@settlementStartDate", parseDateTime.ParseIsoDateTimeString(items[indexSettlementStartDate])); }
-
- if (indexSettlementEndDate == -1 || items[indexSettlementEndDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@settlementEndDate", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@settlementEndDate", parseDateTime.ParseIsoDateTimeString(items[indexSettlementEndDate])); }
-
- if (indexDepositDate == -1 || items[indexDepositDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@depositDate", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@depositDate", parseDateTime.ParseIsoDateTimeString(items[indexDepositDate])); }
-
- if (indexTotalAmount == -1 || items[indexTotalAmount].Length == 0) { sqlCommand.Parameters.AddWithValue("@totalAmount", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@settlementotalAmounttId", settlementAmount); }
-
- if (string.IsNullOrWhiteSpace(reportId)) { sqlCommand.Parameters.AddWithValue("@reportId", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@reportId", reportId); }
-
- sqlCommand.Parameters.AddWithValue("@currency", currency);
-
- //if (currencyId == -1) { sqlCommand.Parameters.AddWithValue("@currencyId", DBNull.Value); }
- //else { sqlCommand.Parameters.AddWithValue("@currencyId", currencyId); }
-
- //execute and retrive id
- settlementReportId = (int)sqlCommand.ExecuteScalar();
-
- }
- }
- else
- {
- //update market place name in main table, if required
- if (marketPlaceUpdated == false && settlementReportId > 0 && items[indexMarketplaceName].Length > 1)
- {
- using (SqlCommand sqlCommand = new SqlCommand(@"
- UPDATE tblImportAmazonSettlementReport
- SET [marketplace-name]=@MarketplaceName
- WHERE ImportAmazonSettlementReportID=@ImportAmazonSettlementReportID
- ", sqlConn))
- {
- sqlCommand.Parameters.AddWithValue("@MarketplaceName", items[indexMarketplaceName]);
- sqlCommand.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
-
- sqlCommand.ExecuteNonQuery();
- marketPlaceUpdated = true;
- }
- }
-
- //insert report items
- using (SqlCommand sqlCommand = new SqlCommand(
- "INSERT INTO tblImportAmazonSettlementReportLine ( " +
- "ImportAmazonSettlementReportID, [transaction-type], [order-id], [merchant-order-id], [adjustment-id], [shipment-id], [marketplace-name], " +
- "[amount-type], [amount-description], [currency], [amount], [fulfillment-id], [posted-date-time], [order-item-code], " +
- "[merchant-order-item-id], [merchant-adjustment-item-id], [sku], [quantity-purchased], [promotion-id] ) " +
- "VALUES ( " +
- "@ImportAmazonSettlementReportID, @TransactionType, @orderRef, @merchantOrderRef, @AdjustmentRef, @ShipmentRef, @MarketplaceName, " +
- "@AmountType, @AmountDescription, @currency, @Amount, @FulfillmentRef, @PostedDateTimeUTC, @OrderItemCode, " +
- "@MerchantOrderItemRef, @MerchantAdjustmentItemRef, @SkuNumber, @QuantityPurchased, @PromotionRef );"
- , sqlConn))
- {
- // add parameters
- sqlCommand.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
-
- sqlCommand.Parameters.AddWithValue("@currency", currency);
-
- if (indexTransactionType == -1 || items[indexTransactionType].Length == 0) { sqlCommand.Parameters.AddWithValue("@TransactionType", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@TransactionType", items[indexTransactionType]); }
-
- if (indexOrderId == -1 || items[indexOrderId].Length == 0) { sqlCommand.Parameters.AddWithValue("@orderRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@orderRef", items[indexOrderId]); }
-
- if (indexMerchantOrderId == -1 || items[indexMerchantOrderId].Length == 0) { sqlCommand.Parameters.AddWithValue("@merchantOrderRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@merchantOrderRef", items[indexMerchantOrderId]); }
-
- if (indexAdjustmentId == -1 || items[indexAdjustmentId].Length == 0) { sqlCommand.Parameters.AddWithValue("@AdjustmentRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@AdjustmentRef", items[indexAdjustmentId]); }
-
- if (indexShipmentId == -1 || items[indexShipmentId].Length == 0) { sqlCommand.Parameters.AddWithValue("@ShipmentRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@ShipmentRef", items[indexShipmentId]); }
-
- if (indexMarketplaceName == -1 || items[indexMarketplaceName].Length == 0) { sqlCommand.Parameters.AddWithValue("@MarketplaceName", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@MarketplaceName", items[indexMarketplaceName]); }
-
- if (indexAmountType == -1 || items[indexAmountType].Length == 0) { sqlCommand.Parameters.AddWithValue("@AmountType", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@AmountType", items[indexAmountType]); }
-
- if (indexAmountDescription == -1 || items[indexAmountDescription].Length == 0) { sqlCommand.Parameters.AddWithValue("@AmountDescription", DBNull.Value); }
- else
- {
- string amountDescription = items[indexAmountDescription];
- if (amountDescription.Length > 100) { amountDescription = amountDescription.Substring(0, 100); }
- sqlCommand.Parameters.AddWithValue("@AmountDescription", amountDescription);
- }
-
- if (indexAmount == -1 || items[indexAmount].Length == 0) { sqlCommand.Parameters.AddWithValue("@Amount", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@Amount", decimal.Parse(items[indexAmount].Replace(",", "."))); }
-
- if (indexFulfillmentId == -1 || items[indexFulfillmentId].Length == 0) { sqlCommand.Parameters.AddWithValue("@FulfillmentRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@FulfillmentRef", items[indexFulfillmentId]); }
-
- if (indexPostedDateTime == -1 || items[indexPostedDateTime].Length == 0) { sqlCommand.Parameters.AddWithValue("@PostedDateTimeUTC", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@PostedDateTimeUTC", new Logic.Utilities.DateTime().ParseIsoDateTimeString(items[indexPostedDateTime])); }
-
- if (indexOrderItemCode == -1 || items[indexOrderItemCode].Length == 0) { sqlCommand.Parameters.AddWithValue("@OrderItemCode", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@OrderItemCode", long.Parse(items[indexOrderItemCode])); }
-
- if (indexMerchantOrderItemId == -1 || items[indexMerchantOrderItemId].Length == 0) { sqlCommand.Parameters.AddWithValue("@MerchantOrderItemRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@MerchantOrderItemRef", long.Parse(items[indexMerchantOrderItemId])); }
-
- if (indexMerchantAdjustmentItemId == -1 || items[indexMerchantAdjustmentItemId].Length == 0) { sqlCommand.Parameters.AddWithValue("@MerchantAdjustmentItemRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@MerchantAdjustmentItemRef", items[indexMerchantAdjustmentItemId]); }
-
- if (indexSku == -1 || items[indexSku].Length == 0) { sqlCommand.Parameters.AddWithValue("@SkuNumber", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@SkuNumber", items[indexSku]); }
-
- if (indexQuantityPurchased == -1 || items[indexQuantityPurchased].Length == 0) { sqlCommand.Parameters.AddWithValue("@QuantityPurchased", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@QuantityPurchased", int.Parse(items[indexQuantityPurchased])); }
-
- if (indexPromotionId == -1 || items[indexPromotionId].Length == 0) { sqlCommand.Parameters.AddWithValue("@PromotionRef", DBNull.Value); }
- else { sqlCommand.Parameters.AddWithValue("@PromotionRef", items[indexPromotionId]); }
-
- sqlCommand.ExecuteNonQuery();
- }
- }
- lineNumber = lineNumber + 1;
- }
- }
-
- //final check - settlement amount matches sum of inserted settlement lines
- using (SqlCommand sqlCommand = new SqlCommand(@"
- SELECT Sum(tblImportAmazonSettlementReportLine.amount) AS SumOfAmount
- FROM tblImportAmazonSettlementReportLine
- WHERE ImportAmazonSettlementReportID=@ImportAmazonSettlementReportID;
- ", sqlConn))
- {
- decimal sumOfAmount = -1.12345m;
-
- sqlCommand.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
- sumOfAmount = (decimal)sqlCommand.ExecuteScalar();
-
- if (sumOfAmount != settlementAmount)
- {
- log.LogError("Error importing settlement id'" + settlementRef + "'. Sum of inserted settlement lines (" + sumOfAmount +
- ") does not match settlement amount (" + settlementAmount + ").");
- return false;
- }
- }
- scope.Complete();
-
- Console.Write("\r");
- log.LogInformation((lineNumber - (2 + lineSkip)) + " total settlement items inserted");
- if (lineSkip > 0)
- {
- log.LogError(lineSkip + " total line(s) where skipped due to insufficent number of cells on row");
- }
- }
- }
- return true;
- }
-
- public void UpdateSpapiReportId (string settlementId, string spapiReportId)
- {
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(@"
- UPDATE
- tblImportAmazonSettlementReport
- SET
- SpapiReportId = @spapiReportId
- WHERE
- [settlement-id] = @settlementId
- ", conn))
- {
- cmd.Parameters.AddWithValue("@spapiReportId", spapiReportId);
- cmd.Parameters.AddWithValue("@settlementId", settlementId);
-
- cmd.ExecuteNonQuery();
- }
- }
- }
- }
-}
diff --git a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementRead.cs b/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementRead.cs
deleted file mode 100644
index 4e46a34..0000000
--- a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementRead.cs
+++ /dev/null
@@ -1,462 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Data.SqlClient;
-
-namespace bnhtrade.Core.Data.Database.Import
-{
- public class AmazonSettlementRead : Connection
- {
- private Data.Database.SqlWhereBuilder whereBuilder = new SqlWhereBuilder();
-
- public List BySettlementIdList(List settlementIdList)
- {
- var settlementList = new List();
-
- // build sql statement
-
- string sql = @"
- SELECT tblImportAmazonSettlementReport.[settlement-id]
- ,tblImportAmazonSettlementReportLine.[transaction-type]
- ,tblImportAmazonSettlementReportLine.[order-id]
- ,tblImportAmazonSettlementReportLine.[merchant-order-id]
- ,tblImportAmazonSettlementReportLine.[adjustment-id]
- ,tblImportAmazonSettlementReportLine.[shipment-id]
- ,tblImportAmazonSettlementReportLine.[marketplace-name]
- ,tblImportAmazonSettlementReportLine.[amount-type]
- ,tblImportAmazonSettlementReportLine.[amount-description]
- ,tblImportAmazonSettlementReportLine.amount
- ,tblImportAmazonSettlementReportLine.currency
- ,tblImportAmazonSettlementReportLine.[fulfillment-id]
- ,tblImportAmazonSettlementReportLine.[posted-date-time]
- ,tblImportAmazonSettlementReportLine.[order-item-code]
- ,tblImportAmazonSettlementReportLine.[merchant-order-item-id]
- ,tblImportAmazonSettlementReportLine.[merchant-adjustment-item-id]
- ,tblImportAmazonSettlementReportLine.sku
- ,tblImportAmazonSettlementReportLine.[quantity-purchased]
- ,tblImportAmazonSettlementReportLine.[promotion-id]
- ,tblImportAmazonSettlementReportLine.IsProcessed
- ,tblImportAmazonSettlementReportLine.ExportAccountInvoiceLineID
- FROM tblImportAmazonSettlementReport
- INNER JOIN tblImportAmazonSettlementReportLine ON tblImportAmazonSettlementReport.ImportAmazonSettlementReportID = tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportID
- WHERE ";
-
- whereBuilder.Init();
- whereBuilder.In("tblImportAmazonSettlementReport.[settlement-id]", settlementIdList);
-
- sql += whereBuilder.SqlWhereString;
-
- sql += @"
- ORDER BY tblImportAmazonSettlementReport.[settlement-id]
- ,tblImportAmazonSettlementReportLine.[posted-date-time] ";
-
- // set variables
- bool firstRecord = true;
- string settlementId = "";
- var lineList = new List();
- var LineListDic = new Dictionary>();
- var headerList = new List();
-
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sql, conn))
- {
- whereBuilder.AddParametersToSqlCommand(cmd);
-
- using (var reader = cmd.ExecuteReader())
- {
- if (!reader.HasRows)
- {
- return settlementList;
- }
-
- // get the header list
- headerList = new Data.Database.Import.AmazonSettlementHeaderRead().BySettlementId(settlementIdList);
-
- // loop through table to build dictionary
- while (reader.Read())
- {
- if (reader.GetString(0) != settlementId)
- {
- if (firstRecord)
- {
- firstRecord = false;
- settlementId = reader.GetString(0);
- }
- else
- {
- LineListDic.Add(settlementId, lineList);
- settlementId = reader.GetString(0);
- lineList = new List();
- }
- }
-
- var line = new Model.Import.AmazonSettlement.SettlementLine();
-
- line.TransactionType = reader.GetString(1);
- if (!reader.IsDBNull(2)) { line.OrderId = reader.GetString(2); }
- if (!reader.IsDBNull(3)) { line.MerchantOrderId = reader.GetString(3); }
- if (!reader.IsDBNull(4)) { line.AdjustmentId = reader.GetString(4); }
- if (!reader.IsDBNull(5)) { line.ShipmentId = reader.GetString(5); }
- if (!reader.IsDBNull(6)) { line.MarketPlaceName = reader.GetString(6); }
- line.AmountType = reader.GetString(7);
- line.AmountDescription = reader.GetString(8);
- line.Amount = reader.GetDecimal(9);
- line.CurrenyCode = reader.GetString(10);
- if (!reader.IsDBNull(11)) { line.FulfillmentId = reader.GetString(11); }
- line.PostDateTime = DateTime.SpecifyKind(reader.GetDateTime(12), DateTimeKind.Utc);
- if (!reader.IsDBNull(13)) { line.OrderItemCode = reader.GetString(13); }
- if (!reader.IsDBNull(14)) { line.MerchantOrderItemId = reader.GetString(14); }
- if (!reader.IsDBNull(15)) { line.MerchantAdjustmentItemId = reader.GetString(15); }
- if (!reader.IsDBNull(16)) { line.Sku = reader.GetString(16); }
- if (!reader.IsDBNull(17)) { line.QuantityPurchased = reader.GetInt32(17); }
- if (!reader.IsDBNull(18)) { line.PromotionId = reader.GetString(18); }
- line.IsProcessed = reader.GetBoolean(19);
- if (!reader.IsDBNull(20)) { int exportAccountInvoiceLineId = reader.GetInt32(20); }
-
- lineList.Add(line);
- }
- LineListDic.Add(settlementId, lineList);
- }
- }
- }
-
- //create return list
- foreach(var item in headerList)
- {
- var settlementReport = new Model.Import.AmazonSettlement(item);
- settlementReport.SettlementLineList = LineListDic[item.SettlementId];
- settlementList.Add(settlementReport);
- }
-
- return settlementList;
- }
-
- public void ByHeaderList()
- {
-
- }
-
- public void BySettlementId()
- {
-
- }
-
-
-
- private Dictionary dicTablePkBySettlementId = new Dictionary();
- private int? returnTop = null;
- private List settlementIdList;
-
- private bool FilterOutIsProcessed { get; set; }
-
- public bool DescendingOrder { get; set; }
-
- public int ReturnTop
- {
- get { return (int)returnTop; }
- set
- {
- if (value > 0)
- { returnTop = value; }
- else
- { returnTop = null; }
- }
- }
-
- public bool ReturnTopIsSet
- {
- get { return returnTop != null; }
- }
-
- private List SettlementIdList
- {
- get { return settlementIdList; }
- set
- {
- if (value.Any())
- { settlementIdList = value; }
- }
-
- }
-
- private bool SettlementIdListIsSet
- {
- get { return SettlementIdList != null; }
- }
-
- public AmazonSettlementRead()
- {
- Innit();
- }
-
- private void Innit()
- {
- DescendingOrder = false;
- FilterOutIsProcessed = false;
- ReturnTop = 0;
- settlementIdList = null;
- }
-
- public List AllUnprocessed()
- {
- Innit();
- FilterOutIsProcessed = true;
- return ExecuteDbQuery();
- }
-
- public Model.Import.AmazonSettlement BySettlementId(string settlementId)
- {
- Innit();
-
- // create settlement list
- var idList = new List();
- idList.Add(settlementId);
- var settlementList = BySettlementId(idList);
-
- // return answer
- if (settlementList == null || !settlementList.Any())
- { return null; }
- else
- { return settlementList.First(); }
- }
-
- public List BySettlementId(List settlementIdList)
- {
- Innit();
-
- if (settlementIdList == null || !settlementIdList.Any())
- { return null; }
-
- SettlementIdList = settlementIdList;
-
- return ExecuteDbQuery();
- }
-
- private List ExecuteDbQuery()
- {
- // get header info
- var settlementList = ReadHeaderList();
- if (settlementList == null || !settlementList.Any())
- {
- return null;
- }
-
- // add lines to header
- foreach (var item in settlementList)
- {
- if (!dicTablePkBySettlementId.ContainsKey(item.SettlementId))
- {
- throw new Exception("This shouldnt' happen!");
- }
- int tablePk = dicTablePkBySettlementId[item.SettlementId];
-
- item.SettlementLineList = ReadLineList(tablePk);
- }
-
- return settlementList;
- }
-
- private List ReadHeaderList()
- {
- // build the sql string
- string sqlString = "SELECT ";
-
- if (ReturnTopIsSet)
- {
- sqlString = sqlString + "TOP " + ReturnTop + " ";
- }
-
- sqlString = sqlString + @"
- ImportAmazonSettlementReportID
- ,[marketplace-name]
- ,[settlement-id]
- ,[settlement-start-date]
- ,[settlement-end-date]
- ,[deposit-date]
- ,[total-amount]
- ,currency
- ,IsProcessed
- FROM tblImportAmazonSettlementReport
- WHERE 1 = 1";
-
- if (FilterOutIsProcessed)
- {
- sqlString = sqlString + @"
- AND IsProcessed = 0";
- }
-
- // build dictionary of parameter and values
- var dicSettlementIdByParameterString = new Dictionary();
- if (SettlementIdListIsSet)
- {
- int count = 0;
- foreach (string item in SettlementIdList)
- {
- if (!string.IsNullOrWhiteSpace(item))
- {
- count = count + 1;
- string parameterString = "@settlementId" + count;
- dicSettlementIdByParameterString.Add(parameterString, item);
- }
- }
- }
-
- if (dicSettlementIdByParameterString.Any())
- {
- int count = 0;
- foreach (var item in dicSettlementIdByParameterString)
- {
- count = count + 1;
- if (count == 1)
- {
- sqlString = sqlString + @"
- AND ( [settlement-id] = " + item.Key;
- }
- else
- {
- sqlString = sqlString + @"
- OR [settlement-id] = " + item.Key;
- }
- }
- sqlString = sqlString + " )";
- }
-
- sqlString = sqlString + @"
- ORDER BY [settlement-start-date] ";
- if (DescendingOrder) { sqlString = sqlString + " DESC"; }
-
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sqlString, conn))
- {
- if (dicSettlementIdByParameterString.Any())
- {
- foreach (var item in dicSettlementIdByParameterString)
- {
- cmd.Parameters.AddWithValue(item.Key, item.Value);
- }
- }
-
- using (var reader = cmd.ExecuteReader())
- {
- if (!reader.HasRows)
- {
- return null;
- }
-
- var headerList = new List();
- while (reader.Read())
- {
- var header = new Model.Import.AmazonSettlement();
-
- int tablePk = reader.GetInt32(0);
- if (!reader.IsDBNull(1)) { header.MarketPlaceName = reader.GetString(1); }
- header.SettlementId = reader.GetString(2);
- header.StartDate = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc);
- header.EndDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
- header.DepositDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
- header.TotalAmount = reader.GetDecimal(6);
- header.CurrencyCode = reader.GetString(7);
- header.IsProcessed = reader.GetBoolean(8);
-
- // update dictionary
- if (!dicTablePkBySettlementId.ContainsKey(header.SettlementId))
- {
- dicTablePkBySettlementId.Add(header.SettlementId, tablePk);
- }
-
- // add header to list
- headerList.Add(header);
- }
-
- return headerList;
- }
- }
- }
- }
-
- private List ReadLineList(int settlementPk)
- {
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(@"
- SELECT ImportAmazonSettlementReportLineID
- ,[transaction-type]
- ,[order-id]
- ,[merchant-order-id]
- ,[adjustment-id]
- ,[shipment-id]
- ,[marketplace-name]
- ,[amount-type]
- ,[amount-description]
- ,amount
- ,currency
- ,[fulfillment-id]
- ,[posted-date-time]
- ,[order-item-code]
- ,[merchant-order-item-id]
- ,[merchant-adjustment-item-id]
- ,sku
- ,[quantity-purchased]
- ,[promotion-id]
- ,IsProcessed
- ,ExportAccountInvoiceLineID
- FROM tblImportAmazonSettlementReportLine
- WHERE ImportAmazonSettlementReportID = @settlementPk
- ORDER BY [posted-date-time]
- ", conn))
- {
- cmd.Parameters.AddWithValue("@settlementPk", settlementPk);
-
- using (var reader = cmd.ExecuteReader())
- {
- if (!reader.HasRows)
- {
- return null;
- }
-
- var lineList = new List();
- while (reader.Read())
- {
- var line = new Model.Import.AmazonSettlement.SettlementLine();
-
- int tablePk = reader.GetInt32(0);
- line.TransactionType = reader.GetString(1);
- if (!reader.IsDBNull(2)) { line.OrderId = reader.GetString(2); }
- if (!reader.IsDBNull(3)) { line.MerchantOrderId = reader.GetString(3); }
- if (!reader.IsDBNull(4)) { line.AdjustmentId = reader.GetString(4); }
- if (!reader.IsDBNull(5)) { line.ShipmentId = reader.GetString(5); }
- if (!reader.IsDBNull(6)) { line.MarketPlaceName = reader.GetString(6); }
- line.AmountType = reader.GetString(7);
- line.AmountDescription = reader.GetString(8);
- line.Amount = reader.GetDecimal(9);
- line.CurrenyCode = reader.GetString(10);
- if (!reader.IsDBNull(11)) { line.FulfillmentId = reader.GetString(11); }
- line.PostDateTime = DateTime.SpecifyKind(reader.GetDateTime(12), DateTimeKind.Utc);
- if (!reader.IsDBNull(13)) { line.OrderItemCode = reader.GetString(13); }
- if (!reader.IsDBNull(14)) { line.MerchantOrderItemId = reader.GetString(14); }
- if (!reader.IsDBNull(15)) { line.MerchantAdjustmentItemId = reader.GetString(15); }
- if (!reader.IsDBNull(16)) { line.Sku = reader.GetString(16); }
- if (!reader.IsDBNull(17)) { line.QuantityPurchased = reader.GetInt32(17); }
- if (!reader.IsDBNull(18)) { line.PromotionId = reader.GetString(18); }
- line.IsProcessed = reader.GetBoolean(19);
- if (!reader.IsDBNull(20)) { int exportAccountInvoiceLineId = reader.GetInt32(20); }
-
- lineList.Add(line);
- }
- return lineList;
- }
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementUpdate.cs b/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementUpdate.cs
deleted file mode 100644
index 41a4c7b..0000000
--- a/src/bnhtrade.Core/Data/Database/Import/AmazonSettlementUpdate.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace bnhtrade.Core.Data.Database.Import
-{
- public class AmazonSettlementUpdate : Connection
- {
- public AmazonSettlementUpdate()
- {
-
- }
-
- public void SetIsProcessedTrue(List settlementIdList)
- {
- if (settlementIdList == null || !settlementIdList.Any())
- {
- throw new Exception("Settlement ID list is empty.");
- }
-
- string sqlString = @"
- UPDATE tblImportAmazonSettlementReport
- SET IsProcessed = 1
- WHERE (1=0)";
-
- for (int i = 0; i < settlementIdList.Count(); i++)
- {
- sqlString += @"
- OR ([settlement-id] = @settlementId" + i + ")";
- }
-
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(sqlString, conn))
- {
- for (int i = 0; i < settlementIdList.Count(); i++)
- {
- cmd.Parameters.AddWithValue("@settlementId" + i, settlementIdList[i]);
- }
-
- if (cmd.ExecuteNonQuery() == 0)
- {
- throw new Exception("Something went wrong updating settlement status.");
- }
- }
- }
- }
- }
-}
diff --git a/src/bnhtrade.Core/Data/Database/Programmability/Sequence.cs b/src/bnhtrade.Core/Data/Database/Programmability/Sequence.cs
deleted file mode 100644
index 58045a9..0000000
--- a/src/bnhtrade.Core/Data/Database/Programmability/Sequence.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Data.SqlClient;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace bnhtrade.Core.Data.Database.Programmability
-{
- public class Sequence : Connection
- {
- public Sequence ()
- {
-
- }
- public int GetNext(string sequenceName)
- {
- if (string.IsNullOrWhiteSpace(sequenceName))
- {
- throw new Exception("Sequence name is null or whitespace.");
- }
-
- using (SqlConnection conn = new SqlConnection(SqlConnectionString))
- {
- conn.Open();
-
- using (SqlCommand cmd = new SqlCommand(@"
- SELECT NEXT VALUE FOR " + sequenceName
- , conn))
- {
- //cmd.Parameters.AddWithValue("@sequenceName", sequenceName);
- // it wouldn't let me use parameters
-
- object obj = cmd.ExecuteScalar();
-
- try
- {
- //string whaaaat = (string)obj;
- return Convert.ToInt32(obj);
- }
- catch (Exception ex)
- {
- throw new Exception("Error returning next value in sequence: " + ex.Message);
- }
- }
- }
- }
- }
-}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/CurrencyRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/CurrencyRepository.cs
new file mode 100644
index 0000000..efb7201
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/CurrencyRepository.cs
@@ -0,0 +1,267 @@
+using bnhtrade.Core.Data.Database.Repository.Interface;
+using Microsoft.Data.SqlClient;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ internal class CurrencyRepository : _Base, ICurrencyRepository
+ {
+ public CurrencyRepository(IDbConnection connection, IDbTransaction transaction) : base(connection, transaction)
+ {
+ }
+
+ ///
+ /// Returns excahnge rate, in decimal format, for a given currency and datetime
+ ///
+ /// currency code
+ /// dat and time
+ ///
+ public decimal? ReadExchangeRate(Model.Account.CurrencyCode currencyCode, DateTime date)
+ {
+ string sql = @"
+ SELECT CurrencyUnitsPerGBP
+ FROM tblAccountExchangeRate
+ WHERE CurrencyCode=@currencyCode AND StartDate<=@conversionDate AND EndDate>@conversionDate
+ ";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@currencyCode", currencyCode.ToString());
+ cmd.Parameters.AddWithValue("@conversionDate", date);
+
+ object result = cmd.ExecuteScalar();
+ if (result != null)
+ {
+ return Convert.ToDecimal(result);
+ }
+ else
+ {
+ return null;
+ }
+ }
+ }
+
+ public List ReadExchangeRate(List currencyCodeList = null, DateTime date = default(DateTime))
+ {
+ //throw new NotImplementedException("Complete, but untested");
+
+ var returnList = new List();
+
+ string sql = @"
+ SELECT AccountExchangeRateID, ExchangeRateSource, CurrencyCode, CurrencyUnitsPerGBP, StartDate, EndDate
+ FROM tblAccountExchangeRate
+ WHERE 1=1 ";
+
+ if (date != default(DateTime))
+ {
+ sql = sql + " AND (@dateTime >= StartDate AND @dateTime < endDate) ";
+ }
+
+ var sqlWhere = new Data.Database.SqlWhereBuilder();
+
+ // create string list
+ List stringList = new List();
+ if (currencyCodeList != null)
+ {
+ stringList = currencyCodeList.ConvertAll(f => f.ToString());
+ if (stringList.Any())
+ {
+ sqlWhere.In("CurrencyCode", stringList, "AND");
+ }
+ }
+
+ sql = sql + sqlWhere.SqlWhereString;
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ if (date != default(DateTime))
+ {
+ cmd.Parameters.AddWithValue("@dateTime", date);
+ }
+ if (stringList.Any())
+ {
+ sqlWhere.AddParametersToSqlCommand(cmd);
+ }
+
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ int id = reader.GetInt32(0);
+ int exchangeRateSource = reader.GetInt32(1);
+ string currencyCodeString = reader.GetString(2);
+ decimal currencyUnitsPerGBP = reader.GetDecimal(3);
+ DateTime startDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
+ DateTime endDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
+
+
+ // convert string to enum
+ if (Enum.TryParse(currencyCodeString, out Model.Account.CurrencyCode currencyCode) == false)
+ {
+ throw new Exception("Failed converting database string to enum");
+ }
+
+ var item = new Model.Account.CurrencyExchangeRate(
+ currencyCode
+ , exchangeRateSource
+ , currencyUnitsPerGBP
+ , startDate
+ , endDate
+ );
+
+ returnList.Add(item);
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public List ReadExchangeRateLatest(List currencyCodeList = null)
+ {
+ var returnList = new List();
+
+ string sql = @"
+ SELECT t1.AccountExchangeRateID, t1.ExchangeRateSource, t1.CurrencyCode, t1.CurrencyUnitsPerGBP, t1.StartDate, t1.EndDate,
+ t2.maxdate
+ FROM tblAccountExchangeRate AS t1
+ INNER JOIN
+ (SELECT max(StartDate) AS maxdate,
+ CurrencyCode
+ FROM tblAccountExchangeRate
+ GROUP BY CurrencyCode
+ ";
+
+ // add any filters
+ var sqlWhere = new Data.Database.SqlWhereBuilder();
+ var codeStringList = new List();
+ if (currencyCodeList != null && currencyCodeList.Any() == true)
+ {
+ // convert to string list
+ foreach (var currencyCode in currencyCodeList)
+ {
+ codeStringList.Add(currencyCode.ToString());
+ }
+
+ // add to where statement
+ sqlWhere.In("CurrencyCode", codeStringList, "HAVING");
+ sql = sql + sqlWhere.SqlWhereString;
+ }
+
+ sql = sql + @" ) AS t2
+ ON t1.CurrencyCode = t2.CurrencyCode
+ AND t1.StartDate = t2.maxdate
+ ORDER BY t1.CurrencyCode;";
+
+ //query db
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ if (codeStringList.Any())
+ {
+ sqlWhere.AddParametersToSqlCommand(cmd);
+ }
+
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ int id = reader.GetInt32(0);
+ int exchangeRateSource = reader.GetInt32(1);
+ string currencyCodeString = reader.GetString(2);
+ decimal currencyUnitsPerGBP = reader.GetDecimal(3);
+ DateTime startDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
+ DateTime endDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
+
+
+ // convert string to enum
+ if (Enum.TryParse(currencyCodeString, out Model.Account.CurrencyCode currencyCode) == false)
+ {
+ throw new Exception("Failed converting database string to enum");
+ }
+
+ var item = new Model.Account.CurrencyExchangeRate(
+ currencyCode
+ , exchangeRateSource
+ , currencyUnitsPerGBP
+ , startDate
+ , endDate
+ );
+
+ returnList.Add(item);
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public int InsertExchangeRate(int exchangeRateSource, Model.Account.CurrencyCode currencyCode,
+ decimal currencyUnitsPerGbp, DateTime periodStartUtc, DateTime periodEnd, bool checkOverride = false)
+ {
+ // checks
+ if (periodStartUtc.Kind != DateTimeKind.Utc || periodEnd.Kind != DateTimeKind.Utc)
+ {
+ throw new FormatException("Currency date time kind must be UTC");
+ }
+
+ currencyUnitsPerGbp = decimal.Round(currencyUnitsPerGbp, 4);
+
+ // CHECKS
+ if (periodEnd <= periodStartUtc)
+ {
+ throw new Exception("Invalid date period.");
+ }
+
+ if (checkOverride == false && (periodEnd - periodStartUtc).Days > 31)
+ {
+ throw new Exception("Date period is greater than 31 days.");
+ }
+
+ string sql = @"
+ INSERT INTO tblAccountExchangeRate (ExchangeRateSource, CurrencyCode, CurrencyUnitsPerGBP, StartDate, EndDate)
+ OUTPUT INSERTED.AccountExchangeRateID
+ VALUES (@exchangeRateSource, @currencyCode, @currencyUnitsPerGbp, @periodStart, @periodEnd);
+ ";
+
+ // make the insert
+ DateTime? periodEndLast = null;
+ int recordId = 0;
+
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@exchangeRateSource", exchangeRateSource);
+ cmd.Parameters.AddWithValue("@currencyCode", currencyCode.ToString());
+ cmd.Parameters.AddWithValue("@currencyUnitsPerGbp", currencyUnitsPerGbp);
+ cmd.Parameters.AddWithValue("@periodStart", periodStartUtc);
+ cmd.Parameters.AddWithValue("@periodEnd", periodEnd);
+
+ recordId = (int)cmd.ExecuteScalar();
+
+ if (recordId < 1)
+ {
+ throw new Exception("Error inserting record, did not retrive new record ID.");
+ }
+ }
+
+ return recordId;
+ }
+
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/ExportInvoiceRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/ExportInvoiceRepository.cs
new file mode 100644
index 0000000..b8846d0
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/ExportInvoiceRepository.cs
@@ -0,0 +1,451 @@
+using bnhtrade.Core.Data.Database.Repository.Interface;
+using bnhtrade.Core.Logic.Validate;
+using Microsoft.Data.SqlClient;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Transactions;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ internal class ExportInvoiceRepository : _Base, IExportInvoiceRepository
+ {
+ public ExportInvoiceRepository(IDbConnection connection, IDbTransaction transaction) : base(connection, transaction)
+ {
+ }
+
+ //
+ // invoice Insert methods
+ //
+
+ ///
+ /// Don't call this directly, use the logic layer instead (for validation and other checks).
+ ///
+ /// list of sales invoices to insert
+ /// dectionary, key= invoice id, value= new invoice
+ public Dictionary InsertSalesInvoices(IEnumerable invoiceList)
+ {
+ var result = InsertBaseExecute(invoiceList);
+ var returnList = new Dictionary();
+ foreach (var item in result)
+ {
+ returnList.Add(item.Key, (Model.Account.SalesInvoice)item.Value);
+ }
+ return returnList;
+ }
+
+ private Dictionary InsertBaseExecute(IEnumerable invoiceList)
+ {
+ if (invoiceList == null)
+ {
+ throw new ArgumentException("Invoice list is null");
+ }
+
+ var returnList = new Dictionary();
+ int invoiceCount = invoiceList.Count();
+
+ // make the inserts
+ foreach (var invoice in invoiceList)
+ {
+ int? invoiceId = null;
+ string sql = @"
+ INSERT INTO tblExportAccountInvoice (
+ ExportAccountInvoiceTypeID
+ ,Contact
+ ,InvoiceDate
+ ,InvoiceDueDate
+ ,InvoiceNumber
+ ,Reference
+ ,CurrencyCode
+ ,LineUnitAmountIsTaxExclusive
+ ,InvoiceAmount
+ ,IsComplete
+ )
+ OUTPUT INSERTED.ExportAccountInvoiceID
+ VALUES (
+ @invoiceTypeId
+ ,@contact
+ ,@invoiceDate
+ ,@invoiceDueDate
+ ,@invoiceNumber
+ ,@reference
+ ,@currencyCode
+ ,@lineUnitAmountIsTaxExclusive
+ ,@invoiceAmount
+ ,@markComplete
+ );";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@invoiceTypeId", (int)invoice.InvoiceType);
+ cmd.Parameters.AddWithValue("@contact", invoice.ContactName);
+ cmd.Parameters.AddWithValue("@invoiceDate", invoice.InvoiceDate);
+ cmd.Parameters.AddWithValue("@invoiceDueDate", invoice.InvoiceDueDate);
+ cmd.Parameters.AddWithValue("@reference", invoice.InvoiceReference);
+ cmd.Parameters.AddWithValue("@currencyCode", invoice.InvoiceCurrencyCode.ToString());
+ cmd.Parameters.AddWithValue("@lineUnitAmountIsTaxExclusive", invoice.InvoiceLineUnitAmountIsTaxExclusive);
+ cmd.Parameters.AddWithValue("@markComplete", false);
+ cmd.Parameters.AddWithValue("@invoiceNumber", invoice.InvoiceNumber);
+ cmd.Parameters.AddWithValue("@invoiceAmount", invoice.InvoiceTotalAmount);
+
+ invoiceId = (int)cmd.ExecuteScalar();
+ }
+
+ foreach (var line in invoice.InvoiceLineList)
+ {
+ string lineSql = @"
+ INSERT INTO tblExportAccountInvoiceLine (
+ ExportAccountInvoiceID
+ ,AccountInvoiceLineItemID
+ ,NetAmount
+ ,AccountChartOfID
+ ,TaxAmount
+ ,AccountTaxCodeID
+ )
+ OUTPUT INSERTED.ExportAccountInvoiceLineID
+ VALUES (
+ @invoiceId
+ ,(
+ SELECT AccountInvoiceLineItemID
+ FROM tblAccountInvoiceLineItem
+ WHERE ItemCode = @itemCode
+ )
+ ,@netAmount
+ ,(
+ SELECT AccountChartOfID
+ FROM tblAccountChartOf
+ WHERE AccountCode = @accountCode
+ )
+ ,@taxAmount
+ ,(
+ SELECT AccountTaxCodeID
+ FROM tblAccountTaxCode
+ WHERE TaxCode = @taxCode
+ )
+ );";
+
+ // insert record
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand) // Use _connection.CreateCommand()
+ {
+ cmd.CommandText = lineSql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@invoiceID", invoiceId);
+ cmd.Parameters.AddWithValue("@itemCode", line.ItemCode);
+ cmd.Parameters.AddWithValue("@netAmount", line.UnitAmount);
+ cmd.Parameters.AddWithValue("@accountCode", (int)line.Account.AccountCode);
+ cmd.Parameters.AddWithValue("@taxAmount", line.TaxAmountTotal);
+ cmd.Parameters.AddWithValue("@taxCode", line.TaxCode.TaxCode);
+
+ int lineId = (int)cmd.ExecuteScalar();
+ }
+ }
+ returnList.Add(invoiceId.Value, invoice);
+ }
+
+ if (returnList.Count != invoiceCount)
+ {
+ throw new Exception("Not all invoices were inserted into the export table. Expected: " + invoiceCount + ", Actual: " + returnList.Count);
+ }
+ else
+ {
+ return returnList;
+ }
+ }
+
+ //
+ // invoice read methods
+ //
+
+ ///
+ /// Returns list of invoice numbers that have not yet been exported (i.e. IsComplete=True)
+ ///
+ /// Sales or Purchase
+ /// Dictionary where key=ExportAccountInvoiceID, value=InvoiceNumber
+ public Dictionary GetNewInvoiceNumbers(Model.Account.InvoiceType invoiceType)
+ {
+ var returnList = new Dictionary();
+
+ string sql = @"
+ SELECT tblExportAccountInvoice.ExportAccountInvoiceID, [InvoiceNumber]
+ FROM tblExportAccountInvoice
+ WHERE (tblExportAccountInvoice.IsComplete = 0)
+ AND (tblExportAccountInvoice.ExportAccountInvoiceTypeID = @invoiceType);";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@invoiceType", (int)invoiceType);
+
+ using (SqlDataReader reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ returnList.Add(reader.GetInt32(0), reader.GetString(1));
+ }
+ }
+ }
+ return returnList;
+ }
+
+ ///
+ /// Get list of invoices by invoice id
+ ///
+ /// list of invoice ids
+ /// dictionary key=id, value=invoice-model
+ public Dictionary GetSalesInvoiceById(IEnumerable idList)
+ {
+ var returnList = new Dictionary();
+
+ if (idList.Any() == false)
+ {
+ return returnList;
+ }
+
+ // get the account and tax code objects
+ var taxcode = new Data.Database.Account.ReadTaxCode().GetAllActive();
+ var account = new Data.Database.Account.ReadAccountCode().All();
+
+ // build sql string
+ string sql = @"
+ SELECT tblExportAccountInvoice.ExportAccountInvoiceID
+ , tblExportAccountInvoice.ExportAccountInvoiceTypeID
+ , tblExportAccountInvoice.Contact
+ , tblExportAccountInvoice.InvoiceNumber
+ , tblExportAccountInvoice.InvoiceDate
+ , tblExportAccountInvoice.InvoiceDueDate
+ , tblExportAccountInvoice.Reference
+ , tblExportAccountInvoice.CurrencyCode
+ , tblExportAccountInvoice.InvoiceAmount
+ , tblExportAccountInvoice.IsComplete
+ , tblExportAccountInvoiceLine.ExportAccountInvoiceLineID
+ , tblAccountInvoiceLineItem.ItemName
+ , tblExportAccountInvoiceLine.AccountChartOfID
+ , tblExportAccountInvoiceLine.NetAmount
+ , tblExportAccountInvoiceLine.AccountTaxCodeID
+ , tblExportAccountInvoiceLine.TaxAmount
+ , tblExportAccountInvoice.LineUnitAmountIsTaxExclusive
+ FROM tblExportAccountInvoice
+ INNER JOIN
+ tblExportAccountInvoiceLine
+ ON tblExportAccountInvoice.ExportAccountInvoiceID = tblExportAccountInvoiceLine.ExportAccountInvoiceID
+ INNER JOIN
+ tblAccountInvoiceLineItem
+ ON tblExportAccountInvoiceLine.AccountInvoiceLineItemID = tblAccountInvoiceLineItem.AccountInvoiceLineItemID
+ ";
+
+ var sqlWhere = new Data.Database.SqlWhereBuilder();
+ sqlWhere.In("tblExportAccountInvoice.ExportAccountInvoiceID", idList, "WHERE");
+
+ sql = sql + sqlWhere.SqlWhereString + " ORDER BY tblExportAccountInvoice.ExportAccountInvoiceID, tblExportAccountInvoiceLine.ExportAccountInvoiceLineID; ";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ sqlWhere.AddParametersToSqlCommand(cmd);
+
+ using (SqlDataReader reader = cmd.ExecuteReader())
+ {
+ if (reader.HasRows == false)
+ {
+ return returnList;
+ }
+
+ int? invoiceId = null;
+ int? previousInvoiceId = null;
+ Model.Account.SalesInvoice invoice = null;
+
+ while (reader.Read())
+ {
+ invoiceId = reader.GetInt32(0);
+
+ // test for first/next invoice
+ if (invoice == null || previousInvoiceId.Value != invoiceId.Value)
+ {
+ // if next invoice, add previous to return list
+ if (previousInvoiceId.HasValue)
+ {
+ // invoice complete, add to return list
+ returnList.Add(previousInvoiceId.Value, invoice);
+ }
+
+ // add header info to new invoice
+ invoice = new Model.Account.SalesInvoice(reader.GetBoolean(16));
+ int invoiceType = reader.GetInt32(1);
+ invoice.ContactName = reader.GetString(2);
+ invoice.InvoiceNumber = reader.GetString(3);
+ invoice.InvoiceDate = reader.GetDateTime(4);
+ invoice.InvoiceDueDate = reader.GetDateTime(5);
+ if (!reader.IsDBNull(6)) { invoice.InvoiceReference = reader.GetString(6); }
+ invoice.InvoiceCurrencyCode = Enum.Parse(reader.GetString(7));
+ if (!reader.IsDBNull(8)) { invoice.InvoiceTotalAmount = reader.GetDecimal(8); }
+ bool isComplete = reader.GetBoolean(9);
+
+ // set credit note
+ if (invoice.InvoiceTotalAmount < 0)
+ {
+ invoice.IsCreditNote = true;
+ }
+ }
+
+ // add line info
+ var invoiceLine = new Model.Account.SalesInvoice.InvoiceLine(invoice);
+ int lineId = reader.GetInt32(10);
+ invoiceLine.ItemCode = reader.GetString(11);
+ invoiceLine.Account = account[Convert.ToUInt32(reader.GetInt32(12))];
+ invoiceLine.UnitAmount = reader.GetDecimal(13);
+ invoiceLine.Quantity = 1;
+ invoiceLine.TaxCode = taxcode[reader.GetByte(14)];
+ invoiceLine.SetTaxAdjustmentByTaxTotal(reader.GetDecimal(15));
+
+ invoice.InvoiceLineList.Add(invoiceLine);
+ previousInvoiceId = invoiceId.Value;
+ }
+
+ // complete final invoice and add to list
+ returnList.Add(invoiceId.Value, invoice);
+ }
+ }
+ return returnList;
+ }
+
+ //
+ // invoice update methods
+ //
+
+ ///
+ /// Update the 'IsComplete' field by invoice id
+ ///
+ /// key=ExportAccountInvoiceTypeID, value=IsComplete
+ /// Number of row effected
+ public int SetInvoiceIsCompleteValue(Dictionary updateDictionary)
+ {
+ int returnCount = 0;
+
+ foreach (var item in updateDictionary)
+ {
+ string sql = @"
+ UPDATE
+ tblExportAccountInvoice
+ SET
+ IsComplete = @isComplete
+ WHERE
+ ExportAccountInvoiceID = @id
+ ";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@id", item.Key);
+ cmd.Parameters.AddWithValue("@isComplete", item.Value);
+
+ returnCount = returnCount + cmd.ExecuteNonQuery();
+ }
+ }
+ return returnCount;
+ }
+
+ //
+ // Invoice Delete Methods
+ //
+
+ public int DeleteInvoiceLine(int invoiceLineId)
+ {
+ // only being able to delete one line at a time is a design/safety decision
+ // otherwise, delete whole invoice
+ if (invoiceLineId <= 0)
+ {
+ throw new ArgumentException("InvoiceLineId must be greater than zero.");
+ }
+ Core.Data.Database.SqlWhereBuilder sqlWhereBuilder = new Core.Data.Database.SqlWhereBuilder();
+ sqlWhereBuilder.In("ExportAccountInvoiceLineID", new List { invoiceLineId });
+ return DeleteInvoiceExecuteInvoiceLine(sqlWhereBuilder);
+ }
+
+ public int DeleteInvoice(IEnumerable invoiceIdList)
+ {
+ if (invoiceIdList == null || invoiceIdList.Count() == 0)
+ {
+ throw new ArgumentException("InvoiceIdList is empty, nothing to delete.");
+ }
+
+ int invoiceToDelete = invoiceIdList.Distinct().Count();
+ int invoiceEffected = 0;
+
+ // delete lines first
+ Core.Data.Database.SqlWhereBuilder sqlWhereBuilder = new Core.Data.Database.SqlWhereBuilder();
+ sqlWhereBuilder.In("ExportAccountInvoiceID", invoiceIdList);
+ int lineCount = DeleteInvoiceExecuteInvoiceLine(sqlWhereBuilder);
+
+ // then delete invoice
+ sqlWhereBuilder = new Core.Data.Database.SqlWhereBuilder();
+ sqlWhereBuilder.In("ExportAccountInvoiceID", invoiceIdList);
+ invoiceEffected = DeleteInvoiceExecuteInvoice(sqlWhereBuilder);
+
+ if (invoiceEffected == invoiceToDelete)
+ {
+ return invoiceEffected;
+ }
+ else
+ {
+ throw new Exception("Error: "
+ + invoiceToDelete + " number invoices requested for deletion, "
+ + invoiceEffected + " number invoices effected. Changes rolled back.");
+ }
+ }
+
+ ///
+ /// Helper method Only intended for use with ExecuteInvoice() or ExecuteInvoiceLine()
+ ///
+ /// the full sql statement
+ /// instance of the sql where builder helper
+ /// Number of row effected (deleted)
+ private int DeleteInvoiceExecuteHelper(string sql, Core.Data.Database.SqlWhereBuilder sqlWhereBuilder)
+ {
+ // Only intended for ExecuteInvoice() or ExecuteInvoiceLine()
+
+ // important checks
+ if (sqlWhereBuilder.IsSetSqlWhereString == false)
+ {
+ throw new ArgumentException("SqlWhereBuilder is not set, set the SqlWhereBuilder before calling this method.");
+ }
+ if (sqlWhereBuilder.ParameterListCount == 0)
+ {
+ throw new Exception("Parameter list count is zero, this could delete all records in table, operation cancelled");
+ }
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction; // Assign the shared transaction
+ sqlWhereBuilder.AddParametersToSqlCommand(cmd);
+
+ return cmd.ExecuteNonQuery();
+ }
+ }
+
+ private int DeleteInvoiceExecuteInvoice(Core.Data.Database.SqlWhereBuilder sqlWhereBuilder)
+ {
+ string sql = "DELETE FROM tblExportAccountInvoice WHERE " + sqlWhereBuilder.SqlWhereString;
+ return DeleteInvoiceExecuteHelper(sql, sqlWhereBuilder);
+ }
+
+ private int DeleteInvoiceExecuteInvoiceLine(Core.Data.Database.SqlWhereBuilder sqlWhereBuilder)
+ {
+ string sql = "DELETE FROM tblExportAccountInvoiceLine WHERE " + sqlWhereBuilder.SqlWhereString;
+ return DeleteInvoiceExecuteHelper(sql, sqlWhereBuilder);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/ImportAmazonRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/ImportAmazonRepository.cs
new file mode 100644
index 0000000..e122a63
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/ImportAmazonRepository.cs
@@ -0,0 +1,713 @@
+using bnhtrade.Core.Data.Database._BoilerPlate;
+using bnhtrade.Core.Data.Database.Repository.Interface;
+using bnhtrade.Core.Model.Amazon;
+using Microsoft.Data.SqlClient;
+using Microsoft.VisualBasic.Logging;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Transactions;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ internal class ImportAmazonRepository : _Base, IImportAmazonRepository
+ {
+ Logic.Log.LogEvent _log = new Logic.Log.LogEvent();
+
+ public ImportAmazonRepository(IDbConnection connection, IDbTransaction transaction) : base(connection, transaction)
+ {
+ }
+
+ //
+ // Read Amazon Settlement Header Information
+ //
+
+ public List ReadAmazonSettlementHeaderInfoBySettlementId(List settlementIdList)
+ {
+ if (settlementIdList == null || !settlementIdList.Any())
+ { return new List(); }
+
+ return ReadAmazonSettlementHeaders(settlementIdList);
+ }
+
+ public List ReadAmazonSettlementHeaderInfoBySpapiReportId(List spapiReportIdList)
+ {
+ if (spapiReportIdList == null || !spapiReportIdList.Any())
+ { return new List(); }
+
+ return ReadAmazonSettlementHeaders(null, spapiReportIdList);
+ }
+
+ private List ReadAmazonSettlementHeaders(
+ List settlementIdList = null, List spapiReportIdList = null, bool filterOutIsProcessed = false,
+ bool DescendingOrder = false, int? returnTop = null)
+ {
+ var returnHeaderList = new List();
+ Dictionary dicTablePkBySettlementId = new Dictionary();
+
+
+ // build the sql string
+ string sqlString = "SELECT ";
+
+ if (returnTop != null)
+ {
+ sqlString = sqlString + "TOP " + returnTop.Value + " ";
+ }
+
+ sqlString = sqlString + @"
+ ImportAmazonSettlementReportID
+ ,[marketplace-name]
+ ,[settlement-id]
+ ,[settlement-start-date]
+ ,[settlement-end-date]
+ ,[deposit-date]
+ ,[total-amount]
+ ,currency
+ ,IsProcessed
+ ,SpapiReportId
+ FROM tblImportAmazonSettlementReport
+ WHERE 1 = 1";
+
+ if (filterOutIsProcessed)
+ {
+ sqlString = sqlString + @"
+ AND IsProcessed = 0";
+ }
+
+ // build dictionary of parameter and values for settlementid
+ var dicSettlementIdByParameterString = new Dictionary();
+ if (settlementIdList != null)
+ {
+ int count = 0;
+ foreach (string item in settlementIdList)
+ {
+ if (!string.IsNullOrWhiteSpace(item))
+ {
+ count = count + 1;
+ string parameterString = "@settlementId" + count;
+ dicSettlementIdByParameterString.Add(parameterString, item);
+ }
+ }
+ }
+
+ if (dicSettlementIdByParameterString.Any())
+ {
+ int count = 0;
+ foreach (var item in dicSettlementIdByParameterString)
+ {
+ count = count + 1;
+ if (count == 1)
+ {
+ sqlString = sqlString + @"
+ AND ( [settlement-id] = " + item.Key;
+ }
+ else
+ {
+ sqlString = sqlString + @"
+ OR [settlement-id] = " + item.Key;
+ }
+ }
+ sqlString = sqlString + " )";
+ }
+
+ // build dictionary of parameter and values for SP-API Report Id
+ var dicSpapiReportIdByParameterString = new Dictionary();
+ if (spapiReportIdList != null && spapiReportIdList.Any())
+ {
+ int count = 0;
+ foreach (string item in spapiReportIdList)
+ {
+ if (!string.IsNullOrWhiteSpace(item))
+ {
+ count = count + 1;
+ string parameterString = "@SpapiReportId" + count;
+ dicSpapiReportIdByParameterString.Add(parameterString, item);
+ }
+ }
+ }
+
+ if (dicSpapiReportIdByParameterString.Any())
+ {
+ int count = 0;
+ foreach (var item in dicSpapiReportIdByParameterString)
+ {
+ count = count + 1;
+ if (count == 1)
+ {
+ sqlString = sqlString + @"
+ AND ( SpapiReportId = " + item.Key;
+ }
+ else
+ {
+ sqlString = sqlString + @"
+ OR SpapiReportId = " + item.Key;
+ }
+ }
+ sqlString = sqlString + " )";
+ }
+
+
+ sqlString = sqlString + @"
+ ORDER BY [settlement-start-date] ";
+ if (DescendingOrder) { sqlString = sqlString + " DESC"; }
+
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sqlString;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ if (dicSettlementIdByParameterString.Any())
+ {
+ foreach (var item in dicSettlementIdByParameterString)
+ {
+ cmd.Parameters.AddWithValue(item.Key, item.Value);
+ }
+ }
+
+ if (dicSpapiReportIdByParameterString.Any())
+ {
+ foreach (var item in dicSpapiReportIdByParameterString)
+ {
+ cmd.Parameters.AddWithValue(item.Key, item.Value);
+ }
+ }
+
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ var header = new Model.Import.AmazonSettlementHeader();
+
+ int tablePk = reader.GetInt32(0);
+ if (!reader.IsDBNull(1)) { header.MarketPlace = MarketPlaceEnumExtensions.FromMarketplaceUrl(reader.GetString(1)); }
+ header.SettlementId = reader.GetString(2);
+ header.StartDate = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc);
+ header.EndDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
+ header.DepositDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
+ header.TotalAmount = reader.GetDecimal(6);
+ header.CurrencyCode = reader.GetString(7);
+ header.IsProcessed = reader.GetBoolean(8);
+ if (!reader.IsDBNull(9)) { header.SpapiReportId = reader.GetString(9); }
+
+ // update dictionary
+ if (!dicTablePkBySettlementId.ContainsKey(header.SettlementId))
+ {
+ dicTablePkBySettlementId.Add(header.SettlementId, tablePk);
+ }
+
+ // add header to list
+ returnHeaderList.Add(header);
+ }
+ }
+ }
+ return returnHeaderList;
+ }
+
+ //
+ // Read Amazon Settlement Report
+ //
+
+ ///
+ /// Gets Amazon settlement report information from the database.
+ ///
+ /// Dictionary where key=id and value=settlement
+ public Dictionary ReadAmazonSettlements(
+ List settlementIdList = null, List marketPlaceNameList = null, bool? isProcessed = null,
+ bool descendingOrder = false, int? returnTop = null )
+ {
+ var returnList = new Dictionary();
+ var whereBuilder = new Data.Database.SqlWhereBuilder();
+
+ // build the sql string
+ string sqlString = "SELECT ";
+
+ if (returnTop != null)
+ {
+ sqlString = sqlString + "TOP " + returnTop.Value + " ";
+ }
+
+ sqlString = sqlString + @"
+ tblImportAmazonSettlementReport.ImportAmazonSettlementReportID,
+ tblImportAmazonSettlementReport.[marketplace-name],
+ tblImportAmazonSettlementReport.[settlement-id],
+ tblImportAmazonSettlementReport.[settlement-start-date],
+ tblImportAmazonSettlementReport.[settlement-end-date],
+ tblImportAmazonSettlementReport.[deposit-date],
+ tblImportAmazonSettlementReport.[total-amount],
+ tblImportAmazonSettlementReport.currency,
+ tblImportAmazonSettlementReport.IsProcessed,
+ tblImportAmazonSettlementReport.SpapiReportId,
+ tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportLineID,
+ tblImportAmazonSettlementReportLine.[transaction-type],
+ tblImportAmazonSettlementReportLine.[order-id],
+ tblImportAmazonSettlementReportLine.[merchant-order-id],
+ tblImportAmazonSettlementReportLine.[adjustment-id],
+ tblImportAmazonSettlementReportLine.[shipment-id],
+ tblImportAmazonSettlementReportLine.[marketplace-name] AS Expr1,
+ tblImportAmazonSettlementReportLine.[amount-type],
+ tblImportAmazonSettlementReportLine.[amount-description],
+ tblImportAmazonSettlementReportLine.amount,
+ tblImportAmazonSettlementReportLine.currency,
+ tblImportAmazonSettlementReportLine.[fulfillment-id],
+ tblImportAmazonSettlementReportLine.[posted-date-time],
+ tblImportAmazonSettlementReportLine.[order-item-code],
+ tblImportAmazonSettlementReportLine.[merchant-order-item-id],
+ tblImportAmazonSettlementReportLine.[merchant-adjustment-item-id],
+ tblImportAmazonSettlementReportLine.sku,
+ tblImportAmazonSettlementReportLine.[quantity-purchased],
+ tblImportAmazonSettlementReportLine.[promotion-id],
+ tblImportAmazonSettlementReportLine.IsProcessed,
+ tblImportAmazonSettlementReportLine.ExportAccountInvoiceLineID
+ FROM tblImportAmazonSettlementReport
+ INNER JOIN
+ tblImportAmazonSettlementReportLine
+ ON tblImportAmazonSettlementReport.ImportAmazonSettlementReportID = tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportID
+ WHERE 1 = 1 ";
+
+ if (isProcessed != null)
+ {
+ if (isProcessed.Value == true)
+ {
+ sqlString = sqlString + @"
+ AND tblImportAmazonSettlementReport.IsProcessed = 1";
+ }
+ else
+ {
+ sqlString = sqlString + @"
+ AND tblImportAmazonSettlementReport.IsProcessed = 0";
+ }
+ }
+
+ if (settlementIdList != null && settlementIdList.Any() == true)
+ {
+ whereBuilder.In("tblImportAmazonSettlementReport.ImportAmazonSettlementReportID", settlementIdList, "AND");
+ }
+
+ if (marketPlaceNameList != null && marketPlaceNameList.Any() == true)
+ {
+ whereBuilder.In("tblImportAmazonSettlementReport.[marketplace-name]", marketPlaceNameList, "AND");
+ }
+
+ sqlString = sqlString + whereBuilder.SqlWhereString;
+
+ // add the order by clause(s)
+ sqlString = sqlString + @"
+ ORDER BY tblImportAmazonSettlementReport.[marketplace-name] ASC, tblImportAmazonSettlementReport.[settlement-start-date] ";
+ if (descendingOrder) { sqlString = sqlString + " DESC"; }
+ else { sqlString = sqlString + " ASC"; }
+ sqlString = sqlString + ", tblImportAmazonSettlementReport.ImportAmazonSettlementReportID ASC, tblImportAmazonSettlementReportLine.[posted-date-time] ASC, "
+ + "tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportLineID ASC;";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sqlString;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ whereBuilder.AddParametersToSqlCommand(cmd);
+
+ using (var reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ int tableId = reader.GetInt32(0);
+
+ if (returnList.ContainsKey(tableId) == false)
+ {
+ var settlement = new Model.Import.AmazonSettlement();
+
+ if (!reader.IsDBNull(1)) { settlement.MarketPlace = MarketPlaceEnumExtensions.FromMarketplaceUrl(reader.GetString(1)); }
+ settlement.SettlementId = reader.GetString(2);
+ settlement.StartDate = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc);
+ settlement.EndDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc);
+ settlement.DepositDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
+ settlement.TotalAmount = reader.GetDecimal(6);
+ settlement.CurrencyCode = reader.GetString(7);
+ settlement.IsProcessed = reader.GetBoolean(8);
+ if (!reader.IsDBNull(9)) { settlement.SpapiReportId = reader.GetString(9); }
+
+ returnList.Add(tableId, settlement);
+ }
+
+ // add lines to settlement
+ var line = new Model.Import.AmazonSettlement.SettlementLine();
+
+ line.TransactionType = reader.GetString(11);
+ if (!reader.IsDBNull(12)) { line.OrderId = reader.GetString(12); }
+ if (!reader.IsDBNull(13)) { line.MerchantOrderId = reader.GetString(13); }
+ if (!reader.IsDBNull(14)) { line.AdjustmentId = reader.GetString(14); }
+ if (!reader.IsDBNull(15)) { line.ShipmentId = reader.GetString(15); }
+ if (!reader.IsDBNull(16)) { line.MarketPlaceName = reader.GetString(16); }
+ line.AmountType = reader.GetString(17);
+ line.AmountDescription = reader.GetString(18);
+ line.Amount = reader.GetDecimal(19);
+ line.CurrenyCode = reader.GetString(20);
+ if (!reader.IsDBNull(21)) { line.FulfillmentId = reader.GetString(21); }
+ line.PostDateTime = DateTime.SpecifyKind(reader.GetDateTime(22), DateTimeKind.Utc);
+ if (!reader.IsDBNull(23)) { line.OrderItemCode = reader.GetString(23); }
+ if (!reader.IsDBNull(24)) { line.MerchantOrderItemId = reader.GetString(24); }
+ if (!reader.IsDBNull(25)) { line.MerchantAdjustmentItemId = reader.GetString(25); }
+ if (!reader.IsDBNull(26)) { line.Sku = reader.GetString(26); }
+ if (!reader.IsDBNull(27)) { line.QuantityPurchased = reader.GetInt32(27); }
+ if (!reader.IsDBNull(28)) { line.PromotionId = reader.GetString(28); }
+ line.IsProcessed = reader.GetBoolean(29);
+ if (!reader.IsDBNull(30)) { line.ExportAccountInvoiceLineId = reader.GetInt32(30); }
+
+ returnList[tableId].SettlementLineList.Add(line);
+ }
+ return returnList;
+ }
+ }
+ }
+
+ //
+ // Update Amazon Settlement Report
+ //
+
+ ///
+ /// Set the IsProcessed flag to true or false for the specified settlement Ids.
+ ///
+ /// List of settlement id (not table id)
+ /// value to set the isProcessed to
+ /// Number of rows effected
+ public int SetAmazonSettlementIsProcessed(List settlementIdList, bool isProcessed)
+ {
+ if (settlementIdList == null || !settlementIdList.Any())
+ {
+ throw new Exception("Settlement ID list is empty.");
+ }
+
+ string sqlString = @"
+ UPDATE tblImportAmazonSettlementReport ";
+
+ sqlString = sqlString + @"
+ SET IsProcessed = " + (isProcessed ? "1" : "0");
+
+ var whereBuilder = new Data.Database.SqlWhereBuilder();
+ whereBuilder.In("tblImportAmazonSettlementReport.[settlement-id]", settlementIdList, "WHERE");
+
+ sqlString = sqlString + whereBuilder.SqlWhereString;
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sqlString;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ whereBuilder.AddParametersToSqlCommand(cmd);
+
+ return cmd.ExecuteNonQuery();
+ }
+ }
+
+ ///
+ /// Takes a Settlement Report flat file from Amazon and imports it into the database.
+ ///
+ /// path to the Amazon report flat file
+ /// The unique Amazon SP-API report id (not settlement id)
+ ///
+ public bool CreateAmazonSettlements(string filePath, string reportId)
+ {
+ int settlementReportId = 0;
+ string settlementRef = "";
+ bool marketPlaceUpdated = false;
+ decimal settlementAmount = 0m;
+ int lineNumber = 2;
+ int lineSkip = 0;
+
+ using (var reader = new StreamReader(filePath))
+ {
+ //read file one line at a time and insert data into table if required
+
+ // read header and retrive information
+ string headerRow = reader.ReadLine();
+ string[] headers = headerRow.Split('\t');
+
+ int columnCount = headers.Length;
+
+ int indexSettlementId = Array.IndexOf(headers, "settlement-id");
+ int indexSettlementStartDate = Array.IndexOf(headers, "settlement-start-date");
+ int indexSettlementEndDate = Array.IndexOf(headers, "settlement-end-date");
+ int indexDepositDate = Array.IndexOf(headers, "deposit-date");
+ int indexTotalAmount = Array.IndexOf(headers, "total-amount");
+ int indexCurrency = Array.IndexOf(headers, "currency");
+ int indexTransactionType = Array.IndexOf(headers, "transaction-type");
+ int indexOrderId = Array.IndexOf(headers, "order-id");
+ int indexMerchantOrderId = Array.IndexOf(headers, "merchant-order-id");
+ int indexAdjustmentId = Array.IndexOf(headers, "adjustment-id");
+ int indexShipmentId = Array.IndexOf(headers, "shipment-id");
+ int indexMarketplaceName = Array.IndexOf(headers, "marketplace-name");
+ int indexAmountType = Array.IndexOf(headers, "amount-type");
+ int indexAmountDescription = Array.IndexOf(headers, "amount-description");
+ int indexAmount = Array.IndexOf(headers, "amount");
+ int indexFulfillmentId = Array.IndexOf(headers, "fulfillment-id");
+ // int indexPostedDate = Array.IndexOf(headers, "posted-date");
+ int indexPostedDateTime = Array.IndexOf(headers, "posted-date-time");
+ int indexOrderItemCode = Array.IndexOf(headers, "order-item-code");
+ int indexMerchantOrderItemId = Array.IndexOf(headers, "merchant-order-item-id");
+ int indexMerchantAdjustmentItemId = Array.IndexOf(headers, "merchant-adjustment-item-id");
+ int indexSku = Array.IndexOf(headers, "sku");
+ int indexQuantityPurchased = Array.IndexOf(headers, "quantity-purchased");
+ int indexPromotionId = Array.IndexOf(headers, "promotion-id");
+
+ string currency = "";
+
+ string fileRow;
+ while ((fileRow = reader.ReadLine()) != null)
+ {
+ Console.Write("\rParsing record: " + lineNumber);
+ //split line into array
+ string[] items = fileRow.Split('\t');
+ if (items.Length != columnCount)
+ {
+ // skip line
+ lineSkip = lineSkip + 1;
+ _log.LogWarning(
+ "Line #" + lineNumber + " skipped due to no enough element in row.",
+ filePath
+ );
+ }
+ else if (lineNumber == 2)
+ {
+ // check if settlement has already been imported
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = "SELECT COUNT(*) FROM tblImportAmazonSettlementReport WHERE [settlement-id]=@settlementId;";
+ cmd.Transaction = _transaction as SqlTransaction;
+ cmd.Parameters.AddWithValue("@settlementId", items[indexSettlementId]);
+
+ int recordCount = (int)cmd.ExecuteScalar();
+ if (recordCount > 0)
+ {
+ SetSpapiReportId(items[indexSettlementId], reportId);
+ _log.LogInformation("Settlement report already imported, skipping...");
+ return true;
+ }
+ }
+ //set currencyId
+ //currencyId = GeneralQueries.GetCurrencyId(items[5]);
+
+ //set currency
+ currency = items[indexCurrency];
+ settlementAmount = decimal.Parse(items[indexTotalAmount].Replace(",", "."));
+
+ // insert
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.Transaction = _transaction as SqlTransaction;
+ cmd.CommandText = @"
+ INSERT INTO tblImportAmazonSettlementReport (
+ [settlement-id]
+ ,[settlement-start-date]
+ ,[settlement-end-date]
+ ,[deposit-date]
+ ,[total-amount]
+ ,[currency]
+ ,SpapiReportId
+ )
+ OUTPUT INSERTED.ImportAmazonSettlementReportID
+ VALUES (
+ @settlementId
+ ,@settlementStartDate
+ ,@settlementEndDate
+ ,@depositDate
+ ,@settlementotalAmounttId
+ ,@currency
+ ,@reportId
+ );";
+
+ // add parameters
+ if (indexSettlementId == -1 || items[indexSettlementId].Length == 0) { cmd.Parameters.AddWithValue("@settlementId", DBNull.Value); }
+ else
+ {
+ settlementRef = items[indexSettlementId];
+ cmd.Parameters.AddWithValue("@settlementId", settlementRef);
+ }
+
+ var parseDateTime = new Core.Logic.Utilities.DateTime();
+
+ if (indexSettlementStartDate == -1 || items[indexSettlementStartDate].Length == 0) { cmd.Parameters.AddWithValue("@settlementStartDate", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@settlementStartDate", parseDateTime.ParseIsoDateTimeString(items[indexSettlementStartDate])); }
+
+ if (indexSettlementEndDate == -1 || items[indexSettlementEndDate].Length == 0) { cmd.Parameters.AddWithValue("@settlementEndDate", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@settlementEndDate", parseDateTime.ParseIsoDateTimeString(items[indexSettlementEndDate])); }
+
+ if (indexDepositDate == -1 || items[indexDepositDate].Length == 0) { cmd.Parameters.AddWithValue("@depositDate", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@depositDate", parseDateTime.ParseIsoDateTimeString(items[indexDepositDate])); }
+
+ if (indexTotalAmount == -1 || items[indexTotalAmount].Length == 0) { cmd.Parameters.AddWithValue("@totalAmount", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@settlementotalAmounttId", settlementAmount); }
+
+ if (string.IsNullOrWhiteSpace(reportId)) { cmd.Parameters.AddWithValue("@reportId", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@reportId", reportId); }
+
+ cmd.Parameters.AddWithValue("@currency", currency);
+
+ //if (currencyId == -1) { sqlCommand.Parameters.AddWithValue("@currencyId", DBNull.Value); }
+ //else { sqlCommand.Parameters.AddWithValue("@currencyId", currencyId); }
+
+ //execute and retrive id
+ settlementReportId = (int)cmd.ExecuteScalar();
+
+ }
+ }
+ else
+ {
+ //update market place name in main table, if required
+ if (marketPlaceUpdated == false && settlementReportId > 0 && items[indexMarketplaceName].Length > 1)
+ {
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.Transaction = _transaction as SqlTransaction;
+ cmd.CommandText = @"
+ UPDATE tblImportAmazonSettlementReport
+ SET [marketplace-name]=@MarketplaceName
+ WHERE ImportAmazonSettlementReportID=@ImportAmazonSettlementReportID;";
+ cmd.Parameters.AddWithValue("@MarketplaceName", items[indexMarketplaceName]);
+ cmd.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
+
+ cmd.ExecuteNonQuery();
+ marketPlaceUpdated = true;
+ }
+ }
+
+ //insert report items
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.Transaction = _transaction as SqlTransaction;
+ cmd.CommandText =
+ "INSERT INTO tblImportAmazonSettlementReportLine ( " +
+ "ImportAmazonSettlementReportID, [transaction-type], [order-id], [merchant-order-id], [adjustment-id], [shipment-id], [marketplace-name], " +
+ "[amount-type], [amount-description], [currency], [amount], [fulfillment-id], [posted-date-time], [order-item-code], " +
+ "[merchant-order-item-id], [merchant-adjustment-item-id], [sku], [quantity-purchased], [promotion-id] ) " +
+ "VALUES ( " +
+ "@ImportAmazonSettlementReportID, @TransactionType, @orderRef, @merchantOrderRef, @AdjustmentRef, @ShipmentRef, @MarketplaceName, " +
+ "@AmountType, @AmountDescription, @currency, @Amount, @FulfillmentRef, @PostedDateTimeUTC, @OrderItemCode, " +
+ "@MerchantOrderItemRef, @MerchantAdjustmentItemRef, @SkuNumber, @QuantityPurchased, @PromotionRef );";
+
+ // add parameters
+ cmd.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
+
+ cmd.Parameters.AddWithValue("@currency", currency);
+
+ if (indexTransactionType == -1 || items[indexTransactionType].Length == 0) { cmd.Parameters.AddWithValue("@TransactionType", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@TransactionType", items[indexTransactionType]); }
+
+ if (indexOrderId == -1 || items[indexOrderId].Length == 0) { cmd.Parameters.AddWithValue("@orderRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@orderRef", items[indexOrderId]); }
+
+ if (indexMerchantOrderId == -1 || items[indexMerchantOrderId].Length == 0) { cmd.Parameters.AddWithValue("@merchantOrderRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@merchantOrderRef", items[indexMerchantOrderId]); }
+
+ if (indexAdjustmentId == -1 || items[indexAdjustmentId].Length == 0) { cmd.Parameters.AddWithValue("@AdjustmentRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@AdjustmentRef", items[indexAdjustmentId]); }
+
+ if (indexShipmentId == -1 || items[indexShipmentId].Length == 0) { cmd.Parameters.AddWithValue("@ShipmentRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@ShipmentRef", items[indexShipmentId]); }
+
+ if (indexMarketplaceName == -1 || items[indexMarketplaceName].Length == 0) { cmd.Parameters.AddWithValue("@MarketplaceName", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@MarketplaceName", items[indexMarketplaceName]); }
+
+ if (indexAmountType == -1 || items[indexAmountType].Length == 0) { cmd.Parameters.AddWithValue("@AmountType", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@AmountType", items[indexAmountType]); }
+
+ if (indexAmountDescription == -1 || items[indexAmountDescription].Length == 0) { cmd.Parameters.AddWithValue("@AmountDescription", DBNull.Value); }
+ else
+ {
+ string amountDescription = items[indexAmountDescription];
+ if (amountDescription.Length > 100) { amountDescription = amountDescription.Substring(0, 100); }
+ cmd.Parameters.AddWithValue("@AmountDescription", amountDescription);
+ }
+
+ if (indexAmount == -1 || items[indexAmount].Length == 0) { cmd.Parameters.AddWithValue("@Amount", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@Amount", decimal.Parse(items[indexAmount].Replace(",", "."))); }
+
+ if (indexFulfillmentId == -1 || items[indexFulfillmentId].Length == 0) { cmd.Parameters.AddWithValue("@FulfillmentRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@FulfillmentRef", items[indexFulfillmentId]); }
+
+ if (indexPostedDateTime == -1 || items[indexPostedDateTime].Length == 0) { cmd.Parameters.AddWithValue("@PostedDateTimeUTC", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@PostedDateTimeUTC", new Logic.Utilities.DateTime().ParseIsoDateTimeString(items[indexPostedDateTime])); }
+
+ if (indexOrderItemCode == -1 || items[indexOrderItemCode].Length == 0) { cmd.Parameters.AddWithValue("@OrderItemCode", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@OrderItemCode", long.Parse(items[indexOrderItemCode])); }
+
+ if (indexMerchantOrderItemId == -1 || items[indexMerchantOrderItemId].Length == 0) { cmd.Parameters.AddWithValue("@MerchantOrderItemRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@MerchantOrderItemRef", long.Parse(items[indexMerchantOrderItemId])); }
+
+ if (indexMerchantAdjustmentItemId == -1 || items[indexMerchantAdjustmentItemId].Length == 0) { cmd.Parameters.AddWithValue("@MerchantAdjustmentItemRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@MerchantAdjustmentItemRef", items[indexMerchantAdjustmentItemId]); }
+
+ if (indexSku == -1 || items[indexSku].Length == 0) { cmd.Parameters.AddWithValue("@SkuNumber", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@SkuNumber", items[indexSku]); }
+
+ if (indexQuantityPurchased == -1 || items[indexQuantityPurchased].Length == 0) { cmd.Parameters.AddWithValue("@QuantityPurchased", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@QuantityPurchased", int.Parse(items[indexQuantityPurchased])); }
+
+ if (indexPromotionId == -1 || items[indexPromotionId].Length == 0) { cmd.Parameters.AddWithValue("@PromotionRef", DBNull.Value); }
+ else { cmd.Parameters.AddWithValue("@PromotionRef", items[indexPromotionId]); }
+
+ cmd.ExecuteNonQuery();
+ }
+ }
+ lineNumber = lineNumber + 1;
+ }
+ }
+
+ //final check - settlement amount matches sum of inserted settlement lines
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.Transaction = _transaction as SqlTransaction;
+ cmd.CommandText = @"
+ SELECT Sum(tblImportAmazonSettlementReportLine.amount) AS SumOfAmount
+ FROM tblImportAmazonSettlementReportLine
+ WHERE ImportAmazonSettlementReportID=@ImportAmazonSettlementReportID;";
+
+ decimal sumOfAmount = -1.12345m;
+
+ cmd.Parameters.AddWithValue("@ImportAmazonSettlementReportID", settlementReportId);
+ sumOfAmount = (decimal)cmd.ExecuteScalar();
+
+ if (sumOfAmount != settlementAmount)
+ {
+ _log.LogError("Error importing settlement id'" + settlementRef + "'. Sum of inserted settlement lines (" + sumOfAmount +
+ ") does not match settlement amount (" + settlementAmount + ").");
+ return false;
+ }
+ }
+
+ Console.Write("\r");
+ _log.LogInformation((lineNumber - (2 + lineSkip)) + " total settlement items inserted");
+ if (lineSkip > 0)
+ {
+ _log.LogError(lineSkip + " total line(s) where skipped due to insufficent number of cells on row");
+ }
+ return true;
+ }
+
+ public int SetSpapiReportId(string settlementId, string spapiReportId)
+ {
+ string sqlString = @"
+ UPDATE
+ tblImportAmazonSettlementReport
+ SET
+ SpapiReportId = @spapiReportId
+ WHERE
+ [settlement-id] = @settlementId;";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sqlString;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@spapiReportId", spapiReportId);
+ cmd.Parameters.AddWithValue("@settlementId", settlementId);
+
+ return cmd.ExecuteNonQuery();
+ }
+ }
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/SequenceGenerator.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/SequenceGenerator.cs
new file mode 100644
index 0000000..51ede37
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/SequenceGenerator.cs
@@ -0,0 +1,47 @@
+using System;
+using System.Collections.Generic;
+using System.Data;
+using Microsoft.Data.SqlClient;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using bnhtrade.Core.Data.Database.Repository.Interface;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ internal class SequenceGenerator : _Base, ISequenceGenerator
+ {
+ public SequenceGenerator (IDbConnection connection, IDbTransaction transaction) : base(connection, transaction)
+ {
+ }
+
+ public int GetNext(string sequenceName)
+ {
+ if (string.IsNullOrWhiteSpace(sequenceName))
+ {
+ throw new Exception("Sequence name is null or whitespace.");
+ }
+
+ string sql = $"SELECT NEXT VALUE FOR {sequenceName};";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ object obj = cmd.ExecuteScalar();
+
+ try
+ {
+ return Convert.ToInt32(obj);
+ }
+ catch (Exception ex)
+ {
+ // Provide more context in the exception
+ throw new InvalidOperationException($"Error retrieving next value for sequence '{sequenceName}'. " +
+ $"Raw value: '{obj}'. Inner exception: {ex.Message}", ex);
+ }
+ }
+ }
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/_Base.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/_Base.cs
new file mode 100644
index 0000000..5c86041
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/_Base.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ abstract class _Base
+ {
+ protected readonly IDbConnection _connection;
+ protected readonly IDbTransaction _transaction;
+
+ public _Base(IDbConnection connection, IDbTransaction transaction)
+ {
+ _connection = connection ?? throw new ArgumentNullException(nameof(connection));
+ _transaction = transaction; // Transaction can be null if not needed for read-only ops
+ // But for NEXT VALUE FOR, it implies a modification/dependency within a transaction
+ }
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Implementation/_BoilerPlate.cs b/src/bnhtrade.Core/Data/Database/Repository/Implementation/_BoilerPlate.cs
new file mode 100644
index 0000000..c7f4974
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Implementation/_BoilerPlate.cs
@@ -0,0 +1,131 @@
+using bnhtrade.Core.Data.Database._BoilerPlate;
+using bnhtrade.Core.Data.Database.Repository.Interface;
+using FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentOutbound;
+using Microsoft.Data.SqlClient;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Transactions;
+
+namespace bnhtrade.Core.Data.Database.Repository.Implementation
+{
+ internal class _BoilerPlate : _Base, _IBoilerPlate
+ {
+ public _BoilerPlate(IDbConnection connection, IDbTransaction transaction) : base(connection, transaction)
+ {
+ }
+
+ public Dictionary SelectByList(List selectList)
+ {
+ var returnList = new Dictionary();
+
+ // check input list for items
+ if (selectList == null)
+ {
+ throw new ArgumentNullException("Method argument cannot be null");
+ }
+
+ // build SQL string
+ string sql = @"
+ SELECT
+ column01
+ ,column02
+ FROM
+ tblTable
+ ";
+
+ var sqlwhere = new Data.Database.SqlWhereBuilder();
+ sqlwhere.In("column03", selectList, "WHERE");
+
+ sql = sql + sqlwhere.SqlWhereString;
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ sqlwhere.AddParametersToSqlCommand(cmd);
+
+ using (SqlDataReader reader = cmd.ExecuteReader())
+ {
+ while (reader.Read())
+ {
+ int id = reader.GetInt32(0);
+ string data = reader.GetString(1);
+
+ returnList.Add(id, data);
+ }
+ }
+ }
+ return returnList;
+ }
+
+ public int Insert()
+ {
+ string sql = @"
+ INSERT INTO tblTable (
+ column01
+ ,column02
+ ,column03
+ ,column04
+ )
+ OUTPUT INSERTED.TablePk
+ VALUES (
+ @value01
+ ,@value02
+ ,@value03
+ ,@value04
+ )
+ ";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@value01", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value02", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value03", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value04", "xxxxxxxx");
+
+ int newId = (int)cmd.ExecuteScalar();
+
+ return newId;
+ }
+ }
+
+ public int Update()
+ {
+ string sql = @"
+ UPDATE
+ tblTable
+ SET
+ column01 = @value01
+ column02 = @value02
+ column03 = @value03
+ column04 = @value04
+ WHERE
+ column05 = @value05
+ ";
+
+ using (SqlCommand cmd = _connection.CreateCommand() as SqlCommand)
+ {
+ cmd.CommandText = sql;
+ cmd.Transaction = _transaction as SqlTransaction;
+
+ cmd.Parameters.AddWithValue("@value01", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value02", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value03", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value04", "xxxxxxxx");
+ cmd.Parameters.AddWithValue("@value04", "xxxxxxxx");
+
+ int recordsEffected = cmd.ExecuteNonQuery();
+
+ return recordsEffected;
+ }
+ }
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Interface/ICurrencyRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Interface/ICurrencyRepository.cs
new file mode 100644
index 0000000..f4ac03a
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Interface/ICurrencyRepository.cs
@@ -0,0 +1,17 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Interface
+{
+ internal interface ICurrencyRepository
+ {
+ public decimal? ReadExchangeRate(Model.Account.CurrencyCode currencyCode, DateTime date);
+ public List ReadExchangeRate(List currencyCodeList = null, DateTime date = default(DateTime));
+ public List ReadExchangeRateLatest(List currencyCodeList = null);
+ public int InsertExchangeRate(int exchangeRateSource, Model.Account.CurrencyCode currencyCode,
+ decimal currencyUnitsPerGbp, DateTime periodStartUtc, DateTime periodEnd, bool checkOverride = false);
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Interface/IExportInvoiceRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Interface/IExportInvoiceRepository.cs
new file mode 100644
index 0000000..c5e7004
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Interface/IExportInvoiceRepository.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Interface
+{
+ internal interface IExportInvoiceRepository
+ {
+ internal Dictionary InsertSalesInvoices(IEnumerable invoiceList);
+ internal Dictionary GetNewInvoiceNumbers(Model.Account.InvoiceType invoiceType);
+ internal Dictionary GetSalesInvoiceById(IEnumerable idList);
+ internal int SetInvoiceIsCompleteValue(Dictionary updateDictionary);
+ internal int DeleteInvoiceLine(int invoiceLineId);
+ internal int DeleteInvoice(IEnumerable invoiceIdList);
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Interface/IImportAmazonRepository.cs b/src/bnhtrade.Core/Data/Database/Repository/Interface/IImportAmazonRepository.cs
new file mode 100644
index 0000000..21cabda
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Interface/IImportAmazonRepository.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Interface
+{
+ internal interface IImportAmazonRepository
+ {
+ public List ReadAmazonSettlementHeaderInfoBySettlementId(List settlementIdList);
+
+ public List ReadAmazonSettlementHeaderInfoBySpapiReportId(List spapiReportIdList);
+
+ public Dictionary ReadAmazonSettlements(
+ List settlementIdList = null, List marketPlaceNameList = null, bool? isProcessed = null,
+ bool descendingOrder = false, int? returnTop = null);
+
+ public int SetAmazonSettlementIsProcessed(List settlementIdList, bool isProcessed);
+
+ public bool CreateAmazonSettlements(string filePath, string reportId);
+
+ public int SetSpapiReportId(string settlementId, string spapiReportId);
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Interface/ISequenceGenerator.cs b/src/bnhtrade.Core/Data/Database/Repository/Interface/ISequenceGenerator.cs
new file mode 100644
index 0000000..15200fa
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Interface/ISequenceGenerator.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Data;
+
+namespace bnhtrade.Core.Data.Database.Repository.Interface
+{
+ internal interface ISequenceGenerator
+ {
+ int GetNext(string sequenceName);
+ }
+}
\ No newline at end of file
diff --git a/src/bnhtrade.Core/Data/Database/Repository/Interface/_IBoilerPlate.cs b/src/bnhtrade.Core/Data/Database/Repository/Interface/_IBoilerPlate.cs
new file mode 100644
index 0000000..626da22
--- /dev/null
+++ b/src/bnhtrade.Core/Data/Database/Repository/Interface/_IBoilerPlate.cs
@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace bnhtrade.Core.Data.Database.Repository.Interface
+{
+ internal interface _IBoilerPlate
+ {
+ internal Dictionary SelectByList(List selectList);
+ internal int Insert();
+ internal int Update();
+ }
+}
diff --git a/src/bnhtrade.Core/Data/Database/SKU/InsertSku.cs b/src/bnhtrade.Core/Data/Database/SKU/InsertSku.cs
index 68cb69a..7578e9d 100644
--- a/src/bnhtrade.Core/Data/Database/SKU/InsertSku.cs
+++ b/src/bnhtrade.Core/Data/Database/SKU/InsertSku.cs
@@ -1,7 +1,7 @@
using FikaAmazonAPI.AmazonSpApiSDK.Models.ProductPricing;
using System;
using System.Collections.Generic;
-using System.Data.SqlClient;
+using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -22,11 +22,11 @@ namespace bnhtrade.Core.Data.Database.Sku
var dbTax = new Data.Database.Account.ReadTaxCode();
var taxCodeList = dbTax.GetByTaxCodeId(new List { accountTaxCodeId });
- if (!taxCodeList.Any())
+ if (taxCodeList.ContainsKey(accountTaxCodeId) == false)
{
throw new Exception("AccountTaxCodeID=" + accountTaxCodeId + " doesn't exist!");
}
- else if (taxCodeList[0].IsValidOnIncome == false)
+ else if (taxCodeList[accountTaxCodeId].IsValidOnIncome == false)
{
throw new Exception("AccountTaxCodeID=" + accountTaxCodeId + " is not a valid type for an SKU.");
}
diff --git a/src/bnhtrade.Core/Data/Database/SqlWhereBuilder.cs b/src/bnhtrade.Core/Data/Database/SqlWhereBuilder.cs
index 73687f1..7f7159d 100644
--- a/src/bnhtrade.Core/Data/Database/SqlWhereBuilder.cs
+++ b/src/bnhtrade.Core/Data/Database/SqlWhereBuilder.cs
@@ -5,6 +5,7 @@ using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using Microsoft.IdentityModel.Tokens;
namespace bnhtrade.Core.Data.Database
{
@@ -12,9 +13,12 @@ namespace bnhtrade.Core.Data.Database
/// Step 1: Call the methods for each where clause you want to create. This can be done multiple times to create an sql where string. Pay attention
/// to the prefixes that you'll require between each where clause, as each time a method is called the sql statement will be appended to the previous sql
/// string.
+ ///
/// Step 2: Appened the created sql string to your sql statement, NB the WHERE statemet is not included by default.
+ ///
/// Step 3: Once you've created your sql command object, add the parameters to it using the method contained within this class.
- /// STep 4: exceute your sql commend.
+ ///
+ /// Step 4: exceute your sql commend.
///
public class SqlWhereBuilder
{
@@ -44,6 +48,21 @@ namespace bnhtrade.Core.Data.Database
public Dictionary ParameterList { get; private set; }
+ public int ParameterListCount
+ {
+ get
+ {
+ if (ParameterList == null || ParameterList.Any() == false)
+ {
+ return 0;
+ }
+ else
+ {
+ return ParameterList.Count();
+ }
+ }
+ }
+
///
/// Initialises the class
///
@@ -83,7 +102,7 @@ namespace bnhtrade.Core.Data.Database
/// Name of the column to used to for the condition statement
/// List of phrases to test in condition statement
/// Optional prefix that gets added to the sql string result
- public void LikeAnd(string columnReference, List phraseList, string wherePrefix = null)
+ public void LikeAnd(string columnReference, IEnumerable phraseList, string wherePrefix = null)
{
Like(columnReference, phraseList, true, wherePrefix);
}
@@ -94,12 +113,12 @@ namespace bnhtrade.Core.Data.Database
/// Name of the column to used to for the condition statement
/// List of phrases to test in condition statement
/// Optional prefix that gets added to the sql string result
- public void LikeOr(string columnReference, List phraseList, string wherePrefix = null)
+ public void LikeOr(string columnReference, IEnumerable phraseList, string wherePrefix = null)
{
Like(columnReference, phraseList, false, wherePrefix);
}
- private void Like(string columnReference, List phraseList, bool isAnd, string wherePrefix = null)
+ private void Like(string columnReference, IEnumerable phraseList, bool isAnd, string wherePrefix = null)
{
if (phraseList == null || !phraseList.Any())
{
@@ -107,7 +126,7 @@ namespace bnhtrade.Core.Data.Database
}
// ensure no values are repeated
- var distinctList = phraseList.ToList();
+ var distinctList = phraseList.Distinct().ToList();
// clean the list
for (int i = 0; i < distinctList.Count; i++)
@@ -166,7 +185,7 @@ namespace bnhtrade.Core.Data.Database
/// Name of the column to used to for the condition statement
/// List of values to test in condition statement
/// Optional prefix that gets added to the sql string result
- public void In(string columnReference, List orValueList, string wherePrefix = null)
+ public void In(string columnReference, IEnumerable