public bool Update(ItemStock obj)
        {
            _db.Entry(obj).State = EntityState.Modified;
            _db.SaveChanges();

            return(true);
        }
Exemplo n.º 2
0
        public IHttpActionResult PutItemStock(long id, ItemStock itemStock)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != itemStock.ID)
            {
                return(BadRequest());
            }

            db.Entry(itemStock).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ItemStockExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 3
0
 private void ChangeItemExitStock(Exit exit)
 {
     foreach (var exitItem in exit.ExitItem)
     {
         ItemStock lastest   = db.ItemStock.Where(s => s.ItemId == exitItem.ItemId && s.StoreId == exitItem.StoreId).OrderByDescending(s => s.DateEnter).FirstOrDefault();
         ItemStock itemStock = new ItemStock();
         itemStock.StoreId     = exitItem.StoreId;
         itemStock.StoreName   = exitItem.StoreName;
         itemStock.ItemId      = exitItem.ItemId;
         itemStock.ItemName    = exitItem.ItemName;
         itemStock.InitCount   = (lastest == null ? 0 : lastest.RealCount);
         itemStock.InitPrice   = 0;
         itemStock.InitAmount  = (lastest == null ? 0 : lastest.RealAmount);
         itemStock.EnterType   = "";
         itemStock.DateEnter   = DateTime.Now;
         itemStock.EnterCount  = 0;
         itemStock.EnterPrice  = 0;
         itemStock.EnterAmount = 0;
         itemStock.ExitType    = exit.ExitType;
         itemStock.ExitCount   = exitItem.QuantityReal;
         itemStock.ExitPrice   = exitItem.Price;
         itemStock.ExitAmount  = exitItem.Price * exitItem.QuantityReal;
         itemStock.DateExit    = DateTime.Now;
         itemStock.RealCount   = itemStock.InitCount + itemStock.EnterCount - itemStock.ExitCount;
         itemStock.RealAmount  = itemStock.InitAmount + itemStock.EnterAmount - itemStock.ExitAmount;
         itemStock.TableName   = "ExitItem";
         string guid = Guid.NewGuid().ToString();
         exitItem.Guid        = guid;
         itemStock.RecordGuid = guid;
         db.ItemStock.InsertOnSubmit(itemStock);
     }
 }
