public ActionResult _Create(int Id) //Id ==>Sale Order Header Id
        {
            StockHeader        H = new StockHeaderService(_unitOfWork).Find(Id);
            StockLineViewModel s = new StockLineViewModel();

            //Getting Settings
            var settings = new StockHeaderSettingsService(_unitOfWork).GetStockHeaderSettingsForDocument(H.DocTypeId, H.DivisionId, H.SiteId);

            s.StockHeaderSettings  = Mapper.Map <StockHeaderSettings, StockHeaderSettingsViewModel>(settings);
            s.DocumentTypeSettings = new DocumentTypeSettingsService(_unitOfWork).GetDocumentTypeSettingsForDocument(H.DocTypeId);
            s.PersonId             = H.PersonId;
            s.StockHeaderId        = H.StockHeaderId;
            s.GodownId             = H.GodownId;
            ViewBag.Status         = H.Status;
            PrepareViewBag(s);
            if (!string.IsNullOrEmpty((string)TempData["CSEXCL"]))
            {
                ViewBag.CSEXCL     = TempData["CSEXCL"];
                TempData["CSEXCL"] = null;
            }

            ViewBag.LineMode = "Create";

            return(PartialView("_Create", s));
        }
        private void PrepareViewBag(StockLineViewModel vm)
        {
            ViewBag.DeliveryUnitList = new UnitService(_unitOfWork).GetUnitList().ToList();
            StockHeaderViewModel H = new StockHeaderService(_unitOfWork).GetStockHeader(vm.StockHeaderId);

            ViewBag.DocNo = H.DocTypeName + "-" + H.DocNo;
        }
        private ActionResult _Delete(int id)
        {
            StockLineViewModel temp = _StockLineService.GetStockLineForIssue(id);

            if (temp == null)
            {
                return(HttpNotFound());
            }

            #region DocTypeTimeLineValidation
            try
            {
                TimePlanValidation = DocumentValidation.ValidateDocumentLine(new DocumentUniqueId {
                    LockReason = temp.LockReason
                }, User.Identity.Name, out ExceptionMsg, out Continue);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXCL"] += message;
                TimePlanValidation  = false;
            }

            if (!TimePlanValidation)
            {
                TempData["CSEXCL"] += ExceptionMsg;
            }
            #endregion

            if ((TimePlanValidation || Continue))
            {
                ViewBag.LineMode = "Delete";
            }

            StockHeader H = new StockHeaderService(_unitOfWork).Find(temp.StockHeaderId);

            //Getting Settings
            var settings = new StockHeaderSettingsService(_unitOfWork).GetStockHeaderSettingsForDocument(H.DocTypeId, H.DivisionId, H.SiteId);


            temp.StockHeaderSettings  = Mapper.Map <StockHeaderSettings, StockHeaderSettingsViewModel>(settings);
            temp.DocumentTypeSettings = new DocumentTypeSettingsService(_unitOfWork).GetDocumentTypeSettingsForDocument(H.DocTypeId);

            temp.GodownId = H.GodownId;

            PrepareViewBag(temp);
            return(PartialView("_Create", temp));
        }
        public ActionResult _Detail(int id)
        {
            StockLineViewModel temp = _StockLineService.GetJobConsumptionLine(id);

            if (temp == null)
            {
                return(HttpNotFound());
            }

            StockHeader H = new StockHeaderService(_unitOfWork).Find(temp.StockHeaderId);

            //Getting Settings
            var settings = new StockHeaderSettingsService(_unitOfWork).GetStockHeaderSettingsForDocument(H.DocTypeId, H.DivisionId, H.SiteId);

            temp.StockHeaderSettings = Mapper.Map <StockHeaderSettings, StockHeaderSettingsViewModel>(settings);

            temp.GodownId = H.GodownId;
            PrepareViewBag(temp);
            return(PartialView("_Create", temp));
        }
        public ActionResult DeletePost(StockLineViewModel vm)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = StockIssueDocEvents.beforeLineDeleteEvent(this, new StockEventArgs(vm.StockHeaderId, vm.StockLineId), ref db);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Validation failed before delete.";
            }

            if (BeforeSave && !EventException)
            {
                int?ProdUid = 0;
                List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                //StockLine StockLine = _StockLineService.Find(vm.StockLineId);
                StockLine StockLine = (from p in db.StockLine
                                       where p.StockLineId == vm.StockLineId
                                       select p).FirstOrDefault();
                StockHeader header = new StockHeaderService(_unitOfWork).Find(StockLine.StockHeaderId);

                LogList.Add(new LogTypeViewModel
                {
                    ExObj = Mapper.Map <StockLine>(StockLine),
                });

                ProdUid = StockLine.ProductUidId;

                if (StockLine.RequisitionLineId.HasValue)
                {
                    new RequisitionLineStatusService(_unitOfWork).UpdateRequisitionQtyOnIssue(StockLine.RequisitionLineId.Value, StockLine.StockLineId, header.DocDate, 0, ref db, true);
                }

                StockLine.ObjectState = Model.ObjectState.Deleted;
                db.StockLine.Remove(StockLine);

                if (header.Status != (int)StatusConstants.Drafted && header.Status != (int)StatusConstants.Import)
                {
                    header.Status       = (int)StatusConstants.Modified;
                    header.ModifiedDate = DateTime.Now;
                    header.ModifiedBy   = User.Identity.Name;
                    header.ObjectState  = Model.ObjectState.Modified;
                    db.StockHeader.Add(header);
                }


                //if (ProdUid != null && ProdUid > 0)
                //{
                //    ProductUidDetail ProductUidDetail = new ProductUidService(_unitOfWork).FGetProductUidLastValues((int)ProdUid, "Stock Head-" + vm.StockHeaderId.ToString());

                //    ProductUid ProductUid = new ProductUidService(_unitOfWork).Find((int)ProdUid);

                //    ProductUid.LastTransactionDocDate = ProductUidDetail.LastTransactionDocDate;
                //    ProductUid.LastTransactionDocId = ProductUidDetail.LastTransactionDocId;
                //    ProductUid.LastTransactionDocNo = ProductUidDetail.LastTransactionDocNo;
                //    ProductUid.LastTransactionDocTypeId = ProductUidDetail.LastTransactionDocTypeId;
                //    ProductUid.LastTransactionPersonId = ProductUidDetail.LastTransactionPersonId;
                //    ProductUid.CurrenctGodownId = ProductUidDetail.CurrenctGodownId;
                //    ProductUid.CurrenctProcessId = ProductUidDetail.CurrenctProcessId;
                //    ProductUid.ObjectState = Model.ObjectState.Modified;
                //    db.ProductUid.Add(ProductUid);
                //}


                XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                try
                {
                    StockIssueDocEvents.onLineDeleteEvent(this, new StockEventArgs(StockLine.StockHeaderId, StockLine.StockLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                    EventException     = true;
                }

                try
                {
                    if (EventException)
                    {
                        throw new Exception();
                    }
                    db.SaveChanges();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    ViewBag.LineMode    = "Delete";
                    return(PartialView("_Create", vm));
                }

                try
                {
                    StockIssueDocEvents.afterLineDeleteEvent(this, new StockEventArgs(StockLine.StockHeaderId, StockLine.StockLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId       = header.DocTypeId,
                    DocId           = header.StockHeaderId,
                    DocLineId       = StockLine.StockLineId,
                    ActivityType    = (int)ActivityTypeContants.Deleted,
                    DocNo           = header.DocNo,
                    xEModifications = Modifications,
                    DocDate         = header.DocDate,
                    DocStatus       = header.Status,
                }));
            }

            return(Json(new { success = true }));
        }
        public ActionResult _CreatePost(StockLineViewModel svm)
        {
            StockHeader temp = new StockHeaderService(_unitOfWork).Find(svm.StockHeaderId);
            StockLine   s    = Mapper.Map <StockLineViewModel, StockLine>(svm);

            if (svm.StockHeaderSettings != null)
            {
                if (svm.StockHeaderSettings.isMandatoryProcessLine == true && (svm.FromProcessId <= 0 || svm.FromProcessId == null))
                {
                    ModelState.AddModelError("FromProcessId", "The Process field is required");
                }
                if (svm.StockHeaderSettings.isMandatoryRate == true && svm.Rate <= 0)
                {
                    ModelState.AddModelError("Rate", "The Rate field is required");
                }
                if (svm.StockHeaderSettings.isMandatoryLineCostCenter == true && !svm.CostCenterId.HasValue)
                {
                    ModelState.AddModelError("CostCenterId", "The Cost Center field is required");
                }
            }

            bool BeforeSave = true;

            try
            {
                if (svm.StockLineId <= 0)
                {
                    BeforeSave = StockIssueDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.StockHeaderId, EventModeConstants.Add), ref db);
                }
                else
                {
                    BeforeSave = StockIssueDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.StockHeaderId, EventModeConstants.Edit), ref db);
                }
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXCL"] += message;
                EventException      = true;
            }

            if (!BeforeSave)
            {
                ModelState.AddModelError("", "Validation failed before save.");
            }

            if (svm.ProductId <= 0)
            {
                ModelState.AddModelError("ProductId", "The Product field is required");
            }

            if (svm.StockLineId <= 0)
            {
                ViewBag.LineMode = "Create";
            }
            else
            {
                ViewBag.LineMode = "Edit";
            }

            if (ModelState.IsValid && BeforeSave && !EventException)
            {
                if (svm.StockLineId <= 0)
                {
                    s.CreatedDate  = DateTime.Now;
                    s.ModifiedDate = DateTime.Now;
                    s.CreatedBy    = User.Identity.Name;
                    s.DocNature    = StockNatureConstants.Issue;
                    s.ModifiedBy   = User.Identity.Name;
                    s.ProductUidId = svm.ProductUidId;
                    s.Sr           = _StockLineService.GetMaxSr(s.StockHeaderId);
                    s.ObjectState  = Model.ObjectState.Added;
                    db.StockLine.Add(s);

                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status       = (int)StatusConstants.Modified;
                        temp.ModifiedDate = DateTime.Now;
                        temp.ModifiedBy   = User.Identity.Name;

                        db.StockHeader.Add(temp);
                    }

                    try
                    {
                        StockIssueDocEvents.onLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, s.StockLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        EventException      = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }
                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    try
                    {
                        StockIssueDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, s.StockLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = temp.DocTypeId,
                        DocId        = temp.StockHeaderId,
                        DocLineId    = s.StockLineId,
                        ActivityType = (int)ActivityTypeContants.Added,
                        DocNo        = temp.DocNo,
                        DocDate      = temp.DocDate,
                        DocStatus    = temp.Status,
                    }));

                    return(RedirectToAction("_Create", new { id = svm.StockHeaderId }));
                }


                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();
                    int       status   = temp.Status;
                    StockLine templine = _StockLineService.Find(s.StockLineId);

                    StockLine ExRec = new StockLine();
                    ExRec = Mapper.Map <StockLine>(templine);

                    templine.ProductId         = s.ProductId;
                    templine.ProductUidId      = s.ProductUidId;
                    templine.RequisitionLineId = s.RequisitionLineId;
                    templine.Specification     = s.Specification;
                    templine.Dimension1Id      = s.Dimension1Id;
                    templine.Dimension2Id      = s.Dimension2Id;
                    templine.Dimension3Id      = s.Dimension3Id;
                    templine.Dimension4Id      = s.Dimension4Id;
                    templine.CostCenterId      = s.CostCenterId;
                    templine.DocNature         = StockNatureConstants.Issue;
                    templine.Rate               = s.Rate;
                    templine.Amount             = s.Amount;
                    templine.LotNo              = s.LotNo;
                    templine.FromProcessId      = s.FromProcessId;
                    templine.Remark             = s.Remark;
                    templine.Qty                = s.Qty;
                    templine.Remark             = s.Remark;
                    templine.ReferenceDocId     = s.ReferenceDocId;
                    templine.ReferenceDocTypeId = s.ReferenceDocTypeId;

                    templine.ModifiedDate = DateTime.Now;
                    templine.ModifiedBy   = User.Identity.Name;
                    templine.ObjectState  = Model.ObjectState.Modified;
                    db.StockLine.Add(templine);

                    //if (templine.RequisitionLineId.HasValue)
                    //    new RequisitionLineStatusService(_unitOfWork).UpdateRequisitionQtyOnIssue(templine.RequisitionLineId.Value, templine.StockLineId, temp.DocDate, templine.Qty, ref db, true);


                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status       = (int)StatusConstants.Modified;
                        temp.ModifiedBy   = User.Identity.Name;
                        temp.ModifiedDate = DateTime.Now;
                        temp.ObjectState  = Model.ObjectState.Modified;
                    }
                    db.StockHeader.Add(temp);


                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = templine,
                    });


                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        StockIssueDocEvents.onLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, templine.StockLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        EventException      = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }
                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    try
                    {
                        StockIssueDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, templine.StockLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    //Saving the Activity Log

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = temp.DocTypeId,
                        DocId           = templine.StockHeaderId,
                        DocLineId       = templine.StockLineId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        DocNo           = temp.DocNo,
                        xEModifications = Modifications,
                        DocDate         = temp.DocDate,
                        DocStatus       = temp.Status,
                    }));

                    //End of Saving the Activity Log

                    return(Json(new { success = true }));
                }
            }
            PrepareViewBag(svm);
            return(PartialView("_Create", svm));
        }
        public ActionResult DeletePost(StockLineViewModel vm)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = RateConversionDocEvents.beforeLineDeleteEvent(this, new StockEventArgs(vm.StockHeaderId, vm.StockLineId), ref db);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Validation failed before delete.";
            }

            if (BeforeSave && !EventException)
            {
                int?StockProcessId = 0;
                int?CostCenterId   = null;
                List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();


                StockLine StockLine = (from p in db.StockLine
                                       where p.StockLineId == vm.StockLineId
                                       select p).FirstOrDefault();

                CostCenterId = StockLine.CostCenterId;

                LogList.Add(new LogTypeViewModel
                {
                    ExObj = Mapper.Map <StockLine>(StockLine),
                });



                StockProcessId = StockLine.StockProcessId;

                //_StockLineService.Delete(StockLine);
                StockLine.ObjectState = Model.ObjectState.Deleted;
                db.StockLine.Remove(StockLine);

                if (StockProcessId != null)
                {
                    new StockProcessService(_unitOfWork).DeleteStockProcessDB((int)StockProcessId, ref db, true);
                }

                StockHeader header = new StockHeaderService(_unitOfWork).Find(StockLine.StockHeaderId);
                if (header.Status != (int)StatusConstants.Drafted)
                {
                    header.Status = (int)StatusConstants.Modified;

                    header.ModifiedDate = DateTime.Now;
                    header.ModifiedBy   = User.Identity.Name;

                    header.ObjectState = Model.ObjectState.Modified;
                    db.StockHeader.Add(header);
                    //new StockHeaderService(_unitOfWork).Update(header);
                }


                if (CostCenterId.HasValue && CostCenterId.Value > 0)
                {
                    var CostCenterStatus = db.CostCenterStatus.Find(CostCenterId);
                    if (CostCenterStatus != null && StockLine.Amount > 0)
                    {
                        if (StockLine.Amount > 0)
                        {
                            CostCenterStatus.AmountDr = CostCenterStatus.AmountDr - StockLine.Amount;
                        }
                        else
                        {
                            CostCenterStatus.AmountCr = CostCenterStatus.AmountCr - StockLine.Amount;
                        }
                        CostCenterStatus.ObjectState = Model.ObjectState.Modified;
                        db.CostCenterStatus.Add(CostCenterStatus);
                    }
                }

                XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                try
                {
                    RateConversionDocEvents.onLineDeleteEvent(this, new StockEventArgs(StockLine.StockHeaderId, StockLine.StockLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                    EventException     = true;
                }

                try
                {
                    if (EventException)
                    {
                        throw new Exception();
                    }
                    db.SaveChanges();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    ViewBag.LineMode    = "Delete";
                    return(PartialView("_Create", vm));
                }

                try
                {
                    RateConversionDocEvents.afterLineDeleteEvent(this, new StockEventArgs(StockLine.StockHeaderId, StockLine.StockLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId       = header.DocTypeId,
                    DocId           = header.StockHeaderId,
                    DocLineId       = StockLine.StockLineId,
                    ActivityType    = (int)ActivityTypeContants.Deleted,
                    DocNo           = header.DocNo,
                    xEModifications = Modifications,
                    DocDate         = header.DocDate,
                    DocStatus       = header.Status,
                }));
            }
            return(Json(new { success = true }));
        }
        public ActionResult _CreatePost(StockLineViewModel svm)
        {
            StockHeader temp = new StockHeaderService(_unitOfWork).Find(svm.StockHeaderId);

            StockLine s = Mapper.Map <StockLineViewModel, StockLine>(svm);

            if (svm.StockHeaderSettings != null)
            {
                if (svm.StockHeaderSettings.isMandatoryProcessLine == true && (svm.FromProcessId <= 0 || svm.FromProcessId == null))
                {
                    ModelState.AddModelError("FromProcessId", "The Process field is required");
                }
                if (svm.Rate <= 0)
                {
                    ModelState.AddModelError("Rate", "The Rate field is required");
                }
                if (svm.StockHeaderSettings.isMandatoryLineCostCenter == true && !(svm.CostCenterId.HasValue))
                {
                    ModelState.AddModelError("CostCenterId", "The CostCenter field is required");
                }
            }

            bool BeforeSave = true;

            try
            {
                if (svm.StockLineId <= 0)
                {
                    BeforeSave = RateConversionDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.StockHeaderId, EventModeConstants.Add), ref db);
                }
                else
                {
                    BeforeSave = RateConversionDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.StockHeaderId, EventModeConstants.Edit), ref db);
                }
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXCL"] += message;
                EventException      = true;
            }

            if (!BeforeSave)
            {
                ModelState.AddModelError("", "Validation failed before save.");
            }

            if (svm.StockLineId <= 0)
            {
                ViewBag.LineMode = "Create";
            }
            else
            {
                ViewBag.LineMode = "Edit";
            }

            if (ModelState.IsValid && BeforeSave && !EventException)
            {
                if (svm.StockLineId <= 0)
                {
                    StockProcessViewModel StockProcessViewModel = new StockProcessViewModel();

                    StockHeader StockHeader = new StockHeaderService(_unitOfWork).Find(temp.StockHeaderId);

                    //Posting in StockProcess
                    if (StockHeader.StockHeaderId != null)
                    {
                        StockProcessViewModel.StockHeaderId = StockHeader.StockHeaderId;
                    }
                    else
                    {
                        StockProcessViewModel.StockHeaderId = 0;
                    }

                    StockProcessViewModel.StockHeaderId       = temp.StockHeaderId;
                    StockProcessViewModel.DocHeaderId         = temp.StockHeaderId;
                    StockProcessViewModel.DocLineId           = s.StockLineId;
                    StockProcessViewModel.DocTypeId           = temp.DocTypeId;
                    StockProcessViewModel.StockHeaderDocDate  = temp.DocDate;
                    StockProcessViewModel.StockProcessDocDate = temp.DocDate;
                    StockProcessViewModel.DocNo              = temp.DocNo;
                    StockProcessViewModel.DivisionId         = temp.DivisionId;
                    StockProcessViewModel.SiteId             = temp.SiteId;
                    StockProcessViewModel.CurrencyId         = null;
                    StockProcessViewModel.HeaderProcessId    = null;
                    StockProcessViewModel.PersonId           = temp.PersonId;
                    StockProcessViewModel.ProductId          = s.ProductId;
                    StockProcessViewModel.HeaderFromGodownId = temp.FromGodownId;
                    StockProcessViewModel.HeaderGodownId     = temp.GodownId;
                    StockProcessViewModel.GodownId           = temp.GodownId ?? 0;
                    StockProcessViewModel.ProcessId          = s.FromProcessId;
                    StockProcessViewModel.LotNo              = s.LotNo;
                    StockProcessViewModel.CostCenterId       = temp.CostCenterId;


                    if (s.Qty < 0)
                    {
                        StockProcessViewModel.Qty_Rec = Math.Abs(s.Qty);
                        StockProcessViewModel.Qty_Iss = 0;
                    }
                    else if (s.Qty > 0)
                    {
                        StockProcessViewModel.Qty_Iss = Math.Abs(s.Qty);
                        StockProcessViewModel.Qty_Rec = 0;
                    }

                    StockProcessViewModel.Rate          = s.Rate;
                    StockProcessViewModel.ExpiryDate    = null;
                    StockProcessViewModel.Specification = s.Specification;
                    StockProcessViewModel.Dimension1Id  = s.Dimension1Id;
                    StockProcessViewModel.Dimension2Id  = s.Dimension2Id;
                    StockProcessViewModel.Dimension3Id  = s.Dimension3Id;
                    StockProcessViewModel.Dimension4Id  = s.Dimension4Id;
                    StockProcessViewModel.Remark        = s.Remark;
                    StockProcessViewModel.Status        = temp.Status;
                    StockProcessViewModel.CreatedBy     = temp.CreatedBy;
                    StockProcessViewModel.CreatedDate   = DateTime.Now;
                    StockProcessViewModel.ModifiedBy    = temp.ModifiedBy;
                    StockProcessViewModel.ModifiedDate  = DateTime.Now;

                    string StockProcessPostingError = "";
                    StockProcessPostingError = new StockProcessService(_unitOfWork).StockProcessPostDB(ref StockProcessViewModel, ref db);

                    if (StockProcessPostingError != "")
                    {
                        ModelState.AddModelError("", StockProcessPostingError);
                        return(PartialView("_Create", svm));
                    }

                    s.StockProcessId = StockProcessViewModel.StockProcessId;

                    s.CreatedDate  = DateTime.Now;
                    s.ModifiedDate = DateTime.Now;
                    s.CreatedBy    = User.Identity.Name;
                    s.ModifiedBy   = User.Identity.Name;
                    s.DocNature    = StockNatureConstants.Receive;
                    s.ObjectState  = Model.ObjectState.Added;
                    //_StockLineService.Create(s);
                    db.StockLine.Add(s);

                    //StockHeader header = new StockHeaderService(_unitOfWork).Find(s.StockHeaderId);
                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status       = (int)StatusConstants.Modified;
                        temp.ModifiedDate = DateTime.Now;
                        temp.ModifiedBy   = User.Identity.Name;

                        temp.ObjectState = Model.ObjectState.Modified;
                        db.StockHeader.Add(temp);
                        //new StockHeaderService(_unitOfWork).Update(temp);
                    }

                    try
                    {
                        RateConversionDocEvents.onLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, s.StockLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        EventException      = true;
                    }


                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }
                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    try
                    {
                        RateConversionDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, s.StockLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = temp.DocTypeId,
                        DocId        = temp.StockHeaderId,
                        DocLineId    = s.StockLineId,
                        ActivityType = (int)ActivityTypeContants.Added,
                        DocNo        = temp.DocNo,
                        DocDate      = temp.DocDate,
                        DocStatus    = temp.Status,
                    }));

                    return(RedirectToAction("_Create", new { id = svm.StockHeaderId }));
                }


                else
                {
                    StockLine templine = _StockLineService.Find(s.StockLineId);

                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                    StockLine ExRec = new StockLine();
                    ExRec = Mapper.Map <StockLine>(templine);

                    if (templine.StockProcessId != null)
                    {
                        StockProcessViewModel StockProcessViewModel = new StockProcessViewModel();
                        StockHeader           StockHeader           = new StockHeaderService(_unitOfWork).Find(temp.StockHeaderId);


                        //Posting in StockProcess
                        if (StockHeader.StockHeaderId != null)
                        {
                            StockProcessViewModel.StockHeaderId = StockHeader.StockHeaderId;
                        }
                        else
                        {
                            StockProcessViewModel.StockHeaderId = 0;
                        }

                        StockProcessViewModel.StockProcessId      = templine.StockProcessId ?? 0;
                        StockProcessViewModel.DocHeaderId         = templine.StockHeaderId;
                        StockProcessViewModel.DocLineId           = templine.StockLineId;
                        StockProcessViewModel.DocTypeId           = temp.DocTypeId;
                        StockProcessViewModel.StockHeaderDocDate  = temp.DocDate;
                        StockProcessViewModel.StockProcessDocDate = temp.DocDate;
                        StockProcessViewModel.DocNo              = temp.DocNo;
                        StockProcessViewModel.DivisionId         = temp.DivisionId;
                        StockProcessViewModel.SiteId             = temp.SiteId;
                        StockProcessViewModel.CurrencyId         = null;
                        StockProcessViewModel.HeaderProcessId    = temp.ProcessId;
                        StockProcessViewModel.PersonId           = temp.PersonId;
                        StockProcessViewModel.ProductId          = s.ProductId;
                        StockProcessViewModel.HeaderFromGodownId = null;
                        StockProcessViewModel.HeaderGodownId     = temp.GodownId;
                        StockProcessViewModel.GodownId           = temp.GodownId;
                        StockProcessViewModel.ProcessId          = temp.ProcessId;
                        StockProcessViewModel.LotNo              = templine.LotNo;
                        StockProcessViewModel.CostCenterId       = templine.CostCenterId;

                        if (s.Qty < 0)
                        {
                            StockProcessViewModel.Qty_Rec = Math.Abs(s.Qty);
                            StockProcessViewModel.Qty_Iss = 0;
                        }
                        else if (s.Qty > 0)
                        {
                            StockProcessViewModel.Qty_Iss = Math.Abs(s.Qty);
                            StockProcessViewModel.Qty_Rec = 0;
                        }

                        StockProcessViewModel.Rate          = templine.Rate;
                        StockProcessViewModel.ExpiryDate    = null;
                        StockProcessViewModel.Specification = templine.Specification;
                        StockProcessViewModel.Dimension1Id  = templine.Dimension1Id;
                        StockProcessViewModel.Dimension2Id  = templine.Dimension2Id;
                        StockProcessViewModel.Dimension3Id  = templine.Dimension3Id;
                        StockProcessViewModel.Dimension4Id  = templine.Dimension4Id;
                        StockProcessViewModel.Remark        = s.Remark;
                        StockProcessViewModel.Status        = temp.Status;
                        StockProcessViewModel.CreatedBy     = templine.CreatedBy;
                        StockProcessViewModel.CreatedDate   = templine.CreatedDate;
                        StockProcessViewModel.ModifiedBy    = User.Identity.Name;
                        StockProcessViewModel.ModifiedDate  = DateTime.Now;

                        string StockProcessPostingError = "";
                        StockProcessPostingError = new StockProcessService(_unitOfWork).StockProcessPostDB(ref StockProcessViewModel, ref db);

                        if (StockProcessPostingError != "")
                        {
                            ModelState.AddModelError("", StockProcessPostingError);
                            return(PartialView("_Create", svm));
                        }
                    }



                    templine.Qty          = s.Qty;
                    templine.Remark       = s.Remark;
                    templine.Amount       = s.Qty * s.Rate;
                    templine.ModifiedDate = DateTime.Now;
                    templine.ModifiedBy   = User.Identity.Name;
                    //_StockLineService.Update(templine);
                    templine.ObjectState = Model.ObjectState.Modified;
                    db.StockLine.Add(templine);

                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status = (int)StatusConstants.Modified;

                        temp.ModifiedBy   = User.Identity.Name;
                        temp.ModifiedDate = DateTime.Now;

                        temp.ObjectState = Model.ObjectState.Modified;
                        db.StockHeader.Add(temp);
                        //new StockHeaderService(_unitOfWork).Update(temp);
                    }

                    if (templine.CostCenterId.HasValue && templine.CostCenterId > 0)
                    {
                        var CostCenterStatus = db.CostCenterStatus.Find(templine.CostCenterId);

                        if (CostCenterStatus != null)
                        {
                            //For Reducing Old Amount
                            if (ExRec.Amount > 0)
                            {
                                CostCenterStatus.AmountDr = CostCenterStatus.AmountDr - ExRec.Amount;
                            }
                            else
                            {
                                CostCenterStatus.AmountCr = CostCenterStatus.AmountCr - ExRec.Amount;
                            }
                            //For Adding New Amount
                            if (templine.Amount > 0)
                            {
                                CostCenterStatus.AmountDr = CostCenterStatus.AmountDr + templine.Amount;
                            }
                            else
                            {
                                CostCenterStatus.AmountCr = CostCenterStatus.AmountCr + templine.Amount;
                            }
                            CostCenterStatus.ObjectState = Model.ObjectState.Modified;
                            db.CostCenterStatus.Add(CostCenterStatus);
                        }
                    }

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = templine,
                    });


                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        RateConversionDocEvents.onLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, templine.StockLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        EventException     = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }
                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    try
                    {
                        RateConversionDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.StockHeaderId, templine.StockLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    //Saving the Activity Log

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = temp.DocTypeId,
                        DocId           = templine.StockHeaderId,
                        DocLineId       = templine.StockLineId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        DocNo           = temp.DocNo,
                        xEModifications = Modifications,
                        DocDate         = temp.DocDate,
                        DocStatus       = temp.Status,
                    }));

                    //End of Saving the Activity Log

                    return(Json(new { success = true }));
                }
            }
            PrepareViewBag(svm);
            return(PartialView("_Create", svm));
        }