Migration from Amazon MWS to Selling Partner API

This commit is contained in:
Bobbie Hodgetts
2024-04-11 12:26:13 +01:00
committed by GitHub
parent e054278cdd
commit a7bc00e73a
1318 changed files with 2778105 additions and 5936 deletions

View File

@@ -2,16 +2,22 @@
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="bnhtrade.Core.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="e2A_Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="e2A_Client.Properties.Settings.ConnectionString" connectionString="Data Source=SQL-Server;Initial Catalog=e2A;Persist Security Info=True;User ID=e2A Client;Password=eSYH4EYoK6Guc5KIclhgFDlGc4;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<applicationSettings>
<bnhtrade.Core.Properties.Settings>
<setting name="DocArchivePath" serializeAs="String">
<value>%USERPROFILE%\Desktop\e2A_Client\Archive\</value>
</setting>
<setting name="DocProcessingPath" serializeAs="String">
<value>%USERPROFILE%\Desktop\e2A_Client\Processing\</value>
</setting>
</bnhtrade.Core.Properties.Settings>
<e2A_Client.Properties.Settings>
<setting name="DocArchivePath" serializeAs="String">
<value>%USERPROFILE%\Desktop\e2A_Client\Archive\</value>
@@ -27,6 +33,34 @@
<assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Bcl.AsyncInterfaces" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="RestSharp" publicKeyToken="598062e77f915f75" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-106.13.0.0" newVersion="106.13.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ComponentModel.Annotations" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.2" newVersion="7.0.0.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,78 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.Parameter.FbaInventory;
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.FbaInventory
{
public class GetFbaInventoryInfo
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public List<string> MarketPlaceIds { get; set; }
/// <summary>
/// True to return inventory summaries with additional summarized inventory details and quantities.
/// Otherwise, returns inventory summaries only (the default value).
/// </summary>
public bool WithDetails { get; set; }
public GetFbaInventoryInfo()
{
}
public Dictionary<string, string> GetFnsku(List<string> skuList)
{
var returnList = new Dictionary<string, string>();
var result = GetInventorySummaries(skuList);
foreach (var list in result)
{
foreach(var item in list)
{
returnList.Add(item.SellerSku, item.FnSku);
}
}
return returnList;
}
private List<FikaAmazonAPI.AmazonSpApiSDK.Models.FbaInventory.InventorySummaries> GetInventorySummaries(List<string> skuList, DateTime? startDateTime = null)
{
var returnList = new List<FikaAmazonAPI.AmazonSpApiSDK.Models.FbaInventory.InventorySummaries>();
// max of 50 sku in one call
int i = 0;
int total = skuList.Count;
var skuRequestList = new List<string>();
foreach (string sku in skuList)
{
i++;
skuRequestList.Add(sku);
if (i == total || i % 50 == 0)
{
var parameters = new ParameterGetInventorySummaries();
//parameters.details = WithDetails;
parameters.granularityType = FikaAmazonAPI.AmazonSpApiSDK.Models.FbaInventory.Granularity.GranularityTypeEnum.Marketplace;
parameters.granularityId = new Data.Amazon.SellingPartnerAPI.Defaults().MarketPlaceIdAsString();
parameters.marketplaceIds = MarketPlaceIds;
//parameters.startDateTime = startDateTime;
parameters.sellerSkus = skuRequestList;
var lkdsjflds = amznConn.FbaInventory.GetInventorySummaries(parameters);
returnList.AddRange(lkdsjflds);
skuRequestList = new List<string>();
}
}
return returnList;
}
}
}

View File

@@ -0,0 +1,27 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Feeds
{
public class GetFeed
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public void GetFeeds(string feedId)
{
var param = new FikaAmazonAPI.Parameter.Feed.ParameterGetFeed();
param.pageSize = 100;
param.processingStatuses = ProcessingStatuses.DONE;
param.feedTypes = new List<FeedType> { FeedType.POST_PRODUCT_PRICING_DATA };
var result = amznConn.Feed.GetFeeds(param);
}
}
}

View File

@@ -0,0 +1,450 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FikaAmazonAPI;
using FikaAmazonAPI.AmazonSpApiSDK.Models.Feeds;
using FikaAmazonAPI.ConstructFeed;
using FikaAmazonAPI.ConstructFeed.Messages;
using FikaAmazonAPI.Utils;
using static FikaAmazonAPI.ConstructFeed.BaseXML;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Feeds
{
public class SampleFeeds
{
AmazonConnection amazonConnection;
public SampleFeeds(AmazonConnection amazonConnection)
{
this.amazonConnection = amazonConnection;
}
public void CallFlatfile()
{
string text = System.IO.File.ReadAllText(@"C:\Users\tareq\Downloads\Beispiel_Upload.txt");
var feedresultTXT = amazonConnection.Feed.SubmitFeed(text
, FeedType.POST_FLAT_FILE_INVLOADER_DATA
, new List<string>() { MarketPlace.UnitedArabEmirates.ID }
, null
, ContentType.TXT);
string pathURL = string.Empty;
while (pathURL == string.Empty)
{
Thread.Sleep(1000 * 30);
var feedOutput = amazonConnection.Feed.GetFeed(feedresultTXT);
if (feedOutput.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Feeds.Feed.ProcessingStatusEnum.DONE)
{
var outPut = amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);
pathURL = outPut.Url;
}
}
}
public void GetFeeds()
{
var data = amazonConnection.Feed.GetFeeds(new FikaAmazonAPI.Parameter.Feed.ParameterGetFeed()
{
processingStatuses = ProcessingStatuses.DONE,
pageSize = 100,
feedTypes = new List<FeedType> { FeedType.POST_PRODUCT_PRICING_DATA },
createdSince = DateTime.UtcNow.AddDays(-6),
createdUntil = DateTime.UtcNow.AddDays(-1),
marketplaceIds = new List<string> { MarketPlace.UnitedArabEmirates.ID }
});
}
public void CreateFeedDocument()
{
var data = amazonConnection.Feed.CreateFeedDocument(ContentType.XML);
}
public void GetFeedDocument()
{
var data2 = amazonConnection.Feed.GetFeedDocument("amzn1.tortuga.3.92d8fd38-6ccf-49be-979f-6dc27375ea3e.T2DF7HINJ0NRA2");
}
public void GetFeed()
{
var data2 = amazonConnection.Feed.GetFeed("194146018872");
}
public void CancelFeed()
{
var data2 = amazonConnection.Feed.CancelFeed("194146018872");
}
public void SubmitFeedInventory()
{
ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
var list = new List<InventoryMessage>();
list.Add(new InventoryMessage()
{
SKU = "API.853038006021.20789.1001",
Quantity = 1
});
createDocument.AddInventoryMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_INVENTORY_AVAILABILITY_DATA);
GetFeedDetails(feedID);
}
/// <summary>
/// UnderTest
/// </summary>
public void SubmitFeedAddProductMessage(string ASIN, string SKU)
{
ConstructFeedService createDocument = new ConstructFeedService(amazonConnection.GetCurrentSellerID, "1.02");
var list = new List<ProductMessage>();
list.Add(new ProductMessage()
{
SKU = SKU,
StandardProductID = new FikaAmazonAPI.ConstructFeed.Messages.StandardProductID()
{
Type = "ASIN",
Value = ASIN
}
});
createDocument.AddProductMessage(list, OperationType.Update);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_DATA);
GetFeedDetails(feedID);
}
public void SubmitFeedDeleteAddProductMessage()
{
ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
var list = new List<ProductMessage>();
list.Add(new ProductMessage()
{
SKU = "8432225129778...."
});
createDocument.AddProductMessage(list, OperationType.Delete);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeedContent(xml, FeedType.POST_PRODUCT_DATA);
GetFeedDetails(feedID);
}
public void AddOfferMessageMessage()
{
ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
var list = new List<OfferMessage>();
list.Add(new OfferMessage()
{
SKU = "4049639414402_b"
});
createDocument.AddOfferMessage(list, OperationType.Delete);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_DATA);
GetFeedDetails(feedID);
}
public void SubmitFeedPRICING(double PRICE, string SKU)
{
ConstructFeedService createDocument = new ConstructFeedService(amazonConnection.GetCurrentSellerID, "1.02");
var list = new List<PriceMessage>();
list.Add(new PriceMessage()
{
SKU = SKU,
StandardPrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
Value = (PRICE).ToString("0.00")
}
});
createDocument.AddPriceMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_PRICING_DATA);
GetFeedDetails(feedID);
}
public async void SubmitFeedPricingWithSalePrice(string sku, decimal price, decimal salePrice, DateTime startDate, DateTime endDate)
{
var currencyCode = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString();
var createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
var list = new List<PriceMessage>();
list.Add(new PriceMessage
{
SKU = sku,
StandardPrice = new StandardPrice
{
currency = currencyCode,
Value = price.ToString("0.00")
},
Sale = new Sale
{
SalePrice = new StandardPrice
{
currency = currencyCode,
Value = salePrice.ToString("0.00")
},
StartDate = startDate.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
EndDate = endDate.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")
}
});
createDocument.AddPriceMessage(list);
var xml = createDocument.GetXML();
var feedId = await amazonConnection.Feed.SubmitFeedAsync(xml, FeedType.POST_PRODUCT_PRICING_DATA);
GetFeedDetails(feedId);
}
public void SubmitFeedSale(double PRICE, string SKU)
{
ConstructFeedService createDocument = new ConstructFeedService("A3J37AJU4O9RHK", "1.02");
var list = new List<PriceMessage>();
list.Add(new PriceMessage()
{
SKU = SKU,
StandardPrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
Value = (PRICE).ToString("0.00")
},
Sale = new Sale()
{
StartDate = DateTime.UtcNow.AddDays(+1).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
EndDate = DateTime.UtcNow.AddDays(+2).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
SalePrice = new StandardPrice()
{
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode.ToString(),
Value = (PRICE - 10).ToString("0.00")
}
}
});
createDocument.AddPriceMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PRODUCT_PRICING_DATA);
GetFeedDetails(feedID);
}
public void FeebPostOrderFullfillment()
{
ConstructFeedService createDocument = new ConstructFeedService("{sellerId}", "1.02");
var list = new List<OrderFulfillmentMessage>();
list.Add(new OrderFulfillmentMessage()
{
AmazonOrderID = "{orderId}",
FulfillmentDate = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"),
FulfillmentData = new FulfillmentData()
{
CarrierName = "Correos Express",
ShippingMethod = "ePaq",
ShipperTrackingNumber = "{trackingNumber}"
}
});
createDocument.AddOrderFulfillmentMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_ORDER_FULFILLMENT_DATA);
GetFeedDetails(feedID);
}
public void SubmitFeedOrderAcknowledgement()
{
ConstructFeedService createDocument = new ConstructFeedService("{sellerId}", "1.02");
var list = new List<OrderAcknowledgementMessage>();
list.Add(new OrderAcknowledgementMessage()
{
AmazonOrderID = "AMZ1234567890123",
MerchantOrderID = "12345678",
StatusCode = OrderAcknowledgementStatusCode.Success,
Item = new List<OrderAcknowledgementItem>() {
new OrderAcknowledgementItem() {
AmazonOrderItemCode = "52986411826454",
MerchantOrderItemID = "1"
}
}
});
createDocument.AddOrderAcknowledgementMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_ORDER_ACKNOWLEDGEMENT_DATA);
GetFeedDetails(feedID);
}
public void SubmitFeedOrderAdjustment()
{
ConstructFeedService createDocument = new ConstructFeedService("{sellerId}", "1.02");
var list = new List<OrderAdjustmentMessage>();
list.Add(new OrderAdjustmentMessage()
{
AmazonOrderID = "AMZ1234567890123",
ActionType = AdjustmentActionType.Refund,
AdjustedItem = new List<AdjustedItem>() {
new AdjustedItem() {
AmazonOrderItemCode = "52986411826454",
AdjustmentReason = AdjustmentReason.CustomerCancel,
DirectPaymentAdjustments = new List<DirectPaymentAdjustments>()
{
new DirectPaymentAdjustments()
{
Component = new List<DirectPaymentAdjustmentsComponent>()
{
new DirectPaymentAdjustmentsComponent() {
DirectPaymentType = "Credit Card Refund",
Amount = new CurrencyAmount() {
Value = 10.50M,
currency = amazonConnection.GetCurrentMarketplace.CurrencyCode
}
}
}
}
}
}
}
});
createDocument.AddOrderAdjustmentMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_PAYMENT_ADJUSTMENT_DATA);
GetFeedDetails(feedID);
}
public void CartonContentsRequestFeed()
{
ConstructFeedService createDocument2 = new ConstructFeedService("{SellerID}", "1.02");
var list22 = new List<CartonContentsRequest>();
list22.Add(new CartonContentsRequest()
{
ShipmentId = "FBA123456",
Carton = new List<Carton> {
new Carton() {
CartonId="1",
Item=new List<CartonItem>(){
new CartonItem() {
QuantityInCase=1,
QuantityShipped=1,
SKU="7004"
}
}
},
new Carton() {
CartonId="2",
Item=new List<CartonItem>(){
new CartonItem() {
QuantityInCase=12,
QuantityShipped=12,
SKU="4051",
ExpirationDate=DateTime.Now,
}
}
}
}
});
createDocument2.AddCartonContentsRequest(list22);
var xml222 = createDocument2.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml222, FeedType.POST_FBA_INBOUND_CARTON_CONTENTS);
GetFeedDetails(feedID);
}
public void SubmitFeedEasyShipDocument()
{
ConstructFeedService createDocument = new ConstructFeedService("{sellerId}", "1.02");
var list = new List<EasyShipDocumentMessage>();
list.Add(new EasyShipDocumentMessage()
{
AmazonOrderID = "AMZ1234567890123",
DocumentTypes = new List<EasyShipDocumentType>() {
EasyShipDocumentType.ShippingLabel
}
});
createDocument.AddEasyShipDocumentMessage(list);
var xml = createDocument.GetXML();
var feedID = amazonConnection.Feed.SubmitFeed(xml, FeedType.POST_EASYSHIP_DOCUMENTS);
GetFeedDetails(feedID);
}
public void GetFeedDetails(string feedID)
{
string ResultFeedDocumentId = string.Empty;
while (string.IsNullOrEmpty(ResultFeedDocumentId))
{
var feedOutput = amazonConnection.Feed.GetFeed(feedID);
if (feedOutput.ProcessingStatus == Feed.ProcessingStatusEnum.DONE)
{
var outPut = amazonConnection.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);
var reportOutput = outPut.Url;
var processingReport = amazonConnection.Feed.GetFeedDocumentProcessingReport(outPut);
DisplayProcessingReportMessage(processingReport);
break;
}
if (!(feedOutput.ProcessingStatus == Feed.ProcessingStatusEnum.INPROGRESS ||
feedOutput.ProcessingStatus == Feed.ProcessingStatusEnum.INQUEUE))
break;
else Thread.Sleep(10000);
}
}
private void DisplayProcessingReportMessage(ProcessingReportMessage processingReport)
{
Console.WriteLine("MessagesProcessed=" + processingReport.ProcessingSummary.MessagesProcessed);
Console.WriteLine("MessagesSuccessful= " + processingReport.ProcessingSummary.MessagesSuccessful);
Console.WriteLine("MessagesWithError=" + processingReport.ProcessingSummary.MessagesWithError);
Console.WriteLine("MessagesWithWarning=" + processingReport.ProcessingSummary.MessagesWithWarning);
if (processingReport.Result != null && processingReport.Result.Count > 0)
{
foreach (var itm in processingReport.Result)
{
Console.WriteLine("ResultDescription=" + (itm.AdditionalInfo?.SKU ?? string.Empty) + " > " + itm.ResultDescription);
}
}
}
}
}

View File

@@ -0,0 +1,113 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Feeds
{
class SubmittFeed
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
private Logic.Log.LogEvent logEvent = new Logic.Log.LogEvent();
public bool FeedSubmissionRecived { get; set; } = false;
// make these functions only accept a database object
public SubmittFeed()
{
}
public Model.Export.AmazonFeedSubmission FlatFileInvLoaderData(System.IO.MemoryStream filestream)
{
return Post("POST_FLAT_FILE_INVLOADER_DATA", filestream, "TXT");
}
private Model.Export.AmazonFeedSubmission Post(string feedType, System.IO.MemoryStream filestream, string fileExtension)
{
throw new NotImplementedException();
if (filestream.Length == 0) { throw new Exception("Filestreeam is empty"); }
if (string.IsNullOrEmpty(fileExtension)) { throw new Exception("Filestreeam is empty"); }
var feedresultTXT = amznConn.Feed.SubmitFeed(filestream.ToString()
, GetFeedType(feedType)
, new List<string>() { amznConn.GetCurrentMarketplace.ID }
, null
, ContentType.TXT);
string pathURL = string.Empty;
while (pathURL == string.Empty)
{
Thread.Sleep(1000 * 30);
var feedOutput = amznConn.Feed.GetFeed(feedresultTXT);
if (feedOutput.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Feeds.Feed.ProcessingStatusEnum.DONE)
{
var outPut = amznConn.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);
pathURL = outPut.Url;
}
}
}
private FeedType GetFeedType(string feedTypeText)
{
// add more here as needed
if (feedTypeText == "POST_FLAT_FILE_INVLOADER_DATA")
{ return FeedType.POST_FLAT_FILE_INVLOADER_DATA; }
else
{ throw new NotImplementedException("Need to implement feed type for " + feedTypeText); }
}
public void SubmitFeed(Model.Export.AmazonFeedSubmission feedSubmission)
{
FeedSubmissionRecived = false;
if (feedSubmission.FileIsSet == false) { throw new Exception("Filestreeam is empty"); }
// get feed type
var feedType = GetFeedType(feedSubmission.FeedType);
string text = feedSubmission.File.FileData.ToString();
var feedresultTXT = amznConn.Feed.SubmitFeed(text
, feedType
, new List<string>() { amznConn.GetCurrentMarketplace.ID }
, null
, ContentType.TXT);
var result = new FikaAmazonAPI.AmazonSpApiSDK.Models.Feeds.FeedDocument();
int sleepTime = (1000 * 25);
int retryCount = 0;
int retryTimeout = 20;
UI.Console.Wait("Feed:" + feedType + " submitted to Amazon, awaiting status check.", 5000);
while (retryCount <= retryTimeout)
{
var feedOutput = amznConn.Feed.GetFeed(feedresultTXT);
if (feedOutput.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Feeds.Feed.ProcessingStatusEnum.DONE)
{
result = amznConn.Feed.GetFeedDocument(feedOutput.ResultFeedDocumentId);
break;
}
retryCount++;
UI.Console.Wait("Feed: " + feedType + ", Processing status: " + feedOutput.ProcessingStatus + ", Retry: " + retryCount + " of "+ retryTimeout, sleepTime);
}
// retry timeout
if (retryCount > retryTimeout)
{
logEvent.LogError("Feed submission timeout. Feedtype:" + feedType + " FeedSubmissionId:" + feedSubmission.FeedSubmissionId);
return;
}
// get and do somehting with this
string pathURL = string.Empty;
pathURL = result.Url;
}
}
}

View File

