public ActionResult OrderInspectionRequestWizard(int id)//DocumentTypeId
        {
            PrepareViewBag(id);
            JobOrderInspectionRequestHeaderViewModel vm = new JobOrderInspectionRequestHeaderViewModel();

            vm.DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"];
            vm.SiteId     = (int)System.Web.HttpContext.Current.Session["SiteId"];
            vm.DocTypeId  = id;

            //Getting Settings
            var settings = new JobOrderInspectionRequestSettingsService(db).GetJobOrderInspectionRequestSettingsForDocument(id, vm.DivisionId, vm.SiteId);

            if (settings == null && UserRoles.Contains("SysAdmin"))
            {
                return(RedirectToAction("CreateJobOrderInspectionRequest", "JobOrderInspectionRequestSettings", new { id = id }).Warning("Please create Purchase order cancel settings"));
            }
            else if (settings == null && !UserRoles.Contains("SysAdmin"))
            {
                return(View("~/Views/Shared/InValidSettings.cshtml"));
            }
            vm.JobOrderInspectionRequestSettings = Mapper.Map <JobOrderInspectionRequestSettingsViewModel>(settings);
            ViewBag.ProcId = settings.ProcessId;
            vm.ProcessId   = settings.ProcessId;

            int?JobWorkerId = new JobWorkerDbService(db).GetJobWorkerForUser(User.Identity.Name);

            if (JobWorkerId.HasValue && JobWorkerId.Value > 0)
            {
                vm.JobWorkerId = JobWorkerId.Value;
            }

            return(View(vm));
        }
        public ActionResult ConfirmedJobOrders(List <JobOrderInspectionRequestWizardViewModel> ConfirmedList, int DocTypeId, string UserRemark)
        {
            if (ConfirmedList.Count() > 0 && ConfirmedList.GroupBy(m => m.JobWorkerId).Count() > 1)
            {
                return(Json(new { Success = false, Data = " Multiple Headers are selected. " }, JsonRequestBehavior.AllowGet));
            }
            else if (ConfirmedList.Count() == 0)
            {
                return(Json(new { Success = false, Data = " No Records are selected. " }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                int DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"];
                int SiteId     = (int)System.Web.HttpContext.Current.Session["SiteId"];

                bool BeforeSave = true;
                int  Serial     = 1;
                List <JobOrderInspectionRequestLineViewModel> LineStatus = new List <JobOrderInspectionRequestLineViewModel>();

                try
                {
                    BeforeSave = JobOrderInspectionRequestDocEvents.beforeWizardSaveEvent(this, new JobEventArgs(0), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    return(Json(new { Success = false, Data = message }, JsonRequestBehavior.AllowGet));
                }


                if (!BeforeSave)
                {
                    TempData["CSEXC"] += "Failed validation before save";
                }


                int Cnt = 0;
                int Sr  = 0;


                JobOrderInspectionRequestSettings Settings = new JobOrderInspectionRequestSettingsService(db).GetJobOrderInspectionRequestSettingsForDocument(DocTypeId, DivisionId, SiteId);

                int?MaxLineId = 0;

                if (ModelState.IsValid && BeforeSave && !EventException)
                {
                    JobOrderInspectionRequestHeader pt = new JobOrderInspectionRequestHeader();

                    //Getting Settings
                    pt.SiteId       = SiteId;
                    pt.JobWorkerId  = ConfirmedList.FirstOrDefault().JobWorkerId;
                    pt.DivisionId   = DivisionId;
                    pt.ProcessId    = Settings.ProcessId;
                    pt.Remark       = UserRemark;
                    pt.DocTypeId    = DocTypeId;
                    pt.DocDate      = DateTime.Now;
                    pt.DocNo        = new DocumentTypeService(_unitOfWork).FGetNewDocNo("DocNo", ConfigurationManager.AppSettings["DataBaseSchema"] + ".JobOrderInspectionRequestHeaders", pt.DocTypeId, pt.DocDate, pt.DivisionId, pt.SiteId);
                    pt.ModifiedBy   = User.Identity.Name;
                    pt.ModifiedDate = DateTime.Now;
                    pt.CreatedBy    = User.Identity.Name;
                    pt.CreatedDate  = DateTime.Now;

                    pt.Status      = (int)StatusConstants.Drafted;
                    pt.ObjectState = Model.ObjectState.Added;

                    db.JobOrderInspectionRequestHeader.Add(pt);

                    var SelectedJobOrders = ConfirmedList;

                    var JobOrderLineIds = SelectedJobOrders.Select(m => m.JobOrderLineId).ToArray();

                    var JobOrderBalanceRecords = (from p in db.ViewJobOrderBalanceForInspectionRequest
                                                  where JobOrderLineIds.Contains(p.JobOrderLineId)
                                                  select p).AsNoTracking().ToList();

                    var JobOrderRecords = (from p in db.JobOrderLine
                                           where JobOrderLineIds.Contains(p.JobOrderLineId)
                                           select p).AsNoTracking().ToList();

                    foreach (var item in SelectedJobOrders)
                    {
                        JobOrderLine Recline    = JobOrderRecords.Where(m => m.JobOrderLineId == item.JobOrderLineId).FirstOrDefault();
                        var          balRecline = JobOrderBalanceRecords.Where(m => m.JobOrderLineId == item.JobOrderLineId).FirstOrDefault();

                        if (item.Qty <= JobOrderBalanceRecords.Where(m => m.JobOrderLineId == item.JobOrderLineId).FirstOrDefault().BalanceQty)
                        {
                            JobOrderInspectionRequestLine line = new JobOrderInspectionRequestLine();

                            line.JobOrderInspectionRequestHeaderId = pt.JobOrderInspectionRequestHeaderId;
                            line.JobOrderLineId = item.JobOrderLineId;
                            line.Qty            = item.Qty;
                            line.Remark         = item.Remark;
                            line.ProductUidId   = Recline.ProductUidId;
                            line.Sr             = Serial++;
                            line.JobOrderInspectionRequestLineId = Cnt;
                            line.CreatedDate  = DateTime.Now;
                            line.ModifiedDate = DateTime.Now;
                            line.CreatedBy    = User.Identity.Name;
                            line.ModifiedBy   = User.Identity.Name;
                            LineStatus.Add(Mapper.Map <JobOrderInspectionRequestLineViewModel>(line));

                            line.ObjectState = Model.ObjectState.Added;
                            db.JobOrderInspectionRequestLine.Add(line);
                            Cnt = Cnt + 1;
                        }
                    }

                    //new JobOrderLineStatusService(_unitOfWork).UpdateJobOrderQtyQAMultiple(LineStatus, pt.DocDate, ref db);

                    try
                    {
                        JobOrderInspectionRequestDocEvents.onWizardSaveEvent(this, new JobEventArgs(pt.JobOrderInspectionRequestHeaderId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        EventException     = true;
                    }

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

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        return(Json(new { Success = false, Data = message }, JsonRequestBehavior.AllowGet));
                    }

                    try
                    {
                        JobOrderInspectionRequestDocEvents.afterWizardSaveEvent(this, new JobEventArgs(pt.JobOrderInspectionRequestHeaderId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = pt.DocTypeId,
                        DocId        = pt.JobOrderInspectionRequestHeaderId,
                        ActivityType = (int)ActivityTypeContants.WizardCreate,
                        DocNo        = pt.DocNo,
                        DocDate      = pt.DocDate,
                        DocStatus    = pt.Status,
                    }));

                    return(Json(new { Success = "URL", Data = "/JobOrderInspectionRequestHeader/Submit/" + pt.JobOrderInspectionRequestHeaderId }, JsonRequestBehavior.AllowGet));
                }

                else
                {
                    return(Json(new { Success = false, Data = "ModelState is Invalid" }, JsonRequestBehavior.AllowGet));
                }
            }
        }
        // here we simulate SQL search, sorting and paging operations
        private IQueryable <JobOrderInspectionRequestWizardViewModel> FilterData(int DocType, DateTime?FromDate, DateTime?ToDate,
                                                                                 string JobOrderHeaderId, string JobWorkerId, string ProductId, string Dimension1Id,
                                                                                 string Dimension2Id, string ProductGroupId, string ProductCategoryId, decimal?BalanceQty, decimal Qty, string Sample)
        {
            List <int> JobOrderHeaderIds = new List <int>();

            if (!string.IsNullOrEmpty(JobOrderHeaderId))
            {
                foreach (var item in JobOrderHeaderId.Split(','))
                {
                    JobOrderHeaderIds.Add(Convert.ToInt32(item));
                }
            }

            List <int> JobWorkerIds = new List <int>();

            if (!string.IsNullOrEmpty(JobWorkerId))
            {
                foreach (var item in JobWorkerId.Split(','))
                {
                    JobWorkerIds.Add(Convert.ToInt32(item));
                }
            }

            List <int> Dimension1Ids = new List <int>();

            if (!string.IsNullOrEmpty(Dimension1Id))
            {
                foreach (var item in Dimension1Id.Split(','))
                {
                    Dimension1Ids.Add(Convert.ToInt32(item));
                }
            }

            List <int> Dimension2Ids = new List <int>();

            if (!string.IsNullOrEmpty(Dimension2Id))
            {
                foreach (var item in Dimension2Id.Split(','))
                {
                    Dimension2Ids.Add(Convert.ToInt32(item));
                }
            }

            int DivisionId = (int)System.Web.HttpContext.Current.Session["DivisionId"];
            int SiteId     = (int)System.Web.HttpContext.Current.Session["SiteId"];

            var Settings = new JobOrderInspectionRequestSettingsService(db).GetJobOrderInspectionRequestSettingsForDocument(DocType, DivisionId, SiteId);

            string[] contraDocTypes = null;
            if (!string.IsNullOrEmpty(Settings.filterContraDocTypes))
            {
                contraDocTypes = Settings.filterContraDocTypes.Split(",".ToCharArray());
            }
            else
            {
                contraDocTypes = new string[] { "NA" };
            }

            string[] contraSites = null;
            if (!string.IsNullOrEmpty(Settings.filterContraSites))
            {
                contraSites = Settings.filterContraSites.Split(",".ToCharArray());
            }
            else
            {
                contraSites = new string[] { "NA" };
            }

            string[] contraDivisions = null;
            if (!string.IsNullOrEmpty(Settings.filterContraDivisions))
            {
                contraDivisions = Settings.filterContraDivisions.Split(",".ToCharArray());
            }
            else
            {
                contraDivisions = new string[] { "NA" };
            }

            IQueryable <JobOrderInspectionRequestWizardViewModel> _data = from p in db.ViewJobOrderBalanceForInspectionRequest
                                                                          join t in db.JobOrderLine on p.JobOrderLineId equals t.JobOrderLineId
                                                                          join jrh in db.JobOrderHeader on p.JobOrderHeaderId equals jrh.JobOrderHeaderId
                                                                          join jw in db.Persons on p.JobWorkerId equals jw.PersonID into jwtable
                                                                          from jwtab in jwtable.DefaultIfEmpty()
                                                                          join prod in db.FinishedProduct on p.ProductId equals prod.ProductId into prodtable
                                                                          from prodtab in prodtable.DefaultIfEmpty()
                                                                          join jol in db.JobOrderLine on t.JobOrderLineId equals jol.JobOrderLineId
                                                                          join dim1 in db.Dimension1 on jol.Dimension1Id equals dim1.Dimension1Id into dimtable
                                                                          from dimtab in dimtable.DefaultIfEmpty()
                                                                          join dim2 in db.Dimension2 on jol.Dimension2Id equals dim2.Dimension2Id into dim2table
                                                                          from dim2tab in dim2table.DefaultIfEmpty()
                                                                          join pg in db.ProductGroups on prodtab.ProductGroupId equals pg.ProductGroupId into pgtable
                                                                          from pgtab in pgtable.DefaultIfEmpty()
                                                                          join pc in db.ProductCategory on prodtab.ProductCategoryId equals pc.ProductCategoryId into pctable
                                                                          from pctab in pctable.DefaultIfEmpty()
                                                                          join ProdUid in db.ProductUid on p.ProductUidId equals ProdUid.ProductUIDId
                                                                          into produidtable
                                                                          from produidtab in produidtable.DefaultIfEmpty()
                                                                          where p.BalanceQty > 0 && jrh.ProcessId == Settings.ProcessId
                                                                          select new JobOrderInspectionRequestWizardViewModel
            {
                OrderDate                = p.OrderDate,
                OrderNo                  = p.JobOrderNo,
                JobOrderLineId           = p.JobOrderLineId,
                BalanceQty               = p.BalanceQty,
                Qty                      = Qty,
                JobWorkerName            = jwtab.Name,
                ProductName              = prodtab.ProductName,
                Dimension1Name           = dimtab.Dimension1Name,
                Dimension2Name           = dim2tab.Dimension2Name,
                JobOrderHeaderId         = p.JobOrderHeaderId,
                JobWorkerId              = p.JobWorkerId,
                ProductGroupId           = pgtab.ProductGroupId,
                ProductGroupName         = pgtab.ProductGroupName,
                ProductCategoryId        = pctab.ProductCategoryId,
                ProductCategoryName      = pctab.ProductCategoryName,
                ProdId                   = p.ProductId,
                Dimension1Id             = dimtab.Dimension1Id,
                Dimension2Id             = dim2tab.Dimension2Id,
                UnitConversionMultiplier = jol.UnitConversionMultiplier,
                DocTypeId                = jrh.DocTypeId,
                ProductUidName           = produidtab.ProductUidName,
                SiteId                   = p.SiteId,
                DivisionId               = p.DivisionId,
            };



            //if (FromDate.HasValue)
            //    _data = from p in _data
            //            where p.OrderDate >= FromDate
            //            select p;



            if (FromDate.HasValue)
            {
                _data = _data.Where(m => m.OrderDate >= FromDate);
            }

            if (ToDate.HasValue)
            {
                _data = _data.Where(m => m.OrderDate <= ToDate);
            }

            if (BalanceQty.HasValue && BalanceQty.Value > 0)
            {
                _data = _data.Where(m => m.BalanceQty == BalanceQty.Value);
            }

            if (!string.IsNullOrEmpty(JobOrderHeaderId))
            {
                _data = _data.Where(m => JobOrderHeaderIds.Contains(m.JobOrderHeaderId));
            }

            if (!string.IsNullOrEmpty(JobWorkerId))
            {
                _data = _data.Where(m => JobWorkerIds.Contains(m.JobWorkerId));
            }

            if (!string.IsNullOrEmpty(ProductId))
            {
                _data = _data.Where(m => m.ProductName.Contains(ProductId));
            }

            if (!string.IsNullOrEmpty(Dimension1Id))
            {
                _data = _data.Where(m => Dimension1Ids.Contains(m.Dimension1Id ?? 0));
            }

            if (!string.IsNullOrEmpty(Dimension2Id))
            {
                _data = _data.Where(m => Dimension2Ids.Contains(m.Dimension2Id ?? 0));
            }

            if (!string.IsNullOrEmpty(ProductGroupId))
            {
                _data = _data.Where(m => m.ProductGroupName.Contains(ProductGroupId));
            }

            if (!string.IsNullOrEmpty(ProductCategoryId))
            {
                _data = _data.Where(m => m.ProductCategoryName.Contains(ProductCategoryId));
            }

            if (!string.IsNullOrEmpty(Settings.filterContraDocTypes))
            {
                _data = _data.Where(m => contraDocTypes.Contains(m.DocTypeId.ToString()));
            }

            if (!string.IsNullOrEmpty(Settings.filterContraSites))
            {
                _data = _data.Where(m => contraSites.Contains(m.SiteId.ToString()));
            }
            else
            {
                _data = _data.Where(m => m.SiteId == SiteId);
            }

            if (!string.IsNullOrEmpty(Settings.filterContraDivisions))
            {
                _data = _data.Where(m => contraDivisions.Contains(m.DivisionId.ToString()));
            }
            else
            {
                _data = _data.Where(m => m.DivisionId == DivisionId);
            }

            //if (!string.IsNullOrEmpty(Sample) && Sample != "Include")
            //{
            //    if (Sample == "Exclude")
            //        _data = _data.Where(m => m.Sample == false);
            //    else if (Sample == "Only")
            //        _data = _data.Where(m => m.Sample == true);
            //}

            _data = _data.OrderBy(m => m.OrderDate).ThenBy(m => m.OrderNo);

            // get just one page of data
            return(_data.Select(m => new JobOrderInspectionRequestWizardViewModel
            {
                OrderDate = m.OrderDate,
                OrderNo = m.OrderNo,
                JobOrderLineId = m.JobOrderLineId,
                BalanceQty = m.BalanceQty,
                Qty = m.Qty,
                JobWorkerName = m.JobWorkerName,
                ProductName = m.ProductName,
                Dimension1Name = m.Dimension1Name,
                Dimension2Name = m.Dimension2Name,
                JobOrderHeaderId = m.JobOrderHeaderId,
                JobWorkerId = m.JobWorkerId,
                ProductGroupId = m.ProductGroupId,
                ProductGroupName = m.ProductGroupName,
                ProductCategoryId = m.ProductCategoryId,
                ProductCategoryName = m.ProductCategoryName,
                ProdId = m.ProdId,
                Dimension1Id = m.Dimension1Id,
                Dimension2Id = m.Dimension2Id,
                UnitConversionMultiplier = m.UnitConversionMultiplier,
                DocTypeId = m.DocTypeId,
                ProductUidName = m.ProductUidName,
                SiteId = m.SiteId,
                DivisionId = m.DivisionId,
            }));
        }