Beispiel #1
0
        // TODO ->> duplicate with DocumentsDAL
        // תנועות מלאי
        private bool CreateInventoryTransaction(InventoryTransaction transaction, OdbcCommand command)
        {
            try
            {
                var query = $@"
                        INSERT INTO InvTrs
                        (
                            Store,		
                            ItemNo,		
                            InOut,		
                            DocCode,		
                            Details,		
                            Subject,		
                            Agent,	    
                            Voucher,     
                            AccNo,      
                            Qty,         
                            ""Sum"",
                            FcSum,		
                            AuxQty,      
                            SerNo,       
                            Color,		
                            Size,		
                            BatchNo,  
                            Pkuda,
                            TrsNo,
                            ExpireDate,  
                            DATE                                    
                        )                        
                        (
                            SELECT 
                            {transaction.StoreNo},
                            '{transaction.ItemId}',
                            '{transaction.InOut}',
                            '{transaction.DocumentId}',
                            '{SafeConvert.ToPervasiveString(transaction.Notes)}',
                            {transaction.SubjectId},
                            {transaction.AgentId},
                            '{transaction.Asmac}',
                            {transaction.AccountId},
                            {transaction.Quantity},
                            {transaction.Total}, 
                            {transaction.FcTotal}, 
                            {transaction.AuxQuantity},
                            '{transaction.SerialNo}',
                            '{transaction.Color}',
                            '{transaction.Size}',
                            '{transaction.BatchNo}',                            
                            {transaction.CommandNo}, 
                            {transaction.TransactionId}, 
                            {PervasiveDBHelper.ToPervasiveDate(transaction.ExpireDate)},
                            {PervasiveDBHelper.ToPervasiveDate(transaction.CreatedDate)}                                                                        
                        )
                    ";

                command.CommandText = query;
                command.ExecuteNonQuery();
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
 public override void AddInventory(InventoryTransaction transaction)
 {
     transaction.AddInventory(this.Inventory);
 }
Beispiel #3
0
        public ActionResult MovEat(int lid, int FoodStockId, decimal Qty, int?LocationId, int ItemId, string submit)
        {
            using (var transaction = db.GetTransaction())
            {
                try
                {
                    var CurrUsr = User.Identity.GetUserId();
                    if (submit == "Move")
                    {
                        //Fetch the FoodStock record
                        //var fs = db.FirstOrDefault<FoodStock>("select * from FoodStock where FoodStockId=@0", FoodStockId);
                        var fs = db.SingleOrDefault <FoodStock>(FoodStockId);
                        if (fs.Qty >= Qty)
                        {
                            var it = new InventoryTransaction {
                                FoodStockId = FoodStockId, ItemId = ItemId, FromLocationId = lid, QtyRemoved = Qty, RecvdByUserId = CurrUsr, TDate = DateTime.Today, ToLocationId = LocationId, UnitId = fs.UnitId
                            };
                            db.Insert(it); //record this move in Inventory Transaction table

                            var tfs = new FoodStock {
                                InventoryTransactionId = it.InventoryTransactionId, ItemId = ItemId, LocationId = LocationId.Value, Qty = Qty, Size = fs.Size, TDate = DateTime.Today, UnitId = fs.UnitId
                            };
                            db.Insert(tfs); //Make the new entry in the benifiting location

                            fs.Qty -= Qty;
                            db.Update(fs); //update the loosing location's stock
                        }
                        else
                        {
                            throw new HttpRequestValidationException("Error: Insufficient Quantity in Stock!");
                        }
                    }


                    if (submit == "Use")
                    {
                        //Fetch the FoodStock record
                        var fs = db.FirstOrDefault <FoodStock>("select * from FoodStock where FoodStockId=@0", FoodStockId);

                        if (fs.Qty >= Qty)
                        {
                            var it = new InventoryTransaction {
                                FoodStockId = FoodStockId, ItemId = ItemId, FromLocationId = lid, QtyRemoved = Qty, RecvdByUserId = CurrUsr, TDate = DateTime.Today, UnitId = fs.UnitId
                            };
                            db.Insert(it);
                            fs.Qty -= Qty;
                            db.Update(fs);
                        }
                        else
                        {
                            throw new HttpRequestValidationException("Error: Insufficient Quantity in Stock!");
                        }
                    }

                    transaction.Complete();
                    return(RedirectToAction("MovEat", new { LocationId = lid }));
                }
                catch (Exception ex)
                {
                    db.AbortTransaction();
                    throw ex;
                }
            }
        }
Beispiel #4
0
 public TableData Load(PageReq pageRequest, InventoryTransaction entity)
 {
     return(_app.Load(pageRequest, entity));
 }
Beispiel #5
0
 public void Upd(InventoryTransaction entity)
 {
     _app.Update(entity);
 }
Beispiel #6
0
        public StockIn Save(StockIn stockIn)
        {
            var balance      = 0.0m;
            var existingItem = inventory.GetAll(a => a.ProductId == stockIn.ProductId && a.BrandId == stockIn.BrandId && a.SizeId == stockIn.SizeId && a.APIId == stockIn.APIId && a.IsActive == true && a.WarehouseId == stockIn.WarehouseId).ToList();

            if (existingItem.Count > 0)
            {
                foreach (var inv in existingItem)
                {
                    inv.UpdatedDate  = DateTime.Now;
                    inv.UpdatedBy    = "";
                    inv.BalanceQty   = inv.BalanceQty + stockIn.BaleQty ?? 0;
                    inv.ProductionIn = inv.ProductionIn ?? 0 + stockIn.BaleQty ?? 0;
                    inventory.Update(inv, inv.Id);
                    balance = inv.BalanceQty;
                }
            }
            else
            {
                Inventory result      = new Inventory();
                Inventory FinalResult = new Inventory();

                result.ProductId     = (int)stockIn.ProductId;
                result.SupplierId    = stockIn.SupplierId ?? 0;
                result.WarehouseId   = (int)stockIn.WarehouseId;
                result.ProductionIn  = stockIn.BaleQty;
                result.PurchasePrice = stockIn.Rate;
                result.BrandId       = stockIn.BrandId;
                result.SizeId        = stockIn.SizeId;
                result.BalanceQty    = stockIn.BaleQty ?? 0;
                result.Notes         = stockIn.Notes;
                result.GoodsType     = "2";
                result.CreatedBy     = CurrentSession.GetCurrentSession().UserName;
                result.CreatedDate   = DateTime.Now;
                result.IsActive      = true;
                FinalResult          = inventory.Save(result);
                balance = result.BalanceQty;
            }
            var invTransaction = new InventoryTransaction()
            {
                APIId           = stockIn.APIId,
                BalanceQty      = balance,
                BrandId         = stockIn.BrandId,
                CreatedBy       = CurrentSession.GetCurrentSession().UserName,
                CreatedDate     = DateTime.Now,
                GoodsType       = "Finished Goods",
                InventoryGuid   = Guid.NewGuid().ToString(),
                InvoiceNo       = "",
                IsActive        = true,
                ProductId       = stockIn.ProductId ?? 0,
                PurchasePrice   = stockIn.Rate,
                Qty             = stockIn.BaleQty,
                SalesPrice      = 0,
                SizeId          = stockIn.SizeId,
                SupplierId      = stockIn.SupplierId ?? 0,
                TransactionType = (int)Util.TransactionType.ProductionIn,
                WarehouseId     = stockIn.WarehouseId ?? 0
            };

            _invTransactionService.Save(invTransaction);
            return(service.Save(stockIn));
        }
Beispiel #7
0
        public ActionResult Manage(FormCollection fm)
        {
            using (var transaction = db.GetTransaction())
            {
                try
                {
                    int     resID    = int.Parse(fm["ReservationID"]);
                    decimal Qty      = int.Parse(fm["Qty"]);
                    decimal fixQty   = Qty;
                    int     ItemID   = db.FirstOrDefault <int>("Select ItemId from Items Where ItemName ='Room Water Bottle' and ItemTypeId='3'");
                    decimal wbPrice  = db.FirstOrDefault <decimal>("Select Price From Menu Where LocationId='2' and ItemId=@0", ItemID);
                    int     lid      = db.FirstOrDefault <int>("Select LocationId from Location Where LocationName ='Room Service' and LocationTypeId =@0", 1);
                    var     FsExist  = db.Fetch <FoodStock>("Select * From FoodStock Where ItemId =@0 and LocationId=@1 and Qty > 0 Order By Tdate asc ", ItemID, lid);
                    bool    QtyChk   = true;
                    decimal QtyMatch = 0;
                    if (FsExist.Count > 0)
                    {
                        foreach (var item in FsExist)
                        {
                            if (QtyChk == true)
                            {
                                if (item.Qty >= Qty)
                                {
                                    item.Qty -= Qty;
                                    QtyChk    = false;
                                    db.Execute($"Update FoodStock set Qty ={item.Qty} Where FoodStockID = {item.FoodStockId}");
                                    break;
                                }
                                else
                                {
                                    QtyMatch  = 0;
                                    QtyMatch += item.Qty;
                                    Qty       = Qty - item.Qty;
                                    item.Qty -= QtyMatch;
                                    db.Execute($"Update FoodStock set Qty ={item.Qty} Where FoodStockId = {item.FoodStockId}");
                                }
                            }
                        }



                        var inv = new InventoryTransaction
                        {
                            TDate          = DateTime.Now,
                            QtyRemoved     = fixQty,
                            FromLocationId = 1, //Room Service
                            RecvdByUserId  = User.Identity.GetUserId(),
                            UnitId         = 1, //Pieces
                            ItemId         = ItemID,
                            FoodStockId    = FsExist.First().FoodStockId
                        };
                        db.Insert(inv);
                        int     ExQty = db.FirstOrDefault <int>("Select Sum(Qty) as Qty From ReservationDetails Where ChargeID = @0 and ItemID = @1 and RDdate =@2 Group By ChargeID,ItemID", resID, ItemID, DateTime.Now.Date);
                        decimal amt   = 0;
                        if (ExQty <= 2)
                        {
                            if (fixQty > 2)
                            {
                                Qty = Qty - 2;
                                amt = wbPrice * Qty;
                            }
                            else
                            {
                                amt = 0;
                            }
                        }
                        else
                        {
                            amt = wbPrice * Qty;
                        }
                        var rd = new ReservationDetail
                        {
                            RDdate      = inv.TDate,
                            ChargeID    = resID,
                            ChargeType  = 2,
                            Description = "Room Water Bottle",
                            Qty         = (int)fixQty,
                            ItemID      = ItemID,
                            Amount      = amt
                        };

                        db.Insert(rd);
                        transaction.Complete();
                    }
                    else
                    {
                        throw new HttpRequestValidationException("Error: Insufficient Quantity in Stock!");
                    }
                }
                catch (Exception ex)
                {
                    db.AbortTransaction();
                    throw ex;
                }
            }

            return(View());
        }
 public void RecordLocationTransaction(InventoryTransaction inventoryTransaction, string transType, User user, string orderNo, Location refLocation, Flow productLine, string receiptNo)
 {
     this.RecordLocationTransaction(inventoryTransaction, transType, user, orderNo, refLocation, null, null, null);
 }
        public void RecordLocationTransaction(OrderLocationTransaction orderLocationTransaction, InventoryTransaction inventoryTransaction, Receipt receipt, User user)
        {
            LocationTransaction locationTransaction = GenerateOrderLocationTransaction(orderLocationTransaction, orderLocationTransaction.Location, user);

            if (inventoryTransaction.Hu != null)
            {
                locationTransaction.HuId  = inventoryTransaction.Hu.HuId;
                locationTransaction.LotNo = inventoryTransaction.Hu.LotNo;
            }
            if (locationTransaction.LotNo == null || locationTransaction.LotNo == string.Empty)
            {
                locationTransaction.LotNo = inventoryTransaction.LotNo;
            }
            locationTransaction.BatchNo       = inventoryTransaction.LocationLotDetailId;
            locationTransaction.RefLocation   = inventoryTransaction.RefLocation;
            locationTransaction.ReceiptNo     = receipt.ReceiptNo;
            locationTransaction.IpNo          = receipt.ReferenceIpNo;
            locationTransaction.Qty           = inventoryTransaction.Qty;
            locationTransaction.EffectiveDate = DateTime.Parse(receipt.CreateDate.ToString("yyyy-MM-dd"));
            if (orderLocationTransaction.OrderDetail.OrderHead.Type == BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_TRANSFER)
            {
                OrderLocationTransaction outOrderLocationTransaction = this.orderLocationTransactionMgr.GetOrderLocationTransaction(orderLocationTransaction.OrderDetail.Id, BusinessConstants.IO_TYPE_OUT)[0];
                locationTransaction.RefLocation     = outOrderLocationTransaction.Location.Code;
                locationTransaction.RefLocationName = outOrderLocationTransaction.Location.Name;
            }

            this.CreateLocationTransaction(locationTransaction);
        }
 public void RecordLocationTransaction(InventoryTransaction inventoryTransaction, string transType, User user)
 {
     this.RecordLocationTransaction(inventoryTransaction, transType, user, null);
 }
 public void RecordLocationTransaction(InventoryTransaction inventoryTransaction, string transType, User user, string orderNo, Location refLocation)
 {
     this.RecordLocationTransaction(inventoryTransaction, transType, user, orderNo, refLocation, null);
 }
        public void RecordLocationTransaction(MiscOrderDetail miscOrderDetail, InventoryTransaction inventoryTransaction, User user)
        {
            LocationTransaction locationTransaction = new LocationTransaction();
            MiscOrder           miscOrder           = miscOrderDetail.MiscOrder;

            locationTransaction.OrderNo = miscOrder.OrderNo;
            if (inventoryTransaction.Hu != null)
            {
                locationTransaction.HuId  = inventoryTransaction.Hu.HuId;
                locationTransaction.LotNo = inventoryTransaction.Hu.LotNo;
            }
            if (locationTransaction.LotNo == null || locationTransaction.LotNo == string.Empty)
            {
                locationTransaction.LotNo = inventoryTransaction.LotNo;
            }
            locationTransaction.BatchNo         = inventoryTransaction.LocationLotDetailId;
            locationTransaction.Item            = miscOrderDetail.Item.Code;
            locationTransaction.ItemDescription = miscOrderDetail.Item.Description;
            locationTransaction.Uom             = miscOrderDetail.Item.Uom.Code;
            locationTransaction.Qty             = inventoryTransaction.Qty;
            locationTransaction.PartyFrom       = miscOrder.Location.Region.Code;
            locationTransaction.PartyFromName   = miscOrder.Location.Region.Name;
            locationTransaction.PartyTo         = miscOrder.Location.Region.Code;
            locationTransaction.PartyToName     = miscOrder.Location.Region.Name;
            locationTransaction.Location        = miscOrder.Location.Code;
            if (locationTransaction.Location == BusinessConstants.SYSTEM_LOCATION_INSPECT)
            {
                throw new BusinessErrorException("Invalided.Location.Inspect");
            }
            if (locationTransaction.Location == BusinessConstants.SYSTEM_LOCATION_REJECT)
            {
                locationTransaction.RefLocation = inventoryTransaction.RefLocation;
            }

            locationTransaction.LocationName   = miscOrder.Location.Name;
            locationTransaction.LocInOutReason = miscOrder.Reason;
            // CodeMaster codeMaster = null;
            if (miscOrder.Type == BusinessConstants.CODE_MASTER_MISC_ORDER_TYPE_VALUE_GI)
            {
                locationTransaction.TransactionType = BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_ISS_UNP;
                //codeMaster = codeMasterMgr.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_STOCK_IN_REASON, miscOrder.Reason);
            }
            else if (miscOrder.Type == BusinessConstants.CODE_MASTER_MISC_ORDER_TYPE_VALUE_GR)
            {
                locationTransaction.TransactionType = BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_RCT_UNP;
                //codeMaster = codeMasterMgr.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_STOCK_OUT_REASON, miscOrder.Reason);
            }
            else if (miscOrder.Type == BusinessConstants.CODE_MASTER_MISC_ORDER_TYPE_VALUE_ADJ)
            {
                locationTransaction.TransactionType = BusinessConstants.CODE_MASTER_LOCATION_TRANSACTION_TYPE_VALUE_CYC_CNT;
                //codeMaster = codeMasterMgr.GetCachedCodeMaster(BusinessConstants.CODE_MASTER_STOCK_ADJUST_REASON, miscOrder.Reason);
            }
            //if (codeMaster != null)
            //{
            //    locationTransaction.LocInOutReasonDescription = codeMaster.Description;
            //}
            locationTransaction.CreateDate    = DateTime.Now;
            locationTransaction.CreateUser    = user.Code;
            locationTransaction.EffectiveDate = DateTime.Parse(miscOrder.EffectiveDate.ToString("yyyy-MM-dd"));

            this.CreateLocationTransaction(locationTransaction);
        }
Beispiel #13
0
        public ReceiveMaster Save(ReceiveMaster cus, List <AdditionalCost> additionalCosts, int wareHouseId, int goodsType)
        {
            var avgAdditionalCost = cus.AdditionalCost / cus.ReceiveDetails.Select(a => a.Qty).Sum();
            var avgCostPrice      = 0.0m;
            var supplier          = supplierService.GetById(cus.SupplierID);

            cus.YearId = financialYearId;
            var result = service.Save(cus);

            if (result != null || result.Id > 0)
            {
                foreach (var item in cus.ReceiveDetails)
                {
                    var balance      = 0.0m;
                    var existingItem = _inventoryService.GetAll(a => a.ProductId == item.ProductId && a.IsActive == true && a.WarehouseId == wareHouseId && a.SizeId == item.SizeId && a.BrandId == item.BrandId && a.APIId == item.APIId).ToList();
                    if (existingItem.Count > 0)
                    {
                        foreach (var inv in existingItem)
                        {
                            var existingCosting = inv.BalanceQty * inv.Costprice ?? 0;
                            var totalAmount     = item.Amount + avgAdditionalCost * item.Qty + existingCosting;
                            avgCostPrice      = totalAmount / (item.Qty + inv.BalanceQty);
                            inv.Costprice     = avgCostPrice;
                            inv.PurchasePrice = item.Rate;
                            inv.UpdatedDate   = DateTime.Now;
                            inv.UpdatedBy     = "";
                            inv.BalanceQty    = inv.BalanceQty + item.Qty;
                            inv.ReceiveQty    = inv.ReceiveQty ?? 0 + item.Qty;
                            _inventoryService.Update(inv, inv.Id);
                            balance = inv.BalanceQty;
                        }
                    }
                    else
                    {
                        Inventory inv = new Inventory();
                        inv.IsActive      = true;
                        inv.CreatedDate   = DateTime.Now;
                        inv.CreatedBy     = "";
                        inv.ProductId     = item.ProductId;
                        inv.ReceiveQty    = item.Qty;
                        inv.SupplierId    = cus.SupplierID;
                        inv.WarehouseId   = wareHouseId;
                        inv.BrandId       = item.BrandId;
                        inv.SizeId        = item.SizeId;
                        inv.APIId         = item.APIId;
                        inv.Faulty        = 0;
                        inv.OpeningQty    = 0;
                        inv.BalanceQty    = item.Qty;
                        inv.PurchasePrice = item.Rate;
                        inv.Costprice     = avgCostPrice;
                        inv.SalesPrice    = 0;
                        inv.GoodsType     = goodsType.ToString();
                        _inventoryService.Save(inv);
                        balance = item.Qty;
                    }

                    var invTransaction = new InventoryTransaction()
                    {
                        APIId           = item.APIId,
                        BalanceQty      = balance,
                        BrandId         = item.BrandId,
                        CreatedBy       = CurrentSession.GetCurrentSession().UserName,
                        CreatedDate     = DateTime.Now,
                        GoodsType       = goodsType.ToString(),
                        InventoryGuid   = Guid.NewGuid().ToString(),
                        InvoiceNo       = cus.InvoiceNo,
                        IsActive        = true,
                        ProductId       = item.ProductId,
                        PurchasePrice   = item.Rate,
                        CostPrice       = avgCostPrice,
                        Qty             = item.Qty,
                        SalesPrice      = 0,
                        SizeId          = item.SizeId,
                        SupplierId      = cus.SupplierID,
                        TransactionType = (int)Util.TransactionType.ReceiveQty,
                        WarehouseId     = item.WarehouseId ?? 0
                    };
                    _invTransactionService.Save(invTransaction);
                }
                // Ledger posting debit to purchase account

                var ledgerObj = new LedgerPosting();
                ledgerObj.VoucherTypeId = (int)VoucherTypeEnum.PurchaseInvoice;
                ledgerObj.VoucherNo     = result.InvoiceNoPaper;
                ledgerObj.PostingDate   = cus.InvoiceDate;
                ledgerObj.LedgerId      = (int)DefaultLedger.PurchaseAccount;
                ledgerObj.InvoiceNo     = cus.InvoiceNo;
                ledgerObj.Credit        = 0;
                ledgerObj.Debit         = cus.GrandTotal;
                ledgerObj.MasterId      = result.Id;
                var save = ledgerService.Save(ledgerObj);

                //Ledger posting to customer ledger credit
                var detailsLedger = new LedgerPosting();
                detailsLedger.VoucherTypeId = (int)VoucherTypeEnum.PurchaseInvoice;
                detailsLedger.VoucherNo     = result.InvoiceNoPaper;
                detailsLedger.PostingDate   = cus.InvoiceDate;
                detailsLedger.LedgerId      = supplier.LedgerId;
                detailsLedger.InvoiceNo     = cus.InvoiceNo;
                detailsLedger.Credit        = cus.TotalAmount - cus.BillDiscount;
                detailsLedger.Debit         = 0;
                detailsLedger.MasterId      = result.Id;
                var detailsLedgerResult = ledgerService.Save(detailsLedger);

                //save addisitonalCost
                if (additionalCosts != null && additionalCosts.Count > 0)
                {
                    foreach (var item in additionalCosts)
                    {
                        item.CreatedBy     = CurrentSession.GetCurrentSession().UserId;
                        item.CreatedDate   = DateTime.Now;
                        item.LedgerId      = supplier.LedgerId;
                        item.VoucherNo     = cus.InvoiceNo;
                        item.Extra1        = cus.AdditionalCostPurpose;
                        item.VoucherTypeId = (int)VoucherTypeEnum.PurchaseInvoice;
                        var isSaved = _addCostService.Save(item);
                    }
                    //
                    var additionalCost = new LedgerPosting();
                    additionalCost.VoucherTypeId = (int)VoucherTypeEnum.AdditionalCost;
                    additionalCost.VoucherNo     = result.InvoiceNoPaper;
                    additionalCost.PostingDate   = cus.InvoiceDate;
                    additionalCost.LedgerId      = (int)DefaultLedger.AdditionalCost;
                    additionalCost.InvoiceNo     = cus.InvoiceNo;
                    additionalCost.Credit        = cus.AdditionalCost;
                    additionalCost.Debit         = 0;
                    additionalCost.MasterId      = result.Id;
                    var _ = ledgerService.Save(additionalCost);
                }

                var party = new PartyBalance();
                party.InvoiceNo       = result.InvoiceNo;
                party.LedgerId        = supplier.LedgerId ?? 0;
                party.Credit          = cus.TotalAmount - cus.BillDiscount;
                party.CreditPeriod    = 60;
                party.Debit           = 0;
                party.MasterId        = result.Id;
                party.FinancialYearId = CurrentSession.GetCurrentSession().FinancialYear;
                party.PostingDate     = cus.InvoiceDate;
                party.VoucherTypeId   = (int)VoucherTypeEnum.PurchaseInvoice;
                party.VoucherNo       = result.InvoiceNo;
                party.extra1          = "Purchase Invoice: " + cus.InvoiceNo + " Paper Invoice No:" + cus.InvoiceNoPaper;
                party.extra2          = result.Id.ToString();
                partyBalanceService.Save(party);
            }
            return(cus);
        }
Beispiel #14
0
        public bool saveReceivedProds3(List <StationeryRetrievalProduct> srpList,
                                       int SRid,
                                       Employee warehousepacker,
                                       Employee storeclerk,
                                       List <StationeryRetrievalRequisitionForm> srrfList)
        {
            using (IDbContextTransaction transcat = db.Database.BeginTransaction())
            {
                try
                {
                    //Check for store clerk and warehouse packer
                    Employee _whpacker = empService.FindByUsernameAndPassword(warehousepacker.Username.ToLower(), warehousepacker.Password);
                    Employee _stclerk  = empService.FindByUsernameAndPassword(storeclerk.Username.ToLower(), storeclerk.Password);

                    if (_whpacker.EmployeeType.EmployeeTypeName != "Warehouse Packer")
                    {
                        throw new Exception("The user type is wrong");
                    }

                    if (_stclerk.EmployeeType.EmployeeTypeName != "Store Clerk" && _stclerk.EmployeeType.EmployeeTypeName != "Store Supervisor" && _stclerk.EmployeeType.EmployeeTypeName != "Store Manager")
                    {
                        throw new Exception("The user type is wrong");
                    }

                    if (_whpacker == null || _stclerk == null)
                    {
                        throw new Exception("The username or password is wrong, please login again");
                    }

                    DateTime transactDate = DateTime.Now;

                    //Create RF List
                    List <RequisitionForm> _rfList = new List <RequisitionForm>();

                    //Create new empty list to save to db
                    List <StationeryRetrievalProduct> _srpList = new List <StationeryRetrievalProduct>();

                    //Create new empty list to save to db
                    List <StationeryRetrievalRequisitionForm> _srrfList = new List <StationeryRetrievalRequisitionForm>();

                    //Find sr
                    StationeryRetrieval _sr = db.StationeryRetrievals.Find(SRid);
                    _sr.SRStatus        = SRStatus.PendingAssignment;
                    _sr.WarehousePacker = _whpacker;
                    _sr.SRRetrievalDate = transactDate;
                    _sr.StoreClerk      = _stclerk;
                    db.StationeryRetrievals.Update(_sr);
                    db.SaveChanges();



                    //Define invtrans Code
                    int count = invtService.FindInvTransByTodayCount();

                    foreach (StationeryRetrievalProduct srp in srpList)
                    {
                        if (srp.ProductReceivedTotal < 0)
                        {
                            throw new Exception("This value should not be negative");
                        }

                        count++;

                        StationeryRetrievalProduct _srp = db.StationeryRetrievalProduct.Find(srp.Id);
                        _srp.ProductReceivedTotal = srp.ProductReceivedTotal;
                        _srpList.Add(_srp);
                        db.StationeryRetrievalProduct.Update(_srp);
                        db.SaveChanges();

                        //Check for logic in terms of each RFP should not have more than what was specified


                        //create itCode
                        string invtransCode = "IT" + "/" + DateTime.Now.ToString("ddMMyy") + "/" + count.ToString();

                        //Create It
                        InventoryTransaction _it = new InventoryTransaction()
                        {
                            EmployeeId = _sr.StoreClerk.Id,
                            ProductId  = _srp.Product.Id,
                            Employee   = _sr.StoreClerk,
                            InventoryChangeQuantity = -_srp.ProductReceivedTotal,
                            InventoryTransComments  = _sr.SRCode,
                            InventoryTransDate      = _sr.SRRetrievalDate,
                            ITStatus = ITStatus.Auto,
                            ITCode   = invtransCode,
                            Product  = _srp.Product
                        };

                        db.InventoryTransactions.Add(_it);
                        db.SaveChanges();



                        //Adjust Inventory Quantity
                        Product _p = db.Products.Find(_srp.Product.Id);
                        _p.InventoryQuantity = _p.InventoryQuantity + _it.InventoryChangeQuantity;
                        if (_p.InventoryQuantity < 0)
                        {
                            throw new Exception(_p.InventoryQuantity + " is not enough");
                        }
                        db.Products.Update(_p);
                        db.SaveChanges();
                    }

                    foreach (StationeryRetrievalRequisitionForm srrf in srrfList)
                    {
                        StationeryRetrievalRequisitionForm _srrf = db.StationeryRetrievalRequisitionForms.Find(srrf.Id);
                        _srrf.SRRFStatus = SRRFStatus.PendingAssignment;
                        db.StationeryRetrievalRequisitionForms.Update(_srrf);
                        db.SaveChanges();

                        RequisitionForm _rf = db.RequisitionForms.Find(_srrf.RequisitionForm.Id);
                        _rf.RFStatus = RFStatus.Ongoing;

                        db.RequisitionForms.Update(_rf);
                        db.SaveChanges();
                    }
                    db.SaveChanges();

                    transcat.Commit();
                    return(true);
                }
                catch
                {
                    transcat.Rollback();
                    return(false);
                }
            }
        }
Beispiel #15
0
        public IActionResult getMutasi(String StoreCode)
        {
            List <InventoryTransactionLines> listtransline = _context.InventoryTransactionLines.ToList();
            List <Item>                 listitem           = _context.Item.ToList();
            List <MutasiOrder>          deliveryOrders     = new List <MutasiOrder>();
            List <InventoryTransaction> dos = _context.InventoryTransaction.Where(c => c.WarehouseOriginal == StoreCode && c.TransactionTypeId == RetailEnum.MutasiOrderOut && c.InforBypass == true).ToList();

            foreach (InventoryTransaction intrans in dos)
            {
                // tambah ini

                InventoryTransaction inventory = intrans;
                //========
                //Select For Header
                MutasiOrder doObj = new MutasiOrder
                {
                    date          = DateTime.Now.ToString("yyyy-MM-dd"),
                    id            = inventory.Id,
                    mutasiOrderId = inventory.TransactionId,

                    status              = inventory.StatusId.HasValue ? inventory.StatusId.Value : 0,
                    totalQty            = inventory.TotalQty.HasValue ? inventory.TotalQty.Value : 0,
                    mutasiFromWarehouse = inventory.WarehouseOriginal,
                    mutasiToWarehouse   = inventory.WarehouseDestination,
                    isPbmPbk            = inventory.InforBypass.HasValue ? inventory.InforBypass.Value : false,
                    totalAmount         = _context.InventoryTransactionLines.Where(c => c.InventoryTransactionId == inventory.Id).Sum(d => d.ValueSalesPrice),
                };

                List <MutasiOrderLine> deliveryOrderLines = new List <MutasiOrderLine>();
                int sumLines = 0;
                //  List<InventoryTransactionLines> dosLines = _context.InventoryTransactionLines.Where(c => c.InventoryTransactionId == intrans.Id).ToList();
                List <InventoryTransactionLines> dosLines = _context.InventoryTransactionLines.Where(c => c.InventoryTransactionId == inventory.Id).ToList();


                foreach (InventoryTransactionLines doObjLines in dosLines)
                {
                    //
                    int idx2 = indexttransline(doObjLines.Id, listtransline);
                    InventoryTransactionLines invenlines = listtransline[idx2];
                    int  idx3 = indextitems(invenlines.ArticleId, listitem);
                    Item item = listitem[idx3];



                    MutasiOrderLine doLine = new MutasiOrderLine
                    {
                        id      = invenlines.Id,
                        article = new Article
                        {
                            articleId      = item.ItemId,
                            articleIdAlias = item.ItemIdAlias,
                            articleName    = invenlines.ArticleName
                        },
                        articleIdFk     = item.Id,
                        mutasiOrderIdFk = inventory.Id,
                        mutasiOrderId   = inventory.TransactionId,
                        quantity        = invenlines.Qty.Value
                    };
                    deliveryOrderLines.Add(doLine);
                }

                doObj.totalQty         = inventory.TotalQty.Value;
                doObj.mutasiOrderLines = deliveryOrderLines;
                deliveryOrders.Add(doObj);
            }
            return(Ok(deliveryOrders));
        }
        public void RecordLocationTransaction(OrderLocationTransaction orderLocationTransaction, InventoryTransaction inventoryTransaction, InProcessLocation inProcessLocation, User user)
        {
            LocationTransaction locationTransaction = GenerateOrderLocationTransaction(orderLocationTransaction, inventoryTransaction.Location, user);

            if (inventoryTransaction.Hu != null)
            {
                locationTransaction.HuId  = inventoryTransaction.Hu.HuId;
                locationTransaction.LotNo = inventoryTransaction.Hu.LotNo;
            }
            if (locationTransaction.LotNo == null || locationTransaction.LotNo == string.Empty)
            {
                locationTransaction.LotNo = inventoryTransaction.LotNo;
            }
            locationTransaction.BatchNo       = inventoryTransaction.LocationLotDetailId;
            locationTransaction.IpNo          = inProcessLocation.IpNo;
            locationTransaction.Qty           = inventoryTransaction.Qty;
            locationTransaction.EffectiveDate = DateTime.Parse(inProcessLocation.CreateDate.ToString("yyyy-MM-dd"));

            if (inventoryTransaction.Location.Code == BusinessConstants.SYSTEM_LOCATION_REJECT)
            {
                locationTransaction.RefLocation = inventoryTransaction.RefLocation;
            }

            this.CreateLocationTransaction(locationTransaction);
        }
Beispiel #17
0
        public ETL_InventoryTransaction ExtractInventoryTransaction(Session session, Guid InventoryTransactionId)
        {
            ETL_InventoryTransaction result = null;

            try
            {
                InventoryTransaction transaction = session.GetObjectByKey <InventoryTransaction>(InventoryTransactionId);
                if (transaction != null)
                {
                    result = new ETL_InventoryTransaction();
                    if (transaction.AccountingPeriodId != null)
                    {
                        result.AccountingPeriodId = transaction.AccountingPeriodId.AccountingPeriodId;
                    }
                    result.Code                   = transaction.Code;
                    result.CreateDate             = transaction.CreateDate;
                    result.Description            = transaction.Description;
                    result.InventoryTransactionId = transaction.InventoryTransactionId;
                    result.IssueDate              = transaction.IssueDate;
                    result.InventoryJournalList   = new List <ETL_InventoryJournal>();
                    result.COGSList               = new List <ETL_COGS>();
                    foreach (InventoryJournal journal in transaction.InventoryJournals)
                    {
                        if (journal.RowStatus >= 0)
                        {
                            ETL_InventoryJournal newJournal = new ETL_InventoryJournal();
                            if (journal.AccountId != null)
                            {
                                newJournal.AccountId = journal.AccountId.AccountId;
                            }
                            newJournal.Credit = journal.Credit;
                            newJournal.Debit  = journal.Debit;
                            if (journal.InventoryId != null)
                            {
                                newJournal.InventoryId = journal.InventoryId.InventoryId;
                            }
                            newJournal.InventoryJournalId = journal.InventoryJournalId;
                            if (journal.InventoryTransactionId != null)
                            {
                                newJournal.InventoryTransactionId = journal.InventoryTransactionId.InventoryTransactionId;
                            }
                            if (journal.ItemUnitId != null)
                            {
                                newJournal.ItemUnitId = journal.ItemUnitId.ItemUnitId;
                            }
                            newJournal.JournalType = journal.JournalType;
                            if (journal.LotId != null)
                            {
                                newJournal.LotId = journal.LotId.LotId;
                            }
                            newJournal.Description = journal.Description;
                            newJournal.CreateDate  = journal.CreateDate;
                            result.InventoryJournalList.Add(newJournal);
                        }
                    }

                    foreach (COGS cogs in transaction.COGSs)
                    {
                        ETL_COGS newCOGS = new ETL_COGS();
                        newCOGS.Amount      = cogs.Amount;
                        newCOGS.Assumption  = cogs.Assumption;
                        newCOGS.Balance     = cogs.Balance;
                        newCOGS.COGSPrice   = cogs.COGSPrice;
                        newCOGS.COGSId      = cogs.COGSId;
                        newCOGS.Credit      = cogs.Credit;
                        newCOGS.Debit       = cogs.Debit;
                        newCOGS.Description = cogs.Description;
                        newCOGS.CreateDate  = cogs.CreateDate;
                        newCOGS.IssueDate   = cogs.IssueDate;
                        newCOGS.UpdateDate  = cogs.UpdateDate;
                        if (cogs.InventoryId != null)
                        {
                            newCOGS.InventoryId = cogs.InventoryId.InventoryId;
                        }
                        if (cogs.InventoryTransactionId != null)
                        {
                            newCOGS.InventoryTransactionId = cogs.InventoryTransactionId.InventoryTransactionId;
                        }
                        if (cogs.ItemUnitId != null)
                        {
                            newCOGS.ItemUnitId = cogs.ItemUnitId.ItemUnitId;
                        }
                        if (cogs.CurrencyId != null)
                        {
                            newCOGS.CurrencyId = cogs.CurrencyId.CurrencyId;
                        }
                        newCOGS.Price = cogs.Price;
                        newCOGS.Total = cogs.Total;
                        result.COGSList.Add(newCOGS);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(result);
        }
Beispiel #18
0
        private Repack CreateRepack(IList <RepackDetail> repackDetailList, string type, User user)
        {
            IList <RepackDetail> inRepackDetailList  = new List <RepackDetail>();
            IList <RepackDetail> outRepackDetailList = new List <RepackDetail>();
            bool hasHu = false;

            #region 判断RepackDetailList是否为空
            if (repackDetailList != null && repackDetailList.Count > 0)
            {
                foreach (RepackDetail repackDetail in repackDetailList)
                {
                    if (repackDetail.Qty != 0)
                    {
                        if (repackDetail.IOType == BusinessConstants.IO_TYPE_IN)
                        {
                            inRepackDetailList.Add(repackDetail);
                        }
                        else if (repackDetail.IOType == BusinessConstants.IO_TYPE_OUT)
                        {
                            outRepackDetailList.Add(repackDetail);
                            if (!hasHu && repackDetail.Hu != null)
                            {
                                hasHu = true;
                            }
                        }
                        else
                        {
                            throw new TechnicalException("Invalid IO Type:" + repackDetail.IOType);
                        }
                    }
                }

                #region 翻箱的如果没有输出,将输入代码合并,生成一张新条码
                if (outRepackDetailList.Count == 0 && type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_REPACK)
                {
                    Hu inHu  = inRepackDetailList[0].Hu;
                    Hu outHu = new Hu();
                    CloneHelper.CopyProperty(inHu, outHu);
                    outHu.OrderNo    = null;
                    outHu.ReceiptNo  = null;
                    outHu.Location   = null;
                    outHu.StorageBin = null;
                    outHu.Status     = BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE;

                    string repackShift = entityPreferenceMgr.LoadEntityPreference(BusinessConstants.ENTITY_PREFERENCE_CODE_REPACK_SHIFT).Value;

                    string prefix = inHu.HuId.Substring(0, inHu.HuId.Length - 4) + repackShift;
                    outHu.HuId       = numberControlMgr.GenerateNumber(prefix, 3);
                    outHu.Qty        = (from l in inRepackDetailList select l.Qty).Sum();
                    outHu.UnitCount  = outHu.Qty;
                    outHu.LotSize    = outHu.UnitCount;
                    outHu.PrintCount = 0;
                    huMgr.CreateHu(outHu);

                    RepackDetail outRepackDetail = new RepackDetail();
                    outRepackDetail.Hu       = outHu;
                    outRepackDetail.IOType   = BusinessConstants.IO_TYPE_OUT;
                    outRepackDetail.Qty      = outHu.Qty;
                    outRepackDetail.itemCode = outHu.Item.Code;
                    outRepackDetailList.Add(outRepackDetail);
                }
                #endregion

                if (inRepackDetailList.Count == 0 || outRepackDetailList.Count == 0)
                {
                    throw new BusinessErrorException("MasterData.Inventory.Repack.Error.RepackDetailEmpty");
                }
                if (hasHu && type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_DEVANNING && outRepackDetailList.Count < 2)
                {
                    throw new BusinessErrorException("MasterData.Inventory.Devanning.Error.DevanningDetailLessThanTwo");
                }
            }
            else
            {
                throw new BusinessErrorException("MasterData.Inventory.Repack.Error.RepackDetailEmpty");
            }
            #endregion

            #region 判断是否被拣货
            foreach (RepackDetail inRepackDetail in inRepackDetailList)
            {
                if (inRepackDetail.LocationLotDetail.Hu != null && this.locationMgr.IsHuOcuppyByPickList(inRepackDetail.LocationLotDetail.Hu.HuId))
                {
                    throw new BusinessErrorException("MasterData.Inventory.Repack.Error.HuOccupied", inRepackDetail.Hu.HuId);
                }
            }
            #endregion

            #region 判断翻箱后条码是否为新条码
            foreach (RepackDetail outRepackDetail in outRepackDetailList)
            {
                if (outRepackDetail.Hu != null && outRepackDetail.Hu.Status != BusinessConstants.CODE_MASTER_STATUS_VALUE_CREATE)
                {
                    throw new BusinessErrorException("MasterData.Inventory.Repack.Error.HuStatusNotCreate", outRepackDetail.Hu.HuId);
                }
            }
            #endregion

            #region 检查In和Out明细数量是否匹配
            IDictionary <string, decimal> inItemQtyDic = new Dictionary <string, decimal>();
            Location location = null;

            #region 收集In数量
            foreach (RepackDetail inRepackDetail in inRepackDetailList)
            {
                LocationLotDetail inLocationLotDetail = this.locationLotDetailMgr.LoadLocationLotDetail(inRepackDetail.LocationLotDetail.Id);

                if (location == null)
                {
                    location = inLocationLotDetail.Location;

                    if (!user.HasPermission(inLocationLotDetail.Location.Region.Code))
                    {
                        throw new BusinessErrorException("MasterData.Inventory.Repack.Error.NoPermission", location.Code);
                    }
                }
                else if (location.Code != inLocationLotDetail.Location.Code)
                {
                    throw new BusinessErrorException("MasterData.Inventory.Repack.Error.InRepackDetailLocationNotEqual");
                }

                if (inItemQtyDic.ContainsKey(inLocationLotDetail.Item.Code))
                {
                    inItemQtyDic[inLocationLotDetail.Item.Code] += inRepackDetail.Qty;
                }
                else
                {
                    inItemQtyDic.Add(inLocationLotDetail.Item.Code, inRepackDetail.Qty);
                }
            }
            #endregion

            #region 收集Out数量
            IDictionary <string, decimal> outItemQtyDic = new Dictionary <string, decimal>();

            foreach (RepackDetail outRepackDetail in outRepackDetailList)
            {
                if (type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_REPACK)
                {
                    if (outRepackDetail.Hu == null)
                    {
                        throw new BusinessErrorException("MasterData.Inventory.Repack.Error.HuIdIsEmpty");
                    }
                    else
                    {
                        if (outItemQtyDic.ContainsKey(outRepackDetail.Hu.Item.Code))
                        {
                            outItemQtyDic[outRepackDetail.Hu.Item.Code] += outRepackDetail.Qty;
                        }
                        else
                        {
                            outItemQtyDic.Add(outRepackDetail.Hu.Item.Code, outRepackDetail.Qty);
                        }
                    }
                }
                else if (type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_DEVANNING)
                {
                    string itemCode = outRepackDetail.Hu != null ? outRepackDetail.Hu.Item.Code : outRepackDetail.itemCode;

                    if (itemCode == null)
                    {
                        throw new TechnicalException("ItemCode not specified.");
                    }

                    if (outItemQtyDic.ContainsKey(itemCode))
                    {
                        outItemQtyDic[itemCode] += outRepackDetail.Qty;
                    }
                    else
                    {
                        outItemQtyDic.Add(itemCode, outRepackDetail.Qty);
                    }
                }
                else
                {
                    throw new TechnicalException("Repack type: " + type + " is not valided.");
                }
            }
            #endregion

            #region 比较
            if (inItemQtyDic.Count != outItemQtyDic.Count)
            {
                throw new BusinessErrorException("MasterData.Inventory.Repack.Error.InOutQtyNotMatch");
            }

            foreach (string itemCode in inItemQtyDic.Keys)
            {
                if (outItemQtyDic.ContainsKey(itemCode))
                {
                    decimal inQty  = inItemQtyDic[itemCode];
                    decimal outQty = outItemQtyDic[itemCode];

                    //是否自动创建剩余数量的记录
                    bool autoCreate = bool.Parse(entityPreferenceMgr.LoadEntityPreference(BusinessConstants.ENTITY_PREFERENCE_CODE_AUTO_CREATE_WHEN_DEAVING).Value);

                    #region 拆箱根据剩余数量得到剩余数量的条码
                    if (autoCreate && type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_DEVANNING && inQty > outQty)
                    {
                        RepackDetail remainRepackDetail = CloneHelper.DeepClone(inRepackDetailList[0]);
                        remainRepackDetail.Qty    = inQty - outQty;
                        remainRepackDetail.IOType = BusinessConstants.IO_TYPE_OUT;
                        outRepackDetailList.Add(remainRepackDetail);
                    }
                    #endregion

                    else if (inQty != outQty)
                    {
                        throw new BusinessErrorException("MasterData.Inventory.Repack.Error.InOutQtyNotMatch");
                    }
                }
                else
                {
                    throw new BusinessErrorException("MasterData.Inventory.Repack.Error.InOutItemNotMatch", itemCode);
                }
            }
            #endregion
            #endregion

            #region 创建翻箱单头
            Repack repack = new Repack();
            repack.RepackNo   = this.numberControlMgr.GenerateNumber(BusinessConstants.CODE_PREFIX_REPACK);
            repack.CreateDate = DateTime.Now;
            repack.CreateUser = user;
            repack.Type       = type;

            this.CreateRepack(repack);
            #endregion

            #region 创建翻箱单明细
            Int32?plannedBillId = null;   //拆箱传递PlannedBill
            foreach (RepackDetail inRepackDetail in inRepackDetailList)
            {
                //出库
                inRepackDetail.Repack = repack;
                this.locationMgr.InventoryRepackIn(inRepackDetail, user);

                this.repackDetailMgr.CreateRepackDetail(inRepackDetail);

                if (repack.Type == BusinessConstants.CODE_MASTER_REPACK_TYPE_VALUE_DEVANNING)
                {
                    plannedBillId = inRepackDetail.LocationLotDetail.IsConsignment ? inRepackDetail.LocationLotDetail.PlannedBill : null;
                }
            }

            foreach (RepackDetail outRepackDetail in outRepackDetailList)
            {
                //入库
                outRepackDetail.Repack = repack;
                InventoryTransaction inventoryTransaction = this.locationMgr.InventoryRepackOut(outRepackDetail, location, plannedBillId, user);
                outRepackDetail.LocationLotDetail = this.locationLotDetailMgr.LoadLocationLotDetail(inventoryTransaction.LocationLotDetailId);

                this.repackDetailMgr.CreateRepackDetail(outRepackDetail);
            }
            #endregion

            return(repack);
        }
 public InventoryTransaction SubmitReceiveInventoryTransaction(InventoryTransaction model, string deliveryNumber, int tenantId, int warehouseId, int userId)
 {
     return(PurchaseOrderService.SubmitReceiveInventoryTransaction(model, deliveryNumber, tenantId, warehouseId, userId));
 }
        public List <Article> getArticle(String customerCode)
        {
            List <Article> allArticle = new List <Article>();

            try
            {
                Customer       customer        = _context.Customer.Where(c => c.CustId == customerCode).First();
                Store          store           = _context.Store.Where(c => c.Id == customer.StoreId).First();
                List <Article> listArtice      = new List <Article>();
                var            priceMaster     = _context.PriceList;
                var            itemMaster      = _context.Item;
                var            inventoryMaster = _context.InventoryLines.Where(c => c.WarehouseId == store.Code);
                var            itemPrice       =
                    from price in priceMaster
                    join item in itemMaster on price.ItemId equals item.ItemIdAlias
                    join inventoryLines in inventoryMaster on item.Id equals inventoryLines.ItemId
                    select new Article
                {
                    id             = item.Id,
                    price          = price.SalesPrice,
                    articleId      = item.ItemId,
                    articleIdAlias = item.ItemIdAlias,
                    articleName    = item.Name,
                    itemGroup      = item.ItemGroup,
                    unit           = "PCS",
                    isService      = item.IsServiceItem.HasValue ? item.IsServiceItem.Value : false
                };
                allArticle = itemPrice.ToList();

                //  List<InventoryTransaction> deliveryOrder = _context.InventoryTransaction.Where(c => c.WarehouseDestination == store.Code && c.TransactionTypeId == Config.RetailEnum.doTransaction && c.StatusId == Config.RetailEnum.doStatusPending).ToList();
                List <InventoryTransaction> deliveryOrder = _context.InventoryTransaction.Where(c => c.WarehouseDestination == store.Code && c.TransactionTypeId == Config.RetailEnum.doTransaction).ToList();
                if (deliveryOrder.Count > 0)
                {
                    for (int i = 0; i < deliveryOrder.Count; i++)
                    {
                        InventoryTransaction             inventoryTransaction = deliveryOrder[i];
                        List <InventoryTransactionLines> list = _context.InventoryTransactionLines.Where(c => c.InventoryTransactionId == inventoryTransaction.Id).ToList();
                        for (int j = 0; j < list.Count; j++)
                        {
                            InventoryTransactionLines inventoryTransactionLines = list[j];
                            try
                            {
                                //check if exist in current item;

                                bool isItemExistInCurrent = allArticle.Any(c => c.articleIdAlias == list[j].ArticleId); //sebelum ny c.artileid //ganti itemprice.any jadi allitem.any
                                if (!isItemExistInCurrent)
                                {
                                    Item    item    = itemMaster.Where(c => c.ItemIdAlias == inventoryTransactionLines.ArticleId).First();// sbelum ny c.ItemId
                                    Article article = new Article();

                                    article.id = item.Id;
                                    if (priceMaster.Any(c => c.ItemId == item.ItemIdAlias))
                                    {
                                        article.price = priceMaster.Where(c => c.ItemId == item.ItemIdAlias).First().SalesPrice;
                                    }
                                    else
                                    {
                                        article.price = 0;
                                    }
                                    article.articleId      = item.ItemId;
                                    article.articleIdAlias = item.ItemIdAlias;
                                    article.articleName    = item.Name;
                                    article.unit           = "PCS";
                                    allArticle.Add(article);
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(allArticle);
        }
Beispiel #21
0
 public TableData ExportData(InventoryTransaction entity)
 {
     return(_app.ExportData(entity));
 }
Beispiel #22
0
        LoadInventoryLedger(Session session, List <ETL_InventoryLedger> ledgerList)
        {
            try
            {
                if (ledgerList == null)
                {
                    return;
                }
                if (ledgerList.Count == 0)
                {
                    return;
                }
                if (ledgerList.Any() == false)
                {
                    return;
                }
                InventoryTransaction invTransaction = session.GetObjectByKey <InventoryTransaction>((ledgerList.FirstOrDefault()).InventoryTransactionId);
                if (invTransaction == null)
                {
                    return;
                }

                CriteriaOperator criteria_RowStatus = new BinaryOperator("RowStatus", Constant.ROWSTATUS_ACTIVE, BinaryOperatorType.GreaterOrEqual);
                CriteriaOperator criteria_Inventory = new BinaryOperator("InventoryTransactionId", invTransaction, BinaryOperatorType.Equal);

                CriteriaOperator criteria = CriteriaOperator.And(criteria_Inventory, criteria_RowStatus);

                XPCollection <InventoryLedger> OldInventoryLedger = new XPCollection <InventoryLedger>(session, criteria);

                foreach (InventoryLedger ledger in OldInventoryLedger)
                {
                    ledger.RowStatus = Constant.ROWSTATUS_DELETED;
                    ledger.Save();
                }

                foreach (ETL_InventoryLedger ledger in ledgerList)
                {
                    InventoryLedger newInventoryLedger = new InventoryLedger(session);
                    newInventoryLedger.AccountId              = session.GetObjectByKey <Account>(ledger.AccountId);
                    newInventoryLedger.CreateDate             = ledger.CreateDate;
                    newInventoryLedger.Credit                 = ledger.Credit;
                    newInventoryLedger.Debit                  = ledger.Debit;
                    newInventoryLedger.Balance                = ledger.Debit - ledger.Credit;
                    newInventoryLedger.Description            = ledger.Description;
                    newInventoryLedger.InventoryId            = session.GetObjectByKey <NAS.DAL.Nomenclature.Inventory.Inventory>(ledger.InventoryId);
                    newInventoryLedger.InventoryTransactionId = session.GetObjectByKey <InventoryTransaction>(ledger.InventoryTransactionId);
                    newInventoryLedger.IsOriginal             = ledger.IsOriginal;
                    newInventoryLedger.IssueDate              = ledger.IssueDate;
                    newInventoryLedger.ItemUnitId             = session.GetObjectByKey <ItemUnit>(ledger.ItemUnitId);
                    newInventoryLedger.LotId                  = session.GetObjectByKey <Lot>(ledger.LotId);
                    newInventoryLedger.RowStatus              = Constant.ROWSTATUS_ACTIVE;
                    newInventoryLedger.UpdateDate             = DateTime.Now;
                    InventoryLedger preInventoryLedger = GetPreviousInventoryLedger(session, newInventoryLedger);
                    if (preInventoryLedger != null)
                    {
                        newInventoryLedger.Balance += preInventoryLedger.Balance;
                    }
                    newInventoryLedger.Save();
                }
            }
            catch (Exception)
            {
                return;
            }
        }
Beispiel #23
0
 public void Ins(InventoryTransaction entity)
 {
     _app.Add(entity);
 }
        /// <summary>
        /// Update Purchase Order Detail
        /// </summary>
        /// <param name="purchaseOrderDetailDataTransformation"></param>
        /// <returns></returns>
        public async Task <ResponseModel <PurchaseOrderDetailDataTransformation> > UpdatePurchaseOrderDetail(PurchaseOrderDetailDataTransformation purchaseOrderDetailDataTransformation)
        {
            ResponseModel <PurchaseOrderDetailDataTransformation> returnResponse = new ResponseModel <PurchaseOrderDetailDataTransformation>();

            PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();

            try
            {
                int accountId             = purchaseOrderDetailDataTransformation.AccountId;
                int purchaseOrderId       = purchaseOrderDetailDataTransformation.PurchaseOrderId;
                int purchaseOrderDetailId = purchaseOrderDetailDataTransformation.PurchaseOrderDetailId;

                if (purchaseOrderDetailDataTransformation.CurrentReceivedQuantity == 0)
                {
                    returnResponse.ReturnMessage.Add("Invalid Received Quantity");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }

                _inventoryManagementDataService.OpenConnection(_connectionStrings.PrimaryDatabaseConnectionString);
                _inventoryManagementDataService.BeginTransaction((int)IsolationLevel.Serializable);

                PurchaseOrder purchaseOrder = await _inventoryManagementDataService.GetPurchaseOrderHeader(accountId, purchaseOrderId);

                if (purchaseOrder == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Purchase Order not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }

                purchaseOrderDetail = await _inventoryManagementDataService.GetPurchaseOrderDetailForUpdate(purchaseOrderDetailId);

                if (purchaseOrderDetail == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Purchase Order Detail not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }

                purchaseOrderDetail.ReceivedQuantity = purchaseOrderDetail.ReceivedQuantity + purchaseOrderDetailDataTransformation.CurrentReceivedQuantity;

                await _inventoryManagementDataService.UpdatePurchaseOrderDetail(purchaseOrderDetail);

                Product product = await _inventoryManagementDataService.GetProductInformationForUpdate(purchaseOrderDetail.ProductId);

                if (product == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Product not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }

                double newAverageCost = CalculateAverageCost(product.OnHandQuantity, product.AverageCost, purchaseOrderDetailDataTransformation.CurrentReceivedQuantity, purchaseOrderDetail.UnitPrice);
                if (newAverageCost != 0)
                {
                    product.AverageCost = newAverageCost;
                }

                product.OnHandQuantity = product.OnHandQuantity + purchaseOrderDetailDataTransformation.CurrentReceivedQuantity;

                await _inventoryManagementDataService.UpdateProduct(product);

                InventoryTransaction inventoryTransaction = new InventoryTransaction();
                inventoryTransaction.EntityId        = purchaseOrderDetail.PurchaseOrderDetailId;
                inventoryTransaction.MasterEntityId  = purchaseOrderDetail.MasterPurchaseOrderDetailId;
                inventoryTransaction.ProductId       = purchaseOrderDetail.ProductId;
                inventoryTransaction.UnitCost        = purchaseOrderDetail.UnitPrice;
                inventoryTransaction.Quantity        = purchaseOrderDetailDataTransformation.CurrentReceivedQuantity;
                inventoryTransaction.TransactionDate = DateTime.UtcNow;

                await _inventoryManagementDataService.CreateInventoryTransaction(inventoryTransaction);

                TransactionQueueOutbound transactionQueue = new TransactionQueueOutbound();
                transactionQueue.Payload         = GenerateInventoryTransactionPayload(inventoryTransaction);
                transactionQueue.TransactionCode = TransactionQueueTypes.InventoryReceived;
                transactionQueue.ExchangeName    = MessageQueueExchanges.InventoryManagement;

                await _inventoryManagementDataService.CreateOutboundTransactionQueue(transactionQueue);

                //await _inventoryManagementDataService.UpdateDatabase();

                _inventoryManagementDataService.CommitTransaction();

                returnResponse.ReturnStatus = true;
            }
            catch (Exception ex)
            {
                _inventoryManagementDataService.RollbackTransaction();
                returnResponse.ReturnStatus = false;
                returnResponse.ReturnMessage.Add(ex.Message);
            }
            finally
            {
                _inventoryManagementDataService.CloseConnection();
            }

            returnResponse.Entity = purchaseOrderDetailDataTransformation;

            return(returnResponse);
        }
Beispiel #25
0
        protected void AddCreateInventoryTransactionCommand(InventoryTransaction transaction)
        {
            var createInventoryTransactionCommand = new CreateInventoryTransaction(transaction);

            Commands.Add(createInventoryTransactionCommand);
        }
        /// <summary>
        /// Update Sales Order Detail
        /// </summary>
        /// <param name="salesOrderDetailDataTransformation"></param>
        /// <returns></returns>
        public async Task <ResponseModel <SalesOrderDetailDataTransformation> > UpdateSalesOrderDetail(SalesOrderDetailDataTransformation salesOrderDetailDataTransformation)
        {
            ResponseModel <SalesOrderDetailDataTransformation> returnResponse = new ResponseModel <SalesOrderDetailDataTransformation>();

            SalesOrderDetail salesOrderDetail = new SalesOrderDetail();

            try
            {
                int accountId          = salesOrderDetailDataTransformation.AccountId;
                int salesOrderId       = salesOrderDetailDataTransformation.SalesOrderId;
                int salesOrderDetailId = salesOrderDetailDataTransformation.SalesOrderDetailId;
                //
                //	Validate Shipped Quantity
                //
                if (salesOrderDetailDataTransformation.CurrentShippedQuantity == 0)
                {
                    returnResponse.ReturnMessage.Add("Invalid Shipped Quantity");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }
                //
                //	Begin a Serializable Transaction
                //
                _inventoryManagementDataService.OpenConnection(_connectionStrings.PrimaryDatabaseConnectionString);
                _inventoryManagementDataService.BeginTransaction((int)IsolationLevel.Serializable);
                //
                //	Get Sales Order Header
                //
                SalesOrder salesOrder = await _inventoryManagementDataService.GetSalesOrderHeader(accountId, salesOrderId);

                if (salesOrder == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Sales Order not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }
                //
                //	Get Sales Order Detail
                //
                salesOrderDetail = await _inventoryManagementDataService.GetSalesOrderDetailForUpdate(salesOrderDetailId);

                if (salesOrderDetail == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Sales Order Detail not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }
                //
                //	Update Sales Order Shipped Quantity
                //
                salesOrderDetail.ShippedQuantity = salesOrderDetail.ShippedQuantity + salesOrderDetailDataTransformation.CurrentShippedQuantity;

                await _inventoryManagementDataService.UpdateSalesOrderDetail(salesOrderDetail);

                //
                //	Get Product Record with an exclusive update lock
                //
                Product product = await _inventoryManagementDataService.GetProductInformationForUpdate(salesOrderDetail.ProductId);

                if (product == null)
                {
                    _inventoryManagementDataService.RollbackTransaction();

                    returnResponse.ReturnMessage.Add("Product not found");
                    returnResponse.ReturnStatus = false;

                    return(returnResponse);
                }
                //
                //	Reduce Product OnHand Quantity by the quantity shipped
                //
                product.OnHandQuantity = product.OnHandQuantity - salesOrderDetailDataTransformation.CurrentShippedQuantity;

                await _inventoryManagementDataService.UpdateProduct(product);

                //
                //	Create Inventory Transaction Record
                //
                InventoryTransaction inventoryTransaction = new InventoryTransaction();
                inventoryTransaction.EntityId        = salesOrderDetail.SalesOrderDetailId;
                inventoryTransaction.MasterEntityId  = salesOrderDetail.MasterSalesOrderDetailId;
                inventoryTransaction.ProductId       = salesOrderDetail.ProductId;
                inventoryTransaction.UnitCost        = product.AverageCost;
                inventoryTransaction.Quantity        = salesOrderDetailDataTransformation.CurrentShippedQuantity;
                inventoryTransaction.TransactionDate = DateTime.UtcNow;

                await _inventoryManagementDataService.CreateInventoryTransaction(inventoryTransaction);

                //
                //	Create Transaction Queue record and create inventory transaction payload
                //
                TransactionQueueOutbound transactionQueue = new TransactionQueueOutbound();
                transactionQueue.Payload         = GenerateInventoryTransactionPayload(inventoryTransaction);
                transactionQueue.TransactionCode = TransactionQueueTypes.InventoryShipped;
                transactionQueue.ExchangeName    = MessageQueueExchanges.InventoryManagement;

                await _inventoryManagementDataService.CreateOutboundTransactionQueue(transactionQueue);

                //await _inventoryManagementDataService.UpdateDatabase();

                //
                //	Commit Transaction
                //
                _inventoryManagementDataService.CommitTransaction();

                returnResponse.ReturnStatus = true;
            }
            catch (Exception ex)
            {
                _inventoryManagementDataService.RollbackTransaction();
                returnResponse.ReturnStatus = false;
                returnResponse.ReturnMessage.Add(ex.Message);
            }
            finally
            {
                _inventoryManagementDataService.CloseConnection();
            }

            returnResponse.Entity = salesOrderDetailDataTransformation;

            return(returnResponse);
        }
Beispiel #27
0
        public bool Save(List <StockOutRequest> stockOuts, string invoiceNo, string Notes)
        {
            var balance        = 0.0m;
            var inventoryLists = stockOuts.Select(a => a.InventoryId).ToList();
            var existingItem   = inventory.GetAll(a => inventoryLists.Contains(a.Id) && a.IsActive == true).ToList();

            if (existingItem.Count > 0)
            {
                var stocks = new List <StockOut>();
                foreach (var inv in existingItem)
                {
                    var qty   = stockOuts.Where(a => a.InventoryId == inv.Id).Sum(a => a.Qty);
                    var stock = new StockOut()
                    {
                        AlreadyProcessed = false,
                        BaleQty          = qty,
                        ProductId        = inv.ProductId,
                        IsActive         = true,
                        InvoiceNo        = invoiceNo,
                        Notes            = Notes,
                        SupplierId       = inv.SupplierId,
                        WarehouseId      = inv.WarehouseId,
                        CreatedBy        = CurrentSession.GetCurrentSession().UserName,
                        CreatedDate      = DateTime.Now,
                        SizeId           = inv.SizeId,
                        SizeName         = inv.Size.Name,
                        BrandId          = inv.BrandId,
                        BrandName        = inv.Brand.BrandName,
                        APIId            = inv.APIId,
                        InventoryId      = inv.Id,
                        Rate             = inv.PurchasePrice,
                        StockOutPrice    = inv.PurchasePrice * qty,
                        ProductionDate   = DateTime.Now
                    };
                    inv.UpdatedDate    = DateTime.Now;
                    inv.UpdatedBy      = CurrentSession.GetCurrentSession().UserName;
                    inv.ProductionOut += qty;
                    inv.BalanceQty     = inv.BalanceQty - qty;
                    balance            = inv.BalanceQty;
                    inventory.Update(inv, inv.Id);
                    stocks.Add(stock);
                    var invTransaction = new InventoryTransaction()
                    {
                        APIId         = stock.APIId,
                        BalanceQty    = balance,
                        BrandId       = stock.BrandId,
                        CreatedBy     = CurrentSession.GetCurrentSession().UserName,
                        CreatedDate   = DateTime.Now,
                        GoodsType     = "Finished Goods",
                        InventoryGuid = Guid.NewGuid().ToString(),
                        InvoiceNo     = "",
                        IsActive      = true,
                        ProductId     = stock.ProductId ?? 0,
                        PurchasePrice = 0,
                        Qty           = stock.BaleQty,
                        SalesPrice    = 0,
                        SizeId        = stock.SizeId,
                        SupplierId    = stock.SupplierId ?? 0,

                        TransactionType = (int)Util.TransactionType.ProductionOut,
                        WarehouseId     = stock.WarehouseId ?? 0
                    };
                    _invTransactionService.Save(invTransaction);
                }
                service.Save(stocks);
                return(true);
            }
            else
            {
                return(false);
            }
        }
 public Task <bool> AddTransaction(Inventory inventory, InventoryTransaction inventoryTransaction)
 {
     throw new NotImplementedException();
 }
Beispiel #29
0
        public async Task <List <DeliveryOrder> > getDO(String StoreCode)
        {
            List <DeliveryOrder> deliveryOrders = new List <DeliveryOrder>();

            List <InventoryTransaction> dos = _context.InventoryTransaction.Where(c => c.WarehouseDestination == StoreCode &&
                                                                                  c.TransactionTypeId == RetailEnum.doTransaction && c.ToBeConfirmed == null && c.StatusId == 0).OrderByDescending(c => c.Id).ToList();

            List <InventoryTransactionLines> listtransline = _context.InventoryTransactionLines.Where(c => dos.Any(d => d.Id == c.InventoryTransactionId)).ToList();
            List <Item> listitem = _context.Item.Where(c => listtransline.Any(d => d.ArticleId == c.ItemIdAlias)).ToList();

            for (int i = 0; i < dos.Count; i++)
            {
                // tambah ini
                InventoryTransaction inventory = dos[i];
                //Select For Header
                DeliveryOrder doObj = new DeliveryOrder
                {
                    date            = DateTime.Now.ToString("yyyy-MM-dd"),
                    deliveryDate    = DateTime.Now.ToString("yyyy-MM-dd"),
                    id              = inventory.Id,
                    deliveryOrderId = inventory.TransactionId,
                    SjFIsik         = inventory.DeliveryOrderNumber,
                    deliveryTime    = DateTime.Now.ToString("yyyy-MM-dd"),
                    time            = DateTime.Now.ToString("hh:mm:dd"),
                    status          = inventory.StatusId,
                    statusName      = inventory.Status,
                    totalQty        = inventory.TotalQty,
                    warehouseFrom   = inventory.WarehouseOriginal,
                    warehouseTo     = inventory.WarehouseDestination,
                    //add for pbmBpk
                    isPbmPbk = (inventory.InforBypass.HasValue) ? inventory.InforBypass.Value : false
                };

                List <DeliveryOrderLine>         deliveryOrderLines = new List <DeliveryOrderLine>();
                List <InventoryTransactionLines> dosLines           = listtransline.Where(c => c.InventoryTransactionId == inventory.Id).ToList();
                var doLines = from invenlines in dosLines
                              join items in listitem
                              on invenlines.ArticleId equals items.ItemIdAlias
                              select new DeliveryOrderLine
                {
                    id      = invenlines.Id,
                    article = new Article
                    {
                        articleId      = items.ItemId,
                        articleIdAlias = items.ItemIdAlias,
                        articleName    = invenlines.ArticleName
                    },
                    articleIdFk       = items.Id,
                    deliveryOrderIdFk = inventory.Id,
                    deliveryOrderId   = inventory.TransactionId,
                    qtyDeliver        = invenlines.Qty,
                    qtyReceive        = invenlines.RecieveQty,
                    amount            = invenlines.ValueSalesPrice,
                    packingNumber     = invenlines.PackingNumber
                };
                deliveryOrderLines       = doLines.ToList();
                doObj.totalAmount        = deliveryOrderLines.Sum(d => d.amount);
                doObj.deliveryOrderLines = deliveryOrderLines;
                doObj.totalQty           = inventory.TotalQty;
                deliveryOrders.Add(doObj);
            }
            return(deliveryOrders);
        }
 /// <summary>
 /// Create Inventory Transaction
 /// </summary>
 /// <param name="inventoryTransaction"></param>
 /// <returns></returns>
 public async Task CreateInventoryTransaction(InventoryTransaction inventoryTransaction)
 {
     await dbConnection.InventoryTransactions.AddAsync(inventoryTransaction);
 }