Exemplo n.º 4
0
        public double CalculatePrice(ItemStock stock, DateTime?date)
        {
            double result = stock.Price;

            if (stock.Price > 0 && stock.ManufacturingDate.HasValue && stock.Entrydate.HasValue)
            {
                var totalDaysFromManufacturing = date.GetValueOrDefault(DateTime.Now).Date.Subtract(stock.ManufacturingDate.Value.Date).TotalDays;
                var age = Math.Truncate(totalDaysFromManufacturing / 365);

                var totalDaysFromEntry = date.GetValueOrDefault(DateTime.Now).Date.Subtract(stock.Entrydate.Value.Date).TotalDays;
                var storeYears         = Math.Truncate(totalDaysFromEntry / 365);

                var computeYears = age - storeYears;

                if (computeYears >= 1 && computeYears <= 5)
                {
                    result *= 1.05;
                }

                if (computeYears >= 6 && computeYears <= 10)
                {
                    result *= 1.10;
                }

                if (computeYears > 10)
                {
                    result *= 1 + (computeYears / 100);
                }
            }

            return(result);
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,ItemId,WarehouseId,ItemCount")] ItemStock itemStock)
        {
            if (id != itemStock.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(itemStock);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ItemStockExists(itemStock.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ItemId"]      = new SelectList(_context.Items, "Id", "Id", itemStock.ItemId);
            ViewData["WarehouseId"] = new SelectList(_context.Warehouses, "Id", "Id", itemStock.WarehouseId);
            return(View(itemStock));
        }
Exemplo n.º 6
0
        public static bool TryParse(string str, out ItemStock result)
        {
            int start = str.IndexOf(DelimiterStart);
            int end = str.IndexOf(DelimiterEnd);

            if (start >= 0 && end >= 0 && end > start)
            {
                var data = str.Substring(start + 1, end - start - 1);
                var parts = data.Split(':');
                if (parts.Length == 2)
                {
                    var subtypeName = parts[0].Trim();
                    var amountString = parts[1].Trim();
                    float amount;
                    if (float.TryParse(amountString, out amount))
                    {
                        result = new ItemStock(subtypeName, amount);
                        return true;
                    }
                }
            }

            result = default(ItemStock);
            return false;
        }
Exemplo n.º 7
0
        public static bool TryParse(string str, out ItemStock result)
        {
            int start = str.IndexOf(DelimiterStart);
            int end   = str.IndexOf(DelimiterEnd);

            if (start >= 0 && end >= 0 && end > start)
            {
                var data  = str.Substring(start + 1, end - start - 1);
                var parts = data.Split(':');
                if (parts.Length == 2)
                {
                    var   subtypeName  = parts[0].Trim();
                    var   amountString = parts[1].Trim();
                    float amount;
                    if (float.TryParse(amountString, out amount))
                    {
                        result = new ItemStock(subtypeName, amount);
                        return(true);
                    }
                }
            }

            result = default(ItemStock);
            return(false);
        }
Exemplo n.º 8
0
        static void Main()
        {
            ItemStock stock = new ItemStock();
            bool      bl    = true;

            while (bl)
            {
                Console.WriteLine("\n This is a menu for user:"******"\n1. Input new purcahsed material\n2. Consume Item\n3. Display\n\n press any other key to Exit\n");
                int check = int.Parse(Console.ReadLine());
                switch (check)
                {
                case 1:
                    stock.AddItem();
                    break;

                case 2:
                    stock.UpdateItem();
                    break;

                case 3:
                    stock.display();
                    break;

                default:
                    bl = false;
                    break;
                }
            }
        }
Exemplo n.º 9
0
        public double CalculatePrice(ItemStock stock, DateTime?date = null)
        {
            double result = stock.Price;

            if (stock.Price > 0 && stock.ExpirationDate.HasValue)
            {
                var expirationDays = stock.ExpirationDate.Value.Date.Subtract(date.GetValueOrDefault(DateTime.Now).Date).Days;

                if (expirationDays <= 1)
                {
                    result = 0;
                }

                if (expirationDays >= 2 && expirationDays <= 3)
                {
                    result /= 2;
                }

                if (expirationDays >= 4 && expirationDays <= 5)
                {
                    result /= 4;
                }
            }

            return(result);
        }
Exemplo n.º 10
0
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            if (e.ColumnIndex == dataGridView1.Columns["Save"].Index)
            {
                if (!Access.Instance.CanProceed(Modules.Inventory, Actions.Edit))
                {
                    return;
                }

                ItemStock record = (ItemStock)dataGridView1.Rows[e.RowIndex].DataBoundItem;
                record.CompanyId = Session.Instance.AuthUser.CompanyId;
                ItemStockBS.AddItemStock(record);
                PopulateInventory();

                return;
            }
            if (e.ColumnIndex == dataGridView1.Columns["Delete"].Index)
            {
                if (!Access.Instance.CanProceed(Modules.Inventory, Actions.Edit))
                {
                    return;
                }

                ItemStockBS.DeleteItemStock(((ItemStock)dataGridView1.Rows[e.RowIndex].DataBoundItem).ItemStockId);
                PopulateInventory();

                return;
            }
        }
Exemplo n.º 11
0
        //Helper Functions
        /// <summary>
        /// Description: This function only works on files with no spce in between lines of records
        /// </summary>
        private static void ParseVendorShipmentFile(string fileLocation)
        {
            //TODO: Find the object type to save to the database. Possibly Warehouse

            ItemCategory itemCategory     = new ItemCategory();
            Vendor       vendor           = new Vendor();
            ItemStock    itemStock        = new ItemStock();
            bool         vendorOrderExist = false;
            int          sequenceNumber   = 0;
            int          counter          = 1;
            int          itemCategoryID;
            int          vendorID;

            try
            {
                using (StreamReader streamReader = new StreamReader(fileLocation))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        if (vendorOrderExist && line.Substring(0, 1) != "T")
                        {
                            vendorID            = Convert.ToInt32(line.Substring(0, 2));
                            line                = line.Remove(0, 2);
                            itemCategoryID      = Convert.ToInt32(line.Substring(0, 5));
                            vendor.ItemProvided = itemCategory;
                            line                = line.Remove(0, 5);
                            itemStock.Quantity  = Convert.ToInt32(line.Substring(0, 6));
                            //Validate Item
                            itemStock.ItemStored = itemCategory;
                            counter++;

                            /***
                             * Go to back order database and fufil all order.
                             * Distribute remaining to all seven warehouses
                             **/
                        }
                        else if (!vendorOrderExist && line.Substring(0, 2) == "HD")
                        {
                            vendorOrderExist = true;
                            sequenceNumber   = Convert.ToInt32(line.Substring(3, 4));
                        }
                        else if (line.Substring(0, 1) == "T")
                        {
                            //Check total vendor items
                            vendorOrderExist = false;
                        }
                        else
                        {
                            throw new Exception();
                        }
                    }
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("File not found in {0}", fileLocation);
            }
        }
Exemplo n.º 12
0
        public static void EditItemStock(ItemStock record)
        {
            var itm = appDb.ItemStocks.FirstOrDefault(item => item.ItemStockId == record.ItemStockId);

            itm.MinimumQty = record.MinimumQty;
            itm.Qty        = record.Qty;
            itm.Remarks    = record.Remarks;
            appDb.SaveChanges();
        }
        public IHttpActionResult Add(ItemStock obj)
        {
            var retId = _itemStockService.Add(obj);

            if (retId == 0)
            {
                return(Content(HttpStatusCode.NotFound, $"Item ID [{obj}] not found."));
            }
            return(Ok(obj));
        }
Exemplo n.º 14
0
        public IHttpActionResult GetItemStock(long id)
        {
            ItemStock itemStock = db.ItemStocks.Find(id);

            if (itemStock == null)
            {
                return(NotFound());
            }

            return(Ok(itemStock));
        }
Exemplo n.º 15
0
        public IHttpActionResult PostItemStock(ItemStock itemStock)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.ItemStocks.Add(itemStock);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = itemStock.ID }, itemStock));
        }
