BillMYOBPoster.cs 12 KB

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