Export amazon settlement report fix

This commit is contained in:
2020-02-06 21:20:15 +00:00
committed by GitHub
parent bed529e1c8
commit 7e50da21e7
52 changed files with 4827 additions and 819 deletions

View File

@@ -0,0 +1,137 @@
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.Account
{
public class ReadAccountCode : Connection
{
private bool allRetrived;
private Dictionary<int, Model.Account.AccountCode> cache;
protected ReadAccountCode(string sqlConnectionString) : base(sqlConnectionString)
{
allRetrived = false;
cache = new Dictionary<int, Model.Account.AccountCode>();
}
protected void ClearCache()
{
allRetrived = false;
cache.Clear();
}
public List<Model.Account.AccountCode> GetAll()
{
if (allRetrived == false)
{
UpdateCache(-1);
allRetrived = true;
}
var returnList = new List<Model.Account.AccountCode>();
foreach (var item in cache)
{
returnList.Add(item.Value);
}
return returnList;
}
public Model.Account.AccountCode GetByAccountCode(int accountCode)
{
if (cache.ContainsKey(accountCode))
{
return cache[accountCode];
}
else if (allRetrived)
{
return null;
}
else
{
UpdateCache(accountCode);
if (cache.ContainsKey(accountCode))
{
return cache[accountCode];
}
else
{
return null;
}
}
}
protected void UpdateCache(int accountCode = -1)
{
var dicCache = new Dictionary<int, Model.Account.AccountCode>();
bool whereClause = false;
//build sql query
string sqlString = @"
SELECT tblAccountChartOf.AccountChartOfID
,tblAccountChartOf.AccountCode
,tblAccountChartOf.AccountName
,tblAccountChartOf.Description
,tblAccountChartOfType.AccountChartOfType
,tblAccountChartOfType.BasicType
FROM tblAccountChartOf
INNER JOIN tblAccountChartOfType ON tblAccountChartOf.AccountChartOfTypeID = tblAccountChartOfType.AccountChartOfTypeID";
if (accountCode > -1)
{
whereClause = true;
sqlString = sqlString + @"
WHERE (((tblAccountChartOf.AccountCode) = @accountCode))";
}
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
if (whereClause)
{
cmd.Parameters.AddWithValue("@accountCode", accountCode);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var result = new Model.Account.AccountCode();
int tablePk = reader.GetInt32(0);
result.AccountCodeId = reader.GetInt32(1);
result.Title = reader.GetString(2);
if (!reader.IsDBNull(3)) { result.Description = reader.GetString(3); }
result.Type = reader.GetString(4);
result.BasicType = reader.GetString(5);
if (whereClause)
{
if (cache.ContainsKey(result.AccountCodeId))
{
cache.Remove(result.AccountCodeId);
}
cache.Add(result.AccountCodeId, result);
}
else
{
dicCache.Add(result.AccountCodeId, result);
}
}
}
}
}
}
// update cache
if (!whereClause)
{
cache.Clear();
allRetrived = true;
cache = dicCache;
}
}
}
}

View File

