CustomerMYOBPoster.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using Comal.Classes;
  2. using FastReport.Data;
  3. using InABox.Core;
  4. using InABox.Core.Postable;
  5. using InABox.Poster.MYOB;
  6. using MYOB.AccountRight.SDK.Services;
  7. using MYOB.AccountRight.SDK.Services.Contact;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using Customer = Comal.Classes.Customer;
  15. using MYOBCustomer = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Customer;
  16. using MYOBAddress = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Address;
  17. using MYOB.AccountRight.SDK.Contracts.Version2.Sale;
  18. using InABox.Clients;
  19. namespace PRS.Shared.Posters.MYOB;
  20. public class CustomerMYOBPosterSettings : MYOBPosterSettings
  21. {
  22. [TextBoxEditor(ToolTip = "The MYOB tax code which should be used when posting customers")]
  23. public string DefaultTaxCode { get; set; }
  24. }
  25. public class CustomerMYOBPoster : IMYOBPoster<Customer, CustomerMYOBPosterSettings>
  26. {
  27. public CustomerMYOBPosterSettings Settings { get; set; }
  28. public MYOBGlobalPosterSettings GlobalSettings { get; set; }
  29. public MYOBConnectionData ConnectionData { get; set; }
  30. private static void SplitName(string name, out string firstName, out string lastName)
  31. {
  32. var names = name.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  33. firstName = names.Length > 0 ? names[0] : "";
  34. lastName = names.Length > 1 ? names[1] : "";
  35. }
  36. private static MYOBAddress ConvertAddress(Address address, int location, IContact contact)
  37. {
  38. return new MYOBAddress
  39. {
  40. Location = location,
  41. Street = address.Street.Truncate(255),
  42. City = address.City.Truncate(255),
  43. State = address.State.Truncate(255),
  44. PostCode = address.PostCode.Truncate(11),
  45. Phone1 = contact.Mobile.Truncate(21),
  46. Phone2 = contact.Telephone.Truncate(21),
  47. Email = contact.Email.Truncate(255),
  48. ContactName = contact.Name.Truncate(25)
  49. };
  50. }
  51. public bool BeforePost(IDataModel<Customer> model)
  52. {
  53. foreach (var (_, table) in model.ModelTables)
  54. {
  55. table.IsDefault = false;
  56. }
  57. model.SetIsDefault<Customer>(true);
  58. model.SetColumns<Customer>(RequiredColumns());
  59. return true;
  60. }
  61. public static Columns<Customer> RequiredColumns()
  62. {
  63. return Columns.None<Customer>()
  64. .Add(x => x.ID)
  65. .Add(x => x.PostedReference)
  66. .Add(x => x.DefaultContact.Name)
  67. .Add(x => x.Name)
  68. .Add(x => x.Code)
  69. .Add(x => x.CustomerStatus.ID)
  70. .Add(x => x.CustomerStatus.Active)
  71. .Add(x => x.Delivery.Street)
  72. .Add(x => x.Delivery.City)
  73. .Add(x => x.Delivery.State)
  74. .Add(x => x.Delivery.PostCode)
  75. .Add(x => x.Postal.Street)
  76. .Add(x => x.Postal.City)
  77. .Add(x => x.Postal.State)
  78. .Add(x => x.Postal.PostCode)
  79. .Add(x => x.DefaultContact.Mobile)
  80. .Add(x => x.DefaultContact.Telephone)
  81. .Add(x => x.DefaultContact.Email)
  82. .Add(x => x.DefaultContact.Name)
  83. .Add(x => x.DefaultContact.Mobile)
  84. .Add(x => x.ABN);
  85. }
  86. public static Result<Exception> UpdateCustomer(MYOBConnectionData data, CustomerMYOBPosterSettings settings, Customer customer, MYOBCustomer myobCustomer, bool isNew)
  87. {
  88. // Documentation: https://developer.myob.com/api/myob-business-api/v2/contact/customer/
  89. // Since this might be called from some other poster, we need to ensure we have the right columns.
  90. Client.EnsureColumns(customer, RequiredColumns());
  91. SplitName(customer.DefaultContact.Name, out var firstName, out var lastName);
  92. myobCustomer.CompanyName = customer.Name.Truncate(50);
  93. myobCustomer.FirstName = firstName.Truncate(30);
  94. myobCustomer.LastName = lastName.Truncate(20);
  95. myobCustomer.IsIndividual = false;
  96. myobCustomer.DisplayID = customer.Code.Truncate(15);
  97. // If there is not customer status, we will use default to Active = true.
  98. myobCustomer.IsActive = customer.CustomerStatus.ID == Guid.Empty || customer.CustomerStatus.Active;
  99. myobCustomer.Addresses =
  100. [
  101. ConvertAddress(customer.Delivery, 1, customer.DefaultContact),
  102. ConvertAddress(customer.Postal, 2, customer.DefaultContact)
  103. ];
  104. // Notes =
  105. // PhotoURI =
  106. // RowVersion =
  107. myobCustomer.SellingDetails.SaleLayout = InvoiceLayoutType.NoDefault;
  108. // myobCustomer.SellingDetails.PrintedFOrm =
  109. myobCustomer.SellingDetails.InvoiceDelivery = DocumentAction.PrintAndEmail;
  110. // myobCustomer.SellingDetails.IncomeAccount =
  111. // myobCustomer.SellingDetails.ReceiptMemo =
  112. // myobCustomer.SellingDetails.SalesPerson =
  113. // myobCustomer.SellingDetails.SaleComment =
  114. // myobCustomer.SellingDetails.ShippingMethod =
  115. // myobCustomer.SellingDetails.HourlyBillRate =
  116. // myobCustomer.SellingDetails.ABNBranch =
  117. myobCustomer.SellingDetails.ABN = customer.ABN.Truncate(14);
  118. if (isNew)
  119. {
  120. if (settings.DefaultTaxCode.IsNullOrWhiteSpace())
  121. {
  122. throw new PostFailedMessageException("Default tax code has not been set up.");
  123. }
  124. else if(data.GetMYOBTaxCodeUID(settings.DefaultTaxCode).Get(out var taxID, out var error))
  125. {
  126. if (taxID == Guid.Empty)
  127. {
  128. return Result.Error(new Exception($"Failed to find TaxCode in MYOB with code {settings.DefaultTaxCode}"));
  129. }
  130. myobCustomer.SellingDetails.TaxCode.UID = taxID;
  131. myobCustomer.SellingDetails.FreightTaxCode.UID = taxID;
  132. }
  133. else
  134. {
  135. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {settings.DefaultTaxCode}");
  136. return Result.Error(new Exception($"Failed to find TaxCode in MYOB with code {settings.DefaultTaxCode}: {error.Message}", error));
  137. }
  138. }
  139. return Result.Ok();
  140. }
  141. /// <summary>
  142. /// Try to find a customer in MYOB which matches <paramref name="customer"/>, and if this fails, create a new one.
  143. /// </summary>
  144. /// <remarks>
  145. /// After this has finished, <paramref name="customer"/> will be updated with <see cref="Customer.PostedReference"/> set to the correct ID.
  146. /// <br/>
  147. /// <paramref name="customer"/> needs to have at least <see cref="Customer.Code"/> and <see cref="Customer.PostedReference"/> as loaded columns.
  148. /// </remarks>
  149. /// <param name="data"></param>
  150. /// <param name="customer">The customer to map to.</param>
  151. /// <returns>The UID of the MYOB customer.</returns>
  152. public static Result<Guid, Exception> MapCustomer(MYOBConnectionData data, Customer customer)
  153. {
  154. if(Guid.TryParse(customer.PostedReference, out var myobID))
  155. {
  156. return new Result<Guid, Exception>(myobID);
  157. }
  158. var service = new CustomerService(data.Configuration, null, data.AuthKey);
  159. var result = service.Query(data, new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(customer.Code), top: 1);
  160. return result.MapOk(customers =>
  161. {
  162. if(customers.Count == 0)
  163. {
  164. if(customer.Code.Length > 15)
  165. {
  166. return Result.Error(new Exception("Customer code is longer than 15 characters"));
  167. }
  168. var myobCustomer = new MYOBCustomer();
  169. return UpdateCustomer(data, PosterUtils.LoadPosterSettings<Customer, CustomerMYOBPosterSettings>(), customer, myobCustomer, true)
  170. .MapOk<Result<Guid, Exception>>(() =>
  171. {
  172. try
  173. {
  174. var result = service.UpdateEx(data.CompanyFile, myobCustomer, data.CompanyFileCredentials);
  175. customer.PostedReference = result.UID.ToString();
  176. return Result.Ok(result.UID);
  177. }
  178. catch (Exception e)
  179. {
  180. CoreUtils.LogException("", e, $"Error while posting customer {customer.ID}");
  181. return Result.Error(e);
  182. }
  183. }).Flatten();
  184. }
  185. else
  186. {
  187. customer.PostedReference = customers.Items[0].UID.ToString();
  188. return Result.Ok(customers.Items[0].UID);
  189. }
  190. }).Flatten();
  191. }
  192. public IPostResult<Customer> Process(IDataModel<Customer> model)
  193. {
  194. var results = new PostResult<Customer>();
  195. var service = new CustomerService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  196. var customers = model.GetTable<Customer>().ToArray<Customer>();
  197. foreach(var customer in customers)
  198. {
  199. if(customer.Code.Length > 15)
  200. {
  201. results.AddFailed(customer, "Code is longer than 15 characters.");
  202. continue;
  203. }
  204. bool isNew;
  205. MYOBCustomer myobCustomer;
  206. Exception? error;
  207. if(Guid.TryParse(customer.PostedReference, out var myobID))
  208. {
  209. if(!service.Get(ConnectionData, myobID).Get(out var newCustomer, out error))
  210. {
  211. CoreUtils.LogException("", error, $"Failed to find Customer in MYOB with id {myobID}");
  212. results.AddFailed(customer, $"Failed to find Customer in MYOB with id {myobID}: {error.Message}");
  213. continue;
  214. }
  215. myobCustomer = newCustomer;
  216. isNew = false;
  217. }
  218. else
  219. {
  220. myobCustomer = new MYOBCustomer();
  221. isNew = true;
  222. }
  223. if(UpdateCustomer(ConnectionData, Settings, customer, myobCustomer, isNew).Get(out error))
  224. {
  225. try
  226. {
  227. var result = service.Update(ConnectionData.CompanyFile, myobCustomer, ConnectionData.CompanyFileCredentials);
  228. results.AddSuccess(customer);
  229. }
  230. catch(Exception e)
  231. {
  232. CoreUtils.LogException("", e, $"Error while posting customer {customer.ID}");
  233. results.AddFailed(customer, e.Message);
  234. }
  235. }
  236. else
  237. {
  238. results.AddFailed(customer, error.Message);
  239. }
  240. }
  241. return results;
  242. }
  243. }
  244. public class CustomerMYOBPosterEngine<T> : MYOBPosterEngine<Customer, CustomerMYOBPosterSettings> { }