PurchaseOrderItemStore.cs 18 KB

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