InvoiceMYOBPoster.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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.SetIsDefault<InvoiceLine>(true, alias: "Invoice_InvoiceLine");
  36. model.SetIsDefault<Customer>(true, alias: "Invoice_Customer");
  37. return true;
  38. }
  39. public IPostResult<Invoice> Process(IDataModel<Invoice> model)
  40. {
  41. // Documentation: https://developer.myob.com/api/myob-business-api/v2/sale/invoice/invoice_service/
  42. var results = new PostResult<Invoice>();
  43. var service = new ServiceInvoiceService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  44. var invoices = model.GetTable<Invoice>().ToArray<Invoice>();
  45. var customers = model.GetTable<Customer>("Invoice_Customer")
  46. .ToObjects<Customer>().ToDictionary(x => x.ID);
  47. var invoiceLines = model.GetTable<InvoiceLine>("Invoice_InvoiceLine")
  48. .ToObjects<InvoiceLine>()
  49. .GroupBy(x => x.InvoiceLink.ID)
  50. .ToDictionary(x => x.Key, x => x.ToArray());
  51. foreach(var invoice in invoices)
  52. {
  53. MYOBInvoice myobInvoice;
  54. if(Guid.TryParse(invoice.PostedReference, out var myobID))
  55. {
  56. if(!service.Get(ConnectionData, myobID).Get(out var newInvoice, out var error))
  57. {
  58. CoreUtils.LogException("", error, $"Failed to find Invoice in MYOB with id {myobID}");
  59. results.AddFailed(invoice, $"Failed to find Invoice in MYOB with id {myobID}: {error.Message}");
  60. continue;
  61. }
  62. myobInvoice = newInvoice;
  63. }
  64. else
  65. {
  66. myobInvoice = new MYOBInvoice();
  67. }
  68. myobInvoice.Number = invoice.Number.ToString().Truncate(13);
  69. myobInvoice.Date = invoice.Date;
  70. // myobInvoice.CustomerPurchaseOrderNumber =
  71. if(customers.TryGetValue(invoice.CustomerLink.ID, out var customer))
  72. {
  73. if(!CustomerMYOBPoster.MapCustomer(ConnectionData, customer).Get(out var customerID, out var error))
  74. {
  75. CoreUtils.LogException("", error, $"Error while posting invoice {invoice.ID}");
  76. results.AddFailed(invoice, error.Message);
  77. continue;
  78. }
  79. myobInvoice.Customer.UID = customerID;
  80. }
  81. // myobInvoice.PromisedDate =
  82. myobInvoice.BalanceDueAmount = (decimal)invoice.Balance;
  83. // BalanceDueAmountForeign
  84. // Status
  85. if(invoiceLines.TryGetValue(invoice.ID, out var lines))
  86. {
  87. var newLines = new MYOBInvoiceLine[lines.Length];
  88. string? failed = null;
  89. for(int i = 0; i < lines.Length; ++i)
  90. {
  91. var item = lines[i];
  92. var line = new MYOBInvoiceLine();
  93. line.Type = InvoiceLineType.Transaction;
  94. line.Description = item.Description;
  95. // line.UnitOfMeasure =
  96. // line.UnitCount =
  97. // line.UnitPrice =
  98. // line.UnitPriceForeign =
  99. // line.DiscountPercent =
  100. line.Total = (decimal)item.IncTax;
  101. line.TotalForeign = 0;
  102. if(item.SellGL.ID == Guid.Empty)
  103. {
  104. failed = "Not all lines have a SellGL code set.";
  105. break;
  106. }
  107. if(!Guid.TryParse(item.SellGL.PostedReference, out var accountID))
  108. {
  109. if (!ConnectionData.GetUID<AccountService, MYOBAccount>(
  110. new Filter<MYOBAccount>(x => x.DisplayID).IsEqualTo(item.SellGL.Code))
  111. .Get(out accountID, out var error))
  112. {
  113. CoreUtils.LogException("", error, $"Failed to find Account in MYOB with code {item.SellGL.Code}");
  114. failed = $"Failed to find Account in MYOB with code {item.SellGL.Code}: {error.Message}";
  115. break;
  116. }
  117. else if (accountID == Guid.Empty)
  118. {
  119. failed = $"Failed to find Account in MYOB with code {item.SellGL.Code}";
  120. break;
  121. }
  122. else
  123. {
  124. results.AddFragment(new GLCode { ID = item.SellGL.ID, PostedReference = accountID.ToString() });
  125. }
  126. }
  127. line.Account.UID = accountID;
  128. if(item.TaxCode.ID == Guid.Empty)
  129. {
  130. failed = "Not all lines have a TaxCode set.";
  131. break;
  132. }
  133. if(!Guid.TryParse(item.TaxCode.PostedReference, out var taxCodeID))
  134. {
  135. if (!ConnectionData.GetUID<TaxCodeService, MYOBTaxCode>(
  136. new Filter<MYOBTaxCode>(x => x.Code).IsEqualTo(item.TaxCode.Code))
  137. .Get(out taxCodeID, out var error))
  138. {
  139. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}");
  140. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}: {error.Message}";
  141. break;
  142. }
  143. else if (taxCodeID == Guid.Empty)
  144. {
  145. failed = $"Failed to find TaxCode in MYOB with code {item.TaxCode.Code}";
  146. break;
  147. }
  148. results.AddFragment(new TaxCode { ID = taxCodeID, PostedReference = taxCodeID.ToString() });
  149. }
  150. line.TaxCode.UID = taxCodeID;
  151. newLines[i] = line;
  152. }
  153. if(failed is not null)
  154. {
  155. results.AddFailed(invoice, failed);
  156. continue;
  157. }
  158. myobInvoice.Lines = newLines;
  159. }
  160. else
  161. {
  162. myobInvoice.Lines = [];
  163. }
  164. // ShipToAddress
  165. // Terms
  166. myobInvoice.IsTaxInclusive = true;
  167. // Freight
  168. // FreightTaxCode
  169. // Category
  170. // Salesperson
  171. myobInvoice.Comment = invoice.Description;
  172. // ShippingMethod
  173. // JournalMemo
  174. // ReferralSource
  175. // InvoiceDeliveryStatus
  176. // CanApplySurcharge
  177. myobInvoice.InvoiceType = InvoiceLayoutType.Service;
  178. // Order
  179. // OnlinePaymentMethod
  180. try
  181. {
  182. var result = service.Update(ConnectionData.CompanyFile, myobInvoice, ConnectionData.CompanyFileCredentials);
  183. results.AddSuccess(invoice);
  184. }
  185. catch (Exception e)
  186. {
  187. CoreUtils.LogException("", e, $"Error while posting invoice {invoice.ID}");
  188. results.AddFailed(invoice, e.Message);
  189. }
  190. }
  191. return results;
  192. }
  193. }
  194. public class InvoiceMYOBPosterEngine<T> : MYOBPosterEngine<Invoice, InvoiceMYOBPosterSettings> { }