Ejemplo n.º 1
0
        public async Task <ActionResult> ConfigureReport(string name)
        {
            var report = (await PortalHelpers.GetReportsAsync(name)).FirstOrDefault();

            if (report == null)
            {
                return(NotFound());
            }
            return(View(new ConfigureReportModel(PortalHelpers, report)
            {
                CurrentUserEmail = CurrentUser.Email
            }));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Download(int attachmentId)
        {
            var attachment = await DB.Attachments.FindAsync(attachmentId);

            if (attachment == null)
            {
                return(HttpNotFound());
            }
            var path = PortalHelpers.GetStorageFolderPath(attachment.FilePath, false);

            Log.Information("Attachment {AttachmentId} was downloaded from {AttachmentPath}", attachmentId, path);
            return(File(System.IO.File.OpenRead(path), attachment.ContentType, attachment.FileName));
        }
        async Task <ActionResult> IWorkflowManager.RequestReassignAsync(Workflow wf)
        {
            Requires.NonNull(wf, nameof(wf));

            //TODO: Get programatically based on user's region
            var reassignGroupId = await GetNextOwnerUserIdAsync(wf, Properties.Settings.Default.ReassignGroupUserName);

            wf.OwnerUserId = reassignGroupId ?? PortalHelpers.GetUserId(Properties.Settings.Default.ReassignGroupUserName);
            var c           = new RedirectingController();
            var routeValues = new RouteValueDictionary(new Dictionary <string, object>());

            return(await Task.FromResult(c.RedirectToAction(UloController.ActionNames.Index, UloController.Name, routeValues)));
        }
Ejemplo n.º 4
0
 private bool ShowGroupRegionMembershipAlert(IEnumerable <string> groupNames, ICollection <int?> regionIds)
 {
     if (regionIds.Count > 0)
     {
         var myRegions = regionIds.ConvertAll(rid => PortalHelpers.GetRegionName(rid.GetValueOrDefault())).WhereNotNull().Format(", ");
         AddPageAlert($"You're a member of the groups: {groupNames.Format(", ")}; with regions: {myRegions}", false, PageAlert.AlertTypes.Info);
     }
     else
     {
         AddPageAlert($"You're a member of the groups: {groupNames.Format(", ")}; but haven't been assigned any regions", false, PageAlert.AlertTypes.Warning);
     }
     return(true);
 }
Ejemplo n.º 5
0
 public BackgroundTasks(IConnectionStringProvider connectionStringProvider, SpecialFolderProvider specialFolderProvider, RazorTemplateProcessor razorTemplateProcessor, IReportRunner reportRunner, IOptions <Config> configOptions, UserHelpers userHelpers, IEmailServer emailServer, UloDbContext db, IWorkflowManager workflowManager, ILogger <BackgroundTasks> logger, PortalHelpers portalHelpers)
     : base(logger)
 {
     ConnectionStringProvider = connectionStringProvider;
     SpecialFolderProvider    = specialFolderProvider;
     RazorTemplateProcessor   = razorTemplateProcessor;
     ReportRunner             = reportRunner;
     ConfigOptions            = configOptions;
     UserHelpers     = userHelpers;
     EmailServer     = emailServer;
     DB              = db;
     WorkflowManager = workflowManager;
     PortalHelpers   = portalHelpers;
 }
Ejemplo n.º 6
0
 async Task IBackgroundTasks.SendAssignWorkFlowsBatchNotifications(int[] workflowIds, string userId)
 {
     try
     {
         var workflows = PortalHelpers.GetWorkflows(DB, workflowIds);
         await SendAssignWorkFlowsBatchNotifications(workflows, userId);
     }
     catch (Exception ex)
     {
         Log.Error(ex,
                   "Problem in {methodName}",
                   nameof(IBackgroundTasks.SendAssignWorkFlowsBatchNotifications));
         throw;
     }
 }
Ejemplo n.º 7
0
        public async Task <IActionResult> FileUpload(int documentId)
        {
            var results             = new List <FileUploadAttachmentResult>();
            var attachmentsTempData = TempData.FileUploadAttachmentResults();

            foreach (var file in Request.Form.Files)
            {
                if (file.Length > 0)
                {
                    var fn         = $"{Guid.NewGuid()}.dat";
                    var attachment = new FileUploadAttachmentResult
                    {
                        AttachmentsId   = Stuff.Random.Next(int.MaxValue),
                        FileName        = file.FileName,
                        CreatedByUserId = CurrentUserId,
                        DocumentId      = documentId,
                        FileSize        = file.Length,
                        ContentType     = file.ContentType ?? System.Net.Mime.MediaTypeNames.Application.Octet
                    };
                    attachment.Whitelisted = PortalHelpers.VerifyFileAccept(attachment.FileName, attachment.ContentType);
                    if (attachment.Whitelisted)
                    {
                        attachment.FilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
                        try
                        {
                            using (var fileStream = System.IO.File.Create(attachment.FilePath))
                            {
                                await file.CopyToAsync(fileStream);
                            }
                            attachment.Added = true;
                            attachmentsTempData.Add(attachment);
                        }
                        catch (Exception ex)
                        {
                            attachment.SaveError = true;
                            attachment.ErrorMessages.Add(ex.Message);
                        }
                    }
                    else
                    {
                        attachment.ErrorMessages.Add(PortalHelpers.AttachmentFileUploadAcceptMessage);
                    }
                    results.Add(attachment);
                }
            }
            TempData.FileUploadAttachmentResults(attachmentsTempData);
            return(Json(results));
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> Details(int uloId = 0, int workflowId = 0)
        {
            //TODO: check if current user is able to view
            var ulo = await DB.UnliquidatedObligations.
                      Include(u => u.Notes).
                      Include(u => u.Region).
                      Include(u => u.Region.Zone).
                      Include(u => u.FinancialActivities).
                      WhereReviewExists().
                      FirstOrDefaultAsync(u => u.UloId == uloId);

            if (ulo == null)
            {
                return(HttpNotFound());
            }
            if (workflowId == 0)
            {
                workflowId = (await DB.Workflows.OrderByDescending(z => z.WorkflowId).FirstOrDefaultAsync(z => z.TargetUloId == ulo.UloId)).WorkflowId;
                return(RedirectToAction(ActionNames.Details, new { uloId, workflowId }));
            }

            Log.Information("Viewing ULO {UloId} with Workflow {WorkflowId}", uloId, workflowId);

            var workflow = await DB.FindWorkflowAsync(workflowId);

            var workflowAssignedToCurrentUser =
                CurrentUserId == workflow.OwnerUserId ||
                PortalHelpers.HasPermission(this.HttpContext.User, ApplicationPermissionNames.EditAnyCase);

            var belongs =
                workflow.AspNetUser.UserType == AspNetUser.UserTypes.Group &&
                BelongsToMyUnassignmentGroup(workflow.OwnerUserId, ulo.RegionId.GetValueOrDefault(-1));

            var workflowDesc = await FindWorkflowDescAsync(workflow);

            var others = DB.GetUloSummariesByPdn(ulo.PegasysDocumentNumber).ToList().Where(z => z.WorkflowId != workflowId).OrderBy(z => z.WorkflowId).ToList();

            var otherDocs = DB.GetUniqueMissingLineageDocuments(workflow, others.Select(o => o.WorkflowId));

            DB.WorkflowViews.Add(new WorkflowView {
                ActionAtUtc = DateTime.UtcNow, UserId = CurrentUserId, ViewAction = WorkflowView.CommonActions.Opened, WorkflowId = workflow.WorkflowId
            });
            await DB.SaveChangesAsync();

            return(View("Details/Index", new UloViewModel(ulo, workflow, workflowDesc, workflowAssignedToCurrentUser, others, otherDocs, belongs)));
        }
        public async Task <ActionResult> BulkReassign()
        {
            var workflowIds         = JsonConvert.DeserializeObject <int[]>(Request.Form["WorkflowIds"]);
            var reviewerId          = Request.Form["SuggestedReviewerId"];
            var comment             = Request.Form["Comments"];
            var regionIds           = UserHelpers.GetUserGroupRegions(CurrentUserName, UserHelpers.ReassignGroupUserId);
            var regionIdPredicate   = PortalHelpers.GetWorkflowsRegionIdPredicate(regionIds);
            var workflowIdPredicate = PortalHelpers.GetWorkflowsWorkflowIdPredicate(workflowIds);
            var workflows           = await DB.Workflows.Where(regionIdPredicate.And(workflowIdPredicate)).ToListAsync();

            workflows.ForEach(wf => wf.OwnerUserId = reviewerId);
            await DB.SaveChangesAsync();

            BackgroundJobClient.Enqueue <IBackgroundTasks>(bt => bt.SendAssignWorkFlowsBatchNotifications(workflowIds, reviewerId));
            AddPageAlert($"Reassigned {workflows.Count}/{workflowIds.Length} items", true, PageAlert.AlertTypes.Info);
            return(Redirect(Request.Headers["Referer"].ToString()));
        }
Ejemplo n.º 10
0
        public async Task <ActionResult> Login(string returnUrl)
        {
            PortalHelpers.HideLoginLinks(ViewBag, true);

            if (ConfigOptions.Value.UseDevAuthentication)
            {
                ViewBag.ReturnUrl = returnUrl;
                return(View("DevLogin"));
            }

            var cookie = Request.Cookies[ConfigOptions.Value.SecureAuthCookieName];

            if (cookie == null)
            {
                return(View(new LoginViewModel()));
            }
            return(await ExternalLoginCallbackAsync(returnUrl, cookie));
        }
        protected BasePageController(UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger logger)
        {
            Requires.NonNull(logger, nameof(logger));

            DB = db;

            Cacher = cacher;

            PortalHelpers = portalHelpers;
            UserHelpers   = userHelpers;

            Logger = logger.ForContext(new ILogEventEnricher[]
            {
                new PropertyEnricher(typeof(Type).Name, this.GetType().Name),
            });

            Logger.Debug("Page request to {Controller}", this.GetType().Name);
        }
Ejemplo n.º 12
0
        public ActionResult Login(string returnUrl)
        {
            PortalHelpers.HideLoginLinks(ViewBag, true);

            if (PortalHelpers.UseDevAuthentication)
            {
                ViewBag.ReturnUrl = returnUrl;
                return(View("DevLogin"));
            }

            var cookie = Request.Cookies[Properties.Settings.Default.SecureAuthCookieName];

            if (cookie == null)
            {
                return(View(new LoginViewModel()));
            }
            return(ExternalLoginCallback(returnUrl));
        }
Ejemplo n.º 13
0
 public JsonResult FileShareInfo(string relativePath, bool create = false)
 {
     try
     {
         if (!Properties.Settings.Default.AllowFileShareInfo)
         {
             throw new HttpException((int)HttpStatusCode.Forbidden, "This functionality has been disabled via configuration");
         }
         var ret = new
         {
             docPath      = Properties.Settings.Default.DocPath,
             relativePath = relativePath,
             fullPath     = PortalHelpers.GetStorageFolderPath(relativePath, create),
             create       = create
         };
         return(Json(ret, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         return(Json(new ExceptionError(ex), JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 14
0
        async Task <System.Net.Mail.Attachment> IReportRunner.ExecuteAsync(string reportName, IDictionary <string, string> paramValueByParamName)
        {
            var report = (await PortalHelpers.GetReportsAsync(reportName)).FirstOrDefault();

            using (var conn = new SqlConnection(PortalHelpers.DefaultUloConnectionString))
            {
                Log.Information("Executing report {ReportName} with {SprocSchema}.{SprocName}", reportName, report.SprocSchema, report.SprocName);
                await conn.OpenAsync();

                using (var cmd = new SqlCommand($"[{report.SprocSchema}].[{report.SprocName}]", conn)
                {
                    CommandType = CommandType.StoredProcedure,
                    CommandTimeout = 60 * 60
                })
                {
                    foreach (var pd in report.Parameters)
                    {
                        var sval = pd.IsHardcoded ? pd.HardCodedValue : paramValueByParamName[pd.SqlParameterName];
                        var oval = Convert.ChangeType(sval, pd.ClrType);
                        cmd.Parameters.Add(new SqlParameter("@" + pd.SqlParameterName, oval));
                    }
                    var ds = cmd.ExecuteReadDataSet();
                    var st = new MemoryStream();
                    ds.ToSpreadSheet(st);
                    st.Position = 0;
                    var    now      = DateTime.UtcNow;
                    string filename = report.FilenamePattern == null ?
                                      report.Name :
                                      string.Format(
                        report.FilenamePattern,
                        now,
                        now.ToLocalTime(),
                        now.ToTimeZone(PortalHelpers.DisplayTimeZone));
                    filename += MimeType.Application.SpreadSheet.Xlsx.PrimaryFileExtension;
                    return(new System.Net.Mail.Attachment(st, filename, MimeType.Application.SpreadSheet.Xlsx));
                }
            }
        }
Ejemplo n.º 15
0
 public ConfigureReportModel(ULODBEntities db, ReportDescription description = null)
 {
     Description = description;
     RegionItems.AddRange(PortalHelpers.CreateRegionSelectListItems());
     ReviewItems.AddRange(PortalHelpers.CreateReviewSelectListItems());
 }
Ejemplo n.º 16
0
 public DebuggingController(IConfiguration configuration, IOptions <Config> configOptions, UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger <DebuggingController> logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
     Configuration = configuration;
     ConfigOptions = configOptions;
 }
Ejemplo n.º 17
0
 public ReviewsController(SpecialFolderProvider specialFolderProvider, IBackgroundJobClient backgroundJobClient, UloDbContext db, PortalHelpers portalHelpers, UserHelpers userHelpers, ICacher cacher, ILogger <ReviewsController> logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
     SpecialFolderProvider = specialFolderProvider;
     BackgroundJobClient   = backgroundJobClient;
 }
Ejemplo n.º 18
0
        public async Task <ActionResult> Create(
            [Bind(new[] {
            nameof(ReviewModel.RegionId),
            nameof(ReviewModel.ReviewName),
            nameof(ReviewModel.ReviewTypeId),
            nameof(ReviewModel.ReviewScopeId),
            nameof(ReviewModel.Comments),
            nameof(ReviewModel.RegionChoices),
            nameof(ReviewModel.ReviewDateInitiated)
        })]
            ReviewModel reviewModel)
        {
            bool errors       = false;
            var  reviewTypeId = Enum.Parse <ReviewTypeEnum>(reviewModel.ReviewTypeId);

            if (DB.Reviews.Any(r => r.ReviewName == reviewModel.ReviewName))
            {
                ModelState.AddModelError("ReviewName", "The name of this review is already in use.");
                errors = true;
            }

            var requiredFileDesignators = ReviewFileDesignators.RequiredFileDesignatorsByReviewType.GetValue(reviewTypeId);

            if (requiredFileDesignators == null)
            {
                throw new UnexpectedSwitchValueException(reviewTypeId);
            }
            var distinctFileTypes = Request.Form.Files.Where(f => f.Length > 0 && requiredFileDesignators.Contains(f.Name)).Select(f => f.Name).ToHashSet();

            if (distinctFileTypes.Count != requiredFileDesignators.Count)
            {
                ModelState.AddModelError("Files", $"You must upload at least one of each type of file: {requiredFileDesignators.Format(", ")}");
                errors = true;
            }
            var    reviewScope = Enum.Parse <ReviewScopeEnum>(reviewModel.ReviewScopeId);
            string workflowDefinitionName;

            if (!PortalHelpers.TryGetGetWorkflowDefinitionName(reviewTypeId, reviewScope, out workflowDefinitionName))
            {
                ModelState.AddModelError("", $"Can't find workflowDefinitionName for scope={reviewScope}");
                errors = true;
            }
            if (ModelState.IsValid && !errors)
            {
                var wd = await DB.WorkflowDefinitions.Where(z => z.IsActive && z.WorkflowDefinitionName == workflowDefinitionName).OrderByDescending(z => z.WorkflowDefinitionId).FirstOrDefaultAsync();

                if (wd == null)
                {
                    ModelState.AddModelError("", $"Can't find active workflowDefinition for workflowDefinitionName={workflowDefinitionName}");
                    errors = true;
                    goto ErrorReturn;
                }

                //content += "before review object create<br />";
                var review = new Review
                {
                    RegionId             = reviewModel.RegionId,
                    ReviewName           = reviewModel.ReviewName,
                    Status               = Review.StatusNames.Creating,
                    ReviewTypeId         = reviewTypeId,
                    Comments             = reviewModel.Comments,
                    ReviewScopeId        = reviewScope,
                    WorkflowDefinitionId = wd.WorkflowDefinitionId,
                    CreatedAtUtc         = DateTime.UtcNow,
                    ReviewDateInitiated  = reviewModel.ReviewDateInitiated
                                           //ProjectDueDate = reviewModel.ProjectDueDate.Value,
                };
                DB.Reviews.Add(review);
                await DB.SaveChangesAsync();

                var uploadFiles = new UploadFilesModel(review.ReviewId);
                var folder      = await SpecialFolderProvider.GetReviewFolderAsync(review.ReviewId);

                foreach (var formFile in Request.Form.Files)
                {
                    if (formFile.Length == 0)
                    {
                        continue;
                    }
                    var name = formFile.FileName;
                    LogInformation("Storing review {reviewId} of type {typeName} with {size} for {fileName}", review.ReviewId, formFile.Name, formFile.Length, name);
                    var file = await folder.CreateFileAsync(name);

                    using (var dst = await file.OpenWriteAsync())
                    {
                        // read file to stream
                        await formFile.CopyToAsync(dst);
                    }
                    switch (formFile.Name)
                    {
                    case ReviewFileDesignators.PegasysFiles:
                        uploadFiles.PegasysFilePathsList.Add(name);
                        break;

                    case ReviewFileDesignators.RetaFiles:
                        uploadFiles.RetaFileList.Add(name);
                        break;

                    case ReviewFileDesignators.EasiFiles:
                        uploadFiles.EasiFileList.Add(name);
                        break;

                    case ReviewFileDesignators.One92Files:
                        uploadFiles.One92FileList.Add(name);
                        break;

                    case ReviewFileDesignators.ActiveCardholderFiles:
                        uploadFiles.ActiveCardholderFiles.Add(name);
                        break;

                    case ReviewFileDesignators.PegasysOpenItemsCreditCards:
                        uploadFiles.PegasysOpenItemsCreditCards.Add(name);
                        break;

                    case ReviewFileDesignators.WorkingCapitalFundFiles:
                        uploadFiles.WorkingCapitalFundReportFiles.Add(name);
                        break;

                    case ReviewFileDesignators.CreditCardAliasCrosswalkFiles:
                        uploadFiles.CreditCardAliasCrosswalkFiles.Add(name);
                        break;

                    default:
                        throw new UnexpectedSwitchValueException(formFile.FileName);
                    }
                }

                var uploadToSqlJob = BackgroundJobClient.Enqueue <IBackgroundTasks>(bt => bt.UploadFiles(uploadFiles));

                var createWorkflowsJobs = BackgroundJob.ContinueJobWith <IBackgroundTasks>(
                    uploadToSqlJob,
                    bt => bt.CreateULOsAndAssign(review.ReviewId, review.WorkflowDefinitionId, review.ReviewDateInitiated.Value));

                BackgroundJob.ContinueJobWith <IBackgroundTasks>(createWorkflowsJobs, bt => bt.AssignWorkFlows(review.ReviewId, PortalHelpers.SendBatchEmailsDuringAssignWorkflows));

                AddPageAlert($"Upload for reviewId={review.ReviewId} was a success. Review will load during background jobs {uploadToSqlJob} and {createWorkflowsJobs}", false, RevolutionaryStuff.AspNetCore.PageAlert.AlertTypes.Success);

                return(RedirectToIndex());
            }
ErrorReturn:
            var m = await CreateReviewModelAsync();

            reviewModel.RegionChoices = m.RegionChoices;
            reviewModel.ReviewTypes   = m.ReviewTypes;
            reviewModel.ReviewScopes  = m.ReviewScopes;
            return(View("Create", reviewModel));
        }
        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
                           )));
        }
Ejemplo n.º 20
0
 public HomeController(UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger <HomeController> logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
 }
Ejemplo n.º 21
0
        public async Task <ActionResult> Create(
            [Bind(Include =
                      nameof(ReviewModel.RegionId) + "," +
                      nameof(ReviewModel.ReviewName) + "," +
                      //nameof(ReviewModel.ReviewStatus)+","+
                      nameof(ReviewModel.ReviewTypeId) + "," +
                      nameof(ReviewModel.ReviewScopeId) + "," +
                      nameof(ReviewModel.Comments) + "," +
                      //nameof(ReviewModel.Review)+","+
                      nameof(ReviewModel.RegionChoices) + "," +
                      nameof(ReviewModel.ReviewDateInitiated))]
            ReviewModel reviewModel)
        {
            bool errors = false;

            if (DB.Reviews.Any(r => r.ReviewName == reviewModel.ReviewName))
            {
                ModelState.AddModelError("ReviewName", "The name of this review is already in use.");
                errors = true;
            }
            var distinctFileTypes = new HashSet <string>();

            foreach (string file in Request.Files)
            {
                var fileContent = Request.Files[file];
                if (fileContent != null && fileContent.ContentLength > 0)
                {
                    distinctFileTypes.Add(file);
                }
            }
            if (distinctFileTypes.Count != ReviewFileDesignators.ReviewFileTypeCount)
            {
                ModelState.AddModelError("Files", "You must upload at least one of each type of file.");
                errors = true;
            }
            var    reviewScope = (ReviewScopeEnum)reviewModel.ReviewScopeId.GetValueOrDefault(-1);
            string workflowDefinitionName;

            if (!PortalHelpers.WorkflowDefinitionNameByReviewScope.TryGetValue(reviewScope, out workflowDefinitionName))
            {
                ModelState.AddModelError("", $"Can't find workflowDefinitionName for scope={reviewScope}");
                errors = true;
            }
            if (ModelState.IsValid && !errors)
            {
                var wd = await DB.WorkflowDefinitions.Where(z => z.IsActive && z.WorkflowDefinitionName == workflowDefinitionName).OrderByDescending(z => z.WorkflowDefinitionId).FirstOrDefaultAsync();

                if (wd == null)
                {
                    ModelState.AddModelError("", $"Can't find active workflowDefinition for workflowDefinitionName={workflowDefinitionName}");
                    errors = true;
                    goto ErrorReturn;
                }

                //content += "before review object create<br />";
                var review = new Review
                {
                    RegionId             = reviewModel.RegionId,
                    ReviewName           = reviewModel.ReviewName,
                    Status               = Review.StatusNames.Creating,
                    ReviewTypeId         = reviewModel.ReviewTypeId.Value,
                    Comments             = reviewModel.Comments,
                    ReviewScopeId        = reviewModel.ReviewScopeId.Value,
                    WorkflowDefinitionId = wd.WorkflowDefinitionId,
                    CreatedAtUtc         = DateTime.UtcNow,
                    ReviewDateInitiated  = reviewModel.ReviewDateInitiated
                                           //ProjectDueDate = reviewModel.ProjectDueDate.Value,
                };
                DB.Reviews.Add(review);
                await DB.SaveChangesAsync();

                var uploadFiles = new UploadFilesModel(review.ReviewId);
                foreach (string file in Request.Files)
                {
                    //content += "staring " + file + "upload <br />";
                    var fileContent = Request.Files[file];
                    if (fileContent != null && fileContent.ContentLength > 0)
                    {
                        var path = PortalHelpers.GetStorageFolderPath($"ReviewUploads/{review.ReviewId / 1024}/{review.ReviewId}/{Guid.NewGuid()}.dat");
                        using (var fileStream = System.IO.File.Create(path))
                        {
                            await fileContent.InputStream.CopyToAsync(fileStream);
                        }
                        switch (file)
                        {
                        case ReviewFileDesignators.PegasysFiles:
                            uploadFiles.PegasysFilePathsList.Add(path);
                            break;

                        case ReviewFileDesignators.RetaFiles:
                            uploadFiles.RetaFileList.Add(path);
                            break;

                        case ReviewFileDesignators.EasiFiles:
                            uploadFiles.EasiFileList.Add(path);
                            break;

                        case ReviewFileDesignators.One92Files:
                            uploadFiles.One92FileList.Add(path);
                            break;

                        case ReviewFileDesignators.ActiveCardholderFiles:
                            uploadFiles.ActiveCardholderFiles.Add(path);
                            break;

                        case ReviewFileDesignators.PegasysOpenItemsCreditCards:
                            uploadFiles.PegasysOpenItemsCreditCards.Add(path);
                            break;

                        case ReviewFileDesignators.CreditCardAliasCrosswalkFiles:
                            uploadFiles.CreditCardAliasCrosswalkFiles.Add(path);
                            break;

                        default:
                            throw new UnexpectedSwitchValueException(file);
                        }
                    }
                }

                var uploadFilesJobId = BackgroundJobClient.Enqueue <IBackgroundTasks>(bt => bt.UploadFiles(uploadFiles));

                var jobId2 = BackgroundJob.ContinueWith <IBackgroundTasks>(uploadFilesJobId,
                                                                           bt => bt.CreateULOsAndAssign(review.ReviewId, review.WorkflowDefinitionId, review.ReviewDateInitiated.Value));

                BackgroundJob.ContinueWith <IBackgroundTasks>(jobId2, bt => bt.AssignWorkFlows(review.ReviewId, Properties.Settings.Default.SendBatchEmailsDuringAssignWorkflows));
                return(RedirectToIndex());
            }
ErrorReturn:
            var m = await CreateReviewModelAsync();

            reviewModel.RegionChoices = m.RegionChoices;
            reviewModel.ReviewTypes   = m.ReviewTypes;
            reviewModel.ReviewScopes  = m.ReviewScopes;
            return(View(reviewModel));
        }
 public DocumentInfoViewComponent(IWorkflowManager manager, UloDbContext context, PortalHelpers portalHelpers, UserHelpers userHelpers, ICacher cacher)
 {
     UloDb         = context;
     Manager       = manager;
     PortalHelpers = portalHelpers;
     UserHelpers   = userHelpers;
     Cacher        = cacher;
 }
Ejemplo n.º 23
0
 public UloController(IWorkflowManager manager, IOptions <Config> configOptions, UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger <UloController> logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
     ConfigOptions = configOptions;
     Manager       = manager;
 }
Ejemplo n.º 24
0
        public async Task <JsonResult> GetNotesAsync(int uloId)
        {
            var notes = (await DB.Notes.Include(z => z.User).Where(z => z.UloId == uloId).ToListAsync()).OrderByDescending(z => z.CreatedAtUtc).Select(z => new { z.NoteId, CreatedBy = z.User.UserName, z.Body, CreatedAt = PortalHelpers.ToLocalizedDisplayDateString(z.CreatedAtUtc, true) }).ToList();

            return(Json(notes));
        }
Ejemplo n.º 25
0
        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[] validity, string[] status, int[] reviews, bool?reassignableByMe,
                                   string sortCol = null, string sortDir = null, int?page = null, int?pageSize = null)
        {
            SetNoDataMessage(ConfigOptions.Value.NoSearchResults);
            var wfPredicate = PortalHelpers.GenerateWorkflowPredicate(this.User, uloId, pegasysDocumentNumber, organization, region, zone, fund,
                                                                      baCode, pegasysTitleNumber, pegasysVendorName, docType, contractingOfficersName, currentlyAssignedTo, hasBeenAssignedTo, awardNumber, reasons, validity, status, reviews, reassignableByMe);
            bool hasFilters = wfPredicate != null || !string.IsNullOrEmpty(Request.Query["f"]);

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

            var workflows = ApplyBrowse(
                Workflows.Where(wfPredicate).AsNoTracking(),
                sortCol ?? nameof(Workflow.DueAtUtc), sortDir, page, pageSize).ToList();

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

            var ReasonIncludedInReviewList = Cacher.FindOrCreateValue(
                Cache.CreateKey(nameof(Search), "ReasonIncludedInReviewList"),
                () => DB.UnliquidatedObligations.Select(u => u.ReasonIncludedInReview).Distinct().OrderBy(p => p).ToList().AsReadOnly(),
                PortalHelpers.MediumCacheTimeout
                );

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


            var reviewListItems = Cacher.FindOrCreateValue(Cache.CreateKey(nameof(Search), "reviewListItems"),
                                                           () =>
                                                           DB.Reviews.OrderByDescending(r => r.ReviewId).ConvertAll(
                                                               r => new SelectListItem
            {
                Text  = $"{r.ReviewName} (#{r.ReviewId}) - {AspHelpers.GetDisplayName(r.ReviewScopeId)} - {AspHelpers.GetDisplayName(r.ReviewTypeId)}",
                Value = r.ReviewId.ToString()
            }).
                                                           ToList().
                                                           AsReadOnly(),
                                                           PortalHelpers.ShortCacheTimeout
                                                           );

            var statuses = Cacher.FindOrCreateValue(
                "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());
            },
                PortalHelpers.MediumCacheTimeout);

            PopulateViewInfoIntoViewBag(workflows);

            return(View(
                       "~/Views/Ulo/Search/Index.cshtml",
                       new FilterViewModel(
                           workflows,
                           PortalHelpers.CreateDocumentTypeSelectListItems().SelectItems(docType),
                           PortalHelpers.CreateZoneSelectListItems().SelectItems(zone),
                           PortalHelpers.CreateRegionSelectListItems().SelectItems(region),
                           baCodes,
                           activityNames,
                           statuses,
                           ReasonIncludedInReviewList,
                           reviewListItems,
                           hasFilters,
                           new[] { new SelectListItem("Yes", "true"), new SelectListItem("No", "false") }.SelectItems(validity)
                           )));
        }
Ejemplo n.º 26
0
 public ReassignInfoViewComponent(IWorkflowManager manager, UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger <ReassignInfoViewComponent> logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
     Manager = manager;
 }
Ejemplo n.º 27
0
        //TODO: Email on exception or let user know what happened.
        async Task IBackgroundTasks.AssignWorkFlows(int reviewId, bool sendBatchNotifications)
        {
            try
            {
                var review = await DB.Reviews.FindAsync(reviewId);

                if (review == null)
                {
                    Log.Information("AssignWorkFlows could not find {reviewId}", reviewId);
                    return;
                }
                review.Status = Review.StatusNames.Assigning;
                await DB.SaveChangesAsync();

                var workflows =
                    DB.Workflows.Include(wf => wf.UnliquidatedObligation).Include(wf => wf.AspNetUser).
                    Where(wf => wf.OwnerUserId == PortalHelpers.PreAssignmentUserUserId).
                    OrderBy(wf => wf.UnliquidatedObligation.ReviewId == reviewId ? 0 : 1).
                    ToList();

                Log.Information("AssignWorkFlows {reviewId} assigning up to {totalRecords}", reviewId, workflows.Count);

                int z = 0;
                foreach (var workflow in workflows)
                {
                    await WorkflowManager.AdvanceAsync(workflow, null, null, true, true, !sendBatchNotifications);

                    if (++z % 10 == 0)
                    {
                        await DB.SaveChangesAsync();

                        Log.Debug("AssignWorkFlows {reviewId} save after {recordsProcessed}/{totalRecords}", reviewId, z, workflows.Count);
                        using (var zdb = PortalHelpers.UloDbCreator())
                        {
                            var r = await zdb.Reviews.FindAsync(reviewId);

                            if (r == null)
                            {
                                Log.Information("AssignWorkFlows cancelled as {reviewId} has been deleted", reviewId);
                                break;
                            }
                        }
                    }
                }
                review.SetStatusDependingOnClosedBit();
                await DB.SaveChangesAsync();

                Log.Information("AssignWorkFlows {reviewId} completed after {recordsProcessed}/{totalRecords}", reviewId, z, workflows.Count);

                if (Properties.Settings.Default.SendBatchEmailsDuringAssignWorkflows)
                {
                    BackgroundJob.Enqueue <IBackgroundTasks>(bt => bt.SendAssignWorkFlowsBatchNotifications(reviewId));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex,
                          "Problem in {methodName}",
                          nameof(IBackgroundTasks.AssignWorkFlows));
                throw;
            }
        }
Ejemplo n.º 28
0
        public AccountController(ILegacyFormsAuthenticationService legacyFormsAuthenticationService, IOptions <Config> configOptions, UloSignInManager signInManager, UloUserManager userManager, UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger <AccountController> logger)
            : base(db, cacher, portalHelpers, userHelpers, logger)
        {
            Requires.NonNull(legacyFormsAuthenticationService, nameof(legacyFormsAuthenticationService));
            Requires.NonNull(configOptions, nameof(configOptions));
            Requires.NonNull(signInManager, nameof(signInManager));
            Requires.NonNull(userManager, nameof(userManager));

            LegacyFormsAuthenticationService = legacyFormsAuthenticationService;
            ConfigOptions = configOptions;
            SignInManager = signInManager;
            UserManager   = userManager;
        }
Ejemplo n.º 29
0
        public IViewComponentResult Invoke(int?id, int workflowId, int uloRegionId, string wfDefintionOwnerName = "", bool isAdmin = false, RequestForReassignmentsController.DetailsBulkToken bulkToken = null)
        {
            bulkToken = (bulkToken != null && bulkToken.IsValid) ? bulkToken : new RequestForReassignmentsController.DetailsBulkToken(CurrentUser, DB, workflowId);
            var db = bulkToken.DB;
            RequestForReassignment requestForReassignment = null;

            if (id.HasValue)
            {
                requestForReassignment = db.RequestForReassignment.Include(z => z.UnliqudatedWorkflowQuestions).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 (PortalHelpers.UseOldGetEligibleReviewersAlgorithm)
            {
                var prohibitedUserIds = bulkToken.ProhibitedOwnerIdsByWorkflowId[workflowId];

                userSelectItems = Cacher.FindOrCreateValue(
                    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(),
                    PortalHelpers.MediumCacheTimeout
                    ).ConvertAll(z => UserHelpers.CreateUserSelectListItem(z.UserId, z.UserName, prohibitedUserIds.Contains(z.UserId))).ToList();

                if (Cacher.FindOrCreateValue(
                        Cache.CreateKey(uloRegionId, User.Identity.Name),
                        () =>
                {
                    var userReassignRegions = UserHelpers.GetReassignmentGroupRegions(User);
                    return(true);   //User.HasClaim("Application", ApplicationPermissionNames.CanReassign.ToString()) && userReassignRegions.Contains(uloRegionId); //sreen : need change back to this statement after Claims fix
                },
                        PortalHelpers.MediumCacheTimeout
                        ))
                {
                    userSelectItems.Add(UserHelpers.ToSelectListItem(bulkToken.CurrentUser));
                }
            }
            else
            {
                userSelectItems = new List <SelectListItem>();
                foreach (var p in bulkToken.PotentialReviewersByWorkflowId[workflowId])
                {
                    string text = MungeReviewerName(p.UserName, p.IsQualified);
                    userSelectItems.Add(UserHelpers.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, UserHelpers.CreateUserSelectListItem(UserHelpers.ReassignGroupUserId, UserHelpers.ReassignGroupUserName));

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

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

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

            return(View("~/Views/Ulo/Details/Workflow/RequestForReassignments/" + detailsView, new RequestForReassignmentViewModel(suggestedReviewerId, justificationKey, requestForReassignmentId, comments, workflowId, uloRegionId, userSelectItems, wfDesc.GetResassignmentJustifications())));
        }
Ejemplo n.º 30
0
 public UloController(IOptions <Config> configOptions, UloDbContext db, ICacher cacher, PortalHelpers portalHelpers, UserHelpers userHelpers, ILogger logger)
     : base(db, cacher, portalHelpers, userHelpers, logger)
 {
     ConfigOptions = configOptions;
     //Manager = manager;
     //UserManager = userManager;
     //PopulateDocumentTypeNameByDocumentTypeIdInViewBag();
 }