Export amazon settlement report fix

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

View File

@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Account
{
public class ValidateAccountCode : Validate
{
private Logic.Utilities.StringCheck stringCheck = new Logic.Utilities.StringCheck();
public new void Innit()
{
base.Innit();
stringCheck = new Logic.Utilities.StringCheck();
}
public bool IsValidAccountCodeId(int accountCode)
{
if (accountCode >=0)
{ return true; }
else
{
ErrorListAdd("Invalid account code.");
return false;
}
}
public bool IsValidTitle(string title)
{
if (stringCheck.MaxLength(title, 150))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList);
return false;
}
}
public bool IsValidDescription(string description)
{
if (stringCheck.MaxLength(description, 500))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList);
return false;
}
}
public bool IsValidType(string type)
{
if (stringCheck.MaxLength(type, 50))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList);
return false;
}
}
public bool IsValidBasicType(string basicType)
{
if (stringCheck.MaxLength(basicType, 50))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList);
return false;
}
}
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Account
{
public class ValidateCurrencyCode : Validate
{
private Logic.Utilities.StringCheck stringCheck = new Logic.Utilities.StringCheck();
public new void Innit()
{
base.Innit();
stringCheck = new Logic.Utilities.StringCheck();
}
public bool IsValidCurrencyCode(string currencyCode)
{
if (stringCheck.Length(currencyCode, 3) && stringCheck.IsAlpha(currencyCode, true))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList);
return false;
}
}
}
}

View File

@@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Account
{
public abstract class ValidateInvoice : Validate
{
protected Account.ValidateAccountCode validateAccountCode = new Account.ValidateAccountCode();
protected Account.ValidateCurrencyCode validateCurrencyCode = new Account.ValidateCurrencyCode();
protected Account.ValidateTaxCode validateTaxCode = new ValidateTaxCode();
protected Logic.Utilities.StringCheck stringCheck = new Logic.Utilities.StringCheck();
public bool InvoiceNumberIsRequired { get; set; } = true;
public bool InvoiceLineDescriptionIsRequired { get; set; } = true;
public new void Innit()
{
base.Innit();
validateAccountCode.Innit();
validateCurrencyCode.Innit();
validateTaxCode.Innit();
stringCheck.Innit();
}
protected bool IsValidInvoice(Model.Account.IInvoice invoice)
{
return IsValidInvoice(new List<Model.Account.IInvoice> { invoice });
}
protected bool IsValidInvoice(List<Model.Account.IInvoice> invoiceList)
{
Innit();
if (invoiceList == null || !invoiceList.Any())
{
ErrorListAdd("Invoice list is null or empty.");
return false;
}
var tempErrorList = new List<string>();
for (int i = 0; i < invoiceList.Count(); i++)
{
Innit();
// check header info
if (invoiceList[i].ContactNameIsSet) { IsValidInvoiceContact(invoiceList[i].ContactName); }
else { ErrorListAdd("'Contact Name' is a required value"); }
if (invoiceList[i].InvoiceAmountIsSet)
{
if (!invoiceList[i].IsCreditNoteIsSet)
{ ErrorListAdd("'Is Credit Note' is a required value"); }
else
{
if (invoiceList[i].IsCreditNote && invoiceList[i].InvoiceAmount > 0)
{ ErrorListAdd("Credit Note amount cannot be greater than zero"); }
else if (!invoiceList[i].IsCreditNote && invoiceList[i].InvoiceAmount < 0)
{ ErrorListAdd("Invoice amount cannot be less than zero"); }
}
}
else { ErrorListAdd("'Invoice Amount' is a required value"); }
if (invoiceList[i].InvoiceCurrencyCodeIsSet) { IsValidInvoiceCurrency(invoiceList[i].InvoiceCurrencyCode); }
else { ErrorListAdd("'Invoice Currency Code' is a required value"); }
if (invoiceList[i].InvoiceDateIsSet) { IsValidInvoiceDate(invoiceList[i].InvoiceDate); }
else { ErrorListAdd("'Invoice Date' is a required value"); }
if (!invoiceList[i].InvoiceDateKindIsSet) { ErrorListAdd("'Invoice Date Kind' is a required value"); }
if (invoiceList[i].InvoiceDueDateIsSet) { IsValidInvoiceDueDate(invoiceList[i].InvoiceDueDate); }
if (invoiceList[i].InvoiceNumberIsSet)
{ IsValidInvoiceNumber(invoiceList[i].InvoiceNumber); }
else
{
if (InvoiceNumberIsRequired) { ErrorListAdd("'Invoice Number' is a required value"); }
}
if (invoiceList[i].InvoiceReferenceIsSet) { IsValidInvoiceReference(invoiceList[i].InvoiceReference); }
else { ErrorListAdd("'Invoice Reference' is a required value"); }
if (!invoiceList[i].IsCreditNoteIsSet) { ErrorListAdd("'Invoice Reference' is a required value"); }
// loop though lines and check and sum totals
if (!invoiceList[i].InvoiceLineListIsSet)
{ ErrorListAdd("Invoice is required to have lines."); }
else
{
decimal lineTotal = 0;
for (int j = 0; j < invoiceList[i].InvoiceLineList.Count(); j++)
{
if (!invoiceList[i].InvoiceLineList[j].AccountCodeIsSet) { ErrorListAdd("Line 'Account Code' is a required value"); }
else { IsValidInvoiceLineAccount(invoiceList[i].InvoiceLineList[j].AccountCode); }
if (!invoiceList[i].InvoiceLineList[j].DescriptionIsSet)
{
if (InvoiceLineDescriptionIsRequired) { ErrorListAdd("Line 'Description' is a required value"); }
}
else { IsValidInvoiceLineDescription(invoiceList[i].InvoiceLineList[j].Description); }
if (!invoiceList[i].InvoiceLineList[j].GrossTotalAmountIsSet) { ErrorListAdd("Line 'Gross Total Amount' is a required value"); }
if (!invoiceList[i].InvoiceLineList[j].ItemCodeIsSet) { ErrorListAdd("Line 'Item Code' is a required value"); }
else { IsValidLineItemCode(invoiceList[i].InvoiceLineList[j].ItemCode); }
if (!invoiceList[i].InvoiceLineList[j].QuantityIsSet) { ErrorListAdd("Line 'Quantity' is a required value"); }
if (!invoiceList[i].InvoiceLineList[j].TaxAmountIsSet) { ErrorListAdd("Line 'Tax Amount' is a required value"); }
if (!invoiceList[i].InvoiceLineList[j].TaxCodeIsSet) { ErrorListAdd("Line 'Tax Code' is a required value"); }
else { IsValidLineTaxCode(invoiceList[i].InvoiceLineList[j].TaxCode); }
if (!invoiceList[i].InvoiceLineList[j].TotalNetAmountIsSet) { ErrorListAdd("Line 'Total Net Amount' is a required value"); }
if ((invoiceList[i].InvoiceLineList[j].TaxAmount
+ invoiceList[i].InvoiceLineList[j].TaxAmountAdjust
+ invoiceList[i].InvoiceLineList[j].TotalNetAmount) != invoiceList[i].InvoiceLineList[j].GrossTotalAmount)
{ ErrorListAdd("Incorrect invoice line total (gross) amount."); }
lineTotal = lineTotal + invoiceList[i].InvoiceLineList[j].GrossTotalAmount;
}
// check totals
if (invoiceList[i].InvoiceAmountIsSet && (invoiceList[i].InvoiceAmount != lineTotal))
{ ErrorListAdd("Invoice line total does not match invoice total amount."); }
}
tempErrorList.AddRange(ErrorList.Select(x => "[Inv" + i + "] " + x).ToList());
}
Innit();
ErrorListAdd(tempErrorList);
if (ErrorListIsSet) { return false; }
else { return true; }
}
protected bool IsValidInvoiceLineAccount(int accountCode)
{
validateAccountCode.Innit();
if (!validateAccountCode.IsValidAccountCodeId(accountCode))
{
ErrorListAdd(validateAccountCode.ErrorList.Select(x => "Invalid invoice line account code: " + x).ToList());
return false;
}
else
{ return true; }
}
protected bool IsValidInvoiceLineDescription(string lineDescription)
{
int maxLength = 150;
stringCheck.Innit();
if (!stringCheck.MaxLength(lineDescription, maxLength))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid invoice line description: " + x).ToList());
return false;
}
return true;
}
protected bool IsValidInvoiceContact(string contactName)
{
int maxlength = 150;
stringCheck.Innit();
if (!stringCheck.MaxLength(contactName, maxlength))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid invoice nontact name: " + x).ToList());
return false;
}
return true;
}
protected bool IsValidInvoiceDate(DateTime invoiceDate)
{
if (invoiceDate.Kind != DateTimeKind.Utc)
{
ErrorListAdd(@"Invalid date/time, UTC kind required.");
return false;
}
else if (invoiceDate == default(DateTime))
{
ErrorListAdd("Date and time is default value.");
return false;
}
return true;
}
protected bool IsValidInvoiceDueDate(DateTime invoiceDueDate)
{
if (invoiceDueDate.Kind != DateTimeKind.Utc)
{
ErrorListAdd(@"Invalid date/time, UTC kind required.");
return false;
}
else if (invoiceDueDate == default(DateTime))
{
ErrorListAdd("Date and time is default value.");
return false;
}
return true;
}
protected bool IsValidInvoiceCurrency(string currencyCode)
{
validateCurrencyCode.Innit();
if (!validateCurrencyCode.IsValidCurrencyCode(currencyCode))
{
ErrorListAdd(validateCurrencyCode.ErrorList.Select(x => "Invalid invoice currency code: " + x).ToList());
return false;
}
else { return true; }
}
protected bool IsValidInvoiceNumber(string invoiceNumber)
{
int maxlength = 64;
stringCheck.Innit();
if (!stringCheck.MaxLength(invoiceNumber, maxlength))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid invoice number: " + x).ToList());
return false;
}
return true;
}
protected bool IsValidInvoiceReference(string invoiceReference)
{
int maxlength = 50;
stringCheck.Innit();
if (!stringCheck.MaxLength(invoiceReference, maxlength))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid invoice reference: " + x).ToList());
return false;
}
return true;
}
protected bool IsValidLineItemCode(string itemCode)
{
int maxlength = 250;
stringCheck.Innit();
if (!stringCheck.MaxLength(itemCode, maxlength))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid invoice line item code: " + x).ToList());
return false;
}
return true;
}
protected bool IsValidLineTaxCode(string taxCode)
{
validateTaxCode.Innit();
if (validateTaxCode.IsValidTaxCodeId(taxCode))
{ return true; }
else
{
ErrorListAdd(validateTaxCode.ErrorList.Select(x => "Invalid invoice line " + x).ToList());
return false;
}
}
}
}

