Feature repricing min max (#10)

amazon settlement import/export improvements
This commit is contained in:
2020-05-01 09:08:23 +01:00
committed by GitHub
parent 56647c7648
commit 43d61c2ef8
118 changed files with 7930 additions and 3021 deletions

View File

@@ -0,0 +1,386 @@
using CsvHelper;
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;
using System.Transactions;
namespace bnhtrade.Core.Logic.Sku.Price
{
public class FbaPricing
{
private string sqlConnectionString;
private bnhtrade.Core.Logic.Log.LogEvent log = new Log.LogEvent();
string err = "FbaPricing Error: ";
private string marginSchemeTaxCode = "T190";
int repriceHoldOnSalePeriod = 14; // days
private int newConditionId = Data.Database.Constants.GetProductConditionIdNew();
private List<Model.Sku.Price.SkuPriceParameter> skuInfo;
private Dictionary<string, Model.Product.CompetitivePrice> competitivePrices;
DateTime crTimeStamp = DateTime.UtcNow;
private int repriceIncrementDivisor = 60;
private Dictionary<string, int> saleCountInPeriod = new Dictionary<string, int>();
private Logic.Account.TaxCalculation taxCalc;
private decimal marginSchemeMargin;
public FbaPricing(string sqlConnectionString)
{
this.sqlConnectionString = sqlConnectionString;
taxCalc = new Account.TaxCalculation();
crTimeStamp = DateTime.UtcNow;
marginSchemeMargin = taxCalc.GetMarginMultiplier(crTimeStamp);
}
public void Update(bool overrideDayCheck = false)
{
using (var scope = new TransactionScope())
{
string orderChannel = "Amazon.co.uk"; // may in future enable other order channels
// need to add some cheks up here for last stock reconcilliation
// get current sku base pricing details (stock quantity, competative price, VAT info, etc.)
skuInfo = new Data.Database.Sku.Price.ReadParameter(sqlConnectionString).Execute();
if (skuInfo == null || !skuInfo.Any())
{
throw new Exception("Querying the database returned no records.");
}
// create lists that we'll add to during lopp
var loader = new List<Model.Export.AmazonIventoryLoaderFile>();
var crDictionary = new Dictionary<string, Model.Sku.Price.PriceInfo>();
// open needed classes
var readAge = new Data.Database.Import.ReadFbaInventoryAge(sqlConnectionString);
// get current db pricing
var dbDictionary = new Data.Database.Sku.Price.ReadPricingDetail(sqlConnectionString).ReadDictionary(skuInfo.Select(o => o.SkuNumber).ToList(), orderChannel);
// get required competivie prices
var readComp = new Logic.Product.GetCompetitivePrice(sqlConnectionString);
readComp.EstimatePrice = true;
var compPrices = readComp.Execute(skuInfo);
// loop through skus returnd from stock query
for (int i = 0; i < skuInfo.Count(); i++)
{
string skuNumber = skuInfo[i].SkuNumber;
var cr = new Model.Sku.Price.PriceInfo();
if (!overrideDayCheck && dbDictionary.Count > 0 && !OkayToReprice(dbDictionary[skuNumber].PriceInfoTimeStamp))
{ continue; }
// load in values from skuInfo
cr.PriceTypeId = 1;
cr.ReviewRequired = false;
cr.OrderChannel = orderChannel;
cr.OrderChannelQuantity = skuInfo[i].TotalQuantity;
cr.PriceInfoTimeStamp = crTimeStamp;
cr.SkuNumber = skuInfo[i].SkuNumber;
// get inventory age range
var invAge = readAge.BySkuNumber(skuInfo[i].SkuNumber, orderChannel);
if (invAge == null)
{
// this means lost stock, or unreconciled inventory... need to pause these skus else the price could decrease without it being on sale
err += "No records returned from tblImportFbaInventoryAgeReport for skuID=" + skuInfo[i].SkuId;
log.LogError(err);
throw new Exception(err);
}
cr.InventoryAgeMin = invAge.Value.MinAge;
cr.InventoryAgeMax = invAge.Value.MaxAge;
// get minimum prices
cr.UnitMinPriceCost = GetMinPriceCost(i);
cr.UnitMinPriceProfit = GetMinPriceProfit(i);
cr.UnitPurchaseCost = skuInfo[i].UnitCostAverage;
// set competitive price
if (compPrices.ContainsKey(skuInfo[i].SkuNumber))
{
cr.CompetitivePrice = compPrices[skuInfo[i].SkuNumber].Price;
cr.CompetitivePriceIsEstimated = compPrices[skuInfo[i].SkuNumber].PriceIsEstimated;
}
else
{
cr.CompetitivePrice = cr.UnitMinPriceProfit + (cr.UnitMinPriceProfit / 2);
cr.CompetitivePriceIsEstimated = true;
}
// set min max price
cr.RepriceIncrement = cr.CompetitivePrice / repriceIncrementDivisor;
if (dbDictionary.ContainsKey(skuNumber))
{
// sales wihtin period, therefore hold price
if (GetSaleCountInPeriod(i) > 0)
{
cr.MaxPrice = dbDictionary[skuNumber].MaxPrice;
cr.MinPrice = dbDictionary[skuNumber].MinPrice;
cr.RepriceIncrement = dbDictionary[skuNumber].RepriceIncrement;
}
// else reduce
else
{
if (dbDictionary[skuNumber].MaxPrice < dbDictionary[skuNumber].MinPrice)
{
err += "Max price lower than min price";
log.LogError(err);
throw new Exception(err);
}
// redue both prices together
else if (dbDictionary[skuNumber].MaxPrice == dbDictionary[skuNumber].MinPrice)
{
cr.MaxPrice = dbDictionary[skuNumber].MaxPrice - cr.RepriceIncrement;
cr.MinPrice = cr.MaxPrice;
}
// reduce only max until it hits the min
else
{
cr.MaxPrice = dbDictionary[skuNumber].MaxPrice - cr.RepriceIncrement;
if (cr.MaxPrice < dbDictionary[skuNumber].MinPrice)
{
cr.MinPrice = cr.MaxPrice;
}
else
{
cr.MinPrice = dbDictionary[skuNumber].MinPrice;
}
}
}
}
else
{
// new value
cr.MaxPrice = cr.CompetitivePrice * 1.2m;
cr.MinPrice = cr.CompetitivePrice * 1m;
}
// check on min price
cr.UnitMinPriceDestory = GetMinPriceDestroy(i);
if (cr.MaxPrice < cr.UnitMinPriceDestory) { cr.MaxPrice = cr.UnitMinPriceDestory; }
if (cr.MinPrice < cr.UnitMinPriceDestory) { cr.MinPrice = cr.UnitMinPriceDestory; }
// add values to inventory loader list
var item = new Model.Export.AmazonIventoryLoaderFile();
item.Sku = skuInfo[i].SkuNumber;
item.Price = cr.MaxPrice;
item.MinimumAllowedPrice = cr.MinPrice;
item.MaximumAllowedPrice = cr.MaxPrice;
item.SetFulfillmentCenterId(true);
loader.Add(item);
// save current prices to dictionary
if (crDictionary.ContainsKey(skuNumber))
{
err += "Multiple SkuId found in data";
log.LogError(err);
throw new Exception(err);
}
crDictionary.Add(skuNumber, cr);
}
// finish loop
// validate and save values to database
var validate = new Core.Logic.Validate.SkuPriceInfo();
if (!validate.IsValidDatabaseCreate(crDictionary.Values.ToList()))
{
err += "Database object create validation failed";
log.LogError(err, validate.ValidationResultListToString());
throw new Exception(err);
}
new Data.Database.Sku.Price.CreatePricingDetail(sqlConnectionString).Executue(crDictionary.Values.ToList());
// create and upload inventory loader file to amazon
var exportList = new List<Model.Export.AmazonIventoryLoaderFile>();
foreach (var item in crDictionary.Values)
{
var listItem = new Model.Export.AmazonIventoryLoaderFile();
listItem.Sku = item.SkuNumber;
listItem.MinimumAllowedPrice = item.MinPrice;
listItem.MaximumAllowedPrice = item.MaxPrice;
listItem.Price = item.MaxPrice;
listItem.SetFulfillmentCenterId(true);
exportList.Add(listItem);
}
// validate
var vaildateInvLoader = new Validate.AmazonIventoryLoaderFile();
if (!vaildateInvLoader.IsValidFbaPricing(exportList))
{
err += "Inventory loader object validation failed";
log.LogError(err, vaildateInvLoader.ValidationResultListToString());
throw new Exception(err);
}
// create file stream
var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.CurrentCulture);
config.Delimiter = "\t";
config.Encoding = Encoding.UTF8;
var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8))
using (var csv = new CsvWriter(writer, config))
{
csv.WriteRecords(exportList);
}
// submit file to database and amazon mws
var submit = new Logic.Export.AmazonSubmitFile(sqlConnectionString);
return;
submit.SubmitInventoryLoader(stream);
scope.Complete();
}
}
private bool OkayToReprice(DateTime lastPriceUpdate)
{
if (lastPriceUpdate == default(DateTime))
{
err += "Invalid, datetime is default.";
log.LogError(err);
throw new Exception(err);
}
bool update = false;
lastPriceUpdate = new DateTime(lastPriceUpdate.Year, lastPriceUpdate.Month, lastPriceUpdate.Day);
DateTime today = new DateTime(crTimeStamp.Year, crTimeStamp.Month, crTimeStamp.Day);
// will only update once on tue, wed or thurs each week.
if (today.DayOfWeek == DayOfWeek.Tuesday || today.DayOfWeek == DayOfWeek.Wednesday || today.DayOfWeek == DayOfWeek.Thursday)
{
if (today > lastPriceUpdate.AddDays(3))
{
update = true;
}
}
return update;
}
/// <summary>
/// Get the minimum sale price to break even.
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private decimal GetMinPriceCost(int i)
{
decimal costPrice = skuInfo[i].UnitCostAverage;
decimal agentFeeFixed = skuInfo[i].AgentFeeFixed;
decimal agentFeeMargin = skuInfo[i].AgentFeeMargin;
decimal vatMargin = skuInfo[i].VatMargin;
decimal price = 0;
if (skuInfo[i].TaxCode == marginSchemeTaxCode)
{
price = (costPrice + agentFeeFixed - (costPrice * marginSchemeMargin))
/ (1 - agentFeeMargin - marginSchemeMargin);
}
else
{
price = (costPrice + agentFeeFixed)
/ (1 - agentFeeMargin - vatMargin);
}
price = decimal.Round(price, 2);
return price;
}
/// <summary>
/// Get the minimum sale price to achieve required profit margin.
/// </summary>
/// <param name="i"></param>
/// <returns>Minimum price in decimal</returns>
private decimal GetMinPriceProfit(int i)
{
decimal costPrice = skuInfo[i].UnitCostAverage;
decimal minProfit = skuInfo[i].PriceMinProfit;
decimal profitMargin = skuInfo[i].ProfitMargin;
decimal agentFeeFixed = skuInfo[i].AgentFeeFixed;
decimal agentFeeMargin = skuInfo[i].AgentFeeMargin;
decimal vatMargin = skuInfo[i].VatMargin;
decimal price = 0;
if (skuInfo[i].TaxCode == marginSchemeTaxCode) // taxcodeinfo now has ismarginscheme boolean
{
price = (costPrice + agentFeeFixed - (costPrice * marginSchemeMargin))
/ (1 - profitMargin - agentFeeMargin - marginSchemeMargin);
}
else
{
price = (costPrice + agentFeeFixed)
/ (1 - profitMargin - agentFeeMargin - vatMargin);
}
price = decimal.Round(price, 2);
// if profit margin is less than min required, redo using min value (not percent)
if (price < minProfit)
{
if (skuInfo[i].TaxCode == marginSchemeTaxCode)
{
price = (minProfit + costPrice + agentFeeFixed - (costPrice * marginSchemeMargin))
/ (1 - agentFeeMargin - marginSchemeMargin);
}
else
{
price = (minProfit + costPrice + agentFeeFixed)
/ (1 - agentFeeMargin - vatMargin);
}
}
price = decimal.Round(price, 2);
return price;
}
private decimal GetMinPriceDestroy(int i)
{
decimal agentFeeFixed = skuInfo[i].AgentFeeFixed;
decimal agentFeeMargin = skuInfo[i].AgentFeeMargin;
decimal vatMargin = skuInfo[i].VatMargin;
decimal price = 0;
if (skuInfo[i].TaxCode == marginSchemeTaxCode)
{
price = (agentFeeFixed) / (1 - agentFeeMargin);
}
else
{
price = (agentFeeFixed) / (1 - agentFeeMargin - vatMargin);
}
price = decimal.Round(price, 2);
return price;
}
private int GetSaleCountInPeriod(int i)
{
if (!saleCountInPeriod.Any())
{
saleCountInPeriod = new Data.Database.Import.ReadFbaSaleShipment(sqlConnectionString)
.GetSaleCount(skuInfo.Select(x => x.SkuNumber).ToList(), DateTime.Now.AddDays(repriceHoldOnSalePeriod * -1), DateTime.Now);
}
if (saleCountInPeriod.ContainsKey(skuInfo[i].SkuNumber))
{
return saleCountInPeriod[skuInfo[i].SkuNumber];
}
else
{
return 0;
}
}
}
}