@@ -0,0 +1,144 @@
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.Account
{
public class ReadInvoiceLineItemCode : Connection
{
public ReadInvoiceLineItemCode(string sqlConnectionString) : base (sqlConnectionString)
{
cacheLineItemByTablePk = new Dictionary<int, Model.Account.InvoiceLineItem>();
cacheTablePkByItemCode = new Dictionary<string, int>();
}
private Dictionary<int, Model.Account.InvoiceLineItem> cacheLineItemByTablePk;
private Dictionary<string, int> cacheTablePkByItemCode;
public bool InsertNewOnNoMatch { get; set; } = false;
public void CacheClear()
{
cacheLineItemByTablePk.Clear();
cacheTablePkByItemCode.Clear();
}
private void CacheRemove(int tablePk)
{
if (cacheLineItemByTablePk.ContainsKey(tablePk))
{
string itemCode = cacheLineItemByTablePk[tablePk].ItemCode;
cacheLineItemByTablePk.Remove(tablePk);
cacheTablePkByItemCode.Remove(itemCode);
}
}
public void CacheRemove(string itemCode)
{
if (cacheTablePkByItemCode.ContainsKey(itemCode))
{
CacheRemove(cacheTablePkByItemCode[itemCode]);
}
}
private void CacheUpdate(int tablePk, Model.Account.InvoiceLineItem lineItem)
{
if (cacheLineItemByTablePk.ContainsKey(tablePk))
{
CacheRemove(tablePk);
}
cacheLineItemByTablePk.Add(tablePk, lineItem);
cacheTablePkByItemCode.Add(lineItem.ItemCode, tablePk);
}
public Model.Account.InvoiceLineItem ByItemCode(string itemCode, bool forceCacheUpdate = false)
{
// check cache
if (!forceCacheUpdate && cacheTablePkByItemCode.ContainsKey(itemCode))
{
return cacheLineItemByTablePk[cacheTablePkByItemCode[itemCode]];
}
var returnObject = new Model.Account.InvoiceLineItem();
returnObject.ItemCode = itemCode;
using (TransactionScope scopeSupress = new TransactionScope(TransactionScopeOption.Suppress))
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(@"
SELECT tblExportAccountInvoiceLineType.ExportAccountInvoiceLineTypeID
,tblExportAccountInvoiceLineType.TypeTitle
,tblExportAccountInvoiceLineType.TypeDescription
,tblExportAccountInvoiceLineType.IsNewReviewRequired
,tblExportAccountInvoiceLineType.InvoiceLineEntryEnable
,tblAccountChartOf.AccountCode
,tblAccountTaxCode.TaxCode
FROM (
tblExportAccountInvoiceLineType LEFT JOIN tblAccountChartOf ON tblExportAccountInvoiceLineType.AccountChartOfID_Default = tblAccountChartOf.AccountChartOfID
)
LEFT JOIN tblAccountTaxCode ON tblExportAccountInvoiceLineType.AccountTaxCodeID_Default = tblAccountTaxCode.AccountTaxCodeID
WHERE (((tblExportAccountInvoiceLineType.MatchString) = @matchString))
", conn))
{
cmd.Parameters.AddWithValue("@matchString", returnObject.ItemCode);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
int tablePk = reader.GetInt32(0);
returnObject.Title = reader.GetString(1);
if (!reader.IsDBNull(2)) { returnObject.Description = reader.GetString(2); }
returnObject.IsNewReviewRequired = reader.GetBoolean(3);
returnObject.InvoiceLineEntryEnabled = reader.GetBoolean(4);
if (!reader.IsDBNull(5)) { returnObject.DefaultAccountCode = reader.GetInt32(5); }
if (!reader.IsDBNull(6)) { returnObject.DefaultTaxCode = reader.GetString(6); }
// add to cache
CacheUpdate(tablePk, returnObject);
// return object
return returnObject;
}
}
}
// insert new and retrive new value, if required
if (InsertNewOnNoMatch)
{
int tablePk = 0;
returnObject.Title = "NEW TYPE";
returnObject.ItemCode = itemCode;
returnObject.IsNewReviewRequired = true;
using (SqlCommand insertCmd = new SqlCommand(@"
INSERT INTO tblExportAccountInvoiceLineType ( TypeTitle, MatchString )
OUTPUT INSERTED.ExportAccountInvoiceLineTypeID
VALUES ( @typeTitle, @matchString )
", conn))
{
insertCmd.Parameters.AddWithValue("@typeTitle", returnObject.Title);
insertCmd.Parameters.AddWithValue("@matchString", returnObject.ItemCode);
tablePk = (int)insertCmd.ExecuteScalar();
scopeSupress.Complete();
}
// add to cache
CacheUpdate(tablePk, returnObject);
// return object
return returnObject;
}
else
{
return null;
}
}
}
}
}

View File

