PurchaseOrderItemStore.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.Dimensions.Unit.ID,
  68. x => x.Dimensions.Unit.Formula,
  69. x => x.Dimensions.Unit.Format,
  70. x => x.Dimensions.Quantity,
  71. x => x.Dimensions.Length,
  72. x => x.Dimensions.Width,
  73. x => x.Dimensions.Height,
  74. x => x.Dimensions.Weight,
  75. x => x.NonStock,
  76. x => x.Dimensions.Unit.HasHeight,
  77. x => x.Dimensions.Unit.HasLength,
  78. x => x.Dimensions.Unit.HasWidth,
  79. x => x.Dimensions.Unit.HasWeight,
  80. x => x.Dimensions.Unit.HasQuantity,
  81. x => x.Dimensions.Unit.Formula,
  82. x => x.Dimensions.Unit.Format,
  83. x => x.Dimensions.Unit.Code,
  84. x => x.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 == 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. if (productrow != null)
  122. {
  123. var productlocationid = productrow.EntityLinkID<Product, StockLocationLink>(x => x.DefaultLocation) ?? Guid.Empty;
  124. if (productlocationid != Guid.Empty)
  125. {
  126. Logger.Send(LogType.Information, UserID, "- Using Product.DefaultLocation.ID as location");
  127. locationid = productlocationid;
  128. }
  129. else
  130. {
  131. var productwarehouseid = productrow.Get<Product, Guid>(c => c.Warehouse.ID);
  132. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, Guid>(c => c.Warehouse.ID) == productwarehouseid);
  133. if (row != null)
  134. {
  135. Logger.Send(LogType.Information, UserID, "- Using Product.Warehouse -> Default as location");
  136. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  137. }
  138. }
  139. }
  140. if (locationid == Guid.Empty)
  141. {
  142. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, bool>(c => c.Warehouse.Default));
  143. if (row != null)
  144. {
  145. Logger.Send(LogType.Information, UserID, "- Using Default Warehouse -> Default Location as location");
  146. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  147. }
  148. }
  149. if (locationid == Guid.Empty)
  150. {
  151. Logger.Send(LogType.Information, UserID, "- Cannot find Location : Skipping Movement Creation");
  152. return;
  153. }
  154. }
  155. if (
  156. (entity.Dimensions.Unit.ID == Guid.Empty)
  157. && (entity.Dimensions.Height == 0)
  158. && (entity.Dimensions.Width == 0)
  159. && (entity.Dimensions.Length == 0)
  160. && (entity.Dimensions.Weight == 0)
  161. )
  162. {
  163. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Unit Size is zero!");
  164. entity.Dimensions.CopyFrom(productrow.ToObject<Product>().Dimensions);
  165. }
  166. if (entity.Job.ID == Guid.Empty)
  167. {
  168. var product = productrow.ToObject<Product>();
  169. var freeqty = product.FreeStock;
  170. var freeavg = product.AverageCost;
  171. var freecost = product.FreeStock * freeavg;
  172. var poqty = entity.Qty * (Math.Abs(entity.Dimensions.Value) > 0.0001F ? entity.Dimensions.Value : 1.0F);
  173. var pocost = entity.Cost * poqty;
  174. var totalqty = freeqty + poqty;
  175. var totalcost = freecost + pocost;
  176. var averagecost = Math.Abs(totalqty) > 0.0001F
  177. ? totalcost / totalqty
  178. : pocost;
  179. if (Math.Abs(averagecost - freeavg) > 0.0001F)
  180. {
  181. product.AverageCost = averagecost;
  182. FindSubStore<Product>().Save(product,
  183. $"Updated Average Cost: " +
  184. $"({freeqty} @ {freeavg:C2}) + ({poqty} @ {entity.Cost:C2}) = {totalcost:C2} / {totalqty}"
  185. );
  186. }
  187. }
  188. foreach (var movement in movements)
  189. {
  190. movement.Batch.Type = StockMovementBatchType.Receipt;
  191. movement.Date = entity.ReceivedDate;
  192. movement.Product.ID = entity.Product.ID;
  193. movement.Received = entity.Qty;
  194. movement.Employee.ID = Guid.Empty;
  195. movement.OrderItem.ID = entity.ID;
  196. movement.Job.ID = entity.Job.ID;
  197. movement.Location.ID = locationid;
  198. movement.Style.ID = entity.Style.ID;
  199. movement.Style.Code = entity.Style.Code;
  200. movement.Style.Description = entity.Style.Description;
  201. movement.Notes = string.Format("Received on PO {0}", entity.PurchaseOrderLink.PONumber);
  202. movement.Cost = entity.Cost;
  203. movement.Type = StockMovementType.Receive;
  204. movement.Dimensions.Unit.ID = entity.Dimensions.Unit.ID;
  205. movement.Dimensions.Height = entity.Dimensions.Height;
  206. movement.Dimensions.Length = entity.Dimensions.Length;
  207. movement.Dimensions.Width = entity.Dimensions.Width;
  208. movement.Dimensions.Weight = entity.Dimensions.Weight;
  209. movement.Dimensions.Quantity = entity.Dimensions.Quantity;
  210. movement.Dimensions.UnitSize = entity.Dimensions.UnitSize;
  211. movement.Dimensions.Value = entity.Dimensions.Value;
  212. movement.Dimensions.UnitSize = entity.Dimensions.UnitSize;
  213. }
  214. var updates = movements.Where(x => x.IsChanged());
  215. if (updates.Any())
  216. FindSubStore<StockMovement>().Save(updates, "Updated by Purchase Order Modification");
  217. }
  218. private void DeleteStockMovements(PurchaseOrderItem entity)
  219. {
  220. var movements = Provider.Query(
  221. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID),
  222. new Columns<StockMovement>(x => x.ID)
  223. ).Rows.Select(x => x.ToObject<StockMovement>());
  224. if (movements.Any())
  225. FindSubStore<StockMovement>().Delete(movements, "Purchase Order Item marked as Unreceived");
  226. }
  227. protected override void AfterSave(PurchaseOrderItem entity)
  228. {
  229. base.AfterSave(entity);
  230. if (entity.HasOriginalValue<PurchaseOrderItem,DateTime>(x=>x.ReceivedDate))
  231. {
  232. if (entity.ReceivedDate.IsEmpty())
  233. DeleteStockMovements(entity);
  234. else
  235. {
  236. var item = Provider
  237. .Query(new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID))
  238. .Rows.FirstOrDefault()?.ToObject<PurchaseOrderItem>();
  239. if (item != null)
  240. {
  241. UpdateStockMovements(item);
  242. UpdateJobRequiItems(item);
  243. }
  244. }
  245. }
  246. }
  247. private void UpdateJobRequiItems(PurchaseOrderItem entity)
  248. {
  249. var table = Provider.Query(
  250. new Filter<JobRequisitionItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  251. new Columns<JobRequisitionItem>(x => x.ID, x => x.Status)
  252. );
  253. if (table.Rows.Any())
  254. {
  255. JobRequisitionItem item = table.Rows.FirstOrDefault().ToObject<JobRequisitionItem>();
  256. if (item.Status == JobRequisitionItemStatus.TreatmentOnOrder)
  257. item.Status = JobRequisitionItemStatus.TreatmentReceived;
  258. else
  259. item.Status = JobRequisitionItemStatus.Received;
  260. Provider.Save(item);
  261. }
  262. }
  263. protected override void BeforeDelete(PurchaseOrderItem entity)
  264. {
  265. base.BeforeDelete(entity);
  266. DeleteStockMovements(entity);
  267. }
  268. protected override void AfterDelete(PurchaseOrderItem entity)
  269. {
  270. base.AfterDelete(entity);
  271. RemoveJobRequisitionItemLink(entity);
  272. }
  273. private void RemoveJobRequisitionItemLink(PurchaseOrderItem entity)
  274. {
  275. CoreTable table = Provider.Query<JobRequisitionItem>
  276. (
  277. new Filter<JobRequisitionItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  278. new Columns<JobRequisitionItem>(x => x.ID, x => x.PurchaseOrderItem.PurchaseOrderLink.PONumber, x => x.Status)
  279. );
  280. if (table.Rows.Any())
  281. {
  282. JobRequisitionItem item = table.Rows.FirstOrDefault().ToObject<JobRequisitionItem>();
  283. item.PurchaseOrderItem.PurchaseOrderLink.PONumber = "";
  284. item.Status = JobRequisitionItemStatus.NotChecked;
  285. Provider.Save<JobRequisitionItem>(item);
  286. }
  287. }
  288. }
  289. }