private MultipleValueDictionary <string, string> GetOrderedActivityNameByWorkflowName()
 => Cacher.FindOrCreateValWithSimpleKey(
     nameof(GetOrderedActivityNameByWorkflowName),
     () =>
 {
     var m = new MultipleValueDictionary <string, string>(null, () => new List <string>());
     foreach (var wd in DB.WorkflowDefinitions.Where(wfd => wfd.IsActive == true))
     {
         foreach (var activityName in wd.Description.WebActionWorkflowActivities.OrderBy(a => a.SequenceNumber).Select(a => a.ActivityName))
         {
             m.Add(wd.WorkflowDefinitionName, activityName);
         }
     }
     return(m);
 },
     UloHelpers.MediumCacheTimeout
     );
Example #2
0
        public ActionResult View(int?documentId, string docType, bool allowDocumentEdit = false)
        {
            if (docType == null && documentId.HasValue)
            {
                docType =
                    (
                        from z in DB.Documents
                        where z.DocumentId == documentId.Value
                        select z.Workflow.UnliquidatedObligation.DocType
                    ).FirstOrDefault();
            }
            Requires.NonNull(docType, nameof(docType));
            Document document;

            if (documentId.GetValueOrDefault() == 0)
            {
                document = new Document();
            }
            else
            {
                document = DB.Documents.
                           Include(z => z.Attachments).
                           Include(z => z.AspNetUser).
                           Include(z => z.DocumentDocumentTypes).
                           FirstOrDefault(dt => dt.DocumentId == documentId);
                if (document == null)
                {
                    return(HttpNotFound());
                }
            }
            document.Attachments = document.Attachments ?? new List <Attachment>();
            var documentTypes = Cacher.FindOrCreateValWithSimpleKey(
                Cache.CreateKey(typeof(DocumentsController), "documentTypes", docType),
                () => DB.DocumentTypes.Where(dt => dt.DocType == null || dt.DocType == docType).OrderBy(dt => dt.Name).ToList().AsReadOnly(),
                UloHelpers.MediumCacheTimeout);

            var workflowAssignedTo = document.DocumentId == 0 ? true : checkOwner(document);

            return(PartialView("~/Views/Ulo/Details/Documents/_View.cshtml", new DocumentModalViewModel(document, documentTypes, workflowAssignedTo)));
        }
        public async Task <ActionResult> Save(
            [Bind(Include =
                      nameof(UserModel.UserId) + "," +
                      nameof(UserModel.UserName) + "," +
                      nameof(UserModel.Email) + "," +
                      nameof(UserModel.UserType) + "," +
                      nameof(UserModel.Claims) + "," +
                      nameof(UserModel.Permissions) + "," +
                      nameof(UserModel.GroupMembershipRegionIds) + "," +
                      nameof(UserModel.Groups) + "," +
                      nameof(UserModel.SubjectCategoryClaims) + "," +
                      nameof(UserModel.SubjectCategoryClaims) + "." + nameof(SubjectCatagoryClaimValue.BACode) + "," +
                      nameof(UserModel.SubjectCategoryClaims) + "." + nameof(SubjectCatagoryClaimValue.DocType) + "," +
                      nameof(UserModel.SubjectCategoryClaims) + "." + nameof(SubjectCatagoryClaimValue.OrgCode) + "," +
                      nameof(UserModel.SubjectCategoryClaims) + "." + nameof(SubjectCatagoryClaimValue.Regions)
                  )]
            UserModel m)
        {
            AspNetUser u = null;

            m.UserId   = StringHelpers.TrimOrNull(m.UserId);
            m.UserName = StringHelpers.TrimOrNull(m.UserName);
            m.Email    = StringHelpers.TrimOrNull(m.Email);
            var users = await DB.AspNetUsers.Where(z => z.UserName == m.UserName || z.Email == m.Email || z.Id == m.UserId).ToListAsync();

            bool hasErrors     = false;
            bool userNameError = false;
            bool emailError    = false;

            foreach (var user in users)
            {
                if (user.Id == m.UserId)
                {
                    u = user;
                    continue;
                }
                if (0 == string.Compare(m.UserName, user.UserName, true) && !userNameError && m.UserName != null)
                {
                    ModelState.AddModelError(nameof(m.UserName), $"Username {m.UserName} already exists, cannot re-add");
                    hasErrors     = true;
                    userNameError = true;
                }
                if (0 == string.Compare(m.Email, user.Email, true) && !emailError && m.Email != null)
                {
                    ModelState.AddModelError(nameof(m.Email), $"Email {m.Email} already exists, cannot re-add");
                    hasErrors  = true;
                    emailError = true;
                }
            }
            if (ModelState.IsValid && !hasErrors)
            {
                if (u == null && m.UserId == null)
                {
                    var res = await UserManager.CreateAsync(new ApplicationUser { UserName = m.UserName, Email = StringHelpers.TrimOrNull(m.Email) });

                    u = await DB.AspNetUsers.FirstOrDefaultAsync(z => z.UserName == m.UserName);

                    Log.Information("Created new user UserId={UserId} => UserName={UserName}, Email={Email}", u.Id, u.UserName, u.Email);
                }
                else if (u == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    Log.Information("Modified existing with UserId={UserId} => OldUserName={OldUserName}, OldEmail={OldEmail}, NewUserName={NewUserName}, NewEmail={NewEmail}", u.Id, u.UserName, u.Email, m.UserName, m.Email);
                    u.Email    = m.Email;
                    u.UserName = m.UserName;
                }

                var myGroups = await DB.AspNetUsers.Where(PortalHelpers.GrouplikeUserPredicate).Where(g => m.Groups.Contains(g.UserName)).ToListAsync();

                foreach (var uu in u.ChildUserUsers.ToList())
                {
                    DB.UserUsers.Remove(uu);
                }
                m.GroupMembershipRegionIds.ForEach(rid => myGroups.ForEach(g => DB.UserUsers.Add(new UserUser {
                    ParentUser = g, ChildUser = u, RegionId = rid
                })));
                foreach (var c in u.AspNetUserClaims.Where(z => z.ClaimType == ApplicationPermissionClaimValue.ClaimType || z.ClaimType == SubjectCatagoryClaimValue.ClaimType).ToList())
                {
                    DB.AspNetUserClaims.Remove(c);
                }
                var allRegions = Cacher.FindOrCreateValWithSimpleKey("allRegionsHashSet", () => DB.Regions.Select(z => z.RegionId).ToSet());
                foreach (var p in m.Permissions)
                {
                    DB.AspNetUserClaims.Add(new AspNetUserClaim
                    {
                        ClaimType  = ApplicationPermissionClaimValue.ClaimType,
                        UserId     = u.Id,
                        AspNetUser = u,
                        ClaimValue = new ApplicationPermissionClaimValue
                        {
                            ApplicationPermissionName = Parse.ParseEnum <ApplicationPermissionNames>(p),
                            Regions = allRegions
                        }.ToXml()
                    });
                }
                var sccDocTypes = HttpContext.Request.Form.GetValues("scc.docType") ?? Empty.StringArray;
                var sccBaCodes  = HttpContext.Request.Form.GetValues("scc.bacode") ?? Empty.StringArray;
                var sccOrgCodes = HttpContext.Request.Form.GetValues("scc.orgcode") ?? Empty.StringArray;
                var sccRegions  = HttpContext.Request.Form.GetValues("scc.region") ?? Empty.StringArray;
                m.Claims.Clear();
                m.SubjectCategoryClaims = new List <AspnetUserSubjectCategoryClaim>();
                for (int z = 0; z < sccDocTypes.Length; ++z)
                {
                    var sccv = new SubjectCatagoryClaimValue
                    {
                        BACode  = sccBaCodes[z],
                        DocType = sccDocTypes[z],
                        OrgCode = sccOrgCodes[z]
                    };
                    if (null == StringHelpers.TrimOrNull(sccv.DocType))
                    {
                        continue;
                    }
                    int regionId = Parse.ParseInt32(sccRegions[z]);
                    sccv.Regions = sccv.Regions ?? new HashSet <int>();
                    sccv.Regions.Add(regionId);
                    DB.AspNetUserClaims.Add(new AspNetUserClaim
                    {
                        ClaimType  = SubjectCatagoryClaimValue.ClaimType,
                        UserId     = u.Id,
                        AspNetUser = u,
                        ClaimValue = sccv.ToXml()
                    });
                    var scc = new AspnetUserSubjectCategoryClaim
                    {
                        BACode       = sccv.BACode,
                        DocumentType = sccv.DocType,
                        OrgCode      = sccv.OrgCode,
                    };
                    m.SubjectCategoryClaims.Add(scc);
                    m.Claims.Add(scc.ToFriendlyString());
                }
                await DB.SaveChangesAsync();

                return(RedirectToIndex());
            }
            await PopulateDetailsViewBag();

            if (m.UserId == null)
            {
                return(View("Create", m));
            }
            else
            {
                return(View("Details", m));
            }
        }
        public ActionResult Search(int?uloId, string pegasysDocumentNumber, string organization, int[] region, int[] zone, string fund, string[] baCode, string pegasysTitleNumber, string pegasysVendorName, string[] docType, string contractingOfficersName, string currentlyAssignedTo, string hasBeenAssignedTo, string awardNumber, string[] reasons, bool[] valid, string[] status, int[] reviewId, bool?reassignableByMe,
                                   string sortCol = null, string sortDir = null, int?page = null, int?pageSize = null)
        {
            SetNoDataMessage(NoDataMessages.NoSearchResults);
            var wfPredicate = PortalHelpers.GenerateWorkflowPredicate(this.User, uloId, pegasysDocumentNumber, organization, region, zone, fund,
                                                                      baCode, pegasysTitleNumber, pegasysVendorName, docType, contractingOfficersName, currentlyAssignedTo, hasBeenAssignedTo, awardNumber, reasons, valid, status, reviewId, reassignableByMe);
            bool hasFilters = wfPredicate != null || Request["f"] != null;

            if (!hasFilters)
            {
                wfPredicate = PredicateBuilder.Create <Workflow>(wf => false);
            }
            else if (wfPredicate == null)
            {
                wfPredicate = PredicateBuilder.Create <Workflow>(wf => true);
            }

            var workflows = ApplyBrowse(
                DB.Workflows.AsNoTracking().Where(wfPredicate).
                Include(wf => wf.UnliquidatedObligation).AsNoTracking().
                Include(wf => wf.UnliquidatedObligation.Region).AsNoTracking().
                Include(wf => wf.UnliquidatedObligation.Region.Zone).AsNoTracking().
                Include(wf => wf.RequestForReassignments).AsNoTracking().
                Include(wf => wf.AspNetUser).AsNoTracking().
                WhereReviewExists(),
                sortCol ?? nameof(Workflow.DueAtUtc), sortDir, page, pageSize).ToList();

            var baCodes = Cacher.FindOrCreateValWithSimpleKey(
                Cache.CreateKey(nameof(Search), "baCodes"),
                () => DB.UnliquidatedObligations.Select(u => u.Prog).Distinct().OrderBy(p => p).ToList().AsReadOnly(),
                UloHelpers.MediumCacheTimeout
                );

            var activityNames = GetOrderedActivityNameByWorkflowName().AtomEnumerable.ConvertAll(z => z.Value).Distinct().OrderBy().ToList();

            var statuses = Cacher.FindOrCreateValWithSimpleKey(
                "AllWorkflowStatusNames",
                () =>
            {
                var names = new List <string>();
                foreach (var wd in DB.WorkflowDefinitions.Where(wfd => wfd.IsActive == true))
                {
                    names.AddRange(wd.Description.WebActionWorkflowActivities.Select(z => z.ActivityName));
                }
                return(names.Distinct().OrderBy());
            },
                UloHelpers.MediumCacheTimeout);

            PopulateViewInfoIntoViewBag(workflows);

            return(View(
                       "~/Views/Ulo/Search/Index.cshtml",
                       new FilterViewModel(
                           workflows,
                           PortalHelpers.CreateDocumentTypeSelectListItems().Select(docType),
                           PortalHelpers.CreateZoneSelectListItems().Select(zone),
                           PortalHelpers.CreateRegionSelectListItems().Select(region),
                           baCodes,
                           activityNames,
                           statuses,
                           Cacher.FindOrCreateValWithSimpleKey(
                               "ReasonsIncludedInReview",
                               () => DB.UnliquidatedObligations.Select(z => z.ReasonIncludedInReview).Distinct().WhereNotNull().OrderBy().AsReadOnly(),
                               UloHelpers.MediumCacheTimeout),
                           hasFilters
                           )));
        }
        public ActionResult MyTasks(string t, string sortCol, string sortDir, int?page, int?pageSize)
        {
            SetNoDataMessage(NoDataMessages.NoTasks);

            var workflows = DB.Workflows.Where(wf => wf.OwnerUserId == CurrentUserId).WhereReviewExists();

            var countByKey = new Dictionary <string, int>(workflows.GroupBy(w => w.CurrentWorkflowActivityKey).Select(g => new { CurrentWorkflowActivityKey = g.Key, Count = g.Count() }).ToDictionaryOnConflictKeepLast(z => z.CurrentWorkflowActivityKey, z => z.Count), Comparers.CaseInsensitiveStringComparer);

            var keyByName = Cacher.FindOrCreateValWithSimpleKey("workflowKeyByActivityNameForAllActiveWorkflows", () => {
                var d = new Dictionary <string, string>(Comparers.CaseInsensitiveStringComparer);
                foreach (var wfd in DB.WorkflowDefinitions.Where(z => z.IsActive))
                {
                    if (wfd.Description == null || wfd.Description.Activities == null)
                    {
                        continue;
                    }
                    foreach (var a in wfd.Description.Activities)
                    {
                        d[a.ActivityName] = a.WorkflowActivityKey;
                    }
                }
                return(d);
            }, UloHelpers.MediumCacheTimeout);

            var tabs = new List <WorkflowListTab>();

            foreach (var name in CSV.ParseLine(Properties.Settings.Default.MyTasksTabsCsv))
            {
                var tab = new WorkflowListTab {
                    TabName = StringHelpers.TrimOrNull(name)
                };
                if (tab.TabName == null)
                {
                    continue;
                }
                tab.TabKey = keyByName.GetValue(tab.TabName);
                if (tab.TabKey == null)
                {
                    continue;
                }
                tab.ItemCount = countByKey.GetValue(tab.TabKey);
                tab.IsCurrent = tab.TabKey == t;
                tabs.Add(tab);
            }

            var items = DB.ListableWorkflows(CurrentUserId, CurrentUserId);

            if (t != null)
            {
                items = items.Where(z => z.CurrentWorkflowActivityKey == t);
            }

            sortCol = sortCol ?? nameof(ListableWorkflows_Result.Status);
            if (sortCol == nameof(ListableWorkflows_Result.Status))
            {
                items = ApplyBrowse(
                    items,
                    sortCol,
                    CSV.ParseLine(Properties.Settings.Default.ReviewStatusOrdering),
                    sortDir, page, pageSize);
            }
            else
            {
                items = ApplyBrowse(
                    items,
                    sortCol, sortDir, page, pageSize);
            }

            PopulateTabsIntoViewBag(tabs);
            return(View(items));
        }
