PurchaseOrderItemStore.cs 17 KB

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