using Comal.Classes; using InABox.Core; using InABox.Core.Postable; using InABox.Poster.MYOB; using InABox.Scripting; using MYOB.AccountRight.SDK.Contracts.Version2.Sale; using MYOB.AccountRight.SDK.Services.GeneralLedger; using MYOB.AccountRight.SDK.Services.Purchase; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MYOBBill = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBill; using MYOBBillLine = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBillLine; using MYOBTaxCode = MYOB.AccountRight.SDK.Contracts.Version2.GeneralLedger.TaxCode; namespace PRS.Shared.Posters.MYOB; public class BillMYOBPosterSettings : MYOBPosterSettings { public override string DefaultScript(Type TPostable) { return @"using MYOBBill = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBill; using MYOBBillLine = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBillLine; public class Module { public void BeforePost(IDataModel model) { // Perform pre-processing } public void ProcessBill(IDataModel model, Bill bill, MYOBBill myobBill) { // Do extra processing for a bill; throw an exception to fail this bill. } public void ProcessBillLine(IDataModel model, BillLine billLine, MYOBBillLine myobBillLine) { // Do extra processing for a bill line; throw an exception to fail this bill line (and thus fail the entire bill) } }"; } } public class BillMYOBPoster : IMYOBPoster { public ScriptDocument? Script { get; set; } public MYOBConnectionData ConnectionData { get; set; } public BillMYOBPosterSettings Settings { get; set; } public MYOBGlobalPosterSettings GlobalSettings { get; set; } public bool BeforePost(IDataModel model) { foreach(var (_, table) in model.ModelTables) { table.IsDefault = false; } model.SetIsDefault(true); model.SetColumns(RequiredBillColumns()); model.SetIsDefault(true, alias: "Bill_BillLine"); model.SetColumns(RequiredBillLineColumns(), alias: "Bill_BillLine"); model.SetIsDefault(true, alias: "Bill_Supplier"); model.SetColumns(RequiredSupplierColumns(), alias: "Bill_Supplier"); Script?.Execute(methodname: "BeforePost", parameters: new object[] { model }); return true; } #region Script Functions private Result ProcessBill(IDataModel model, Bill bill, MYOBBill myobBill) { return this.WrapScript("ProcessBill", model, bill, myobBill); } private Result ProcessBillLine(IDataModel model, BillLine billLine, MYOBBillLine myobBillLine) { return this.WrapScript("ProcessBillLine", model, billLine, myobBillLine); } #endregion private static Columns RequiredBillColumns() { return Columns.None() .Add(x => x.ID) .Add(x => x.Approved) .Add(x => x.PostedReference) .Add(x => x.Number) .Add(x => x.AccountingDate) .Add(x => x.SupplierLink.ID) .Add(x => x.Description); } private static Columns RequiredBillLineColumns() { return Columns.None() .Add(x => x.ID) .Add(x => x.BillLink.ID) .Add(x => x.Description) .Add(x => x.IncTax) .Add(x => x.PurchaseGL.ID) .Add(x => x.PurchaseGL.Code) .Add(x => x.PurchaseGL.PostedReference) .Add(x => x.TaxCode.ID) .Add(x => x.TaxCode.Code) .Add(x => x.TaxCode.PostedReference); } private static Columns RequiredSupplierColumns() { return SupplierMYOBPoster.RequiredColumns(); } public IPostResult Process(IDataModel model) { // https://developer.myob.com/api/myob-business-api/v2/purchase/bill/bill_service/ var results = new PostResult(); var service = new ServiceBillService(ConnectionData.Configuration, null, ConnectionData.AuthKey); var bills = model.GetTable().ToArray(); if(bills.Any(x => x.Approved.IsEmpty())) { throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing."); } var suppliers = model.GetTable("Bill_Supplier") .ToObjects().ToDictionary(x => x.ID); var billLines = model.GetTable("Bill_BillLine") .ToObjects().GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToArray()); foreach(var bill in bills) { MYOBBill myobBill; Exception? error; bool isNew; if(Guid.TryParse(bill.PostedReference, out var myobID)) { if(!service.Get(ConnectionData, myobID).Get(out var newBill, out error)) { CoreUtils.LogException("", error, $"Failed to find Bill in MYOB with id {myobID}"); results.AddFailed(bill, $"Failed to find Bill in MYOB with id {myobID}: {error.Message}"); continue; } myobBill = newBill; isNew = false; } else { myobBill = new MYOBBill(); isNew = true; } myobBill.Number = bill.Number.Truncate(13); // Probably configure which date. myobBill.Date = bill.AccountingDate; myobBill.SupplierInvoiceNumber = bill.Number.Truncate(255); if(suppliers.TryGetValue(bill.SupplierLink.ID, out var supplier)) { if(!SupplierMYOBPoster.MapSupplier(ConnectionData, supplier, GlobalSettings).Get(out var supplierID, out error)) { CoreUtils.LogException("", error, $"Error while posting bill {bill.ID}"); results.AddFailed(bill, error.Message); continue; } myobBill.Supplier ??= new(); myobBill.Supplier.UID = supplierID; results.AddFragment(supplier, supplier.PostedStatus); } // myobBill.ShipToAddress = // myobBill.Terms = myobBill.IsTaxInclusive = true; myobBill.IsReportable = true; // myobBill.Freight = // myobBill.FreightForeign = if (isNew) { if(!this.GetDefaultTaxCode().Get(out var taxCodeID, out error)) { results.AddFailed(bill, error.Message); continue; } myobBill.FreightTaxCode ??= new(); myobBill.FreightTaxCode.UID = taxCodeID; } // myobBill.Category = myobBill.Comment = bill.Description.Truncate(2000); // myobBill.ShippingMethod = // myobBill.PromisedDate = // myobBill.JournalMemo = // myobBill.BillDeliveryStatus = // myobBill.Order = if(billLines.TryGetValue(bill.ID, out var lines)) { var newLines = new MYOBBillLine[lines.Length]; string? failed = null; for(int i = 0; i < lines.Length; ++i) { var billLine = lines[i]; var line = new MYOBBillLine(); line.Type = InvoiceLineType.Transaction; line.Description = billLine.Description.Truncate(1000); if(billLine.PurchaseGL.ID == Guid.Empty) { failed = "Not all lines have a PurchaseGL code set."; break; } if(!Guid.TryParse(billLine.PurchaseGL.PostedReference, out var accountID)) { if(AccountMYOBUtils.GetAccount(ConnectionData, billLine.PurchaseGL.Code).Get(out accountID, out error)) { results.AddFragment(new GLCode { ID = billLine.PurchaseGL.ID, PostedReference = accountID.ToString() }); } else { CoreUtils.LogException("", error); failed = error.Message; break; } } line.Account ??= new(); line.Account.UID = accountID; line.Total = (decimal)billLine.IncTax; line.TotalForeign = 0; // line.UnitsOfMeasure = // line.UnitCount = // line.UnitPrice = // line.UnitPriceForeign = // line.DiscountPercent = // line.Job = if(billLine.TaxCode.ID == Guid.Empty) { failed = "Not all lines have a TaxCode set."; break; } if(!Guid.TryParse(billLine.TaxCode.PostedReference, out var taxCodeID)) { if (!ConnectionData.GetUID( new Filter(x => x.Code).IsEqualTo(billLine.TaxCode.Code)) .Get(out taxCodeID, out error)) { CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}"); failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}: {error.Message}"; break; } else if (taxCodeID == Guid.Empty) { failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}"; break; } results.AddFragment(new TaxCode { ID = taxCodeID, PostedReference = taxCodeID.ToString() }); } line.TaxCode ??= new(); line.TaxCode.UID = taxCodeID; if(!ProcessBillLine(model, billLine, line).Get(out error)) { failed = error.Message; break; } newLines[i] = line; } if(failed is not null) { results.AddFailed(bill, failed); continue; } myobBill.Lines = newLines; } else { myobBill.Lines = []; } if(!ProcessBill(model, bill, myobBill).Get(out error)) { results.AddFailed(bill, error.Message); continue; } if(service.Save(ConnectionData, myobBill).Get(out var result, out error)) { bill.PostedReference = result.UID.ToString(); results.AddSuccess(bill); } else { CoreUtils.LogException("", error, $"Error while posting purchase order {bill.ID}"); results.AddFailed(bill, error.Message); } } return results; } } public class BillMYOBPosterEngine : MYOBPosterEngine { }