Exemplo n.º 16
0
 public void Handle(EventMessage <ItemStockCreated> message)
 {
     using (var context = new MyNotesReadModelEntities())
     {
         var item = new ItemStock();
         item.Qty   = message.Payload.Qty;
         item.Item  = message.Payload.Item;
         item.RefId = message.Payload.RefId;
         context.ItemStocks.AddObject(item);
         context.SaveChanges();
     }
 }
        public async Task <IActionResult> Create([Bind("Id,ItemId,WarehouseId,ItemCount")] ItemStock itemStock)
        {
            if (ModelState.IsValid)
            {
                _context.Add(itemStock);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ItemId"]      = new SelectList(_context.Items, "Id", "Id", itemStock.ItemId);
            ViewData["WarehouseId"] = new SelectList(_context.Warehouses, "Id", "Id", itemStock.WarehouseId);
            return(View(itemStock));
        }
        public void Stock_with_no_expiration_date()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 100, ExpirationDate = null
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(100, newPrice, 0.02d);
        }
        public void ExpirationDays_with_price0()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 0, ExpirationDate = DateTime.Now.AddDays(2)
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(0, newPrice, 0.02d);
        }
Exemplo n.º 20
0
        public void No_required_ComputeYears()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 100, ManufacturingDate = DateTime.Now.AddYears(-1), Entrydate = DateTime.Now.AddYears(-1)
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(100d, newPrice, 0.02d);
        }
        public void ExpirationDays_less_than_1()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 100, ExpirationDate = DateTime.Now
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(0, newPrice, 0.02d);
        }
Exemplo n.º 22
0
        public void Same_price()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 100
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(100, newPrice, 0.02d);
        }
        public void ExpirationDays_between_3_and_4()
        {
            //Arrange
            var stock = new ItemStock {
                Price = 100, ExpirationDate = DateTime.Now.AddDays(4)
            };

            //Act
            var newPrice = strategy.CalculatePrice(stock);

            //Assert
            Assert.AreEqual(25, newPrice, 0.02d);
        }
