mirror of
https://github.com/stokebob/BealeEngineering.git
synced 2026-03-21 07:37:16 +00:00
81 lines
2.9 KiB
C#
81 lines
2.9 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace BealeEngineering.Core.Logic.Import
|
|
{
|
|
public class XeroInvoiceFlatFile
|
|
{
|
|
private string sqlConnectionString;
|
|
|
|
public XeroInvoiceFlatFile(string sqlConnectionString)
|
|
{
|
|
this.sqlConnectionString = sqlConnectionString;
|
|
}
|
|
|
|
private List<Model.Import.XeroInvoiceFlatFile> XeroInvoiceData { get; set; }
|
|
|
|
public int InvoicesCreated { get; private set; } = 0;
|
|
|
|
public int InvoicesUpdated { get; private set; } = 0;
|
|
|
|
public int InvoicesProcessed { get; private set; } = 0;
|
|
|
|
|
|
public void ByFilePath(string filePath, bool updateContacts = true)
|
|
{
|
|
// get xero data
|
|
var data = new Data.Xero.FlatFile.ReadXeroInvoiceFlatFile();
|
|
XeroInvoiceData = data.ByFilePath(filePath);
|
|
|
|
// update db contacts
|
|
UpdateContacts();
|
|
|
|
// populate/map xero data to invoice model list
|
|
var dbInvoiceData = new Logic.Adapter.SaleInvoice().XeroInvoiceFlatFile(XeroInvoiceData);
|
|
|
|
//check
|
|
if (dbInvoiceData == null ||( XeroInvoiceData.Count != dbInvoiceData.Count))
|
|
{
|
|
throw new Exception("Something went wrong while mapping the data.");
|
|
}
|
|
|
|
// send list to database (it will get validated in data layer)
|
|
if (dbInvoiceData.Any())
|
|
{
|
|
var updateInvoice = new Data.Database.Sale.UpdateInvoice(sqlConnectionString);
|
|
updateInvoice.ByInvoiceList(dbInvoiceData);
|
|
|
|
InvoicesCreated = updateInvoice.RecordsCreated;
|
|
InvoicesUpdated = updateInvoice.RecordsUpdated;
|
|
InvoicesProcessed = updateInvoice.InvoicesProcessed;
|
|
|
|
if (InvoicesProcessed != (InvoicesCreated + InvoicesUpdated))
|
|
{ throw new Exception("Error importing invoices"); }
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Get a dictionary of contacts, referenced by unique 'Contact Name'. Any contacts not found in db are
|
|
/// automatically added.
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
private void UpdateContacts()
|
|
{
|
|
var contactAdapter = new Logic.Adapter.Contact();
|
|
var dicContacts = new Dictionary<string, Model.Contact.Contact>();
|
|
for (var i = 0; i < XeroInvoiceData.Count; i++)
|
|
{
|
|
if (!dicContacts.ContainsKey(XeroInvoiceData[0].ContactName))
|
|
{
|
|
dicContacts.Add(XeroInvoiceData[0].ContactName, contactAdapter.XeroInvoiceFlatFile(XeroInvoiceData[0]));
|
|
}
|
|
}
|
|
if (dicContacts.Any())
|
|
{
|
|
var updateContact = new Data.Database.Contact.UpdateContact(sqlConnectionString);
|
|
updateContact.ByContactList(dicContacts.Values.ToList());
|
|
}
|
|
}
|
|
}
|
|
}
|