BillMYOBPoster.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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.Approved)
  77. .Add(x => x.PostedReference)
  78. .Add(x => x.Number)
  79. .Add(x => x.AccountingDate)
  80. .Add(x => x.SupplierLink.ID)
  81. .Add(x => x.Description);
  82. }
  83. private static Columns<BillLine> RequiredBillLineColumns()
  84. {
  85. return Columns.None<BillLine>()
  86. .Add(x => x.ID)
  87. .Add(x => x.BillLink.ID)
  88. .Add(x => x.Description)
  89. .Add(x => x.IncTax)
  90. .Add(x => x.PurchaseGL.ID)
  91. .Add(x => x.PurchaseGL.Code)
  92. .Add(x => x.PurchaseGL.PostedReference)
  93. .Add(x => x.TaxCode.ID)
  94. .Add(x => x.TaxCode.Code)
  95. .Add(x => x.TaxCode.PostedReference);
  96. }
  97. private static Columns<Supplier> RequiredSupplierColumns()
  98. {
  99. return SupplierMYOBPoster.RequiredColumns();
  100. }
  101. public IPostResult<Bill> Process(IDataModel<Bill> model)
  102. {
  103. // https://developer.myob.com/api/myob-business-api/v2/purchase/bill/bill_service/
  104. var results = new PostResult<Bill>();
  105. var service = new ServiceBillService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
  106. var bills = model.GetTable<Bill>().ToArray<Bill>();
  107. if(bills.Any(x => x.Approved.IsEmpty()))
  108. {
  109. throw new PostFailedMessageException("We can't process unapproved bills; please approve all bills before processing.");
  110. }
  111. var suppliers = model.GetTable<Supplier>("Bill_Supplier")
  112. .ToObjects<Supplier>().ToDictionary(x => x.ID);
  113. var billLines = model.GetTable<BillLine>("Bill_BillLine")
  114. .ToObjects<BillLine>().GroupBy(x => x.BillLink.ID).ToDictionary(x => x.Key, x => x.ToArray());
  115. foreach(var bill in bills)
  116. {
  117. MYOBBill myobBill;
  118. Exception? error;
  119. bool isNew;
  120. if(Guid.TryParse(bill.PostedReference, out var myobID))
  121. {
  122. if(!service.Get(ConnectionData, myobID).Get(out var newBill, out error))
  123. {
  124. CoreUtils.LogException("", error, $"Failed to find Bill in MYOB with id {myobID}");
  125. results.AddFailed(bill, $"Failed to find Bill in MYOB with id {myobID}: {error.Message}");
  126. continue;
  127. }
  128. myobBill = newBill;
  129. isNew = false;
  130. }
  131. else
  132. {
  133. myobBill = new MYOBBill();
  134. isNew = true;
  135. }
  136. myobBill.Number = bill.Number.Truncate(13);
  137. // Probably configure which date.
  138. myobBill.Date = bill.AccountingDate;
  139. myobBill.SupplierInvoiceNumber = bill.Number.Truncate(255);
  140. if(suppliers.TryGetValue(bill.SupplierLink.ID, out var supplier))
  141. {
  142. if(!SupplierMYOBPoster.MapSupplier(ConnectionData, supplier, GlobalSettings).Get(out var supplierID, out error))
  143. {
  144. CoreUtils.LogException("", error, $"Error while posting bill {bill.ID}");
  145. results.AddFailed(bill, error.Message);
  146. continue;
  147. }
  148. myobBill.Supplier ??= new();
  149. myobBill.Supplier.UID = supplierID;
  150. results.AddFragment(supplier, supplier.PostedStatus);
  151. }
  152. // myobBill.ShipToAddress =
  153. // myobBill.Terms =
  154. myobBill.IsTaxInclusive = true;
  155. myobBill.IsReportable = true;
  156. // myobBill.Freight =
  157. // myobBill.FreightForeign =
  158. if (isNew)
  159. {
  160. if(!this.GetDefaultTaxCode().Get(out var taxCodeID, out error))
  161. {
  162. results.AddFailed(bill, error.Message);
  163. continue;
  164. }
  165. myobBill.FreightTaxCode ??= new();
  166. myobBill.FreightTaxCode.UID = taxCodeID;
  167. }
  168. // myobBill.Category =
  169. myobBill.Comment = bill.Description.Truncate(2000);
  170. // myobBill.ShippingMethod =
  171. // myobBill.PromisedDate =
  172. // myobBill.JournalMemo =
  173. // myobBill.BillDeliveryStatus =
  174. // myobBill.Order =
  175. if(billLines.TryGetValue(bill.ID, out var lines))
  176. {
  177. var newLines = new MYOBBillLine[lines.Length];
  178. string? failed = null;
  179. for(int i = 0; i < lines.Length; ++i)
  180. {
  181. var billLine = lines[i];
  182. var line = new MYOBBillLine();
  183. line.Type = InvoiceLineType.Transaction;
  184. line.Description = billLine.Description.Truncate(1000);
  185. if(billLine.PurchaseGL.ID == Guid.Empty)
  186. {
  187. failed = "Not all lines have a PurchaseGL code set.";
  188. break;
  189. }
  190. if(!Guid.TryParse(billLine.PurchaseGL.PostedReference, out var accountID))
  191. {
  192. if(AccountMYOBUtils.GetAccount(ConnectionData, billLine.PurchaseGL.Code).Get(out accountID, out error))
  193. {
  194. results.AddFragment(new GLCode { ID = billLine.PurchaseGL.ID, PostedReference = accountID.ToString() });
  195. }
  196. else
  197. {
  198. CoreUtils.LogException("", error);
  199. failed = error.Message;
  200. break;
  201. }
  202. }
  203. line.Account ??= new();
  204. line.Account.UID = accountID;
  205. line.Total = Math.Round(Convert.ToDecimal(billLine.IncTax, 2));
  206. line.TotalForeign = 0;
  207. // line.UnitsOfMeasure =
  208. // line.UnitCount =
  209. // line.UnitPrice =
  210. // line.UnitPriceForeign =
  211. // line.DiscountPercent =
  212. // line.Job =
  213. if(billLine.TaxCode.ID == Guid.Empty)
  214. {
  215. failed = "Not all lines have a TaxCode set.";
  216. break;
  217. }
  218. if(!Guid.TryParse(billLine.TaxCode.PostedReference, out var taxCodeID))
  219. {
  220. if (!ConnectionData.GetUID<TaxCodeService, MYOBTaxCode>(
  221. new Filter<MYOBTaxCode>(x => x.Code).IsEqualTo(billLine.TaxCode.Code))
  222. .Get(out taxCodeID, out error))
  223. {
  224. CoreUtils.LogException("", error, $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}");
  225. failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}: {error.Message}";
  226. break;
  227. }
  228. else if (taxCodeID == Guid.Empty)
  229. {
  230. failed = $"Failed to find TaxCode in MYOB with code {billLine.TaxCode.Code}";
  231. break;
  232. }
  233. results.AddFragment(new TaxCode { ID = taxCodeID, PostedReference = taxCodeID.ToString() });
  234. }
  235. line.TaxCode ??= new();
  236. line.TaxCode.UID = taxCodeID;
  237. if(!ProcessBillLine(model, billLine, line).Get(out error))
  238. {
  239. failed = error.Message;
  240. break;
  241. }
  242. newLines[i] = line;
  243. }
  244. if(failed is not null)
  245. {
  246. results.AddFailed(bill, failed);
  247. continue;
  248. }
  249. myobBill.Lines = newLines;
  250. }
  251. else
  252. {
  253. myobBill.Lines = [];
  254. }
  255. if(!ProcessBill(model, bill, myobBill).Get(out error))
  256. {
  257. results.AddFailed(bill, error.Message);
  258. continue;
  259. }
  260. if(service.Save(ConnectionData, myobBill).Get(out var result, out error))
  261. {
  262. bill.PostedReference = result.UID.ToString();
  263. results.AddSuccess(bill);
  264. }
  265. else
  266. {
  267. CoreUtils.LogException("", error, $"Error while posting purchase order {bill.ID}");
  268. results.AddFailed(bill, error.Message);
  269. }
  270. }
  271. return results;
  272. }
  273. }
  274. public class BillMYOBPosterEngine<T> : MYOBPosterEngine<Bill, BillMYOBPoster, BillMYOBPosterSettings> { }