PurchaseOrderItemStore.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Comal.Classes;
  5. using InABox.Core;
  6. using PRSStores;
  7. using System;
  8. using InABox.Database;
  9. using InABox.Scripting;
  10. using NPOI.SS.Formula.Functions;
  11. using PRSDimensionUtils;
  12. using Columns = InABox.Core.Columns;
  13. namespace Comal.Stores;
  14. internal class PurchaseOrderItemStore : BaseStore<PurchaseOrderItem>
  15. {
  16. static PurchaseOrderItemStore()
  17. {
  18. RegisterListener<ProductDimensionUnit>(ReloadDimensionScripts);
  19. }
  20. private static void ReloadDimensionScripts(Guid[] ids)
  21. {
  22. DimensionUtils.ReloadDimensionScriptCache(
  23. ids,
  24. (f, c) => DbFactory.NewProvider(InABox.Core.Logger.Main).Query(f, c)
  25. );
  26. }
  27. // private void TransformDimensions(PurchaseOrderItem item)
  28. // {
  29. // if (_productdimensionunitcache == null)
  30. // ReloadProductDimensionUnitCache(null);
  31. // if (_productdimensionunitcache?.TryGetValue(item.Dimensions.Unit.ID, out ScriptDocument? script) == true)
  32. // {
  33. // var oldqty = item.Qty; // 1
  34. // if (!oldqty.IsEffectivelyEqual(0.0))
  35. // {
  36. // script.SetValue("Quantity", oldqty);
  37. // script.SetValue("Dimensions", item.Dimensions); // Length = 5.8
  38. // script.Execute("Module", DimensionUnit.ConvertDimensionsMethodName()); // Length = 1, Qty = 5.8,
  39. // var newqty = Convert.ToDouble(script.GetValue("Quantity")); // 5.8
  40. // item.Qty = newqty;
  41. // item.Cost = item.Cost * newqty / oldqty;
  42. // }
  43. // }
  44. // }
  45. private void UpdateStockMovements(PurchaseOrderItem entity)
  46. {
  47. var movements = Provider.Query<StockMovement>(
  48. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID))
  49. .ToArray<StockMovement>();
  50. foreach(var mvt in movements)
  51. {
  52. mvt.Date = entity.ReceivedDate;
  53. mvt.Cost = entity.Cost;
  54. }
  55. FindSubStore<StockMovement>().Save(movements, "Updated by purchase order modification");
  56. }
  57. private void CreateStockMovements(PurchaseOrderItem entity)
  58. {
  59. if (!entity.Product.IsValid())
  60. {
  61. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product.ID is blank!");
  62. return;
  63. }
  64. if (entity.Qty == 0)
  65. {
  66. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem Qty is blank!");
  67. return;
  68. }
  69. var locationid = entity.StockLocation.ID;
  70. var locationValid = entity.StockLocation.IsValid();
  71. var poiaTask = Task.Run(() =>
  72. {
  73. return Provider.Query(
  74. new Filter<PurchaseOrderItemAllocation>(x => x.Item.ID).IsEqualTo(entity.ID),
  75. Columns.None<PurchaseOrderItemAllocation>()
  76. .Add(x => x.ID)
  77. .Add(x => x.Job.ID)
  78. .Add(x => x.JobRequisitionItem.ID)
  79. .Add(x => x.JobRequisitionItem.Cancelled)
  80. .Add(x => x.Quantity))
  81. .ToArray<PurchaseOrderItemAllocation>();
  82. });
  83. var consigntask = Task.Run(() =>
  84. {
  85. if (entity.Consignment.ID != Guid.Empty && !entity.Consignment.ExTax.IsEffectivelyEqual(0.0))
  86. {
  87. var values = Provider.Query(
  88. new Filter<PurchaseOrderItem>(x => x.Consignment.ID).IsEqualTo(entity.Consignment.ID),
  89. Columns.None<PurchaseOrderItem>().Add(x => x.ExTax)
  90. ).Rows.Select(r => r.Get<PurchaseOrderItem, double>(c => c.ExTax));
  91. return values.Sum();
  92. }
  93. else
  94. {
  95. return 0.0;
  96. }
  97. });
  98. var producttask = Task.Run(
  99. () => Provider.Query(
  100. new Filter<Product>(x => x.ID).IsEqualTo(entity.Product.ID),
  101. Columns.None<Product>()
  102. .Add(x => x.ID)
  103. .Add(x => x.DefaultLocation.ID)
  104. .Add(x => x.Warehouse.ID)
  105. .AddDimensionsColumns(x => x.DefaultInstance.Dimensions, Dimensions.ColumnsType.All)
  106. .Add(x => x.NonStock))
  107. .Rows.FirstOrDefault());
  108. var locationtask = Task.Run(
  109. () => Provider.Query(
  110. new Filter<StockLocation>(x => x.Default).IsEqualTo(true),
  111. Columns.None<StockLocation>().Add(x => x.ID, x => x.Warehouse.ID, x => x.Warehouse.Default)));
  112. Task.WaitAll(producttask, locationtask, poiaTask, consigntask);
  113. var productrow = producttask.Result;
  114. var defaultlocations = locationtask.Result;
  115. var allocations = poiaTask.Result.ToArray();
  116. if (productrow is null)
  117. {
  118. Logger.Send(LogType.Information, UserID, "Cannot Find PurchaseOrderItem.Product.ID!");
  119. return;
  120. }
  121. if (productrow.Get<Product, bool>(x => x.NonStock))
  122. {
  123. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product is marked as Non Stock!");
  124. return;
  125. }
  126. if (!locationValid)
  127. {
  128. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Location.ID is blank!");
  129. var productlocationid = productrow.EntityLinkID<Product, StockLocationLink>(x => x.DefaultLocation) ?? Guid.Empty;
  130. if (productlocationid != Guid.Empty)
  131. {
  132. Logger.Send(LogType.Information, UserID, "- Using Product.DefaultLocation.ID as location");
  133. locationid = productlocationid;
  134. }
  135. else
  136. {
  137. var productwarehouseid = productrow.Get<Product, Guid>(c => c.Warehouse.ID);
  138. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, Guid>(c => c.Warehouse.ID) == productwarehouseid);
  139. if (row != null)
  140. {
  141. Logger.Send(LogType.Information, UserID, "- Using Product.Warehouse -> Default as location");
  142. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  143. }
  144. }
  145. if (locationid == Guid.Empty)
  146. {
  147. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, bool>(c => c.Warehouse.Default));
  148. if (row != null)
  149. {
  150. Logger.Send(LogType.Information, UserID, "- Using Default Warehouse -> Default Location as location");
  151. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  152. }
  153. }
  154. if (locationid == Guid.Empty)
  155. {
  156. Logger.Send(LogType.Information, UserID, "- Cannot find Location : Skipping Movement Creation");
  157. return;
  158. }
  159. }
  160. if (entity.Dimensions.Unit.ID == Guid.Empty
  161. && entity.Dimensions.Height == 0
  162. && entity.Dimensions.Width == 0
  163. && entity.Dimensions.Length == 0
  164. && entity.Dimensions.Weight == 0)
  165. {
  166. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Unit Size is zero!");
  167. entity.Dimensions.CopyFrom(productrow.ToObject<Product>().DefaultInstance.Dimensions);
  168. }
  169. entity.ConvertDimensions(DbFactory.NewProvider(Logger.Main).QueryProvider<ProductDimensionUnit>(UserID));
  170. // Actual logic begins here.
  171. var totalAllocations = allocations.Sum(x => x.Quantity);
  172. var freeQty = entity.Qty - totalAllocations;
  173. var instancetask = Task.Run(
  174. () => !freeQty.IsEffectivelyEqual(0.0)
  175. ? Provider.Query(
  176. new Filter<ProductInstance>(x => x.Product.ID).IsEqualTo(entity.Product.ID)
  177. .And(x => x.Style.ID).IsEqualTo(entity.Style.ID)
  178. .And(x => x.Dimensions).DimensionEquals(entity.Dimensions),
  179. Columns.Required<ProductInstance>()
  180. .Add(x => x.ID)
  181. .Add(x => x.FreeStock)
  182. .Add(x => x.AverageCost)
  183. .Add(x => x.LastCost)
  184. ).Rows.FirstOrDefault()
  185. : null
  186. );
  187. var batch = new StockMovementBatch
  188. {
  189. Type = StockMovementBatchType.Receipt,
  190. TimeStamp = DateTime.Now,
  191. Notes = $"Received on PO"
  192. };
  193. var movements = new List<StockMovement>();
  194. var _pototal = entity.Qty;
  195. var poCost = entity.Cost;
  196. if (!consigntask.Result.IsEffectivelyEqual(0.0)
  197. && !entity.Qty.IsEffectivelyEqual(0.0))
  198. {
  199. poCost += entity.Cost * entity.Consignment.ExTax / consigntask.Result;
  200. }
  201. var transactionID = Guid.NewGuid();
  202. foreach (var poia in allocations)
  203. {
  204. if (poia.Quantity == 0) continue;
  205. // Then, we make transfers into each of the allocations.
  206. var jri = poia.JobRequisitionItem.ID == Guid.Empty ? null : poia.JobRequisitionItem;
  207. var mvt = CreateReceive(movements, entity, locationid, poia.Job, jri, poia.Quantity, poCost, transactionID);
  208. if(jri is not null && !jri.Cancelled.IsEmpty())
  209. {
  210. CreateJRICancelledTransfer(mvt, entity, movements, jri, poia.Quantity, Guid.NewGuid());
  211. }
  212. }
  213. var qty = entity.Qty - allocations.Sum(x => x.Quantity);
  214. if(qty != 0)
  215. {
  216. CreateReceive(movements, entity, locationid, entity.Job, null, qty, poCost, transactionID);
  217. }
  218. FindSubStore<StockMovementBatch>().Save(batch, "Received on PO");
  219. foreach(var mvt in movements)
  220. {
  221. mvt.Batch.ID = batch.ID;
  222. }
  223. // We need the instancetask to return before updating any stock movements
  224. instancetask.Wait();
  225. FindSubStore<StockMovement>().Save(movements, "Updated by Purchase Order Modification");
  226. // Update the AverageCost on the instance
  227. if (!freeQty.IsEffectivelyEqual(0.0))
  228. {
  229. var instance = instancetask.Result?.ToObject<ProductInstance>();
  230. if (instance == null)
  231. {
  232. instance = new ProductInstance();
  233. instance.Product.ID = entity.Product.ID;
  234. instance.Style.ID = entity.Style.ID;
  235. instance.Dimensions.CopyFrom(entity.Dimensions);
  236. }
  237. instance.LastCost = entity.Cost;
  238. var freeqty = instance.FreeStock;
  239. var freeavg = instance.AverageCost;
  240. var freecost = instance.FreeStock * freeavg;
  241. var poqty = freeQty * (Math.Abs(entity.Dimensions.Value) > 0.0001F ? entity.Dimensions.Value : 1.0F);
  242. var pocost = entity.Cost * poqty;
  243. if (!consigntask.Result.IsEffectivelyEqual(0.0))
  244. pocost += freeQty * entity.Cost * entity.Consignment.ExTax / consigntask.Result;
  245. var totalqty = freeqty + poqty;
  246. var totalcost = freecost + pocost;
  247. var averagecost = Math.Abs(totalqty) > 0.0001F
  248. ? totalcost / totalqty
  249. : pocost;
  250. if (Math.Abs(averagecost - freeavg) > 0.0001F)
  251. {
  252. instance.AverageCost = averagecost;
  253. FindSubStore<ProductInstance>().Save(instance,
  254. $"Updated Average Cost: " +
  255. $"({freeqty} @ {freeavg:C2}) + ({poqty} @ {entity.Cost:C2}) = {totalcost:C2} / {totalqty}"
  256. );
  257. }
  258. }
  259. entity.CancelChanges();
  260. }
  261. private static void CreateJRICancelledTransfer(
  262. IStockHolding movement,
  263. PurchaseOrderItem entity,
  264. List<StockMovement> movements,
  265. IJobRequisitionItem jri,
  266. double qty,
  267. Guid transactionID)
  268. {
  269. var lastMovement = movements.Count > 0 ? movements[^1] : null;
  270. var tOut = movement.CreateMovement();
  271. tOut.JobRequisitionItem.ID = jri.ID;
  272. tOut.Date = lastMovement is not null ? lastMovement.Date.AddTicks(1) : entity.ReceivedDate;
  273. tOut.Issued = qty;
  274. tOut.OrderItem.ID = entity.ID;
  275. tOut.Notes = "Internal transfer from cancelled requisition";
  276. tOut.System = true;
  277. tOut.Cost = entity.Cost;
  278. tOut.Transaction = transactionID;
  279. tOut.Type = StockMovementType.TransferOut;
  280. var tIn = movement.CreateMovement();
  281. tIn.Transaction = transactionID;
  282. tIn.Date = tOut.Date.AddTicks(1);
  283. tIn.Received = qty;
  284. tIn.OrderItem.ID = entity.ID;
  285. tOut.Notes = "Internal transfer from cancelled requisition";
  286. tOut.System = true;
  287. tIn.Cost = entity.Cost;
  288. tIn.Type = StockMovementType.TransferIn;
  289. movements.Add(tOut);
  290. movements.Add(tIn);
  291. }
  292. private static StockMovement CreateStockMovement(
  293. List<StockMovement> movements,
  294. PurchaseOrderItem entity,
  295. Guid locationID,
  296. IJob? job, IJobRequisitionItem? jri,
  297. double cost, Guid transactionID)
  298. {
  299. var movement = new StockMovement();
  300. movement.Product.ID = entity.Product.ID;
  301. movement.Location.ID = locationID;
  302. movement.Style.ID = entity.Style.ID;
  303. if(job is not null)
  304. {
  305. movement.Job.ID = job.ID;
  306. }
  307. movement.Dimensions.CopyFrom(entity.Dimensions);
  308. var lastMovement = movements.Count > 0 ? movements[^1] : null;
  309. movement.Date = lastMovement is not null ? lastMovement.Date.AddTicks(1) : entity.ReceivedDate;
  310. movement.Employee.ID = Guid.Empty;
  311. movement.Cost = cost;
  312. movement.Transaction = transactionID;
  313. if (jri is not null)
  314. {
  315. movement.JobRequisitionItem.ID = jri.ID;
  316. }
  317. movements.Add(movement);
  318. return movement;
  319. }
  320. private static StockMovement CreateReceive(List<StockMovement> movements, PurchaseOrderItem entity, Guid locationid, IJob? job, IJobRequisitionItem? jri, double qty, double cost, Guid transactionID)
  321. {
  322. var movement = new StockMovement();
  323. movement.Transaction = transactionID;
  324. movement.Product.ID = entity.Product.ID;
  325. if(job is not null)
  326. {
  327. movement.Job.ID = job.ID;
  328. }
  329. movement.Location.ID = locationid;
  330. movement.Style.ID = entity.Style.ID;
  331. movement.Dimensions.CopyFrom(entity.Dimensions);
  332. movement.Date = entity.ReceivedDate;
  333. movement.Received = qty;
  334. movement.Employee.ID = Guid.Empty;
  335. movement.OrderItem.ID = entity.ID;
  336. movement.Notes = string.Format("Received on PO {0}", entity.PurchaseOrderLink.PONumber);
  337. movement.Cost = cost;
  338. movement.Type = StockMovementType.Receive;
  339. if (jri is not null)
  340. {
  341. movement.JobRequisitionItem.ID = jri.ID;
  342. }
  343. movements.Add(movement);
  344. return movement;
  345. }
  346. private void DeleteStockMovements(PurchaseOrderItem entity)
  347. {
  348. var movements = Provider.Query(
  349. new Filter<StockMovement>(x => x.Transaction)
  350. .InQuery(new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID), x => x.Transaction),
  351. Columns.None<StockMovement>().Add(x => x.ID)
  352. ).ToArray<StockMovement>();
  353. if (movements.Length > 0)
  354. FindSubStore<StockMovement>().Delete(movements, "Purchase Order Item marked as Unreceived");
  355. }
  356. protected override void AfterSave(PurchaseOrderItem entity)
  357. {
  358. base.AfterSave(entity);
  359. if (entity.HasOriginalValue(x=>x.ReceivedDate))
  360. {
  361. if (entity.ReceivedDate.IsEmpty())
  362. DeleteStockMovements(entity);
  363. else
  364. {
  365. var original = entity.GetOriginalValue(x => x.ReceivedDate);
  366. if(original == DateTime.MinValue)
  367. {
  368. var item = Provider.Query(
  369. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  370. LookupFactory.RequiredColumns<PurchaseOrderItem>())
  371. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  372. if(item is not null)
  373. CreateStockMovements(item);
  374. }
  375. else
  376. {
  377. var item = Provider.Query(
  378. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  379. Columns.None<PurchaseOrderItem>().Add(x => x.ID)
  380. .Add(x => x.ReceivedDate)
  381. .Add(x => x.Cost))
  382. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  383. if(item is not null)
  384. UpdateStockMovements(item);
  385. }
  386. }
  387. }
  388. }
  389. private Guid GetJobRequisitionID(PurchaseOrderItem entity)
  390. {
  391. var jri = Provider.Query(
  392. new Filter<PurchaseOrderItemAllocation>(x => x.Item.ID).IsEqualTo(entity.ID),
  393. Columns.Required<PurchaseOrderItemAllocation>())
  394. .Rows
  395. .FirstOrDefault()?
  396. .Get<PurchaseOrderItemAllocation, Guid>(x => x.JobRequisitionItem.ID) ?? Guid.Empty;
  397. return jri;
  398. }
  399. protected override void BeforeDelete(PurchaseOrderItem entity)
  400. {
  401. base.BeforeDelete(entity);
  402. DeleteStockMovements(entity);
  403. }
  404. }