@@ -0,0 +1,227 @@
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.Account
{
public class ReadTaxCode : Connection
{
private bool allRetrived;
private Dictionary<string, Model.Account.TaxCode> cache;
public ReadTaxCode(string sqlConnectionString) : base(sqlConnectionString)
{
allRetrived = false;
cache = new Dictionary<string, Model.Account.TaxCode>();
}
private void ClearCache()
{
allRetrived = false;
cache.Clear();
}
public List<Model.Account.TaxCode> GetAll()
{
if (allRetrived == false)
{
UpdateCache(null);
allRetrived = true;
}
var returnList = new List<Model.Account.TaxCode>();
foreach (var item in cache)
{
returnList.Add(item.Value);
}
return returnList;
}
public Dictionary<string, Model.Account.TaxCode> BySkuNumber(List<string> skuNumberList)
{
// check input list for items
if (skuNumberList == null || !skuNumberList.Any())
{
return null;
}
// build SQL string
string sqlString = @"
SELECT
tblSku.skuSkuNumber, tblAccountTaxCode.TaxCode
FROM
tblAccountTaxCode INNER JOIN tblSku ON tblAccountTaxCode.AccountTaxCodeID = tblSku.AccountTaxCodeID
WHERE
";
var parameterValueList = new List<Tuple<string, string>>();
foreach (var item in skuNumberList)
{
if (!string.IsNullOrWhiteSpace(item))
{
int count = parameterValueList.Count;
var parameterValue = new Tuple<string, string>("@parameter" + count, item);
parameterValueList.Add(parameterValue);
if (count == 0)
{
sqlString = sqlString + @"
skuSkuNumber = " + parameterValue.Item1;
}
else
{
sqlString = sqlString + @"
OR skuSkuNumber = " + parameterValue.Item1;
}
}
}
if (parameterValueList.Count == 0)
{
return null;
}
// execute query and build result list
var skuTaxCodeList = new List<Tuple<string, string>>();
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
foreach (var item in parameterValueList)
{
cmd.Parameters.AddWithValue(item.Item1, item.Item2);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
return null;
}
while (reader.Read())
{
var skuTaxCode = new Tuple<string, string>(
reader.GetString(0),
reader.GetString(1)
);
skuTaxCodeList.Add(skuTaxCode);
}
}
}
// build dictionary of skuNumber to TaxCodeInfo
var returnDictionary = new Dictionary<string, Model.Account.TaxCode>();
foreach (var item in skuTaxCodeList)
{
returnDictionary.Add(item.Item1, GetByTaxCodeId(item.Item2));
}
return returnDictionary;
}
}
public Model.Account.TaxCode GetByTaxCodeId(string taxCode)
{
if (cache.ContainsKey(taxCode))
{
return cache[taxCode];
}
else if (allRetrived)
{
return null;
}
else
{
UpdateCache(taxCode);
if (cache.ContainsKey(taxCode))
{
return cache[taxCode];
}
else
{
return null;
}
}
}
private void UpdateCache(string taxCode)
{
var dicCache = new Dictionary<string, Model.Account.TaxCode>();
bool whereClause = false;
//build sql query
string sqlString = @"
SELECT
TaxCode
,TaxRateName
,TaxRateMultiplierNet
,TaxRateMultiplierGross
,IsValidOnExpense
,IsVailidOnIncome
,Description
,IsActive
,TaxType
FROM tblAccountTaxCode";
if (!string.IsNullOrWhiteSpace(taxCode))
{
whereClause = true;
sqlString = sqlString + @"
WHERE TaxCode = @taxCode";
}
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
if (whereClause)
{
cmd.Parameters.AddWithValue("@taxCode", taxCode);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var result = new Model.Account.TaxCode();
result.TaxCodeId = reader.GetString(0);
result.TaxRateTitle = reader.GetString(1);
result.NetAmountMultiplier = reader.GetDecimal(2);
result.GrossAmountMultiplier = reader.GetDecimal(3);
result.IsValidOnExpense = reader.GetBoolean(4);
result.IsValidOnIncome = reader.GetBoolean(5);
if (!reader.IsDBNull(6)) { result.TaxRateDescription = reader.GetString(6); }
result.IsActive = reader.GetBoolean(7);
result.TaxType = reader.GetString(8);
if (whereClause)
{
if (cache.ContainsKey(result.TaxCodeId))
{
cache.Remove(result.TaxCodeId);
}
cache.Add(result.TaxCodeId, result);
}
else
{
dicCache.Add(result.TaxCodeId, result);
}
}
}
}
}
}
// update cache
if (!whereClause)
{
cache.Clear();
allRetrived = true;
cache = dicCache;
}
}
}
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace bnhtrade.Core.Data.Database
{

View File

@@ -0,0 +1,50 @@
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 string ErrorMessage { get; set; }
public ImportAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
{
}
public bool RunCheck()
{
ErrorMessage = null;
using (var sqlConn = new SqlConnection())
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand(@"
SELECT Count(tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportLineID) AS CountOfID
FROM tblImportAmazonSettlementReportLine
INNER JOIN tblImportAmazonSettlementReport ON tblImportAmazonSettlementReportLine.ImportAmazonSettlementReportID = tblImportAmazonSettlementReport.ImportAmazonSettlementReportID
WHERE (
((tblImportAmazonSettlementReport.IsProcessed) = 0)
AND ((tblImportAmazonSettlementReportLine.AccountTransactionID) IS NOT NULL)
)
OR (
((tblImportAmazonSettlementReport.IsProcessed) = 0)
AND ((tblImportAmazonSettlementReportLine.IsProcessed) = 1)
);
", sqlConn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count != 0)
{
ErrorMessage = "Error, " + count + " settlement report lines have transactionId/IsProcessed set on an unprocessed settlement";
return false;
}
}
}
return true;
}
}
}

