/// <summary>
        /// Generates the receive model.
        /// </summary>
        /// <param name="receive">The receive.</param>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public static Models.ReceiveViewModel GenerateReceiveModel(BLL.Receive receive, UserProfile user)
        {
            ReceiveViewModel model = new ReceiveViewModel();
            model._UserProfile = user;

            model.InitalizeViewModel();
            model.IsEditMode = true;
            model.ReceiveID = receive.ReceiveID;
            model.DriverName = receive.DriverName;
            model.GRN = receive.GRN;
            model.PlateNo_Prime = receive.PlateNo_Prime;
            model.PlateNo_Trailer = receive.PlateNo_Trailer;

            model.TransporterID = receive.TransporterID;
            model.HubID = receive.HubID;

            ReceiveDetail receiveDetail = receive.ReceiveDetails.FirstOrDefault();//p=>p.QuantityInMT>0);
            Transaction receiveDetailtransaction = null;
            if (receiveDetail != null)
                foreach (Transaction transaction in receiveDetail.TransactionGroup.Transactions)
                {
                    var negTransaction = receiveDetail.TransactionGroup.Transactions.FirstOrDefault(p => p.QuantityInMT < 0);
                    if(negTransaction != null)
                        model.SourceHubID = negTransaction.Account.EntityID;
                    receiveDetailtransaction = transaction;
                    break;
                }
            if (receiveDetailtransaction != null)
             {
                 model.SINumber = receiveDetailtransaction.ShippingInstruction != null ? receiveDetailtransaction.ShippingInstruction.Value : "";

                 model.ProjectNumber = receiveDetailtransaction.ProjectCode != null ? receiveDetailtransaction.ProjectCode.Value : "";

                 model.ProgramID = receiveDetailtransaction.Program != null ? receiveDetailtransaction.Program.ProgramID : default(int);

                 model.StoreID = receiveDetailtransaction.Store != null ? receiveDetailtransaction.Store.StoreID : default(int);

                 model.StackNumber = receiveDetailtransaction.Stack.HasValue ? receiveDetailtransaction.Stack.Value : default(int);

             }else
            {
                model.SINumber = "";
                model.ProjectNumber = "";
                model.ProgramID = default(int);
                model.StoreID = default(int);
                model.StackNumber = default(int);
            }

            model.ReceiptDate = receive.ReceiptDate;
            model.WayBillNo = receive.WayBillNo;
            model.CommodityTypeID = receive.CommodityTypeID;
            model.ResponsibleDonorID = receive.ResponsibleDonorID;
            model.SourceDonorID = receive.SourceDonorID;
            model.CommoditySourceID = receive.CommoditySourceID;
            model.TicketNumber = receive.WeightBridgeTicketNumber;
            model.WeightBeforeUnloading = receive.WeightBeforeUnloading;
            model.WeightAfterUnloading = receive.WeightAfterUnloading;
            model.VesselName = receive.VesselName;
            model.PortName = receive.PortName;
            model.ReceiptAllocationID = receive.ReceiptAllocationID;
            model.PurchaseOrder = receive.PurchaseOrder;
            model.SupplierName = receive.SupplierName;

            model.Remark = receive.Remark;
            model.ReceivedByStoreMan = receive.ReceivedByStoreMan;

            model.ReceiveDetails = DRMFSS.Web.Models.ReceiveDetailViewModel.GenerateReceiveDetailModels(receive.ReceiveDetails);
            return model;
        }
