PurchaseOrderItemStore.cs 15 KB

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