View File

@@ -0,0 +1,171 @@
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
{
private Logic.Log.LogEvent log = new Logic.Log.LogEvent();
public CreateSalesInvoice(string sqlConnectionString) : base(sqlConnectionString)
{
}
public void SaveInvoice(List<Model.Account.SalesInvoice> invoiceList)
{
using (TransactionScope scope = new TransactionScope())
{
// get table pks for invoice type line and fill in invoice line details
var readItemCode = new Data.Database.Account.ReadInvoiceLineItemCode(sqlConnectionString);
readItemCode.InsertNewOnNoMatch = true;
bool newTypeFound = false;
for (int i = 0; i < invoiceList.Count(); i++)
{
for (int j = 0; j < invoiceList[i].InvoiceLineList.Count(); j++)
{
var itemCodeInfo = readItemCode.ByItemCode(invoiceList[i].InvoiceLineList[j].ItemCode);
if (itemCodeInfo.IsNewReviewRequired)
{ newTypeFound = true; }
else
{
invoiceList[i].InvoiceLineList[j].AccountCode = itemCodeInfo.DefaultAccountCode;
invoiceList[i].InvoiceLineList[j].TaxCode = itemCodeInfo.DefaultTaxCode;
invoiceList[i].InvoiceLineList[j].Description = itemCodeInfo.Description;
}
}
}
if (newTypeFound)
{
log.LogError("New line ItemCode created while processing Amazon settlements. Update table to complete.");
return;
}
// add temp invoice numbers to invoices
var sequence = new Programmability.Sequence(sqlConnectionString);
for (int i = 0; i < invoiceList.Count(); i++)
{
if (invoiceList[i].InvoiceNumberIsSet)
{
var log = new Logic.Log.LogEvent();
log.LogError("Unexpected invoice number found.");
return;
}
invoiceList[i].InvoiceNumber = "_tmp" + sequence.GetNext("ExportTempInvoiceNumber").ToString("00000000");
}
// validate the list of invoices
var validateInvoice = new Logic.Account.ValidateSalesInvoice();
validateInvoice.InvoiceLineDescriptionIsRequired = false;
validateInvoice.IsValidInvoice(invoiceList);
if (validateInvoice.ErrorListIsSet)
{
log.LogError("Invalid Sales invoice(s) found during Amazon Settlement process. See extended info.", validateInvoice.ErrorListToString());
return;
}
validateInvoice = null;
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].InvoiceAmount);
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
,ExportAccountInvoiceLineTypeID
,NetAmount
,AccountChartOfID
,TaxAmount
,AccountTaxCodeID
)
OUTPUT INSERTED.ExportAccountInvoiceLineID
VALUES (
@invoiceId
,(
SELECT ExportAccountInvoiceLineTypeID
FROM tblExportAccountInvoiceLineType
WHERE MatchString = @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].TotalNetAmount);
cmd.Parameters.AddWithValue("@accountCode", invoiceList[i].InvoiceLineList[j].AccountCode);
cmd.Parameters.AddWithValue("@taxAmount", invoiceList[i].InvoiceLineList[j].TaxAmount);
cmd.Parameters.AddWithValue("@taxCode", invoiceList[i].InvoiceLineList[j].TaxCode);
int lineId = (int)cmd.ExecuteScalar();
}
}
}
}
scope.Complete();
}
}
}
}

View File