@@ -0,0 +1,66 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.FulFillmentInbound
{
public class CreateInboundShipmentPlan
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public CreateInboundShipmentPlan()
{
}
public void CreatePlan(List<bnhtrade.Core.Model.AmazonFba.ShippingPlanItem> itemList)
{
throw new NotImplementedException();
// complete, but not tested (need to do something with the result)
var request = new FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.CreateInboundShipmentPlanRequest();
request.LabelPrepPreference = FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.LabelPrepPreference.SELLERLABEL;
request.ShipFromAddress.Name = ConfigurationManager.AppSettings["AmazonFbaShipFrom.Name"];
request.ShipFromAddress.AddressLine1 = ConfigurationManager.AppSettings["AmazonFbaShipFrom.AddressLine1"];
request.ShipFromAddress.AddressLine2 = ConfigurationManager.AppSettings["AmazonFbaShipFrom.AddressLine2"];
//request.ShipFromAddress.DistrictOrCounty = null; // not required
request.ShipFromAddress.City = ConfigurationManager.AppSettings["AmazonFbaShipFrom.City"];
request.ShipFromAddress.StateOrProvinceCode = ConfigurationManager.AppSettings["AmazonFbaShipFrom.StateOrProvinceCode"]; //required
request.ShipFromAddress.PostalCode = ConfigurationManager.AppSettings["AmazonFbaShipFrom.PostalCode"];
request.ShipFromAddress.CountryCode = ConfigurationManager.AppSettings["AmazonFbaShipFrom.CountryCode"];
request.ShipToCountryCode = ConfigurationManager.AppSettings["AmazonFbaShipFrom.CountryCode"];
// add item list
request.InboundShipmentPlanRequestItems = TransposeItemList(itemList);
var result = amznConn.FulFillmentInbound.CreateInboundShipmentPlan(request);
}
private InboundShipmentPlanRequestItemList TransposeItemList(List<bnhtrade.Core.Model.AmazonFba.ShippingPlanItem> itemList)
{
var returnList = new InboundShipmentPlanRequestItemList();
foreach(var item in itemList)
{
var requestItem = new InboundShipmentPlanRequestItem();
requestItem.SellerSKU = item.SkuNumber;
requestItem.ASIN = item.ASIN;
if (Enum.TryParse(item.Condition, out Condition myStatus)) { requestItem.Condition = myStatus; }
else { throw new Exception("Unable to parse string '" + item.Condition + "' to ENUM"); }
requestItem.Quantity = item.Quantity;
//requestItem.QuantityInCase;
//requestItem.PrepDetailsList;
returnList.Add(requestItem);
}
return returnList;
}
}
}

View File

@@ -0,0 +1,128 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.FulFillmentInbound
{
public class GetShipmentItems
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public GetShipmentItems()
{
}
public List<Model.AmazonFba.ShipmentItemInfo> GetByDateRange(DateTime utcDateTimeAfter, DateTime utcDateTimeBefore)
{
var result = new List<Model.AmazonFba.ShipmentItemInfo>();
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipmentItems();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.DATE_RANGE;
parameter.LastUpdatedAfter = utcDateTimeAfter;
parameter.LastUpdatedBefore = utcDateTimeBefore;
var apiResult = amznConn.FulFillmentInbound.GetShipmentItems(parameter);
AppendNextToken(ref apiResult);
return TransposeModel(apiResult);
}
public List<Model.AmazonFba.ShipmentItemInfo> GetByShipmentId(string shipmentId)
{
var result = new List<Model.AmazonFba.ShipmentItemInfo>();
if (string.IsNullOrEmpty(shipmentId)) { return result; }
// build the request
//var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipmentItems();
//parameter.MarketplaceId = marketPlaceId;
//parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.SHIPMENT;
//parameter.ShipmentId = shipmentId;
var apiResult = amznConn.FulFillmentInbound.GetShipmentItemsByShipmentId(shipmentId);
AppendNextToken(ref apiResult);
return TransposeModel(apiResult);
}
// checks for next-token, if true appends additional data to the ShipmentData
private void AppendNextToken(ref FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.InboundShipmentItemList shipmentList)
{
while (!string.IsNullOrEmpty(shipmentList.NextToken))
{
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipmentItems();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.NEXT_TOKEN;
parameter.NextToken = shipmentList.NextToken;
var result = amznConn.FulFillmentInbound.GetShipmentItems(parameter);
shipmentList.AddRange(result);
shipmentList.NextToken = result.NextToken;
}
}
private void AppendNextToken(ref FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.GetShipmentItemsResult shipmentList)
{
while (!string.IsNullOrEmpty(shipmentList.NextToken))
{
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipmentItems();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.NEXT_TOKEN;
parameter.NextToken = shipmentList.NextToken;
var result = amznConn.FulFillmentInbound.GetShipmentItems(parameter);
shipmentList.ItemData.AddRange(result);
shipmentList.NextToken = result.NextToken;
}
}
private List<Model.AmazonFba.ShipmentItemInfo> TransposeModel(FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.InboundShipmentItemList shipmentResult)
{
var returnList = new List<Model.AmazonFba.ShipmentItemInfo>();
for (var i = 0; i < shipmentResult.Count; i++)
{
var item = new Model.AmazonFba.ShipmentItemInfo();
// under new SP-API there are more details to be used, if needed
item.AmazonFNSKU = shipmentResult[i].FulfillmentNetworkSKU;
item.AmazonShipmentId = shipmentResult[i].ShipmentId;
item.QuantityAllocated = shipmentResult[i].QuantityShipped.GetValueOrDefault();
item.QuantityReceived = shipmentResult[i].QuantityReceived.GetValueOrDefault();
item.SKUNumber = shipmentResult[i].SellerSKU;
returnList.Add(item);
}
return returnList;
}
private List<Model.AmazonFba.ShipmentItemInfo> TransposeModel(FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.GetShipmentItemsResult shipmentResult)
{
var returnList = new List<Model.AmazonFba.ShipmentItemInfo>();
for (var i = 0; i < shipmentResult.ItemData.Count; i++)
{
var item = new Model.AmazonFba.ShipmentItemInfo();
// under new SP-API there are more details to be used, if needed
item.AmazonFNSKU = shipmentResult.ItemData[i].FulfillmentNetworkSKU;
item.AmazonShipmentId = shipmentResult.ItemData[i].ShipmentId;
item.QuantityAllocated = shipmentResult.ItemData[i].QuantityShipped.GetValueOrDefault();
item.QuantityReceived = shipmentResult.ItemData[i].QuantityReceived.GetValueOrDefault();
item.SKUNumber = shipmentResult.ItemData[i].SellerSKU;
returnList.Add(item);
}
return returnList;
}
}
}

View File

@@ -0,0 +1,110 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.FulFillmentInbound
{
public class GetShipments
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public GetShipments()
{
}
public List<Model.AmazonFba.ShipmentInfo> GetByDateRange(DateTime utcDateTimeAfter, DateTime utcDateTimeBefore)
{
// At least one of the ShipmentStatusList and ShipmentIdList must be provided
var result = new List<Model.AmazonFba.ShipmentInfo>();
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipments();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.DATE_RANGE;
parameter.LastUpdatedAfter = utcDateTimeAfter;
parameter.LastUpdatedBefore = utcDateTimeBefore;
AddShipmentStatusList(ref parameter);
var apiResult = amznConn.FulFillmentInbound.GetShipments(parameter);
AppendNextToken(ref apiResult);
return TransposeModel(apiResult);
}
public List<Model.AmazonFba.ShipmentInfo> GetByShipmentIdList(List<string> shipmentIdList)
{
var result = new List<Model.AmazonFba.ShipmentInfo>();
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipments();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.SHIPMENT;
parameter.ShipmentIdList = shipmentIdList;
var apiResult = amznConn.FulFillmentInbound.GetShipments(parameter);
AppendNextToken(ref apiResult);
return TransposeModel(apiResult);
}
private void AddShipmentStatusList(ref FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipments parameters)
{
var list = new List<ShipmentStatus>();
list.Add(ShipmentStatus.CANCELLED);
list.Add(ShipmentStatus.CHECKED_IN);
list.Add(ShipmentStatus.CLOSED);
list.Add(ShipmentStatus.DELETED);
list.Add(ShipmentStatus.DELIVERED);
list.Add(ShipmentStatus.ERROR);
list.Add(ShipmentStatus.IN_TRANSIT);
list.Add(ShipmentStatus.READY_TO_SHIP);
list.Add(ShipmentStatus.RECEIVING);
list.Add(ShipmentStatus.SHIPPED);
list.Add(ShipmentStatus.WORKING);
parameters.ShipmentStatusList = list;
}
// checks for next-token, if true appends additional data to the ShipmentData
private void AppendNextToken(ref FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.GetShipmentsResult shipmentList)
{
while (!string.IsNullOrEmpty(shipmentList.NextToken))
{
// build the request
var parameter = new FikaAmazonAPI.Parameter.FulFillmentInbound.ParameterGetShipments();
parameter.MarketplaceId = amznConn.GetCurrentMarketplace.ID;
parameter.QueryType = FikaAmazonAPI.Utils.Constants.QueryType.NEXT_TOKEN;
parameter.NextToken = shipmentList.NextToken;
var result = amznConn.FulFillmentInbound.GetShipments(parameter);
shipmentList.ShipmentData.AddRange(result.ShipmentData);
shipmentList.NextToken = result.NextToken;
}
}
// transposes return api object data to my model
private List<Model.AmazonFba.ShipmentInfo> TransposeModel(FikaAmazonAPI.AmazonSpApiSDK.Models.FulfillmentInbound.GetShipmentsResult shipmentResult)
{
var returnList = new List<Model.AmazonFba.ShipmentInfo>();
for (var i = 0; i < shipmentResult.ShipmentData.Count; i++)
{
var item = new Model.AmazonFba.ShipmentInfo();
item.FbaShipmentId = shipmentResult.ShipmentData[i].ShipmentId;
item.DestinationFulfillmentCenterId = shipmentResult.ShipmentData[i].DestinationFulfillmentCenterId;
item.ShipmentName = shipmentResult.ShipmentData[i].ShipmentName;
item.ShipmentStatus = shipmentResult.ShipmentData[i].ShipmentStatus.ToString();
returnList.Add(item);
}
return returnList;
}
}
}

View File

@@ -0,0 +1,100 @@
//using MarketplaceWebServiceProducts.Model;
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.AmazonSpApiSDK.Models.ProductFees;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.ProductFee
{
public class GetFeeEstimate
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public string CurrencyCode { get; set; } = "GBP";
public string MarketPlaceId { get; set; }
public GetFeeEstimate()
{
}
public Model.Amazon.ProductFeeEstimate GetFba(string asin, int productId, decimal listingPrice)
{
var returnObj = new Model.Amazon.ProductFeeEstimate();
if (string.IsNullOrWhiteSpace(asin))
{
throw new Exception("ASIN given to GetFeeEstimate is null or whitespace.");
}
var listingPriceObj = new MoneyType(CurrencyCode, listingPrice);
var priceToEstimateFees = new PriceToEstimateFees(listingPriceObj);
// create the request and get a response
var request = new FeesEstimateRequest(MarketPlaceId, true, priceToEstimateFees, productId.ToString());
var result = amznConn.ProductFee.GetMyFeesEstimateForASIN(asin, request);
if (result.FeesEstimateIdentifier.IdValue != asin)
throw new Exception("returned ud value does not match ASIN");
returnObj.Asin = asin;
returnObj.ProductId = int.Parse(result.FeesEstimateIdentifier.SellerInputIdentifier);
// test for error
if (result.Error != null)
{
var sb = new StringBuilder();
sb.AppendLine("ASIN: " + asin);
sb.AppendLine("Error Code: " + result.Error.Code);
if (result.Error.Detail != null)
{ sb.AppendLine("Detail: " + result.Error.Detail); }
if (result.Error.Message != null)
{ sb.AppendLine("Message: " + result.Error.Message); }
if (result.Error.Type != null)
{ sb.AppendLine("Type: " + result.Error.Type); }
MiscFunction.EventLogInsert("Error running GetProductEstimateFee for ASIN:" + asin + ", further details attached.", 1, sb.ToString());
throw new Exception("ProductFeeEstimate error, check logs for further details");
}
returnObj.IsAmazonFulfilled = result.FeesEstimateIdentifier.IsAmazonFulfilled.Value;
returnObj.TimeOfFeeEstimation = result.FeesEstimate.TimeOfFeesEstimation.Value;
returnObj.TotalFeeEstimate = result.FeesEstimate.TotalFeesEstimate.Amount.Value;
returnObj.CurrencyCode = result.FeesEstimate.TotalFeesEstimate.CurrencyCode;
returnObj.PriceToEstimateFeeListingPrice = result.FeesEstimateIdentifier.PriceToEstimateFees.ListingPrice.Amount.Value;
returnObj.PriceToEstimateFeeShipping = 0;
if (result.FeesEstimateIdentifier.PriceToEstimateFees.Shipping != null)
returnObj.PriceToEstimateFeeShipping = result.FeesEstimateIdentifier.PriceToEstimateFees.Shipping.Amount.Value;
returnObj.PriceToEstimateFeePoints = 0;
if (result.FeesEstimateIdentifier.PriceToEstimateFees.Points != null)
returnObj.PriceToEstimateFeePoints = result.FeesEstimateIdentifier.PriceToEstimateFees.Points.PointsMonetaryValue.Amount.Value;
returnObj.ReferralFee = 0m;
returnObj.VariableClosingFee = 0m;
returnObj.FulfillmentFees = 0m;
returnObj.PerItemFee = 0m;
returnObj.OtherFee_Exception = 0m;
FeeDetailList feeDetailList = result.FeesEstimate.FeeDetailList;
List<FeeDetail> feeDetail = feeDetailList;
foreach (FeeDetail feeDetailItem in feeDetail)
{
if (feeDetailItem.FeeType == "AmazonReferralFee" || feeDetailItem.FeeType == "ReferralFee")
{ returnObj.ReferralFee = (decimal)feeDetailItem.FinalFee.Amount; }
else if (feeDetailItem.FeeType == "VariableClosingFee")
{ returnObj.VariableClosingFee = (decimal)feeDetailItem.FinalFee.Amount; }
else if (feeDetailItem.FeeType == "PerItemFee")
{ returnObj.PerItemFee = (decimal)feeDetailItem.FinalFee.Amount; }
else if (feeDetailItem.FeeType == "FBAFees" || feeDetailItem.FeeType == "FulfillmentFees")
{ returnObj.FulfillmentFees = (decimal)feeDetailItem.FinalFee.Amount; }
else
{ returnObj.OtherFee_Exception = returnObj.OtherFee_Exception + (decimal)feeDetailItem.FinalFee.Amount; }
}
return returnObj;
}
}
}

View File

