using System; using Comal.Classes; using Comal.Stores; using InABox.Core; using InABox.Database; using System.Collections.Generic; using System.Linq; namespace PRSStores; public enum JobRequisitionItemAction { Created, Updated, Deleted, None } public class JobRequisitionItemStore : BaseStore { protected override void AfterSave(JobRequisitionItem entity) { base.AfterSave(entity); if(entity.HasOriginalValue(x => x.Cancelled)) { CancelMovements(entity); } } private static IEnumerable GetMovements(IStore store, Guid jriID, Filter? filter, Columns columns) { return store.Provider .Query( Filter.And( new Filter(x => x.JobRequisitionItem.ID).IsEqualTo(jriID), filter), columns) .ToObjects(); } private void CancelMovements(JobRequisitionItem entity) { // Here, we care about *all* movements into or out of this requi. If stuff has been issued, it must be included, // since we cannot return issued stock back to general stock for the job. var movements = GetMovements(this, entity.ID, null, Columns.None().Add( x => x.Product.ID, x => x.Style.ID, x => x.Job.ID, x => x.Location.ID, x => x.Units, x => x.Cost, x => x.OrderItem.ID) .AddDimensionsColumns(x => x.Dimensions, Dimensions.ColumnsType.Local)); var newMovements = new List(); foreach(var movement in movements) { var from = movement.CreateMovement(); from.Date = entity.Cancelled; from.Cost = movement.Cost; from.System = true; from.JobRequisitionItem.ID = entity.ID; from.OrderItem.ID = movement.OrderItem.ID; from.Notes = "Requisition item cancelled"; var to = movement.CreateMovement(); to.Date = entity.Cancelled; to.Cost = movement.Cost; to.System = true; to.Notes = "Requisition item cancelled"; to.OrderItem.ID = movement.OrderItem.ID; to.Transaction = from.Transaction; if(movement.Units > 0) { // If this movement was an increase to reservation allocation, we create a transfer out of the reservation. from.Issued = movement.Units; to.Received = movement.Units; from.Type = StockMovementType.TransferOut; to.Type = StockMovementType.TransferIn; } else if(movement.Units < 0) { // If this movement was a decrease to reservation allocation, we create a transfer into the reservation. from.Received = -movement.Units; to.Issued = -movement.Units; from.Type = StockMovementType.TransferIn; to.Type = StockMovementType.TransferOut; } newMovements.Add(from); newMovements.Add(to); } if(newMovements.Count > 0) { var batch = new StockMovementBatch { Notes = "Requisition item cancelled." }; FindSubStore().Save(batch, ""); foreach(var mvt in newMovements) { mvt.Batch.ID = batch.ID; } FindSubStore().Save(newMovements, "Requisition item cancelled."); } } }