PurchaseOrderItemStore.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Comal.Classes;
  5. using InABox.Core;
  6. using PRSStores;
  7. using System;
  8. using InABox.Database;
  9. using InABox.Scripting;
  10. using NPOI.SS.Formula.Functions;
  11. using Columns = InABox.Core.Columns;
  12. namespace Comal.Stores;
  13. internal class PurchaseOrderItemStore : BaseStore<PurchaseOrderItem>
  14. {
  15. static PurchaseOrderItemStore()
  16. {
  17. RegisterListener<ProductDimensionUnit>(ReloadProductDimensionUnitCache);
  18. }
  19. private static Dictionary<Guid, ScriptDocument>? _productdimensionunitcache = null;
  20. private static void ReloadProductDimensionUnitCache(Guid[]? ids)
  21. {
  22. if (_productdimensionunitcache == null)
  23. _productdimensionunitcache = new Dictionary<Guid, ScriptDocument>();
  24. var scripts = DbFactory.NewProvider(Logger.Main).Query(
  25. ids != null
  26. ? new Filter<ProductDimensionUnit>(x => x.ID).InList(ids)
  27. : null,
  28. Columns.None<ProductDimensionUnit>()
  29. .Add(x => x.ID)
  30. .Add(x => x.Conversion)
  31. ).ToDictionary<ProductDimensionUnit, Guid, String>(x => x.ID, x => x.Conversion);
  32. foreach (var id in scripts.Keys)
  33. {
  34. var doc = !String.IsNullOrWhiteSpace(scripts[id]) ? new ScriptDocument(scripts[id]) : null;
  35. if (doc?.Compile() == true)
  36. _productdimensionunitcache[id] = doc;
  37. else
  38. _productdimensionunitcache.Remove(id);
  39. }
  40. }
  41. private void TransformDimensions(PurchaseOrderItem item)
  42. {
  43. if (_productdimensionunitcache == null)
  44. ReloadProductDimensionUnitCache(null);
  45. if (_productdimensionunitcache?.TryGetValue(item.Dimensions.Unit.ID, out ScriptDocument? script) == true)
  46. script.Execute("Module",DimensionUnit.ConvertDimensionsMethodName(), [item]);
  47. }
  48. private void UpdateStockMovements(PurchaseOrderItem entity)
  49. {
  50. var movements = Provider.Query<StockMovement>(
  51. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID))
  52. .ToArray<StockMovement>();
  53. foreach(var mvt in movements)
  54. {
  55. mvt.Date = entity.ReceivedDate;
  56. mvt.Cost = entity.Cost;
  57. }
  58. FindSubStore<StockMovement>().Save(movements, "Updated by purchase order modification");
  59. }
  60. private void CreateStockMovements(PurchaseOrderItem entity)
  61. {
  62. if (!entity.Product.IsValid())
  63. {
  64. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product.ID is blank!");
  65. return;
  66. }
  67. if (entity.Qty == 0)
  68. {
  69. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem Qty is blank!");
  70. return;
  71. }
  72. var locationid = entity.StockLocation.ID;
  73. var locationValid = entity.StockLocation.IsValid();
  74. var jriTask = Task<Guid>.Run(() =>
  75. {
  76. return Provider.Query(
  77. new Filter<JobRequisitionItem>(x => x.ID).InQuery(
  78. new Filter<JobRequisitionItemPurchaseOrderItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  79. x => x.JobRequisitionItem.ID),
  80. Columns.None<JobRequisitionItem>().Add(x => x.ID)
  81. .Add(x => x.Status)
  82. .Add(x=>x.Qty)
  83. )
  84. .ToObjects<JobRequisitionItem>();
  85. });
  86. var consigntask = Task<double>.Run(() =>
  87. {
  88. if (entity.Consignment.ID != Guid.Empty && !entity.Consignment.ExTax.IsEffectivelyEqual(0.0))
  89. {
  90. var values = Provider.Query(
  91. new Filter<PurchaseOrderItem>(x => x.Consignment.ID).IsEqualTo(entity.Consignment.ID),
  92. Columns.None<PurchaseOrderItem>().Add(x => x.ExTax)
  93. ).Rows.Select(r => r.Get<PurchaseOrderItem, double>(c => c.ExTax));
  94. return values.Sum(x => x);
  95. }
  96. return 0.0;
  97. });
  98. var instancetask = new Task<CoreRow?>(() =>
  99. {
  100. return Provider.Query(
  101. new Filter<ProductInstance>(x => x.Product.ID).IsEqualTo(entity.Product.ID)
  102. .And(x=>x.Style.ID).IsEqualTo(entity.Style.ID)
  103. .And(x => x.Dimensions).DimensionEquals(entity.Dimensions),
  104. Columns.Required<ProductInstance>().Add(
  105. x => x.ID,
  106. x => x.Product.NonStock,
  107. x => x.Product.DefaultLocation.ID,
  108. x => x.Product.Warehouse.ID,
  109. x => x.Dimensions.Unit.ID,
  110. x => x.Dimensions.Unit.Formula,
  111. x => x.Dimensions.Unit.Format,
  112. x => x.Dimensions.Quantity,
  113. x => x.Dimensions.Length,
  114. x => x.Dimensions.Width,
  115. x => x.Dimensions.Height,
  116. x => x.Dimensions.Weight,
  117. x => x.Dimensions.Unit.HasHeight,
  118. x => x.Dimensions.Unit.HasLength,
  119. x => x.Dimensions.Unit.HasWidth,
  120. x => x.Dimensions.Unit.HasWeight,
  121. x => x.Dimensions.Unit.HasQuantity,
  122. x => x.Dimensions.Unit.Formula,
  123. x => x.Dimensions.Unit.Format,
  124. x => x.Dimensions.Unit.Code,
  125. x => x.Dimensions.Unit.Description,
  126. x => x.FreeStock,
  127. x => x.AverageCost,
  128. x => x.LastCost
  129. )
  130. ).Rows.FirstOrDefault();
  131. });
  132. instancetask.Start();
  133. var producttask = new Task<CoreRow?>(() =>
  134. {
  135. return Provider.Query(
  136. new Filter<Product>(x => x.ID).IsEqualTo(entity.Product.ID),
  137. Columns.None<Product>().Add(
  138. x => x.ID,
  139. x => x.DefaultLocation.ID,
  140. x => x.Warehouse.ID,
  141. x => x.DefaultInstance.Dimensions.Unit.ID,
  142. x => x.DefaultInstance.Dimensions.Unit.Formula,
  143. x => x.DefaultInstance.Dimensions.Unit.Format,
  144. x => x.DefaultInstance.Dimensions.Quantity,
  145. x => x.DefaultInstance.Dimensions.Length,
  146. x => x.DefaultInstance.Dimensions.Width,
  147. x => x.DefaultInstance.Dimensions.Height,
  148. x => x.DefaultInstance.Dimensions.Weight,
  149. x => x.NonStock,
  150. x => x.DefaultInstance.Dimensions.Unit.HasHeight,
  151. x => x.DefaultInstance.Dimensions.Unit.HasLength,
  152. x => x.DefaultInstance.Dimensions.Unit.HasWidth,
  153. x => x.DefaultInstance.Dimensions.Unit.HasWeight,
  154. x => x.DefaultInstance.Dimensions.Unit.HasQuantity,
  155. x => x.DefaultInstance.Dimensions.Unit.Formula,
  156. x => x.DefaultInstance.Dimensions.Unit.Format,
  157. x => x.DefaultInstance.Dimensions.Unit.Code,
  158. x => x.DefaultInstance.Dimensions.Unit.Description
  159. )
  160. ).Rows.FirstOrDefault();
  161. });
  162. producttask.Start();
  163. var locationtask = new Task<CoreTable>(() =>
  164. {
  165. return Provider.Query(
  166. new Filter<StockLocation>(x => x.Default).IsEqualTo(true),
  167. Columns.None<StockLocation>().Add(x => x.ID, x => x.Warehouse.ID, x => x.Warehouse.Default)
  168. );
  169. });
  170. locationtask.Start();
  171. Task.WaitAll(producttask, locationtask, instancetask, jriTask, consigntask);
  172. var instancerow = instancetask.Result;
  173. var productrow = producttask.Result;
  174. var defaultlocations = locationtask.Result;
  175. var jris = jriTask.Result.ToArray();
  176. if (productrow is null)
  177. {
  178. Logger.Send(LogType.Information, UserID, "Cannot Find PurchaseOrderItem.Product.ID!");
  179. return;
  180. }
  181. if (productrow.Get<Product, bool>(x => x.NonStock))
  182. {
  183. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Product is marked as Non Stock!");
  184. return;
  185. }
  186. if (!locationValid)
  187. {
  188. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Location.ID is blank!");
  189. var productlocationid = productrow.EntityLinkID<Product, StockLocationLink>(x => x.DefaultLocation) ?? Guid.Empty;
  190. if (productlocationid != Guid.Empty)
  191. {
  192. Logger.Send(LogType.Information, UserID, "- Using Product.DefaultLocation.ID as location");
  193. locationid = productlocationid;
  194. }
  195. else
  196. {
  197. var productwarehouseid = productrow.Get<Product, Guid>(c => c.Warehouse.ID);
  198. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, Guid>(c => c.Warehouse.ID) == productwarehouseid);
  199. if (row != null)
  200. {
  201. Logger.Send(LogType.Information, UserID, "- Using Product.Warehouse -> Default as location");
  202. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  203. }
  204. }
  205. if (locationid == Guid.Empty)
  206. {
  207. var row = defaultlocations.Rows.FirstOrDefault(r => r.Get<StockLocation, bool>(c => c.Warehouse.Default));
  208. if (row != null)
  209. {
  210. Logger.Send(LogType.Information, UserID, "- Using Default Warehouse -> Default Location as location");
  211. locationid = row.Get<StockLocation, Guid>(x => x.ID);
  212. }
  213. }
  214. if (locationid == Guid.Empty)
  215. {
  216. Logger.Send(LogType.Information, UserID, "- Cannot find Location : Skipping Movement Creation");
  217. return;
  218. }
  219. }
  220. if (
  221. (entity.Dimensions.Unit.ID == Guid.Empty)
  222. && (entity.Dimensions.Height == 0)
  223. && (entity.Dimensions.Width == 0)
  224. && (entity.Dimensions.Length == 0)
  225. && (entity.Dimensions.Weight == 0)
  226. )
  227. {
  228. Logger.Send(LogType.Information, UserID, "PurchaseOrderItem.Unit Size is zero!");
  229. entity.Dimensions.CopyFrom(productrow.ToObject<Product>().DefaultInstance.Dimensions);
  230. }
  231. TransformDimensions(entity);
  232. if (entity.Job.ID == Guid.Empty)
  233. {
  234. var instance = instancerow?.ToObject<ProductInstance>();
  235. if (instance == null)
  236. {
  237. instance = new ProductInstance();
  238. instance.Product.ID = entity.Product.ID;
  239. instance.Style.ID = entity.Style.ID;
  240. instance.Dimensions.CopyFrom(entity.Dimensions);
  241. }
  242. instance.LastCost = entity.Cost;
  243. //var product = productrow.ToObject<Product>();
  244. var freeqty = instance.FreeStock;
  245. var freeavg = instance.AverageCost;
  246. var freecost = instance.FreeStock * freeavg;
  247. var poqty = entity.Qty * (Math.Abs(entity.Dimensions.Value) > 0.0001F ? entity.Dimensions.Value : 1.0F);
  248. var pocost = entity.Cost * poqty;
  249. if (!consigntask.Result.IsEffectivelyEqual(0.0) && !entity.Qty.IsEffectivelyEqual(0.0))
  250. pocost += entity.Qty * entity.Cost * entity.Consignment.ExTax / consigntask.Result;
  251. var totalqty = freeqty + poqty;
  252. var totalcost = freecost + pocost;
  253. var averagecost = Math.Abs(totalqty) > 0.0001F
  254. ? totalcost / totalqty
  255. : pocost;
  256. if (Math.Abs(averagecost - freeavg) > 0.0001F)
  257. {
  258. instance.AverageCost = averagecost;
  259. FindSubStore<ProductInstance>().Save(instance,
  260. $"Updated Average Cost: " +
  261. $"({freeqty} @ {freeavg:C2}) + ({poqty} @ {entity.Cost:C2}) = {totalcost:C2} / {totalqty}"
  262. );
  263. }
  264. }
  265. var batch = new StockMovementBatch
  266. {
  267. Type = StockMovementBatchType.Receipt,
  268. TimeStamp = DateTime.Now,
  269. Notes = $"Received on PO"
  270. };
  271. var movements = new List<StockMovement>();
  272. var _pototal = entity.Qty;
  273. var poCost = entity.Cost;
  274. if (!consigntask.Result.IsEffectivelyEqual(0.0)
  275. && !entity.Qty.IsEffectivelyEqual(0.0))
  276. {
  277. poCost += entity.Cost * entity.Consignment.ExTax / consigntask.Result;
  278. }
  279. foreach (var jri in jris)
  280. {
  281. // Going through each jri, make sure we don't allocate more than the po line allows
  282. var jriQty = Math.Min(jri.Qty, _pototal);
  283. // And reduce the po balance by the jri Allocation
  284. _pototal -= jriQty;
  285. // Let's not make zero-quantity transactions
  286. if (!jriQty.IsEffectivelyEqual(0.0))
  287. CreateMovement(entity, locationid, movements, jri, jriQty, poCost);
  288. }
  289. // If there is any left over (ie over-ordered), now we can create a
  290. // second transaction to receive the unallocated stock
  291. if (!_pototal.IsEffectivelyEqual(0.0F))
  292. CreateMovement(entity, locationid, movements, null, _pototal, poCost);
  293. FindSubStore<StockMovementBatch>().Save(batch, "Received on PO");
  294. foreach(var mvt in movements)
  295. {
  296. mvt.Batch.ID = batch.ID;
  297. }
  298. FindSubStore<StockMovement>().Save(movements, "Updated by Purchase Order Modification");
  299. entity.CancelChanges();
  300. }
  301. private static void CreateMovement(PurchaseOrderItem entity, Guid locationid, List<StockMovement> movements, JobRequisitionItem jri, double qty, double cost)
  302. {
  303. var movement = new StockMovement();
  304. movement.Product.ID = entity.Product.ID;
  305. movement.Job.ID = entity.Job.ID;
  306. movement.Location.ID = locationid;
  307. movement.Style.ID = entity.Style.ID;
  308. movement.Dimensions.CopyFrom(entity.Dimensions);
  309. movement.Date = entity.ReceivedDate;
  310. movement.Received = qty;
  311. movement.Employee.ID = Guid.Empty;
  312. movement.OrderItem.ID = entity.ID;
  313. movement.Notes = string.Format("Received on PO {0}", entity.PurchaseOrderLink.PONumber);
  314. movement.Cost = cost;
  315. movement.Type = StockMovementType.Receive;
  316. movements.Add(movement);
  317. if (jri is not null)
  318. {
  319. movement.JobRequisitionItem.ID = jri.ID;
  320. if (!jri.Cancelled.IsEmpty())
  321. {
  322. // We need to create an immediate transfer in and out of the job requisition item.
  323. var tOut = movement.CreateMovement();
  324. tOut.JobRequisitionItem.ID = jri.ID;
  325. tOut.Date = entity.ReceivedDate;
  326. tOut.Issued = jri.Qty;
  327. tOut.OrderItem.ID = entity.ID;
  328. tOut.Notes = "Internal transfer from cancelled requisition";
  329. tOut.System = true;
  330. tOut.Cost = entity.Cost;
  331. tOut.Type = StockMovementType.TransferOut;
  332. var tIn = movement.CreateMovement();
  333. tIn.Transaction = tOut.Transaction;
  334. tIn.Date = entity.ReceivedDate;
  335. tIn.Received = jri.Qty;
  336. tIn.OrderItem.ID = entity.ID;
  337. tOut.Notes = "Internal transfer from cancelled requisition";
  338. tOut.System = true;
  339. tIn.Cost = entity.Cost;
  340. tIn.Type = StockMovementType.TransferIn;
  341. movements.Add(tOut);
  342. movements.Add(tIn);
  343. }
  344. }
  345. }
  346. private void DeleteStockMovements(PurchaseOrderItem entity)
  347. {
  348. var movements = Provider.Query(
  349. new Filter<StockMovement>(x => x.OrderItem.ID).IsEqualTo(entity.ID),
  350. Columns.None<StockMovement>().Add(x => x.ID)
  351. ).Rows.Select(x => x.ToObject<StockMovement>());
  352. if (movements.Any())
  353. FindSubStore<StockMovement>().Delete(movements, "Purchase Order Item marked as Unreceived");
  354. }
  355. protected override void AfterSave(PurchaseOrderItem entity)
  356. {
  357. base.AfterSave(entity);
  358. if (entity.HasOriginalValue(x=>x.ReceivedDate))
  359. {
  360. if (entity.ReceivedDate.IsEmpty())
  361. {
  362. DeleteStockMovements(entity);
  363. UpdateJobRequiItems(entity, JobRequisitionItemAction.Updated);
  364. }
  365. else
  366. {
  367. var original = entity.GetOriginalValue(x => x.ReceivedDate);
  368. if(original == DateTime.MinValue)
  369. {
  370. var item = Provider.Query(
  371. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  372. LookupFactory.RequiredColumns<PurchaseOrderItem>())
  373. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  374. if(item is not null)
  375. {
  376. CreateStockMovements(item);
  377. UpdateJobRequiItems(item, JobRequisitionItemAction.Updated);
  378. }
  379. }
  380. else
  381. {
  382. var item = Provider.Query(
  383. new Filter<PurchaseOrderItem>(x => x.ID).IsEqualTo(entity.ID),
  384. Columns.None<PurchaseOrderItem>().Add(x => x.ID)
  385. .Add(x => x.ReceivedDate)
  386. .Add(x => x.Cost))
  387. .ToObjects<PurchaseOrderItem>().FirstOrDefault();
  388. if(item is not null)
  389. {
  390. UpdateStockMovements(item);
  391. UpdateJobRequiItems(item, JobRequisitionItemAction.Updated);
  392. }
  393. }
  394. }
  395. }
  396. else if(entity.HasOriginalValue(x => x.ID)
  397. || entity.HasOriginalValue(x => x.Product.ID)
  398. || entity.HasOriginalValue(x => x.Qty))
  399. {
  400. UpdateJobRequiItems(entity, entity.HasOriginalValue(x => x.ID) ? JobRequisitionItemAction.Created : JobRequisitionItemAction.Updated);
  401. }
  402. }
  403. private Guid GetJobRequisitionID(PurchaseOrderItem entity)
  404. {
  405. var jri = Provider.Query(
  406. new Filter<JobRequisitionItemPurchaseOrderItem>(x => x.PurchaseOrderItem.ID).IsEqualTo(entity.ID),
  407. Columns.None<JobRequisitionItemPurchaseOrderItem>().Add(x => x.JobRequisitionItem.ID))
  408. .Rows
  409. .FirstOrDefault()?
  410. .Get<JobRequisitionItemPurchaseOrderItem, Guid>(x => x.JobRequisitionItem.ID) ?? Guid.Empty;
  411. return jri;
  412. }
  413. private void UpdateJobRequiItems(PurchaseOrderItem entity, JobRequisitionItemAction action)
  414. {
  415. var id = GetJobRequisitionID(entity);
  416. if (id != Guid.Empty)
  417. JobRequisitionItemStore.UpdateStatus(this, id, action);
  418. }
  419. private Guid _jobrequisitionitemid = Guid.Empty;
  420. protected override void BeforeDelete(PurchaseOrderItem entity)
  421. {
  422. base.BeforeDelete(entity);
  423. DeleteStockMovements(entity);
  424. _jobrequisitionitemid = GetJobRequisitionID(entity);
  425. }
  426. protected override void AfterDelete(PurchaseOrderItem entity)
  427. {
  428. base.AfterDelete(entity);
  429. if (_jobrequisitionitemid != Guid.Empty)
  430. JobRequisitionItemStore.UpdateStatus(this, _jobrequisitionitemid, JobRequisitionItemAction.Deleted);
  431. }
  432. }