PurchaseOrderItemStore.cs 16 KB

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