GenerateReceive() 공개 메소드

Generates the receive.
public GenerateReceive ( ) : BLL.Receive
리턴 BLL.Receive
예제 #1
0
        /// <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);
        }