CustomerMYOBPoster.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. using Org.BouncyCastle.Bcpg.OpenPgp;
  23. namespace PRS.Shared.Posters.MYOB;
  24. public class CustomerMYOBPosterSettings : MYOBPosterSettings
  25. {
  26. public override string DefaultScript(Type TPostable)
  27. {
  28. return @"using MYOBCustomer = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Customer;
  29. public class Module
  30. {
  31. public void BeforePost(IDataModel<Customer> model)
  32. {
  33. // Perform pre-processing
  34. }
  35. public void ProcessCustomer(IDataModel<Customer> model, Customer customer, MYOBCustomer myobCustomer)
  36. {
  37. // Do extra processing for a customer; throw an exception to fail this customer.
  38. }
  39. }";
  40. }
  41. }
  42. public static class ContactMYOBUtils
  43. {
  44. public static void SplitName(string name, out string firstName, out string lastName)
  45. {
  46. var names = name.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
  47. firstName = names.Length > 0 ? names[0] : "";
  48. lastName = names.Length > 1 ? names[1] : "";
  49. }
  50. public static Address ConvertAddress(MYOBAddress address)
  51. {
  52. var newAddress = new Address
  53. {
  54. Street = address.Street,
  55. City = address.City,
  56. State = address.State,
  57. PostCode = address.PostCode
  58. };
  59. return newAddress;
  60. }
  61. public static MYOBAddress ConvertAddress(Address address, int location, IContact contact)
  62. {
  63. var mobile = contact.Mobile.Truncate(21);
  64. var phone = contact.Telephone.Truncate(21);
  65. var newAddress = new MYOBAddress
  66. {
  67. Location = location,
  68. Street = address.Street.Truncate(255),
  69. City = address.City.Truncate(255),
  70. State = address.State.Truncate(255),
  71. PostCode = address.PostCode.Truncate(11),
  72. Email = contact.Email.Truncate(255),
  73. ContactName = contact.Name.Truncate(25)
  74. };
  75. if (mobile.IsNullOrWhiteSpace())
  76. {
  77. newAddress.Phone1 = phone;
  78. }
  79. else
  80. {
  81. newAddress.Phone1 = mobile;
  82. newAddress.Phone2 = phone;
  83. }
  84. return newAddress;
  85. }
  86. }
  87. public class CustomerMYOBAutoRefresher : IAutoRefresher<Customer>
  88. {
  89. public bool ShouldRepost(Customer customer)
  90. {
  91. var shouldRepost = customer.HasOriginalValue(x => x.Name)
  92. || customer.HasOriginalValue(x => x.Code)
  93. || customer.HasOriginalValue(x => x.ABN)
  94. || customer.DefaultContact.HasOriginalValue(x => x.ID)
  95. || customer.Delivery.HasOriginalValue(x => x.Street)
  96. || customer.Delivery.HasOriginalValue(x => x.City)
  97. || customer.Delivery.HasOriginalValue(x => x.State)
  98. || customer.Delivery.HasOriginalValue(x => x.PostCode)
  99. || customer.Postal.HasOriginalValue(x => x.Street)
  100. || customer.Postal.HasOriginalValue(x => x.City)
  101. || customer.Postal.HasOriginalValue(x => x.State)
  102. || customer.Postal.HasOriginalValue(x => x.PostCode);
  103. if (shouldRepost)
  104. {
  105. return true;
  106. }
  107. if(customer.CustomerStatus.HasOriginalValue(x => x.ID))
  108. {
  109. var originalID = customer.CustomerStatus.GetOriginalValue(x => x.ID);
  110. var currentID = customer.CustomerStatus.ID;
  111. var statuses = DbFactory.NewProvider(Logger.Main).Query<CustomerStatus>(
  112. new Filter<CustomerStatus>(x => x.ID).IsEqualTo(originalID).Or(x => x.ID).IsEqualTo(currentID),
  113. Columns.None<CustomerStatus>().Add(x => x.ID).Add(x => x.Active))
  114. .ToArray<CustomerStatus>();
  115. if (statuses.Length == 2 && statuses[0].Active != statuses[1].Active)
  116. {
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. }
  123. public class CustomerMYOBPoster :
  124. IMYOBPoster<Customer, CustomerMYOBPosterSettings>,
  125. IAutoRefreshPoster<Customer, CustomerMYOBAutoRefresher>
  126. {
  127. public ScriptDocument? Script { get; set; }
  128. public CustomerMYOBPosterSettings Settings { get; set; }
  129. public MYOBGlobalPosterSettings GlobalSettings { get; set; }
  130. public MYOBConnectionData ConnectionData { get; set; }
  131. public bool BeforePost(IDataModel<Customer> model)
  132. {
  133. foreach (var (_, table) in model.ModelTables)
  134. {
  135. table.IsDefault = false;
  136. }
  137. model.SetIsDefault<Customer>(true);
  138. model.SetColumns<Customer>(RequiredColumns());
  139. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  140. return true;
  141. }
  142. public static Columns<Customer> RequiredColumns()
  143. {
  144. return Columns.None<Customer>()
  145. .Add(x => x.ID)
  146. .Add(x => x.PostedReference)
  147. .Add(x => x.PostedStatus)
  148. .Add(x => x.DefaultContact.Name)
  149. .Add(x => x.Name)
  150. .Add(x => x.Code)
  151. .Add(x => x.CustomerStatus.ID)
  152. .Add(x => x.CustomerStatus.Active)
  153. .Add(x => x.Delivery.Street)
  154. .Add(x => x.Delivery.City)
  155. .Add(x => x.Delivery.State)
  156. .Add(x => x.Delivery.PostCode)
  157. .Add(x => x.Postal.Street)
  158. .Add(x => x.Postal.City)
  159. .Add(x => x.Postal.State)
  160. .Add(x => x.Postal.PostCode)
  161. .Add(x => x.DefaultContact.Mobile)
  162. .Add(x => x.DefaultContact.Telephone)
  163. .Add(x => x.DefaultContact.Email)
  164. .Add(x => x.DefaultContact.Name)
  165. .Add(x => x.DefaultContact.Mobile)
  166. .Add(x => x.ABN);
  167. }
  168. #region Script Functions
  169. private Result<Exception> ProcessCustomer(IDataModel<Customer> model, Customer customer, MYOBCustomer myobCustomer)
  170. {
  171. return this.WrapScript("ProcessCustomer", model, customer, myobCustomer);
  172. }
  173. #endregion
  174. public static Result<Exception> UpdateCustomer(MYOBConnectionData data, MYOBGlobalPosterSettings settings, Customer customer, MYOBCustomer myobCustomer, bool isNew)
  175. {
  176. // Documentation: https://developer.myob.com/api/myob-business-api/v2/contact/customer/
  177. // Since this might be called from some other poster, we need to ensure we have the right columns.
  178. Client.EnsureColumns(customer, RequiredColumns());
  179. ContactMYOBUtils.SplitName(customer.DefaultContact.Name, out var firstName, out var lastName);
  180. myobCustomer.CompanyName = customer.Name.Truncate(50);
  181. myobCustomer.FirstName = firstName.Truncate(30);
  182. myobCustomer.LastName = lastName.Truncate(20);
  183. myobCustomer.IsIndividual = false;
  184. myobCustomer.DisplayID = customer.Code.Truncate(15);
  185. // If there is not customer status, we will use default to Active = true.
  186. myobCustomer.IsActive = customer.CustomerStatus.ID == Guid.Empty || customer.CustomerStatus.Active;
  187. myobCustomer.Addresses =
  188. [
  189. ContactMYOBUtils.ConvertAddress(customer.Postal, 1, customer.DefaultContact),
  190. ContactMYOBUtils.ConvertAddress(customer.Delivery, 2, customer.DefaultContact)
  191. ];
  192. // Notes =
  193. // PhotoURI =
  194. // RowVersion =
  195. myobCustomer.SellingDetails ??= new();
  196. myobCustomer.SellingDetails.SaleLayout = InvoiceLayoutType.NoDefault;
  197. // myobCustomer.SellingDetails.PrintedFOrm =
  198. myobCustomer.SellingDetails.InvoiceDelivery = DocumentAction.PrintAndEmail;
  199. // myobCustomer.SellingDetails.IncomeAccount =
  200. // myobCustomer.SellingDetails.ReceiptMemo =
  201. // myobCustomer.SellingDetails.SalesPerson =
  202. // myobCustomer.SellingDetails.SaleComment =
  203. // myobCustomer.SellingDetails.ShippingMethod =
  204. // myobCustomer.SellingDetails.HourlyBillRate =
  205. // myobCustomer.SellingDetails.ABNBranch =
  206. myobCustomer.SellingDetails.ABN = customer.ABN.Truncate(14);
  207. if (isNew)
  208. {
  209. if(!MYOBPosterUtils.GetDefaultTaxCode(data, settings).Get(out var taxID, out var error))
  210. {
  211. return Result.Error(error);
  212. }
  213. myobCustomer.SellingDetails.TaxCode ??= new();
  214. myobCustomer.SellingDetails.TaxCode.UID = taxID;
  215. myobCustomer.SellingDetails.FreightTaxCode ??= new();
  216. myobCustomer.SellingDetails.FreightTaxCode.UID = taxID;
  217. }
  218. return Result.Ok();
  219. }
  220. /// <summary>
  221. /// Try to find a customer in MYOB which matches <paramref name="customer"/>, and if this fails, create a new one.
  222. /// </summary>
  223. /// <remarks>
  224. /// After this has finished, <paramref name="customer"/> will be updated with <see cref="Customer.PostedReference"/> set to the correct ID.
  225. /// <br/>
  226. /// <paramref name="customer"/> needs to have at least <see cref="Customer.Code"/> and <see cref="Customer.PostedReference"/> as loaded columns.
  227. /// </remarks>
  228. /// <param name="data"></param>
  229. /// <param name="customer">The customer to map to.</param>
  230. /// <returns>The UID of the MYOB customer.</returns>
  231. public static Result<Guid, Exception> MapCustomer(MYOBConnectionData data, Customer customer, MYOBGlobalPosterSettings settings)
  232. {
  233. if(Guid.TryParse(customer.PostedReference, out var myobID))
  234. {
  235. return new Result<Guid, Exception>(myobID);
  236. }
  237. var service = new CustomerService(data.Configuration, null, data.AuthKey);
  238. var result = service.Query(data, new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(customer.Code), top: 1);
  239. return result.MapOk(customers =>
  240. {
  241. if(customers.Items.Length == 0)
  242. {
  243. if(customer.Code.Length > 15)
  244. {
  245. return Result.Error(new Exception("Customer code is longer than 15 characters"));
  246. }
  247. var myobCustomer = new MYOBCustomer();
  248. return UpdateCustomer(data, settings, customer, myobCustomer, true)
  249. .MapOk(() => service.Save(data, myobCustomer)
  250. .MapOk(x =>
  251. {
  252. // Marking as repost because a script may not have run.
  253. customer.PostedStatus = PostedStatus.RequiresRepost;
  254. customer.PostedReference = x.UID.ToString();
  255. return x.UID;
  256. }))
  257. .Flatten();
  258. }
  259. else
  260. {
  261. customer.PostedReference = customers.Items[0].UID.ToString();
  262. customer.PostedStatus = PostedStatus.RequiresRepost;
  263. return Result.Ok(customers.Items[0].UID);
  264. }
  265. }).Flatten();
  266. }
  267. private static bool IsBlankCode(string code)
  268. {
  269. return code.IsNullOrWhiteSpace() || code.Equals("*None");
  270. }
  271. public IPullResult<Customer> Pull()
  272. {
  273. var result = new PullResult<Customer>();
  274. var top = 400;
  275. var skip = 0;
  276. var customerCodes = new HashSet<string>();
  277. var service = new CustomerService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  278. while (true)
  279. {
  280. if(!service.Query(ConnectionData, null, top: top, skip: skip).Get(out var myobCustomers, out var error))
  281. {
  282. CoreUtils.LogException("", error);
  283. throw new PullFailedMessageException(error.Message);
  284. }
  285. if(myobCustomers.Items.Length == 0)
  286. {
  287. break;
  288. }
  289. var myobIDs = myobCustomers.Items.ToArray(x => x.UID.ToString());
  290. var myobCodes = myobCustomers.Items.Select(x => x.DisplayID).Where(x => !IsBlankCode(x)).ToArray();
  291. var myobNames = myobCustomers.Items.Where(x => IsBlankCode(x.DisplayID) && !x.CompanyName.IsNullOrWhiteSpace())
  292. .Select(x => x.CompanyName).ToArray();
  293. var customers = Client.Query(
  294. new Filter<Customer>(x => x.PostedReference).InList(myobIDs)
  295. .Or(x => x.Code).InList(myobCodes)
  296. .Or(x => x.Name).InList(myobNames),
  297. Columns.None<Customer>().Add(x => x.ID).Add(x => x.PostedReference).Add(x => x.Code).Add(x => x.Name))
  298. .ToArray<Customer>();
  299. var customerDict = customers.Where(x => !x.PostedReference.IsNullOrWhiteSpace())
  300. .ToDictionary(x => x.PostedReference);
  301. var blankCustomers = customers.Where(x => x.PostedReference.IsNullOrWhiteSpace()).ToArray();
  302. var needCodes = new Dictionary<string, (string prefix, int i, Customer customer)>();
  303. foreach(var myobCustomer in myobCustomers.Items)
  304. {
  305. if (customerDict.TryGetValue(myobCustomer.UID.ToString(), out var customer))
  306. {
  307. // Skipping existing customers at this point.
  308. continue;
  309. }
  310. customer = !IsBlankCode(myobCustomer.DisplayID)
  311. ? blankCustomers.FirstOrDefault(x => string.Equals(x.Code, myobCustomer.DisplayID))
  312. : blankCustomers.FirstOrDefault(x => string.Equals(x.Name, myobCustomer.CompanyName));
  313. if(customer is not null)
  314. {
  315. customer.PostedReference = myobCustomer.UID.ToString();
  316. result.AddEntity(PullResultType.Linked, customer);
  317. continue;
  318. }
  319. customer = new Customer();
  320. string code;
  321. if (!IsBlankCode(myobCustomer.DisplayID))
  322. {
  323. code = myobCustomer.DisplayID.ToString();
  324. }
  325. else if (!myobCustomer.CompanyName.IsNullOrWhiteSpace())
  326. {
  327. code = myobCustomer.CompanyName[..Math.Min(3, myobCustomer.CompanyName.Length)].ToUpper();
  328. }
  329. else
  330. {
  331. code = "CUS";
  332. }
  333. int i = 1;
  334. customer.Code = code;
  335. while (customerCodes.Contains(customer.Code))
  336. {
  337. customer.Code = $"{code}{i:d3}";
  338. ++i;
  339. }
  340. customerCodes.Add(customer.Code);
  341. customer.Name = myobCustomer.CompanyName;
  342. customer.ABN = myobCustomer.SellingDetails.ABN;
  343. if(myobCustomer.Addresses is not null)
  344. {
  345. var delivery = myobCustomer.Addresses.FirstOrDefault(x => x.Location == 2);
  346. if(delivery is not null)
  347. {
  348. customer.Delivery.CopyFrom(ContactMYOBUtils.ConvertAddress(delivery));
  349. }
  350. var postal = myobCustomer.Addresses.FirstOrDefault(x => x.Location == 1);
  351. if(postal is not null)
  352. {
  353. customer.Postal.CopyFrom(ContactMYOBUtils.ConvertAddress(postal));
  354. }
  355. customer.Email = delivery?.Email ?? postal?.Email ?? "";
  356. }
  357. customer.PostedReference = myobCustomer.UID.ToString();
  358. result.AddEntity(PullResultType.New, customer);
  359. needCodes.Add(customer.Code, (code, i, customer));
  360. }
  361. // Do code clash checking
  362. while(needCodes.Count > 0)
  363. {
  364. var codes = Client.Query(
  365. new Filter<Customer>(x => x.Code).InList(needCodes.Values.Select(x => x.customer.Code).ToArray()),
  366. Columns.None<Customer>().Add(x => x.Code));
  367. var newNeedCodes = new Dictionary<string, (string prefix, int i, Customer customer)>();
  368. foreach(var row in codes.Rows)
  369. {
  370. var code = row.Get<Customer, string>(x => x.Code);
  371. if(needCodes.Remove(code, out var needed))
  372. {
  373. int i = needed.i;
  374. do
  375. {
  376. needed.customer.Code = $"{needed.prefix}{i:d3}";
  377. ++i;
  378. } while (customerCodes.Contains(needed.customer.Code));
  379. customerCodes.Add(needed.customer.Code);
  380. newNeedCodes.Add(needed.customer.Code, (needed.prefix, i, needed.customer));
  381. }
  382. }
  383. needCodes = newNeedCodes;
  384. }
  385. skip += top;
  386. }
  387. return result;
  388. }
  389. public IPostResult<Customer> Process(IDataModel<Customer> model)
  390. {
  391. var results = new PostResult<Customer>();
  392. var service = new CustomerService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  393. var customers = model.GetTable<Customer>().ToArray<Customer>();
  394. foreach(var customer in customers)
  395. {
  396. if(customer.Code.Length > 15)
  397. {
  398. results.AddFailed(customer, "Code is longer than 15 characters.");
  399. continue;
  400. }
  401. bool isNew;
  402. MYOBCustomer myobCustomer;
  403. Exception? error;
  404. if(Guid.TryParse(customer.PostedReference, out var myobID))
  405. {
  406. if(!service.Get(ConnectionData, myobID).Get(out var newCustomer, out error))
  407. {
  408. CoreUtils.LogException("", error, $"Failed to find Customer in MYOB with id {myobID}");
  409. results.AddFailed(customer, $"Failed to find Customer in MYOB with id {myobID}: {error.Message}");
  410. continue;
  411. }
  412. myobCustomer = newCustomer;
  413. isNew = false;
  414. }
  415. else
  416. {
  417. if(service.Query(
  418. ConnectionData,
  419. new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(customer.Code),
  420. top: 1).Get(out var myobCustomers, out error))
  421. {
  422. if(myobCustomers.Items.Length > 0)
  423. {
  424. myobCustomer = myobCustomers.Items[0];
  425. isNew = false;
  426. }
  427. else if(service.Query(
  428. ConnectionData,
  429. new Filter<MYOBCustomer>(x => x.CompanyName).IsEqualTo(customer.Name)
  430. .And(new Filter<MYOBCustomer>(x => x.DisplayID).IsEqualTo(null)
  431. .Or(x => x.DisplayID).IsEqualTo("")
  432. .Or(x => x.DisplayID).IsEqualTo("*None")),
  433. top: 1).Get(out myobCustomers, out error))
  434. {
  435. if(myobCustomers.Items.Length > 0)
  436. {
  437. myobCustomer = myobCustomers.Items[0];
  438. myobCustomer.DisplayID = customer.Code;
  439. isNew = false;
  440. }
  441. else
  442. {
  443. myobCustomer = new MYOBCustomer();
  444. isNew = true;
  445. }
  446. }
  447. else
  448. {
  449. CoreUtils.LogException("", error);
  450. results.AddFailed(customer, error.Message);
  451. continue;
  452. }
  453. }
  454. else
  455. {
  456. CoreUtils.LogException("", error);
  457. results.AddFailed(customer, error.Message);
  458. continue;
  459. }
  460. }
  461. if(UpdateCustomer(ConnectionData, GlobalSettings, customer, myobCustomer, isNew)
  462. .MapOk(() => ProcessCustomer(model, customer, myobCustomer)).Flatten()
  463. .MapOk(() => service.Save(ConnectionData, myobCustomer)).Flatten()
  464. .Get(out var result, out error))
  465. {
  466. customer.PostedReference = result.UID.ToString();
  467. results.AddSuccess(customer);
  468. }
  469. else
  470. {
  471. results.AddFailed(customer, error.Message);
  472. }
  473. }
  474. return results;
  475. }
  476. }
  477. public class CustomerMYOBPosterEngine<T> : MYOBPosterEngine<Customer, CustomerMYOBPoster, CustomerMYOBPosterSettings>, IPullerEngine<Customer, CustomerMYOBPoster>
  478. {
  479. public IPullResult<Customer> DoPull()
  480. {
  481. LoadConnectionData();
  482. return Poster.Pull();
  483. }
  484. }