BillMYOBPoster.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.Core.Postable;
  4. using InABox.Poster.MYOB;
  5. using InABox.Scripting;
  6. using MYOB.AccountRight.SDK.Contracts.Version2.Sale;
  7. using MYOB.AccountRight.SDK.Services.GeneralLedger;
  8. using MYOB.AccountRight.SDK.Services.Purchase;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using MYOB.AccountRight.SDK.Contracts.Version2;
  15. using MYOBBill = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBill;
  16. using MYOBBillLine = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBillLine;
  17. using MYOBTaxCode = MYOB.AccountRight.SDK.Contracts.Version2.GeneralLedger.TaxCode;
  18. namespace PRS.Shared.Posters.MYOB;
  19. public class BillMYOBPosterSettings : MYOBPosterSettings
  20. {
  21. public override string DefaultScript(Type TPostable)
  22. {
  23. return @"using MYOBBill = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBill;
  24. using MYOBBillLine = MYOB.AccountRight.SDK.Contracts.Version2.Purchase.ServiceBillLine;
  25. public class Module
  26. {
  27. public void BeforePost(IDataModel<Bill> model)
  28. {
  29. // Perform pre-processing
  30. }
  31. public void ProcessBill(IDataModel<Bill> model, Bill bill, MYOBBill myobBill)
  32. {
  33. // Do extra processing for a bill; throw an exception to fail this bill.
  34. }
  35. public void ProcessBillLine(IDataModel<Bill> model, BillLine billLine, MYOBBillLine myobBillLine)
  36. {
  37. // Do extra processing for a bill line; throw an exception to fail this bill line (and thus fail the entire bill)
  38. }
  39. }";
  40. }
  41. }
  42. public class BillMYOBPoster : IMYOBPoster<Bill, BillMYOBPosterSettings>
  43. {
  44. public ScriptDocument? Script { get; set; }
  45. public MYOBConnectionData ConnectionData { get; set; }
  46. public BillMYOBPosterSettings Settings { get; set; }
  47. public MYOBGlobalPosterSettings GlobalSettings { get; set; }
  48. public bool BeforePost(IDataModel<Bill> model)
  49. {
  50. foreach(var (_, table) in model.ModelTables)
  51. {
  52. table.IsDefault = false;
  53. }
  54. model.SetIsDefault<Bill>(true);
  55. model.SetColumns<Bill>(RequiredBillColumns());
  56. model.SetIsDefault<BillLine>(true, alias: "Bill_BillLine");
  57. model.SetColumns<BillLine>(RequiredBillLineColumns(), alias: "Bill_BillLine");
  58. model.SetIsDefault<Supplier>(true, alias: "Bill_Supplier");
  59. model.SetColumns<Supplier>(RequiredSupplierColumns(), alias: "Bill_Supplier");
  60. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  61. return true;
  62. }
  63. #region Script Functions
  64. private Result<Exception> ProcessBill(IDataModel<Bill> model, Bill bill, MYOBBill myobBill)
  65. {
  66. return this.WrapScript("ProcessBill", model, bill, myobBill);
  67. }
  68. private Result<Exception> ProcessBillLine(IDataModel<Bill> model, BillLine billLine, MYOBBillLine myobBillLine)
  69. {
  70. return this.WrapScript("ProcessBillLine", model, billLine, myobBillLine);
  71. }
  72. #endregion
  73. private static Columns<Bill> RequiredBillColumns()
  74. {
  75. return Columns.None<Bill>()
  76. .Add(x => x.ID)
  77. //.Add(x => x.IsApproved)
  78. .Add(x => x.ApprovalStatus)
  79. .Add(x => x.PostedReference)
  80. .Add(x => x.Number)
  81. .Add(x => x.AccountingDate)
  82. .Add(x => x.PaymentDate)
  83. .Add(x => x.SupplierLink.ID)
  84. .Add(x => x.Description);
  85. }
  86. private static Columns<BillLine> RequiredBillLineColumns()
  87. {
  88. return Columns.None<BillLine>()
  89. .Add(x => x.ID)
  90. .Add(x => x.BillLink.ID)
  91. .Add(x => x.Description)
  92. .Add(x => x.IncTax)
  93. .Add(x => x.PurchaseGL.ID)
  94. .Add(x => x.PurchaseGL.Code)
  95. .Add(x => x.PurchaseGL.PostedReference)
  96. .Add(x => x.TaxCode.ID)
  97. .Add(x => x.TaxCode.Code)
  98. .Add(x => x.TaxCode.PostedReference);
  99. }
  100. private static Columns<Supplier> RequiredSupplierColumns()
  101. {
  102. return SupplierMYOBPoster.RequiredColumns();
  103. }
  104. public IPostResult<Bill> Process(IDataModel<Bill> model)
  105. {
  106. // https://developer.myob.com/api/myob-business-api/v2/purchase/bill/bill_service/
  107. var results = new PostResult<Bill>();
  108. var service = new ServiceBillService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  109. var bills = model.GetTable<Bill>().ToArray<Bill>();
  110. if(bills.Any(x => x.ApprovalStatus != BillApprovalStatus.Approved))
  111. {
  112. throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing.");
  113. }
  114. var suppliers = model.GetTable<Supplier>("Bill_Supplier")
  115. .ToObjects<Supplier>().ToDictionary(x => x.ID);
  116. var billLines = model.GetTable<BillLine>("Bill_BillLine")
  117. .ToObjects<BillLine>().GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToArray());
  118. foreach(var bill in bills)
  119. {
  120. MYOBBill myobBill;
  121. Exception? error;
  122. bool isNew;
  123. if(Guid.TryParse(bill.PostedReference, out var myobID))
  124. {
  125. if(!service.Get(ConnectionData, myobID).Get(out var newBill, out error))
  126. {
  127. CoreUtils.LogException("", error, $"Failed to find Bill in MYOB with id {myobID}");
  128. results.AddFailed(bill, $"Failed to find Bill in MYOB with id {myobID}: {error.Message}");
  129. continue;
  130. }
  131. myobBill = newBill;
  132. isNew = false;
  133. }
  134. else
  135. {
  136. myobBill = new MYOBBill();
  137. isNew = true;
  138. }
  139. myobBill.Number = bill.Number.Truncate(13);
  140. // Probably configure which date.
  141. myobBill.Date = bill.AccountingDate;
  142. myobBill.Terms ??= new();
  143. myobBill.Terms.PaymentIsDue = TermsPaymentType.InAGivenNumberOfDays;
  144. myobBill.Terms.BalanceDueDate = (bill.PaymentDate.Date - bill.BillDate.Date).Days + 1;
  145. myobBill.SupplierInvoiceNumber = bill.Number.Truncate(255);
  146. if(suppliers.TryGetValue(bill.SupplierLink.ID, out var supplier))
  147. {
  148. if(!SupplierMYOBPoster.MapSupplier(ConnectionData, supplier, GlobalSettings).Get(out var supplierID, out error))
  149. {
  150. CoreUtils.LogException("", error, $"Error while posting bill {bill.ID}");
  151. results.AddFailed(bill, error.Message);
  152. continue;
  153. }
  154. myobBill.Supplier ??= new();
  155. myobBill.Supplier.UID = supplierID;
  156. results.AddFragment(supplier, supplier.PostedStatus);
  157. }
  158. // myobBill.ShipToAddress =
  159. // myobBill.Terms =
  160. myobBill.IsTaxInclusive = true;
  161. myobBill.IsReportable = true;
  162. // myobBill.Freight =
  163. // myobBill.FreightForeign =
  164. if (isNew)
  165. {
  166. if(!this.GetDefaultTaxCode().Get(out var taxCodeID, out error))
  167. {
  168. results.AddFailed(bill, error.Message);
  169. continue;
  170. }
  171. myobBill.FreightTaxCode ??= new();
  172. myobBill.FreightTaxCode.UID = taxCodeID;
  173. }
  174. // myobBill.Category =
  175. myobBill.Comment = bill.Description.Truncate(2000);
  176. // myobBill.ShippingMethod =
  177. // myobBill.PromisedDate =
  178. // myobBill.JournalMemo =
  179. // myobBill.BillDeliveryStatus =
  180. // myobBill.Order =
  181. if(billLines.TryGetValue(bill.ID, out var lines))
  182. {
  183. var newLines = new MYOBBillLine[lines.Length];
  184. string? failed = null;
  185. for(int i = 0; i < lines.Length; ++i)
  186. {
  187. var billLine = lines[i];
  188. var line = new MYOBBillLine();
  189. line.Type = InvoiceLineType.Transaction;
  190. line.Description = billLine.Description.Truncate(1000);
  191. if(billLine.PurchaseGL.ID == Guid.Empty)
  192. {
  193. failed = "Not all lines have a PurchaseGL code set.";
  194. break;
  195. }
  196. if(!Guid.TryParse(billLine.PurchaseGL.PostedReference, out var accountID))
  197. {
  198. if(AccountMYOBUtils.GetAccount(ConnectionData, billLine.PurchaseGL.Code).Get(out accountID, out error))
  199. {
  200. results.AddFragment(new GLCode { PostedReference = accountID.ToString() }
  201. .SetID(billLine.PurchaseGL.ID));
  202. }
  203. else
  204. {
  205. CoreUtils.LogException("", error);
  206. failed = error.Message;
  207. break;
  208. }
  209. }
  210. line.Account ??= new();
  211. line.Account.UID = accountID;
  212. line.Total = Math.Round(Convert.ToDecimal(billLine.IncTax), 2);
  213. line.TotalForeign = 0;
  214. // line.UnitsOfMeasure =
  215. // line.UnitCount =
  216. // line.UnitPrice =
  217. // line.UnitPriceForeign =
  218. // line.DiscountPercent =
  219. // line.Job =
  220. if(billLine.TaxCode.ID == Guid.Empty)
  221. {
  222. failed = "Not all lines have a TaxCode set.";
  223. break;
  224. }
  225. if(!Guid.TryParse(billLine.TaxCode.PostedReference, out var taxCodeID))
  226. {
  227. if (!ConnectionData.GetUID<TaxCodeService, MYOBTaxCode>(
  228. Filter<MYOBTaxCode>.Where(x => x.Code).IsEqualTo(billLine.TaxCode.Code))
  229. .Get(out taxCodeID, out error))
  230. {
  231. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}");
  232. failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}: {error.Message}";
  233. break;
  234. }
  235. else if (taxCodeID == Guid.Empty)
  236. {
  237. failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}";
  238. break;
  239. }
  240. results.AddFragment(new TaxCode { PostedReference = taxCodeID.ToString() }.SetID(taxCodeID));
  241. }
  242. line.TaxCode ??= new();
  243. line.TaxCode.UID = taxCodeID;
  244. if(!ProcessBillLine(model, billLine, line).Get(out error))
  245. {
  246. failed = error.Message;
  247. break;
  248. }
  249. newLines[i] = line;
  250. }
  251. if(failed is not null)
  252. {
  253. results.AddFailed(bill, failed);
  254. continue;
  255. }
  256. myobBill.Lines = newLines;
  257. }
  258. else
  259. {
  260. myobBill.Lines = [];
  261. }
  262. if(!ProcessBill(model, bill, myobBill).Get(out error))
  263. {
  264. results.AddFailed(bill, error.Message);
  265. continue;
  266. }
  267. if(service.Save(ConnectionData, myobBill).Get(out var result, out error))
  268. {
  269. bill.PostedReference = result.UID.ToString();
  270. results.AddSuccess(bill);
  271. }
  272. else
  273. {
  274. CoreUtils.LogException("", error, $"Error while posting purchase order {bill.ID}");
  275. results.AddFailed(bill, error.Message);
  276. }
  277. }
  278. return results;
  279. }
  280. }
  281. public class BillMYOBPosterEngine<T> : MYOBPosterEngine<Bill, BillMYOBPoster, BillMYOBPosterSettings> { }