View File

@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Account
{
public class ValidateSalesInvoice : ValidateInvoice
{
public ValidateSalesInvoice()
{
int propertyCount = new Model.Account.SalesInvoice().GetType().GetProperties().Count();
if (propertyCount != 20)
{ throw new Exception("Model.Account.SalesInvoice property count has altered. Validate class requires an update."); }
propertyCount = new Model.Account.SalesInvoice.InvoiceLine().GetType().GetProperties().Count();
if (propertyCount != 18)
{ throw new Exception("Model.Account.SalesInvoice property count has altered. Validate class requires an update."); }
}
public bool IsValidInvoice(Model.Account.SalesInvoice invoice)
{
return IsValidInvoice(new List<Model.Account.SalesInvoice> { invoice });
}
public bool IsValidInvoice(List<Model.Account.SalesInvoice> invoiceList)
{
var interfaceList = invoiceList.Cast<Model.Account.IInvoice>().ToList();
return IsValidInvoice(interfaceList);
}
}
}

View File

@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Account
{
public class ValidateTaxCode : Validate
{
private Logic.Utilities.StringCheck stringCheck = new Logic.Utilities.StringCheck();
public new void Innit()
{
base.Innit();
stringCheck.Innit();
}
public bool IsValidGrossAmountMultiplier(decimal multiplier)
{
if (multiplier >= 0 && multiplier <= 1)
{
return true;
}
else
{
ErrorListAdd( "Gross multiplier must be equal to, or between, 0 and 1.");
return false;
}
}
public bool IsValidNetAmountMultiplier(decimal multiplier)
{
if (multiplier >= 0 && multiplier <= 1)
{
return true;
}
else
{
ErrorListAdd("Net multiplier must not be less than 0 or greater than 1.");
return false;
}
}
public bool IsValidOnExpense(Model.Account.TaxCode taxInfo)
{
if (taxInfo.IsValidOnExpense || taxInfo.IsSetIsValidOnIncome)
{
if (taxInfo.IsSetIsValidOnExpense)
{
return true;
}
else
{
ErrorListAdd("Is Valid On Expense has not been set.");
return false;
}
}
else
{
ErrorListAdd("Either 'IsValidOnExpense' or 'IsSetIsValidOnSale' must be set to true.");
return false;
}
}
public bool IsValidOnIncome(Model.Account.TaxCode taxInfo)
{
if (taxInfo.IsValidOnExpense || taxInfo.IsSetIsValidOnIncome)
{
if (taxInfo.IsSetIsValidOnIncome)
{
return true;
}
else
{
ErrorListAdd("Is Valid On Income has not been set.");
return false;
}
}
else
{
ErrorListAdd("Either 'IsValidOnPurchase' or 'IsSetIsValidOnSale' must be set to true.");
return false;
}
}
public bool IsValidTaxCodeId(string taxCodeId)
{
if (!stringCheck.IsAlphaNumeric(taxCodeId, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid Tax Code: " + x).ToList());
return false;
}
if (taxCodeId.Length != 4)
{
ErrorListAdd("Invalid Tax Code: Length does not equal 4 charaters.");
return false;
}
return true;
}
public bool IsValidTaxRateDescription(string description)
{
if (stringCheck.MaxLength(description, 250, true))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid Tax Rate Description: " + x).ToList());
return false;
}
}
public bool IsValidTaxRateTitle(string title)
{
if (stringCheck.MaxLength(title, 50, false))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid Tax Rate Title: " + x).ToList());
return false;
}
}
public bool IsValidTaxRateTitleShort(string title)
{
if (stringCheck.MaxLength(title, 50, false))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid Tax Rate Title Short: " + x).ToList());
return false;
}
}
public bool IsValidTaxType(string taxType)
{
if (stringCheck.MaxLength(taxType, 50, false))
{
return true;
}
else
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid Tax Rate Type: " + x).ToList());
return false;
}
}
}
}