View File

@@ -0,0 +1,787 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Transactions;
namespace bnhtrade.Core.Logic.Sku.Price
{
public class UpdateRepricingValues
{
//public void Update(string sqlConnectionString, bool skipReportUpdate = false)
//{
// // need to add some cheks up here for last amazon reports import dates
// /*
// * Quite complex this one, order of business
// *
// * Stage 1 - Stock Ledger Query reporting FBA stock (loop through this table)
// * Stage 1 - Read current values from SkuPrice tabel into variables
// * Stage 2 - Get/Set current MIN Price type 'crPriceMin_SkuPriceType'
// * Stage 3 - Set MIN Price, based off type
// * Stage 4 - Get/Set current MAX Price type 'crPriceMin_SkuPriceType'
// * Stage 5 - Set MAX Price, based off type
// * Stage 6 - Final check before db update
// * Stage 7 - Update main/history table
// */
// DateTime crTimeStamp = DateTime.UtcNow;
// int orderChannelId = 2; // may in future enable other order channels
// // refers to max price movements
// decimal repriceDecreaseIncrement = 0.03m; // 3% each week
// int repriceDecreasePeriod = 7; // days
// int repriceHoldOnSalePeriod = 14; // days
// decimal repriceIncreaseIncrement = repriceDecreaseIncrement; // increases price if max sale price is within % of max price
// decimal repriceIncreaseOnStockSold = 0.3m; // percent of total qty sold over sale hold period
// // add a check up here to test for any ASINs that do not have an estimated fee
// // maybe add a constistancy check here (double entries in table (sku and order channel combination)
// using (var conn = new SqlConnection(sqlConnectionString))
// {
// // loop through table
// using (var cmd01 = new SqlCommand("needs deleteing", conn))
// {
// using (var reader01 = cmd01.ExecuteReader())
// {
// var skuPricing = new Data.Database.Sku.Price.ReadParameter(sqlConnectionString).Execute();
// if (skuPricing == null)
// {
// throw new Exception("Querying the database returned no records.");
// }
// else
// {
// new Data.Database.Sku.Price.UpdateSkuPriceIsProcessed(sqlConnectionString).Update();
// }
// using (var scope = new TransactionScope())
// using (var scopeConn = new SqlConnection(sqlConnectionString))
// {
// scopeConn.Open();
// foreach (var sku in skuPricing)
// {
// // switches
// bool insertRequired = false; // skuId does not already exist in table
// bool updateRequired = false; // skuId exists and an edit is required
// bool resetMaxBaseAndMultiplier = false; // Quantity is moving from 0 to >0, lookup/update some values is required
// // current (cr) variables
// var cr = new Model.Sku.Price.DetailResponce();
// cr.OrderChannelQuantity = sku.TotalQuantity;
// cr.UnitAvgCost = sku.UnitCostAverage;
// // Stage 1
// // get db values from inventory table
// var db = new Data.Database.Sku.Price.ReadPricingDetail(sqlConnectionString).Read(sku.SkuId, orderChannelId);
// if (db == null)
// {
// insertRequired = true;
// db = new Model.Sku.Price.DetailResponce();
// // if this is null alot of the following code can be skipped, wip
// }
// // STAGE 2
// // SKU current stock details (i.e. quantity, cost per unit, inventory age, etc.)
// // get inventory age range
// var invAge = new Data.Database.Import.ReadFbaInventoryAge(sqlConnectionString).BySkuId(sku.SkuId, db.OrderChannelId);
// if (invAge == null)
// {
// throw new Exception("No records returned from tblImportFbaInventoryAgeReport for skuID=" + sku.SkuId);
// }
// cr.InventoryAgeMin = invAge.Value.MinAge;
// cr.InventoryAgeMax = invAge.Value.MaxAge;
// // STAGE 3
// // Get/Set Min Price SkukPriceTypeID
// // Do not change the 'crPriceMin_SkuPriceType' value after this stage
// //
// //bool setMinToAuto = true;
// cr.PriceMin_SkuPriceType = 0;
// switch (db.PriceMin_SkuPriceType)
// {
// // Out of Stock
// case 0:
// if (cr.OrderChannelQuantity > 0)
// { cr.PriceMin_SkuPriceType = 1; }
// break;
// //Auto
// case 1:
// cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType;
// break;
// // Fixed SKU price
// case 2:
// cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType;
// break;
// // Manual Price, Permanent
// case 100:
// cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType;
// break;
// // Manual Price, Inv Age Range Includes
// case 110:
// if (db.PriceMinStoredInt >= cr.InventoryAgeMin && db.PriceMinStoredInt <= cr.InventoryAgeMax)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Age Range Less Than
// case 111:
// if (cr.InventoryAgeMax < db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Age Range Greater Than
// case 112:
// if (cr.InventoryAgeMin > db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Less than
// case 120:
// if (cr.OrderChannelQuantity < db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Greater than
// case 121:
// if (cr.OrderChannelQuantity > db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Equal to
// case 122:
// if (cr.OrderChannelQuantity == db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Equal to
// case 123:
// if (cr.OrderChannelQuantity != db.PriceMinStoredInt)
// { cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType; }
// else { cr.PriceMin_SkuPriceType = 1; }
// break;
// default:
// // review of some sort required
// if (db.PriceMin_SkuPriceType >= 200 && db.PriceMin_SkuPriceType < 225)
// {
// cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType;
// cr.ReviewRequired = true;
// }
// // error type
// else if (db.PriceMin_SkuPriceType >= 225 && db.PriceMin_SkuPriceType < 256)
// {
// cr.PriceMin_SkuPriceType = db.PriceMin_SkuPriceType;
// }
// // unhandled id type
// else
// {
// cr.PriceMin_SkuPriceType = 255;
// cr.ReviewRequired = true;
// }
// break;
// }
// // Check manual enteries are present, if they are required
// if ((db.RequireAmountManual && db.PriceMinAmountManual == null) || (db.RequireStordedInt && db.PriceMinStoredInt == null))
// {
// cr.PriceMin_SkuPriceType = 253;
// cr.ReviewRequired = true;
// }
// // Stage 4
// // Set MIN Price
// // calculate the min 'auto' sku price & tax
// decimal crProfitMinAmount;
// decimal crPriceMinCalculatedTax;
// if (sku.TaxRateName == "MS" || sku.TaxRateName == "GA")
// {
// cr.PriceMinAmountAuto = (5m * cr.UnitAvgCost + 6m * sku.AgentFeeFixed) / (-6m * sku.ProfitMargin - 6m * sku.AmazonMargin + 5m);
// crPriceMinCalculatedTax = (cr.PriceMinAmountAuto - cr.UnitAvgCost) * (1 / 6);
// crProfitMinAmount = cr.PriceMinAmountAuto * sku.ProfitMargin;
// }
// else
// {
// cr.PriceMinAmountAuto = (cr.UnitAvgCost + sku.AgentFeeFixed) / (1 - (sku.ProfitMargin + sku.AmazonMargin + sku.VatMargin));
// crPriceMinCalculatedTax = cr.PriceMinAmountAuto * sku.VatMargin;
// crProfitMinAmount = cr.PriceMinAmountAuto * sku.ProfitMargin;
// }
// // if profit margin is less than min required, redo
// if (crProfitMinAmount < sku.PriceMinProfit)
// {
// if (sku.TaxRateName == "MS" || sku.TaxRateName == "GA")
// {
// cr.PriceMinAmountAuto = (6m * sku.PriceMinProfit + 5m * cr.UnitAvgCost + 6m * sku.AgentFeeFixed) / (-6m * sku.AmazonMargin + 5m);
// crPriceMinCalculatedTax = (cr.PriceMinAmountAuto - cr.UnitAvgCost) * (1 / 6);
// crProfitMinAmount = cr.PriceMinAmountAuto * sku.ProfitMargin;
// }
// else
// {
// cr.PriceMinAmountAuto = (cr.UnitAvgCost + sku.AgentFeeFixed + sku.PriceMinProfit) / (1 - (sku.AgentFeeMargin + sku.VatMargin));
// crPriceMinCalculatedTax = cr.PriceMinAmountAuto * sku.VatMargin;
// crProfitMinAmount = cr.PriceMinAmountAuto * sku.ProfitMargin;
// }
// }
// // Calculate current final MIN price values
// if (cr.PriceMin_SkuPriceType == 1)
// {
// cr.PriceMinAmountFinal = cr.PriceMinAmountAuto;
// cr.PriceMinAmountFinalFee = (cr.PriceMinAmountFinal * sku.AgentFeeMargin) + sku.AgentFeeFixed;
// cr.PriceMinAmountFinalTax = crPriceMinCalculatedTax;
// }
// else
// {
// cr.PriceMinAmountFinal = (decimal)db.PriceMinAmountManual;
// cr.PriceMinAmountFinalFee = ((decimal)db.PriceMinAmountManual * sku.AgentFeeMargin) + sku.AgentFeeFixed;
// if (sku.TaxRateName == "MS" || sku.TaxRateName == "GA")
// {
// cr.PriceMinAmountFinalTax = ((decimal)db.PriceMinAmountManual - cr.UnitAvgCost) * (1 / 6);
// }
// else
// {
// cr.PriceMinAmountFinalTax = cr.PriceMinAmountAuto * sku.VatMargin;
// }
// }
// // STAGE 5
// // Get/Set MAX Price SkukPriceTypeID
// // Do not change the 'cr.PriceMax_SkuPriceType' value after this stage
// cr.PriceMax_SkuPriceType = 0;
// switch (db.PriceMax_SkuPriceType)
// {
// // Out of Stock
// case 0:
// if (cr.OrderChannelQuantity > 0)
// { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Auto
// case 1:
// cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType;
// break;
// // Fixed SKU price
// case 2:
// cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType;
// break;
// // Manual Price, Permanent
// case 100:
// cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType;
// break;
// // Manual Price, Inv Age Range Includes
// case 110:
// if (db.PriceMaxStoredInt >= cr.InventoryAgeMin && db.PriceMaxStoredInt <= cr.InventoryAgeMax)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Age Range Less Than
// case 111:
// if (cr.InventoryAgeMax < db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Age Range Greater Than
// case 112:
// if (cr.InventoryAgeMin > db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Less than
// case 120:
// if (cr.OrderChannelQuantity < db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Greater than
// case 121:
// if (cr.OrderChannelQuantity > db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Equal to
// case 122:
// if (cr.OrderChannelQuantity == db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// // Manual Price, Inv Quanity is Not Equal to
// case 123:
// if (cr.OrderChannelQuantity == db.PriceMaxStoredInt)
// { cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType; }
// else { cr.PriceMax_SkuPriceType = 1; }
// break;
// default:
// // review of some sort required
// if (db.PriceMax_SkuPriceType >= 200 && db.PriceMax_SkuPriceType < 225)
// {
// cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType;
// cr.ReviewRequired = true;
// }
// // error type
// else if (db.PriceMax_SkuPriceType >= 225 && db.PriceMax_SkuPriceType < 256)
// {
// cr.PriceMax_SkuPriceType = db.PriceMax_SkuPriceType;
// }
// // unhandled id type
// else
// {
// cr.PriceMax_SkuPriceType = 255;
// cr.ReviewRequired = true;
// }
// break;
// }
// // Check manual enteried are present, if they are required
// if ((db.RequireAmountManualMax && db.PriceMaxAmountManual == null) || (db.RequireStordedIntMax && db.PriceMaxStoredInt == null))
// {
// cr.PriceMax_SkuPriceType = 253;
// cr.ReviewRequired = true;
// }
// // STAGE 6
// // Set MAX Price
// // CASE: Reset MAX-Price base & multiplier values (new record or switching back to auto)
// if (insertRequired || (cr.PriceMax_SkuPriceType == 1 && db.PriceMax_SkuPriceType != 1))
// {
// // get competative price and apply multiplier
// bool usedForceNew = false;
// var request = new bnhtrade.Core.Product.ProductQuery();
// var compPrice = request.ProductCompetitivePriceGet(sqlConnectionString, sku.ProductId, sku.ConditionId);
// if (compPrice.price == null || compPrice.priceDate == null)
// {
// if (sku.ConditionId != 10)
// {
// usedForceNew = true;
// compPrice = request.ProductCompetitivePriceGet(sqlConnectionString, sku.ProductId, 10);
// }
// if (compPrice.price == null || compPrice.priceDate == null)
// {
// cr.PriceMax_SkuPriceType = 254;
// cr.ReviewRequired = true;
// }
// }
// cr.PriceMaxAmountAutoBase = compPrice.price ?? 0;
// if (usedForceNew)
// {
// cr.PriceMaxAmountAutoMultiplier = sku.CompetitivePriceMultiplierNew;
// }
// else
// {
// cr.PriceMaxAmountAutoMultiplier = sku.CompetitivePriceMultiplierMatch;
// }
// // transfer manual values, if required
// if (insertRequired == false)
// {
// cr.PriceMaxAmountManual = db.PriceMaxAmountManual;
// cr.PriceMaxStoredInt = db.PriceMaxStoredInt;
// }
// // set final max value
// cr.PriceMaxAmountFinal = cr.PriceMaxAmountAutoBase * cr.PriceMaxAmountAutoMultiplier;
// }
// // already on auto, adjust existing value, if required
// else if (db.PriceMax_SkuPriceType == 1)
// {
// // get last sale date
// int shipmentsInSaleHoldPeriod = 0;
// // works from last unit ship-date, not the preferred order-date
// // TODO: this could be better when other parts of application get more info
// DateTime shipDateFilter = crTimeStamp.AddDays(repriceHoldOnSalePeriod * -1);
// shipDateFilter = new DateTime(shipDateFilter.Year, shipDateFilter.Month, shipDateFilter.Day);
// using (var cmd04 = new SqlCommand(@"
// SELECT COUNT(tblImportFbaSaleShipment.ImportFbaSaleShipmentID) AS RecordCount
// FROM tblImportFbaSaleShipment
// INNER JOIN tblSku ON tblImportFbaSaleShipment.sku = tblSku.skuSkuNumber
// WHERE (tblSku.skuSkuID = @skuID)
// AND (tblImportFbaSaleShipment.[shipment-date] >= @shipDateFilter)
// ", conn))
// {
// cmd04.Parameters.AddWithValue("@skuID", sku.SkuId);
// cmd04.Parameters.AddWithValue("@shipDateFilter", shipDateFilter);
// shipmentsInSaleHoldPeriod = (int)cmd04.ExecuteScalar();
// }
// // get max item sale price during period
// decimal maxSalePrice = 0;
// if (shipmentsInSaleHoldPeriod > 0)
// {
// using (var cmd05 = new SqlCommand(@"
// SELECT Max(ISNULL([tblImportFbaSaleShipment].[item-price], 0) + ISNULL([tblImportFbaSaleShipment].[item-tax], 0)) AS Expr1
// FROM tblImportFbaSaleShipment
// INNER JOIN tblSku ON tblImportFbaSaleShipment.sku = tblSku.skuSkuNumber
// WHERE (
// ((tblSku.skuSkuID) = @skuID)
// AND ((tblImportFbaSaleShipment.[shipment-date]) >= @shipDateFilter)
// )
// ", conn))
// {
// cmd05.Parameters.AddWithValue("@skuID", sku.SkuId);
// cmd05.Parameters.AddWithValue("@shipDateFilter", shipDateFilter);
// maxSalePrice = (decimal)cmd05.ExecuteScalar();
// }
// }
// DateTime updateDate = new DateTime(db.PriceCreated.Year, db.PriceCreated.Month, db.PriceCreated.Day);
// updateDate = updateDate.AddDays(repriceDecreasePeriod);
// // decrease maxx price
// if (crTimeStamp >= updateDate && shipmentsInSaleHoldPeriod == 0)
// {
// cr.PriceMaxAmountAutoBase = db.PriceMaxAmountAutoBase;
// cr.PriceMaxAmountAutoMultiplier = db.PriceMaxAmountAutoMultiplier - repriceDecreaseIncrement;
// cr.PriceMaxAmountManual = db.PriceMaxAmountManual;
// cr.PriceMaxStoredInt = db.PriceMaxStoredInt;
// cr.PriceMaxAmountFinal = cr.PriceMaxAmountAutoBase * cr.PriceMaxAmountAutoMultiplier;
// }
// else
// {
// // increase price
// if (maxSalePrice >= (db.PriceMaxAmountAutoBase * (db.PriceMaxAmountAutoMultiplier - repriceIncreaseIncrement)))
// {
// cr.PriceMaxAmountAutoBase = db.PriceMaxAmountAutoBase;
// cr.PriceMaxAmountAutoMultiplier = db.PriceMaxAmountAutoMultiplier + repriceIncreaseIncrement;
// cr.PriceMaxAmountManual = db.PriceMaxAmountManual;
// cr.PriceMaxStoredInt = db.PriceMaxStoredInt;
// cr.PriceMaxAmountFinal = cr.PriceMaxAmountAutoBase * cr.PriceMaxAmountAutoMultiplier;
// }
// // remain same
// else
// {
// cr.PriceMaxAmountAutoBase = db.PriceMaxAmountAutoBase;
// cr.PriceMaxAmountAutoMultiplier = db.PriceMaxAmountAutoMultiplier;
// cr.PriceMaxAmountManual = db.PriceMaxAmountManual;
// cr.PriceMaxStoredInt = db.PriceMaxStoredInt;
// cr.PriceMaxAmountFinal = cr.PriceMaxAmountAutoBase * cr.PriceMaxAmountAutoMultiplier;
// }
// }
// }
// // STAGE 7
// // Checks before update
// // max < min
// if (cr.PriceMaxAmountFinal < cr.PriceMinAmountFinal)
// {
// // on auto, set max to min value and update base multipier to reflect new value
// if (cr.PriceMax_SkuPriceType == 1)
// {
// cr.PriceMaxAmountFinal = cr.PriceMinAmountFinal;
// cr.PriceMaxAmountAutoMultiplier = cr.PriceMinAmountFinal / cr.PriceMaxAmountAutoBase;
// }
// else if (cr.PriceMax_SkuPriceType > 0 && cr.PriceMax_SkuPriceType < 200)
// {
// cr.PriceMax_SkuPriceType = 252;
// cr.ReviewRequired = true;
// }
// }
// // this should be last check
// // check for zero values (where there should not be any) -- this could be a life saver i.e. selling item for £0.00
// if (cr.PriceMinAmountFinal * cr.PriceMaxAmountFinal == 0)
// {
// cr.PriceMax_SkuPriceType = 251;
// cr.ReviewRequired = true;
// }
// // STAGE 8
// // Update main/history tables, if required
// // round decimals for db comarison
// cr.UnitAvgCost = decimal.Round(cr.UnitAvgCost, 2);
// cr.PriceMinAmountAuto = decimal.Round(cr.PriceMinAmountAuto, 2);
// cr.PriceMinAmountFinalFee = decimal.Round(cr.PriceMinAmountFinalFee, 2);
// cr.PriceMinAmountFinalTax = decimal.Round(cr.PriceMinAmountFinalTax, 2);
// cr.PriceMinAmountFinal = decimal.Round(cr.PriceMinAmountFinal, 2);
// cr.PriceMaxAmountAutoMultiplier = decimal.Round(cr.PriceMaxAmountAutoMultiplier, 8);
// cr.PriceMaxAmountFinal = decimal.Round(cr.PriceMaxAmountFinal, 2);
// if (insertRequired == false &&
// (
// db.OrderChannelQuantity != cr.OrderChannelQuantity ||
// db.UnitAvgCost != cr.UnitAvgCost ||
// db.InventoryAgeMin != cr.InventoryAgeMin ||
// db.InventoryAgeMax != cr.InventoryAgeMax ||
// db.PriceMin_SkuPriceType != cr.PriceMin_SkuPriceType ||
// db.PriceMinAmountAuto != cr.PriceMinAmountAuto ||
// db.PriceMinAmountFinalFee != cr.PriceMinAmountFinalFee ||
// db.PriceMinAmountFinalTax != cr.PriceMinAmountFinalTax ||
// db.PriceMinAmountFinal != cr.PriceMinAmountFinal ||
// db.PriceMax_SkuPriceType != cr.PriceMax_SkuPriceType ||
// db.PriceMaxAmountAutoBase != cr.PriceMaxAmountAutoBase ||
// db.PriceMaxAmountAutoMultiplier != cr.PriceMaxAmountAutoMultiplier ||
// db.PriceMaxAmountFinal != cr.PriceMaxAmountFinal ||
// db.ReviewRequired != cr.ReviewRequired
// )
// )
// {
// updateRequired = true;
// }
// // insert old data to history table
// if (updateRequired)
// {
// using (var cmd06 = new SqlCommand(@"
// INSERT INTO tblSkuPriceHistory (
// SkuID
// ,OrderChannelID
// ,OrderChannelQuantity
// ,UnitAvgCost
// ,InventoryAgeMin
// ,InventoryAgeMax
// ,PriceMin_SkuPriceType
// ,PriceMinAmountAuto
// ,PriceMinAmountManual
// ,PriceMinStoredInt
// ,PriceMinAmountFinalFee
// ,PriceMinAmountFinalTax
// ,PriceMinAmountFinal
// ,PriceMax_SkuPriceType
// ,PriceMaxAmountAutoBase
// ,PriceMaxAmountAutoMultiplier
// ,PriceMaxAmountManual
// ,PriceMaxStoredInt
// ,PriceMaxAmountFinal
// ,RecordModified
// ,ReviewRequired
// )
// VALUES (
// @skuID
// ,@dbOrderChannelID
// ,@dbOrderChannelQuantity
// ,@dbUnitAvgCost
// ,@dbInventoryAgeMin
// ,@dbInventoryAgeMax
// ,@dbPriceMin_SkuPriceType
// ,@dbPriceMinAmountAuto
// ,@dbPriceMinAmountManual
// ,@dbPriceMinStoredInt
// ,@dbPriceMinAmountFinalFee
// ,@dbPriceMinAmountFinalTax
// ,@dbPriceMinAmountFinal
// ,@dbPriceMax_SkuPriceType
// ,@dbPriceMaxAmountAutoBase
// ,@dbPriceMaxAmountAutoMultiplier
// ,@dbPriceMaxAmountManual
// ,@dbPriceMaxStoredInt
// ,@dbPriceMaxAmountFinal
// ,@dbRecordModified
// ,@dbReviewRequired
// )
// ", scopeConn))
// {
// cmd06.Parameters.AddWithValue("@skuID", sku.SkuId);
// cmd06.Parameters.AddWithValue("@dbOrderChannelID", db.OrderChannelId);
// cmd06.Parameters.AddWithValue("@dbOrderChannelQuantity", db.OrderChannelQuantity);
// cmd06.Parameters.AddWithValue("@dbUnitAvgCost", db.UnitAvgCost);
// cmd06.Parameters.AddWithValue("@dbInventoryAgeMin", db.InventoryAgeMin);
// cmd06.Parameters.AddWithValue("@dbInventoryAgeMax", db.InventoryAgeMax);
// cmd06.Parameters.AddWithValue("@dbPriceMin_SkuPriceType", db.PriceMin_SkuPriceType);
// cmd06.Parameters.AddWithValue("@dbPriceMinAmountAuto", db.PriceMinAmountAuto);
// cmd06.Parameters.AddWithValue("@dbPriceMinAmountManual", db.PriceMinAmountManual);
// cmd06.Parameters.AddWithValue("@dbPriceMinStoredInt", db.PriceMinStoredInt);
// cmd06.Parameters.AddWithValue("@dbPriceMinAmountFinalFee", db.PriceMinAmountFinalFee);
// cmd06.Parameters.AddWithValue("@dbPriceMinAmountFinalTax", db.PriceMinAmountFinalTax);
// cmd06.Parameters.AddWithValue("@dbPriceMinAmountFinal", db.PriceMinAmountFinal);
// cmd06.Parameters.AddWithValue("@dbPriceMax_SkuPriceType", db.PriceMax_SkuPriceType);
// cmd06.Parameters.AddWithValue("@dbPriceMaxAmountAutoBase", db.PriceMaxAmountAutoBase);
// cmd06.Parameters.AddWithValue("@dbPriceMaxAmountAutoMultiplier", db.PriceMaxAmountAutoMultiplier);
// cmd06.Parameters.AddWithValue("@dbPriceMaxAmountManual", db.PriceMaxAmountManual);
// cmd06.Parameters.AddWithValue("@dbPriceMaxStoredInt", db.PriceMaxStoredInt);
// cmd06.Parameters.AddWithValue("@dbPriceMaxAmountFinal", db.PriceMaxAmountFinal);
// cmd06.Parameters.AddWithValue("@dbRecordModified", db.PriceCreated);
// cmd06.Parameters.AddWithValue("@dbReviewRequired", db.ReviewRequired);
// int count = cmd06.ExecuteNonQuery();
// }
// }
// // delete existing data in current table
// if (updateRequired)
// {
// using (var cmd07 = new SqlCommand(@"
// DELETE FROM tblSkuPriceHistory
// WHERE SkuID = @skuID AND OrderChannelID = @dbOrderChannelID
// ", scopeConn))
// {
// cmd07.Parameters.AddWithValue("@skuID", sku.SkuId);
// cmd07.Parameters.AddWithValue("@dbOrderChannelID", db.OrderChannelId);
// int count = cmd07.ExecuteNonQuery();
// }
// }
// // insert new data into current table
// if (updateRequired || insertRequired)
// {
// using (var cmd06 = new SqlCommand(@"
// INSERT INTO tblSkuPrice (
// SkuID
// ,OrderChannelID
// ,OrderChannelQuantity
// ,UnitAvgCost
// ,InventoryAgeMin
// ,InventoryAgeMax
// ,PriceMin_SkuPriceType
// ,PriceMinAmountAuto
// ,PriceMinAmountManual
// ,PriceMinStoredInt
// ,PriceMinAmountFinalFee
// ,PriceMinAmountFinalTax
// ,PriceMinAmountFinal
// ,PriceMax_SkuPriceType
// ,PriceMaxAmountAutoBase
// ,PriceMaxAmountAutoMultiplier
// ,PriceMaxAmountManual
// ,PriceMaxStoredInt
// ,PriceMaxAmountFinal
// ,RecordModified
// ,ReviewRequired
// )
// VALUES (
// @skuID
// ,@crOrderChannelID
// ,@crOrderChannelQuantity
// ,@crUnitAvgCost
// ,@crInventoryAgeMin
// ,@crInventoryAgeMax
// ,@crPriceMin_SkuPriceType
// ,@crPriceMinAmountAuto
// ,@crPriceMinAmountManual
// ,@crPriceMinStoredInt
// ,@crPriceMinAmountFinalFee
// ,@crPriceMinAmountFinalTax
// ,@crPriceMinAmountFinal
// ,@crPriceMax_SkuPriceType
// ,@crPriceMaxAmountAutoBase
// ,@crPriceMaxAmountAutoMultiplier
// ,@crPriceMaxAmountManual
// ,@crPriceMaxStoredInt
// ,@crPriceMaxAmountFinal
// ,@crRecordModified
// ,@crReviewRequired
// )
// ", scopeConn))
// {
// cmd06.Parameters.AddWithValue("@skuID", sku.SkuId);
// cmd06.Parameters.AddWithValue("@crOrderChannelID", db.OrderChannelId);
// cmd06.Parameters.AddWithValue("@crOrderChannelQuantity", cr.OrderChannelQuantity);
// cmd06.Parameters.AddWithValue("@crUnitAvgCost", cr.UnitAvgCost);
// cmd06.Parameters.AddWithValue("@crInventoryAgeMin", cr.InventoryAgeMin);
// cmd06.Parameters.AddWithValue("@crInventoryAgeMax", cr.InventoryAgeMax);
// cmd06.Parameters.AddWithValue("@crPriceMin_SkuPriceType", cr.PriceMin_SkuPriceType);
// cmd06.Parameters.AddWithValue("@crPriceMinAmountAuto", cr.PriceMinAmountAuto);
// cmd06.Parameters.AddWithValue("@crPriceMinAmountManual", cr.PriceMinAmountManual);
// cmd06.Parameters.AddWithValue("@crPriceMinStoredInt", cr.PriceMinStoredInt);
// cmd06.Parameters.AddWithValue("@crPriceMinAmountFinalFee", cr.PriceMinAmountFinalFee);
// cmd06.Parameters.AddWithValue("@crPriceMinAmountFinalTax", cr.PriceMinAmountFinalTax);
// cmd06.Parameters.AddWithValue("@crPriceMinAmountFinal", cr.PriceMinAmountFinal);
// cmd06.Parameters.AddWithValue("@crPriceMax_SkuPriceType", cr.PriceMax_SkuPriceType);
// cmd06.Parameters.AddWithValue("@crPriceMaxAmountAutoBase", cr.PriceMaxAmountAutoBase);
// cmd06.Parameters.AddWithValue("@crPriceMaxAmountAutoMultiplier", cr.PriceMaxAmountAutoMultiplier);
// cmd06.Parameters.AddWithValue("@crPriceMaxAmountManual", cr.PriceMaxAmountManual);
// cmd06.Parameters.AddWithValue("@crPriceMaxStoredInt", cr.PriceMaxStoredInt);
// cmd06.Parameters.AddWithValue("@crPriceMaxAmountFinal", cr.PriceMaxAmountFinal);
// cmd06.Parameters.AddWithValue("@crRecordModified", cr.PriceCreated);
// cmd06.Parameters.AddWithValue("@crReviewRequired", cr.ReviewRequired);
// int count = cmd06.ExecuteNonQuery();
// }
// }
// } // drop out of query while loop here
// // set any records that are not IsProcessed=TRUE to no quantity (i.e. by type) and quantity
// // or... do I copy record to history and delete <------- THIS
// // also, should add check, cross reference inventory age table against stock ledger results to highlight sku where I reckon
// // qty is zero and amazon is >0
// scope.Complete();
// }
// }
// }
// }
//}
}
}