@@ -84,7 +84,7 @@ namespace bnhtrade.Core.Data.Database.FBAInbound
foreach (string item in ShipmentIdList)
{
countShipId = countShipId + 1;
string parameterString = "@shipmentId" + countShipId.ToString().PadLeft(6, '0');
string parameterString = "@shipmentId" + countShipId;
dicShipIdByParameterString.Add(parameterString, item);
if (countShipId == 1)
{

View File

@@ -11,7 +11,7 @@ namespace bnhtrade.Core.Data.Database.FBAInbound
public class SetShipmentInfo : Connection
{
private GetShipmentPrimaryKey getPK;
private Data.Database.SKU.GetSKUId skuIdLoopkup;
private Data.Database.SKU.GetSkuId skuIdLoopkup;
public SetShipmentInfo(string sqlConnectionString) : base(sqlConnectionString) { }
private GetShipmentPrimaryKey GetPK
{
@@ -28,13 +28,13 @@ namespace bnhtrade.Core.Data.Database.FBAInbound
getPK = value;
}
}
private Data.Database.SKU.GetSKUId SkuIdLoopkup
private Data.Database.SKU.GetSkuId SkuIdLoopkup
{
get
{
if (skuIdLoopkup == null)
{
skuIdLoopkup = new SKU.GetSKUId(sqlConnectionString);
skuIdLoopkup = new SKU.GetSkuId(sqlConnectionString);
}
return skuIdLoopkup;
}

View File

@@ -0,0 +1,323 @@
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 ReadAmazonSettlement : Connection
{
private Dictionary<string, int> dicTablePkBySettlementId = new Dictionary<string, int>();
private int? returnTop = null;
private List<string> 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<string> SettlementIdList
{
get { return settlementIdList; }
set
{
if (value.Any())
{ settlementIdList = value; }
}
}
private bool SettlementIdListIsSet
{
get { return SettlementIdList != null; }
}
public ReadAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
{
Innit();
}
private void Innit()
{
DescendingOrder = false;
FilterOutIsProcessed = false;
ReturnTop = 0;
settlementIdList = null;
}
public List<Model.Import.AmazonSettlement> AllUnprocessed()
{
Innit();
FilterOutIsProcessed = true;
return ExecuteDbQuery();
}
public Model.Import.AmazonSettlement BySettlementId(string settlementId)
{
Innit();
// create settlement list
var idList = new List<string>();
idList.Add(settlementId);
var settlementList = BySettlementId(idList);
// return answer
if (settlementList == null || !settlementList.Any())
{ return null; }
else
{ return settlementList.First(); }
}
public List<Model.Import.AmazonSettlement> BySettlementId(List<string> settlementIdList)
{
Innit();
if (settlementIdList == null || !settlementIdList.Any())
{ return null; }
SettlementIdList = settlementIdList;
return ExecuteDbQuery();
}
private List<Model.Import.AmazonSettlement> 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<Model.Import.AmazonSettlement> 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<string, string>();
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<Model.Import.AmazonSettlement>();
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<Model.Import.AmazonSettlement.SettlementLine> 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<Model.Import.AmazonSettlement.SettlementLine>();
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;
}
}
}
}
}
}

View File

@@ -0,0 +1,54 @@
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 UpdateAmazonSettlement : Connection
{
public UpdateAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
{
}
public void SetIsProcessedTrue(List<string> 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.");
}
}
}
}
}
}

View File

@@ -0,0 +1,77 @@
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.Log
{
public class LogEvent
{
protected void DatabaseLogInsert
(string detailShort, int eventType, string detailLong, DateTime eventDateTime, bool consolePrint = true)
{
var console = new UI.Console.Update();
if (consolePrint)
{
if (string.IsNullOrWhiteSpace(detailLong))
{ console.WriteLine(detailShort); }
else { console.WriteLine(detailShort + Environment.NewLine + detailLong); }
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// need to remove this section once code has been rewritten, writing to console will be handled
// in the business layer
// login credentials only allow insert on log table
string userId = "Log_bnhtrade";
string password = "52ya9dky55cniyynwro5e48mV9";
string sqlConnectionString =
"Data Source=SQL-Server;Initial Catalog=e2A;Persist Security Info=TRUE;User ID=" + userId +
";Password=" + password + ";MultipleActiveResultSets=TRUE";
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
{
sqlConn.Open();
try
{
using (SqlCommand cmd = new SqlCommand(@"
INSERT INTO tblLogEvent (
EventDateTime
,LogEventTypeID
,LogEventSourceID
,Detail
,DetailLong
)
VALUES (
@eventDateTime
,@eventType
,1
,@detailShort
,@detailLong
)
", sqlConn))
{
cmd.Parameters.AddWithValue("@eventDateTime", eventDateTime);
cmd.Parameters.AddWithValue("@eventType", eventType);
cmd.Parameters.AddWithValue("@detailShort", detailShort);
if (detailLong == null) { cmd.Parameters.AddWithValue("@detailLong", DBNull.Value); }
else { cmd.Parameters.AddWithValue("@detailLong", detailLong); }
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
console.WriteLine("WTF!!!! Error with error logging, jobs foooked!");
throw ex;
}
scope.Complete();
}
}
}
}
}

View File

@@ -0,0 +1,49 @@
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 (string sqlConnectionString) : base(sqlConnectionString)
{
}
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);
}
}
}
}
}
}

