InvoiceMYOBPoster.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.Poster.MYOB;
  4. using InABox.Scripting;
  5. using MYOB.AccountRight.SDK.Contracts.Version2.Sale;
  6. using MYOB.AccountRight.SDK.Services.Contact;
  7. using MYOB.AccountRight.SDK.Services.GeneralLedger;
  8. using MYOB.AccountRight.SDK.Services.Sale;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using Invoice = Comal.Classes.Invoice;
  15. using InvoiceLine = Comal.Classes.InvoiceLine;
  16. using MYOBAccount = MYOB.AccountRight.SDK.Contracts.Version2.GeneralLedger.Account;
  17. using MYOBInvoice = MYOB.AccountRight.SDK.Contracts.Version2.Sale.ServiceInvoice;
  18. using MYOBInvoiceLine = MYOB.AccountRight.SDK.Contracts.Version2.Sale.ServiceInvoiceLine;
  19. using MYOBTaxCode = MYOB.AccountRight.SDK.Contracts.Version2.GeneralLedger.TaxCode;
  20. namespace PRS.Shared.Posters.MYOB;
  21. public class InvoiceMYOBPosterSettings : MYOBPosterSettings
  22. {
  23. public override string DefaultScript(Type TPostable)
  24. {
  25. return @"using MYOBInvoice = MYOB.AccountRight.SDK.Contracts.Version2.Sale.ServiceInvoice;
  26. using MYOBInvoiceLine = MYOB.AccountRight.SDK.Contracts.Version2.Sale.ServiceInvoiceLine;
  27. public class Module
  28. {
  29. public void BeforePost(IDataModel<Invoice> model)
  30. {
  31. // Perform pre-processing
  32. }
  33. public void ProcessInvoice(IDataModel<Invoice> model, Invoice invoice, MYOBInvoice myobInvoice)
  34. {
  35. // Do extra processing for an invoice; throw an exception to fail this invoice.
  36. }
  37. public void ProcessInvoiceLine(IDataModel<Invoice> model, InvoiceLine invoiceLine, MYOBInvoiceLine myobInvoiceLine)
  38. {
  39. // Do extra processing for an invoice line; throw an exception to fail this invoice line (and thus fail the entire invoice)
  40. }
  41. }";
  42. }
  43. }
  44. public class InvoiceMYOBPoster : IMYOBPoster<Invoice, InvoiceMYOBPosterSettings>
  45. {
  46. public ScriptDocument? Script { get; set; }
  47. public MYOBConnectionData ConnectionData { get; set; }
  48. public InvoiceMYOBPosterSettings Settings { get; set; }
  49. public MYOBGlobalPosterSettings GlobalSettings { get; set; }
  50. public bool BeforePost(IDataModel<Invoice> model)
  51. {
  52. foreach (var (_, table) in model.ModelTables)
  53. {
  54. table.IsDefault = false;
  55. }
  56. model.SetIsDefault<Invoice>(true);
  57. model.SetColumns<Invoice>(RequiredInvoiceColumns());
  58. model.SetIsDefault<InvoiceLine>(true, alias: "Invoice_InvoiceLine");
  59. model.SetColumns<InvoiceLine>(RequiredInvoiceLineColumns(), alias: "Invoice_InvoiceLine");
  60. model.SetIsDefault<Customer>(true, alias: "Invoice_Customer");
  61. model.SetColumns<Customer>(RequiredCustomerColumns(), alias: "Invoice_Customer");
  62. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  63. return true;
  64. }
  65. #region Script Functions
  66. private Result<Exception> ProcessInvoice(IDataModel<Invoice> model, Invoice invoice, MYOBInvoice myobInvoice)
  67. {
  68. return this.WrapScript("ProcessInvoice", model, invoice, myobInvoice);
  69. }
  70. private Result<Exception> ProcessInvoiceLine(IDataModel<Invoice> model, InvoiceLine invoiceLine, MYOBInvoiceLine myobInvoiceLine)
  71. {
  72. return this.WrapScript("ProcessInvoiceLine", model, invoiceLine, myobInvoiceLine);
  73. }
  74. #endregion
  75. private static Columns<Invoice> RequiredInvoiceColumns()
  76. {
  77. return Columns.None<Invoice>()
  78. .Add(x => x.ID)
  79. .Add(x => x.PostedReference)
  80. .Add(x => x.Number)
  81. .Add(x => x.Date)
  82. .Add(x => x.CustomerLink.ID)
  83. .Add(x => x.Description);
  84. }
  85. private static Columns<InvoiceLine> RequiredInvoiceLineColumns()
  86. {
  87. return Columns.None<InvoiceLine>()
  88. .Add(x => x.ID)
  89. .Add(x => x.InvoiceLink.ID)
  90. .Add(x => x.Description)
  91. .Add(x => x.IncTax)
  92. .Add(x => x.SellGL.ID)
  93. .Add(x => x.SellGL.Code)
  94. .Add(x => x.SellGL.PostedReference)
  95. .Add(x => x.TaxCode.ID)
  96. .Add(x => x.TaxCode.Code)
  97. .Add(x => x.TaxCode.PostedReference);
  98. }
  99. private static Columns<Customer> RequiredCustomerColumns()
  100. {
  101. return CustomerMYOBPoster.RequiredColumns();
  102. }
  103. public IPostResult<Invoice> Process(IDataModel<Invoice> model)
  104. {
  105. // Documentation: https://developer.myob.com/api/myob-business-api/v2/sale/invoice/invoice_service/
  106. var results = new PostResult<Invoice>();
  107. var service = new ServiceInvoiceService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  108. var invoices = model.GetTable<Invoice>().ToArray<Invoice>();
  109. var customers = model.GetTable<Customer>("Invoice_Customer")
  110. .ToObjects<Customer>().ToDictionary(x => x.ID);
  111. var invoiceLines = model.GetTable<InvoiceLine>("Invoice_InvoiceLine")
  112. .ToObjects<InvoiceLine>()
  113. .GroupBy(x => x.InvoiceLink.ID)
  114. .ToDictionary(x => x.Key, x => x.ToArray());
  115. foreach(var invoice in invoices)
  116. {
  117. MYOBInvoice myobInvoice;
  118. Exception? error;
  119. if(Guid.TryParse(invoice.PostedReference, out var myobID))
  120. {
  121. if(!service.Get(ConnectionData, myobID).Get(out var newInvoice, out error))
  122. {
  123. CoreUtils.LogException("", error, $"Failed to find Invoice in MYOB with id {myobID}");
  124. results.AddFailed(invoice, $"Failed to find Invoice in MYOB with id {myobID}: {error.Message}");
  125. continue;
  126. }
  127. myobInvoice = newInvoice;
  128. }
  129. else
  130. {
  131. myobInvoice = new MYOBInvoice();
  132. }
  133. myobInvoice.Number = invoice.Number.ToString().Truncate(13);
  134. myobInvoice.Date = invoice.Date;
  135. // myobInvoice.CustomerPurchaseOrderNumber =
  136. if(customers.TryGetValue(invoice.CustomerLink.ID, out var customer))
  137. {
  138. if(!CustomerMYOBPoster.MapCustomer(ConnectionData, customer, GlobalSettings).Get(out var customerID, out error))
  139. {
  140. CoreUtils.LogException("", error, $"Error while posting invoice {invoice.ID}");
  141. results.AddFailed(invoice, error.Message);
  142. continue;
  143. }
  144. myobInvoice.Customer ??= new();
  145. myobInvoice.Customer.UID = customerID;
  146. results.AddFragment(customer, customer.PostedStatus);
  147. }
  148. // myobInvoice.PromisedDate =
  149. if(invoiceLines.TryGetValue(invoice.ID, out var lines))
  150. {
  151. var newLines = new MYOBInvoiceLine[lines.Length];
  152. string? failed = null;
  153. for(int i = 0; i < lines.Length; ++i)
  154. {
  155. var item = lines[i];
  156. var line = new MYOBInvoiceLine();
  157. line.Type = InvoiceLineType.Transaction;
  158. line.Description = item.Description.Truncate(1000);
  159. // line.UnitOfMeasure =
  160. // line.UnitCount =
  161. // line.UnitPrice =
  162. // line.UnitPriceForeign =
  163. // line.DiscountPercent =
  164. line.Total = (decimal)item.IncTax;
  165. line.TotalForeign = 0;
  166. if(item.SellGL.ID == Guid.Empty)
  167. {
  168. failed = "Not all lines have a SellGL code set.";
  169. break;
  170. }
  171. if(!Guid.TryParse(item.SellGL.PostedReference, out var accountID))
  172. {
  173. if(AccountMYOBUtils.GetAccount(ConnectionData, item.SellGL.Code).Get(out accountID, out error))
  174. {
  175. results.AddFragment(new GLCode { ID = item.SellGL.ID, PostedReference = accountID.ToString() });
  176. }
  177. else
  178. {
  179. CoreUtils.LogException("", error);
  180. failed = error.Message;
  181. break;
  182. }
  183. }
  184. line.Account ??= new();
  185. line.Account.UID = accountID;
  186. if(item.TaxCode.ID == Guid.Empty)
  187. {
  188. failed = "Not all lines have a TaxCode set.";
  189. break;
  190. }
  191. if(!Guid.TryParse(item.TaxCode.PostedReference, out var taxCodeID))
  192. {
  193. if (!ConnectionData.GetUID<TaxCodeService, MYOBTaxCode>(
  194. new Filter<MYOBTaxCode>(x => x.Code).IsEqualTo(item.TaxCode.Code))
  195. .Get(out taxCodeID, out error))
  196. {
  197. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}");
  198. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}: {error.Message}";
  199. break;
  200. }
  201. else if (taxCodeID == Guid.Empty)
  202. {
  203. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}";
  204. break;
  205. }
  206. results.AddFragment(new TaxCode { ID = taxCodeID, PostedReference = taxCodeID.ToString() });
  207. }
  208. line.TaxCode ??= new();
  209. line.TaxCode.UID = taxCodeID;
  210. if(!ProcessInvoiceLine(model, item, line).Get(out error))
  211. {
  212. failed = error.Message;
  213. break;
  214. }
  215. newLines[i] = line;
  216. }
  217. if(failed is not null)
  218. {
  219. results.AddFailed(invoice, failed);
  220. continue;
  221. }
  222. myobInvoice.Lines = newLines;
  223. }
  224. else
  225. {
  226. myobInvoice.Lines = [];
  227. }
  228. // ShipToAddress
  229. // Terms
  230. myobInvoice.IsTaxInclusive = true;
  231. // Freight
  232. // FreightTaxCode
  233. // Category
  234. // Salesperson
  235. myobInvoice.Comment = invoice.Description.Truncate(2000);
  236. // ShippingMethod
  237. // JournalMemo
  238. // ReferralSource
  239. // InvoiceDeliveryStatus
  240. // CanApplySurcharge
  241. myobInvoice.InvoiceType = InvoiceLayoutType.Service;
  242. // Order
  243. // OnlinePaymentMethod
  244. if(!ProcessInvoice(model, invoice, myobInvoice).Get(out error))
  245. {
  246. results.AddFailed(invoice, error.Message);
  247. continue;
  248. }
  249. if(service.Save(ConnectionData, myobInvoice).Get(out var result, out error))
  250. {
  251. invoice.PostedReference = result.UID.ToString();
  252. results.AddSuccess(invoice);
  253. }
  254. else
  255. {
  256. CoreUtils.LogException("", error, $"Error while posting invoice {invoice.ID}");
  257. results.AddFailed(invoice, error.Message);
  258. }
  259. }
  260. return results;
  261. }
  262. }
  263. public class InvoiceMYOBPosterEngine<T> : MYOBPosterEngine<Invoice, InvoiceMYOBPosterSettings> { }