Exemplo n.º 24
0
    public void Setup(List <IMyTerminalBlock> ship)
    {
        // First build map of defaults
        var defaultItemStocksMap = new Dictionary <string, ItemStock>();

        for (int i = 0; i < defaultItemStocks.Length; i++)
        {
            var itemStock = defaultItemStocks[i];
            defaultItemStocksMap.Add(itemStock.SubtypeName, itemStock);
        }

        // Get assemblers
        var assemblers = ZACommons.GetBlocksOfType <IMyAssembler>(ship);
        var candidates = new LinkedList <IMyAssembler>();

        // If anything has already been appropriately named, remove it from our map
        for (var e = assemblers.GetEnumerator(); e.MoveNext();)
        {
            var       assembler = (IMyAssembler)e.Current;
            ItemStock target;
            if (ItemStock.TryParse(assembler.CustomName, out target))
            {
                defaultItemStocksMap.Remove(target.SubtypeName);
            }
            else
            {
                // Otherwise add assembler as candidate for renaming
                candidates.AddLast(assembler);
            }
        }

        for (var e = defaultItemStocksMap.Values.GetEnumerator(); e.MoveNext() && candidates.First != null;)
        {
            var itemStock = e.Current;

            // Get first candidate
            var candidate = candidates.First.Value;
            candidates.RemoveFirst();

            // Rename appropriately
            StringBuilder builder = new StringBuilder();
            builder.Append(candidate.CustomName);
            builder.Append(' ');
            builder.Append(DelimiterStart);
            builder.Append(itemStock.SubtypeName);
            builder.Append(DelimiterAmount);
            builder.Append(itemStock.Amount);
            builder.Append(DelimiterEnd);
            candidate.SetCustomName(builder);
        }
    }
Exemplo n.º 25
0
 public static ItemStock AddItemStock(ItemStock itemStock)
 {
     if (GetItemStockById(itemStock.ItemStockId) != null)
     {
         EditItemStock(itemStock);
         return(itemStock);
     }
     else
     {
         var record = appDb.ItemStocks.Add(itemStock);
         appDb.SaveChanges();
         return(record);
     }
 }
Exemplo n.º 26
0
        public IHttpActionResult DeleteItemStock(long id)
        {
            ItemStock itemStock = db.ItemStocks.Find(id);

            if (itemStock == null)
            {
                return(NotFound());
            }

            db.ItemStocks.Remove(itemStock);
            db.SaveChanges();

            return(Ok(itemStock));
        }
        private ItemStock MapStockItem(DbDataReader dr)
        {
            ItemStock stockItem = new ItemStock();

            stockItem.CompanyId                = NullHandler.GetString(dr["CompanyId"]);
            stockItem.ItemId                   = NullHandler.GetString(dr["ItemId"]);
            stockItem.ItemName                 = NullHandler.GetString(dr["ItemName"]);
            stockItem.CountPerBox              = NullHandler.GetInt32(dr["CountPerBox"]);
            stockItem.StockId                  = NullHandler.GetString(dr["StockId"]);
            stockItem.CurrentStockTotal        = NullHandler.GetInt32(dr["TotalStock"]);
            stockItem.CurrentDamagedStockTotal = NullHandler.GetInt32(dr["DamagedStock"]);
            stockItem.ChalanNo                 = NullHandler.GetString(dr["ChalanNo"]);
            stockItem.StockEntryDate           = NullHandler.GetDateTime(dr["StockEntryDate"]);
            stockItem.CalculateBoxesFromTotalStock();
            stockItem.CalculateBoxesFromDamagedTotalStock();
            return(stockItem);
        }
        private void FindItemWithName(string itemName)
        {
            Item ItemToRemove = null;

            foreach (Item item in ItemStock)
            {
                if (item.Name == itemName)
                {
                    ItemToRemove = item;
                    Console.WriteLine("You Have Selected {0}", item.Name);
                    Selection.Add(item);
                    break;
                }
            }

            if (ItemToRemove != null)
            {
                ItemStock.Remove(ItemToRemove);
            }
        }
