InvoiceMYOBPoster.cs 12 KB

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