View File

@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace bnhtrade.Core.Logic.Export
{
public class AmazonSettlementData
{
private string sqlConnectionString;
private Dictionary<string, Model.Account.TaxCode> taxCodeBySkuNumer;
public AmazonSettlementData(string sqlConnectionString)
{
this.sqlConnectionString = sqlConnectionString;
}
public void ToInvoice()
{
var console = new UI.Console.Update();
var log = new Logic.Log.LogEvent();
log.LogInformation("Starting processing of Amazon settlement data into export invoice table...");
// get list of unprocssed settlement reports to export
var settlementData = new Data.Database.Import.ReadAmazonSettlement(sqlConnectionString);
var settlementList = settlementData.AllUnprocessed();
settlementData = null;
if (settlementList == null)
{
log.LogInformation("No new settlements to process, exiting import...");
return;
}
// create list of settlement ids
var settlementIdList = new List<string>();
for (int i = 0; i < settlementList.Count(); i++)
{
settlementIdList.Add(settlementList[i].SettlementId);
}
// test marketplace-name has been sucsessfully entered into settlement table --
// as this is not supplied in the original report from Amazon and has to be inferred from settlement line data
// this is not picked up in validate stage as null value is valid
for (int i = 0; i < settlementList.Count(); i++)
{
if (!settlementList[i].MarketPlaceNameIsSet)
{
log.LogError(
"Action required: Enter market place name for settlelment report id " + settlementList[i].SettlementId + "."
, "Unable to process settlement data from one settlement report '" + settlementList[i].SettlementId +
"'. Report header table requires a market place name, which is not supplied in original " +
"report from Amazon. This is useually inferred from settlement lines. " +
"However, in this case, it was not not possible. Manual edit/entry for database table required."
);
}
}
// validate settlelments
var validate = new Logic.Import.ValidateAmazonSettlement();
for (int i = 0; i < settlementList.Count(); i++)
{
if (!validate.IsValid(settlementList[i]))
{
log.LogError("Error procesing Amazon Settlement data for export.", validate.ErrorListToString());
}
}
if (validate.ErrorListIsSet) { return; }
// get dictionary of sku-number to taxcodeId
Console.Write("\rBuilding SKU list... ");
var dicSkuNumberToTaxCodeId = new Dictionary<string, string>();
for (int i = 0; i < settlementList.Count(); i++)
{
if (settlementList[i].SettlementLineListIsSet)
{
for (int j = 0; j < settlementList[i].SettlementLineList.Count(); j++)
{
if (settlementList[i].SettlementLineList[j].SkuIsSet
&& !string.IsNullOrWhiteSpace(settlementList[i].SettlementLineList[j].Sku))
{
if (!dicSkuNumberToTaxCodeId.ContainsKey(settlementList[i].SettlementLineList[j].Sku))
{
dicSkuNumberToTaxCodeId.Add(settlementList[i].SettlementLineList[j].Sku, null);
}
}
}
}
}
var readTaxCode = new Data.Database.Account.ReadTaxCode(sqlConnectionString);
taxCodeBySkuNumer = readTaxCode.BySkuNumber(dicSkuNumberToTaxCodeId.Keys.ToList());
// loop through each settlement and build list of invoices to export
Console.Write("\rBuilding invoices to export... ");
var invoiceList = new List<Model.Account.SalesInvoice>();
for (int i = 0; i < settlementList.Count(); i++)
{
// split settlement line list into months
// List<Model.Account.SalesInvoice.InvoiceLine>
var monthList = settlementList[i].SettlementLineList
.GroupBy(x => new DateTime(x.PostDateTime.Year, x.PostDateTime.Month, 1, 0, 0, 0, x.PostDateTime.Kind));
//.GroupBy(x => string.Format("{0}-{1}", x.PostDateTime.Year, x.PostDateTime.Month));
//.GroupBy(x => new { x.PostDateTime.Month, x.PostDateTime.Year });
int monthCount = 0;
foreach (var month in monthList)
{
monthCount++;
var itemCodeTotal = new Dictionary<string, decimal>();
foreach (var line in month)
{
string itemCode = BuildLineItemCode(line.Sku, line.TransactionType, line.AmountType, line.AmountDescription);
if (itemCodeTotal.ContainsKey(itemCode))
{
itemCodeTotal[itemCode] += line.Amount;
}
else
{
itemCodeTotal.Add(itemCode, line.Amount);
}
}
// create invoice, one for each month
var invoice = new Model.Account.SalesInvoice();
// create invoice lines forsy
invoice.InvoiceLineList = new List<Model.Account.SalesInvoice.InvoiceLine>();
decimal lineNetTotal = 0m;
decimal lineTaxTotal = 0m;
foreach (var item in itemCodeTotal)
{
var line = new Model.Account.SalesInvoice.InvoiceLine();
line.ItemCode = item.Key;
line.TotalNetAmount = item.Value;
lineNetTotal += item.Value;
line.TaxAmount = 0;
lineTaxTotal += 0;
line.Quantity = 1;
invoice.InvoiceLineList.Add(line);
}
invoice.ContactName = settlementList[i].MarketPlaceName;
invoice.InvoiceCurrencyCode = settlementList[i].CurrencyCode;
if (monthList.Count() == 1 || monthList.Count() == monthCount)
{ invoice.InvoiceDate = settlementList[i].EndDate; }
else
{ invoice.InvoiceDate = new DateTime(month.Key.Year, month.Key.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddDays(-1); }
invoice.InvoiceDateKind = DateTimeKind.Utc;
invoice.InvoiceDueDate = settlementList[i].DepositDate;
invoice.InvoiceReference = settlementList[i].SettlementId;
invoice.InvoiceAmount = lineNetTotal + lineTaxTotal;
if (invoice.InvoiceAmount < 0) { invoice.IsCreditNote = true; }
else { invoice.IsCreditNote = false; }
// invoice complete, add to list
invoiceList.Add(invoice);
}
}
// sort list of invoices
invoiceList = invoiceList.OrderBy(x => x.InvoiceReference).ThenBy(x => x.InvoiceDate).ToList();
// check invoice total against settlement totals
var invoiceTotal = new Dictionary<string, decimal>();
for (int i = 0; i < invoiceList.Count(); i++)
{
if (invoiceTotal.ContainsKey(invoiceList[i].InvoiceReference))
{
invoiceTotal[invoiceList[i].InvoiceReference] += invoiceList[i].InvoiceAmount;
}
else
{
invoiceTotal.Add(invoiceList[i].InvoiceReference, invoiceList[i].InvoiceAmount);
}
}
for (int i = 0; i < settlementList.Count(); i++)
{
if (settlementList[i].TotalAmount != invoiceTotal[settlementList[i].SettlementId])
{
throw new Exception("invoice totals does not match settlement total.");
}
}
if (settlementIdList.Count != invoiceTotal.Count())
{
log.LogError("Stopping Settlement export. Not all settlements have been transposed into invoices.");
return;
}
// postfix invoices spanning multiple months with -n
if (invoiceList.Count() > 1)
{
string lastRef = invoiceList[0].InvoiceReference;
int countRef = 1;
for (int i = 1; i < invoiceList.Count(); i++)
{
if (invoiceList[i].InvoiceReference == lastRef)
{
if (countRef == 1)
{
invoiceList[i - 1].InvoiceReference = lastRef + "-" + countRef;
}
invoiceList[i].InvoiceReference = lastRef + "-" + (countRef += 1);
}
else
{
// shouldn't normally be more than 2 date ranges, log and move on.
if (countRef > 2)
{
log.LogError(
countRef + " total numner of export invoices created from Amazon Settlement Id" + lastRef + "."
, "Settlement period appears to span more 3 months or more. Whilst this is possible, it is unsual. Confirm his is correct.");
}
lastRef = invoiceList[i].InvoiceReference;
countRef = 1;
}
}
}
Console.Write("\rWriting to database... ");
using (TransactionScope scope = new TransactionScope())
{
try
{
// write to the database (gets validated there)
new Data.Database.Export.CreateSalesInvoice(sqlConnectionString).SaveInvoice(invoiceList);
// set settlements to isprocessed
new Data.Database.Import.UpdateAmazonSettlement(sqlConnectionString).SetIsProcessedTrue(settlementIdList);
scope.Complete();
}
catch (Exception ex)
{
log.LogError(ex.Message);
return;
}
}
Console.Write("\r");
log.LogInformation("Finished processing of Amazon settlement data. " + invoiceList.Count() + " invoices created from "+ settlementIdList.Count() + " Amazon settlement reports.");
}
private string BuildLineItemCode(string skuNumber, string transactionType, string amountType, string amountDescription)
{
// build the match string
// NB special case for global accounting sale and refunds (also note Goodlwill is included) and sku's where tax is included
string match01 = transactionType;
string match02 = amountType;
string match03 = amountDescription;
string matchString = "<AmazonReport><SettlementReportLine><" + match01 + "><" + match02 + "><" + match03 + ">";
// add tax info if required
if ((match01 == "Order" || match01 == "Refund")
&& (match02 == "ItemPrice" || match02 == "Promotion"))
{
if (taxCodeBySkuNumer.ContainsKey(skuNumber))
{
matchString = matchString + "<TaxCode=" + taxCodeBySkuNumer[skuNumber].TaxCodeId + ">";
}
else
{
throw new Exception("Sku#" + skuNumber + " tax info not found in dictionary list.");
}
}
return matchString;
}
}
}

View File

@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Export
{
class ValidateSalesInvoice : Logic.Account.ValidateInvoice
{
//public bool IsValidInvoice(Model.Export.SetSalesInvoice invoice)
//{
// ErrorMessage = null;
// var baseInvoice = CopyInvoiceToBase(invoice);
// if (!base.IsValidInvoice(baseInvoice))
// {
// return false;
// }
// // check each match string only appears once
// var dicLookup = new Dictionary<string, string>();
// foreach (var line in invoice.InvoiceLineList)
// {
// if (dicLookup.ContainsKey(line.LineTypeMatchString))
// {
// ErrorMessage = "'Line type match string' duplication.";
// return false;
// }
// else
// {
// dicLookup.Add(line.LineTypeMatchString, null);
// }
// }
// return true;
//}
//public bool IsValidInvoiceHeader(Model.Export.SetSalesInvoice invoice)
//{
// ErrorMessage = null;
// var baseInvoice = CopyInvoiceHeaderToBase(invoice);
// if (base.IsValidInvoiceHeader(baseInvoice))
// {
// return true;
// }
// else
// {
// return false;
// }
//}
//public bool IsValidInvoiceLine(Model.Export.SetSalesInvoiceLine invoiceLine)
//{
// ErrorMessage = null;
// var baseLine = CopyInvoiceLineToBase(invoiceLine);
// if (!IsValidLineTypeMatchString(invoiceLine.LineTypeMatchString)
// || !base.IsValidInvoiceLine(baseLine))
// {
// return false;
// }
// return true;
//}
//public bool IsValidLineTypeMatchString(string matchString)
//{
// ErrorMessage = null;
// var stringCheck = new Logic.Utilities.StringCheck();
// if (!stringCheck.MaxLength(matchString, 250))
// {
// ErrorMessage = "Invalid Line Type Match String: " + stringCheck.ErrorMessage;
// return false;
// }
// return true;
//}
//private Model.Account.SalesInvoice CopyInvoiceToBase(Model.Export.SetSalesInvoice invoice)
//{
// var baseInvoice = CopyInvoiceHeaderToBase(invoice);
// if (invoice.IsSetInvoiceLineList)
// {
// var baseLineList = new List<Model.Account.SalesInvoiceLine>();
// foreach (var line in invoice.InvoiceLineList)
// {
// baseLineList.Add(CopyInvoiceLineToBase(line));
// }
// baseInvoice.InvoiceLineList = baseLineList;
// }
// return baseInvoice;
//}
//private Model.Account.SalesInvoice CopyInvoiceHeaderToBase(Model.Export.SetSalesInvoice invoice)
//{
// var baseInvoice = new Model.Account.SalesInvoice();
// if (invoice.IsSetContactName)
// { baseInvoice.ContactName = invoice.ContactName; }
// if (invoice.IsSetInvoiceAmount)
// { baseInvoice.InvoiceAmount = invoice.InvoiceAmount; }
// if (invoice.IsSetInvoiceCurrencyCode)
// { baseInvoice.InvoiceCurrencyCode = invoice.InvoiceCurrencyCode; }
// if (invoice.IsSetInvoiceDate)
// { baseInvoice.InvoiceDate = invoice.InvoiceDate; }
// if (invoice.IsSetInvoiceNumber)
// { baseInvoice.InvoiceNumber = invoice.InvoiceNumber; }
// if (invoice.IsSetInvoiceReference)
// { baseInvoice.InvoiceReference = invoice.InvoiceReference; }
// if (invoice.IsSetIsComplete)
// { baseInvoice.IsComplete = invoice.IsComplete; }
// return baseInvoice;
//}
//private Model.Account.SalesInvoiceLine CopyInvoiceLineToBase(Model.Export.SetSalesInvoiceLine invoiceLine)
//{
// var baseLine = new Model.Account.SalesInvoiceLine();
// if (invoiceLine.IsSetAccountCode)
// { baseLine.AccountCode = invoiceLine.AccountCode; }
// // something missing here ??????
// if (invoiceLine.IsSetDescription)
// { baseLine.Description = invoiceLine.Description; }
// if (invoiceLine.IsSetNetAmount)
// { baseLine.TotalNetAmount = invoiceLine.NetAmount; }
// // tax adjustment to set ??????????
// if (invoiceLine.IsSetTaxCode)
// { baseLine.TaxCode = invoiceLine.TaxCode; }
// return baseLine;
//}
}
}

View File

@@ -0,0 +1,499 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Import
{
public class ValidateAmazonSettlement : Validate
{
protected Utilities.StringCheck stringCheck = new Utilities.StringCheck();
protected Utilities.DateTimeCheck timeCheck = new Utilities.DateTimeCheck();
protected Account.ValidateCurrencyCode currencyCheck = new Account.ValidateCurrencyCode();
protected Utilities.DecimalCheck decimalCheck = new Utilities.DecimalCheck();
public ValidateAmazonSettlement() : base()
{
}
public bool ValidateMarketPlaceName { get; set; } = true;
public new void Innit()
{
base.Innit();
timeCheck.Innit();
stringCheck.Innit();
currencyCheck.Innit();
decimalCheck.Innit();
}
public bool IsValid(Model.Import.AmazonSettlement settlement)
{
return IsValid(new List<Model.Import.AmazonSettlement> { settlement });
}
public bool IsValid(List<Model.Import.AmazonSettlement> settlementList)
{
Innit();
for (int i = 0; i < settlementList.Count; i++)
{
if (!settlementList[i].CurrencyCodeIsSet) { ErrorListAdd("CurrencyCode is a required value."); }
else { IsValidCurrencyCode(settlementList[i].CurrencyCode); }
if (!settlementList[i].DepositDateIsSet) { ErrorListAdd("DepositDate is a required value."); }
else { IsValidDepositDate(settlementList[i].DepositDate); }
if (!settlementList[i].EndDateIsSet) { ErrorListAdd("EndDate is a required value."); }
else { IsValidEndDate(settlementList[i].EndDate); }
if (!settlementList[i].IsProcessedIsSet) { ErrorListAdd("IsProcessed is a required value."); }
else { IsValidIsProcessed(settlementList[i].IsProcessed); }
if (!settlementList[i].MarketPlaceNameIsSet)
{
if (ValidateMarketPlaceName) { ErrorListAdd("MarketPlaceName is a required value."); }
}
else { IsValidMarketPlaceName(settlementList[i].MarketPlaceName); }
if (!settlementList[i].SettlementIdIsSet) { ErrorListAdd("SettlementId is a required value."); }
else { IsValidSettlementId(settlementList[i].SettlementId); }
if (!settlementList[i].StartDateIsSet) { ErrorListAdd("StartDate is a required value."); }
else { IsValidStartDate(settlementList[i].StartDate); }
if (!settlementList[i].TotalAmountIsSet) { ErrorListAdd("TotalAmount is a required value."); }
else { IsValidTotalAmount(settlementList[i].TotalAmount); }
// check line list
if (!settlementList[i].SettlementLineListIsSet)
{
ErrorListAdd("Settlement line list is null or empty");
continue;
}
else
{
// loop though lines and check
decimal lineSum = 0;
for (int j = 0; j < settlementList[i].SettlementLineList.Count(); j++)
{
IsValid(settlementList[i].SettlementLineList[j]);
if (settlementList[i].SettlementLineList[j].AmountIsSet)
{ lineSum += settlementList[i].SettlementLineList[j].Amount; }
}
// check totals
if (lineSum != settlementList[i].TotalAmount)
{
ErrorListAdd("Settlement header total (" + settlementList[i].TotalAmount +
") does not match line total (" + lineSum + ")");
}
}
}
if (ErrorListIsSet) { return false; }
else { return true; }
}
public bool IsValid(Model.Import.AmazonSettlement.SettlementLine settlementLine)
{
if (settlementLine.AdjustmentIdIsSet)
{
if (!IsValidAdjustmentId(settlementLine.AdjustmentId)) { }
}
if (settlementLine.AmountIsSet)
{
if (!IsValidAmount(settlementLine.Amount)) { }
}
else
{
ErrorListAdd("Amount is a required value.");
}
if (settlementLine.AmountDescriptionIsSet)
{
if (!IsValidAmountDescription(settlementLine.AmountDescription)) { }
}
else
{
ErrorListAdd("Amount Description is a required value.");
}
if (settlementLine.AmountTypeIsSet)
{
if (!IsValidAmountType(settlementLine.AmountType)) { }
}
else
{
ErrorListAdd("Amount Type is a required value.");
}
if (settlementLine.CurrenyCodeIsSet)
{
if (!IsValidCurrenyCode(settlementLine.CurrenyCode)) { }
}
else
{
ErrorListAdd("Currency Code is a required value.");
}
if (settlementLine.ExportAccountInvoiceLineIdIsSet)
{
if (!IsValidExportAccountInvoiceLineId(settlementLine.ExportAccountInvoiceLineId)) { }
}
if (settlementLine.FulfillmentIdIsSet)
{
if (!IsValidFulfillmentId(settlementLine.FulfillmentId)) { }
}
if (settlementLine.IsProcessedIsSet)
{
if (!IsValidIsProcessed(settlementLine.IsProcessed)) { }
}
else
{
ErrorListAdd("Is Processed is a required value.");
}
if (settlementLine.MarketPlaceNameIsSet)
{
if (!IsValidMarketPlaceName(settlementLine.MarketPlaceName)) { }
}
if (settlementLine.MerchantAdjustmentItemIdIsSet)
{
if (!IsValidMerchantAdjustmentItemId(settlementLine.MerchantAdjustmentItemId)) { }
}
if (settlementLine.MerchantOrderIdIsSet)
{
if (!IsValidMerchantOrderId(settlementLine.MerchantOrderId)) { }
}
if (settlementLine.MerchantOrderItemIdIsSet)
{
if (!IsValidMerchantOrderItemId(settlementLine.MerchantOrderItemId)) { }
}
if (settlementLine.OrderIdIsSet)
{
if (!IsValidOrderId(settlementLine.OrderId)) { }
}
if (settlementLine.OrderItemCodeIsSet)
{
if (!IsValidOrderItemCode(settlementLine.OrderItemCode)) { }
}
if (settlementLine.PostDateTimeIsSet)
{
if (!IsValidPostDateTime(settlementLine.PostDateTime)) { }
}
else
{
ErrorListAdd("Posted DateTime is a required value.");
}
if (settlementLine.PromotionIdIsSet)
{
if (!IsValidPromotionId(settlementLine.PromotionId)) { }
}
if (settlementLine.QuantityPurchasedIsSet)
{
if (!IsValidQuantityPurchased(settlementLine.QuantityPurchased)) { }
}
if (settlementLine.ShipmentIdIsSet)
{
if (!IsValidShipmentId(settlementLine.ShipmentId)) { }
}
if (settlementLine.SkuIsSet)
{
if (!IsValidSku(settlementLine.Sku)) { }
}
if (settlementLine.TransactionTypeIsSet)
{
if (!IsValidTransactionType(settlementLine.TransactionType)) { }
}
else
{
ErrorListAdd("Transaction Type is a required value.");
}
if (ErrorListIsSet) { return false; }
else { return true; }
}
public bool IsValidSettlementId(string settlementId)
{
if (!stringCheck.IsNumeric(settlementId))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid settlement Id: " + x).ToList());
return false;
}
if (!stringCheck.MaxLength(settlementId, 50))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid settlement Id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidIsProcessed(bool isProcessed)
{
return true;
}
public bool IsValidMarketPlaceName(string marketPlaceName)
{
if (!stringCheck.MaxLength(marketPlaceName, 50, true))
{
ErrorListAdd("Invalid market place name.");
return false;
}
return true;
}
public bool IsValidStartDate(DateTime startDate)
{
if (!timeCheck.IsUtc(startDate))
{
ErrorListAdd(timeCheck.ErrorList.Select(x => "Invalid StartDate: " + x).ToList());
return false;
}
return true;
}
public bool IsValidEndDate(DateTime endDate)
{
if (!timeCheck.IsUtc(endDate))
{
ErrorListAdd(timeCheck.ErrorList.Select(x => "Invalid EndDate: " + x).ToList());
return false;
}
return true;
}
public bool IsValidDepositDate(DateTime depositDate)
{
if (!timeCheck.IsUtc(depositDate))
{
ErrorListAdd(timeCheck.ErrorList.Select(x => "Invalid DepositDate: " + x).ToList());
return false;
}
return true;
}
public bool IsValidTotalAmount(decimal totalAmount)
{
if (!decimalCheck.SqlLength92(totalAmount))
{
ErrorListAdd(decimalCheck.ErrorList.Select(x => "Total Amount Invalid: " + x).ToList());
return false;
}
return true;
}
public bool IsValidCurrencyCode(string currencyCode)
{
if (!currencyCheck.IsValidCurrencyCode(currencyCode))
{
ErrorListAdd(currencyCheck.ErrorList.Select(x => "Total Amount CurrencyCode: " + x).ToList());
return false;
}
return true;
}
public bool IsValidTransactionType(string transactionType)
{
if (!stringCheck.MaxLength(transactionType, 50))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid transaction type: " + x).ToList());
return false;
}
return true;
}
public bool IsValidOrderId(string orderId)
{
if (!stringCheck.MaxLength(orderId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid order id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidMerchantOrderId(string merchantOrderId)
{
if (!stringCheck.MaxLength(merchantOrderId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid merchant order id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidAdjustmentId(string adjustmentId)
{
if (!stringCheck.MaxLength(adjustmentId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid adjustment id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidShipmentId(string shipmentId)
{
if (!stringCheck.MaxLength(shipmentId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid shipment id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidAmountType(string amountType)
{
if (!stringCheck.MaxLength(amountType, 50))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid amount type: " + x).ToList());
return false;
}
return true;
}
public bool IsValidAmountDescription(string amountDescription)
{
if (!stringCheck.MaxLength(amountDescription, 100))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid amount description: " + x).ToList());
return false;
}
return true;
}
public bool IsValidAmount(decimal amount)
{
if (!decimalCheck.SqlLength92(amount))
{
ErrorListAdd(decimalCheck.ErrorList.Select(x => "Invalid amount: " + x).ToList());
return false;
}
return true;
}
public bool IsValidCurrenyCode(string currenyCode)
{
if (!currencyCheck.IsValidCurrencyCode(currenyCode))
{
ErrorListAdd(currencyCheck.ErrorList.Select(x => "Invalid curreny code: " + x).ToList());
return false;
}
return true;
}
public bool IsValidFulfillmentId(string fulfillmentId)
{
if (!stringCheck.MaxLength(fulfillmentId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid fulfillment Id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidPostDateTime(DateTime postDateTime)
{
var timeCheck = new Logic.Utilities.DateTimeCheck();
if (!timeCheck.IsUtc(postDateTime))
{
ErrorListAdd(@"Invalid post date/time, not set to UTC kind.");
return false;
}
return true;
}
public bool IsValidOrderItemCode(string orderItemCode)
{
if (!stringCheck.MaxLength(orderItemCode, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid order item code: " + x).ToList());
return false;
}
return true;
}
public bool IsValidMerchantOrderItemId(string merchantOrderItemId)
{
if (!stringCheck.MaxLength(merchantOrderItemId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid merchant order item id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidMerchantAdjustmentItemId(string merchantAdjustmentItemId)
{
if (!stringCheck.MaxLength(merchantAdjustmentItemId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid merchant adjustment item id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidSku(string skuNumber)
{
if (!stringCheck.MaxLength(skuNumber, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid sku number: " + x).ToList());
return false;
}
return true;
}
public bool IsValidQuantityPurchased(int quantityPurchased)
{
return true;
}
public bool IsValidPromotionId(string promotionId)
{
if (!stringCheck.MaxLength(promotionId, 50, true))
{
ErrorListAdd(stringCheck.ErrorList.Select(x => "Invalid promotion id: " + x).ToList());
return false;
}
return true;
}
public bool IsValidExportAccountInvoiceLineId(int exportAccountInvoiceLineId)
{
if (exportAccountInvoiceLineId > 0)
{
return true;
}
else
{
ErrorListAdd("Export account invoice line id cannot be less than 1");
return false;
}
}
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Log
{
public class LogEvent : Data.Database.Log.LogEvent
{
private DateTime? eventDateTimeUtc;
private int? eventType;
private bool? printToConsole;
public DateTime EventDateTimeUtc
{
get { return (DateTime)eventDateTimeUtc; }
set { eventDateTimeUtc = DateTime.SpecifyKind(value, DateTimeKind.Utc); }
}
private int EventType
{
get { return (int)eventType; }
set { eventType = value; }
}
private string DetailShort { get; set; }
private string DetailLong { get; set; }
public bool PrintToConsole
{
get { return (bool)printToConsole; }
set { printToConsole = value; }
}
public LogEvent()
{
EventType = 3;
PrintToConsole = true;
}
private void Execute()
{
// ensure we have enough parameter set
if (!(IsSetDetailShort
&& IsSetEventType
&& IsSetPrintToConsole))
{
throw new Exception("Insurficent Log Event parameters set");
}
// add datetime value if required
bool resetDateTime = false;
if (!IsSetEventDateTime)
{
EventDateTimeUtc = DateTime.UtcNow;
resetDateTime = true;
}
// update console
var console = new UI.Console.Update();
if (!IsSetDetailLong)
{ console.WriteLine(DetailShort); }
else { console.WriteLine(DetailShort + Environment.NewLine + DetailLong); }
// log in database
DatabaseLogInsert(DetailShort, EventType, DetailLong, EventDateTimeUtc, false); // remove false on end once code is re-writtien
// clean up
if (resetDateTime)
{ eventDateTimeUtc = null; }
}
public void LogAuditFailure(string detailShort, string detailLong = null)
{
eventType = 5;
DetailShort = detailShort;
DetailLong = detailLong;
Execute();
}
public void LogAuditSuccess(string detailShort, string detailLong = null)
{
eventType = 4;
DetailShort = detailShort;
DetailLong = detailLong;
Execute();
}
public void LogError(string detailShort, string detailLong = null)
{
eventType = 1;
DetailShort = detailShort;
DetailLong = detailLong;
Execute();
}
public void LogWarning(string detailShort, string detailLong = null)
{
eventType = 2;
DetailShort = detailShort;
DetailLong = detailLong;
Execute();
}
public void LogInformation(string detailShort, string detailLong = null)
{
eventType = 3;
DetailShort = detailShort;
DetailLong = detailLong;
Execute();
}
public void Initialise()
{
eventDateTimeUtc = null;
eventType = null;
DetailShort = null;
DetailLong = null;
PrintToConsole = true;
}
public bool IsSetEventDateTime
{
get { return eventDateTimeUtc != null; }
}
public bool IsSetEventType
{
get { return eventType != null; }
}
public bool IsSetDetailShort
{
get { return DetailShort != null; }
}
public bool IsSetDetailLong
{
get { return DetailLong != null; }
}
public bool IsSetPrintToConsole
{
get { return printToConsole != null; }
}
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Utilities
{
public class AccountVat
{
public decimal Round(decimal vatToRound)
{
return decimal.Round(vatToRound, 2, MidpointRounding.AwayFromZero);
}
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Utilities
{
public class DateTimeCheck : Validate
{
public bool IsUtc(DateTime dateTimeToCheck)
{
if (dateTimeToCheck == default(DateTime))
{
ErrorListAdd( "DateTime value set to default.");
return false;
}
if (dateTimeToCheck.Kind != DateTimeKind.Utc)
{
ErrorListAdd("DateTime not set to UTC kind.");
return false;
}
return true;
}
public bool IsLocal(DateTime dateTimeToCheck)
{
if (dateTimeToCheck == default(DateTime))
{
ErrorListAdd("DateTime value set to default.");
return false;
}
if (dateTimeToCheck.Kind != DateTimeKind.Local)
{
ErrorListAdd("DateTime not set to Local kind.");
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Utilities
{
public class DecimalCheck : Validate
{
/// <summary>
/// Finds total number of digits in a decimal number, does not include decimal point.
/// </summary>
/// <param name="decimalNumber">Decimal number to check</param>
/// <returns></returns>
public int GetLength(decimal decimalNumber)
{
return (decimalNumber.ToString().Length - 1);
}
/// <summary>
/// Finds total number of digits to the right of the decimal point in a decimal number.
/// </summary>
/// <param name="decimalNumber">Decimal number to check</param>
/// <returns></returns>
public int GetPrecision(decimal decimalNumber)
{
return BitConverter.GetBytes(decimal.GetBits(decimalNumber)[3])[2];
}
/// <summary>
/// Checks decimal number is match for SQL Server datatype 'decimal(9, 2)'
/// </summary>
/// <param name="decimalToCheck">Decimal number to check</param>
/// <returns></returns>
public bool SqlLength92(decimal decimalToCheck)
{
int precision = GetPrecision(decimalToCheck);
if (precision > 2)
{
ErrorListAdd("Decimal precision overload");
return false;
}
int length = GetLength(decimalToCheck);
if (length > 9)
{
ErrorListAdd("Decimal length overload");
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,36 @@
using System;
namespace bnhtrade.Core.Logic.Utilities
{
class PropertyCheck
{
public string ErrorMessage { get; set; }
public bool IsPropertyExist(dynamic classObject, string propertyName)
{
ErrorMessage = null;
if (classObject == null)
{
throw new Exception("Object is null.");
//ErrorMessage = "Object is null.";
//return false;
}
if (string.IsNullOrWhiteSpace(propertyName))
{
throw new Exception("Property name is null or whitespace.");
//ErrorMessage = "Property name is null or whitespace.";
//return false;
}
dynamic val = classObject[propertyName];
if (object.ReferenceEquals(val, null))
{
ErrorMessage = "Property '" + propertyName + "' does not exist in '" + classObject.GetType().Name + "'.";
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic.Utilities
{
public class StringCheck : Validate
{
public bool AllowEmpty { get; set; } = false;
public bool AllowWhiteSpace { get; set; } = false;
public void ResetToDefault()
{
Innit();
AllowEmpty = false;
AllowWhiteSpace = false;
}
public bool IsAlpha(string stringToCheck, bool upperCaseOnly = false, bool allowNull = false)
{
if (stringToCheck == null)
{
if (!allowNull)
{
ErrorListAdd("String is null");
return false;
}
}
else
{
foreach (char c in stringToCheck)
{
if (!((c >= 'A' && c <= 'Z')
|| ((c >= 'a' && c <= 'z') && !upperCaseOnly)))
{
if ((c >= 'a' && c <= 'z') && upperCaseOnly)
{
ErrorListAdd("String contains lower case numerical charater(s).");
return false;
}
else
{
ErrorListAdd("String contains non-alpha charater(s).");
return false;
}
}
}
}
return true;
}
public bool IsAlphaNumeric(string stringToCheck, bool upperCaseOnly = false, bool allowNull = false)
{
if (stringToCheck == null)
{
if (!allowNull)
{
ErrorListAdd("String is null");
return false;
}
}
else
{
foreach (char c in stringToCheck)
{
if (!((c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'Z')
|| ((c >= 'a' && c <= 'z') && !upperCaseOnly)))
{
if ((c >= 'a' && c <= 'z') && upperCaseOnly)
{
ErrorListAdd("String contains lower case numerical charater(s).");
return false;
}
else
{
ErrorListAdd("String contains non-alphanumeric charater(s).");
return false;
}
}
}
}
return true;
}
public bool IsNumeric(string stringToCheck, bool allowNull = false)
{
if (stringToCheck == null)
{
if (allowNull == false)
{
ErrorListAdd("String is null");
return false;
}
}
else
{
foreach (char c in stringToCheck)
{
if (c < '0' || c > '9')
{
ErrorListAdd("String contains non-numeric charater(s).");
return false;
}
}
}
return true;
}
public bool Length(string stringToCheck, int stringLength, bool allowNull = false)
{
if (!NullOrWhiteSpaceCheck(stringToCheck, allowNull))
{
return false;
}
int length = stringToCheck.Length;
if (length != stringLength)
{
ErrorListAdd("String length (" + length + ") does not equal " + stringLength + " charaters.");
return false;
}
return true;
}
public bool MaxLength(string stringToCheck, int maxLength, bool allowNull = false)
{
if (!NullOrWhiteSpaceCheck(stringToCheck, allowNull))
{
return false;
}
if (stringToCheck != null)
{
int length = stringToCheck.Length;
if (length > maxLength)
{
ErrorListAdd("String length (" + length + ") is greater than " + maxLength + " charaters.");
return false;
}
}
return true;
}
public bool MinLength(string stringToCheck, int minLength, bool allowNull = false)
{
if (!NullOrWhiteSpaceCheck(stringToCheck, allowNull))
{
return false;
}
int length = stringToCheck.Length;
if (length <= minLength)
{
ErrorListAdd("String length (" + length + ") is less than " + minLength + " charaters.");
return false;
}
return true;
}
private bool NullOrWhiteSpaceCheck(string stringToCheck, bool allowNull = false)
{
if (string.IsNullOrWhiteSpace(stringToCheck))
{
if (stringToCheck == null)
{
if (!allowNull)
{
ErrorListAdd("String is null, empty or white space.");
return false;
}
}
else if (stringToCheck == "")
{
if (!AllowEmpty)
{
ErrorListAdd("String is empty.");
return false;
}
}
else
{
if (!AllowWhiteSpace)
{
ErrorListAdd("String is white space.");
return false;
}
}
}
return true;
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bnhtrade.Core.Logic
{
public abstract class Validate
{
private List<string> errorList = new List<string>();
public List<string> ErrorList
{
get { return errorList; }
}
public bool ErrorListIsSet
{
get
{
if (errorList == null || !errorList.Any()) { return false; }
else { return true; }
}
}
protected void ErrorListAdd(string errorString)
{
this.errorList.Add(errorString);
}
protected void ErrorListAdd(List<string> errorList)
{
this.errorList.AddRange(errorList);
}
public string ErrorListToString()
{
if (ErrorListIsSet)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < ErrorList.Count; i++)
{
result.AppendLine(ErrorList[i]);
}
return result.ToString();
}
else { return null; }
}
public void Innit()
{
this.errorList = new List<string>();
}
}
}