Exemplo n.º 29
0
        public ActionResult UpdateItemStock(string id, int stock, [FromHeader] string token)
        {
            if (Logins.Verify(token, true) != null)
            {
                List<ItemStock> items = Program.db.Query<ItemStock>($"SELECT * FROM ItemStock WHERE id = '{id}';");

                if (items.Count > 0)
                {
                    ItemStock s = items.First();

                    s.stock = stock;

                    Program.db.Update(s);
                    return Ok(s);
                }
                else
                    return NotFound();
            }
            else
                return Unauthorized();
        }
        public SavingState SaveItemsOrder(DataGridView dataGridViewOrder, string companyId, string srDsrId, string marketId, DateTime orderDate, SRDSRDue srDsrDue, bool isFromTemplate = false, bool isItemReturnedFromOrder = false, bool isDamagedItemReturnedFromOrder = false)
        {
            SavingState svState = SavingState.Failed;

            DbCommand thisCommand = null;

            try
            {
                thisCommand             = GenericDataAccess.CreateCommand();
                thisCommand.CommandType = CommandType.Text;
                GenericDataAccess.OpenDBConnection(thisCommand);

                if ((isFromTemplate && !IsSrDsrOrderExist(companyId, srDsrId, marketId, orderDate)) || (!isFromTemplate && IsSrDsrOrderExist(companyId, srDsrId, marketId, orderDate)))
                {
                    foreach (DataGridViewRow row in dataGridViewOrder.Rows)
                    {
                        int stockAvailableInStore       = 0;
                        int damagedItemAvailableInStock = 0;
                        if (string.IsNullOrEmpty(NullHandler.GetString(row.Cells["OrderId"].Value)))
                        {
                            /// insert the item order
                            thisCommand.CommandText = "INSERT INTO IM_Orders (OrderId, CompanyId, SrId, MarketId, ItemId, Date, OrderCount, ReturnCount, SoldCount, DamagedCount) VALUES(@OrderId, @CompanyId, @SrId, @MarketId, @ItemId, @Date, @OrderCount, @ReturnCount, @SoldCount, @DamagedCount)";
                            CreateParameter.AddParam(thisCommand, "@OrderId", Guid.NewGuid().ToString(), DbType.String);
                            CreateParameter.AddParam(thisCommand, "@CompanyId", companyId, DbType.String);
                            CreateParameter.AddParam(thisCommand, "@SrId", srDsrId, DbType.String);
                            CreateParameter.AddParam(thisCommand, "@MarketId", marketId, DbType.String);
                            CreateParameter.AddParam(thisCommand, "@ItemId", NullHandler.GetString(row.Cells["ItemId"].Value), DbType.String);
                            CreateParameter.AddParam(thisCommand, "@Date", orderDate.Date, DbType.Date);
                            stockAvailableInStore = NullHandler.GetInt32(row.Cells["CurrentStockTotal"].Value) - NullHandler.GetInt32(row.Cells["SellsCount"].Value);

                            damagedItemAvailableInStock = NullHandler.GetInt32(row.Cells["CurrentDamagedStockTotal"].Value);
                        }
                        else
                        {
                            /// update the item order based on OrderId
                            thisCommand.CommandText = "UPDATE IM_Orders SET OrderCount = @OrderCount, ReturnCount = @ReturnCount, SoldCount = @SoldCount, DamagedCount = @DamagedCount WHERE OrderId = @OrderId";
                            CreateParameter.AddParam(thisCommand, "@OrderId", row.Cells["OrderId"].Value.ToString(), DbType.String);

                            stockAvailableInStore = isItemReturnedFromOrder ? (NullHandler.GetInt32(row.Cells["CurrentStockTotal"].Value) + NullHandler.GetInt32(row.Cells["ReturnCount"].Value)) : NullHandler.GetInt32(row.Cells["CurrentStockTotal"].Value);

                            damagedItemAvailableInStock = isDamagedItemReturnedFromOrder? (NullHandler.GetInt32(row.Cells["CurrentDamagedStockTotal"].Value) + NullHandler.GetInt32(row.Cells["DamageCount"].Value)): NullHandler.GetInt32(row.Cells["CurrentDamagedStockTotal"].Value);
                        }

                        CreateParameter.AddParam(thisCommand, "@OrderCount", row.Cells["OrderCount"].Value, DbType.Int32);
                        CreateParameter.AddParam(thisCommand, "@ReturnCount", row.Cells["ReturnCount"].Value, DbType.Int32);
                        CreateParameter.AddParam(thisCommand, "@DamagedCount", row.Cells["DamageCount"].Value, DbType.Int32);
                        CreateParameter.AddParam(thisCommand, "@SoldCount", row.Cells["SellsCount"].Value, DbType.Int32);

                        GenericDataAccess.ExecuteNonQueryTransaction(thisCommand);
                        thisCommand.Parameters.Clear();

                        if (!string.IsNullOrEmpty(NullHandler.GetString(row.Cells["StockId"].Value)))
                        {
                            ItemStock stock = new ItemStock();
                            stock.StockId                  = NullHandler.GetString(row.Cells["StockId"].Value);
                            stock.ItemId                   = NullHandler.GetString(row.Cells["ItemId"].Value);
                            stock.ChalanNo                 = NullHandler.GetString(row.Cells["ChalanNo"].Value);
                            stock.StockEntryDate           = NullHandler.GetDateTime(row.Cells["StockEntryDate"].Value);
                            stock.CurrentStockTotal        = stockAvailableInStore;//NullHandler.GetInt32(row.Cells["CurrentStockTotal"].Value);
                            stock.CurrentDamagedStockTotal = damagedItemAvailableInStock;

                            svState = SaveStockItem(stock, thisCommand, true);
                        }
                    }
                }
                else
                {
                    svState = SavingState.DuplicateExists;
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("duplicate key"))
                {
                    svState = SavingState.DuplicateExists;
                }
            }
            finally
            {
                GenericDataAccess.CloseDBConnection(thisCommand);
            }

            if (svState.Equals(SavingState.Success) && !string.IsNullOrEmpty(srDsrDue.Id))
            {
                svState = SRDSRManager.Instance.SaveSrDsrDue(srDsrDue);
            }

            return(svState);
        }