@@ -0,0 +1,155 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.AmazonSpApiSDK.Models.ProductPricing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.ProductPricing
{
public class GetCompetitivePricing
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public string MarketPlaceId { get; set; }
/// <summary>
/// Gets Amazon Buy Box price for a given product. Will return no price if page does not have buy box
/// </summary>
public GetCompetitivePricing()
{
}
/// <summary>
/// Retrives current Buy Box price (+ additional info) for a given ASIN
/// </summary>
/// <param name="asin">Amazon ASIN product reference</param>
/// <returns></returns>
public Model.Amazon.ProductCompetitivePrice ByAsin(string asin)
{
var result = Execute(new List<string> { asin }, false);
if (result.Any()) { return result[0]; }
else { return null; }
}
/// <summary>
/// Retrives current Buy Box price (+ additional info) for a given ASIN
/// </summary>
/// <param name="asin">Amazon ASIN product reference</param>
/// <returns></returns>
public List<Model.Amazon.ProductCompetitivePrice> ByAsin(List<string> asinList)
{
return Execute(asinList, false);
}
/// <summary>
/// Ideally use ASIN
/// </summary>
/// <param name="skuList"></param>
/// <returns></returns>
private Model.Amazon.ProductCompetitivePrice BySku(string sku)
{
var result = Execute(new List<string> { sku }, true);
if (result.Any()) { return result[0]; }
else { return null; }
}
/// <summary>
/// Ideally use ASIN
/// </summary>
/// <param name="skuList"></param>
/// <returns></returns>
private List<Model.Amazon.ProductCompetitivePrice> BySku(List<string> skuList)
{
return Execute(skuList, true);
}
private List<Model.Amazon.ProductCompetitivePrice> Execute(List<string> itemList, bool isSkuList)
{
var apiList = new List<Price>();
// max of 20 items in one call
int i = 0;
int total = itemList.Count;
var itemRequestList = new List<string>();
foreach (string sku in itemList)
{
i++;
itemRequestList.Add(sku);
if (i == total || i % 20 == 0)
{
var parameter = new FikaAmazonAPI.Parameter.ProductPricing.ParameterGetCompetitivePricing();
if (isSkuList) { parameter.Skus = itemRequestList; }
else { parameter.Asins = itemRequestList; }
parameter.MarketplaceId = MarketPlaceId;
apiList.AddRange(amznConn.ProductPricing.GetCompetitivePricing(parameter));
itemRequestList = new List<string>();
}
}
return TransposeData(apiList);
}
private List<Model.Amazon.ProductCompetitivePrice> TransposeData(IList<Price> spapiList)
{
var returnList = new List<Model.Amazon.ProductCompetitivePrice>();
foreach (var item in spapiList)
{
string asin = item.ASIN;
decimal competitivePrice;
bool competitivePriceIsSet;
bool isBuyBox;
bool buyBoxBelongsToRequester;
int offersCountNew = 0;
int offersCountUsed = 0;
if (item.Product.CompetitivePricing.CompetitivePrices.Count == 0)
{
competitivePrice = 0;
competitivePriceIsSet = false;
isBuyBox = false;
buyBoxBelongsToRequester = false;
}
else if (item.Product.CompetitivePricing.CompetitivePrices.Count == 1)
{
if (item.Product.CompetitivePricing.CompetitivePrices[0].Condition != "New")
throw new Exception("Condition returned is not new");
competitivePrice = item.Product.CompetitivePricing.CompetitivePrices[0].Price.LandedPrice.Amount.Value;
competitivePriceIsSet = true;
isBuyBox = true;
buyBoxBelongsToRequester = item.Product.CompetitivePricing.CompetitivePrices[0].BelongsToRequester.Value;
}
else
{
throw new Exception("More than one competitive price returned");
}
// get quanities
foreach (var offer in item.Product.CompetitivePricing.NumberOfOfferListings)
{
if (offer.Condition == "New") { offersCountNew = offer.Count.Value; }
if (offer.Condition == "Used") { offersCountUsed = offer.Count.Value; }
}
// add to list
var returnItem = new Model.Amazon.ProductCompetitivePrice(
asin
, competitivePrice
, competitivePriceIsSet
, isBuyBox
, buyBoxBelongsToRequester
, offersCountNew
, offersCountUsed);
returnList.Add(returnItem);
}
return returnList;
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaCustomerReturn : ReportLogic
{
public FbaCustomerReturn() : base(ReportTypes.GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA)
{
}
public void GetReport(DateTime startTime, DateTime endTime)
{
int maxRange = 0; // there doesn't appear to be any limit on time span
DownloadTimePeriodReport(startTime, endTime, maxRange);
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaInventory : ReportLogic
{
public FbaInventory() : base (ReportTypes.GET_FBA_MYI_ALL_INVENTORY_DATA)
{
}
public void GetReport(int reportMaxAge = 30)
{
// Amazon will throttle (return 'FATAL' error) when requesting this report twice within 15 minutes
DownloadSnapshotReport(reportMaxAge);
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaInventoryAdustment : ReportLogic
{
public FbaInventoryAdustment() : base(ReportTypes.GET_FBA_FULFILLMENT_INVENTORY_ADJUSTMENTS_DATA)
{
throw new Exception("report has been depreciated https://developer-docs.amazon.com/sp-api/docs/sp-api-deprecations");
}
public void GetReport(DateTime startTime, DateTime endTime)
{
DownloadTimePeriodReport(startTime, endTime, 0);
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaInventoryAge : ReportLogic
{
public FbaInventoryAge() : base(ReportTypes.GET_FBA_INVENTORY_AGED_DATA)
{
throw new Exception("report has been depreciated https://developer-docs.amazon.com/sp-api/docs/sp-api-deprecations");
}
public new void GetReport(int reportMaxAge = 30)
{
throw new Exception("GET_FBA_INVENTORY_AGED_DATA report has been retired since 22/06/2022 and replaced by GET_FBA_INVENTORY_PLANNING_DATA");
//DownloadSnapshotReport(reportMaxAge);
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaInventoryReceipt : ReportLogic
{
/*
* Not able to uniquley define each row in flat file and check for duplicate in DB
* therefore, do not download report date range that has already been imported, as records will be duplicated
*
* Due to a MWS bug, MWS can/will include some records that are before the specified date range. As mws report is updated once daily,
* it is safe to omitt lines < startDate when parsing/inserting lines into db (as these will have been previously imported)
*/
public FbaInventoryReceipt() : base(ReportTypes.GET_FBA_FULFILLMENT_INVENTORY_RECEIPTS_DATA)
{
throw new Exception("report has been depreciated https://developer-docs.amazon.com/sp-api/docs/sp-api-deprecations");
}
public void GetReport(DateTime startTime, DateTime endTime)
{
DownloadTimePeriodReport(startTime, endTime, 0);
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaReimbursement : ReportLogic
{
public FbaReimbursement() : base(ReportTypes.GET_FBA_REIMBURSEMENTS_DATA)
{
}
public void GetReport(DateTime startTime, DateTime endTime)
{
DownloadTimePeriodReport(startTime, endTime, 0);
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaRemovalOrder : ReportLogic
{
public FbaRemovalOrder() : base(ReportTypes.GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA)
{
}
public void GetReport(DateTime startTime, DateTime endTime)
{
DownloadTimePeriodReport(startTime, endTime, 0);
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class FbaSaleShipment : ReportLogic
{
//public FbaSaleShipment() : base(ReportTypes.GET_FBA_FULFILLMENT_CUSTOMER_SHIPMENT_SALES_DATA)
public FbaSaleShipment() : base(ReportTypes.GET_AMAZON_FULFILLED_SHIPMENTS_DATA_GENERAL)
{
}
public void GetReport(DateTime startTime, DateTime endTime)
{
DownloadTimePeriodReport(startTime, endTime, 30);
}
}
}

View File

@@ -0,0 +1,236 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.Parameter.Report;
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class ReportLogic
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
private FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report report;
private ReportTypes reportType;
protected Logic.Log.LogEvent log = new Logic.Log.LogEvent();
public DateTime? ReportCreatedTime
{
get
{
if (report == null) { return null; }
else { return report.CreatedTime; }
}
}
public bool ReportDoneNoData { get; private set; }
public string ReportFilePath { get; private set; }
private FikaAmazonAPI.Utils.MarketplaceIds MarketPlaceIds { get; set; }
public bool ReportFilePathIsSet
{
get { return !string.IsNullOrWhiteSpace(ReportFilePath); }
}
public ReportLogic(ReportTypes reportType)
{
this.reportType = reportType;
this.MarketPlaceIds = new MarketplaceIds();
this.MarketPlaceIds.Add(amznConn.GetCurrentMarketplace.ID);
Innit();
}
private void Innit()
{
ReportDoneNoData = false;
ReportFilePath = null;
report = null;
}
/// <summary>
/// Always use this function to report and it's filepath, this ensures the two correlate
/// </summary>
/// <param name="report"></param>
/// <param name="reportFilePath"></param>
private void SetFilePath(FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report report, string reportFilePath)
{
this.report = report;
this.ReportFilePath = reportFilePath;
}
protected void DownloadTimePeriodReport(DateTime utcDataStartTime, DateTime utcDataEndTime, int maxDateRangeDays)
{
if (utcDataStartTime.Kind != DateTimeKind.Utc || utcDataEndTime.Kind != DateTimeKind.Utc)
throw new Exception("Report period time should be set to UTC");
if (maxDateRangeDays > 0 && (utcDataEndTime - utcDataStartTime).TotalDays > maxDateRangeDays)
throw new Exception("Date range for report is greater than the maximum allowable");
var specification = new ParameterCreateReportSpecification();
specification.marketplaceIds = this.MarketPlaceIds;
specification.reportType = reportType;
specification.dataStartTime = utcDataStartTime;
specification.dataEndTime = utcDataEndTime;
DownloadReport(specification, false);
}
protected void DownloadSnapshotReport(int snapshotMaxAge)
{
var specification = new ParameterCreateReportSpecification();
specification.marketplaceIds = this.MarketPlaceIds;
specification.reportType = reportType;
DownloadReport(specification, true, snapshotMaxAge);
}
private void DownloadReport(ParameterCreateReportSpecification specification, bool isSnapshotReport, int snapshotMaxAge = 0)
{
// Amazon create report is throttled to 1 report every 15 minutes
Innit();
// check for existing report with same specification
string reportId = ExistingReportSearch(specification);
if (reportId == null)
{ reportId = amznConn.Reports.CreateReport(specification); }
var filePath = amznConn.Reports.GetReportFile(reportId);
var report = amznConn.Reports.GetReport(reportId); // filePath and report need to be called in this order
if (!string.IsNullOrWhiteSpace(filePath))
{
SetFilePath(report, filePath);
return;
}
else
{
// test for 'Fatal' return when report has recently been requested.
report = amznConn.Reports.GetReport(reportId);
if (report.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.CANCELLED)
{
// From SPAPI Documentation: The report was cancelled. There are two ways a report can be cancelled:
// an explicit cancellation request before the report starts processing, or an automatic cancellation
// if there is no data to return.
log.Initialise();
log.LogInformation("ReportID:" + reportId + " returned 'CANCELLED' status (no data).");
ReportDoneNoData = true;
return;
}
else if (report.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.FATAL)
{
if (isSnapshotReport)
{
SnapahotThrottleHanderler(ref report, specification, snapshotMaxAge);
filePath = amznConn.Reports.GetReportFile(report.ReportId);
if (string.IsNullOrWhiteSpace(filePath))
{
LogReportError(report, "Error while retriving report " + reportType.ToString());
throw new Exception("Error while retriving report " + reportType.ToString());
}
SetFilePath(report, filePath);
return;
}
else
{
throw new Exception("Report processing status returned 'FATAL' report#" + reportType.ToString());
}
}
}
throw new Exception("Error while retriving " + reportType.ToString() + " report, nothing should be getting here!!");
}
/// <summary>
/// If a duplicate report has been recently requested, Amazon may return 'FATAL'. This method tests for, and attempts to retrive the duplicate report that is causing the error.
/// </summary>
/// <param name="report">Report to test for throttled response</param>
/// <param name="specification">The specification that created to throttle report.</param>
private void SnapahotThrottleHanderler(ref FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report report, ParameterCreateReportSpecification specification, int snapshotMaxAge)
{
if (report.ProcessingStatus != FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.FATAL)
return;
if (snapshotMaxAge <= 0)
{
// report not avaiable
throw new Exception( reportType.ToString() + " report not avaibale for requested timeframe");
}
// search for valid reports with required timeframe
var parameters = new ParameterReportList();
parameters.reportTypes = new List<ReportTypes> { specification.reportType };
parameters.createdSince = report.CreatedTime.Value.AddMinutes(-snapshotMaxAge);
parameters.marketplaceIds = specification.marketplaceIds;
var reports = amznConn.Reports.GetReports(parameters);
if (reports == null || !reports.Any())
{
return;
}
foreach (var item in reports)
{
if (item.ProcessingStatus != FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.CANCELLED
&& item.ProcessingStatus != FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.FATAL)
{
report = item;
}
}
}
private string ExistingReportSearch(ParameterCreateReportSpecification specification)
{
// amazon may return 'fatal' due to report already existing and/or report request matches an recent existing request
// search for valid reports with required timeframe
var parameters = new ParameterReportList();
parameters.reportTypes = new List<ReportTypes> { specification.reportType };
parameters.marketplaceIds = specification.marketplaceIds;
var reportList = amznConn.Reports.GetReports(parameters);
// list is ordered with the most recent first
foreach (var item in reportList)
{
if (item.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.DONE
|| item.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.INPROGRESS
|| item.ProcessingStatus == FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report.ProcessingStatusEnum.INQUEUE)
{
if(item.DataStartTime == specification.dataStartTime
&& item.DataEndTime == specification.dataEndTime)
{
return item.ReportId;
}
}
}
return null;
}
private void LogReportError(FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report report, string errorTitle)
{
log.Initialise();
log.LogError(errorTitle,
"ReportType: " + report.ReportType + "\r\n"
+ "ReportId: " + report.ReportId + "\r\n"
+ "MarketplaceIds: " + report.MarketplaceIds + "\r\n"
+ "CreatedTime: " + report.CreatedTime + "\r\n"
+ "ReportScheduleId: " + report.ReportScheduleId + "\r\n"
+ "ReportDocumentId: " + report.ReportDocumentId + "\r\n"
+ "DataStartTime: " + report.DataStartTime + "\r\n"
+ "DataEndTime: " + report.DataEndTime + "\r\n"
+ "ProcessingStartTime: " + report.ProcessingStartTime + "\r\n"
+ "ProcessingEndTime: " + report.ProcessingEndTime + "\r\n"
+ "ProcessingStatus: " + report.ProcessingStatus + "\r\n"
);
}
}
}

View File

@@ -0,0 +1,52 @@
using bnhtrade.Core.Data.Amazon.SellingPartnerAPI;
using FikaAmazonAPI;
using FikaAmazonAPI.Parameter.Report;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.Report
{
public class SettlementReport
{
private AmazonConnection amznConn = new SpApiConnection().Connection;
public SettlementReport ()
{
}
/// <summary>
/// Gets a list of reportId (not settlement report Id) for settlement reports available on the amazon api
/// </summary>
/// <returns>ReportId list</returns>
public List<string> ListAvaliableReports()
{
UI.Console.WriteLine("Requesting list of avaliable settlement reports form Amazon SP-API");
// set parameters
var parameters = new ParameterReportList();
parameters.reportTypes = new List<ReportTypes>() { ReportTypes.GET_V2_SETTLEMENT_REPORT_DATA_FLAT_FILE_V2};
parameters.marketplaceIds.Add(amznConn.GetCurrentMarketplace.ID);
// request from amazon
var result = amznConn.Reports.GetReports(parameters);
var returnList = new List<string>();
foreach (var report in result)
{
returnList.Add(report.ReportId);
}
UI.Console.WriteLine("{0} Settlement reports avaible on Amazon SP-API");
return returnList;
}
public string GetFile(string reportId)
{
return amznConn.Reports.GetReportFile(reportId);
}
}
}

View File

@@ -0,0 +1,122 @@
////using bnhtrade.Core.Data.Amazon.SellingPartnerAPI.Services;
//using FikaAmazonAPI.Services;
//using System;
//using System.Collections.Generic;
//using System.Text;
//namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI
//{
// public class AmazonConnection
// {
// private AmazonCredential Credentials { get; set; }
// public FbaInboundService FbaInbound => this._FbaInbound ?? throw _NoCredentials;
// public FbaInventoryService FbaInventory => this._FbaInventory ?? throw _NoCredentials;
// public FulFillmentInboundService FulFillmentInbound => this._FulFillmentInbound ?? throw _NoCredentials;
// public ProductFeeService ProductFee => this._ProductFee ?? throw _NoCredentials;
// public ProductPricingService ProductPricing => this._ProductPricing ?? throw _NoCredentials;
// public ReportService Reports => this._Reports ?? throw _NoCredentials;
// //public AplusContentService AplusContent => this._AplusContent ?? throw _NoCredentials;
// //public AuthorizationService Authorization => this._Authorization ?? throw _NoCredentials;
// //public CatalogItemService CatalogItem => this._CatalogItems ?? throw _NoCredentials;
// //public FbaInboundEligibilityService FbaInboundEligibility => this._FbaInboundEligibility ?? throw _NoCredentials;
// //public FbaOutboundService FbaOutbound => this._FbaOutbound ?? throw _NoCredentials;
// //public FbaSmallandLightService FbaSmallandLight => this._FbaSmallandLight ?? throw _NoCredentials;
// //public FeedService Feed => this._Feed ?? throw _NoCredentials;
// //public FinancialService Financial => this._Financials ?? throw _NoCredentials;
// //public FulFillmentOutboundService FulFillmentOutbound => this._FulFillmentOutbound ?? throw _NoCredentials;
// //public ListingsItemService ListingsItem => this._ListingsItem ?? throw _NoCredentials;
// //public MerchantFulfillmentService MerchantFulfillment => this._MerchantFulfillment ?? throw _NoCredentials;
// //public MessagingService Messaging => this._Messaging ?? throw _NoCredentials;
// //public NotificationService Notification => this._Notification ?? throw _NoCredentials;
// //public OrderService Orders => this._Orders ?? throw _NoCredentials;
// //public SalesService Sales => this._Sales ?? throw _NoCredentials;
// //public SellerService Seller => this._Seller ?? throw _NoCredentials;
// //public ServicesService Services => this._Services ?? throw _NoCredentials;
// //public ShipmentInvoicingService ShipmentInvoicing => this._ShipmentInvoicing ?? throw _NoCredentials;
// //public ShippingService Shipping => this._Shipping ?? throw _NoCredentials;
// //public SolicitationService Solicitations => this._Solicitations ?? throw _NoCredentials;
// //public TokenService Tokens => this._Tokens ?? throw _NoCredentials;
// //public UploadService Upload => this._Upload ?? throw _NoCredentials;
// private FbaInboundService _FbaInbound { get; set; }
// private FbaInventoryService _FbaInventory { get; set; }
// private FulFillmentInboundService _FulFillmentInbound { get; set; }
// private ProductFeeService _ProductFee { get; set; }
// private ProductPricingService _ProductPricing { get; set; }
// private ReportService _Reports { get; set; }
// //private AplusContentService _AplusContent { get; set; }
// //private AuthorizationService _Authorization { get; set; }
// //private CatalogItemService _CatalogItems { get; set; }
// //private FbaInboundEligibilityService _FbaInboundEligibility { get; set; }
// //private FbaOutboundService _FbaOutbound { get; set; }
// //private FbaSmallandLightService _FbaSmallandLight { get; set; }
// private FeedService _Feed { get; set; }
// //private FinancialService _Financials { get; set; }
// //private FulFillmentOutboundService _FulFillmentOutbound { get; set; }
// //private ListingsItemService _ListingsItem { get; set; }
// //private MerchantFulfillmentService _MerchantFulfillment { get; set; }
// //private MessagingService _Messaging { get; set; }
// //private NotificationService _Notification { get; set; }
// //private OrderService _Orders { get; set; }
// //private SalesService _Sales { get; set; }
// //private SellerService _Seller { get; set; }
// //private ServicesService _Services { get; set; }
// //private ShipmentInvoicingService _ShipmentInvoicing { get; set; }
// //private ShippingService _Shipping { get; set; }
// //private SolicitationService _Solicitations { get; set; }
// //private TokenService _Tokens { get; set; }
// //private UploadService _Upload { get; set; }
// private UnauthorizedAccessException _NoCredentials = new UnauthorizedAccessException($"Error, you cannot make calls to Amazon without credentials!");
// public AmazonConnection(AmazonCredential Credentials)
// {
// this.Authenticate(Credentials);
// }
// public void Authenticate(AmazonCredential Credentials)
// {
// if (this.Credentials == default(AmazonCredential))
// Init(Credentials);
// else
// throw new InvalidOperationException("Error, you are already authenticated to amazon in this AmazonConnection, dispose of this connection and create a new one to connect to a different account.");
// }
// private void Init(AmazonCredential Credentials)
// {
// this.Credentials = Credentials;
// this._FbaInbound = new FbaInboundService(this.Credentials);
// this._FbaInventory = new FbaInventoryService(this.Credentials);
// this._FulFillmentInbound = new FulFillmentInboundService(this.Credentials);
// this._ProductFee = new ProductFeeService(this.Credentials);
// this._ProductPricing = new ProductPricingService(this.Credentials);
// this._Reports = new ReportService(this.Credentials);
// //this._AplusContent = new AplusContentService(this.Credentials);
// //this._CatalogItems = new CatalogItemService(this.Credentials);
// //this._FbaInboundEligibility = new FbaInboundEligibilityService(this.Credentials);
// //this._FbaOutbound = new FbaOutboundService(this.Credentials);
// //this._FbaSmallandLight = new FbaSmallandLightService(this.Credentials);
// this._Feed = new FeedService(this.Credentials);
// //this._Financials = new FinancialService(this.Credentials);
// //this._FulFillmentOutbound= new FulFillmentOutboundService(this.Credentials);
// //this._ListingsItem = new ListingsItemService(this.Credentials);
// //this._MerchantFulfillment = new MerchantFulfillmentService(this.Credentials);
// //this._Messaging= new MessagingService(this.Credentials);
// //this._Notification= new NotificationService(this.Credentials);
// //this._Orders = new OrderService(this.Credentials);
// //this._Sales= new SalesService(this.Credentials);
// //this._Seller= new SellerService(this.Credentials);
// //this._Services= new ServicesService(this.Credentials);
// //this._ShipmentInvoicing= new ShipmentInvoicingService(this.Credentials);
// //this._Shipping= new ShippingService(this.Credentials);
// //this._Solicitations = new SolicitationService(this.Credentials);
// //this._Tokens= new TokenService(this.Credentials);
// //this._Upload= new UploadService(this.Credentials);
// }
// }
//}

View File

@@ -0,0 +1,103 @@
//using bnhtrade.Core.Data.Amazon.SellingPartnerAPI.SDK.Models.Token;
//using bnhtrade.Core.Data.Amazon.SellingPartnerAPI.Utils;
using FikaAmazonAPI.AmazonSpApiSDK.Models.Token;
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using static FikaAmazonAPI.AmazonSpApiSDK.Models.Token.CacheTokenData;
using static FikaAmazonAPI.Utils.Constants;
//using static bnhtrade.Core.Data.Amazon.SellingPartnerAPI.SDK.Models.Token.CacheTokenData;
//using static bnhtrade.Core.Data.Amazon.SellingPartnerAPI.Utils.Constants;
namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI
{
public class AmazonCredential
{
public string AccessKey { get; set; }
public string SecretKey { get; set; }
public string RoleArn { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string RefreshToken { get; set; }
public MarketPlace MarketPlace { get; set; }
private CacheTokenData CacheTokenData { get; set; } = new CacheTokenData();
public bool IsActiveLimitRate { get; set; } = true;
public Environments Environment { get; set; } = Environments.Production;
public AmazonCredential()
{
// attempt to retrive credentials from app.local.config
try
{
Innit(ConfigurationManager.AppSettings["SpapiAccessKey"]
, ConfigurationManager.AppSettings["SpapiSecretKey"]
, ConfigurationManager.AppSettings["SpapiRoleArn"]
, ConfigurationManager.AppSettings["SpapiClientId"]
, ConfigurationManager.AppSettings["SpapiClientSecret"]
, ConfigurationManager.AppSettings["SpapiRefreshToken"]);
if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["SpapiMarketplaceId"]))
{
this.MarketPlace = MarketPlace.UnitedKingdom;
}
}
catch (Exception ex)
{
throw new Exception("Unable to retirve Amazon SP API credentials: " + ex.Message);
}
}
private AmazonCredential(string accessKey, string secretKey, string roleArn, string clientId, string clientSecret, string refreshToken)
{
// Use other method by default, however can change this method back to public is the need arises.
Innit(accessKey
, secretKey
, roleArn
, clientId
, clientSecret
, refreshToken);
}
public AmazonCredential(Core.Model.Credentials.AmazonSPAPI userCredentials)
{
Innit(userCredentials.AccessKey
, userCredentials.SecretKey
, userCredentials.RoleArn
, userCredentials.ClientId
, userCredentials.ClientSecret
, userCredentials.RefreshToken);
}
private void Innit(string accessKey, string secretKey, string roleArn, string clientId, string clientSecret, string refreshToken)
{
this.AccessKey = accessKey;
this.SecretKey = secretKey;
this.RoleArn = roleArn;
this.ClientId = clientId;
this.ClientSecret = clientSecret;
this.RefreshToken = refreshToken;
}
public TokenResponse GetToken(TokenDataType tokenDataType)
{
return CacheTokenData.GetToken(tokenDataType);
}
public void SetToken(TokenDataType tokenDataType, TokenResponse token)
{
CacheTokenData.SetToken(tokenDataType, token);
}
public AWSAuthenticationTokenData GetAWSAuthenticationTokenData()
{
return CacheTokenData.GetAWSAuthenticationTokenData();
}
public void SetAWSAuthenticationTokenData(AWSAuthenticationTokenData tokenData)
{
CacheTokenData.SetAWSAuthenticationTokenData(tokenData);
}
}
}

View File

@@ -0,0 +1,22 @@
using FikaAmazonAPI.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI
{
public class Defaults
{
public MarketPlace MarketPlaceId()
{
return MarketPlace.GetMarketPlaceByID(ConfigurationManager.AppSettings["SpapiMarketplaceId"]);
}
public string MarketPlaceIdAsString()
{
return ConfigurationManager.AppSettings["SpapiMarketplaceId"];
}
}
}

View File

@@ -0,0 +1,318 @@
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.Text;
//namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI.Services
//{
// public class ReportService : RequestService
// {
// private Dictionary<string, RestSharp.RestResponse<SDK.Models.Reports.Report>> reportList;
// private Dictionary<string, string> filePath;
// private bool fatalEncounter = false;
// protected Logic.Log.LogEvent log = new Logic.Log.LogEvent();
// private int reportRequestCount = 0;
// public ReportService() : base (new AmazonCredential())
// {
// Innit();
// }
// public ReportService(AmazonCredential amazonCredential) : base(amazonCredential)
// {
// Innit();
// }
// public void Innit()
// {
// reportList = new Dictionary<string, RestSharp.RestResponse<FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report>>();
// filePath = new Dictionary<string, string>();
// }
// public FikaAmazonAPI.AmazonSpApiSDK.Models.Reports.Report GetReport(string reportId, bool forceRequery = false)
// {
// // Rate limit: 2.0 requests per second, 15 burst
// int rateLimitMilliseconds = 500;
// if (reportList.ContainsKey(reportId))
// {
// if (forceRequery)
// {
// reportList.Remove(reportId);
// }
// else
// {
// return reportList[reportId].Data;
// }
// }
// // request report form amaozn
// if (reportRequestCount == 0)
// {
// UI.Console.WriteLine("Requesting report from amazon SPAPI (ReportId:" + reportId + ").");
// reportRequestCount = reportRequestCount + 1;
// }
// CreateAuthorizedRequest(ReportApiUrls.GetReport(reportId), RestSharp.Method.Get);
// var response = ExecuteRequestWithHttpInfo<SDK.Models.Reports.Report>(rateLimitMilliseconds);
// if (response == null)
// { return null; }
// reportList.Add(response.Data.ReportId, response);
// return response.Data;
// }
// public List<SDK.Models.Reports.Report> GetReports(ParameterReportList parameterReportList)
// {
// var parameters = parameterReportList.getParameters();
// CreateAuthorizedRequest(ReportApiUrls.GetReports, RestSharp.Method.Get, parameters);
// var response = ExecuteRequest<GetReportsResponseV00>();
// parameterReportList.nextToken = response.NextToken;
// var list = response.Reports;
// while (!string.IsNullOrEmpty(parameterReportList.nextToken))
// {
// var nextTokenResponse = GetReportsByNextToken(parameterReportList);
// list.AddRange(nextTokenResponse.Reports);
// parameterReportList.nextToken = nextTokenResponse.NextToken;
// }
// return list;
// }
// public bool CancelReport(string reportId)
// {
// CreateAuthorizedRequest(ReportApiUrls.CancelReport(reportId), RestSharp.Method.Delete);
// var response = ExecuteRequest<CancelReportResponse>();
// if (response != null && response.Errors != null)
// return false;
// return true;
// }
// public ReportScheduleList GetReportSchedules(ParameterReportSchedules parametersSchedules)
// {
// var parameters = parametersSchedules.getParameters();
// CreateAuthorizedRequest(ReportApiUrls.GetReportSchedules, RestSharp.Method.Get, parameters);
// var response = ExecuteRequest<GetReportSchedulesResponseV00>();
// if (response != null && response.ReportSchedules != null)
// return response.ReportSchedules;
// return null;
// }
// private GetReportsResponseV00 GetReportsByNextToken(ParameterReportList parameterReportList)
// {
// var parameterReportListNew = new ParameterReportList();
// parameterReportListNew.nextToken = parameterReportList.nextToken;
// var parameters = parameterReportListNew.getParameters();
// CreateAuthorizedRequest(ReportApiUrls.GetReports, RestSharp.Method.Get, parameters);
// var response = ExecuteRequest<GetReportsResponseV00>();
// return response;
// }
// public string CreateReport(ParameterCreateReportSpecification createReportSpecification)
// {
// CreateAuthorizedRequest(ReportApiUrls.CreateReport, RestSharp.Method.Post, null, createReportSpecification);
// var response = ExecuteRequest<SDK.Models.Reports.CreateReportResult>();
// if (response == null)
// return null;
// string reportId = response.ReportId;
// return response.ReportId;
// }
// public string CreateReportSchedule(ParameterCreateReportScheduleSpecification createReportScheduleSpecification)
// {
// CreateAuthorizedRequest(ReportApiUrls.CreateReportSchedule, RestSharp.Method.Post, null, createReportScheduleSpecification);
// var response = ExecuteRequest<CreateReportScheduleResult>();
// if (response == null)
// return null;
// return response.ReportScheduleId;
// }
// public ReportSchedule GetReportSchedule(string reportScheduleId)
// {
// CreateAuthorizedRequest(ReportApiUrls.GetReportSchedule(reportScheduleId), RestSharp.Method.Get);
// var response = ExecuteRequest<ReportSchedule>();
// if (response != null)
// return response;
// return null;
// }
// public ReportDocument GetReportDocument(string reportDocumentId, IParameterBasedPII ParameterBasedPII = null)
// {
// CreateAuthorizedRequest(ReportApiUrls.GetReportDocument(reportDocumentId), RestSharp.Method.Get, parameter: ParameterBasedPII);
// var response = ExecuteRequest<ReportDocument>();
// if (response != null)
// return response;
// return null;
// }
// public bool WaitForReportProcessing(SDK.Models.Reports.Report report)
// {
// // wait for report processing loop
// int checkCount = 0;
// int checkRequency = 10000;
// while (true)
// {
// checkCount++;
// if (checkCount > 60)
// {
// throw new Exception("GetReport timedout requesting reportId:" + report.ReportId + ".");
// }
// if (report.ProcessingStatus == SDK.Models.Reports.Report.ProcessingStatusEnum.DONE)
// {
// UI.Console.WriteLine("Report proccessing status is 'DONE' (ReportId:" + report.ReportId + ").");
// return true;
// }
// else if (report.ProcessingStatus == SDK.Models.Reports.Report.ProcessingStatusEnum.INPROGRESS)
// {
// // wait for 10 seconds between chacks
// UI.Console.Wait("Report processing 'In Progress'. Updating in {0} seconds...", checkRequency);
// report = GetReport(report.ReportId, true);
// }
// else if (report.ProcessingStatus == SDK.Models.Reports.Report.ProcessingStatusEnum.INQUEUE)
// {
// // wait for 10 seconds between chacks
// UI.Console.Wait("Report processing 'In Queue'. Updating in {0} seconds...", checkRequency);
// report = GetReport(report.ReportId, true);
// }
// else if (report.ProcessingStatus == SDK.Models.Reports.Report.ProcessingStatusEnum.CANCELLED)
// {
// // when report has been cancelled by client or amazon (no data)
// return false;
// }
// else if (report.ProcessingStatus == SDK.Models.Reports.Report.ProcessingStatusEnum.FATAL)
// {
// // some report requests will return a 'FATAL' if they have already been requsted recently (15 minutes).
// return false;
// }
// else
// {
// throw new Exception("New ReportProcessingStatusEnum '" + report.ProcessingStatus + "' "
// + " found for reportid:" + report.ReportId);
// }
// }
// }
// /// <summary>
// /// Retrives file containing Amazon SP-API report
// /// </summary>
// /// <param name="reportId">Amazon SP-API unique report id</param>
// /// <returns>File path for report</returns>
// public string GetReportFile(string reportId)
// {
// if (string.IsNullOrWhiteSpace(reportId))
// {
// throw new Exception("invalid Report ID");
// }
// // check for cached filepath
// if (!filePath.ContainsKey(reportId))
// {
// var report = GetReport(reportId); // this can return null, need to deal with this
// if (WaitForReportProcessing(report))
// {
// // download report from url
// string reportFilePath = GetFile(reportId);
// filePath.Add(reportId, reportFilePath);
// return reportFilePath;
// }
// else
// {
// return null;
// }
// }
// return filePath[reportId];
// }
// private string GetFile(string reportId)
// {
// // fatal error and reportDoument Id check
// if (fatalEncounter)
// {
// if (string.IsNullOrWhiteSpace(reportList[reportId].Data.ReportDocumentId))
// {
// log.LogError("Fatal error from Amazon SPAPI when requesting reportId:" + reportId
// , "The reason for the fatal error is unknown, no document was available for further information.");
// return "FATAL";
// }
// else
// {
// log.LogError("Fatal error from Amazon SPAPI when requesting reportId:" + reportId
// , "The report was aborted due to a fatal error and a reportDocumentId is present. Check reportDocumentId as it may explain why the report processing ended.");
// }
// fatalEncounter = false;
// }
// // as file url expires after 5 minutes, request just before download
// UI.Console.WriteLine("Requesting download url for Amazon report (ReportId:" + reportId + ").");
// var reportDocument = GetReportDocument(reportList[reportId].Data.ReportDocumentId);
// // download report from url
// log.LogInformation("Downloading Amazon report #" + reportId, "Report Document ID: " + reportDocument.ReportDocumentId);
// var response = new byte[0];
// using (var webClient = new System.Net.WebClient())
// {
// response = webClient.DownloadData(reportDocument.Url);
// }
// string report = null;
// // decrypt report
// UI.Console.WriteLine("Processing download (ReportId:" + reportId + ").");
// if (reportDocument.EncryptionDetails != null)
// {
// byte[] key = Encoding.ASCII.GetBytes(reportDocument.EncryptionDetails.Key);
// byte[] iv = Encoding.ASCII.GetBytes(reportDocument.EncryptionDetails.InitializationVector);
// report = Logic.Utilities.FileTransform.DecryptString(key, iv, response);
// }
// else
// {
// report = Encoding.ASCII.GetString(response);
// }
// // decompress
// if (reportDocument.CompressionAlgorithm != null)
// {
// report = Logic.Utilities.FileTransform.Decompress(report);
// }
// // save to file
// string reportFilePath = MiscFunction.GetTempFilePath(reportId + ".txt");
// System.IO.File.WriteAllText(reportFilePath, report);
// log.LogInformation("Amazon report #" + reportId + " sucessfully saved to disk.");
// return reportFilePath;
// }
// public bool CancelReportSchedule(string reportScheduleId)
// {
// CreateAuthorizedRequest(ReportApiUrls.CancelReportSchedule(reportScheduleId), RestSharp.Method.Delete);
// var response = ExecuteRequest<CancelReportScheduleResponse>();
// if (response != null && response.Errors != null)
// return false;
// return true;
// }
// protected void SleepForRateLimit(IList<RestSharp.Parameter> headers)
// {
// // get report has limit rate 0.0222 per second (1 every 45 seconds) and a burst of 10
// int defaultTime = 46000;
// SleepForRateLimit(headers, defaultTime);
// }
// }
//}

View File

@@ -0,0 +1,50 @@
using FikaAmazonAPI;
using FikaAmazonAPI.Utils;
using FikaAmazonAPI.AmazonSpApiSDK.Models.Token;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FikaAmazonAPI.AmazonSpApiSDK.Services.EnvironemntManager;
namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI
{
class SpApiConnection
{
public AmazonConnection Connection { get; private set; }
//public MarketPlace MarketPlace { get; private set; }
//public string MarketPlaceId { get; private set; }
public SpApiConnection()
{
InnitConnection();
}
private void InnitConnection()
{
// attempt to create credential object from app.local.config
var credential = new FikaAmazonAPI.AmazonCredential();
try
{
credential = new FikaAmazonAPI.AmazonCredential();
credential.AccessKey = ConfigurationManager.AppSettings["SpapiAccessKey"];
credential.SecretKey = ConfigurationManager.AppSettings["SpapiSecretKey"];
credential.RoleArn = ConfigurationManager.AppSettings["SpapiRoleArn"];
credential.ClientId = ConfigurationManager.AppSettings["SpapiClientId"];
credential.ClientSecret = ConfigurationManager.AppSettings["SpapiClientSecret"];
credential.RefreshToken = ConfigurationManager.AppSettings["SpapiRefreshToken"];
credential.MarketPlaceID = ConfigurationManager.AppSettings["SpapiMarketplaceId"];
credential.IsDebugMode = true;
credential.MaxThrottledRetryCount = 3;
}
catch (Exception ex)
{
throw new Exception("Unable to retirve Amazon SP API credentials: " + ex.Message);
}
this.Connection = new AmazonConnection(credential);
}
}
}

View File

@@ -1,14 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace bnhtrade.Core.Data.AmazonMWS
namespace bnhtrade.Core.Data.Amazon.SellingPartnerAPI.Utils
{
public class CurrentDateTime
{
@@ -38,9 +32,10 @@ namespace bnhtrade.Core.Data.AmazonMWS
return returnTime;
}
public DateTime GetLocal()
{
return GetUtc().ToLocalTime();
}
}
}
}

View File

@@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.AmazonMWS
{
public class CredentialMws
{
public string MerchantId { get { return "A3RUYNKLWWM5KW"; } }
public string MarketPlaceIdUK { get { return "A1F83G8C2ARO7P"; } } // Amazon.co.uk
public string AccessKeyId { get { return "AKIAJU45WSYVINEN45UA"; } }
public string SecretAccessKey { get { return "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"; } }
public string ApplicationName { get { return "bnhtrade.Core"; } }
public string ApplicationVersion { get { return "0.1"; } }
public string ServiceURL { get { return "https://mws.amazonservices.co.uk"; } }
}
}

View File

@@ -1,189 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FBAInboundServiceMWS.Model;
namespace bnhtrade.Core.Data.AmazonMWS.FBAInbound
{
class ListInboundShipmentItems
{
public string AmazonShipmentId { get; private set; }
public DateTime LastUpdatedAfter { get; private set; }
public DateTime LastUpdatedBefore { get; private set; }
public bool IsSetAmazonShipmentId()
{
return AmazonShipmentId != null;
}
public bool IsSetLastUpdatedAfter()
{
return LastUpdatedAfter != null;
}
public bool IsSetLastUpdatedBefore()
{
return LastUpdatedBefore != null;
}
public List<Model.AmazonFba.ShipmentItemInfo> GetByAmazonShipmentId(string amazonShipmentId)
{
// checks
if (amazonShipmentId.Length < 9)
{
throw new Exception("Amazon shipment id incorrect length '" + amazonShipmentId + "'");
}
var request = new ListInboundShipmentItemsRequest();
request.ShipmentId = amazonShipmentId;
AmazonShipmentId = amazonShipmentId;
return ListInboundShipmentItemsGet(request);
}
public List<Model.AmazonFba.ShipmentItemInfo> GetByDates(DateTime lastUpdatedAfter, DateTime lastUpdatedBefore)
{
//checks
if (lastUpdatedAfter >= lastUpdatedBefore)
{
throw new Exception("Paramter LastUpdatedAfter must be greater than LastUpdatedBefore");
}
var request = new ListInboundShipmentItemsRequest();
request.LastUpdatedAfter = lastUpdatedAfter;
request.LastUpdatedBefore = lastUpdatedBefore;
LastUpdatedAfter = lastUpdatedAfter;
LastUpdatedBefore = lastUpdatedBefore;
return ListInboundShipmentItemsGet(request);
}
private List<Model.AmazonFba.ShipmentItemInfo> ListInboundShipmentItemsGet(ListInboundShipmentItemsRequest request)
{
// variables
int mwsPollFrequency = 500;
int mwsPollTimeout = 60;
// add default entries, if not already set
if (!request.IsSetSellerId())
{
var cred = new AmazonMWS.CredentialMws();
request.SellerId = cred.MerchantId;
}
// checks
if ((request.IsSetLastUpdatedAfter() || request.IsSetLastUpdatedBefore()) && request.IsSetShipmentId())
{
throw new Exception("If ShipmentId is specified, LastUpdatedBefore and LastUpdatedAfter are ignored.");
}
// get amazon service, responce and result
var service = new AmazonMWS.Service().FbaInbound;
//var response = new ListInboundShipmentItemsResponse();
var result = new ListInboundShipmentItemsResult();
// poll mws for response
int count = 0;
do
{
var response = service.ListInboundShipmentItems(request);
if (response.IsSetListInboundShipmentItemsResult())
{
result = response.ListInboundShipmentItemsResult;
break;
}
else
{
Thread.Sleep(mwsPollFrequency);
count++;
}
} while (count < mwsPollTimeout);
if (count == mwsPollTimeout)
{
throw new Exception("Response from Amazon MWS timeout");
}
// create the return list
var returnList = new List<Model.AmazonFba.ShipmentItemInfo>();
// check a result was returned, return empty list on no results
if (!result.IsSetItemData())
{
return returnList;
}
// add data list
InboundShipmentItemList resultList = result.ItemData;
var infoList = new List<InboundShipmentItem>();
infoList.AddRange(resultList.member);
// check for next dataset
if (result.IsSetNextToken())
{
string nextToken = result.NextToken;
do
{
var nextRequest = new ListInboundShipmentItemsByNextTokenRequest();
var nextResult = new ListInboundShipmentItemsByNextTokenResult();
nextRequest.NextToken = nextToken;
nextRequest.SellerId = request.SellerId;
count = 0;
do
{
var response = service.ListInboundShipmentItemsByNextToken(nextRequest);
if (response.IsSetListInboundShipmentItemsByNextTokenResult())
{
nextResult = response.ListInboundShipmentItemsByNextTokenResult;
break;
}
else
{
Thread.Sleep(mwsPollFrequency);
count++;
}
} while (count < mwsPollTimeout);
if (count == mwsPollTimeout)
{
throw new Exception("Response from Amazon MWS timeout");
}
// add data to list
InboundShipmentItemList nextResultList = nextResult.ItemData;
infoList.AddRange(nextResultList.member);
if (nextResult.IsSetNextToken())
{
nextToken = nextResult.NextToken;
}
else
{
nextToken = "";
}
} while (nextToken.Length > 0); // next token is true
}
// load data set into returnList
foreach (var item in infoList)
{
var returnItem = new Model.AmazonFba.ShipmentItemInfo();
returnItem.AmazonShipmentId = item.ShipmentId;
returnItem.SKUNumber = item.SellerSKU;
returnItem.AmazonFNSKU = item.FulfillmentNetworkSKU;
if (item.IsSetQuantityShipped()) { returnItem.QuantityAllocated = (int)item.QuantityShipped; }
else { returnItem.QuantityAllocated = 0; }
if (item.IsSetQuantityReceived()) { returnItem.QuantityReceived = (int)item.QuantityReceived; }
else { returnItem.QuantityReceived = 0; }
returnList.Add(returnItem);
}
return returnList;
}
}
}

View File

@@ -1,229 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FBAInboundServiceMWS.Model;
namespace bnhtrade.Core.Data.AmazonMWS.FBAInbound
{
public class ListInboundShipments
{
/// <summary>
/// List of Shipment Status' to return. Default is all status' returned.
/// </summary>
public List<string> ShipmentStatusList { get; set; }
/// <summary>
/// List of Shipment Id to return.
/// </summary>
public List<string> ShipmentIdList { get; set; }
public DateTime LastUpdatedAfter { get; set; }
public DateTime LastUpdatedBefore { get; set; }
public bool IsSetShipmentStatusList()
{
return ShipmentStatusList != null;
}
public bool IsSetShipmentIdList()
{
return ShipmentIdList != null;
}
public bool IsSetLastUpdatedAfter()
{
return LastUpdatedAfter != null;
}
public bool IsSetLastUpdatedBefore()
{
return LastUpdatedBefore != null;
}
public List<Core.Model.AmazonFba.ShipmentInfo> GetShipmentInfo()
{
// variables
int mwsPollFrequency = 500; // restore rate of two requests every second
int mwsPollTimeout = 60;
// at least one search variable needs to be set (to make sure EVERYTHING isn't returned)
if (!IsSetShipmentStatusList() && !IsSetShipmentIdList() && !IsSetLastUpdatedAfter() && !IsSetLastUpdatedBefore())
{
throw new Exception("No request variables have been set");
}
// date checks
if (IsSetLastUpdatedAfter() || IsSetLastUpdatedBefore())
{
if (!IsSetLastUpdatedAfter() || !IsSetLastUpdatedBefore())
{
throw new Exception("If LastUpdatedBefore or LastUpdatedAfter is specified then both parameters must be specified");
}
// set date types
DateTime.SpecifyKind(LastUpdatedAfter, DateTimeKind.Utc);
DateTime.SpecifyKind(LastUpdatedBefore, DateTimeKind.Utc);
if (LastUpdatedBefore.ToUniversalTime() < LastUpdatedAfter.ToUniversalTime())
{
throw new Exception("Parameter LastUpdatedBefore must be less than LastUpdatedAfter");
}
}
// down to business, build the mws request
var request = new ListInboundShipmentsRequest();
var cred = new AmazonMWS.CredentialMws();
request.SellerId = cred.MerchantId;
// add shipment status to request
if (!IsSetShipmentStatusList() && !IsSetShipmentIdList())
{
// defaults values
var statusList = new ShipmentStatusList();
statusList.member.Add("WORKING");
statusList.member.Add("SHIPPED");
statusList.member.Add("IN_TRANSIT");
statusList.member.Add("DELIVERED");
statusList.member.Add("CHECKED_IN");
statusList.member.Add("RECEIVING");
statusList.member.Add("CLOSED");
statusList.member.Add("CANCELLED");
statusList.member.Add("DELETED");
statusList.member.Add("ERROR");
request.ShipmentStatusList = statusList;
}
else if (IsSetShipmentStatusList())
{
var statusList = new ShipmentStatusList();
foreach (string item in ShipmentStatusList)
{
statusList.member.Add(item);
}
request.ShipmentStatusList = statusList;
}
// add shipment Id list to request
if (IsSetShipmentIdList())
{
var shipmentIdList = new ShipmentIdList();
foreach (string item in ShipmentIdList)
{
shipmentIdList.member.Add(item);
}
request.ShipmentIdList = shipmentIdList;
}
// add dates to request
if (IsSetLastUpdatedAfter())
{
request.LastUpdatedAfter = LastUpdatedAfter.ToUniversalTime();
request.LastUpdatedBefore = LastUpdatedBefore.ToUniversalTime();
}
// get amazon service, responce and result
var service = new AmazonMWS.Service().FbaInbound;
var result = new ListInboundShipmentsResult();
// poll mws for response
int count = 0;
do
{
var response = service.ListInboundShipments(request);
if (response.IsSetListInboundShipmentsResult())
{
result = response.ListInboundShipmentsResult;
break;
}
else
{
Thread.Sleep(mwsPollFrequency);
count++;
}
} while (count < mwsPollTimeout);
if (count == mwsPollTimeout)
{
throw new Exception("Response from Amazon MWS timeout");
}
// check a result was returned
if (!result.IsSetShipmentData())
{
return null;
}
// add data list
InboundShipmentList resultList = result.ShipmentData;
var infoList = new List<InboundShipmentInfo>();
infoList.AddRange(resultList.member);
// check for next dataset
if (result.IsSetNextToken())
{
string nextToken = result.NextToken;
do
{
var nextRequest = new ListInboundShipmentsByNextTokenRequest();
var nextResult = new ListInboundShipmentsByNextTokenResult();
nextRequest.NextToken = nextToken;
nextRequest.SellerId = request.SellerId;
count = 0;
do
{
var response = service.ListInboundShipmentsByNextToken(nextRequest);
if (response.IsSetListInboundShipmentsByNextTokenResult())
{
nextResult = response.ListInboundShipmentsByNextTokenResult;
break;
}
else
{
Thread.Sleep(mwsPollFrequency);
count++;
}
} while (count < mwsPollTimeout);
if (count == mwsPollTimeout)
{
throw new Exception("Response from Amazon MWS timeout");
}
// add data to list
InboundShipmentList nextResultList = nextResult.ShipmentData;
infoList.AddRange(nextResultList.member);
if (nextResult.IsSetNextToken())
{
nextToken = nextResult.NextToken;
}
else
{
nextToken = "";
}
} while (nextToken.Length > 0); // next token is true
}
// build return value
var returnItem = new List<Core.Model.AmazonFba.ShipmentInfo>();
//var lastUpdated = infoList.
foreach( InboundShipmentInfo item in infoList)
{
var listItem = new Core.Model.AmazonFba.ShipmentInfo();
listItem.FbaShipmentId = item.ShipmentId;
listItem.DestinationFulfillmentCenterId = item.DestinationFulfillmentCenterId;
listItem.ShipmentName = item.ShipmentName;
listItem.ShipmentStatus = item.ShipmentStatus;
returnItem.Add(listItem);
}
return returnItem;
}
}
}

View File

@@ -1,135 +0,0 @@
using MarketplaceWebService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.AmazonMWS.Feeds
{
public class GetFeedSubmissions
{
private Logic.Log.LogEvent logEvent = new Logic.Log.LogEvent();
public List<string> FeedSubmissionIdList { get; set; } = new List<string>();
public int MaxCount { get; set; } = 100;
public List<MarketplaceWebService.Model.FeedSubmissionInfo> Invoke()
{
//build the request
var cred = new AmazonMWS.CredentialMws();
var request = new MarketplaceWebService.Model.GetFeedSubmissionListRequest();
request.MaxCount = MaxCount;
request.Merchant = cred.MerchantId;
if (FeedSubmissionIdList.Any())
{
var idList = new MarketplaceWebService.Model.IdList();
idList.Id = FeedSubmissionIdList;
request.FeedSubmissionIdList = idList;
}
string error = "GetFeedSubmissionList failed: ";
string errorLong = null;
int i = 0;
int loopMax = 100;
try
{
var service = new Data.AmazonMWS.Service().MarketPlaceWeb;
// set the return list
var feedInfoList = new List<MarketplaceWebService.Model.FeedSubmissionInfo>();
string nextToken = null;
while (i < loopMax)
{
i++;
try
{
if (nextToken == null)
{
var responseList = service.GetFeedSubmissionList(request);
if (responseList.IsSetGetFeedSubmissionListResult())
{
var getFeedListResult = responseList.GetFeedSubmissionListResult;
feedInfoList = getFeedListResult.FeedSubmissionInfo;
if (getFeedListResult.HasNext)
{
nextToken = getFeedListResult.NextToken;
}
else
{
return feedInfoList;
}
}
else
{
errorLong = responseList.ToXML();
throw new Exception("FeedSubmissionListResult was not set");
}
if (nextToken == null)
break;
}
else
{
var requestToken = new MarketplaceWebService.Model.GetFeedSubmissionListByNextTokenRequest();
requestToken.NextToken = nextToken;
requestToken.Merchant = cred.MerchantId;
var responseList = service.GetFeedSubmissionListByNextToken(requestToken);
if (responseList.IsSetGetFeedSubmissionListByNextTokenResult())
{
var getFeedListResult = responseList.GetFeedSubmissionListByNextTokenResult;
feedInfoList.AddRange(getFeedListResult.FeedSubmissionInfo);
if (getFeedListResult.HasNext)
{
nextToken = getFeedListResult.NextToken;
}
else
{
return feedInfoList;
}
}
else
{
errorLong = responseList.ToXML();
throw new Exception("FeedSubmissionListResult was not set");
}
}
}
catch (MarketplaceWebServiceException ex) when (ex.ErrorCode == "RequestThrottled")
{
if (nextToken == null) { MiscFunction.MwsThrottleWait(60); } // 10 intial requests, 1 restore every 45 seconds
else { MiscFunction.MwsThrottleWait(5); } // 30 intial requests, 1 restore every 2 seconds
}
catch (MarketplaceWebServiceException ex)
{
errorLong = "Caught Exception: " + ex.Message +
"\r\nResponse Status Code: " + ex.StatusCode +
"\r\nError Code: " + ex.ErrorCode +
"\r\nError Type: " + ex.ErrorType +
"\r\nRequest ID: " + ex.RequestId +
"\r\nResponseHeaderMetadata: " + ex.ResponseHeaderMetadata +
"\r\nXML:\r\n" + ex.XML;
throw new Exception("MarketplaceWebServiceException");
}
}
}
catch (Exception ex)
{
error = error + ex.Message;
}
// should never get here
if (i == loopMax)
error += "Timeout";
logEvent.LogError(error, errorLong);
throw new Exception(error);
}
}
}

View File

@@ -1,120 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MarketplaceWebService;
using bnhtrade.Core.Logic;
namespace bnhtrade.Core.Data.AmazonMWS.Feeds
{
public class SubmitFeed
{
private Logic.Log.LogEvent logEvent = new Logic.Log.LogEvent();
public bool FeedSubmissionRecived { get; set; } = false;
public SubmitFeed(Model.Export.AmazonFeedSubmission feedSubmission)
{
FeedSubmissionRecived = false;
var cred = new CredentialMws();
var config = new MarketplaceWebService.MarketplaceWebServiceConfig();
config.ServiceURL = cred.ServiceURL;
var marketPlaceList = new MarketplaceWebService.Model.IdList();
marketPlaceList.Id = new List<string> { cred.MarketPlaceIdUK };
var request = new MarketplaceWebService.Model.SubmitFeedRequest();
request.MarketplaceIdList = marketPlaceList;
request.Merchant = cred.MerchantId;
request.FeedContent = feedSubmission.File.FileData;
request.FeedType = feedSubmission.FeedType;
request.ContentMD5 = feedSubmission.File.FileMD5base64;
request.FeedContent.Position = 0;
var service = new Data.AmazonMWS.Service().MarketPlaceWeb;
bool repeat = true;
var response = new MarketplaceWebService.Model.SubmitFeedResponse();
// try for a response
while (repeat)
{
try
{
response = service.SubmitFeed(request);
repeat = false;
}
catch (MarketplaceWebServiceException ex) when (ex.ErrorCode == "RequestThrottled")
{
MiscFunction.MwsThrottleWait(150); // 15 inital requests, restore 1 every 2 minutes
}
catch (MarketplaceWebService.MarketplaceWebServiceException ex)
{
string errorLong = "Caught Exception: " + ex.Message + Environment.NewLine
+ "Response Status Code: " + ex.StatusCode + Environment.NewLine
+ "Error Code: " + ex.ErrorCode + Environment.NewLine
+ "Error Type: " + ex.ErrorType + Environment.NewLine
+ "Request ID: " + ex.RequestId + Environment.NewLine
+ "XML: " + Environment.NewLine + ex.XML + Environment.NewLine
+ "ResponseHeaderMetadata: " + ex.ResponseHeaderMetadata + Environment.NewLine;
logEvent.LogError("Unhandled MarketplaceWebServiceException while running InvokeSubmitFeed", errorLong);
throw new Exception("Unhandled MarketplaceWebServiceException while running InvokeSubmitFeed");
}
}
// test the response
if (response.IsSetSubmitFeedResult())
{
MarketplaceWebService.Model.SubmitFeedResult submitFeedResult = response.SubmitFeedResult;
if (submitFeedResult.IsSetFeedSubmissionInfo())
{
MarketplaceWebService.Model.FeedSubmissionInfo feedSubmissionInfo = submitFeedResult.FeedSubmissionInfo;
if (feedSubmissionInfo.IsSetFeedSubmissionId())
{
feedSubmission.FeedSubmissionId = feedSubmissionInfo.FeedSubmissionId;
FeedSubmissionRecived = true;
}
else
{
logEvent.LogError("Response from MWS SubmitFeed did not contain a 'FeedSubmissionId'", submitFeedResult.ToString());
return;
}
if (feedSubmissionInfo.IsSetFeedProcessingStatus())
{
feedSubmission.FeedProcessingStatus = feedSubmissionInfo.FeedProcessingStatus;
}
if (feedSubmissionInfo.IsSetCompletedProcessingDate())
{
feedSubmission.CompletedProcessingDate = DateTime.SpecifyKind(feedSubmissionInfo.CompletedProcessingDate, DateTimeKind.Utc);
}
if (feedSubmissionInfo.IsSetStartedProcessingDate())
{
feedSubmission.StartedProcessingDate = DateTime.SpecifyKind(feedSubmissionInfo.StartedProcessingDate, DateTimeKind.Utc);
}
if (feedSubmissionInfo.IsSetSubmittedDate())
{
if (feedSubmissionInfo.SubmittedDate != null)
{
feedSubmission.SubmittedDate = DateTime.SpecifyKind(DateTime.Parse(feedSubmissionInfo.SubmittedDate), DateTimeKind.Utc);
}
}
}
else
{
logEvent.LogError("Response from MWS SubmitFeed did not contain a 'FeedSubmissionInfo'", response.ToXML());
throw new Exception("Request FeedSubmissionInfo not set."); // no idea what to do here, what happened, has it been submitted?
}
}
else
{
logEvent.LogError("Response from MWS SubmitFeed did not contain a 'SubmitFeedResult'", response.ToXML());
throw new Exception("Request SubmitFeedResult not set."); // no idea what to do here, what happened, has it been submitted?
}
}
}
}

View File

@@ -1,73 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using bnhtrade.Core.Data.AmazonMWS.FBAInbound;
using FBAInboundServiceMWS;
//using bnhtrade.Core.Data.AmazonMWS;
using MarketplaceWebService;
namespace bnhtrade.Core.Data.AmazonMWS
{
public class Service : CredentialMws
{
private string merchantId;
private string marketplaceId; // Amazon.co.uk
private string accessKeyId;
private string secretAccessKey;
private string applicationName;
private string applicationVersion;
private string serviceURL;
// class constructor
public Service()
{
var cred = new AmazonMWS.CredentialMws();
this.merchantId = cred.MerchantId;
this.marketplaceId = cred.MarketPlaceIdUK;
this.accessKeyId = cred.AccessKeyId;
this.secretAccessKey = cred.SecretAccessKey;
this.applicationName = cred.ApplicationName;
this.applicationVersion = cred.ApplicationVersion;
this.serviceURL = cred.ServiceURL;
}
public MarketplaceWebService.MarketplaceWebService MarketPlaceWeb
{
get
{
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = serviceURL;
MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
config);
return service;
}
}
public global::FBAInboundServiceMWS.FBAInboundServiceMWS FbaInbound
{
get
{
FBAInboundServiceMWSConfig config = new FBAInboundServiceMWSConfig();
config.ServiceURL = serviceURL;
global::FBAInboundServiceMWS.FBAInboundServiceMWS service = new FBAInboundServiceMWSClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
config);
return service;
}
}
}
}

View File

@@ -9,13 +9,13 @@ namespace bnhtrade.Core.Data.Database.Account
{
public class CreateInvoiceLineItem : Connection
{
public CreateInvoiceLineItem(string sqlConnectionString) : base(sqlConnectionString)
public CreateInvoiceLineItem()
{
}
public int CreateDefault(string itemCode)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -12,7 +12,7 @@ namespace bnhtrade.Core.Data.Database.Account
private Data.Database.SqlWhereBuilder sqlWhere = new SqlWhereBuilder();
private List<Model.Account.AccountCode> resultList;
public ReadAccountCode(string sqlConnectionString) : base(sqlConnectionString)
public ReadAccountCode()
{
}
@@ -49,7 +49,7 @@ namespace bnhtrade.Core.Data.Database.Account
INNER JOIN tblAccountChartOfType ON tblAccountChartOf.AccountChartOfTypeID = tblAccountChartOfType.AccountChartOfTypeID
" + sqlWhere;
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Account
{
public class ReadInvoiceLineItem : Connection
{
public ReadInvoiceLineItem(string sqlConnectionString) : base(sqlConnectionString)
public ReadInvoiceLineItem()
{
Innit();
}
@@ -66,7 +66,7 @@ namespace bnhtrade.Core.Data.Database.Account
whereBuilder.In("tblAccountInvoiceLineItem.ItemCode", itemCodeList);
sql += whereBuilder.SqlWhereString;
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -11,7 +11,7 @@ namespace bnhtrade.Core.Data.Database.Account
{
private Data.Database.SqlWhereBuilder whereBuilder;
public ReadTaxCode(string sqlConnectionString) : base(sqlConnectionString)
public ReadTaxCode()
{
whereBuilder = new SqlWhereBuilder();
}
@@ -36,7 +36,7 @@ namespace bnhtrade.Core.Data.Database.Account
sqlString += sqlWhere;
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -129,7 +129,7 @@ namespace bnhtrade.Core.Data.Database.Account
sql += whereBuilder.SqlWhereString;
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -179,7 +179,7 @@ namespace bnhtrade.Core.Data.Database.Account
sql += whereBuilder.SqlWhereString;
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Amazon
{
public class FeeEstimate : Connection
{
/// <summary>
/// Update the tblAmazonFeeEstimate table (a new record will be created if it does not already exist to update)
/// </summary>
/// <param name="feeEstimate">Record to be updated/inserted into database</param>
public void UpdateProductFeeEstimate(Model.Amazon.ProductFeeEstimate feeEstimate)
{
using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
{
sqlConn.Open();
using (SqlCommand sqlCommand = new SqlCommand(@"
UPDATE tblAmazonFeeEstimate SET
ProductIdentifier=@productIdentifier, IsAmazonFulfilled=@isAmazonFulfilled, TimeOfFeeEstimation=@timeOfFeeEstimation,
TotalFeeEstimate=@totalFeeEstimate, PriceToEstimateFeeListingPrice=@priceToEstimateFeeListingPrice,
PriceToEstimateFeeShipping=@priceToEstimateFeeShipping, PriceToEstimateFeePoints=@priceToEstimateFeePoints,
ReferralFee=@referralFee, VariableClosingFee=@variableClosingFee, PerItemFee=@perItemFee, FBAFee=@fbaFee,
OtherFee_Exception=@otherFee_Exception, currencyCode=CurrencyCode
WHERE AmazonASIN=@asin
IF @@ROWCOUNT = 0
INSERT INTO tblAmazonFeeEstimate ( AmazonASIN,
ProductIdentifier, IsAmazonFulfilled, TimeOfFeeEstimation, TotalFeeEstimate, PriceToEstimateFeeListingPrice,
PriceToEstimateFeeShipping, PriceToEstimateFeePoints, ReferralFee, VariableClosingFee, PerItemFee, FBAFee,
OtherFee_Exception, CurrencyCode
) VALUES ( @asin,
@productIdentifier, @isAmazonFulfilled, @timeOfFeeEstimation, @totalFeeEstimate, @priceToEstimateFeeListingPrice,
@priceToEstimateFeeShipping, @priceToEstimateFeePoints, @referralFee, @variableClosingFee, @perItemFee, @fbaFee,
@otherFee_Exception, @currencyCode
)
", sqlConn))
{
sqlCommand.Parameters.AddWithValue("@asin", feeEstimate.Asin);
sqlCommand.Parameters.AddWithValue("@productIdentifier", feeEstimate.ProductId);
sqlCommand.Parameters.AddWithValue("@isAmazonFulfilled", feeEstimate.IsAmazonFulfilled);
sqlCommand.Parameters.AddWithValue("@timeOfFeeEstimation", feeEstimate.TimeOfFeeEstimation);
sqlCommand.Parameters.AddWithValue("@totalFeeEstimate", feeEstimate.TotalFeeEstimate);
sqlCommand.Parameters.AddWithValue("@priceToEstimateFeeListingPrice", feeEstimate.PriceToEstimateFeeListingPrice);
sqlCommand.Parameters.AddWithValue("@priceToEstimateFeeShipping", feeEstimate.PriceToEstimateFeeShipping);
sqlCommand.Parameters.AddWithValue("@priceToEstimateFeePoints", feeEstimate.PriceToEstimateFeePoints);
sqlCommand.Parameters.AddWithValue("@referralFee", feeEstimate.ReferralFee);
sqlCommand.Parameters.AddWithValue("@variableClosingFee", feeEstimate.VariableClosingFee);
sqlCommand.Parameters.AddWithValue("@perItemFee", feeEstimate.PerItemFee);
sqlCommand.Parameters.AddWithValue("@fbaFee", feeEstimate.FulfillmentFees);
sqlCommand.Parameters.AddWithValue("@otherFee_Exception", feeEstimate.OtherFee_Exception);
sqlCommand.Parameters.AddWithValue("@currencyCode", feeEstimate.CurrencyCode);
sqlCommand.ExecuteNonQuery();
}
}
}
}
}

View File

@@ -12,7 +12,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
{
private List<string> shipmentIdList;
public ReadShipmentInfo(string sqlConnectionString) : base(sqlConnectionString)
public ReadShipmentInfo()
{
}
@@ -126,7 +126,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
AND IsClosed = 0";
}
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -13,7 +13,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
private Dictionary<string, int> shipmentPKByAmazonShipmentIdDic;
private Dictionary<int, string> amazonShipmentIdByShipmentPKDic;
public ReadShipmentPrimaryKey(string sqlConnectionString) : base(sqlConnectionString)
public ReadShipmentPrimaryKey()
{
}
@@ -79,7 +79,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
}
int shipmentPK = -1;
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -13,7 +13,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
private ReadShipmentPrimaryKey getPK;
private Data.Database.Sku.GetSkuId skuIdLoopkup;
public SetShipmentInfo(string sqlConnectionString) : base(sqlConnectionString)
public SetShipmentInfo()
{
}
@@ -23,7 +23,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
{
if (getPK == null)
{
getPK = new ReadShipmentPrimaryKey(sqlConnectionString);
getPK = new ReadShipmentPrimaryKey();
}
return getPK;
}
@@ -39,7 +39,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
{
if (skuIdLoopkup == null)
{
skuIdLoopkup = new Sku.GetSkuId(sqlConnectionString);
skuIdLoopkup = new Sku.GetSkuId(SqlConnectionString);
}
return skuIdLoopkup;
}
@@ -49,7 +49,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
{
using (var scope = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -126,7 +126,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
private void DeleteShipmentItems(int shipmentId)
{
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -151,7 +151,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
throw new Exception("Unsuficent properties set in Shipment Header Info.");
}
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -218,7 +218,7 @@ namespace bnhtrade.Core.Data.Database.AmazonShipment
}
// make the update
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -4,21 +4,45 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
namespace bnhtrade.Core.Data.Database
{
public class Connection
{
protected readonly string sqlConnectionString;
//protected readonly string SqlConnectionString;
private Model.Credentials.bnhtradeDB dbCredentials;
public Connection(string sqlConnectionString)
protected string SqlConnectionString
{
get { return dbCredentials.ConnectionString; }
}
public Connection()
{
// attempt to retrive credentials from app.local.config
try
{
var dbCredentials = new bnhtrade.Core.Model.Credentials.bnhtradeDB(
ConfigurationManager.AppSettings["DbDataSource"]
, ConfigurationManager.AppSettings["DbUserId"]
, ConfigurationManager.AppSettings["DbUserPassword"]
);
this.dbCredentials = dbCredentials;
}
catch(Exception ex)
{
throw new Exception("Unable to retirve DB credentials: " + ex.Message);
}
}
public Connection(Model.Credentials.bnhtradeDB dbCredentials)
{
// setup sql parameters
if (string.IsNullOrWhiteSpace(sqlConnectionString))
{
throw new Exception("Zero length sql connection string passed");
if (dbCredentials == null)
{
throw new Exception("DB credentials object is null");
}
this.sqlConnectionString = sqlConnectionString;
}
}
}

View File

@@ -9,7 +9,7 @@ namespace bnhtrade.Core.Data.Database.Consistency
{
public class ImportAmazonSettlement : Connection
{
public ImportAmazonSettlement(string sqlConnectionString) : base(sqlConnectionString)
public ImportAmazonSettlement()
{
}
@@ -29,7 +29,7 @@ namespace bnhtrade.Core.Data.Database.Consistency
{
ErrorMessage = null;
using (var sqlConn = new SqlConnection(sqlConnectionString))
using (var sqlConn = new SqlConnection(SqlConnectionString))
{
var log = new Logic.Log.LogEvent();
sqlConn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Export
{
public class CreateAmazonFeedSubmission : Connection
{
public CreateAmazonFeedSubmission (string sqlConnectionString) : base(sqlConnectionString)
public CreateAmazonFeedSubmission ()
{
}
@@ -20,7 +20,7 @@ namespace bnhtrade.Core.Data.Database.Export
// write to db
int id = 0;
var result = new Model.Export.AmazonFeedSubmission();
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Export
{
public class CreateSalesInvoice : Connection
{
public CreateSalesInvoice(string sqlConnectionString) : base(sqlConnectionString)
public CreateSalesInvoice()
{
}
@@ -19,7 +19,7 @@ namespace bnhtrade.Core.Data.Database.Export
{
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
{
sqlConn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Export
{
public class ReadAmazonFeedSubmission : Connection
{
public ReadAmazonFeedSubmission(string sqlConnectionString) : base(sqlConnectionString)
public ReadAmazonFeedSubmission()
{
}
@@ -65,7 +65,7 @@ namespace bnhtrade.Core.Data.Database.Export
sql += sqlWhereClause;
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -9,14 +9,14 @@ namespace bnhtrade.Core.Data.Database.Export
{
public class UpdateAmazonFeedSubmission : Connection
{
public UpdateAmazonFeedSubmission(string sqlConnectionString) : base(sqlConnectionString)
public UpdateAmazonFeedSubmission()
{
}
public void AddAmazonFeedId(int exportAmazonFeedSubmissionID, string amazonFeedId)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -59,7 +59,7 @@ namespace bnhtrade.Core.Data.Database.Export
if (feedSubmissionList == null || !feedSubmissionList.Any())
return;
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -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;
}
}
}
}

View File

@@ -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;
}
}
}
}

View File

@@ -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());
}
}
}
}

View File

@@ -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();

View 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());
}
}
}
}

View File

@@ -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;
}
}
}
}

View 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;
}
}
}
}

View 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;
}
}
}
}

