PurchaseOrderItemStore.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. namespace Comal.Stores
  8. {
  9. internal class PurchaseOrderItemStore : BaseStore<PurchaseOrderItem>
  10. {
  11. private void UpdateStockMovements(PurchaseOrderItem entity)
  12. {
  13. if (!entity.Product.IsValid())
  14. {
  15. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product.ID is blank!");
  16. return;
  17. }
  18. var locationid = entity.StockLocation.ID;
  19. var locationValid = entity.StockLocation.IsValid();
  20. var movementtask = new Task<List<StockMovement>>(() =>
  21. {
  22. var result = Provider.Query(
  23. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID),
  24. new Columns<StockMovement>(
  25. x => x.ID,
  26. x => x.Date,
  27. x => x.Product.ID,
  28. x => x.Received,
  29. x => x.Employee.ID,
  30. x => x.OrderItem.ID,
  31. x => x.Job.ID,
  32. x => x.Location.ID,
  33. x => x.Dimensions.Unit.ID,
  34. x => x.Dimensions.Unit.Formula,
  35. x => x.Dimensions.Unit.Format,
  36. x => x.Dimensions.Quantity,
  37. x => x.Dimensions.Length,
  38. x => x.Dimensions.Width,
  39. x => x.Dimensions.Height,
  40. x => x.Dimensions.Weight,
  41. x => x.Notes,
  42. x => x.Cost,
  43. x => x.Dimensions.Unit.HasHeight,
  44. x => x.Dimensions.Unit.HasLength,
  45. x => x.Dimensions.Unit.HasWidth,
  46. x => x.Dimensions.Unit.HasWeight,
  47. x => x.Dimensions.Unit.HasQuantity,
  48. x => x.Dimensions.Unit.Formula,
  49. x => x.Dimensions.Unit.Format,
  50. x => x.Dimensions.Unit.Code,
  51. x => x.Dimensions.Unit.Description
  52. )
  53. ).Rows.Select(x => x.ToObject<StockMovement>()).ToList();
  54. if (!result.Any())
  55. result.Add(new StockMovement());
  56. return result;
  57. });
  58. movementtask.Start();
  59. var producttask = new Task<CoreRow?>(() =>
  60. {
  61. return Provider.Query(
  62. new Filter<Product>(x => x.ID).IsEqualTo(entity.Product.ID),
  63. new Columns<Product>(
  64. x => x.ID,
  65. x => x.DefaultLocation.ID,
  66. x => x.Warehouse.ID,
  67. x => x.DefaultInstance.Dimensions.Unit.ID,
  68. x => x.DefaultInstance.Dimensions.Unit.Formula,
  69. x => x.DefaultInstance.Dimensions.Unit.Format,
  70. x => x.DefaultInstance.Dimensions.Quantity,
  71. x => x.DefaultInstance.Dimensions.Length,
  72. x => x.DefaultInstance.Dimensions.Width,
  73. x => x.DefaultInstance.Dimensions.Height,
  74. x => x.DefaultInstance.Dimensions.Weight,
  75. x => x.NonStock,
  76. x => x.DefaultInstance.Dimensions.Unit.HasHeight,
  77. x => x.DefaultInstance.Dimensions.Unit.HasLength,
  78. x => x.DefaultInstance.Dimensions.Unit.HasWidth,
  79. x => x.DefaultInstance.Dimensions.Unit.HasWeight,
  80. x => x.DefaultInstance.Dimensions.Unit.HasQuantity,
  81. x => x.DefaultInstance.Dimensions.Unit.Formula,
  82. x => x.DefaultInstance.Dimensions.Unit.Format,
  83. x => x.DefaultInstance.Dimensions.Unit.Code,
  84. x => x.DefaultInstance.Dimensions.Unit.Description,
  85. x => x.FreeStock,
  86. x => x.AverageCost
  87. )
  88. ).Rows.FirstOrDefault();
  89. });
  90. producttask.Start();
  91. var locationtask = new Task<CoreTable>(() =>
  92. {
  93. return Provider.Query(
  94. new Filter<StockLocation>(x => x.Default).IsEqualTo(true),
  95. new Columns<StockLocation>(x => x.ID, x => x.Warehouse.ID, x => x.Warehouse.Default)
  96. );
  97. });
  98. locationtask.Start();
  99. Task.WaitAll(movementtask, producttask, locationtask);
  100. var movements = movementtask.Result;
  101. var productrow = producttask.Result;
  102. var defaultlocations = locationtask.Result;
  103. if (entity.Qty == 0)
  104. {
  105. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem Qty is blank!");
  106. return;
  107. }
  108. if (productrow is null)
  109. {
  110. Logger.Send(LogType.Information, UserID, "Cannot Find PurchaseOrderItem.Product.ID!");
  111. return;
  112. }
  113. if (productrow.Get<Product, bool>(x => x.NonStock))
  114. {
  115. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product is marked as Non Stock!");
  116. return;
  117. }
  118. if (!locationValid)
  119. {
  120. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Location.ID is blank!");
  121. var productlocationid = productrow.EntityLinkID<Product, StockLocationLink>(x => x.DefaultLocation) ?? Guid.Empty;
  122. if (productlocationid != Guid.Empty)
  123. {
  124. Logger.Send(LogType.Information, UserID, "- Using Product.DefaultLocation.ID as location");
  125. locationid = productlocationid;
  126. }
  127. else
  128. {
  129. var productwarehouseid = productrow.Get<Product, Guid>(c => c.Warehouse.ID);
  130. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, Guid>(c => c.Warehouse.ID) == productwarehouseid);
  131. if (row != null)
  132. {
  133. Logger.Send(LogType.Information, UserID, "- Using Product.Warehouse -> Default as location");
  134. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  135. }
  136. }
  137. if (locationid == Guid.Empty)
  138. {
  139. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, bool>(c => c.Warehouse.Default));
  140. if (row != null)
  141. {
  142. Logger.Send(LogType.Information, UserID, "- Using Default Warehouse -> Default Location as location");
  143. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  144. }
  145. }
  146. if (locationid == Guid.Empty)
  147. {
  148. Logger.Send(LogType.Information, UserID, "- Cannot find Location : Skipping Movement Creation");
  149. return;
  150. }
  151. }
  152. if (
  153. (entity.Dimensions.Unit.ID == Guid.Empty)
  154. && (entity.Dimensions.Height == 0)
  155. && (entity.Dimensions.Width == 0)
  156. && (entity.Dimensions.Length == 0)
  157. && (entity.Dimensions.Weight == 0)
  158. )
  159. {
  160. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Unit Size is zero!");
  161. entity.Dimensions.CopyFrom(productrow.ToObject<Product>().DefaultInstance.Dimensions);
  162. }
  163. if (entity.Job.ID == Guid.Empty)
  164. {
  165. var product = productrow.ToObject<Product>();
  166. var freeqty = product.FreeStock;
  167. var freeavg = product.AverageCost;
  168. var freecost = product.FreeStock * freeavg;
  169. var poqty = entity.Qty * (Math.Abs(entity.Dimensions.Value) > 0.0001F ? entity.Dimensions.Value : 1.0F);
  170. var pocost = entity.Cost * poqty;
  171. var totalqty = freeqty + poqty;
  172. var totalcost = freecost + pocost;
  173. var averagecost = Math.Abs(totalqty) > 0.0001F
  174. ? totalcost / totalqty
  175. : pocost;
  176. if (Math.Abs(averagecost - freeavg) > 0.0001F)
  177. {
  178. product.AverageCost = averagecost;
  179. FindSubStore<Product>().Save(product,
  180. $"Updated Average Cost: " +
  181. $"({freeqty} @ {freeavg:C2}) + ({poqty} @ {entity.Cost:C2}) = {totalcost:C2} / {totalqty}"
  182. );
  183. }
  184. }
  185. foreach (var movement in movements)
  186. {
  187. movement.Batch.Type = StockMovementBatchType.Receipt;
  188. movement.Date = entity.ReceivedDate;
  189. movement.Product.ID = entity.Product.ID;
  190. movement.Received = entity.Qty;
  191. movement.Employee.ID = Guid.Empty;
  192. movement.OrderItem.ID = entity.ID;
  193. movement.Job.ID = entity.Job.ID;
  194. movement.Location.ID = locationid;
  195. movement.Style.ID = entity.Style.ID;
  196. movement.Style.Code = entity.Style.Code;
  197. movement.Style.Description = entity.Style.Description;
  198. movement.Notes = string.Format("Received on PO {0}", entity.PurchaseOrderLink.PONumber);
  199. movement.Cost = entity.Cost;
  200. movement.Type = StockMovementType.Receive;
  201. movement.Dimensions.Unit.ID = entity.Dimensions.Unit.ID;
  202. movement.Dimensions.Height = entity.Dimensions.Height;
  203. movement.Dimensions.Length = entity.Dimensions.Length;
  204. movement.Dimensions.Width = entity.Dimensions.Width;
  205. movement.Dimensions.Weight = entity.Dimensions.Weight;
  206. movement.Dimensions.Quantity = entity.Dimensions.Quantity;
  207. movement.Dimensions.UnitSize = entity.Dimensions.UnitSize;
  208. movement.Dimensions.Value = entity.Dimensions.Value;
  209. movement.Dimensions.UnitSize = entity.Dimensions.UnitSize;
  210. }
  211. var updates = movements.Where(x => x.IsChanged());
  212. if (updates.Any())
  213. FindSubStore<StockMovement>().Save(updates, "Updated by Purchase Order Modification");
  214. }
  215. private void DeleteStockMovements(PurchaseOrderItem entity)
  216. {
  217. var movements = Provider.Query(
  218. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID),
  219. new Columns<StockMovement>(x => x.ID)
  220. ).Rows.Select(x => x.ToObject<StockMovement>());
  221. if (movements.Any())
  222. FindSubStore<StockMovement>().Delete(movements, "Purchase Order Item marked as Unreceived");
  223. }
  224. protected override void AfterSave(PurchaseOrderItem entity)
  225. {
  226. base.AfterSave(entity);
  227. if (entity.HasOriginalValue<PurchaseOrderItem,DateTime>(x=>x.ReceivedDate))
  228. {
  229. if (entity.ReceivedDate.IsEmpty())
  230. DeleteStockMovements(entity);
  231. else
  232. {
  233. var item = Provider
  234. .Query(new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID))
  235. .Rows.FirstOrDefault()?.ToObject<PurchaseOrderItem>();
  236. if (item != null)
  237. {
  238. UpdateStockMovements(item);
  239. UpdateJobRequiItems(item);
  240. }
  241. }
  242. }
  243. }
  244. private void UpdateJobRequiItems(PurchaseOrderItem entity)
  245. {
  246. var table = Provider.Query(
  247. new Filter<JobRequisitionItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  248. new Columns<JobRequisitionItem>(x => x.ID, x => x.Status)
  249. );
  250. if (table.Rows.Any())
  251. {
  252. JobRequisitionItem item = table.Rows.FirstOrDefault().ToObject<JobRequisitionItem>();
  253. if (item.Status == JobRequisitionItemStatus.TreatmentOnOrder)
  254. item.Status = JobRequisitionItemStatus.TreatmentReceived;
  255. else
  256. item.Status = JobRequisitionItemStatus.Received;
  257. Provider.Save(item);
  258. }
  259. }
  260. protected override void BeforeDelete(PurchaseOrderItem entity)
  261. {
  262. base.BeforeDelete(entity);
  263. DeleteStockMovements(entity);
  264. }
  265. protected override void AfterDelete(PurchaseOrderItem entity)
  266. {
  267. base.AfterDelete(entity);
  268. RemoveJobRequisitionItemLink(entity);
  269. }
  270. private void RemoveJobRequisitionItemLink(PurchaseOrderItem entity)
  271. {
  272. CoreTable table = Provider.Query<JobRequisitionItem>
  273. (
  274. new Filter<JobRequisitionItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  275. new Columns<JobRequisitionItem>(x => x.ID, x => x.PurchaseOrderItem.PurchaseOrderLink.PONumber, x => x.Status)
  276. );
  277. if (table.Rows.Any())
  278. {
  279. JobRequisitionItem item = table.Rows.FirstOrDefault().ToObject<JobRequisitionItem>();
  280. item.PurchaseOrderItem.PurchaseOrderLink.PONumber = "";
  281. item.Status = JobRequisitionItemStatus.NotChecked;
  282. Provider.Save<JobRequisitionItem>(item);
  283. }
  284. }
  285. }
  286. }