CustomerMYOBPoster.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. using InABox.Database;
  20. using MYOB.AccountRight.SDK;
  21. using InABox.Scripting;
  22. namespace PRS.Shared.Posters.MYOB;
  23. public class CustomerMYOBPosterSettings : MYOBPosterSettings
  24. {
  25. public override string DefaultScript(Type TPostable)
  26. {
  27. return @"using MYOBCustomer = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Customer;
  28. public class Module
  29. {
  30. public void BeforePost(IDataModel<Customer> model)
  31. {
  32. // Perform pre-processing
  33. }
  34. public void ProcessCustomer(IDataModel<Customer> model, Customer customer, MYOBCustomer myobCustomer)
  35. {
  36. // Do extra processing for a customer; throw an exception to fail this customer.
  37. }
  38. }";
  39. }
  40. }
  41. public static class ContactMYOBUtils
  42. {
  43. public static void SplitName(string name, out string firstName, out string lastName)
  44. {
  45. var names = name.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  46. firstName = names.Length > 0 ? names[0] : "";
  47. lastName = names.Length > 1 ? names[1] : "";
  48. }
  49. public static MYOBAddress ConvertAddress(Address address, int location, IContact contact)
  50. {
  51. var mobile = contact.Mobile.Truncate(21);
  52. var phone = contact.Telephone.Truncate(21);
  53. var newAddress = new MYOBAddress
  54. {
  55. Location = location,
  56. Street = address.Street.Truncate(255),
  57. City = address.City.Truncate(255),
  58. State = address.State.Truncate(255),
  59. PostCode = address.PostCode.Truncate(11),
  60. Email = contact.Email.Truncate(255),
  61. ContactName = contact.Name.Truncate(25)
  62. };
  63. if (mobile.IsNullOrWhiteSpace())
  64. {
  65. newAddress.Phone1 = phone;
  66. }
  67. else
  68. {
  69. newAddress.Phone1 = mobile;
  70. newAddress.Phone2 = phone;
  71. }
  72. return newAddress;
  73. }
  74. }
  75. public class CustomerMYOBAutoRefresher : IAutoRefresher<Customer>
  76. {
  77. public bool ShouldRepost(Customer customer)
  78. {
  79. var shouldRepost = customer.HasOriginalValue(x => x.Name)
  80. || customer.HasOriginalValue(x => x.Code)
  81. || customer.HasOriginalValue(x => x.ABN)
  82. || customer.DefaultContact.HasOriginalValue(x => x.ID)
  83. || customer.Delivery.HasOriginalValue(x => x.Street)
  84. || customer.Delivery.HasOriginalValue(x => x.City)
  85. || customer.Delivery.HasOriginalValue(x => x.State)
  86. || customer.Delivery.HasOriginalValue(x => x.PostCode)
  87. || customer.Postal.HasOriginalValue(x => x.Street)
  88. || customer.Postal.HasOriginalValue(x => x.City)
  89. || customer.Postal.HasOriginalValue(x => x.State)
  90. || customer.Postal.HasOriginalValue(x => x.PostCode);
  91. if (shouldRepost)
  92. {
  93. return true;
  94. }
  95. if(customer.CustomerStatus.HasOriginalValue(x => x.ID))
  96. {
  97. var originalID = customer.CustomerStatus.GetOriginalValue(x => x.ID);
  98. var currentID = customer.CustomerStatus.ID;
  99. var statuses = DbFactory.Provider.Query<CustomerStatus>(
  100. new Filter<CustomerStatus>(x => x.ID).IsEqualTo(originalID).Or(x => x.ID).IsEqualTo(currentID),
  101. Columns.None<CustomerStatus>().Add(x => x.ID).Add(x => x.Active))
  102. .ToArray<CustomerStatus>();
  103. if (statuses.Length == 2 && statuses[0].Active != statuses[1].Active)
  104. {
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. }
  111. public class CustomerMYOBPoster : IMYOBPoster<Customer, CustomerMYOBPosterSettings>, IAutoRefreshPoster<Customer, CustomerMYOBAutoRefresher>
  112. {
  113. public ScriptDocument? Script { get; set; }
  114. public CustomerMYOBPosterSettings Settings { get; set; }
  115. public MYOBGlobalPosterSettings GlobalSettings { get; set; }
  116. public MYOBConnectionData ConnectionData { get; set; }
  117. public bool BeforePost(IDataModel<Customer> model)
  118. {
  119. foreach (var (_, table) in model.ModelTables)
  120. {
  121. table.IsDefault = false;
  122. }
  123. model.SetIsDefault<Customer>(true);
  124. model.SetColumns<Customer>(RequiredColumns());
  125. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  126. return true;
  127. }
  128. public static Columns<Customer> RequiredColumns()
  129. {
  130. return Columns.None<Customer>()
  131. .Add(x => x.ID)
  132. .Add(x => x.PostedReference)
  133. .Add(x => x.PostedStatus)
  134. .Add(x => x.DefaultContact.Name)
  135. .Add(x => x.Name)
  136. .Add(x => x.Code)
  137. .Add(x => x.CustomerStatus.ID)
  138. .Add(x => x.CustomerStatus.Active)
  139. .Add(x => x.Delivery.Street)
  140. .Add(x => x.Delivery.City)
  141. .Add(x => x.Delivery.State)
  142. .Add(x => x.Delivery.PostCode)
  143. .Add(x => x.Postal.Street)
  144. .Add(x => x.Postal.City)
  145. .Add(x => x.Postal.State)
  146. .Add(x => x.Postal.PostCode)
  147. .Add(x => x.DefaultContact.Mobile)
  148. .Add(x => x.DefaultContact.Telephone)
  149. .Add(x => x.DefaultContact.Email)
  150. .Add(x => x.DefaultContact.Name)
  151. .Add(x => x.DefaultContact.Mobile)
  152. .Add(x => x.ABN);
  153. }
  154. #region Script Functions
  155. private Result<Exception> ProcessCustomer(IDataModel<Customer> model, Customer customer, MYOBCustomer myobCustomer)
  156. {
  157. return this.WrapScript("ProcessCustomer", model, customer, myobCustomer);
  158. }
  159. #endregion
  160. public static Result<Exception> UpdateCustomer(MYOBConnectionData data, MYOBGlobalPosterSettings settings, Customer customer, MYOBCustomer myobCustomer, bool isNew)
  161. {
  162. // Documentation: https://developer.myob.com/api/myob-business-api/v2/contact/customer/
  163. // Since this might be called from some other poster, we need to ensure we have the right columns.
  164. Client.EnsureColumns(customer, RequiredColumns());
  165. ContactMYOBUtils.SplitName(customer.DefaultContact.Name, out var firstName, out var lastName);
  166. myobCustomer.CompanyName = customer.Name.Truncate(50);
  167. myobCustomer.FirstName = firstName.Truncate(30);
  168. myobCustomer.LastName = lastName.Truncate(20);
  169. myobCustomer.IsIndividual = false;
  170. myobCustomer.DisplayID = customer.Code.Truncate(15);
  171. // If there is not customer status, we will use default to Active = true.
  172. myobCustomer.IsActive = customer.CustomerStatus.ID == Guid.Empty || customer.CustomerStatus.Active;
  173. myobCustomer.Addresses =
  174. [
  175. ContactMYOBUtils.ConvertAddress(customer.Postal, 2, customer.DefaultContact),
  176. ContactMYOBUtils.ConvertAddress(customer.Delivery, 1, customer.DefaultContact)
  177. ];
  178. // Notes =
  179. // PhotoURI =
  180. // RowVersion =
  181. myobCustomer.SellingDetails ??= new();
  182. myobCustomer.SellingDetails.SaleLayout = InvoiceLayoutType.NoDefault;
  183. // myobCustomer.SellingDetails.PrintedFOrm =
  184. myobCustomer.SellingDetails.InvoiceDelivery = DocumentAction.PrintAndEmail;
  185. // myobCustomer.SellingDetails.IncomeAccount =
  186. // myobCustomer.SellingDetails.ReceiptMemo =
  187. // myobCustomer.SellingDetails.SalesPerson =
  188. // myobCustomer.SellingDetails.SaleComment =
  189. // myobCustomer.SellingDetails.ShippingMethod =
  190. // myobCustomer.SellingDetails.HourlyBillRate =
  191. // myobCustomer.SellingDetails.ABNBranch =
  192. myobCustomer.SellingDetails.ABN = customer.ABN.Truncate(14);
  193. if (isNew)
  194. {
  195. if(!MYOBPosterUtils.GetDefaultTaxCode(data, settings).Get(out var taxID, out var error))
  196. {
  197. return Result.Error(error);
  198. }
  199. myobCustomer.SellingDetails.TaxCode ??= new();
  200. myobCustomer.SellingDetails.TaxCode.UID = taxID;
  201. myobCustomer.SellingDetails.FreightTaxCode ??= new();
  202. myobCustomer.SellingDetails.FreightTaxCode.UID = taxID;
  203. }
  204. return Result.Ok();
  205. }
  206. /// <summary>
  207. /// Try to find a customer in MYOB which matches <paramref name="customer"/>, and if this fails, create a new one.
  208. /// </summary>
  209. /// <remarks>
  210. /// After this has finished, <paramref name="customer"/> will be updated with <see cref="Customer.PostedReference"/> set to the correct ID.
  211. /// <br/>
  212. /// <paramref name="customer"/> needs to have at least <see cref="Customer.Code"/> and <see cref="Customer.PostedReference"/> as loaded columns.
  213. /// </remarks>
  214. /// <param name="data"></param>
  215. /// <param name="customer">The customer to map to.</param>
  216. /// <returns>The UID of the MYOB customer.</returns>
  217. public static Result<Guid, Exception> MapCustomer(MYOBConnectionData data, Customer customer, MYOBGlobalPosterSettings settings)
  218. {
  219. if(Guid.TryParse(customer.PostedReference, out var myobID))
  220. {
  221. return new Result<Guid, Exception>(myobID);
  222. }
  223. var service = new CustomerService(data.Configuration, null, data.AuthKey);
  224. var result = service.Query(data, new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(customer.Code), top: 1);
  225. return result.MapOk(customers =>
  226. {
  227. if(customers.Items.Length == 0)
  228. {
  229. if(customer.Code.Length > 15)
  230. {
  231. return Result.Error(new Exception("Customer code is longer than 15 characters"));
  232. }
  233. var myobCustomer = new MYOBCustomer();
  234. return UpdateCustomer(data, settings, customer, myobCustomer, true)
  235. .MapOk(() => service.Save(data, myobCustomer)
  236. .MapOk(x =>
  237. {
  238. // Marking as repost because a script may not have run.
  239. customer.PostedStatus = PostedStatus.RequiresRepost;
  240. customer.PostedReference = x.UID.ToString();
  241. return x.UID;
  242. }))
  243. .Flatten();
  244. }
  245. else
  246. {
  247. customer.PostedReference = customers.Items[0].UID.ToString();
  248. customer.PostedStatus = PostedStatus.RequiresRepost;
  249. return Result.Ok(customers.Items[0].UID);
  250. }
  251. }).Flatten();
  252. }
  253. public IPostResult<Customer> Process(IDataModel<Customer> model)
  254. {
  255. var results = new PostResult<Customer>();
  256. var service = new CustomerService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  257. var customers = model.GetTable<Customer>().ToArray<Customer>();
  258. foreach(var customer in customers)
  259. {
  260. if(customer.Code.Length > 15)
  261. {
  262. results.AddFailed(customer, "Code is longer than 15 characters.");
  263. continue;
  264. }
  265. bool isNew;
  266. MYOBCustomer myobCustomer;
  267. Exception? error;
  268. if(Guid.TryParse(customer.PostedReference, out var myobID))
  269. {
  270. if(!service.Get(ConnectionData, myobID).Get(out var newCustomer, out error))
  271. {
  272. CoreUtils.LogException("", error, $"Failed to find Customer in MYOB with id {myobID}");
  273. results.AddFailed(customer, $"Failed to find Customer in MYOB with id {myobID}: {error.Message}");
  274. continue;
  275. }
  276. myobCustomer = newCustomer;
  277. isNew = false;
  278. }
  279. else
  280. {
  281. if(service.Query(
  282. ConnectionData,
  283. new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(customer.Code),
  284. top: 1).Get(out var myobCustomers, out error))
  285. {
  286. if(myobCustomers.Items.Length > 0)
  287. {
  288. myobCustomer = myobCustomers.Items[0];
  289. isNew = false;
  290. }
  291. else
  292. {
  293. myobCustomer = new MYOBCustomer();
  294. isNew = true;
  295. }
  296. }
  297. else
  298. {
  299. CoreUtils.LogException("", error);
  300. results.AddFailed(customer, error.Message);
  301. continue;
  302. }
  303. }
  304. if(UpdateCustomer(ConnectionData, GlobalSettings, customer, myobCustomer, isNew)
  305. .MapOk(() => ProcessCustomer(model, customer, myobCustomer)).Flatten()
  306. .MapOk(() => service.Save(ConnectionData, myobCustomer)).Flatten()
  307. .Get(out var result, out error))
  308. {
  309. customer.PostedReference = result.UID.ToString();
  310. results.AddSuccess(customer);
  311. }
  312. else
  313. {
  314. results.AddFailed(customer, error.Message);
  315. }
  316. }
  317. return results;
  318. }
  319. }
  320. public class CustomerMYOBPosterEngine<T> : MYOBPosterEngine<Customer, CustomerMYOBPosterSettings> { }