InvoiceMYOBPoster.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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());
  38. model.SetIsDefault<Customer>(true, alias: "Invoice_Customer");
  39. model.SetColumns<Customer>(RequiredCustomerColumns());
  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;
  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 (!ConnectionData.GetUID<AccountService, MYOBAccount>(
  138. new Filter<MYOBAccount>(x => x.DisplayID).IsEqualTo(item.SellGL.Code))
  139. .Get(out accountID, out var error))
  140. {
  141. CoreUtils.LogException("", error, $"Failed to find Account in MYOB with code {item.SellGL.Code}");
  142. failed = $"Failed to find Account in MYOB with code {item.SellGL.Code}: {error.Message}";
  143. break;
  144. }
  145. else if (accountID == Guid.Empty)
  146. {
  147. failed = $"Failed to find Account in MYOB with code {item.SellGL.Code}";
  148. break;
  149. }
  150. else
  151. {
  152. results.AddFragment(new GLCode { ID = item.SellGL.ID, PostedReference = accountID.ToString() });
  153. }
  154. }
  155. line.Account.UID = accountID;
  156. if(item.TaxCode.ID == Guid.Empty)
  157. {
  158. failed = "Not all lines have a TaxCode set.";
  159. break;
  160. }
  161. if(!Guid.TryParse(item.TaxCode.PostedReference, out var taxCodeID))
  162. {
  163. if (!ConnectionData.GetUID<TaxCodeService, MYOBTaxCode>(
  164. new Filter<MYOBTaxCode>(x => x.Code).IsEqualTo(item.TaxCode.Code))
  165. .Get(out taxCodeID, out var error))
  166. {
  167. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}");
  168. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}: {error.Message}";
  169. break;
  170. }
  171. else if (taxCodeID == Guid.Empty)
  172. {
  173. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}";
  174. break;
  175. }
  176. results.AddFragment(new TaxCode { ID = taxCodeID, PostedReference = taxCodeID.ToString() });
  177. }
  178. line.TaxCode.UID = taxCodeID;
  179. newLines[i] = line;
  180. }
  181. if(failed is not null)
  182. {
  183. results.AddFailed(invoice, failed);
  184. continue;
  185. }
  186. myobInvoice.Lines = newLines;
  187. }
  188. else
  189. {
  190. myobInvoice.Lines = [];
  191. }
  192. // ShipToAddress
  193. // Terms
  194. myobInvoice.IsTaxInclusive = true;
  195. // Freight
  196. // FreightTaxCode
  197. // Category
  198. // Salesperson
  199. myobInvoice.Comment = invoice.Description;
  200. // ShippingMethod
  201. // JournalMemo
  202. // ReferralSource
  203. // InvoiceDeliveryStatus
  204. // CanApplySurcharge
  205. myobInvoice.InvoiceType = InvoiceLayoutType.Service;
  206. // Order
  207. // OnlinePaymentMethod
  208. try
  209. {
  210. var result = service.Update(ConnectionData.CompanyFile, myobInvoice, ConnectionData.CompanyFileCredentials);
  211. results.AddSuccess(invoice);
  212. }
  213. catch (Exception e)
  214. {
  215. CoreUtils.LogException("", e, $"Error while posting invoice {invoice.ID}");
  216. results.AddFailed(invoice, e.Message);
  217. }
  218. }
  219. return results;
  220. }
  221. }
  222. public class InvoiceMYOBPosterEngine<T> : MYOBPosterEngine<Invoice, InvoiceMYOBPosterSettings> { }