View 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);
}
}
}
}

View File

@@ -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;
}
}
}

View 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();
}
}
}
}
}

View File

@@ -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();

View File

@@ -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();

View File

@@ -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);
}
}
}
}

View File

@@ -9,7 +9,7 @@ namespace bnhtrade.Core.Data.Database.Log
{
public class DateTimeLog : Connection
{
public DateTimeLog(string sqlConnectionString) : base(sqlConnectionString)
public DateTimeLog()
{
}
@@ -20,7 +20,7 @@ namespace bnhtrade.Core.Data.Database.Log
/// <returns>UTC DateTime or null</returns>
public DateTime GetDateTimeUtc(string logDateTimeId)
{
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -54,7 +54,7 @@ namespace bnhtrade.Core.Data.Database.Log
{
utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -88,7 +88,7 @@ namespace bnhtrade.Core.Data.Database.Log
utcDateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -8,17 +8,21 @@ using System.Transactions;
namespace bnhtrade.Core.Data.Database.Log
{
public class LogEvent
public class LogEvent : Connection
{
public LogEvent()
{
}
protected void DatabaseLogInsert
(string detailShort, int eventType, string detailLong, DateTime eventDateTime, bool consolePrint = true)
{
var console = new UI.Console.Update();
if (consolePrint)
{
if (string.IsNullOrWhiteSpace(detailLong))
{ console.WriteLine(detailShort); }
else { console.WriteLine(detailShort + Environment.NewLine + detailLong); }
{ UI.Console.WriteLine(detailShort); }
else { UI.Console.WriteLine(detailShort + Environment.NewLine + detailLong); }
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// need to remove this section once code has been rewritten, writing to console will be handled
@@ -66,7 +70,7 @@ namespace bnhtrade.Core.Data.Database.Log
}
catch (Exception ex)
{
console.WriteLine("WTF!!!! Error with error logging, jobs foooked!");
UI.Console.WriteLine("WTF!!!! Error with error logging, jobs foooked!");
throw ex;
}
scope.Complete();

View File

@@ -9,7 +9,7 @@ namespace bnhtrade.Core.Data.Database.Product
{
public class CreateCompetitivePrice : Connection
{
public CreateCompetitivePrice(string sqlConnectionString) : base(sqlConnectionString)
public CreateCompetitivePrice()
{
}
@@ -31,7 +31,7 @@ namespace bnhtrade.Core.Data.Database.Product
throw new Exception("Unspecified DateTimeKind");
}
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
{
sqlConn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Product
{
public class ReadCompetitivePrice : Connection
{
public ReadCompetitivePrice(string sqlConnectionString) : base(sqlConnectionString)
public ReadCompetitivePrice()
{
}
@@ -91,7 +91,7 @@ namespace bnhtrade.Core.Data.Database.Product
AND (t.SkuConditionID = a.SkuConditionID)";
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
{
sqlConn.Open();

View File

@@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Product
{
public class ReadProduct : Connection
{
private List<string> filterByAsin;
private List<int> filterByProductId;
public ReadProduct()
{
Innit();
}
public List<string> FilterByAsin
{
get { return filterByAsin; }
set
{
if (value == null) { filterByAsin = new List<string>(); }
else { filterByAsin = value; }
}
}
public List<int> FilterByProductId
{
get { return filterByProductId; }
set
{
if (value == null) { filterByProductId = new List<int>(); }
else { filterByProductId = value; }
}
}
public void Innit()
{
FilterByProductId = new List<int>();
FilterByAsin = new List<string>();
}
public List<Model.Product.ProductInfo> ExecuteQuery()
{
var returnList = new List<Model.Product.ProductInfo>();
// build SQL string
string sqlString = @"
SELECT [prdProductID]
,[prdTitle]
,[TitleSuffix]
,[ProductCategoryID]
,[ProductCategorySubID]
,[ReleaseDate]
,[RecommendedRetailPrice]
,[prdMaxPrice]
,[prdAmazonASIN]
,[Manufacturer]
,[PackageWeightKilogram]
,[PackageDimensionHeightMeter]
,[PackageDimensionWidthMeter]
,[PackageDimensionLengthMeter]
,[CatId]
,[ProductProcurementControlID]
,[ManualCompetativePriceUpdate]
,[prdAmazonBuyBoxActive]
,[prdAmazonBuyBoxActiveUpdated]
,[prdActive]
,[prdRecordCreated]
,[prdRecordModified]
,[Draft]
FROM [e2A].[dbo].[tblProduct]
WHERE 1=1 ";
var sqlBuilder = new Database.SqlWhereBuilder();
if (FilterByProductId.Any())
{
sqlBuilder.In("prdProductID", FilterByProductId, "AND");
sqlString = sqlString + sqlBuilder.SqlWhereString;
}
if (FilterByAsin.Any())
{
sqlBuilder.In("prdAmazonASIN", FilterByAsin, "AND");
sqlString = sqlString + sqlBuilder.SqlWhereString;
}
// execute query and build result list
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
sqlBuilder.AddParametersToSqlCommand(cmd);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
return returnList;
}
while (reader.Read())
{
// none nullable values
string title = reader.GetString(1);
int productCategoryId = reader.GetInt32(3);
int productProcurementControlId = reader.GetInt32(15);
// create model
var item = new Model.Product.ProductInfo(title, productCategoryId, productProcurementControlId);
item.ProductID = reader.GetInt32(0);
// add nullable items to model
if (!reader.IsDBNull(2))
item.TitleSuffix = reader.GetString(2);
if (!reader.IsDBNull(3))
item.ProductCategorySubID = reader.GetInt32(4);
if (!reader.IsDBNull(5))
item.ReleaseDate = DateTime.SpecifyKind(reader.GetDateTime(5), DateTimeKind.Utc);
if (!reader.IsDBNull(6))
item.RecommendedRetailPrice = reader.GetDecimal(6);
if (!reader.IsDBNull(7))
item.MaxPrice = reader.GetDecimal(7);
if (!reader.IsDBNull(8))
item.AmazonASIN = reader.GetString(8);
if (!reader.IsDBNull(9))
item.Manufacturer = reader.GetString(9);
if (!reader.IsDBNull(10))
item.PackageWeightKilogram = reader.GetDecimal(10);
if (!reader.IsDBNull(11) && !reader.IsDBNull(12) && !reader.IsDBNull(13))
item.SetPackageDimension(reader.GetDecimal(11), reader.GetDecimal(12), reader.GetDecimal(13));
if (!reader.IsDBNull(14))
item.CatId = reader.GetInt32(14);
if (!reader.IsDBNull(16))
item.ManualCompetativePriceUpdate = reader.GetBoolean(16);
if (!reader.IsDBNull(17))
item.AmazonBuyBoxActive = reader.GetBoolean(17);
if (!reader.IsDBNull(18))
item.AmazonBuyBoxActiveUpdated = DateTime.SpecifyKind(reader.GetDateTime(18), DateTimeKind.Utc);
if (!reader.IsDBNull(19))
item.IsActive = reader.GetBoolean(19);
if (!reader.IsDBNull(20))
item.RecordCreated = DateTime.SpecifyKind(reader.GetDateTime(20), DateTimeKind.Utc);
if (!reader.IsDBNull(21))
item.RecordModified = DateTime.SpecifyKind(reader.GetDateTime(21), DateTimeKind.Utc);
if (!reader.IsDBNull(22))
item.IsDraft = reader.GetBoolean(22);
returnList.Add(item);
}
}
}
}
return returnList;
}
/// <summary>
/// Get product id by sku number
/// </summary>
/// <param name="skuNumberList">List of SKU numbers to query</param>
/// <returns>Dictionary with SKU number as key and product id as value</returns>
public Dictionary<string, int> ProductIdBySkuNumber(List<string> skuNumberList)
{
var returnList = new Dictionary<string, int>();
if (skuNumberList == null || !skuNumberList.Any())
{
return returnList;
}
skuNumberList = skuNumberList.Distinct().ToList();
string sql = @"
SELECT tblProduct.prdProductID
,tblSku.skuSkuNumber
FROM tblProduct
INNER JOIN tblSku ON tblProduct.prdProductID = tblSku.skuProductID
WHERE
";
var sqlWhereBuilder = new Database.SqlWhereBuilder();
sqlWhereBuilder.Innit();
sqlWhereBuilder.In("tblSku.skuSkuNumber", skuNumberList);
sql += sqlWhereBuilder.SqlWhereString;
using (SqlConnection conn = new SqlConnection())
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
sqlWhereBuilder.AddParametersToSqlCommand(cmd);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
returnList.Add(reader.GetString(1), reader.GetInt32(0));
}
}
}
}
return returnList;
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Product
{
class ReadProductId : Connection
{
public Dictionary<string, int> ProductIdByAsin(List<string> asinList)
{
var productIdList = new Dictionary<string, int>();
if (asinList == null || !asinList.Any())
return productIdList;
// build SQL string
string sql =
@"SELECT prdProductID, prdAmazonASIN
FROM [e2A].[dbo].[tblProduct]
WHERE ";
var sqlBuilder = new Database.SqlWhereBuilder();
sqlBuilder.In("prdAmazonASIN", asinList);
sql = sql + sqlBuilder.SqlWhereString;
// execute query and build result list
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
sqlBuilder.AddParametersToSqlCommand(cmd);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
productIdList.Add(reader.GetString(1), reader.GetInt32(0));
}
}
}
}
return productIdList;
}
}
}

View File

@@ -9,7 +9,7 @@ namespace bnhtrade.Core.Data.Database.Programmability
{
public class Sequence : Connection
{
public Sequence (string sqlConnectionString) : base(sqlConnectionString)
public Sequence ()
{
}
@@ -20,7 +20,7 @@ namespace bnhtrade.Core.Data.Database.Programmability
throw new Exception("Sequence name is null or whitespace.");
}
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database
{
public class ReadRandomData : Connection
{
public List<string> GetSkuNumber(int listCount)
{
var returnList = new List<string>();
if (listCount < 1)
return returnList;
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"SELECT TOP "+ listCount + " [skuSkuNumber] FROM [e2A].[dbo].[tblSku] ORDER BY newid()", conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
returnList.Add(reader.GetString(0));
}
}
}
}
return returnList;
}
public List<string> GetAsinNumber(int listCount)
{
var returnList = new List<string>();
if (listCount < 1)
return returnList;
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(
"SELECT TOP " + listCount + " prdAmazonASIN FROM [e2A].[dbo].[tblProduct] WHERE prdAmazonASIN IS NOT NULL ORDER BY newid()", conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
returnList.Add(reader.GetString(0));
}
}
}
}
return returnList;
}
}
}