View File

@@ -4,12 +4,12 @@ using System.Data.SqlClient;
namespace bnhtrade.Core.Data.Database.SKU
{
public class GetSKUId
public class GetSkuId
{
private Dictionary<string, int> SKUIdBySKUNumber { get; set; }
private Dictionary<int, string> SKUNumberBySKUId { get; set; }
private string SqlConnectionString { get; set; }
public GetSKUId(string sqlConnectionString)
public GetSkuId(string sqlConnectionString)
{
// setup sql parameters
if (sqlConnectionString.Length == 0)

View File

@@ -0,0 +1,158 @@
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.SKU
{
class GetSku : Connection
{
private Dictionary<string, Model.Sku.Sku> cache;
protected GetSku (string sqlConnection) : base(sqlConnection)
{
Default();
}
protected List<Model.Sku.Sku> BySkuNumberList(List<string> skuNumberList, bool forceRequery = false)
{
if (skuNumberList == null || !skuNumberList.Any())
{
return null;
}
var getList = new List<string>();
foreach(string item in skuNumberList)
{
if (forceRequery || !cache.ContainsKey(item))
{
getList.Add(item);
}
}
// update the cache
CacheUpdate(getList);
// build the return list
var returnList = new List<Model.Sku.Sku>();
foreach (string item in skuNumberList)
{
if (cache.ContainsKey(item))
{
returnList.Add(cache[item]);
}
}
//return the list
if (returnList.Any())
{
return returnList;
}
else
{
return null;
}
}
protected void CacheClear()
{
cache.Clear();
}
private void CacheUpdate(List<string> skuNumberList)
{
// build the sql string
string sqlString = @"
SELECT
skuSkuID
,skuSkuNumber
,skuAmazonFNSKU
,skuActive
FROM tblSku
WHERE 1 = 1";
// build dictionary of parameters and skunumbers
var dicSkuNumberByParameterString = new Dictionary<string, string>();
int count = 0;
foreach (string item in skuNumberList)
{
if (!string.IsNullOrWhiteSpace(item))
{
count = count + 1;
string parameterString = "@skuNumber" + count;
dicSkuNumberByParameterString.Add(parameterString, item);
}
}
if (dicSkuNumberByParameterString.Any())
{
count = 0;
foreach (var item in dicSkuNumberByParameterString)
{
count = count + 1;
if (count == 1)
{
sqlString = sqlString + @"
AND ( skuSkuNumber = " + item.Key;
}
else
{
sqlString = sqlString + @"
OR skuSkuNumber = " + item.Key;
}
}
sqlString = sqlString + " )";
}
else
{
return;
}
sqlString = sqlString + @"
ORDER BY skuSkuNumber";
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
if (dicSkuNumberByParameterString.Any())
{
foreach (var item in dicSkuNumberByParameterString)
{
cmd.Parameters.AddWithValue(item.Key, item.Value);
}
}
using (var reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
return;
}
while (reader.Read())
{
var sku = new Model.Sku.Sku();
int tablePk = reader.GetInt32(0);
sku.SkuNumber = reader.GetString(1);
if (!reader.IsDBNull(2)) { sku.AmazonFNSKU = reader.GetString(2); }
sku.IsActive = reader.GetBoolean(3);
// update cache
if (cache.ContainsKey(sku.SkuNumber))
{
cache.Remove(sku.SkuNumber);
}
cache.Add(sku.SkuNumber, sku);
}
}
}
}
}
protected void Default()
{
cache = new Dictionary<string, Model.Sku.Sku>();
}
}
}