InvoiceMYOBPoster.cs 9.3 KB

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