View File

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

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
{
public class CreatePricingDetail : Connection
{
public CreatePricingDetail(string sqlConnectionString) : base(sqlConnectionString)
public CreatePricingDetail()
{
}
@@ -20,7 +20,7 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
{ return; }
using (var scope = new TransactionScope())
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -10,12 +10,12 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
{
public class ReadParameter : Connection
{
public ReadParameter(string sqlConnectionString) : base(sqlConnectionString)
public ReadParameter() : base()
{
}
public List<Model.Sku.Price.SkuPriceParameter> Execute()
public List<Model.Sku.Price.SkuRepriceInfo> Execute()
{
string stringSql = @"
SELECT
@@ -71,17 +71,17 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
) b
INNER JOIN tblSku ON b.SkuID = tblSku.skuSkuID)
INNER JOIN tblProduct ON tblSku.skuProductID = tblProduct.prdProductID)
LEFT JOIN tblAmazonFeeEstimate ON tblProduct.prdProductID = tblAmazonFeeEstimate.ProductIdentifier )
LEFT JOIN tblAmazonFeeEstimate ON tblProduct.prdProductID = tblAmazonFeeEstimate.ProductID )
INNER JOIN tblProductCategory ON tblProduct.ProductCategoryID = tblProductCategory.ProductCategoryID)
INNER JOIN tblAccountTaxCode ON tblSku.AccountTaxCodeID = tblAccountTaxCode.AccountTaxCodeID
INNER JOIN tblSkuCondition ON tblSku.skuSkuConditionID = tblSkuCondition.scnSkuConditionID
";
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection())
{
conn.Open();
var invPricing = conn.Query<Model.Sku.Price.SkuPriceParameter>(stringSql).ToList();
var invPricing = conn.Query<Model.Sku.Price.SkuRepriceInfo>(stringSql).ToList();
if (invPricing != null || invPricing.Any())
{
@@ -95,4 +95,3 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
}
}
}

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
{
public class ReadPricingDetail : Connection
{
public ReadPricingDetail(string sqlConnectionString) : base(sqlConnectionString)
public ReadPricingDetail()
{
}
@@ -28,7 +28,7 @@ namespace bnhtrade.Core.Data.Database.Sku.Price
public List<Model.Sku.Price.PriceInfo> Read(List<string> skuNumberList, string orderChannel)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Sku
{
public class ReadSku : Connection
{
private SqlWhereBuilder sqlWhere = new SqlWhereBuilder();
public ReadSku()
{
}
public List<Model.Sku.Sku> BySkuNumber(List<string> skuNumberList)
{
var returnList = new List<Model.Sku.Sku>();
if (!skuNumberList.Any())
{
return returnList;
}
// build the sql string
string sqlString = @"
SELECT
skuSkuNumber
,skuAmazonFNSKU
,skuActive
FROM tblSku
WHERE ";
sqlWhere.Innit();
sqlWhere.In("skuSkuNumber", skuNumberList);
sqlString += sqlWhere.SqlWhereString;
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
sqlWhere.AddParametersToSqlCommand(cmd);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var sku = new Model.Sku.Sku();
sku.SkuNumber = reader.GetString(0);
if (!reader.IsDBNull(1)) { sku.AmazonFNSKU = reader.GetString(1); }
sku.IsActive = reader.GetBoolean(2);
returnList.Add(sku);
}
}
}
}
return returnList;
}
}
}