Exemplo n.º 31
0
    public void Run(ZACommons commons, EventDriver eventDriver)
    {
        if (CurrentState == STATE_INACTIVE)
        {
            return;
        }

        var ship = LIMIT_PRODUCTION_MANAGER_SAME_GRID ? commons.Blocks : commons.AllBlocks;

        var allowedSubtypes  = new HashSet <string>();
        var assemblerTargets = new Dictionary <string, AssemblerTarget>();

        var assemblers = ZACommons.GetBlocksOfType <IMyAssembler>(ship);

        for (var e = assemblers.GetEnumerator(); e.MoveNext();)
        {
            var       assembler = (IMyAssembler)e.Current;
            ItemStock target;
            if (ItemStock.TryParse(assembler.CustomName, out target))
            {
                var subtype = target.SubtypeName;

                // When we take inventory, filter to just these types
                allowedSubtypes.Add(subtype);

                AssemblerTarget assemblerTarget;
                if (!assemblerTargets.TryGetValue(subtype, out assemblerTarget))
                {
                    assemblerTarget = new AssemblerTarget(target.Amount);
                    assemblerTargets.Add(subtype, assemblerTarget);
                }

                // Remember this assembler for this subtype
                assemblerTarget.Assemblers.Add(assembler);

                // Adjust target amount, if necessary
                assemblerTarget.Amount = Math.Max(assemblerTarget.Amount, target.Amount);
            }
        }

        if (CurrentState == STATE_ACTIVE)
        {
            // Get current stocks
            var stocks = EnumerateItems(ship, allowedSubtypes);

            // Now we just enable/disable based on who's low
            for (var e = assemblerTargets.GetEnumerator(); e.MoveNext();)
            {
                var subtype = e.Current.Key;
                var target  = e.Current.Value;
                VRage.MyFixedPoint currentStock;
                if (!stocks.TryGetValue(subtype, out currentStock))
                {
                    currentStock = (VRage.MyFixedPoint) 0.0f;
                }

                // Enable or disable based on current stock
                target.EnableAssemblers((float)currentStock < target.Amount);
            }
        }
        else if (CurrentState == STATE_INACTIVATING)
        {
            // Shut down all known assemblers
            for (var e = assemblerTargets.Values.GetEnumerator(); e.MoveNext();)
            {
                e.Current.EnableAssemblers(false);
            }
            SetState(commons, STATE_INACTIVE);
        }

        eventDriver.Schedule(RunDelay, Run);
    }