Example #6
0
 private Task <IQueryable <ReportDescription> > GetAllReportsAsync()
 => Task.FromResult(Cacher.FindOrCreateValWithSimpleKey(
                        nameof(GetAllReportsAsync),
                        () => DB.ReportDefinitions.Where(rd => rd.IsActive == true).ConvertAll(rd => rd.Description).WhereNotNull().ToList().AsReadOnly(),
                        UloHelpers.MediumCacheTimeout).AsQueryable()
                    );
        public ActionResult Details(int?id, int workflowId, int uloRegionId, string wfDefintionOwnerName = "", bool isAdmin = false, DetailsBulkToken bulkToken = null)
        {
            bulkToken = (bulkToken != null && bulkToken.IsValid) ? bulkToken : new DetailsBulkToken(CurrentUser, DB, workflowId);
            var db = bulkToken.DB;
            RequestForReassignment requestForReassignment = null;

            if (id.HasValue)
            {
                requestForReassignment = db.RequestForReassignments.Include(z => z.UnliqudatedObjectsWorkflowQuestion).FirstOrDefault(r => r.RequestForReassignmentID == id.Value);
            }

            var workflow = db.Workflows.Find(workflowId);
            var wfDesc   = Manager.GetWorkflowDescriptionAsync(workflow).Result;

            string groupOwnerId;

            if (wfDefintionOwnerName == "")
            {
                var currentActivity = wfDesc.WebActionWorkflowActivities
                                      .FirstOrDefault(a => a.WorkflowActivityKey == workflow.CurrentWorkflowActivityKey);
                groupOwnerId = PortalHelpers.GetUserId(currentActivity.OwnerUserName);
            }
            else
            {
                groupOwnerId = PortalHelpers.GetUserId(wfDefintionOwnerName);
            }


            IList <SelectListItem> userSelectItems;

            if (Properties.Settings.Default.UseOldGetEligibleReviewersAlgorithm)
            {
                var prohibitedUserIds = bulkToken.ProhibitedOwnerIdsByWorkflowId[workflowId];

                userSelectItems = Cacher.FindOrCreateValWithSimpleKey(
                    Cache.CreateKey(groupOwnerId, uloRegionId, "fdsfdsaf"),
                    () => db.UserUsers
                    .Where(uu => uu.ParentUserId == groupOwnerId && uu.RegionId == uloRegionId && uu.ChildUser.UserType == AspNetUser.UserTypes.Person)
                    .Select(uu => new { UserName = uu.ChildUser.UserName, UserId = uu.ChildUserId }).ToList(),
                    UloHelpers.MediumCacheTimeout
                    ).ConvertAll(z => PortalHelpers.CreateUserSelectListItem(z.UserId, z.UserName, prohibitedUserIds.Contains(z.UserId))).ToList();

                if (Cacher.FindOrCreateValWithSimpleKey(
                        Cache.CreateKey(uloRegionId, User.Identity.Name),
                        () =>
                {
                    var userReassignRegions = User.GetReassignmentGroupRegions();
                    return(true);   // User.HasPermission(ApplicationPermissionNames.CanReassign) && userReassignRegions.Contains(uloRegionId);
                },
                        UloHelpers.MediumCacheTimeout
                        ))
                {
                    userSelectItems.Add((bulkToken.CurrentUser).ToSelectListItem(prohibitedUserIds.Contains(CurrentUserId)));
                }
            }
            else
            {
                userSelectItems = new List <SelectListItem>();
                foreach (var p in bulkToken.PotentialReviewersByWorkflowId[workflowId])
                {
                    string text = MungeReviewerName(p.UserName, p.IsQualified);
                    userSelectItems.Add(PortalHelpers.CreateUserSelectListItem(p.UserId, text));
                }
            }

            if (workflow.OwnerUserId == CurrentUserId)
            {
                userSelectItems.Remove(userSelectItems.Where(z => z.Value == CurrentUserId).ToList());
            }

            userSelectItems = userSelectItems.OrderBy(z => z.Text).ToList();

            userSelectItems.Insert(0, PortalHelpers.CreateUserSelectListItem(PortalHelpers.ReassignGroupUserId, PortalHelpers.ReassignGroupUserName));

            var requestForReassignmentId = requestForReassignment?.RequestForReassignmentID;
            var suggestedReviewerId      = requestForReassignment != null ? requestForReassignment.SuggestedReviewerId : "";
            var justificationKey         = requestForReassignment?.UnliqudatedObjectsWorkflowQuestion.JustificationKey;

            var comments = requestForReassignment != null
                ? requestForReassignment.UnliqudatedObjectsWorkflowQuestion.Comments : "";

            var detailsView = isAdmin ? "_DetailsMasterList.cshtml" : "_Details.cshtml";

            return(PartialView(
                       "~/Views/Ulo/Details/Workflow/RequestForReassignments/" + detailsView,
                       new RequestForReassignmentViewModel(suggestedReviewerId, justificationKey, requestForReassignmentId, comments, workflowId, uloRegionId, userSelectItems, wfDesc.GetResassignmentJustifications())));
        }