View File

@@ -8,17 +8,19 @@ using Dapper;
namespace bnhtrade.Core.Data.Database.Sku
{
public class ReadSkuConditionInfo : Connection
{
public ReadSkuConditionInfo(string sqlConnectionString): base(sqlConnectionString)
{
public class ReadSkuConditionInfo : Connection
{
private Data.Database.SqlWhereBuilder sqlWhere = new SqlWhereBuilder();
}
public ReadSkuConditionInfo()
{
public List<Model.Sku.SkuConditionInfo> Read(List<int> conditionIdList)
{
string sql = @"
SELECT scnSkuConditionID AS SkuConditionId
}
public List<Model.Sku.SkuConditionInfo> ByConditionCode(List<string> conditionCodeList)
{
string sql = @"
SELECT SkuConditionCode
,scnTitleShort AS TitleShort
,scnSkuNumberSuffix AS SkuConditionNumber
,BaseType AS AmazonBaseType
@@ -30,22 +32,64 @@ namespace bnhtrade.Core.Data.Database.Sku
,scnDescription AS Description
FROM tblSkuCondition";
if (conditionIdList != null || !conditionIdList.Any())
if (conditionCodeList != null || !conditionCodeList.Any())
{
sql += @"
WHERE scnSkuConditionID IN @conditionIdList
WHERE SkuConditionCode IN @conditionIdList
";
}
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
var paramter = new DynamicParameters();
paramter.Add("@conditionIdList", conditionIdList);
paramter.Add("@conditionIdList", conditionCodeList);
return conn.Query<Model.Sku.SkuConditionInfo>(sql, paramter).ToList();
}
}
}
}
}
/// <summary>
/// Retrives list of condition codes for a given list of sku numbers.
/// </summary>
/// <param name="skuNumberList">SKU number list</param>
/// <returns>Dictionary with sku number as key and condition code as value</returns>
public Dictionary<string, string> ReadSkuConditionCode(List<string> skuNumberList)
{
var returnList = new Dictionary<string, string>();
if (skuNumberList == null || !skuNumberList.Any())
{
return returnList;
}
sqlWhere.In("tblSku.skuSkuNumber", skuNumberList);
string sql = @"
SELECT tblSku.skuSkuNumber, tblSkuCondition.SkuConditionCode
FROM tblSku INNER JOIN tblSkuCondition ON tblSku.skuSkuConditionID = tblSkuCondition.scnSkuConditionID
WHERE " + sqlWhere.SqlWhereString;
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
using (var cmd = new SqlCommand(sql, conn))
{
sqlWhere.AddParametersToSqlCommand(cmd);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
returnList.Add(reader.GetString(0), reader.GetString(1));
}
}
}
}
return returnList;
}
}
}

