InvoiceUtilities.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using PRSDimensionUtils;
  5. namespace PRS.Shared;
  6. public enum InvoiceTimeCalculation
  7. {
  8. Detailed,
  9. Activity,
  10. Collapsed,
  11. }
  12. public enum InvoiceMaterialCalculation
  13. {
  14. Detailed,
  15. Product,
  16. CostCentre,
  17. Collapsed,
  18. }
  19. public enum InvoiceExpensesCalculation
  20. {
  21. Detailed,
  22. Collapsed,
  23. }
  24. public static class InvoiceUtilities
  25. {
  26. private class InvoiceLineDetail
  27. {
  28. public String Description { get; set; }
  29. public TaxCodeLink TaxCode { get; set; }
  30. public double Quantity { get; set; }
  31. public double Charge { get; set; }
  32. public InvoiceLineDetail()
  33. {
  34. TaxCode = new TaxCodeLink();
  35. }
  36. }
  37. private static async Task<InvoiceLine[]> TimeLines(Invoice invoice, InvoiceTimeCalculation timesummary)
  38. {
  39. var timelines = new Dictionary<Guid, InvoiceLineDetail>();
  40. var activitiesTask = Task.Run(() =>
  41. {
  42. return Client.Query(
  43. Filter<CustomerActivitySummary>.Where(x => x.Customer.ID).InList(invoice.CustomerLink.ID, Guid.Empty),
  44. Columns.None<CustomerActivitySummary>().Add(x => x.Customer.ID)
  45. .Add(x => x.Activity.ID)
  46. .Add(x => x.Activity.Code)
  47. .Add(x => x.Activity.Description)
  48. .Add(x => x.Charge.TaxCode.ID)
  49. .Add(x => x.Charge.TaxCode.Rate)
  50. .Add(x => x.Charge.Chargeable)
  51. .Add(x => x.Charge.FixedCharge)
  52. .Add(x => x.Charge.ChargeRate)
  53. .Add(x => x.Charge.ChargePeriod)
  54. .Add(x => x.Charge.MinimumCharge))
  55. .ToObjects<CustomerActivitySummary>()
  56. .GroupByDictionary(x => (CustomerID: x.Customer.ID, ActivityID: x.Activity.ID));
  57. });
  58. var assignmentsTask = Task.Run(() =>
  59. {
  60. return Client.Query(
  61. Filter<Assignment>.Where(x => x.Invoice.ID).IsEqualTo(invoice.ID).And(x => x.Charge.Chargeable).IsEqualTo(true),
  62. Columns.None<Assignment>()
  63. .Add(x => x.ID)
  64. .Add(x => x.ActivityLink.ID)
  65. .Add(x => x.ActivityLink.Description)
  66. .Add(x => x.Date)
  67. .Add(x => x.Title)
  68. .Add(x => x.Description)
  69. .Add(x => x.Charge.OverrideCharge)
  70. .Add(x => x.Charge.Charge)
  71. .Add(x => x.Charge.OverrideQuantity)
  72. .Add(x => x.Charge.Quantity)
  73. .Add(x => x.Actual.Duration),
  74. new SortOrder<Assignment>(x => x.Date))
  75. .ToArray<Assignment>();
  76. });
  77. var activities = await activitiesTask;
  78. foreach (var assignment in await assignmentsTask)
  79. {
  80. var id = timesummary switch
  81. {
  82. InvoiceTimeCalculation.Detailed => assignment.ID,
  83. InvoiceTimeCalculation.Activity => assignment.ActivityLink.ID,
  84. _ => Guid.Empty
  85. };
  86. var description = timesummary switch
  87. {
  88. InvoiceTimeCalculation.Detailed => $"{assignment.Date:dd MMM yy} - {assignment.Title}: {assignment.Description}",
  89. InvoiceTimeCalculation.Activity => assignment.ActivityLink.Description,
  90. _ => "Labour"
  91. };
  92. var quantity = assignment.Charge.OverrideQuantity
  93. ? TimeSpan.FromHours(assignment.Charge.Quantity)
  94. : assignment.Actual.Duration;
  95. var activity = activities.GetValueOrDefault((invoice.CustomerLink.ID, assignment.ActivityLink.ID))?.FirstOrDefault()
  96. ?? activities.GetValueOrDefault((Guid.Empty, assignment.ActivityLink.ID))?.FirstOrDefault()
  97. ?? new CustomerActivitySummary();
  98. double charge;
  99. if (assignment.Charge.OverrideCharge)
  100. {
  101. charge = quantity.TotalHours * assignment.Charge.Charge;
  102. }
  103. else
  104. {
  105. var chargeperiod = !activity.Charge.ChargePeriod.Equals(TimeSpan.Zero)
  106. ? activity.Charge.ChargePeriod
  107. : TimeSpan.FromHours(1);
  108. // Here we adjust the period, essentially; should this update the actual 'quantity' we are using for this line?
  109. // It seems no, but just checking.
  110. var rounded = quantity.Ceiling(chargeperiod);
  111. // Rate is charge per hour, so we must divide by the charge period time, to get dollars per hour, rather than dollars per period
  112. // $/hr = ($/pd) * (pd/hr) = ($/pd) / (hr/pd)
  113. // where $/pd is ChargeRate and hr/pd = chargeperiod.TotalHours
  114. var rate = activity.Charge.ChargeRate / chargeperiod.TotalHours;
  115. charge = Math.Max(
  116. activity.Charge.FixedCharge + (rounded.TotalHours * rate),
  117. activity.Charge.MinimumCharge);
  118. }
  119. if(!timelines.TryGetValue(id, out var timeline))
  120. {
  121. timeline = new InvoiceLineDetail
  122. {
  123. Description = description
  124. };
  125. timeline.TaxCode.CopyFrom(activity.Charge.TaxCode);
  126. timelines.Add(id, timeline);
  127. }
  128. timeline.Quantity += quantity.TotalHours;
  129. timeline.Charge += charge;
  130. }
  131. return timelines.Values.ToArray(line =>
  132. {
  133. var update = new InvoiceLine();
  134. update.InvoiceLink.ID = invoice.ID;
  135. update.Description = line.Description;
  136. update.TaxCode.CopyFrom(line.TaxCode);
  137. update.Quantity = timesummary != InvoiceTimeCalculation.Collapsed ? line.Quantity : 1;
  138. update.ExTax = line.Charge;
  139. return update;
  140. });
  141. }
  142. private static async Task<InvoiceLine[]> PartLines(Invoice invoice, InvoiceMaterialCalculation partsummary)
  143. {
  144. var productsTask = Task.Run(() =>
  145. {
  146. return Client.Query(
  147. Filter<CustomerProductSummary>.Where(x => x.Customer.ID).InList(invoice.CustomerLink.ID, Guid.Empty),
  148. Columns.None<CustomerProductSummary>()
  149. .Add(x => x.Customer.ID)
  150. .Add(x => x.Product.ID)
  151. .Add(x => x.Product.Code)
  152. .Add(x => x.Product.Name)
  153. .Add(x => x.Product.TaxCode.ID)
  154. .Add(x => x.Product.TaxCode.Rate)
  155. .Add(x => x.Charge.Chargeable)
  156. .Add(x => x.Charge.PriceType)
  157. .Add(x => x.Charge.Price)
  158. .Add(x => x.Charge.Markup))
  159. .ToObjects<CustomerProductSummary>()
  160. .GroupByDictionary(x => (CustomerID: x.Customer.ID, ProductID: x.Product.ID));
  161. });
  162. var movementsTask = Task.Run(() =>
  163. {
  164. return Client.Query(
  165. Filter<StockMovement>.Where(x => x.Invoice.ID).IsEqualTo(invoice.ID).And(x => x.Charge.Chargeable).IsEqualTo(true),
  166. Columns.None<StockMovement>()
  167. .Add(x => x.ID)
  168. .Add(x => x.Qty)
  169. .Add(x => x.Product.ID)
  170. .Add(x => x.Product.Name)
  171. .Add(x => x.Product.CostCentre.ID)
  172. .Add(x => x.Product.CostCentre.Description)
  173. .Add(x => x.Style.Code)
  174. .Add(x => x.Dimensions.UnitSize)
  175. .Add(x => x.Charge.OverrideCharge)
  176. .Add(x => x.Charge.Charge)
  177. .Add(x => x.Charge.OverrideQuantity)
  178. .Add(x => x.Charge.Quantity))
  179. .ToArray<StockMovement>();
  180. });
  181. var partlines = new Dictionary<Guid, InvoiceLineDetail>();
  182. var products = await productsTask;
  183. foreach (var item in await movementsTask)
  184. {
  185. var id = partsummary switch
  186. {
  187. InvoiceMaterialCalculation.Detailed => item.ID,
  188. InvoiceMaterialCalculation.Product => item.Product.ID,
  189. InvoiceMaterialCalculation.CostCentre => item.Product.CostCentre.ID,
  190. _ => Guid.Empty
  191. };
  192. var description = partsummary switch
  193. {
  194. InvoiceMaterialCalculation.Detailed => $"{item.Product.Name}: {item.Style.Code}; {item.Dimensions.UnitSize}",
  195. InvoiceMaterialCalculation.Product => item.Product.Name,
  196. InvoiceMaterialCalculation.CostCentre => item.Product.CostCentre.Description,
  197. _ => "Materials"
  198. };
  199. var quantity = item.Charge.OverrideQuantity
  200. ? item.Charge.Quantity
  201. : item.Qty; // Should this be 'Cost' instead? Also, this will give negative cost for transfer outs and issues. Doesn't seem right.
  202. var product =
  203. products.GetValueOrDefault((invoice.CustomerLink.ID, item.Product.ID))?.FirstOrDefault()
  204. ?? products.GetValueOrDefault((Guid.Empty, item.Product.ID))?.FirstOrDefault()
  205. ?? new CustomerProductSummary();
  206. double charge;
  207. if (item.Charge.OverrideCharge)
  208. {
  209. charge = quantity * item.Charge.Charge;
  210. }
  211. else
  212. {
  213. // Or perhaps should this be multiplying 'Cost' here?
  214. charge = quantity * (product.Charge.PriceType switch
  215. {
  216. ProductPriceType.CostPlus => 1 + product.Charge.Markup / 100,
  217. _ => product.Charge.Price
  218. });
  219. }
  220. if(!partlines.TryGetValue(id, out var partline))
  221. {
  222. partline = new InvoiceLineDetail
  223. {
  224. Description = description
  225. };
  226. partline.TaxCode.CopyFrom(product.Product.TaxCode);
  227. partlines.Add(id, partline);
  228. }
  229. partline.Quantity += quantity;
  230. partline.Charge += charge;
  231. }
  232. return partlines.Values.ToArray(line =>
  233. {
  234. var update = new InvoiceLine();
  235. update.InvoiceLink.ID = invoice.ID;
  236. update.Description = line.Description;
  237. update.TaxCode.CopyFrom(line.TaxCode);
  238. update.Quantity = new[] { InvoiceMaterialCalculation.Detailed, InvoiceMaterialCalculation.Product }.Contains(partsummary) ? line.Quantity : 1.0F;
  239. update.ExTax = line.Charge;
  240. return update;
  241. });
  242. }
  243. private static async Task<InvoiceLine[]> ExpenseLines(Invoice invoice, InvoiceExpensesCalculation expensesSummary)
  244. {
  245. var billLinesTask = Task.Run(() =>
  246. {
  247. return Client.Query(
  248. Filter<BillLine>.Where(x => x.Invoice.ID).IsEqualTo(invoice.ID).And(x => x.Charge.Chargeable).IsEqualTo(true),
  249. Columns.None<BillLine>()
  250. .Add(x => x.ID)
  251. .Add(x => x.Description)
  252. .Add(x => x.ExTax)
  253. .Add(x => x.TaxCode.ID)
  254. .Add(x => x.TaxCode.Rate)
  255. .Add(x => x.Charge.OverrideCharge)
  256. .Add(x => x.Charge.Charge)
  257. .Add(x => x.Charge.OverrideQuantity)
  258. .Add(x => x.Charge.Quantity))
  259. .ToArray<BillLine>();
  260. });
  261. var expenselines = new Dictionary<Guid, InvoiceLineDetail>();
  262. foreach (var item in await billLinesTask)
  263. {
  264. var id = expensesSummary switch
  265. {
  266. InvoiceExpensesCalculation.Detailed => item.ID,
  267. _ => Guid.Empty
  268. };
  269. var description = expensesSummary switch
  270. {
  271. InvoiceExpensesCalculation.Detailed => $"{item.Description}",
  272. _ => "Expenses"
  273. };
  274. var quantity = item.Charge.OverrideQuantity
  275. ? item.Charge.Quantity
  276. : 1.0;
  277. double charge;
  278. if (item.Charge.OverrideCharge)
  279. {
  280. charge = quantity * item.Charge.Charge;
  281. }
  282. else
  283. {
  284. charge = quantity * item.ExTax * (1 + invoice.CustomerLink.Markup / 100);
  285. }
  286. if(!expenselines.TryGetValue(id, out var expenseLine))
  287. {
  288. expenseLine = new InvoiceLineDetail
  289. {
  290. Description = description
  291. };
  292. expenseLine.TaxCode.CopyFrom(item.TaxCode);
  293. expenselines.Add(id, expenseLine);
  294. }
  295. expenseLine.Quantity += quantity;
  296. expenseLine.Charge += charge;
  297. }
  298. return expenselines.Values.ToArray(line =>
  299. {
  300. var update = new InvoiceLine();
  301. update.InvoiceLink.ID = invoice.ID;
  302. update.Description = line.Description;
  303. update.TaxCode.CopyFrom(line.TaxCode);
  304. update.Quantity = expensesSummary != InvoiceExpensesCalculation.Collapsed ? line.Quantity : 1.0F;
  305. update.ExTax = line.Charge;
  306. return update;
  307. });
  308. }
  309. public static void GenerateInvoiceLines(
  310. Guid invoiceid,
  311. InvoiceTimeCalculation timesummary,
  312. InvoiceMaterialCalculation partsummary,
  313. InvoiceExpensesCalculation expensesSummary,
  314. IProgress<String>? progress
  315. )
  316. {
  317. progress?.Report("Loading Invoice");
  318. var invoice = Client.Query(
  319. Filter<Invoice>.Where(x => x.ID).IsEqualTo(invoiceid))
  320. .ToObjects<Invoice>().FirstOrDefault();
  321. if(invoice is null)
  322. {
  323. Logger.Send(LogType.Error, "", $"Could not find invoice with ID {invoiceid}");
  324. return;
  325. }
  326. progress?.Report("Loading Detail Data");
  327. var deleteOldTask = Task.Run(() =>
  328. {
  329. var oldlines = new Client<InvoiceLine>().Query(
  330. Filter<InvoiceLine>.Where(x => x.InvoiceLink.ID).IsEqualTo(invoice.ID),
  331. Columns.None<InvoiceLine>().Add(x => x.ID)
  332. ).Rows.Select(x => x.ToObject<InvoiceLine>()).ToArray();
  333. new Client<InvoiceLine>().Delete(oldlines, "");
  334. });
  335. var timeLinesTask = TimeLines(invoice, timesummary);
  336. var partLinesTask = PartLines(invoice, partsummary);
  337. var expenseLinesTask = ExpenseLines(invoice, expensesSummary);
  338. progress?.Report("Calculating...");
  339. var updates = CoreUtils.Concatenate(
  340. timeLinesTask.Result,
  341. partLinesTask.Result,
  342. expenseLinesTask.Result);
  343. progress?.Report("Creating Invoice Lines");
  344. Client.Save(updates, "Recalculating Invoice from Time and Materials");
  345. }
  346. }