BillMYOBPoster.cs 11 KB

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