Beispiel #2
0
        /// <summary>
        /// Generates the receive model.
        /// </summary>
        /// <param name="receive">The receive.</param>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public static Models.ReceiveViewModel GenerateReceiveModel(BLL.Receive receive, List <Commodity> commodities, List <CommodityGrade> commodityGrades, List <Transporter> transporters, List <CommodityType> commodityTypes,
                                                                   List <CommoditySource> commoditySources, List <Program> programs, List <Donor> donors, List <Hub> hubs, UserProfile user)
        {
            ReceiveViewModel model = new ReceiveViewModel();

            model._UserProfile = user;

            model.InitalizeViewModel(commodities, commodityGrades, transporters, commodityTypes,
                                     commoditySources, programs, donors, hubs, user);
            model.IsEditMode      = true;
            model.ReceiveID       = receive.ReceiveID;
            model.DriverName      = receive.DriverName;
            model.GRN             = receive.GRN;
            model.PlateNo_Prime   = receive.PlateNo_Prime;
            model.PlateNo_Trailer = receive.PlateNo_Trailer;

            model.TransporterID = receive.TransporterID;
            model.HubID         = receive.HubID;

            ReceiveDetail receiveDetail            = receive.ReceiveDetails.FirstOrDefault();//p=>p.QuantityInMT>0);
            Transaction   receiveDetailtransaction = null;

            if (receiveDetail != null)
            {
                foreach (Transaction transaction in receiveDetail.TransactionGroup.Transactions)
                {
                    var negTransaction = receiveDetail.TransactionGroup.Transactions.FirstOrDefault(p => p.QuantityInMT < 0);
                    if (negTransaction != null)
                    {
                        model.SourceHubID = negTransaction.Account.EntityID;
                    }
                    receiveDetailtransaction = transaction;
                    break;
                }
            }
            if (receiveDetailtransaction != null)
            {
                model.SINumber = receiveDetailtransaction.ShippingInstruction != null ? receiveDetailtransaction.ShippingInstruction.Value : "";

                model.ProjectNumber = receiveDetailtransaction.ProjectCode != null ? receiveDetailtransaction.ProjectCode.Value : "";

                model.ProgramID = receiveDetailtransaction.Program != null ? receiveDetailtransaction.Program.ProgramID : default(int);

                model.StoreID = receiveDetailtransaction.Store != null ? receiveDetailtransaction.Store.StoreID : default(int);

                model.StackNumber = receiveDetailtransaction.Stack.HasValue ? receiveDetailtransaction.Stack.Value : default(int);
            }
            else
            {
                model.SINumber      = "";
                model.ProjectNumber = "";
                model.ProgramID     = default(int);
                model.StoreID       = default(int);
                model.StackNumber   = default(int);
            }

            model.ReceiptDate           = receive.ReceiptDate;
            model.WayBillNo             = receive.WayBillNo;
            model.CommodityTypeID       = receive.CommodityTypeID;
            model.ResponsibleDonorID    = receive.ResponsibleDonorID;
            model.SourceDonorID         = receive.SourceDonorID;
            model.CommoditySourceID     = receive.CommoditySourceID;
            model.TicketNumber          = receive.WeightBridgeTicketNumber;
            model.WeightBeforeUnloading = receive.WeightBeforeUnloading;
            model.WeightAfterUnloading  = receive.WeightAfterUnloading;
            model.VesselName            = receive.VesselName;
            model.PortName            = receive.PortName;
            model.ReceiptAllocationID = receive.ReceiptAllocationID;
            model.PurchaseOrder       = receive.PurchaseOrder;
            model.SupplierName        = receive.SupplierName;

            model.Remark             = receive.Remark;
            model.ReceivedByStoreMan = receive.ReceivedByStoreMan;

            model.ReceiveDetails = DRMFSS.Web.Models.ReceiveDetailViewModel.GenerateReceiveDetailModels(receive.ReceiveDetails);
            return(model);
        }
        /// <summary>
        /// Saves the receipt transaction.
        /// </summary>
        /// <param name="receiveModels">The receive models.</param>
        /// <param name="user">The user.</param>
        public void SaveReceiptTransaction(ReceiveViewModel receiveModels, UserProfile user)
        {
            // Populate more details of the reciept object
            // Save it when you are done.

            Receive receive = receiveModels.GenerateReceive();
            receive.CreatedDate = DateTime.Now;
            receive.HubID = user.DefaultHub.HubID;
            receive.UserProfileID = user.UserProfileID;
            var commType = _unitOfWork.CommodityTypeRepository.FindById(receiveModels.CommodityTypeID);

            // var comms = GenerateReceiveDetail(commodities);

            foreach (ReceiveDetailViewModel c in receiveModels.ReceiveDetails)
            {
                if (commType.CommodityTypeID == 2)//if it's a non food
                {
                    c.ReceivedQuantityInMT = 0;
                    c.SentQuantityInMT = 0;
                }
                TransactionGroup tgroup = new TransactionGroup();

                var receiveDetail = new ReceiveDetail()
                {
                    CommodityID = c.CommodityID,
                    Description = c.Description,
                    SentQuantityInMT = c.SentQuantityInMT.Value,
                    SentQuantityInUnit = c.SentQuantityInUnit.Value,
                    UnitID = c.UnitID,
                    ReceiveID = receive.ReceiveID
                };
                if (c.ReceiveDetailID.HasValue)
                {
                    receiveDetail.ReceiveDetailID = c.ReceiveDetailID.Value;
                }

                // receiveDetail.TransactionGroupID = tgroup.TransactionGroupID;
                receiveDetail.TransactionGroup = tgroup;
                receive.ReceiveDetails.Add(receiveDetail);

                Transaction transaction = new Transaction();
                transaction.TransactionDate = DateTime.Now;
                transaction.ParentCommodityID = _unitOfWork.CommodityRepository.FindById(c.CommodityID).ParentID ?? c.CommodityID;
                transaction.CommodityID = c.CommodityID;
                transaction.LedgerID = Ledger.Constants.GOODS_ON_HAND_UNCOMMITED;
                transaction.HubOwnerID = user.DefaultHub.HubOwnerID;

                transaction.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receive.HubID);
                transaction.ShippingInstructionID = _shippingInstructionService.GetSINumberIdWithCreate(receiveModels.SINumber).ShippingInstructionID;

                //TODO:After Implementing ProjectCodeService Please Return Here
                //transaction.ProjectCodeID = repository.ProjectCode.GetProjectCodeIdWIthCreate(receiveModels.ProjectNumber).ProjectCodeID;
                transaction.HubID = user.DefaultHub.HubID;
                transaction.UnitID = c.UnitID;
                if (c.ReceivedQuantityInMT != null) transaction.QuantityInMT = c.ReceivedQuantityInMT.Value;
                if (c.ReceivedQuantityInUnit != null) transaction.QuantityInUnit = c.ReceivedQuantityInUnit.Value;
                if (c.CommodityGradeID != null) transaction.CommodityGradeID = c.CommodityGradeID.Value;

                transaction.ProgramID = receiveModels.ProgramID;
                transaction.StoreID = receiveModels.StoreID;
                transaction.Stack = receiveModels.StackNumber;
                transaction.TransactionGroupID = tgroup.TransactionGroupID;
                tgroup.Transactions.Add(transaction);

                // do the second half of the transaction here.

                var transaction2 = new Transaction();
                transaction2.TransactionDate = DateTime.Now;
                //TAKEs the PARENT FROM THE FIRST TRANSACTION
                transaction2.ParentCommodityID = transaction.ParentCommodityID;
                transaction2.CommodityID = c.CommodityID;
                transaction2.HubOwnerID = user.DefaultHub.HubOwnerID;
                //Decide from where the -ve side of the transaction comes from
                //it is either from the allocated stock
                // or it is from goods under care.

                // this means that this receipt is done without having gone through the gift certificate process.

                if (receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.DONATION || receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.LOCALPURCHASE)
                {
                    transaction2.LedgerID = Ledger.Constants.GOODS_UNDER_CARE;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.DONOR, receive.ResponsibleDonorID.Value);
                }
                else if (receiveModels.CommoditySourceID == BLL.CommoditySource.Constants.REPAYMENT)
                {
                    transaction2.LedgerID = Ledger.Constants.GOODS_RECIEVABLE;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receiveModels.SourceHubID.Value);
                }
                else
                {
                    transaction2.LedgerID = Ledger.Constants.LIABILITIES;
                    transaction2.AccountID = _accountService.GetAccountIdWithCreate(Account.Constants.HUB, receiveModels.SourceHubID.Value);
                }

                transaction2.ShippingInstructionID = _shippingInstructionService.GetSINumberIdWithCreate(receiveModels.SINumber).ShippingInstructionID;
                //TODO:After Implementing ProjectCodeService Please return here
                //transaction2.ProjectCodeID = repository.ProjectCode.GetProjectCodeIdWIthCreate(receiveModels.ProjectNumber).ProjectCodeID;
                transaction2.HubID = user.DefaultHub.HubID;
                transaction2.UnitID = c.UnitID;
                // this is the credit part, so make it Negative
                if (c.ReceivedQuantityInMT != null) transaction2.QuantityInMT = -c.ReceivedQuantityInMT.Value;
                if (c.ReceivedQuantityInUnit != null) transaction2.QuantityInUnit = -c.ReceivedQuantityInUnit.Value;
                if (c.CommodityGradeID != null) transaction2.CommodityGradeID = c.CommodityGradeID.Value;

                transaction2.ProgramID = receiveModels.ProgramID;
                transaction2.StoreID = receiveModels.StoreID;
                transaction2.Stack = receiveModels.StackNumber;
                transaction2.TransactionGroupID = tgroup.TransactionGroupID;
                // hack to get past same key object in context error
                //repository.Transaction = new TransactionRepository();
                tgroup.Transactions.Add(transaction2);

            }

            // Try to save this transaction
            //   db.Database.Connection.Open();
            //  DbTransaction dbTransaction = db.Database.Connection.BeginTransaction();
            try
            {
                //repository.Receive.Add(receive);
                _unitOfWork.ReceiveRepository.Add(receive);
                _unitOfWork.Save();
            }
            catch (Exception exp)
            {
                //  dbTransaction.Rollback();
                //TODO: Save the exception somewhere
                throw new Exception("The Receipt Transaction Cannot be saved. <br />Detail Message :" + exp.StackTrace);

            }
        }
        public virtual ActionResult Create(ReceiveViewModel receiveModels)
        {
            MembershipProvider membership = new MembershipProvider();
            BLL.UserProfile user = _userProfileService.GetUser(User.Identity.Name);

            var commodities = _commodityService.GetAllCommodity().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
            var commodityGrades = _commodityGradeService.GetAllCommodityGrade().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
            var transporters = _transporterService.GetAllTransporter().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
            var commoditySources = _commoditySourceService.GetAllCommoditySource().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
            var commodityTypes = _commodityTypeService.GetAllCommodityType().DefaultIfEmpty().OrderBy(o => o.Name).ToList();

            var programs = _programService.GetAllProgram().DefaultIfEmpty().OrderBy(o => o.Name).ToList();
            var donors = _donorService.GetAllDonor().DefaultIfEmpty().OrderBy(o => o.Name).ToList();

            var hubs = _hubService.GetAllWithoutId(user.DefaultHub.HubID).DefaultIfEmpty().OrderBy(o => o.Name).ToList();

            var insertCommodities = new List<Models.ReceiveDetailViewModel>();
            var updateCommodities = new List<Models.ReceiveDetailViewModel>();
            var prevCommodities = new List<Models.ReceiveDetailViewModel>();
            if (receiveModels.JSONPrev != null)
            {
                prevCommodities = GetSelectedCommodities(receiveModels.JSONPrev);

                //Even though they are updated they are not saved so move them in to the inserted at the end of a succcessful submit
                int count = 0;
                foreach (var receiveDetailAllViewModels in prevCommodities)
                {
                    if (receiveDetailAllViewModels.ReceiveDetailID == null)
                    {
                        count--;
                        receiveDetailAllViewModels.ReceiveDetailCounter = count;
                        insertCommodities.Add(receiveDetailAllViewModels);
                    }
                    else
                    {
                        receiveDetailAllViewModels.ReceiveDetailCounter = 1;
                        updateCommodities.Add(receiveDetailAllViewModels);
                    }
                }

                ViewBag.ReceiveDetails = prevCommodities;
                receiveModels.ReceiveDetails = prevCommodities;
                bool isValid = ModelState.IsValid;

                //this check need's to be revisited
                if (prevCommodities.Count() == 0)
                {
                    ModelState.AddModelError("ReceiveDetails", "Please add atleast one commodity to save this Reciept");
                }

                //TODO add check against the commodity type for each commodity
                string errorMessage = null;
                foreach (var receiveDetailViewModel in prevCommodities)
                {
                    var validationContext = new ValidationContext(receiveDetailViewModel, null, null);
                    IEnumerable<ValidationResult> validationResults = receiveDetailViewModel.Validate(validationContext);
                    foreach (var v in validationResults)
                    {
                        errorMessage = string.Format("{0}, {1}", errorMessage, v.ErrorMessage);
                    }
                    Commodity comms = _commodityService.FindById(receiveDetailViewModel.CommodityID);
                    CommodityType commType = _commodityTypeService.FindById(receiveModels.CommodityTypeID);
                    if (receiveModels.CommodityTypeID != comms.CommodityTypeID)
                        ModelState.AddModelError("ReceiveDetails", comms.Name + " is not of type " + commType.Name);
                }
                if (errorMessage != null)
                {
                    ModelState.AddModelError("ReceiveDetails", errorMessage);
                }
            }
            else
            {
                ModelState.AddModelError("ReceiveDetails", "Please add atleast one commodity to save this Reciept");
            }
            switch (receiveModels.CommoditySourceID)
            {
                case BLL.CommoditySource.Constants.DONATION:
                    ModelState.Remove("SourceHubID");
                    ModelState.Remove("SupplierName");
                    ModelState.Remove("PurchaseOrder");
                    break;
                case BLL.CommoditySource.Constants.LOCALPURCHASE:
                    //ModelState.Remove("DonorID");
                    ModelState.Remove("SourceHubID");
                    //ModelState.Remove("ResponsibleDonorID");
                    break;
                default:
                    ModelState.Remove("DonorID");
                    ModelState.Remove("ResponsibleDonorID");
                    ModelState.Remove("SupplierName");
                    ModelState.Remove("PurchaseOrder");
                    break;
            }

            if (ModelState.IsValid && user != null)
            {
                if (receiveModels.ChangeStoreManPermanently != null && receiveModels.ChangeStoreManPermanently == true)
                {
                    BLL.Store storeTobeChanged = _storeService.FindById(receiveModels.StoreID);
                    if (storeTobeChanged != null && receiveModels.ChangeStoreManPermanently == true)
                    storeTobeChanged.StoreManName = receiveModels.ReceivedByStoreMan;
                    //repository.Store.SaveChanges(storeTobeChanged);
                }

                BLL.Receive receive = receiveModels.GenerateReceive();
                //if (receive.ReceiveID == null )
                if(receiveModels.ReceiveID == null)
                {
                    //List<ReceiveDetailViewModel> commodities = GetSelectedCommodities(receiveModels.JSONInsertedCommodities);
                    receiveModels.ReceiveDetails = prevCommodities;
                    foreach (var gridCommodities in prevCommodities)
                    {
                        if (user.PreferedWeightMeasurment.Equals("qn"))
                        {
                            gridCommodities.ReceivedQuantityInMT /= 10;
                            gridCommodities.SentQuantityInMT /= 10;
                        }
                    }
                    _transactionService.SaveReceiptTransaction(receiveModels, user);
                }
                else
                {
                    //List<Models.ReceiveDetailViewModel>
                    //insertCommodities = GetSelectedCommodities(receiveModels.JSONInsertedCommodities);
                    List<Models.ReceiveDetailViewModel> deletedCommodities = GetSelectedCommodities(receiveModels.JSONDeletedCommodities);
                   // List<Models.ReceiveDetailViewModel> updateCommodities = GetSelectedCommodities(receiveModels.JSONUpdatedCommodities);
                    receive.HubID = user.DefaultHub.HubID;
                    receive.UserProfileID = user.UserProfileID;
                    receive.Update(GenerateReceiveDetail(insertCommodities),
                        GenerateReceiveDetail(updateCommodities),
                        GenerateReceiveDetail(deletedCommodities));

                }

                return RedirectToAction("Index");
            }
            receiveModels.InitializeEditLists(commodities,commodityGrades,transporters,commodityTypes,commoditySources,programs,donors,hubs,user );
            if(receiveModels.ReceiveID != null)
            {
                receiveModels.IsEditMode = true;
            }
            return View(receiveModels);
        }