PurchaseOrderItemStore.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. namespace Comal.Stores;
  9. internal class PurchaseOrderItemStore : BaseStore<PurchaseOrderItem>
  10. {
  11. private Columns<PurchaseOrderItem> RequiredColumns()
  12. {
  13. return new Columns<PurchaseOrderItem>(x => x.ID)
  14. .Add(x => x.Product.ID)
  15. .Add(x => x.Qty)
  16. .Add(x => x.Cost)
  17. .Add(x => x.StockLocation.ID)
  18. .Add(x => x.Style.ID)
  19. .Add(x => x.Job.ID)
  20. .Add(x => x.ReceivedDate)
  21. .Add(x => x.PurchaseOrderLink.PONumber)
  22. .AddDimensionsColumns(x => x.Dimensions, Dimensions.ColumnsType.Data);
  23. }
  24. private void UpdateStockMovements(PurchaseOrderItem entity)
  25. {
  26. var movements = Provider.Query<StockMovement>(
  27. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID))
  28. .ToArray<StockMovement>();
  29. foreach(var mvt in movements)
  30. {
  31. mvt.Date = entity.ReceivedDate;
  32. mvt.Cost = entity.Cost;
  33. }
  34. FindSubStore<StockMovement>().Save(movements, "Updated by purchase order modification");
  35. }
  36. private void CreateStockMovements(PurchaseOrderItem entity)
  37. {
  38. if (!entity.Product.IsValid())
  39. {
  40. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product.ID is blank!");
  41. return;
  42. }
  43. if (entity.Qty == 0)
  44. {
  45. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem Qty is blank!");
  46. return;
  47. }
  48. var locationid = entity.StockLocation.ID;
  49. var locationValid = entity.StockLocation.IsValid();
  50. var jriTask = Task<Guid>.Run(() =>
  51. {
  52. return Provider.Query(
  53. new Filter<JobRequisitionItem>(x => x.ID).InQuery(
  54. new Filter<JobRequisitionItemPurchaseOrderItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  55. x => x.JobRequisitionItem.ID),
  56. new Columns<JobRequisitionItem>(x => x.ID)
  57. .Add(x => x.Status)
  58. .Add(x=>x.Qty)
  59. )
  60. .ToObjects<JobRequisitionItem>();
  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);
  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. var totalqty = freeqty + poqty;
  221. var totalcost = freecost + pocost;
  222. var averagecost = Math.Abs(totalqty) > 0.0001F
  223. ? totalcost / totalqty
  224. : pocost;
  225. if (Math.Abs(averagecost - freeavg) > 0.0001F)
  226. {
  227. instance.AverageCost = averagecost;
  228. FindSubStore<ProductInstance>().Save(instance,
  229. $"Updated Average Cost: " +
  230. $"({freeqty} @ {freeavg:C2}) + ({poqty} @ {entity.Cost:C2}) = {totalcost:C2} / {totalqty}"
  231. );
  232. }
  233. }
  234. var batch = new StockMovementBatch
  235. {
  236. Type = StockMovementBatchType.Receipt,
  237. TimeStamp = DateTime.Now,
  238. Notes = $"Received on PO"
  239. };
  240. var movements = new List<StockMovement>();
  241. var _pototal = entity.Qty;
  242. foreach (var jri in jris)
  243. {
  244. CreateMovement(entity, locationid, movements, jri, jri.Qty);
  245. _pototal -= jri.Qty;
  246. }
  247. if (!_pototal.IsEffectivelyEqual(0.0F))
  248. CreateMovement(entity, locationid, movements, null, _pototal);
  249. FindSubStore<StockMovementBatch>().Save(batch, "Received on PO");
  250. foreach(var mvt in movements)
  251. {
  252. mvt.Batch.ID = batch.ID;
  253. }
  254. FindSubStore<StockMovement>().Save(movements, "Updated by Purchase Order Modification");
  255. }
  256. private static void CreateMovement(PurchaseOrderItem entity, Guid locationid, List<StockMovement> movements, JobRequisitionItem jri, double qty)
  257. {
  258. var movement = new StockMovement();
  259. movement.Product.ID = entity.Product.ID;
  260. movement.Job.ID = entity.Job.ID;
  261. movement.Location.ID = locationid;
  262. movement.Style.ID = entity.Style.ID;
  263. movement.Dimensions.CopyFrom(entity.Dimensions);
  264. movement.Date = entity.ReceivedDate;
  265. movement.Received = qty;
  266. movement.Employee.ID = Guid.Empty;
  267. movement.OrderItem.ID = entity.ID;
  268. movement.Notes = string.Format("Received on PO {0}", entity.PurchaseOrderLink.PONumber);
  269. movement.Cost = entity.Cost;
  270. movement.Type = StockMovementType.Receive;
  271. movements.Add(movement);
  272. if (jri is not null)
  273. {
  274. movement.JobRequisitionItem.ID = jri.ID;
  275. if (!jri.Cancelled.IsEmpty())
  276. {
  277. // We need to create an immediate transfer in and out of the job requisition item.
  278. var tOut = movement.CreateMovement();
  279. tOut.JobRequisitionItem.ID = jri.ID;
  280. tOut.Date = entity.ReceivedDate;
  281. tOut.Issued = jri.Qty;
  282. tOut.OrderItem.ID = entity.ID;
  283. tOut.Notes = "Internal transfer from cancelled requisition";
  284. tOut.System = true;
  285. tOut.Cost = entity.Cost;
  286. tOut.Type = StockMovementType.TransferOut;
  287. var tIn = movement.CreateMovement();
  288. tIn.Transaction = tOut.Transaction;
  289. tIn.Date = entity.ReceivedDate;
  290. tIn.Received = jri.Qty;
  291. tIn.OrderItem.ID = entity.ID;
  292. tOut.Notes = "Internal transfer from cancelled requisition";
  293. tOut.System = true;
  294. tIn.Cost = entity.Cost;
  295. tIn.Type = StockMovementType.TransferIn;
  296. movements.Add(tOut);
  297. movements.Add(tIn);
  298. }
  299. }
  300. }
  301. private void DeleteStockMovements(PurchaseOrderItem entity)
  302. {
  303. var movements = Provider.Query(
  304. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID),
  305. new Columns<StockMovement>(x => x.ID)
  306. ).Rows.Select(x => x.ToObject<StockMovement>());
  307. if (movements.Any())
  308. FindSubStore<StockMovement>().Delete(movements, "Purchase Order Item marked as Unreceived");
  309. }
  310. protected override void AfterSave(PurchaseOrderItem entity)
  311. {
  312. base.AfterSave(entity);
  313. if (entity.HasOriginalValue(x=>x.ReceivedDate))
  314. {
  315. if (entity.ReceivedDate.IsEmpty())
  316. {
  317. DeleteStockMovements(entity);
  318. UpdateJobRequiItems(entity, JobRequisitionItemAction.Updated);
  319. }
  320. else
  321. {
  322. var original = entity.GetOriginalValue(x => x.ReceivedDate);
  323. if(original == DateTime.MinValue)
  324. {
  325. var item = Provider.Query(
  326. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  327. RequiredColumns())
  328. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  329. if(item is not null)
  330. {
  331. CreateStockMovements(item);
  332. UpdateJobRequiItems(item, JobRequisitionItemAction.Updated);
  333. }
  334. }
  335. else
  336. {
  337. var item = Provider.Query(
  338. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  339. new Columns<PurchaseOrderItem>(x => x.ID)
  340. .Add(x => x.ReceivedDate)
  341. .Add(x => x.Cost))
  342. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  343. if(item is not null)
  344. {
  345. UpdateStockMovements(item);
  346. UpdateJobRequiItems(item, JobRequisitionItemAction.Updated);
  347. }
  348. }
  349. }
  350. }
  351. else if(entity.HasOriginalValue(x => x.ID)
  352. || entity.HasOriginalValue(x => x.Product.ID)
  353. || entity.HasOriginalValue(x => x.Qty))
  354. {
  355. UpdateJobRequiItems(entity, entity.HasOriginalValue(x => x.ID) ? JobRequisitionItemAction.Created : JobRequisitionItemAction.Updated);
  356. }
  357. }
  358. private Guid GetJobRequisitionID(PurchaseOrderItem entity)
  359. {
  360. var jri = Provider.Query(
  361. new Filter<JobRequisitionItemPurchaseOrderItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  362. new Columns<JobRequisitionItemPurchaseOrderItem>(x => x.JobRequisitionItem.ID))
  363. .Rows
  364. .FirstOrDefault()?
  365. .Get<JobRequisitionItemPurchaseOrderItem, Guid>(x => x.JobRequisitionItem.ID) ?? Guid.Empty;
  366. return jri;
  367. }
  368. private void UpdateJobRequiItems(PurchaseOrderItem entity, JobRequisitionItemAction action)
  369. {
  370. var id = GetJobRequisitionID(entity);
  371. if (id != Guid.Empty)
  372. JobRequisitionItemStore.UpdateStatus(this, id, action);
  373. }
  374. private Guid _jobrequisitionitemid = Guid.Empty;
  375. protected override void BeforeDelete(PurchaseOrderItem entity)
  376. {
  377. base.BeforeDelete(entity);
  378. DeleteStockMovements(entity);
  379. _jobrequisitionitemid = GetJobRequisitionID(entity);
  380. }
  381. protected override void AfterDelete(PurchaseOrderItem entity)
  382. {
  383. base.AfterDelete(entity);
  384. if (_jobrequisitionitemid != Guid.Empty)
  385. JobRequisitionItemStore.UpdateStatus(this, _jobrequisitionitemid, JobRequisitionItemAction.Deleted);
  386. }
  387. }