mirror of
https://github.com/stokebob/bnhtrade.git
synced 2026-03-27 09:57:16 +00:00
Migration from Amazon MWS to Selling Partner API
This commit is contained in:
@@ -0,0 +1,246 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaCustomerReturn : Connection
|
||||
{
|
||||
public AmazonFbaCustomerReturn()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool UpdateByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineDuplicateSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "return-date");
|
||||
int index02 = Array.IndexOf(headers, "order-id");
|
||||
int index03 = Array.IndexOf(headers, "sku");
|
||||
int index04 = Array.IndexOf(headers, "asin");
|
||||
int index05 = Array.IndexOf(headers, "fnsku");
|
||||
int index06 = Array.IndexOf(headers, "quantity");
|
||||
int index07 = Array.IndexOf(headers, "fulfillment-center-id");
|
||||
int index08 = Array.IndexOf(headers, "detailed-disposition");
|
||||
int index09 = Array.IndexOf(headers, "reason");
|
||||
int index10 = Array.IndexOf(headers, "status");
|
||||
int index11 = Array.IndexOf(headers, "license-plate-number");
|
||||
int index12 = Array.IndexOf(headers, "customer-comments");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string returnDate = items[index01];
|
||||
string orderId = items[index02];
|
||||
string sku = items[index03];
|
||||
string asin = items[index04];
|
||||
string fnsku = items[index05];
|
||||
string quantity = items[index06];
|
||||
string fulfillmentCenterId = items[index07];
|
||||
string detailedDisposition = items[index08];
|
||||
string reason = items[index09];
|
||||
string status = items[index10];
|
||||
string licensePlateNumber = items[index11];
|
||||
string customerComments = items[index12];
|
||||
|
||||
// check number of times line conbination appears in file
|
||||
int fileCount = 0;
|
||||
int dbCount = 0;
|
||||
using (var dupReader = new StreamReader(filePath))
|
||||
{
|
||||
dupReader.ReadLine(); // read header row
|
||||
string dupFileRow;
|
||||
while ((dupFileRow = dupReader.ReadLine()) != null)
|
||||
{
|
||||
string[] dupItems = dupFileRow.Split('\t');
|
||||
if (dupItems.Length != columnCount)
|
||||
{
|
||||
// skip
|
||||
}
|
||||
else
|
||||
{
|
||||
if (items[index01] == dupItems[index01] &&
|
||||
items[index02] == dupItems[index02] &&
|
||||
items[index05] == dupItems[index05] &&
|
||||
items[index11] == dupItems[index11])
|
||||
{
|
||||
// count will always find at least one (itself)
|
||||
fileCount = fileCount + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check for duplicate line in db
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT COUNT(ImportFbaCustomerReturnID) FROM tblImportFbaCustomerReturn " +
|
||||
"WHERE [return-date]=@returnDate AND [order-id]=@orderId AND [fnsku]=@fnsku " +
|
||||
"AND ([license-plate-number]=@licensePlateNumber OR [license-plate-number] IS NULL) ;"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
if (returnDate == "") { cmd.Parameters.AddWithValue("@returnDate", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@returnDate", DateTime.Parse(returnDate).ToUniversalTime()); }
|
||||
if (orderId == "") { cmd.Parameters.AddWithValue("@orderId", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@orderId", orderId); }
|
||||
if (fnsku == "") { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (licensePlateNumber == "") { cmd.Parameters.AddWithValue("@licensePlateNumber", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@licensePlateNumber", licensePlateNumber); }
|
||||
|
||||
dbCount = (int)cmd.ExecuteScalar();
|
||||
}
|
||||
|
||||
if (fileCount <= dbCount)
|
||||
{
|
||||
//skip
|
||||
lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//insert report items
|
||||
using (SqlCommand insertCmd = new SqlCommand(
|
||||
"INSERT INTO tblImportFbaCustomerReturn ( " +
|
||||
"[return-date], [order-id], sku, asin, fnsku, " +
|
||||
"quantity, [fulfillment-center-id], [detailed-disposition], reason, status, " +
|
||||
"[license-plate-number], [customer-comments] ) " +
|
||||
"VALUES ( " +
|
||||
"@returnDate, @orderId, @sku, @asin, @fnsku, " +
|
||||
"@quantity, @fulfillmentCenterId, @detailedDisposition, @reason, @status, " +
|
||||
"@licensePlateNumber, @customerComments );"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
if (returnDate == "") { insertCmd.Parameters.AddWithValue("@returnDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@returnDate", DateTime.Parse(returnDate).ToUniversalTime()); }
|
||||
if (orderId == "") { insertCmd.Parameters.AddWithValue("@orderId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@orderId", orderId); }
|
||||
if (sku == "") { insertCmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@sku", sku); }
|
||||
if (asin == "") { insertCmd.Parameters.AddWithValue("@asin", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@asin", asin); }
|
||||
if (fnsku == "") { insertCmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (quantity == "") { insertCmd.Parameters.AddWithValue("@quantity", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@quantity", int.Parse(quantity)); }
|
||||
if (fulfillmentCenterId == "") { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId); }
|
||||
if (detailedDisposition == "") { insertCmd.Parameters.AddWithValue("@detailedDisposition", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@detailedDisposition", detailedDisposition); }
|
||||
if (reason == "") { insertCmd.Parameters.AddWithValue("@reason", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@reason", reason); }
|
||||
if (status == "") { insertCmd.Parameters.AddWithValue("@status", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@status", status); }
|
||||
if (licensePlateNumber == "") { insertCmd.Parameters.AddWithValue("@licensePlateNumber", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@licensePlateNumber", licensePlateNumber); }
|
||||
if (customerComments == "") { insertCmd.Parameters.AddWithValue("@customerComments", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@customerComments", customerComments); }
|
||||
|
||||
insertCmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineDuplicateSkip)) + " total new items inserted, " + lineDuplicateSkip + " duplicates were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([return-date]) AS MaxDate FROM tblImportFbaCustomerReturn;"
|
||||
, sqlConn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2015-08-25T00:00:00Z"); //this before first return
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running GetFbaReturnsReport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaInventoryAdjustment : Connection
|
||||
{
|
||||
public AmazonFbaInventoryAdjustment()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineDuplicateSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "adjusted-date");
|
||||
int index02 = Array.IndexOf(headers, "transaction-item-id");
|
||||
int index03 = Array.IndexOf(headers, "fnsku");
|
||||
int index04 = Array.IndexOf(headers, "sku");
|
||||
int index05 = Array.IndexOf(headers, "product-name");
|
||||
int index06 = Array.IndexOf(headers, "fulfillment-center-id");
|
||||
int index07 = Array.IndexOf(headers, "quantity");
|
||||
int index08 = Array.IndexOf(headers, "reason");
|
||||
int index09 = Array.IndexOf(headers, "disposition");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string adjustmentDate = items[index01];
|
||||
string transactionItemId = items[index02];
|
||||
string fnsku = items[index03];
|
||||
string sku = items[index04];
|
||||
string fulfillmentCenterId = items[index06];
|
||||
string quantity = items[index07];
|
||||
string reason = items[index08];
|
||||
string disposition = items[index09];
|
||||
|
||||
// check number of times line combination appears in file
|
||||
// don't think is a nesseary step, the transactionItemId is a unique identifier, I'm 99% sure
|
||||
int fileCount = 0;
|
||||
int dbCount = 0;
|
||||
using (var dupReader = new StreamReader(filePath))
|
||||
{
|
||||
dupReader.ReadLine(); // read header row
|
||||
string dupFileRow;
|
||||
while ((dupFileRow = dupReader.ReadLine()) != null)
|
||||
{
|
||||
string[] dupItems = dupFileRow.Split('\t');
|
||||
if (dupItems.Length != columnCount)
|
||||
{
|
||||
// skip
|
||||
}
|
||||
else
|
||||
{
|
||||
if (items[index01] == dupItems[index01] &&
|
||||
items[index02] == dupItems[index02] &&
|
||||
items[index03] == dupItems[index03] &&
|
||||
items[index06] == dupItems[index06] &&
|
||||
items[index08] == dupItems[index08] &&
|
||||
items[index09] == dupItems[index09]
|
||||
)
|
||||
{
|
||||
// count will always find at least one (itself)
|
||||
fileCount = fileCount + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check for duplicate line in db
|
||||
|
||||
//using (SqlCommand cmd = new SqlCommand(
|
||||
// "SELECT COUNT(ImportFbaInventoryAdjustmentReportID) FROM tblImportFbaInventoryAdjustmentReport " +
|
||||
// "WHERE [adjusted-date]=@adjustmentDate AND [transaction-item-id]=@transactionItemId AND [fnsku]=@fnsku " +
|
||||
// " AND [fulfillment-center-id]=@fulfillmentCenterId AND [reason]=@reason AND [disposition]=@disposition;"
|
||||
// , sqlConn, trans))
|
||||
//{
|
||||
// if (adjustmentDate == "") { cmd.Parameters.AddWithValue("@adjustmentDate", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@adjustmentDate", DateTime.Parse(adjustmentDate).ToUniversalTime()); }
|
||||
// if (transactionItemId == "") { cmd.Parameters.AddWithValue("@transactionItemId", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@transactionItemId", transactionItemId); }
|
||||
// if (fnsku == "") { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
// if (fulfillmentCenterId == "") { cmd.Parameters.AddWithValue("@fulfillmentCenterId", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId); }
|
||||
// if (reason == "") { cmd.Parameters.AddWithValue("@reason", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@reason", reason); }
|
||||
// if (disposition == "") { cmd.Parameters.AddWithValue("@disposition", DBNull.Value); }
|
||||
// else { cmd.Parameters.AddWithValue("@disposition", disposition); }
|
||||
|
||||
// dbCount = (int)cmd.ExecuteScalar();
|
||||
//}
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT COUNT(ImportFbaInventoryAdjustmentReportID) FROM tblImportFbaInventoryAdjustmentReport " +
|
||||
"WHERE [transaction-item-id]=@transactionItemId;"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@transactionItemId", transactionItemId);
|
||||
|
||||
dbCount = (int)cmd.ExecuteScalar();
|
||||
}
|
||||
|
||||
|
||||
if (fileCount <= dbCount)
|
||||
{
|
||||
//skip
|
||||
lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//insert report items
|
||||
using (SqlCommand insertCmd = new SqlCommand(
|
||||
"INSERT INTO tblImportFbaInventoryAdjustmentReport ( " +
|
||||
"[adjusted-date], [transaction-item-id], fnsku, sku, " +
|
||||
"[fulfillment-center-id], quantity, reason, disposition ) " +
|
||||
"VALUES ( " +
|
||||
"@adjustmentDate, @transactionItemId, @fnsku, @sku, " +
|
||||
"@fulfillmentCenterId, @quantity, @reason, @disposition );"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
if (adjustmentDate == "") { insertCmd.Parameters.AddWithValue("@adjustmentDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@adjustmentDate", DateTime.Parse(adjustmentDate).ToUniversalTime()); }
|
||||
if (transactionItemId == "") { insertCmd.Parameters.AddWithValue("@transactionItemId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@transactionItemId", transactionItemId); }
|
||||
if (fnsku == "") { insertCmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (sku == "") { insertCmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@sku", sku); }
|
||||
if (fulfillmentCenterId == "") { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId); }
|
||||
if (quantity == "") { insertCmd.Parameters.AddWithValue("@quantity", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@quantity", int.Parse(quantity)); }
|
||||
if (reason == "") { insertCmd.Parameters.AddWithValue("@reason", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@reason", reason); }
|
||||
if (disposition == "") { insertCmd.Parameters.AddWithValue("@disposition", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@disposition", disposition); }
|
||||
|
||||
insertCmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineDuplicateSkip)) + " total new items inserted, " + lineDuplicateSkip + " duplicates were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running ImportFbaAdustmentReport method, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([adjusted-date]) AS MaxDate FROM tblImportFbaInventoryAdjustmentReport;"
|
||||
, sqlConn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2014-09-01T00:00:00Z");
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running GetFbaAdustmentData, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Transactions;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaInventoryAgeData : Connection
|
||||
{
|
||||
public AmazonFbaInventoryAgeData()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (TransactionScope scope = new TransactionScope())
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
//clear table data
|
||||
using (SqlCommand cmd = new SqlCommand(@"
|
||||
DELETE FROM tblImportFbaInventoryAgeReport;
|
||||
", sqlConn))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineNoStockSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
if (columnCount != 38)
|
||||
{
|
||||
throw new Exception("Chnages found to 'Fba Inventory Age Data' flatfile structure");
|
||||
}
|
||||
|
||||
int index01 = Array.IndexOf(headers, "snapshot-date");
|
||||
int index02 = Array.IndexOf(headers, "marketplace");
|
||||
int index03 = Array.IndexOf(headers, "sku");
|
||||
int index04 = Array.IndexOf(headers, "fnsku");
|
||||
int index05 = Array.IndexOf(headers, "asin");
|
||||
int index06 = Array.IndexOf(headers, "product-name");
|
||||
int index07 = Array.IndexOf(headers, "condition");
|
||||
int index08 = Array.IndexOf(headers, "avaliable-quantity(sellable)");
|
||||
int index09 = Array.IndexOf(headers, "qty-with-removals-in-progress");
|
||||
int index10 = Array.IndexOf(headers, "inv-age-0-to-90-days");
|
||||
int index11 = Array.IndexOf(headers, "inv-age-91-to-180-days");
|
||||
int index12 = Array.IndexOf(headers, "inv-age-181-to-270-days");
|
||||
int index13 = Array.IndexOf(headers, "inv-age-271-to-365-days");
|
||||
int index14 = Array.IndexOf(headers, "inv-age-365-plus-days");
|
||||
int index15 = Array.IndexOf(headers, "currency");
|
||||
int index16 = Array.IndexOf(headers, "qty-to-be-charged-ltsf-6-mo");
|
||||
int index17 = Array.IndexOf(headers, "projected-ltsf-6-mo");
|
||||
int index18 = Array.IndexOf(headers, "qty-to-be-charged-ltsf-12-mo");
|
||||
int index19 = Array.IndexOf(headers, "projected-ltsf-12-mo");
|
||||
int index20 = Array.IndexOf(headers, "units-shipped-last-7-days");
|
||||
int index21 = Array.IndexOf(headers, "units-shipped-last-30-days");
|
||||
int index22 = Array.IndexOf(headers, "units-shipped-last-60-days");
|
||||
int index23 = Array.IndexOf(headers, "units-shipped-last-90-days");
|
||||
int index24 = Array.IndexOf(headers, "alert");
|
||||
int index25 = Array.IndexOf(headers, "your-price");
|
||||
int index26 = Array.IndexOf(headers, "sales_price");
|
||||
int index27 = Array.IndexOf(headers, "lowest_price_new");
|
||||
int index28 = Array.IndexOf(headers, "lowest_price_used");
|
||||
int index29 = Array.IndexOf(headers, "Recommended action");
|
||||
int index30 = Array.IndexOf(headers, "Healthy Inventory Level");
|
||||
int index31 = Array.IndexOf(headers, "Recommended sales price");
|
||||
int index32 = Array.IndexOf(headers, "Recommended sale duration (days)");
|
||||
int index33 = Array.IndexOf(headers, "Recommended Removal Quantity");
|
||||
int index34 = Array.IndexOf(headers, "estimated-cost-savings-of-recommended-actions");
|
||||
int index35 = Array.IndexOf(headers, "sell-through");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string snapshotDate = items[index01];
|
||||
string marketplace = items[index02];
|
||||
string sku = items[index03];
|
||||
string fnsku = items[index04];
|
||||
string asin = items[index05];
|
||||
string productName = items[index06];
|
||||
string condition = items[index07];
|
||||
string avaliableQuantity = items[index08];
|
||||
string qtyWithRemovalsInProgress = items[index09];
|
||||
string invAge0To90Days = items[index10];
|
||||
string invAge91To180Days = items[index11];
|
||||
string invAge181To270Days = items[index12];
|
||||
string invAge271To365Days = items[index13];
|
||||
string invAge365PlusDays = items[index14];
|
||||
string currency = items[index15];
|
||||
string qtyToBeChargedLtsf6Mo = items[index16];
|
||||
string projectedLtsf6Mo = Regex.Replace(items[index17], "[^.0-9]", ""); // strip currency code prefix
|
||||
string qtyToBeChargedLtsf12Mo = items[index18];
|
||||
string projectedLtsf12Mo = Regex.Replace(items[index19], "[^.0-9]", ""); // strip currency code prefix
|
||||
string unitsShippedLast7Days = items[index20];
|
||||
string unitsShippedLast30Days = items[index21];
|
||||
string unitsShippedLast60Days = items[index22];
|
||||
string unitsShippedLast90Days = items[index23];
|
||||
string alert = items[index24];
|
||||
string yourPrice = Regex.Replace(items[index25], "[^.0-9]", ""); // strip currency code prefix
|
||||
string salesPrice = Regex.Replace(items[index26], "[^.0-9]", ""); // strip currency code prefix
|
||||
string lowestPriceNew = Regex.Replace(items[index27], "[^.0-9]", ""); // strip currency code prefix
|
||||
string lowestPriceUsed = Regex.Replace(items[index28], "[^.0-9]", ""); // strip currency code prefix
|
||||
string recommendedAction = items[index29];
|
||||
string healthyInventoryLevel = items[index30];
|
||||
string recommendedSalesPrice = Regex.Replace(items[index31], "[^.0-9]", ""); // strip currency code prefix
|
||||
string recommendedSaleDuration = items[index32];
|
||||
string recommendedRemovalQuantity = items[index33];
|
||||
string estimatedCostSavingsOfRecommendedActions = items[index34];
|
||||
string sellThrough = items[index35];
|
||||
|
||||
using (SqlCommand cmd = new SqlCommand(@"
|
||||
INSERT INTO tblImportFbaInventoryAgeReport(
|
||||
[snapshot-date], marketplace, sku, fnsku, asin, [product-name], condition, [avaliable-quantity(sellable)],
|
||||
[qty-with-removals-in-progress], [inv-age-0-to-90-days], [inv-age-91-to-180-days], [inv-age-181-to-270-days],
|
||||
[inv-age-271-to-365-days], [inv-age-365-plus-days], currency, [qty-to-be-charged-ltsf-6-mo], [projected-ltsf-6-mo],
|
||||
[qty-to-be-charged-ltsf-12-mo], [projected-ltsf-12-mo], [units-shipped-last-7-days], [units-shipped-last-30-days],
|
||||
[units-shipped-last-60-days], [units-shipped-last-90-days], alert, [your-price], sales_price, lowest_price_new,
|
||||
lowest_price_used, [Recommended action], [Healthy Inventory Level], [Recommended sales price],
|
||||
[Recommended sale duration (days)], [Recommended Removal Quantity], [estimated-cost-savings-of-recommended-actions],
|
||||
[sell-through] )
|
||||
VALUES (
|
||||
@snapshotDate, @marketplace, @sku, @fnsku, @asin, @productName, @condition, @avaliableQuantity,
|
||||
@qtyWithRemovalsInProgress, @invAge0To90Days, @invAge91To180Days, @invAge181To270Days, @invAge271To365Days, @invAge365PlusDays, @currency, @qtyToBeChargedLtsf6Mo,
|
||||
@projectedLtsf6Mo, @qtyToBeChargedLtsf12Mo, @projectedLtsf12Mo, @unitsShippedLast7Days, @unitsShippedLast30Days, @unitsShippedLast60Days, @unitsShippedLast90Days, @alert,
|
||||
@yourPrice, @salesPrice, @lowestPriceNew, @lowestPriceUsed, @recommendedAction, @healthyInventoryLevel, @recommendedSalesPrice,
|
||||
@recommendedSaleDuration, @recommendedRemovalQuantity, @estimatedCostSavingsOfRecommendedActions,
|
||||
@sellThrough );
|
||||
", sqlConn))
|
||||
{
|
||||
// add parameters
|
||||
if (snapshotDate.Length == 0) { cmd.Parameters.AddWithValue("@snapshotDate", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@snapshotDate", DateTime.Parse(snapshotDate).ToUniversalTime()); }
|
||||
|
||||
if (marketplace.Length == 0) { cmd.Parameters.AddWithValue("@marketplace", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@marketplace", marketplace); }
|
||||
|
||||
if (sku.Length == 0) { cmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@sku", sku); }
|
||||
|
||||
if (fnsku.Length == 0) { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
|
||||
if (asin.Length == 0) { cmd.Parameters.AddWithValue("@asin", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@asin", asin); }
|
||||
|
||||
if (productName.Length == 0) { cmd.Parameters.AddWithValue("@productName", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@productName", productName); }
|
||||
|
||||
if (condition.Length == 0) { cmd.Parameters.AddWithValue("@condition", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@condition", condition); }
|
||||
|
||||
if (avaliableQuantity.Length == 0) { cmd.Parameters.AddWithValue("@avaliableQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@avaliableQuantity", int.Parse(avaliableQuantity)); }
|
||||
|
||||
if (qtyWithRemovalsInProgress.Length == 0) { cmd.Parameters.AddWithValue("@qtyWithRemovalsInProgress", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@qtyWithRemovalsInProgress", int.Parse(qtyWithRemovalsInProgress)); }
|
||||
|
||||
if (invAge0To90Days.Length == 0) { cmd.Parameters.AddWithValue("@invAge0To90Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@invAge0To90Days", int.Parse(invAge0To90Days)); }
|
||||
|
||||
if (invAge91To180Days.Length == 0) { cmd.Parameters.AddWithValue("@invAge91To180Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@invAge91To180Days", int.Parse(invAge91To180Days)); }
|
||||
|
||||
if (invAge181To270Days.Length == 0) { cmd.Parameters.AddWithValue("@invAge181To270Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@invAge181To270Days", int.Parse(invAge181To270Days)); }
|
||||
|
||||
if (invAge271To365Days.Length == 0) { cmd.Parameters.AddWithValue("@invAge271To365Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@invAge271To365Days", int.Parse(invAge271To365Days)); }
|
||||
|
||||
if (invAge365PlusDays.Length == 0) { cmd.Parameters.AddWithValue("@invAge365PlusDays", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@invAge365PlusDays", int.Parse(invAge365PlusDays)); }
|
||||
|
||||
if (currency.Length == 0) { cmd.Parameters.AddWithValue("@currency", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@currency", currency); }
|
||||
|
||||
if (qtyToBeChargedLtsf6Mo.Length == 0) { cmd.Parameters.AddWithValue("@qtyToBeChargedLtsf6Mo", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@qtyToBeChargedLtsf6Mo", int.Parse(qtyToBeChargedLtsf6Mo)); }
|
||||
|
||||
if (projectedLtsf6Mo.Length == 0) { cmd.Parameters.AddWithValue("@projectedLtsf6Mo", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@projectedLtsf6Mo", decimal.Parse(projectedLtsf6Mo)); }
|
||||
|
||||
if (qtyToBeChargedLtsf12Mo.Length == 0) { cmd.Parameters.AddWithValue("@qtyToBeChargedLtsf12Mo", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@qtyToBeChargedLtsf12Mo", int.Parse(qtyToBeChargedLtsf12Mo)); }
|
||||
|
||||
if (projectedLtsf12Mo.Length == 0) { cmd.Parameters.AddWithValue("@projectedLtsf12Mo", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@projectedLtsf12Mo", decimal.Parse(projectedLtsf12Mo)); }
|
||||
|
||||
if (unitsShippedLast7Days.Length == 0) { cmd.Parameters.AddWithValue("@unitsShippedLast7Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@unitsShippedLast7Days", int.Parse(unitsShippedLast7Days)); }
|
||||
|
||||
if (unitsShippedLast30Days.Length == 0) { cmd.Parameters.AddWithValue("@unitsShippedLast30Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@unitsShippedLast30Days", int.Parse(unitsShippedLast30Days)); }
|
||||
|
||||
if (unitsShippedLast60Days.Length == 0) { cmd.Parameters.AddWithValue("@unitsShippedLast60Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@unitsShippedLast60Days", int.Parse(unitsShippedLast60Days)); }
|
||||
|
||||
if (unitsShippedLast90Days.Length == 0) { cmd.Parameters.AddWithValue("@unitsShippedLast90Days", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@unitsShippedLast90Days", int.Parse(unitsShippedLast90Days)); }
|
||||
|
||||
if (alert.Length == 0) { cmd.Parameters.AddWithValue("@alert", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@alert", alert); }
|
||||
|
||||
if (yourPrice.Length == 0) { cmd.Parameters.AddWithValue("@yourPrice", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@yourPrice", decimal.Parse(yourPrice)); }
|
||||
|
||||
if (salesPrice.Length == 0) { cmd.Parameters.AddWithValue("@salesPrice", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@salesPrice", decimal.Parse(salesPrice)); }
|
||||
|
||||
if (lowestPriceNew.Length == 0) { cmd.Parameters.AddWithValue("@lowestPriceNew", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@lowestPriceNew", decimal.Parse(lowestPriceNew)); }
|
||||
|
||||
if (lowestPriceUsed.Length == 0) { cmd.Parameters.AddWithValue("@lowestPriceUsed", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@lowestPriceUsed", decimal.Parse(lowestPriceUsed)); }
|
||||
|
||||
if (recommendedAction.Length == 0) { cmd.Parameters.AddWithValue("@recommendedAction", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@recommendedAction", recommendedAction); }
|
||||
|
||||
if (healthyInventoryLevel.Length == 0) { cmd.Parameters.AddWithValue("@healthyInventoryLevel", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@healthyInventoryLevel", int.Parse(healthyInventoryLevel)); }
|
||||
|
||||
if (recommendedSalesPrice.Length == 0) { cmd.Parameters.AddWithValue("@recommendedSalesPrice", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@recommendedSalesPrice", decimal.Parse(recommendedSalesPrice)); }
|
||||
|
||||
if (recommendedSaleDuration.Length == 0) { cmd.Parameters.AddWithValue("@recommendedSaleDuration", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@recommendedSaleDuration", int.Parse(recommendedSaleDuration)); }
|
||||
|
||||
if (recommendedRemovalQuantity.Length == 0) { cmd.Parameters.AddWithValue("@recommendedRemovalQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@recommendedRemovalQuantity", int.Parse(recommendedRemovalQuantity)); }
|
||||
|
||||
if (estimatedCostSavingsOfRecommendedActions.Length == 0) { cmd.Parameters.AddWithValue("@estimatedCostSavingsOfRemoval", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@estimatedCostSavingsOfRecommendedActions", decimal.Parse(estimatedCostSavingsOfRecommendedActions)); }
|
||||
|
||||
if (sellThrough.Length == 0) { cmd.Parameters.AddWithValue("@sellThrough", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@sellThrough", decimal.Parse(sellThrough)); }
|
||||
|
||||
// execute the query
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert(
|
||||
"Operation complete. " + lineNumber + " items processes. " + (lineNumber - lineErrorSkip - lineNoStockSkip) + " total new items inserted, "
|
||||
+ lineNoStockSkip + " 'No Stock' records were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.Complete();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Something went wrong during import, check details for more.", 1, ex.ToString());
|
||||
Console.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class ReadFbaInventoryAge : Connection
|
||||
public class AmazonFbaInventoryAgeRead : Connection
|
||||
{
|
||||
public ReadFbaInventoryAge(string sqlConnectionString): base(sqlConnectionString)
|
||||
public AmazonFbaInventoryAgeRead()
|
||||
{
|
||||
|
||||
}
|
||||
@@ -19,7 +19,7 @@ namespace bnhtrade.Core.Data.Database.Import
|
||||
int minAge = 0;
|
||||
int maxAge = 0;
|
||||
|
||||
using (var conn = new SqlConnection(sqlConnectionString))
|
||||
using (var conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
196
src/bnhtrade.Core/Data/Database/Import/AmazonFbaInventoryData.cs
Normal file
196
src/bnhtrade.Core/Data/Database/Import/AmazonFbaInventoryData.cs
Normal file
@@ -0,0 +1,196 @@
|
||||
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 AmazonFbaInventoryData : Connection
|
||||
{
|
||||
|
||||
public AmazonFbaInventoryData()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public void InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (TransactionScope scope = new TransactionScope())
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
//clear table data
|
||||
using (SqlCommand cmd = new SqlCommand(@"
|
||||
DELETE FROM tblImportFbaManageInventory;
|
||||
", sqlConn))
|
||||
{
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineNoStockSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "sku");
|
||||
int index02 = Array.IndexOf(headers, "fnsku");
|
||||
int index03 = Array.IndexOf(headers, "asin");
|
||||
int index04 = Array.IndexOf(headers, "product-name");
|
||||
int index05 = Array.IndexOf(headers, "condition");
|
||||
int index06 = Array.IndexOf(headers, "your-price");
|
||||
int index07 = Array.IndexOf(headers, "mfn-listing-exists");
|
||||
int index08 = Array.IndexOf(headers, "mfn-fulfillable-quantity");
|
||||
int index09 = Array.IndexOf(headers, "afn-listing-exists");
|
||||
int index10 = Array.IndexOf(headers, "afn-warehouse-quantity");
|
||||
int index11 = Array.IndexOf(headers, "afn-fulfillable-quantity");
|
||||
int index12 = Array.IndexOf(headers, "afn-unsellable-quantity");
|
||||
int index13 = Array.IndexOf(headers, "afn-reserved-quantity");
|
||||
int index14 = Array.IndexOf(headers, "afn-total-quantity");
|
||||
int index15 = Array.IndexOf(headers, "per-unit-volume");
|
||||
int index16 = Array.IndexOf(headers, "afn-inbound-working-quantity");
|
||||
int index17 = Array.IndexOf(headers, "afn-inbound-shipped-quantity");
|
||||
int index18 = Array.IndexOf(headers, "afn-inbound-receiving-quantity");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
// only import sku with stock
|
||||
// afnTotalQuantity includes fba stock and inbound shipments
|
||||
string afnTotalQuantity = items[index14];
|
||||
//if (int.Parse(afnTotalQuantity) == 0)
|
||||
//{
|
||||
// lineNoStockSkip = lineNoStockSkip + 1;
|
||||
// continue;
|
||||
//}
|
||||
|
||||
//read values
|
||||
string sku = items[index01];
|
||||
string fnsku = items[index02];
|
||||
string asin = items[index03];
|
||||
string productName = items[index04];
|
||||
string condition = items[index05];
|
||||
string yourPrice = items[index06];
|
||||
string mfnListingExists = items[index07];
|
||||
string mfnFulfillableQuantity = items[index08];
|
||||
string afnListingExists = items[index09];
|
||||
string afnWarehouseQuantity = items[index10];
|
||||
string afnFulfillableQuantity = items[index11];
|
||||
string afnUnsellableQuantity = items[index12];
|
||||
string afnReservedQuantity = items[index13];
|
||||
string perUnitVolume = items[index15];
|
||||
string afnInboundWorkingQuantity = items[index16];
|
||||
string afnInboundShippedQuantity = items[index17];
|
||||
string afnInboundReceivingQuantity = items[index18];
|
||||
|
||||
using (SqlCommand cmd = new SqlCommand(@"
|
||||
INSERT INTO tblImportFbaManageInventory(
|
||||
sku, fnsku, asin, [product-name], condition, [your-price], [mfn-listing-exists], [mfn-fulfillable-quantity],
|
||||
[afn-listing-exists], [afn-warehouse-quantity], [afn-fulfillable-quantity], [afn-unsellable-quantity],
|
||||
[afn-reserved-quantity], [afn-total-quantity], [per-unit-volume], [afn-inbound-working-quantity],
|
||||
[afn-inbound-shipped-quantity], [afn-inbound-receiving-quantity] )
|
||||
VALUES (
|
||||
@sku, @fnsku, @asin, @productName, @condition, @yourPrice, @mfnListingExists, @mfnFulfillableQuantity,
|
||||
@afnListingExists, @afnWarehouseQuantity, @afnFulfillableQuantity, @afnUnsellableQuantity,
|
||||
@afnReservedQuantity, @afnTotalQuantity, @perUnitVolume, @afnInboundWorkingQuantity,
|
||||
@afnInboundShippedQuantity, @afnInboundReceivingQuantity );
|
||||
", sqlConn))
|
||||
{
|
||||
// add parameters
|
||||
cmd.Parameters.AddWithValue("@sku", sku);
|
||||
|
||||
if (fnsku.Length == 0) { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (asin.Length == 0) { cmd.Parameters.AddWithValue("@asin", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@asin", asin); }
|
||||
if (productName.Length == 0) { cmd.Parameters.AddWithValue("@productName", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@productName", productName); }
|
||||
if (condition.Length == 0) { cmd.Parameters.AddWithValue("@condition", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@condition", condition); }
|
||||
if (yourPrice.Length == 0) { cmd.Parameters.AddWithValue("@yourPrice", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@yourPrice", decimal.Parse(yourPrice)); }
|
||||
if (mfnListingExists.Length == 0) { cmd.Parameters.AddWithValue("@mfnListingExists", DBNull.Value); }
|
||||
else if (mfnListingExists == "Yes") { cmd.Parameters.AddWithValue("@mfnListingExists", true); }
|
||||
else { cmd.Parameters.AddWithValue("@mfnListingExists", false); }
|
||||
if (mfnFulfillableQuantity.Length == 0) { cmd.Parameters.AddWithValue("@mfnFulfillableQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@mfnFulfillableQuantity", int.Parse(mfnFulfillableQuantity)); }
|
||||
if (afnListingExists.Length == 0) { cmd.Parameters.AddWithValue("@afnListingExists", DBNull.Value); }
|
||||
else if (afnListingExists == "Yes") { cmd.Parameters.AddWithValue("@afnListingExists", true); }
|
||||
else { cmd.Parameters.AddWithValue("@afnListingExists", false); }
|
||||
if (afnWarehouseQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnWarehouseQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnWarehouseQuantity", int.Parse(afnWarehouseQuantity)); }
|
||||
if (afnFulfillableQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnFulfillableQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnFulfillableQuantity", int.Parse(afnFulfillableQuantity)); }
|
||||
if (afnUnsellableQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnUnsellableQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnUnsellableQuantity", int.Parse(afnUnsellableQuantity)); }
|
||||
if (afnReservedQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnReservedQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnReservedQuantity", int.Parse(afnReservedQuantity)); }
|
||||
if (afnTotalQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnTotalQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnTotalQuantity", int.Parse(afnTotalQuantity)); }
|
||||
if (perUnitVolume.Length == 0) { cmd.Parameters.AddWithValue("@perUnitVolume", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@perUnitVolume", decimal.Parse(perUnitVolume)); }
|
||||
if (afnInboundWorkingQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnInboundWorkingQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnInboundWorkingQuantity", int.Parse(afnInboundWorkingQuantity)); }
|
||||
if (afnInboundShippedQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnInboundShippedQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnInboundShippedQuantity", int.Parse(afnInboundShippedQuantity)); }
|
||||
if (afnInboundReceivingQuantity.Length == 0) { cmd.Parameters.AddWithValue("@afnInboundReceivingQuantity", 0); }
|
||||
else { cmd.Parameters.AddWithValue("@afnInboundReceivingQuantity", int.Parse(afnInboundReceivingQuantity)); }
|
||||
|
||||
|
||||
// execute the query
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert(
|
||||
"Operation complete. " + lineNumber + " items processes. " + (lineNumber - lineErrorSkip - lineNoStockSkip) + " total new items inserted, "
|
||||
+ lineNoStockSkip + " 'No Stock' records were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.Complete();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Something went wrong during import, check details for more.", 1, ex.ToString());
|
||||
Console.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaInventoryReceipt : Connection
|
||||
{
|
||||
public AmazonFbaInventoryReceipt()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool InsertByFlatFile(string filePath, DateTime startDate)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineOutsideScope = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
// create notification if amazon add extra headers
|
||||
if (columnCount > 7)
|
||||
{
|
||||
MiscFunction.EventLogInsert(
|
||||
"Amazon have added a new column to their 'Fba Inventory Receipt' report, you may want to check this out.",
|
||||
2);
|
||||
}
|
||||
|
||||
int indexOfReceivedDate = Array.IndexOf(headers, "received-date");
|
||||
int indexOfFnsku = Array.IndexOf(headers, "fnsku");
|
||||
int indexOfSku = Array.IndexOf(headers, "sku");
|
||||
int indexOfProductName = Array.IndexOf(headers, "product-name");
|
||||
int indexOfQuantity = Array.IndexOf(headers, "quantity");
|
||||
int indexOfFbaShipmentId = Array.IndexOf(headers, "fba-shipment-id");
|
||||
int indexOfFulfillmentCenterId = Array.IndexOf(headers, "fulfillment-center-id");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
DateTime receivedDate = DateTime.Parse(
|
||||
items[indexOfReceivedDate],
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal);
|
||||
|
||||
//ensure line has recieved date <= startdate
|
||||
// due to mws bug, downloaded report can contain records outside of the requested scope
|
||||
if (receivedDate < startDate)
|
||||
{
|
||||
lineOutsideScope = lineOutsideScope + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
string fnsku = items[indexOfFnsku];
|
||||
string sku = items[indexOfSku];
|
||||
int quantity = int.Parse(items[indexOfQuantity]);
|
||||
string fbaShipemntId = items[indexOfFbaShipmentId];
|
||||
string fulfillmentCenterId = items[indexOfFulfillmentCenterId];
|
||||
|
||||
//insert report items
|
||||
using (SqlCommand insertCmd = new SqlCommand(
|
||||
"INSERT INTO tblImportFbaInventoryReceiptReport ( " +
|
||||
"[received-date], [fnsku], [sku], [quantity], [fba-shipment-id], [fulfillment-center-id] ) " +
|
||||
"VALUES ( " +
|
||||
"@receivedDate, @fnsku, @sku, @quantity, @FbaShipmentId, @FulfillmentCenterId );"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
insertCmd.Parameters.AddWithValue("@receivedDate", receivedDate.ToUniversalTime());
|
||||
insertCmd.Parameters.AddWithValue("@fnsku", fnsku);
|
||||
insertCmd.Parameters.AddWithValue("@sku", sku);
|
||||
insertCmd.Parameters.AddWithValue("@quantity", quantity);
|
||||
insertCmd.Parameters.AddWithValue("@fbaShipmentId", fbaShipemntId);
|
||||
insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId);
|
||||
|
||||
insertCmd.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
|
||||
////check for duplicate line in db
|
||||
//using (SqlCommand cmd = new SqlCommand(
|
||||
// "SELECT ImportFbaInventoryReceiptReportID FROM tblImportFbaInventoryReceiptReport " +
|
||||
// "WHERE [received-date]=@receivedDate AND [fnsku]=@fnsku AND [fba-shipment-id]=@fbaShipmentId AND [fulfillment-center-id]=@fulfillmentCenterId;"
|
||||
// , sqlConn, trans))
|
||||
//{
|
||||
// cmd.Parameters.AddWithValue("@receivedDate", receivedDate);
|
||||
// cmd.Parameters.AddWithValue("@fnsku", fnsku);
|
||||
// cmd.Parameters.AddWithValue("@fbaShipmentId", fbaShipemntId);
|
||||
// cmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId);
|
||||
|
||||
// using (SqlDataReader sqlReader = cmd.ExecuteReader())
|
||||
// {
|
||||
// if (sqlReader.HasRows == true)
|
||||
// {
|
||||
// lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// }
|
||||
// }
|
||||
|
||||
//}
|
||||
}
|
||||
}
|
||||
// only commit if records all complete with no errors -- ommiting duplcates relies on all records from one day being committed together
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineOutsideScope)) + " total report items inserted into db, " + lineOutsideScope + " item(s) outside of requested time scope where skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection conn;
|
||||
try
|
||||
{
|
||||
using (conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
conn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([received-date]) AS MaxDate FROM tblImportFbaInventoryReceiptReport;"
|
||||
, conn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2014-09-01T00:00:00Z");
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
291
src/bnhtrade.Core/Data/Database/Import/AmazonFbaReimbursement.cs
Normal file
291
src/bnhtrade.Core/Data/Database/Import/AmazonFbaReimbursement.cs
Normal file
@@ -0,0 +1,291 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaReimbursement : Connection
|
||||
{
|
||||
public AmazonFbaReimbursement()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineDuplicateSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "approval-date");
|
||||
int index02 = Array.IndexOf(headers, "reimbursement-id");
|
||||
int index03 = Array.IndexOf(headers, "case-id");
|
||||
int index04 = Array.IndexOf(headers, "amazon-order-id");
|
||||
int index05 = Array.IndexOf(headers, "reason");
|
||||
int index06 = Array.IndexOf(headers, "sku");
|
||||
int index07 = Array.IndexOf(headers, "fnsku");
|
||||
int index08 = Array.IndexOf(headers, "asin");
|
||||
int index09 = Array.IndexOf(headers, "product-name");
|
||||
int index10 = Array.IndexOf(headers, "condition");
|
||||
int index11 = Array.IndexOf(headers, "currency-unit");
|
||||
int index12 = Array.IndexOf(headers, "amount-per-unit");
|
||||
int index13 = Array.IndexOf(headers, "amount-total");
|
||||
int index14 = Array.IndexOf(headers, "quantity-reimbursed-cash");
|
||||
int index15 = Array.IndexOf(headers, "quantity-reimbursed-inventory");
|
||||
int index16 = Array.IndexOf(headers, "quantity-reimbursed-total");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string approvalDate = items[index01];
|
||||
string reimbursementid = items[index02];
|
||||
string caseid = items[index03];
|
||||
string amazonOrderId = items[index04];
|
||||
string reason = items[index05];
|
||||
string sku = items[index06];
|
||||
string fnsku = items[index07];
|
||||
string asin = items[index08];
|
||||
string productName = items[index09];
|
||||
string condition = items[index10];
|
||||
string currencyUnit = items[index11];
|
||||
string amountPerUnit = items[index12];
|
||||
string amountTotal = items[index13];
|
||||
|
||||
int quantityReimbursedCash = 0;
|
||||
if (items[index14] != "")
|
||||
{ quantityReimbursedCash = int.Parse(items[index14]); }
|
||||
|
||||
int quantityReimbursedInventory = 0;
|
||||
if (items[index15] != "")
|
||||
{ quantityReimbursedInventory = int.Parse(items[index15]); }
|
||||
|
||||
int quantityReimbursedTotal = 0;
|
||||
if (items[index16] != "")
|
||||
{ quantityReimbursedTotal = int.Parse(items[index16]); }
|
||||
|
||||
// totals checks
|
||||
if (quantityReimbursedTotal == 0)
|
||||
{
|
||||
throw new Exception("Total Reimbursed total cannot be zero.");
|
||||
}
|
||||
if (quantityReimbursedCash + quantityReimbursedInventory != quantityReimbursedTotal)
|
||||
{
|
||||
throw new Exception("Reimbursed totals do not tally.");
|
||||
}
|
||||
|
||||
// check number of times line conbination appears in file
|
||||
int fileCount = 0;
|
||||
int dbCount = 0;
|
||||
using (var dupReader = new StreamReader(filePath))
|
||||
{
|
||||
dupReader.ReadLine(); // read header row
|
||||
string dupFileRow;
|
||||
while ((dupFileRow = dupReader.ReadLine()) != null)
|
||||
{
|
||||
string[] dupItems = dupFileRow.Split('\t');
|
||||
if (dupItems.Length != columnCount)
|
||||
{
|
||||
// skip
|
||||
}
|
||||
else
|
||||
{
|
||||
if (items[index01] == dupItems[index01] &&
|
||||
items[index02] == dupItems[index02] &&
|
||||
items[index03] == dupItems[index03] &&
|
||||
items[index04] == dupItems[index04] &&
|
||||
items[index05] == dupItems[index05] &&
|
||||
items[index07] == dupItems[index07] &&
|
||||
items[index13] == dupItems[index13]
|
||||
)
|
||||
{
|
||||
// count will always find at least one (itself)
|
||||
fileCount = fileCount + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//check for duplicate line in db
|
||||
using (SqlCommand cmd = new SqlCommand(@"
|
||||
SELECT
|
||||
COUNT(ImportFbaReimbursementReportID) AS number
|
||||
FROM
|
||||
tblImportFbaReimbursementReport
|
||||
WHERE
|
||||
[reimbursement-id]=@reimbursementid
|
||||
AND ([case-id]=@caseid OR [case-id] IS NULL)
|
||||
AND ([amazon-order-id]=@amazonOrderId OR [amazon-order-id] IS NULL)
|
||||
AND reason=@reason AND fnsku=@fnsku
|
||||
AND [amount-total]=@amountTotal;
|
||||
", sqlConn, trans))
|
||||
{
|
||||
if (reimbursementid == "") { cmd.Parameters.AddWithValue("@reimbursementid", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@reimbursementid", reimbursementid); }
|
||||
if (caseid == "") { cmd.Parameters.AddWithValue("@caseid", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@caseid", caseid); }
|
||||
if (amazonOrderId == "") { cmd.Parameters.AddWithValue("@amazonOrderId", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@amazonOrderId", amazonOrderId); }
|
||||
if (reason == "") { cmd.Parameters.AddWithValue("@reason", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@reason", reason); }
|
||||
if (fnsku == "") { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (amountTotal == "") { cmd.Parameters.AddWithValue("@amountTotal", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@amountTotal", decimal.Parse(amountTotal)); }
|
||||
|
||||
dbCount = (int)cmd.ExecuteScalar();
|
||||
}
|
||||
|
||||
if (fileCount <= dbCount)
|
||||
{
|
||||
//skip
|
||||
lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//insert report items
|
||||
using (SqlCommand insertCmd = new SqlCommand(
|
||||
"INSERT INTO tblImportFbaReimbursementReport ( " +
|
||||
"[approval-date], [reimbursement-id], [case-id], [amazon-order-id], reason, " +
|
||||
"sku, fnsku, asin, condition, [currency-unit], " +
|
||||
"[amount-per-unit], [amount-total], [quantity-reimbursed-cash], [quantity-reimbursed-inventory], [quantity-reimbursed-total] )" +
|
||||
"VALUES ( " +
|
||||
"@approvalDate, @reimbursementid, @caseid, @amazonOrderId, @reason, " +
|
||||
"@sku, @fnsku, @asin, @condition, @currencyUnit, " +
|
||||
"@amountPerUnit, @amountTotal, @quantityReimbursedCash, @quantityReimbursedInventory, @quantityReimbursedTotal );"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
if (approvalDate == "") { insertCmd.Parameters.AddWithValue("@approvalDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@approvalDate", DateTime.Parse(approvalDate).ToUniversalTime()); }
|
||||
if (reimbursementid == "") { insertCmd.Parameters.AddWithValue("@reimbursementid", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@reimbursementid", reimbursementid); }
|
||||
if (caseid == "") { insertCmd.Parameters.AddWithValue("@caseid", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@caseid", caseid); }
|
||||
if (amazonOrderId == "") { insertCmd.Parameters.AddWithValue("@amazonOrderId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@amazonOrderId", amazonOrderId); }
|
||||
if (reason == "") { insertCmd.Parameters.AddWithValue("@reason", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@reason", reason); }
|
||||
if (sku == "") { insertCmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@sku", sku); }
|
||||
if (fnsku == "") { insertCmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (asin == "") { insertCmd.Parameters.AddWithValue("@asin", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@asin", asin); }
|
||||
if (condition == "") { insertCmd.Parameters.AddWithValue("@condition", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@condition", condition); }
|
||||
if (currencyUnit == "") { insertCmd.Parameters.AddWithValue("@currencyUnit", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@currencyUnit", currencyUnit); }
|
||||
if (amountPerUnit == "") { insertCmd.Parameters.AddWithValue("@amountPerUnit", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@amountPerUnit", decimal.Parse(amountPerUnit)); }
|
||||
if (amountTotal == "") { insertCmd.Parameters.AddWithValue("@amountTotal", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@amountTotal", decimal.Parse(amountTotal)); }
|
||||
insertCmd.Parameters.AddWithValue("@quantityReimbursedCash", quantityReimbursedCash);
|
||||
insertCmd.Parameters.AddWithValue("@quantityReimbursedInventory", quantityReimbursedInventory);
|
||||
insertCmd.Parameters.AddWithValue("@quantityReimbursedTotal", quantityReimbursedTotal);
|
||||
|
||||
insertCmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineDuplicateSkip)) + " total new items inserted, " + lineDuplicateSkip + " duplicates were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running ImportFbaReimbursementReport method, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([approval-date]) AS MaxDate FROM tblImportFbaReimbursementReport;"
|
||||
, sqlConn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2014-09-01T00:00:00Z");
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running GetFbaReimbursementData, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
240
src/bnhtrade.Core/Data/Database/Import/AmazonFbaRemovalOrder.cs
Normal file
240
src/bnhtrade.Core/Data/Database/Import/AmazonFbaRemovalOrder.cs
Normal file
@@ -0,0 +1,240 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaRemovalOrder : Connection
|
||||
{
|
||||
public AmazonFbaRemovalOrder()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public bool InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineUpdate = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "request-date");
|
||||
int index02 = Array.IndexOf(headers, "order-id");
|
||||
int index03 = Array.IndexOf(headers, "order-type");
|
||||
int index04 = Array.IndexOf(headers, "service-speed");
|
||||
int index05 = Array.IndexOf(headers, "order-status");
|
||||
int index06 = Array.IndexOf(headers, "last-updated-date");
|
||||
int index07 = Array.IndexOf(headers, "sku");
|
||||
int index08 = Array.IndexOf(headers, "fnsku");
|
||||
int index09 = Array.IndexOf(headers, "disposition");
|
||||
int index10 = Array.IndexOf(headers, "requested-quantity");
|
||||
int index11 = Array.IndexOf(headers, "cancelled-quantity");
|
||||
int index12 = Array.IndexOf(headers, "disposed-quantity");
|
||||
int index13 = Array.IndexOf(headers, "shipped-quantity");
|
||||
int index14 = Array.IndexOf(headers, "in-process-quantity");
|
||||
int index15 = Array.IndexOf(headers, "removal-fee");
|
||||
int index16 = Array.IndexOf(headers, "currency");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string requestDate = items[index01];
|
||||
string orderId = items[index02];
|
||||
string orderType = items[index03];
|
||||
string serviceSpeed = items[index04];
|
||||
string orderStatus = items[index05];
|
||||
string lastUpdatedDate = items[index06];
|
||||
string sku = items[index07];
|
||||
string fnsku = items[index08];
|
||||
string disposition = items[index09];
|
||||
string requestedQuantity = items[index10];
|
||||
string cancelledQuantity = items[index11];
|
||||
string disposedQuantity = items[index12];
|
||||
string shippedQuantity = items[index13];
|
||||
string inProcessQuantity = items[index14];
|
||||
string removalFee = items[index15];
|
||||
string currency = items[index16];
|
||||
|
||||
if (orderId == "") { continue; }
|
||||
int importTableId = 0;
|
||||
|
||||
//check for existing orderId
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT ImportFbaRemovalOrderReportID FROM tblImportFbaRemovalOrderReport WHERE [order-id]=@orderId AND fnsku=@fnsku AND disposition=@disposition;"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@orderId", orderId);
|
||||
cmd.Parameters.AddWithValue("@fnsku", fnsku);
|
||||
cmd.Parameters.AddWithValue("@disposition", disposition);
|
||||
importTableId = Convert.ToInt32(cmd.ExecuteScalar());
|
||||
}
|
||||
|
||||
string sqlQuery;
|
||||
if (importTableId > 0)
|
||||
{
|
||||
// update
|
||||
lineUpdate = lineUpdate + 1;
|
||||
sqlQuery =
|
||||
"UPDATE tblImportFbaRemovalOrderReport SET " +
|
||||
"[request-date]=@requestDate, [order-id]=@orderId, [order-type]=@orderType, [service-speed]=@serviceSpeed, " +
|
||||
"[order-status]=@orderStatus, [last-updated-date]=@lastUpdatedDate, sku=@sku, fnsku=@fnsku, " +
|
||||
"disposition=@disposition, [requested-quantity]=@requestedQuantity, [cancelled-quantity]=@cancelledQuantity, [disposed-quantity]=@disposedQuantity, " +
|
||||
"[shipped-quantity]=@shippedQuantity, [in-process-quantity]=@inProcessQuantity, [removal-fee]=@removalFee, currency=@currency " +
|
||||
"WHERE ImportFbaRemovalOrderReportID=@importTableId;";
|
||||
}
|
||||
else
|
||||
{
|
||||
// insert
|
||||
sqlQuery =
|
||||
"INSERT INTO tblImportFbaRemovalOrderReport ( " +
|
||||
"[request-date], [order-id], [order-type], [service-speed], [order-status], [last-updated-date], sku, fnsku, " +
|
||||
"disposition, [requested-quantity], [cancelled-quantity], [disposed-quantity], [shipped-quantity], [in-process-quantity], [removal-fee], currency ) " +
|
||||
"VALUES ( " +
|
||||
"@requestDate, @orderId, @orderType, @serviceSpeed, @orderStatus, @lastUpdatedDate, @sku, @fnsku, " +
|
||||
"@disposition, @requestedQuantity, @cancelledQuantity, @disposedQuantity, @shippedQuantity, @inProcessQuantity, @removalFee, @currency );";
|
||||
}
|
||||
|
||||
// make the update/insert
|
||||
using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
cmd.Parameters.AddWithValue("@importTableId", importTableId);
|
||||
if (requestDate == "") { cmd.Parameters.AddWithValue("@requestDate", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@requestDate", DateTime.Parse(requestDate).ToUniversalTime()); }
|
||||
if (orderId == "") { cmd.Parameters.AddWithValue("@orderId", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@orderId", orderId); }
|
||||
if (orderType == "") { cmd.Parameters.AddWithValue("@orderType", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@orderType", orderType); }
|
||||
if (serviceSpeed == "") { cmd.Parameters.AddWithValue("@serviceSpeed", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@serviceSpeed", serviceSpeed); }
|
||||
if (orderStatus == "") { cmd.Parameters.AddWithValue("@orderStatus", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@orderStatus", orderStatus); }
|
||||
if (lastUpdatedDate == "") { cmd.Parameters.AddWithValue("@lastUpdatedDate", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@lastUpdatedDate", DateTime.Parse(lastUpdatedDate).ToUniversalTime()); }
|
||||
if (sku == "") { cmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@sku", sku); }
|
||||
if (fnsku == "") { cmd.Parameters.AddWithValue("@fnsku", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@fnsku", fnsku); }
|
||||
if (disposition == "") { cmd.Parameters.AddWithValue("@disposition", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@disposition", disposition); }
|
||||
if (requestedQuantity == "") { cmd.Parameters.AddWithValue("@requestedQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@requestedQuantity", int.Parse(requestedQuantity)); }
|
||||
if (cancelledQuantity == "") { cmd.Parameters.AddWithValue("@cancelledQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@cancelledQuantity", int.Parse(cancelledQuantity)); }
|
||||
if (disposedQuantity == "") { cmd.Parameters.AddWithValue("@disposedQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@disposedQuantity", int.Parse(disposedQuantity)); }
|
||||
if (shippedQuantity == "") { cmd.Parameters.AddWithValue("@shippedQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@shippedQuantity", int.Parse(shippedQuantity)); }
|
||||
if (inProcessQuantity == "") { cmd.Parameters.AddWithValue("@inProcessQuantity", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@inProcessQuantity", int.Parse(inProcessQuantity)); }
|
||||
if (removalFee == "") { cmd.Parameters.AddWithValue("@removalFee", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@removalFee", decimal.Parse(removalFee)); }
|
||||
if (currency == "") { cmd.Parameters.AddWithValue("@currency", DBNull.Value); }
|
||||
else { cmd.Parameters.AddWithValue("@currency", currency); }
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert("ImportFbaRemovalOrderReport() " + (lineNumber - (1 + lineErrorSkip + lineUpdate)) + " records created, " + lineUpdate + " records updated.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running ImportFbaRemovalOrderReport method, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([request-date]) AS MaxDate FROM tblImportFbaRemovalOrderReport;"
|
||||
, sqlConn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2015-09-15T00:00:00Z");
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
lastRecordDate = lastRecordDate.AddDays(-30); // yes, that's right -30 days
|
||||
//startTime = DateTime.Parse("2015-05-01T00:00:00Z");
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running GetFbaRemovalOrderReport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
665
src/bnhtrade.Core/Data/Database/Import/AmazonFbaSaleShipment.cs
Normal file
665
src/bnhtrade.Core/Data/Database/Import/AmazonFbaSaleShipment.cs
Normal file
@@ -0,0 +1,665 @@
|
||||
using Dapper;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class AmazonFbaSaleShipment : Connection
|
||||
{
|
||||
public AmazonFbaSaleShipment()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
// seems amazon have reduced the number of columns in the table significantly, probably due data protection. This is the
|
||||
// old one
|
||||
public bool InsertByFlatFile(string filePath)
|
||||
{
|
||||
SqlConnection sqlConn;
|
||||
SqlTransaction trans;
|
||||
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (trans = sqlConn.BeginTransaction())
|
||||
using (var reader = new StreamReader(filePath))
|
||||
{
|
||||
//read file one line at a time and insert data into table if required
|
||||
int lineNumber = 1;
|
||||
int lineErrorSkip = 0;
|
||||
int lineDuplicateSkip = 0;
|
||||
|
||||
// read header and retrive information
|
||||
string headerRow = reader.ReadLine();
|
||||
string[] headers = headerRow.Split('\t');
|
||||
|
||||
int columnCount = headers.Length;
|
||||
|
||||
int index01 = Array.IndexOf(headers, "amazon-order-id");
|
||||
int index02 = Array.IndexOf(headers, "merchant-order-id");
|
||||
int index03 = Array.IndexOf(headers, "shipment-id");
|
||||
int index04 = Array.IndexOf(headers, "shipment-item-id");
|
||||
int index05 = Array.IndexOf(headers, "amazon-order-item-id");
|
||||
int index06 = Array.IndexOf(headers, "merchant-order-item-id");
|
||||
int index07 = Array.IndexOf(headers, "purchase-date");
|
||||
int index08 = Array.IndexOf(headers, "payments-date");
|
||||
int index09 = Array.IndexOf(headers, "shipment-date");
|
||||
int index10 = Array.IndexOf(headers, "reporting-date");
|
||||
int index11 = Array.IndexOf(headers, "buyer-email");
|
||||
int index12 = Array.IndexOf(headers, "buyer-name");
|
||||
int index13 = Array.IndexOf(headers, "sku");
|
||||
int index14 = Array.IndexOf(headers, "quantity-shipped");
|
||||
int index15 = Array.IndexOf(headers, "currency");
|
||||
int index16 = Array.IndexOf(headers, "item-price");
|
||||
int index17 = Array.IndexOf(headers, "item-tax");
|
||||
int index18 = Array.IndexOf(headers, "shipping-price");
|
||||
int index19 = Array.IndexOf(headers, "shipping-tax");
|
||||
int index20 = Array.IndexOf(headers, "gift-wrap-price");
|
||||
int index21 = Array.IndexOf(headers, "gift-wrap-tax");
|
||||
int index22 = Array.IndexOf(headers, "recipient-name");
|
||||
int index23 = Array.IndexOf(headers, "ship-address-1");
|
||||
int index24 = Array.IndexOf(headers, "ship-address-2");
|
||||
int index25 = Array.IndexOf(headers, "ship-address-3");
|
||||
int index26 = Array.IndexOf(headers, "ship-city");
|
||||
int index27 = Array.IndexOf(headers, "ship-state");
|
||||
int index28 = Array.IndexOf(headers, "ship-postal-code");
|
||||
int index29 = Array.IndexOf(headers, "ship-country");
|
||||
int index30 = Array.IndexOf(headers, "ship-phone-number");
|
||||
int index31 = Array.IndexOf(headers, "bill-address-1");
|
||||
int index32 = Array.IndexOf(headers, "bill-address-2");
|
||||
int index33 = Array.IndexOf(headers, "bill-address-3");
|
||||
int index34 = Array.IndexOf(headers, "bill-city");
|
||||
int index35 = Array.IndexOf(headers, "bill-state");
|
||||
int index36 = Array.IndexOf(headers, "bill-postal-code");
|
||||
int index37 = Array.IndexOf(headers, "bill-country");
|
||||
int index38 = Array.IndexOf(headers, "item-promotion-discount");
|
||||
int index39 = Array.IndexOf(headers, "ship-promotion-discount");
|
||||
int index40 = Array.IndexOf(headers, "fulfillment-center-id");
|
||||
int index41 = Array.IndexOf(headers, "fulfillment-channel");
|
||||
int index42 = Array.IndexOf(headers, "sales-channel");
|
||||
|
||||
string fileRow;
|
||||
while ((fileRow = reader.ReadLine()) != null)
|
||||
{
|
||||
lineNumber = lineNumber + 1;
|
||||
Console.Write("\rParsing record: " + lineNumber);
|
||||
//split line into array
|
||||
string[] items = fileRow.Split('\t');
|
||||
if (items.Length != columnCount)
|
||||
{
|
||||
// skip line
|
||||
lineErrorSkip = lineErrorSkip + 1;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
filePath
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
//read values
|
||||
string amazonOrderId = items[index01];
|
||||
string merchantOrderid = items[index02];
|
||||
string shipmentId = items[index03];
|
||||
string shipmentItemId = items[index04];
|
||||
string amazonOrderItemId = items[index05];
|
||||
string merchantOrderItemId = items[index06];
|
||||
DateTime purchaseDate = DateTime.Parse(items[index07]);
|
||||
DateTime paymentsDate = DateTime.Parse(items[index08]);
|
||||
DateTime shipmentDate = DateTime.Parse(items[index09]);
|
||||
DateTime reportingDate = DateTime.Parse(items[index10]);
|
||||
string buyerEmail = items[index11];
|
||||
string buyerName = items[index12];
|
||||
string sku = items[index13];
|
||||
int quantityShipped = Int32.Parse(items[index14]);
|
||||
string currency = items[index15];
|
||||
decimal itemPrice = decimal.Parse(items[index16]);
|
||||
decimal itemTax = decimal.Parse(items[index17]);
|
||||
decimal shippingPrice = decimal.Parse(items[index18]);
|
||||
decimal shippingTax = decimal.Parse(items[index19]);
|
||||
decimal giftWrapPrice = decimal.Parse(items[index20]);
|
||||
decimal giftWrapTax = decimal.Parse(items[index21]);
|
||||
string recipientName = items[index22];
|
||||
string shipAddress1 = items[index23];
|
||||
string shipAddress2 = items[index24];
|
||||
string shipAddress3 = items[index25];
|
||||
string shipCity = items[index26];
|
||||
string shipState = items[index27];
|
||||
string shipPostalCode = items[index28];
|
||||
string shipCountry = items[index29];
|
||||
string shipPhoneNumber = items[index30];
|
||||
string billAddress1 = items[index31];
|
||||
string billAddress2 = items[index32];
|
||||
string billAddress3 = items[index33];
|
||||
string billCity = items[index34];
|
||||
string billState = items[index35];
|
||||
string billPostalCode = items[index36];
|
||||
string billCountry = items[index37];
|
||||
string itemPromotionDiscount = items[index38];
|
||||
string shipPromotionDiscount = items[index39];
|
||||
string fulfillmentCenterId = items[index40];
|
||||
string fulfillmentChannel = items[index41];
|
||||
string salesChannel = items[index42];
|
||||
|
||||
//check for duplicate line in db
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT ImportFbaSaleShipmentID FROM tblImportFbaSaleShipment " +
|
||||
"WHERE [shipment-item-id]=@shipmentItemId;"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@shipmentItemId", shipmentItemId);
|
||||
|
||||
using (SqlDataReader sqlReader = cmd.ExecuteReader())
|
||||
{
|
||||
if (sqlReader.Read())
|
||||
{
|
||||
lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//insert report items
|
||||
|
||||
//start transaction
|
||||
|
||||
|
||||
using (SqlCommand insertCmd = new SqlCommand(
|
||||
"INSERT INTO tblImportFbaSaleShipment ( " +
|
||||
"[amazon-order-id], [merchant-order-id], [shipment-id], [shipment-item-id], [amazon-order-item-id], " +
|
||||
"[merchant-order-item-id], [purchase-date], [payments-date], [shipment-date], [reporting-date], " +
|
||||
"[buyer-email], [buyer-name], sku, [quantity-shipped], currency, " +
|
||||
"[item-price], [item-tax], [shipping-price], [shipping-tax], [gift-wrap-price], " +
|
||||
"[gift-wrap-tax], [recipient-name], [ship-address-1], [ship-address-2], [ship-address-3], " +
|
||||
"[ship-city], [ship-state], [ship-postal-code], [ship-country], [ship-phone-number], " +
|
||||
"[bill-address-1], [bill-address-2], [bill-address-3], [bill-city], [bill-state], " +
|
||||
"[bill-postal-code], [bill-country], [item-promotion-discount], [ship-promotion-discount], [fulfillment-center-id], " +
|
||||
"[fulfillment-channel], [sales-channel] ) " +
|
||||
"VALUES ( " +
|
||||
"@amazonOrderId, @merchantOrderid, @shipmentId, @shipmentItemId, @amazonOrderItemId, " +
|
||||
"@merchantOrderItemId, @purchaseDate, @paymentsDate, @shipmentDate, @reportingDate, " +
|
||||
"@buyerEmail, @buyerName, @sku, @quantityShipped, @currency, " +
|
||||
"@itemPrice, @itemTax, @shippingPrice, @shippingTax, @giftWrapPrice, " +
|
||||
"@giftWrapTax, @recipientName, @shipAddress1, @shipAddress2, @shipAddress3, " +
|
||||
"@shipCity, @shipState, @shipPostalCode, @shipCountry, @shipPhoneNumber, " +
|
||||
"@billAddress1, @billAddress2, @billAddress3, @billCity, @billState, " +
|
||||
"@billPostalCode, @billCountry, @itemPromotionDiscount, @shipPromotionDiscount, @fulfillmentCenterId, " +
|
||||
"@fulfillmentChannel, @salesChannel );"
|
||||
, sqlConn, trans))
|
||||
{
|
||||
// add parameters
|
||||
if (amazonOrderId == "") { insertCmd.Parameters.AddWithValue("@amazonOrderId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@amazonOrderId", amazonOrderId); }
|
||||
if (merchantOrderid == "") { insertCmd.Parameters.AddWithValue("@merchantOrderid", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@merchantOrderid", merchantOrderid); }
|
||||
if (shipmentId == "") { insertCmd.Parameters.AddWithValue("@shipmentId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipmentId", shipmentId); }
|
||||
if (shipmentItemId == "") { insertCmd.Parameters.AddWithValue("@shipmentItemId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipmentItemId", shipmentItemId); }
|
||||
if (amazonOrderItemId == "") { insertCmd.Parameters.AddWithValue("@amazonOrderItemId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@amazonOrderItemId", amazonOrderItemId); }
|
||||
if (merchantOrderItemId == "") { insertCmd.Parameters.AddWithValue("@merchantOrderItemId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@merchantOrderItemId", merchantOrderItemId); }
|
||||
if (purchaseDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@purchaseDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@purchaseDate", purchaseDate.ToUniversalTime()); }
|
||||
if (paymentsDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@paymentsDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@paymentsDate", paymentsDate.ToUniversalTime()); }
|
||||
if (shipmentDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@shipmentDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipmentDate", shipmentDate.ToUniversalTime()); }
|
||||
if (reportingDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@reportingDate", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@reportingDate", reportingDate.ToUniversalTime()); }
|
||||
if (buyerEmail == "") { insertCmd.Parameters.AddWithValue("@buyerEmail", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@buyerEmail", buyerEmail); }
|
||||
if (buyerName == "") { insertCmd.Parameters.AddWithValue("@buyerName", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@buyerName", buyerName); }
|
||||
if (sku == "") { insertCmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@sku", sku); }
|
||||
insertCmd.Parameters.AddWithValue("@quantityShipped", quantityShipped);
|
||||
if (currency == "") { insertCmd.Parameters.AddWithValue("@currency", DBNull.Value); }
|
||||
insertCmd.Parameters.AddWithValue("@currency", currency);
|
||||
insertCmd.Parameters.AddWithValue("@itemPrice", itemPrice);
|
||||
insertCmd.Parameters.AddWithValue("@itemTax", itemTax);
|
||||
insertCmd.Parameters.AddWithValue("@shippingPrice", shippingPrice);
|
||||
insertCmd.Parameters.AddWithValue("@shippingTax", shippingTax);
|
||||
insertCmd.Parameters.AddWithValue("@giftWrapPrice", giftWrapPrice);
|
||||
insertCmd.Parameters.AddWithValue("@giftWrapTax", giftWrapTax);
|
||||
if (recipientName == "") { insertCmd.Parameters.AddWithValue("@recipientName", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@recipientName", recipientName); }
|
||||
if (shipAddress1 == "") { insertCmd.Parameters.AddWithValue("@shipAddress1", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipAddress1", shipAddress1); }
|
||||
if (shipAddress2 == "") { insertCmd.Parameters.AddWithValue("@shipAddress2", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipAddress2", shipAddress2); }
|
||||
if (shipAddress3 == "") { insertCmd.Parameters.AddWithValue("@shipAddress3", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipAddress3", shipAddress3); }
|
||||
if (shipCity == "") { insertCmd.Parameters.AddWithValue("@shipCity", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipCity", shipCity); }
|
||||
if (shipState == "") { insertCmd.Parameters.AddWithValue("@shipState", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipState", shipState); }
|
||||
if (shipPostalCode == "") { insertCmd.Parameters.AddWithValue("@shipPostalCode", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipPostalCode", shipPostalCode); }
|
||||
if (shipCountry == "") { insertCmd.Parameters.AddWithValue("@shipCountry", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipCountry", shipCountry); }
|
||||
if (shipPhoneNumber == "") { insertCmd.Parameters.AddWithValue("@shipPhoneNumber", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipPhoneNumber", shipPhoneNumber); }
|
||||
if (billAddress1 == "") { insertCmd.Parameters.AddWithValue("@billAddress1", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billAddress1", billAddress1); }
|
||||
if (billAddress2 == "") { insertCmd.Parameters.AddWithValue("@billAddress2", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billAddress2", billAddress2); }
|
||||
if (billAddress3 == "") { insertCmd.Parameters.AddWithValue("@billAddress3", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billAddress3", billAddress3); }
|
||||
if (billCity == "") { insertCmd.Parameters.AddWithValue("@billCity", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billCity", billCity); }
|
||||
if (billState == "") { insertCmd.Parameters.AddWithValue("@billState", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billState", billState); }
|
||||
if (billPostalCode == "") { insertCmd.Parameters.AddWithValue("@billPostalCode", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billPostalCode", billPostalCode); }
|
||||
if (billCountry == "") { insertCmd.Parameters.AddWithValue("@billCountry", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@billCountry", billCountry); }
|
||||
if (itemPromotionDiscount == "") { insertCmd.Parameters.AddWithValue("@itemPromotionDiscount", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@itemPromotionDiscount", itemPromotionDiscount); }
|
||||
if (shipPromotionDiscount == "") { insertCmd.Parameters.AddWithValue("@shipPromotionDiscount", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@shipPromotionDiscount", shipPromotionDiscount); }
|
||||
if (fulfillmentCenterId == "") { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId); }
|
||||
if (fulfillmentChannel == "") { insertCmd.Parameters.AddWithValue("@fulfillmentChannel", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@fulfillmentChannel", fulfillmentChannel); }
|
||||
if (salesChannel == "") { insertCmd.Parameters.AddWithValue("@salesChannel", DBNull.Value); }
|
||||
else { insertCmd.Parameters.AddWithValue("@salesChannel", salesChannel); }
|
||||
|
||||
insertCmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
trans.Commit();
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineDuplicateSkip)) + " total new items inserted, " + lineDuplicateSkip + " duplicates were skipped.");
|
||||
if (lineErrorSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//public bool InsertByFlatFileold(string filePath)
|
||||
//{
|
||||
// SqlConnection sqlConn;
|
||||
// SqlTransaction trans;
|
||||
// //try
|
||||
// //{
|
||||
// using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
// {
|
||||
// sqlConn.Open();
|
||||
// using (trans = sqlConn.BeginTransaction())
|
||||
// using (var reader = new StreamReader(filePath))
|
||||
// {
|
||||
// //read file one line at a time and insert data into table if required
|
||||
// int lineNumber = 1;
|
||||
// int lineErrorSkip = 0;
|
||||
// int lineDuplicateSkip = 0;
|
||||
|
||||
// // read header and retrive information
|
||||
// string headerRow = reader.ReadLine();
|
||||
// string[] headers = headerRow.Split('\t');
|
||||
|
||||
// int columnCount = headers.Length;
|
||||
|
||||
// int index01 = Array.IndexOf(headers, "amazon-order-id");
|
||||
// int index09 = Array.IndexOf(headers, "shipment-date");
|
||||
// int index13 = Array.IndexOf(headers, "sku");
|
||||
// int index14 = Array.IndexOf(headers, "quantity");
|
||||
// int index15 = Array.IndexOf(headers, "currency");
|
||||
// int index16 = Array.IndexOf(headers, "item-price-per-unit");
|
||||
// int index18 = Array.IndexOf(headers, "shipping-price");
|
||||
// int index20 = Array.IndexOf(headers, "gift-wrap-price");
|
||||
// int index26 = Array.IndexOf(headers, "ship-city");
|
||||
// int index27 = Array.IndexOf(headers, "ship-state");
|
||||
// int index28 = Array.IndexOf(headers, "ship-postal-code");
|
||||
// int index40 = Array.IndexOf(headers, "fulfillment-center-id");
|
||||
|
||||
// string fileRow;
|
||||
// while ((fileRow = reader.ReadLine()) != null)
|
||||
// {
|
||||
// lineNumber = lineNumber + 1;
|
||||
// Console.Write("\rParsing record: " + lineNumber);
|
||||
// //split line into array
|
||||
// string[] items = fileRow.Split('\t');
|
||||
// if (items.Length != columnCount)
|
||||
// {
|
||||
// // skip line
|
||||
// lineErrorSkip = lineErrorSkip + 1;
|
||||
// MiscFunction.EventLogInsert(
|
||||
// "Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
// 2,
|
||||
// filePath
|
||||
// );
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //read values
|
||||
// string amazonOrderId = items[index01];
|
||||
// DateTime shipmentDate = DateTime.Parse(items[index09]);
|
||||
// string sku = items[index13];
|
||||
// int quantityShipped = Int32.Parse(items[index14]);
|
||||
// string currency = items[index15];
|
||||
// decimal itemPrice = decimal.Parse(items[index16]);
|
||||
// decimal shippingPrice = decimal.Parse(items[index18]);
|
||||
// decimal giftWrapPrice = decimal.Parse(items[index20]);
|
||||
// string shipCity = items[index26];
|
||||
// string shipState = items[index27];
|
||||
// string shipPostalCode = items[index28];
|
||||
// string fulfillmentCenterId = items[index40];
|
||||
|
||||
// //check for duplicate line in db
|
||||
// using (SqlCommand cmd = new SqlCommand(
|
||||
// "SELECT ImportFbaSaleShipmentID FROM tblImportFbaSaleShipment " +
|
||||
// "WHERE [shipment-item-id]=@shipmentItemId;"
|
||||
// , sqlConn, trans))
|
||||
// {
|
||||
// cmd.Parameters.AddWithValue("@shipmentItemId", shipmentItemId);
|
||||
|
||||
// using (SqlDataReader sqlReader = cmd.ExecuteReader())
|
||||
// {
|
||||
// if (sqlReader.Read())
|
||||
// {
|
||||
// lineDuplicateSkip = lineDuplicateSkip + 1;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// //insert report items
|
||||
|
||||
// //start transaction
|
||||
|
||||
|
||||
// using (SqlCommand insertCmd = new SqlCommand(
|
||||
// "INSERT INTO tblImportFbaSaleShipment ( " +
|
||||
// "[amazon-order-id], [merchant-order-id], [shipment-id], [shipment-item-id], [amazon-order-item-id], " +
|
||||
// "[merchant-order-item-id], [purchase-date], [payments-date], [shipment-date], [reporting-date], " +
|
||||
// "[buyer-email], [buyer-name], sku, [quantity-shipped], currency, " +
|
||||
// "[item-price], [item-tax], [shipping-price], [shipping-tax], [gift-wrap-price], " +
|
||||
// "[gift-wrap-tax], [recipient-name], [ship-address-1], [ship-address-2], [ship-address-3], " +
|
||||
// "[ship-city], [ship-state], [ship-postal-code], [ship-country], [ship-phone-number], " +
|
||||
// "[bill-address-1], [bill-address-2], [bill-address-3], [bill-city], [bill-state], " +
|
||||
// "[bill-postal-code], [bill-country], [item-promotion-discount], [ship-promotion-discount], [fulfillment-center-id], " +
|
||||
// "[fulfillment-channel], [sales-channel] ) " +
|
||||
// "VALUES ( " +
|
||||
// "@amazonOrderId, @merchantOrderid, @shipmentId, @shipmentItemId, @amazonOrderItemId, " +
|
||||
// "@merchantOrderItemId, @purchaseDate, @paymentsDate, @shipmentDate, @reportingDate, " +
|
||||
// "@buyerEmail, @buyerName, @sku, @quantityShipped, @currency, " +
|
||||
// "@itemPrice, @itemTax, @shippingPrice, @shippingTax, @giftWrapPrice, " +
|
||||
// "@giftWrapTax, @recipientName, @shipAddress1, @shipAddress2, @shipAddress3, " +
|
||||
// "@shipCity, @shipState, @shipPostalCode, @shipCountry, @shipPhoneNumber, " +
|
||||
// "@billAddress1, @billAddress2, @billAddress3, @billCity, @billState, " +
|
||||
// "@billPostalCode, @billCountry, @itemPromotionDiscount, @shipPromotionDiscount, @fulfillmentCenterId, " +
|
||||
// "@fulfillmentChannel, @salesChannel );"
|
||||
// , sqlConn, trans))
|
||||
// {
|
||||
// // add parameters
|
||||
// if (amazonOrderId == "") { insertCmd.Parameters.AddWithValue("@amazonOrderId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@amazonOrderId", amazonOrderId); }
|
||||
// if (merchantOrderid == "") { insertCmd.Parameters.AddWithValue("@merchantOrderid", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@merchantOrderid", merchantOrderid); }
|
||||
// if (shipmentId == "") { insertCmd.Parameters.AddWithValue("@shipmentId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipmentId", shipmentId); }
|
||||
// if (shipmentItemId == "") { insertCmd.Parameters.AddWithValue("@shipmentItemId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipmentItemId", shipmentItemId); }
|
||||
// if (amazonOrderItemId == "") { insertCmd.Parameters.AddWithValue("@amazonOrderItemId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@amazonOrderItemId", amazonOrderItemId); }
|
||||
// if (merchantOrderItemId == "") { insertCmd.Parameters.AddWithValue("@merchantOrderItemId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@merchantOrderItemId", merchantOrderItemId); }
|
||||
// if (purchaseDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@purchaseDate", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@purchaseDate", purchaseDate.ToUniversalTime()); }
|
||||
// if (paymentsDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@paymentsDate", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@paymentsDate", paymentsDate.ToUniversalTime()); }
|
||||
// if (shipmentDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@shipmentDate", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipmentDate", shipmentDate.ToUniversalTime()); }
|
||||
// if (reportingDate == DateTime.MinValue) { insertCmd.Parameters.AddWithValue("@reportingDate", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@reportingDate", reportingDate.ToUniversalTime()); }
|
||||
// if (buyerEmail == "") { insertCmd.Parameters.AddWithValue("@buyerEmail", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@buyerEmail", buyerEmail); }
|
||||
// if (buyerName == "") { insertCmd.Parameters.AddWithValue("@buyerName", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@buyerName", buyerName); }
|
||||
// if (sku == "") { insertCmd.Parameters.AddWithValue("@sku", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@sku", sku); }
|
||||
// insertCmd.Parameters.AddWithValue("@quantityShipped", quantityShipped);
|
||||
// if (currency == "") { insertCmd.Parameters.AddWithValue("@currency", DBNull.Value); }
|
||||
// insertCmd.Parameters.AddWithValue("@currency", currency);
|
||||
// insertCmd.Parameters.AddWithValue("@itemPrice", itemPrice);
|
||||
// insertCmd.Parameters.AddWithValue("@itemTax", itemTax);
|
||||
// insertCmd.Parameters.AddWithValue("@shippingPrice", shippingPrice);
|
||||
// insertCmd.Parameters.AddWithValue("@shippingTax", shippingTax);
|
||||
// insertCmd.Parameters.AddWithValue("@giftWrapPrice", giftWrapPrice);
|
||||
// insertCmd.Parameters.AddWithValue("@giftWrapTax", giftWrapTax);
|
||||
// if (recipientName == "") { insertCmd.Parameters.AddWithValue("@recipientName", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@recipientName", recipientName); }
|
||||
// if (shipAddress1 == "") { insertCmd.Parameters.AddWithValue("@shipAddress1", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipAddress1", shipAddress1); }
|
||||
// if (shipAddress2 == "") { insertCmd.Parameters.AddWithValue("@shipAddress2", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipAddress2", shipAddress2); }
|
||||
// if (shipAddress3 == "") { insertCmd.Parameters.AddWithValue("@shipAddress3", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipAddress3", shipAddress3); }
|
||||
// if (shipCity == "") { insertCmd.Parameters.AddWithValue("@shipCity", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipCity", shipCity); }
|
||||
// if (shipState == "") { insertCmd.Parameters.AddWithValue("@shipState", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipState", shipState); }
|
||||
// if (shipPostalCode == "") { insertCmd.Parameters.AddWithValue("@shipPostalCode", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipPostalCode", shipPostalCode); }
|
||||
// if (shipCountry == "") { insertCmd.Parameters.AddWithValue("@shipCountry", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipCountry", shipCountry); }
|
||||
// if (shipPhoneNumber == "") { insertCmd.Parameters.AddWithValue("@shipPhoneNumber", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipPhoneNumber", shipPhoneNumber); }
|
||||
// if (billAddress1 == "") { insertCmd.Parameters.AddWithValue("@billAddress1", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billAddress1", billAddress1); }
|
||||
// if (billAddress2 == "") { insertCmd.Parameters.AddWithValue("@billAddress2", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billAddress2", billAddress2); }
|
||||
// if (billAddress3 == "") { insertCmd.Parameters.AddWithValue("@billAddress3", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billAddress3", billAddress3); }
|
||||
// if (billCity == "") { insertCmd.Parameters.AddWithValue("@billCity", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billCity", billCity); }
|
||||
// if (billState == "") { insertCmd.Parameters.AddWithValue("@billState", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billState", billState); }
|
||||
// if (billPostalCode == "") { insertCmd.Parameters.AddWithValue("@billPostalCode", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billPostalCode", billPostalCode); }
|
||||
// if (billCountry == "") { insertCmd.Parameters.AddWithValue("@billCountry", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@billCountry", billCountry); }
|
||||
// if (itemPromotionDiscount == "") { insertCmd.Parameters.AddWithValue("@itemPromotionDiscount", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@itemPromotionDiscount", itemPromotionDiscount); }
|
||||
// if (shipPromotionDiscount == "") { insertCmd.Parameters.AddWithValue("@shipPromotionDiscount", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@shipPromotionDiscount", shipPromotionDiscount); }
|
||||
// if (fulfillmentCenterId == "") { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@fulfillmentCenterId", fulfillmentCenterId); }
|
||||
// if (fulfillmentChannel == "") { insertCmd.Parameters.AddWithValue("@fulfillmentChannel", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@fulfillmentChannel", fulfillmentChannel); }
|
||||
// if (salesChannel == "") { insertCmd.Parameters.AddWithValue("@salesChannel", DBNull.Value); }
|
||||
// else { insertCmd.Parameters.AddWithValue("@salesChannel", salesChannel); }
|
||||
|
||||
// insertCmd.ExecuteNonQuery();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// trans.Commit();
|
||||
// Console.Write("\r");
|
||||
// MiscFunction.EventLogInsert((lineNumber - (1 + lineErrorSkip + lineDuplicateSkip)) + " total new items inserted, " + lineDuplicateSkip + " duplicates were skipped.");
|
||||
// if (lineErrorSkip > 0)
|
||||
// {
|
||||
// MiscFunction.EventLogInsert(lineErrorSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// //}
|
||||
// //catch (Exception ex)
|
||||
// //{
|
||||
// // MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
// // 1,
|
||||
// // ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
// // );
|
||||
|
||||
// // throw ex;
|
||||
// //}
|
||||
// return true;
|
||||
//}
|
||||
|
||||
public Dictionary<string, decimal> ReadMaxSalePrice(List<string> skuNumber, int timePeriodDay)
|
||||
{
|
||||
var returnList = new Dictionary<string, decimal>();
|
||||
|
||||
if (skuNumber == null || !skuNumber.Any())
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
string sql = @"
|
||||
SELECT sku
|
||||
,Max(ISNULL([tblImportFbaSaleShipment].[item-price], 0) + ISNULL([tblImportFbaSaleShipment].[item-tax], 0)) AS Expr1
|
||||
FROM tblImportFbaSaleShipment
|
||||
WHERE (
|
||||
(sku IN (";
|
||||
|
||||
for (int i = 0; i < skuNumber.Count; i++)
|
||||
{
|
||||
if (!(i + 1 == skuNumber.Count))
|
||||
{
|
||||
sql += "@skuNumber" + i + ", ";
|
||||
}
|
||||
else
|
||||
{
|
||||
sql += "@skuNumber" + i + "))";
|
||||
}
|
||||
}
|
||||
|
||||
sql += @"
|
||||
AND ((tblImportFbaSaleShipment.[shipment-date]) >= @shipDateFilter)
|
||||
)
|
||||
GROUP BY sku;";
|
||||
|
||||
using (var conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
using (var cmd = new SqlCommand(sql, conn))
|
||||
{
|
||||
for (int i = 0; i < skuNumber.Count; i++)
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@skuNumber" + i, skuNumber[i]);
|
||||
}
|
||||
cmd.Parameters.AddWithValue("@shipDateFilter", DateTime.Today.AddDays(timePeriodDay * -1));
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
decimal price = reader.GetDecimal(1);
|
||||
if (price > 0)
|
||||
{
|
||||
returnList.Add(reader.GetString(0), price);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnList;
|
||||
}
|
||||
|
||||
public DateTime ReadRecentDate()
|
||||
{
|
||||
DateTime lastRecordDate;
|
||||
SqlConnection sqlConn;
|
||||
try
|
||||
{
|
||||
using (sqlConn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
sqlConn.Open();
|
||||
using (SqlCommand cmd = new SqlCommand(
|
||||
"SELECT Max([shipment-date]) AS MaxDate FROM tblImportFbaSaleShipment;"
|
||||
, sqlConn))
|
||||
{
|
||||
if (cmd.ExecuteScalar() == DBNull.Value)
|
||||
{
|
||||
// use first month started selling on Amazon
|
||||
lastRecordDate = DateTime.Parse("2014-09-01T00:00:00Z");
|
||||
// no need to specific timezone, etc, as "Z" already specifis UTC
|
||||
lastRecordDate = DateTime.Parse("2016-02-01T00:00:00Z");
|
||||
// fba sale shipments for previous 18 months only
|
||||
}
|
||||
else
|
||||
{
|
||||
lastRecordDate = ((DateTime)cmd.ExecuteScalar());
|
||||
lastRecordDate = DateTime.SpecifyKind(lastRecordDate, DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
return lastRecordDate;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error running FbaInventoryReceiptReportImport, no records were commited",
|
||||
1,
|
||||
ex.ToString() + "\r\nTraceMessage:\r\n" + MiscFunction.TraceMessage()
|
||||
);
|
||||
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public Dictionary<string, int> ReadSaleCount(List<string> skuNumber, DateTime periodStart, DateTime periodEnd)
|
||||
{
|
||||
var returnList = new Dictionary<string, int>();
|
||||
|
||||
if (skuNumber == null || !skuNumber.Any())
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
string sql = @"
|
||||
SELECT sku
|
||||
,Count(1) AS CountOfSku
|
||||
FROM tblImportFbaSaleShipment
|
||||
WHERE (
|
||||
(sku IN @skuNumber)
|
||||
AND (
|
||||
(tblImportFbaSaleShipment.[shipment-date] >= @periodStart)
|
||||
AND tblImportFbaSaleShipment.[shipment-date] <= @periodEnd
|
||||
)
|
||||
)
|
||||
GROUP BY sku;";
|
||||
|
||||
using (var conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
var param = new DynamicParameters();
|
||||
param.Add("@skuNumber", skuNumber);
|
||||
param.Add("@periodStart", periodStart.ToUniversalTime());
|
||||
param.Add("@periodEnd", periodEnd.ToUniversalTime());
|
||||
|
||||
return conn.Query(sql, param).ToDictionary(
|
||||
row => (string)row.sku,
|
||||
row => (int)row.CountOfSku);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
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<string, int> dicTablePkBySettlementId = new Dictionary<string, int>();
|
||||
private int? returnTop = null;
|
||||
private List<string> settlementIdList;
|
||||
private List<string> 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<string> SettlementIdList
|
||||
{
|
||||
get { return settlementIdList; }
|
||||
set
|
||||
{
|
||||
if (value.Any())
|
||||
{ settlementIdList = value; }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private List<string> 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<Model.Import.AmazonSettlementHeader> AllUnprocessed()
|
||||
{
|
||||
Innit();
|
||||
FilterOutIsProcessed = true;
|
||||
return ReadHeaderList();
|
||||
}
|
||||
|
||||
public Model.Import.AmazonSettlementHeader 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.AmazonSettlementHeader> BySettlementId(List<string> settlementIdList)
|
||||
{
|
||||
Innit();
|
||||
|
||||
if (settlementIdList == null || !settlementIdList.Any())
|
||||
{ return new List<Model.Import.AmazonSettlementHeader>(); }
|
||||
|
||||
SettlementIdList = settlementIdList;
|
||||
|
||||
return ReadHeaderList();
|
||||
}
|
||||
|
||||
public List<Model.Import.AmazonSettlementHeader> BySpapiReportId(List<string> spapiReportIdList)
|
||||
{
|
||||
Innit();
|
||||
|
||||
if (spapiReportIdList == null || !spapiReportIdList.Any())
|
||||
{ return new List<Model.Import.AmazonSettlementHeader>(); }
|
||||
|
||||
SpapiReportIdList = spapiReportIdList;
|
||||
|
||||
return ReadHeaderList();
|
||||
}
|
||||
|
||||
private List<Model.Import.AmazonSettlementHeader> ReadHeaderList()
|
||||
{
|
||||
var returnHeaderList = new List<Model.Import.AmazonSettlementHeader>();
|
||||
|
||||
// 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<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 + " )";
|
||||
}
|
||||
|
||||
// build dictionary of parameter and values for SP-API Report Id
|
||||
var dicSpapiReportIdByParameterString = new Dictionary<string, string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
329
src/bnhtrade.Core/Data/Database/Import/AmazonSettlementInsert.cs
Normal file
329
src/bnhtrade.Core/Data/Database/Import/AmazonSettlementInsert.cs
Normal file
@@ -0,0 +1,329 @@
|
||||
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
|
||||
{
|
||||
public AmazonSettlementInsert ()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="filePath"></param>
|
||||
/// <param name="reportId">The unique Amazon SP-API report id (not settlement id)</param>
|
||||
/// <returns></returns>
|
||||
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;
|
||||
MiscFunction.EventLogInsert(
|
||||
"Line #" + lineNumber + " skipped due to no enough element in row.",
|
||||
2,
|
||||
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);
|
||||
MiscFunction.EventLogInsert("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.DateTimeParse();
|
||||
|
||||
if (indexSettlementStartDate == -1 || items[indexSettlementStartDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@settlementStartDate", DBNull.Value); }
|
||||
else { sqlCommand.Parameters.AddWithValue("@settlementStartDate", parseDateTime.ParseMwsReportDateTime(items[indexSettlementStartDate])); }
|
||||
|
||||
if (indexSettlementEndDate == -1 || items[indexSettlementEndDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@settlementEndDate", DBNull.Value); }
|
||||
else { sqlCommand.Parameters.AddWithValue("@settlementEndDate", parseDateTime.ParseMwsReportDateTime(items[indexSettlementEndDate])); }
|
||||
|
||||
if (indexDepositDate == -1 || items[indexDepositDate].Length == 0) { sqlCommand.Parameters.AddWithValue("@depositDate", DBNull.Value); }
|
||||
else { sqlCommand.Parameters.AddWithValue("@depositDate", parseDateTime.ParseMwsReportDateTime(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.DateTimeParse().ParseMwsReportDateTime(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)
|
||||
{
|
||||
MiscFunction.EventLogInsert("Error importing settlement id'" + settlementRef + "'. Sum of inserted settlement lines (" + sumOfAmount +
|
||||
") does not match settlement amount (" + settlementAmount + ").", 1);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
scope.Complete();
|
||||
|
||||
Console.Write("\r");
|
||||
MiscFunction.EventLogInsert((lineNumber - (2 + lineSkip)) + " total settlement items inserted");
|
||||
if (lineSkip > 0)
|
||||
{
|
||||
MiscFunction.EventLogInsert(lineSkip + " total line(s) where skipped due to insufficent number of cells on row", 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,147 @@ using System.Data.SqlClient;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class ReadAmazonSettlement : Connection
|
||||
public class AmazonSettlementRead : Connection
|
||||
{
|
||||
private Data.Database.SqlWhereBuilder whereBuilder = new SqlWhereBuilder();
|
||||
|
||||
public List<Model.Import.AmazonSettlement> BySettlementIdList(List<string> settlementIdList)
|
||||
{
|
||||
var settlementList = new List<Model.Import.AmazonSettlement>();
|
||||
|
||||
// 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.Innit();
|
||||
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<Model.Import.AmazonSettlement.SettlementLine>();
|
||||
var LineListDic = new Dictionary<string, List<Model.Import.AmazonSettlement.SettlementLine>>();
|
||||
var headerList = new List<Model.Import.AmazonSettlementHeader>();
|
||||
|
||||
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<Model.Import.AmazonSettlement.SettlementLine>();
|
||||
}
|
||||
}
|
||||
|
||||
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<string, int> dicTablePkBySettlementId = new Dictionary<string, int>();
|
||||
private int? returnTop = null;
|
||||
private List<string> settlementIdList;
|
||||
@@ -50,7 +189,7 @@ namespace bnhtrade.Core.Data.Database.Import
|
||||
get { return SettlementIdList != null; }
|
||||
}
|
||||
|
||||
public ReadAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
|
||||
public AmazonSettlementRead()
|
||||
{
|
||||
Innit();
|
||||
}
|
||||
@@ -191,7 +330,7 @@ namespace bnhtrade.Core.Data.Database.Import
|
||||
ORDER BY [settlement-start-date] ";
|
||||
if (DescendingOrder) { sqlString = sqlString + " DESC"; }
|
||||
|
||||
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
|
||||
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
@@ -245,7 +384,7 @@ namespace bnhtrade.Core.Data.Database.Import
|
||||
|
||||
private List<Model.Import.AmazonSettlement.SettlementLine> ReadLineList(int settlementPk)
|
||||
{
|
||||
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
|
||||
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
@@ -7,9 +7,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class UpdateAmazonSettlement : Connection
|
||||
public class AmazonSettlementUpdate : Connection
|
||||
{
|
||||
public UpdateAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
|
||||
public AmazonSettlementUpdate()
|
||||
{
|
||||
|
||||
}
|
||||
@@ -32,7 +32,7 @@ namespace bnhtrade.Core.Data.Database.Import
|
||||
OR ([settlement-id] = @settlementId" + i + ")";
|
||||
}
|
||||
|
||||
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
|
||||
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
|
||||
namespace bnhtrade.Core.Data.Database.Import
|
||||
{
|
||||
public class ReadFbaSaleShipment : Connection
|
||||
{
|
||||
public ReadFbaSaleShipment(string sqlConnectionString): base(sqlConnectionString)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public Dictionary<string, decimal> GetMaxSalePrice(List<string> skuNumber, int timePeriodDay)
|
||||
{
|
||||
var returnList = new Dictionary<string, decimal>();
|
||||
|
||||
if (skuNumber == null || !skuNumber.Any())
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
string sql = @"
|
||||
SELECT sku
|
||||
,Max(ISNULL([tblImportFbaSaleShipment].[item-price], 0) + ISNULL([tblImportFbaSaleShipment].[item-tax], 0)) AS Expr1
|
||||
FROM tblImportFbaSaleShipment
|
||||
WHERE (
|
||||
(sku IN (";
|
||||
|
||||
for (int i = 0; i < skuNumber.Count; i++)
|
||||
{
|
||||
if (!(i + 1 == skuNumber.Count))
|
||||
{
|
||||
sql += "@skuNumber" + i + ", ";
|
||||
}
|
||||
else
|
||||
{
|
||||
sql += "@skuNumber" + i + "))";
|
||||
}
|
||||
}
|
||||
|
||||
sql += @"
|
||||
AND ((tblImportFbaSaleShipment.[shipment-date]) >= @shipDateFilter)
|
||||
)
|
||||
GROUP BY sku;";
|
||||
|
||||
using (var conn = new SqlConnection(sqlConnectionString))
|
||||
{
|
||||
using (var cmd = new SqlCommand(sql, conn))
|
||||
{
|
||||
for (int i = 0; i < skuNumber.Count; i++)
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@skuNumber" + i, skuNumber[i]);
|
||||
}
|
||||
cmd.Parameters.AddWithValue("@shipDateFilter", DateTime.Today.AddDays(timePeriodDay * -1));
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
decimal price = reader.GetDecimal(1);
|
||||
if (price > 0)
|
||||
{
|
||||
returnList.Add(reader.GetString(0), price);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return returnList;
|
||||
}
|
||||
|
||||
public Dictionary<string, int> GetSaleCount(List<string> skuNumber, DateTime periodStart, DateTime periodEnd)
|
||||
{
|
||||
var returnList = new Dictionary<string, int>();
|
||||
|
||||
if (skuNumber == null || !skuNumber.Any())
|
||||
{
|
||||
return returnList;
|
||||
}
|
||||
|
||||
string sql = @"
|
||||
SELECT sku
|
||||
,Count(1) AS CountOfSku
|
||||
FROM tblImportFbaSaleShipment
|
||||
WHERE (
|
||||
(sku IN @skuNumber)
|
||||
AND (
|
||||
(tblImportFbaSaleShipment.[shipment-date] >= @periodStart)
|
||||
AND tblImportFbaSaleShipment.[shipment-date] <= @periodEnd
|
||||
)
|
||||
)
|
||||
GROUP BY sku;";
|
||||
|
||||
using (var conn = new SqlConnection(sqlConnectionString))
|
||||
{
|
||||
var param = new DynamicParameters();
|
||||
param.Add("@skuNumber", skuNumber);
|
||||
param.Add("@periodStart", periodStart.ToUniversalTime());
|
||||
param.Add("@periodEnd", periodEnd.ToUniversalTime());
|
||||
|
||||
return conn.Query(sql, param).ToDictionary(
|
||||
row => (string)row.sku,
|
||||
row => (int)row.CountOfSku);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user