View File

@@ -9,13 +9,13 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class CreateSkuTransaction : Connection
{
public CreateSkuTransaction(string sqlConnectionString) : base(sqlConnectionString)
public CreateSkuTransaction()
{
}
public void Create(Model.Stock.SkuTransaction skuTransaction)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -9,13 +9,13 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class DeleteSkuTransaction : Connection
{
public DeleteSkuTransaction (string sqlConnectionString): base(sqlConnectionString)
public DeleteSkuTransaction ()
{
}
public void ByTransactionId(int skuReconcileId)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -13,7 +13,7 @@ namespace bnhtrade.Core.Data.Database.Stock
private Data.Database.SqlWhereBuilder whereBuilder = new SqlWhereBuilder();
private List<int> transactionIdList = new List<int>();
public ReadSkuTransaction(string sqlConnectionString) : base(sqlConnectionString)
public ReadSkuTransaction()
{
}
@@ -52,7 +52,7 @@ namespace bnhtrade.Core.Data.Database.Stock
/// <returns>Stock Journal ID</returns>
public int? GetJournalId(int skuTransactionId)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -151,7 +151,7 @@ namespace bnhtrade.Core.Data.Database.Stock
sql += @"
ORDER BY tblStockSkuTransaction.TransactionDate ASC, tblStockSkuTransaction.StockSkuTransactionID DESC;";
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class ReadSkuTransactionType : Connection
{
public ReadSkuTransactionType(string sqlConnectionString) : base(sqlConnectionString)
public ReadSkuTransactionType()
{
}
@@ -34,7 +34,7 @@ namespace bnhtrade.Core.Data.Database.Stock
{
throw new Exception("Empty match string passed to method");
}
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionString))
using (SqlConnection sqlConn = new SqlConnection(SqlConnectionString))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand(@"
@@ -115,7 +115,7 @@ namespace bnhtrade.Core.Data.Database.Stock
sql += sqlWhere;
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -9,14 +9,14 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class ReadStatusBalance : Connection
{
public ReadStatusBalance(string sqlConnectionString) : base(sqlConnectionString)
public ReadStatusBalance()
{
}
public int BySku(string sku, int statusId)
{
int statusBalance = new int();
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -51,7 +51,7 @@ namespace bnhtrade.Core.Data.Database.Stock
public int ByStockNumber(int stockNumber, int statusId)
{
int statusBalance = new int();
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -85,7 +85,7 @@ namespace bnhtrade.Core.Data.Database.Stock
public int ByStockId(int stockId, int statusId)
{
int statusBalance = new int();
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -10,7 +10,7 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class ReadStatusTransaction : Connection
{
public ReadStatusTransaction(string sqlConnectionString) : base(sqlConnectionString)
public ReadStatusTransaction()
{
}
@@ -43,7 +43,7 @@ namespace bnhtrade.Core.Data.Database.Stock
,tblStock.StockNumber
";
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -98,7 +98,7 @@ namespace bnhtrade.Core.Data.Database.Stock
WHERE a.Balance <> 0
";
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -168,7 +168,7 @@ namespace bnhtrade.Core.Data.Database.Stock
ORDER BY tblStockJournal.EntryDate
";
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Data.Database.Stock
{
public class ReadStatusTypeBalance : Connection
{
private Data.Database.SqlWhereBuilder sqlWhereBuilder = new SqlWhereBuilder();
public ReadStatusTypeBalance()
{
}
public Dictionary<string, int> ReadSku(List<int> statusTypeIdList)
{
var returnList = new Dictionary<string, int>();
if (statusTypeIdList == null || !statusTypeIdList.Any())
{
return returnList;
}
statusTypeIdList = statusTypeIdList.Distinct().ToList();
string sql = @"
SELECT tblSku.skuSkuNumber AS SkuNumber
,SUM(tblStockJournalPost.Quantity) AS SumOfQuantity
FROM tblStockJournalPost
INNER JOIN tblStockStatus ON tblStockJournalPost.StockStatusID = tblStockStatus.StockStatusID
INNER JOIN tblStockJournal ON tblStockJournalPost.StockJournalID = tblStockJournal.StockJournalID
INNER JOIN tblStock ON tblStockJournal.StockID = tblStock.StockID
INNER JOIN tblSku ON tblStock.SkuID = tblSku.skuSkuID
WHERE
";
sqlWhereBuilder.In("tblStockStatus.StockStatusTypeID", statusTypeIdList);
sql += sqlWhereBuilder.SqlWhereString;
sql += @"
GROUP BY tblSku.skuSkuNumber
HAVING (SUM(tblStockJournalPost.Quantity) > 0)
";
using (var conn = new SqlConnection())
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
sqlWhereBuilder.AddParametersToSqlCommand(cmd);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
returnList.Add(reader.GetString(0), reader.GetInt32(1));
}
}
}
}
return returnList;
}
}
}

View File

@@ -11,7 +11,7 @@ namespace bnhtrade.Core.Data.Database.Stock
{
public class ReadStockId : Connection
{
public ReadStockId(string sqlConnectionString) : base(sqlConnectionString)
public ReadStockId()
{
}
@@ -33,7 +33,7 @@ namespace bnhtrade.Core.Data.Database.Stock
var whereBuilder = new Database.SqlWhereBuilder();
whereBuilder.In("StockNumber", stockNumberList, strSQL);
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
using (SqlConnection conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -11,13 +11,13 @@ namespace bnhtrade.Core.Data.Database.Stock
{
private string err = "Database UpdateSkuTransaction: ";
public UpdateSkuTransaction(string sqlConnectionString) : base(sqlConnectionString)
public UpdateSkuTransaction()
{
}
public void Update(int skuTransactionId, bool isProcessed)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -53,7 +53,7 @@ namespace bnhtrade.Core.Data.Database.Stock
,StockJournalID = @stockJournalID
WHERE StockSkuTransactionID = @transactionId;";
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -83,7 +83,7 @@ namespace bnhtrade.Core.Data.Database.Stock
,Quantity = @quantity
WHERE StockSkuTransactionID = @transactionId;";
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -125,7 +125,7 @@ namespace bnhtrade.Core.Data.Database.Stock
sql += @"
WHERE StockSkuTransactionID = @transactionId;";
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();
@@ -148,7 +148,7 @@ namespace bnhtrade.Core.Data.Database.Stock
public void Update(Model.Stock.SkuTransaction skuTransaction)
{
using (var conn = new SqlConnection(sqlConnectionString))
using (var conn = new SqlConnection(SqlConnectionString))
{
conn.Open();

View File

@@ -8,76 +8,53 @@ namespace bnhtrade.Core.Logic.Account
{
public class GetAccountCodeInfo
{
private string sqlConnectionString;
private Data.Database.Account.ReadAccountCode readAccountCode;
private Dictionary<int, Model.Account.AccountCode> cache;
public GetAccountCodeInfo(string sqlConnectionString)
public GetAccountCodeInfo()
{
this.sqlConnectionString = sqlConnectionString;
readAccountCode = new Data.Database.Account.ReadAccountCode(sqlConnectionString);
cache = new Dictionary<int, Model.Account.AccountCode>();
readAccountCode = new Data.Database.Account.ReadAccountCode();
}
public void CacheClear()
public List<Model.Account.AccountCode> GetAll()
{
cache.Clear();
return readAccountCode.All();
}
public void CacheFill()
public Model.Account.AccountCode ByAccountCode(int accountCode)
{
CacheClear();
var resultList = readAccountCode.All();
foreach (var result in resultList)
var list = ByAccountCode(new List<int> { accountCode });
if (list.Any())
{
cache.Add(result.AccountCodeId, result);
}
}
public void CacheFill(List<int> accountCodeList, bool forceDbRead = false)
{
if (accountCodeList == null || !accountCodeList.Any())
{
return;
}
var accountCodeQueryList = new List<int>();
foreach (var code in accountCodeList.Distinct().ToList())
{
if (forceDbRead)
{
cache.Remove(code);
accountCodeQueryList.Add(code);
}
else if (!cache.ContainsKey(code))
{
accountCodeQueryList.Add(code);
}
}
// get db list
var dbList = readAccountCode.ByAccountCode(accountCodeQueryList);
// add to cache
foreach (var item in dbList)
{
cache.Add(item.AccountCodeId, item);
}
}
public Model.Account.AccountCode ByAccountCode(int accountCode, bool forceDbRead = false)
{
CacheFill(new List<int> { accountCode }, forceDbRead);
if (cache.ContainsKey(accountCode))
{
return cache[accountCode];
return list[0];
}
else
{
return null;
}
}
public List<Model.Account.AccountCode> ByAccountCode(List<int> accountCodeList)
{
return readAccountCode.ByAccountCode(accountCodeList);
}
public Dictionary<int, Model.Account.AccountCode> ConvertToDictionary(List<Model.Account.AccountCode> accountCodeList)
{
var returnDict = new Dictionary<int, Model.Account.AccountCode>();
if (accountCodeList == null)
{
return returnDict;
}
foreach (var accountCode in accountCodeList)
{
if (!returnDict.ContainsKey(accountCode.AccountCodeId))
{
returnDict.Add(accountCode.AccountCodeId, accountCode);
}
}
return returnDict;
}
}
}
}

View File

@@ -8,20 +8,18 @@ namespace bnhtrade.Core.Logic.Account
{
public class GetInvoiceLineItem
{
string sqlConnectionString;
private Dictionary<string, Model.Account.InvoiceLineItem> cache;
private Data.Database.Account.ReadInvoiceLineItem dbRead;
private Logic.Log.LogEvent log = new Logic.Log.LogEvent();
private Logic.Account.GetTaxCodeInfo getTaxCode;
private Logic.Account.GetAccountCodeInfo getAccountCode;
public GetInvoiceLineItem(string sqlConnectionString)
public GetInvoiceLineItem()
{
this.sqlConnectionString = sqlConnectionString;
CacheInnit();
dbRead = new Data.Database.Account.ReadInvoiceLineItem(sqlConnectionString);
getAccountCode = new GetAccountCodeInfo(sqlConnectionString);
getTaxCode = new GetTaxCodeInfo(sqlConnectionString);
dbRead = new Data.Database.Account.ReadInvoiceLineItem();
getAccountCode = new GetAccountCodeInfo();
getTaxCode = new GetTaxCodeInfo();
}
/// <summary>
@@ -63,21 +61,21 @@ namespace bnhtrade.Core.Logic.Account
// query database
var resultList = dbRead.ByItemCode(itemCodeQueryList);
// fill account & tax codes cache
getAccountCode.CacheFill(dbRead.AccountCodeList.Values.ToList(), forceDbRead);
getTaxCode.CacheFill(dbRead.TaxCodeList.Values.ToList(), forceDbRead);
// get account & tax codes dictionaries
var accountCodeDict = getAccountCode.ConvertToDictionary(getAccountCode.ByAccountCode(dbRead.AccountCodeList.Values.ToList()));
var taxCodeDict = getTaxCode.ConvertToDictionary(getTaxCode.GetByTaxCode(dbRead.TaxCodeList.Values.ToList()));
// build final itemcode object and add to cache
foreach (var result in resultList.Values)
{
if (dbRead.AccountCodeList.ContainsKey(result.ItemCode))
{
result.DefaultAccountCode = getAccountCode.ByAccountCode(dbRead.AccountCodeList[result.ItemCode]);
result.DefaultAccountCode = accountCodeDict[dbRead.AccountCodeList[result.ItemCode]];
}
if (dbRead.TaxCodeList.ContainsKey(result.ItemCode))
{
result.DefaultTaxCode = getTaxCode.GetByTaxCode(dbRead.TaxCodeList[result.ItemCode]);
result.DefaultTaxCode = taxCodeDict[dbRead.TaxCodeList[result.ItemCode]];
}
cache.Add(result.ItemCode, result);
@@ -91,7 +89,7 @@ namespace bnhtrade.Core.Logic.Account
/// <returns></returns>
public Model.Account.InvoiceLineItem CreateDefault(string itemCode)
{
new Data.Database.Account.CreateInvoiceLineItem(sqlConnectionString).CreateDefault(itemCode);
new Data.Database.Account.CreateInvoiceLineItem().CreateDefault(itemCode);
var item = dbRead.ByItemCode(itemCode);
cache.Add(item.ItemCode, item);
return item;

View File

@@ -8,86 +8,29 @@ namespace bnhtrade.Core.Logic.Account
{
public class GetTaxCodeInfo
{
string sqlConnectionString;
private bool allRetrived;
private Dictionary<string, Model.Account.TaxCodeInfo> cache;
private Dictionary<string, Model.Account.TaxCodeInfo> cacheInvoiceItem;
private Data.Database.Account.ReadTaxCode dbRead;
public GetTaxCodeInfo(string sqlConnectionString)
public GetTaxCodeInfo()
{
this.sqlConnectionString = sqlConnectionString;
allRetrived = false;
CacheClear();
dbRead = new Data.Database.Account.ReadTaxCode(sqlConnectionString);
}
private void CacheClear()
{
cache = new Dictionary<string, Model.Account.TaxCodeInfo>();
cacheInvoiceItem = new Dictionary<string, Model.Account.TaxCodeInfo>();
}
public void CacheFill()
{
CacheClear();
var list = dbRead.GetAllActive();
foreach (var item in list)
{
cache.Add(item.TaxCode, item);
}
}
public void CacheFill(List<string> taxCodeList, bool forceDbRead = false)
{
if (taxCodeList == null || !taxCodeList.Any())
{
return;
}
var taxCodeQueryList = new List<string>();
foreach (var code in taxCodeList.Distinct().ToList())
{
if (forceDbRead)
{
cache.Remove(code);
taxCodeQueryList.Add(code);
}
else if (!cache.ContainsKey(code))
{
taxCodeQueryList.Add(code);
}
}
// get db list
var dbList = dbRead.GetByTaxCode(taxCodeQueryList);
// add to cache
foreach (var item in dbList)
{
cache.Add(item.TaxCode, item);
}
dbRead = new Data.Database.Account.ReadTaxCode();
}
public List<Model.Account.TaxCodeInfo> GetAllActive()
{
CacheFill();
return cache.Values.ToList();
return dbRead.GetAllActive();
}
public Model.Account.TaxCodeInfo GetByTaxCode(string taxCode, bool forceDbRead = false)
public List<Model.Account.TaxCodeInfo> GetByTaxCode(List<string> taxCodeList)
{
if (string.IsNullOrWhiteSpace(taxCode))
{
return null;
}
return dbRead.GetByTaxCode(taxCodeList);
}
CacheFill(new List<string> { taxCode }, forceDbRead);
if (cache.ContainsKey(taxCode))
public Model.Account.TaxCodeInfo GetByTaxCode(string taxCode)
{
var temp = GetByTaxCode(new List<string> { taxCode });
if (temp.Any())
{
return cache[taxCode];
return temp[0];
}
else
{
@@ -109,17 +52,9 @@ namespace bnhtrade.Core.Logic.Account
return returnList;
}
// remove any duplicates
var cleanSkuList = skuNumberList.Distinct().ToList();
// get db list
var dbList = dbRead.GetTaxCodeBySkuNumber(skuNumberList);
if (!dbList.Any()) { return returnList; }
// charge the cache
dbRead.GetAllActive();
// build dictionary
foreach (var item in dbList)
{
@@ -133,9 +68,50 @@ namespace bnhtrade.Core.Logic.Account
return returnList;
}
public Dictionary<string, Model.Account.TaxCodeInfo> Get(List<Model.Account.InvoiceLineItem> invoiceLineList)
public bool AddToSkuInfo(List<Model.Sku.Sku> skuList)
{
throw new NotImplementedException();
bool missionSuccess = true;
if (skuList == null || !skuList.Any())
{
return true;
}
// get list of sku numbers to condition codes
var lookupDictionary = GetBySkuNumber(skuList.Select(x => x.SkuNumber).ToList());
for (int i = 0; i < skuList.Count; i++)
{
if (lookupDictionary.ContainsKey(skuList[i].SkuNumber))
{
skuList[i].TaxCodeInfo = lookupDictionary[skuList[i].SkuNumber];
}
else
{
missionSuccess = false;
}
}
return missionSuccess;
}
public Dictionary<string, Model.Account.TaxCodeInfo> ConvertToDictionary(List<Model.Account.TaxCodeInfo> taxCodeList)
{
var returnDict = new Dictionary<string, Model.Account.TaxCodeInfo>();
if (taxCodeList == null)
{
return returnDict;
}
foreach (var taxCode in taxCodeList)
{
if (!returnDict.ContainsKey(taxCode.TaxCode))
{
returnDict.Add(taxCode.TaxCode, taxCode);
}
}
return returnDict;
}
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Amazon.Fba
{
public class Fnsku
{
/// <summary>
/// Gets any Amazon FNSKU numbers that are missing from database
/// </summary>
public void GetFnskus()
{
}
}
}

View File

@@ -10,33 +10,21 @@ namespace bnhtrade.Core.Logic.AmazonFBAInbound
{
public class ShipmentInfoPersistanceUpdate
{
private string sqlConnectionString;
private readonly string logDateTimeId = "FbaInboundShipmentNewCheck";
public int TotalUpdated { get; private set; } = 0;
public ShipmentInfoPersistanceUpdate(string sqlConnectionString)
{
this.sqlConnectionString = sqlConnectionString;
}
public void GetNew()
{
TotalUpdated = 0;
// get time frame to check
DateTime dateTimeBefore = new Data.AmazonMWS.CurrentDateTime().GetUtc();
DateTime dateTimeAfter = new Data.Database.Log.DateTimeLog(sqlConnectionString).GetDateTimeUtc(logDateTimeId);
DateTime dateTimeBefore = new Data.Amazon.SellingPartnerAPI.Utils.CurrentDateTime().GetUtc();
DateTime dateTimeAfter = new Data.Database.Log.DateTimeLog().GetDateTimeUtc(logDateTimeId);
//var objGetUtc = new Data.AmazonMWS.CurrentDateTime();
//DateTime dateTimeBefore = objGetUtc.GetUtc();
var amazonApi = new Data.Amazon.FulFillmentInbound.GetShipments();
//var objDateTimeCheck = new Data.Database.Log.DateTimeLog(sqlConnectionString);
//DateTime dateTimeAfter = objDateTimeCheck.GetDateTimeUtc(logDateTimeId);
//
var shipmentRequest = new Data.AmazonMWS.FBAInbound.ListInboundShipments();
shipmentRequest.LastUpdatedAfter = dateTimeAfter.AddDays(-14);
shipmentRequest.LastUpdatedBefore = dateTimeBefore;
List<Model.AmazonFba.ShipmentInfo> shipmentInfoList = shipmentRequest.GetShipmentInfo();
var shipmentInfoList = amazonApi.GetByDateRange(dateTimeAfter.AddDays(-14), dateTimeBefore);
// build list of shipments returned from mws
var dicShipExistsInDb = new Dictionary<string, bool>();
@@ -55,7 +43,7 @@ namespace bnhtrade.Core.Logic.AmazonFBAInbound
var newShipmentId = new List<string>();
// query db for shipment header info
var resultHeader = new Data.Database.AmazonShipment.ReadShipmentInfo(sqlConnectionString)
var resultHeader = new Data.Database.AmazonShipment.ReadShipmentInfo()
.HeaderByFbaShipmentId(dicShipExistsInDb.Keys.ToList());
// compare db and mws result
@@ -71,16 +59,15 @@ namespace bnhtrade.Core.Logic.AmazonFBAInbound
}
}
// query mws for new shipment info
// query amazon's api for new shipment info
if (newShipmentId.Any())
{
shipmentRequest.ShipmentIdList = newShipmentId;
newShipmentInfoList = shipmentRequest.GetShipmentInfo();
newShipmentInfoList = amazonApi.GetByShipmentIdList(newShipmentId);
foreach (var item in newShipmentInfoList)
{
var shipmentItemInfoRequest = new Data.AmazonMWS.FBAInbound.ListInboundShipmentItems();
item.ShipmentItemInfoList = shipmentItemInfoRequest.GetByAmazonShipmentId(item.FbaShipmentId);
var shipmentItemInfoRequest = new Data.Amazon.FulFillmentInbound.GetShipmentItems();
item.ShipmentItemInfoList = shipmentItemInfoRequest.GetByShipmentId(item.FbaShipmentId);
}
}
@@ -93,7 +80,7 @@ namespace bnhtrade.Core.Logic.AmazonFBAInbound
item.LastUpdated = dateTimeBefore;
// write to db
var dbWrite = new Data.Database.AmazonShipment.SetShipmentInfo(sqlConnectionString);
var dbWrite = new Data.Database.AmazonShipment.SetShipmentInfo();
dbWrite.Excecute(item);
complete = complete + 1;
}
@@ -101,7 +88,7 @@ namespace bnhtrade.Core.Logic.AmazonFBAInbound
}
// update datetime log
new Data.Database.Log.DateTimeLog(sqlConnectionString).SetDateTimeUtc(logDateTimeId, dateTimeBefore);
new Data.Database.Log.DateTimeLog().SetDateTimeUtc(logDateTimeId, dateTimeBefore);
//objDateTimeCheck.SetDateTimeUtc(logDateTimeId, dateTimeBefore);
scope.Complete();

View File

@@ -21,16 +21,15 @@ namespace bnhtrade.Core.Logic.Export
public void ToInvoice()
{
var console = new UI.Console.Update();
log.LogInformation("Starting processing of Amazon settlement data into export invoice table...");
// check settlement reports consistancy
var consistencyCheck = new Data.Database.Consistency.ImportAmazonSettlement(sqlConnectionString).PeriodDateGaps();
var consistencyCheck = new Data.Database.Consistency.ImportAmazonSettlement().PeriodDateGaps();
if (consistencyCheck == false)
{ return; }
// get list of unprocssed settlement reports to export
var settlementData = new Data.Database.Import.ReadAmazonSettlement(sqlConnectionString);
var settlementData = new Data.Database.Import.AmazonSettlementRead();
var settlementList = settlementData.AllUnprocessed();
settlementData = null;
@@ -92,7 +91,7 @@ namespace bnhtrade.Core.Logic.Export
}
}
}
var taxCodeBySkuNumer = new Logic.Account.GetTaxCodeInfo(sqlConnectionString).GetBySkuNumber(skuList);
var taxCodeBySkuNumer = new Logic.Account.GetTaxCodeInfo().GetBySkuNumber(skuList);
// loop through each settlement and build list of invoices to export
Console.Write("\rBuilding invoices to export... ");
@@ -190,10 +189,11 @@ namespace bnhtrade.Core.Logic.Export
// add invoice item code data to lines
// also clean invoices of any disabled lines (remove lines and possibly invoices)
var getLineItemInfo = new Logic.Account.GetInvoiceLineItem(sqlConnectionString);
var getLineItemInfo = new Logic.Account.GetInvoiceLineItem();
getLineItemInfo.InsertNewOnNoMatch = true;
getLineItemInfo.CacheFill(lineItemCodeList);
bool newTypeFound = false;
string newTypeText = null;
for (int i = 0; i < invoiceList.Count(); i++)
{
@@ -209,6 +209,14 @@ namespace bnhtrade.Core.Logic.Export
else if (itemCode.IsNewReviewRequired)
{
newTypeFound = true;
if (string.IsNullOrWhiteSpace(itemCode.ItemCode))
{
newTypeText = itemCode.Name;
}
else
{
newTypeText = itemCode.ItemCode;
}
}
// clean invoices of any disabled lines (remove lines and possibly invoices)
else if (itemCode.InvoiceLineEntryEnabled == false)
@@ -243,7 +251,7 @@ namespace bnhtrade.Core.Logic.Export
{
if (newTypeFound)
{
throw new Exception("New line ItemCode found. Add item code default values and then try again.");
throw new Exception("Parameters required for Invoice line item code '"+ newTypeText + "'. Set in tblAccountInvoiceLineItem.");
}
return;
}
@@ -292,7 +300,7 @@ namespace bnhtrade.Core.Logic.Export
saveInv.SaveSalesInvoice(invoiceList);
// set settlements to isprocessed
new Data.Database.Import.UpdateAmazonSettlement(sqlConnectionString).SetIsProcessedTrue(settlementIdList);
new Data.Database.Import.AmazonSettlementUpdate().SetIsProcessedTrue(settlementIdList);
scope.Complete();
}
@@ -319,7 +327,7 @@ namespace bnhtrade.Core.Logic.Export
// add tax info if required
if ((match01 == "Order" || match01 == "Refund")
&& (match02 == "ItemPrice" || match02 == "Promotion"))
&& (match02 == "ItemPrice" || match02 == "Promotion" || match02 == "ItemWithheldTax"))
{
if (taxCodeBySkuNumer.ContainsKey(skuNumber))
{

View File

@@ -24,29 +24,17 @@ namespace bnhtrade.Core.Logic.Export
public void SubmitInventoryLoader(MemoryStream stream)
{
Model.Export.AmazonFeedSubmission result;
int queueId = QueueInventoryLoader(stream, out result);
SubmitQueuedFeedSubmission(queueId, result);
}
public void SubmitInventoryLoader(MemoryStream stream, out Model.Export.AmazonFeedSubmission result)
{
int queueId = QueueInventoryLoader(stream, out result);
SubmitQueuedFeedSubmission(queueId, result);
int queueId = QueueInventoryLoader(stream);
SubmitQueuedFeedSubmission(queueId);
}
public int QueueInventoryLoader(MemoryStream stream)
{
Model.Export.AmazonFeedSubmission result;
return QueueFeedSubbmission("_POST_FLAT_FILE_INVLOADER_DATA_", "txt", stream, out result);
return QueueFeedSubbmission("_POST_FLAT_FILE_INVLOADER_DATA_", "txt", stream);
}
public int QueueInventoryLoader(MemoryStream stream, out Model.Export.AmazonFeedSubmission result)
{
// write file database
return QueueFeedSubbmission("_POST_FLAT_FILE_INVLOADER_DATA_", "txt", stream, out result);
}
private int QueueFeedSubbmission(string feedType, string fileExtention, MemoryStream stream, out Model.Export.AmazonFeedSubmission result)
// adds the file(stream) to the database and returns the queue Id
private int QueueFeedSubbmission(string feedType, string fileExtention, MemoryStream stream)
{
// construct file object
var fileInfo = new Model.Data.DatabaseFileStream();
@@ -63,7 +51,7 @@ namespace bnhtrade.Core.Logic.Export
int queueId = 0;
using (var scope = new TransactionScope())
{
queueId = new Data.Database.Export.CreateAmazonFeedSubmission(sqlConnectionString).Execute(feedType, fileInfo);
queueId = new Data.Database.Export.CreateAmazonFeedSubmission().Execute(feedType, fileInfo);
// validate the result
var validateResults = new List<ValidationResult>();
@@ -83,11 +71,6 @@ namespace bnhtrade.Core.Logic.Export
scope.Complete();
}
// create feed object
result = new Model.Export.AmazonFeedSubmission();
result.FeedType = feedType;
result.File = fileInfo;
return queueId;
}
@@ -95,7 +78,11 @@ namespace bnhtrade.Core.Logic.Export
private void SubmitQueuedFeedSubmission(int queueId, Model.Export.AmazonFeedSubmission feedSubmission)
{
// upload to mws
var feedSubmitt = new Data.AmazonMWS.Feeds.SubmitFeed(feedSubmission);
//var feedSubmitt = new Data.AmazonMWS.Feeds.SubmitFeed(feedSubmission);
// upload to sp-api
var feedSubmitt = new Data.Amazon.Feeds.SubmittFeed();
feedSubmitt.SubmitFeed(feedSubmission);
if (!feedSubmitt.FeedSubmissionRecived)
{
@@ -104,7 +91,7 @@ namespace bnhtrade.Core.Logic.Export
}
// set the amazon feed Id
var dbUpdate = new Data.Database.Export.UpdateAmazonFeedSubmission(sqlConnectionString);
var dbUpdate = new Data.Database.Export.UpdateAmazonFeedSubmission();
dbUpdate.AddAmazonFeedId(queueId, feedSubmission.FeedSubmissionId);
// update progress info

View File

@@ -1,59 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Export
{
public class AmazonSubmitFileStatus
{
private string sqlConnectionString;
private bnhtrade.Core.Logic.Log.LogEvent log = new Log.LogEvent();
public AmazonSubmitFileStatus(string sqlConnectionString)
{
this.sqlConnectionString = sqlConnectionString;
}
public void UpdateStatusInfo()
{
var openList = new Data.Database.Export.ReadAmazonFeedSubmission(sqlConnectionString).GetOpenFeeds();
if (openList.Count == 0)
return;
var getStatus = new Data.AmazonMWS.Feeds.GetFeedSubmissions();
getStatus.FeedSubmissionIdList = openList.Select(x => x.FeedSubmissionId).ToList();
var currentStatus = getStatus.Invoke();
for (int i = 0; i < openList.Count; i++)
{
bool found = false;
for (int j = 0; j < currentStatus.Count; j++)
{
if (openList[i].FeedSubmissionId == currentStatus[j].FeedSubmissionId)
{
found = true;
openList[i].FeedProcessingStatus = currentStatus[j].FeedProcessingStatus;
if (currentStatus[j].IsSetCompletedProcessingDate())
openList[i].CompletedProcessingDate = currentStatus[j].CompletedProcessingDate;
if (currentStatus[j].IsSetStartedProcessingDate())
openList[i].StartedProcessingDate = currentStatus[j].StartedProcessingDate;
if (currentStatus[j].IsSetSubmittedDate())
openList[i].SubmittedDate = DateTime.Parse(currentStatus[j].SubmittedDate);
}
}
if (found == false)
{
log.LogError("FeedSubmissionId '" + openList[i].FeedSubmissionId + "' exists in database but was not returned by Amazon MWS when queried.");
openList.RemoveAt(i);
i = i - 1;
}
}
// update the database
new Data.Database.Export.UpdateAmazonFeedSubmission(sqlConnectionString).UpdateStatusInfo(openList);
}
}
}

View File

@@ -18,7 +18,7 @@ namespace bnhtrade.Core.Logic.Export
public string GetNextTempInvoiceNumber()
{
var sequence = new Data.Database.Programmability.Sequence(sqlConnectionString);
var sequence = new Data.Database.Programmability.Sequence();
return "_tmp" + sequence.GetNext("ExportTempInvoiceNumber").ToString("00000000");
}
@@ -47,7 +47,7 @@ namespace bnhtrade.Core.Logic.Export
validateInvoice = null;
// save to database
new Data.Database.Export.CreateSalesInvoice(sqlConnectionString).Execute(invoiceList);
new Data.Database.Export.CreateSalesInvoice().Execute(invoiceList);
}
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaCustomerReturn
{
public void SyncDatabaseWithAmazon()
{
/*
* flat file lines/rows maybe unique
* Overlap reports by 3 days.
* To disambiguate duplicate row, I will use combination of date, orderid, fnsku, quantity, LPN#, disposition, and reason.
*/
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaCustomerReturn();
var startDate = db.ReadRecentDate().AddDays(-14);
var getFile = new Data.Amazon.Report.FbaCustomerReturn();
getFile.GetReport(startDate, DateTime.UtcNow);
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
db.UpdateByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaInventory
{
public void SyncDatabaseWithAmazon()
{
var getFile = new Data.Amazon.Report.FbaInventory();
getFile.GetReport();
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
new Data.Database.Import.AmazonFbaInventoryData().InsertByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaInventoryAdjustment
{
public void SyncDatabaseWithAmazon()
{
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaInventoryAdjustment();
var startDate = db.ReadRecentDate().AddDays(-3);
var getFile = new Data.Amazon.Report.FbaInventoryAdustment();
getFile.GetReport(startDate, DateTime.UtcNow);
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
db.InsertByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaInventoryAge
{
public void SyncDatabaseWithAmazon()
{
var getFile = new Data.Amazon.Report.FbaInventoryAge();
getFile.GetReport();
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
new Data.Database.Import.AmazonFbaInventoryAgeData().InsertByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaInventoryReceipt
{
public void SyncDatabaseWithAmazon()
{
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaInventoryReceipt();
var startDate = db.ReadRecentDate().AddSeconds(1);
var getReport = new Data.Amazon.Report.FbaInventoryReceipt();
getReport.GetReport(startDate, DateTime.UtcNow);
if (!getReport.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
db.InsertByFlatFile(getReport.ReportFilePath, startDate);
}
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaReimbursement
{
public void SyncDatabaseWithAmazon()
{
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaReimbursement();
var startDate = db.ReadRecentDate().AddDays(-3);
var getFile = new Data.Amazon.Report.FbaReimbursement();
getFile.GetReport(startDate, DateTime.UtcNow);
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
db.InsertByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaRemovalOrder
{
public void SyncDatabaseWithAmazon()
{
/*
* flat file lines/rows are unique
* FROM MWS GUIDANCE
* https://docs.developer.amazonservices.com/en_UK/fba_guide/FBAGuide_TipsShipmentsReport.html
* Overlap report by 3 days. To disambiguate duplicate shipment reports, use the ShipmentItemId (not the OrderId or the OrderItemId)
*/
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaRemovalOrder();
var startDate = db.ReadRecentDate().AddDays(-30);
var getFile = new Data.Amazon.Report.FbaRemovalOrder();
getFile.GetReport(startDate, DateTime.UtcNow);
if (!getFile.ReportFilePathIsSet)
{
MiscFunction.EventLogInsert(
"Something went wrong retriving report from Amazon SP API. Operation cancelled.",
2
);
return;
}
db.InsertByFlatFile(getFile.ReportFilePath);
}
}
}

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class AmazonFbaSaleShipment
{
private int maxTimePeriodDay = 30;
public void SyncDatabaseWithAmazon()
{
/*
* flat file lines/rows are unique
* FROM MWS GUIDANCE
* https://docs.developer.amazonservices.com/en_UK/fba_guide/FBAGuide_TipsShipmentsReport.html
* Overlap report by 3 days. To disambiguate duplicate shipment reports, use the ShipmentItemId (not the OrderId or the OrderItemId)
*/
// get most recent record from db
var db = new Data.Database.Import.AmazonFbaSaleShipment();
var dataSart = db.ReadRecentDate().AddDays(-3);
var dataEnd = DateTime.UtcNow;
// error check
if (dataSart >= dataEnd)
throw new Exception("Data start time is equal or greater than the end time.");
bool doLoop = true;
var requestStart = dataSart;
var requestEnd = dataSart.AddDays(maxTimePeriodDay);
if (requestEnd > dataEnd)
requestEnd = dataEnd;
do
{
var getFile = new Data.Amazon.Report.FbaSaleShipment();
getFile.GetReport(requestStart, requestEnd);
if (getFile.ReportDoneNoData)
{
// continue
}
else if (getFile.ReportFilePathIsSet)
{
db.InsertByFlatFile(getFile.ReportFilePath);
}
else
{
throw new Exception("no report returned");
}
// increment requests times and test for end
if (requestEnd == dataEnd)
{
doLoop = false;
}
else
{
requestStart = requestEnd;
requestEnd = requestStart.AddDays(maxTimePeriodDay);
if (requestEnd > dataEnd)
requestEnd = dataEnd;
if (requestStart == requestEnd)
doLoop = false;
}
}
while (doLoop);
}
}
}

Some files were not shown because too many files have changed in this diff Show More