public void TestOrderEditedAccountManagerNoEmailPrefs1()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("burns");
            SetupUsers();
            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);
            var user = UserRepository.GetNullableById("hsimpson");
            var approval = new Approval();
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager);
            approval.Completed = true;
            order.GenerateRequestNumber();
            new FakeEmailPreferences(0, EmailPreferenceRepository);
            #endregion Arrange

            #region Act
            NotificationService.OrderEdited(order, user);
            #endregion Act

            #region Assert
            Assert.AreEqual(1, order.EmailQueuesV2.Count);
            Assert.AreEqual(DateTime.UtcNow.ToPacificTime().Date, order.EmailQueuesV2[0].DateTimeCreated.Date);
            Assert.IsNull(order.EmailQueuesV2[0].DateTimeSent);
            Assert.AreEqual(EmailPreferences.NotificationTypes.PerEvent, order.EmailQueuesV2[0].NotificationType);
            Assert.IsTrue(order.EmailQueuesV2[0].Pending);
            Assert.IsNull(order.EmailQueuesV2[0].Status);
            Assert.AreEqual("Changed", order.EmailQueuesV2[0].Action);
            Assert.AreEqual("By Homer Simpson at Account Manager review.", order.EmailQueuesV2[0].Details);
            #endregion Assert
        }
        public void TestOrderApprovedAccountManagerEmailPrefs2()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("burns");
            SetupUsers();

            var emailPrefs = new List<EmailPreferences>();
            emailPrefs.Add(new EmailPreferences("bender"));
            emailPrefs[0].NotificationType = EmailPreferences.NotificationTypes.Daily;
            emailPrefs.Add(new EmailPreferences("hsimpson"));
            emailPrefs[1].NotificationType = EmailPreferences.NotificationTypes.Weekly;
            new FakeEmailPreferences(0, EmailPreferenceRepository, emailPrefs, true);

            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);
            var approval = new Approval();
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager);
            approval.Completed = true;
            #endregion Arrange

            #region Act
            NotificationService.OrderApproved(order, approval);
            #endregion Act

            #region Assert
            Assert.AreEqual(2, order.EmailQueuesV2.Count);
            Assert.AreEqual(EmailPreferences.NotificationTypes.Daily, order.EmailQueuesV2[0].NotificationType);
            Assert.AreEqual(EmailPreferences.NotificationTypes.Weekly, order.EmailQueuesV2[1].NotificationType);
            #endregion Assert
        }
        public void Put(Approval approval)
        {
            if (!ModelState.IsValid)
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));

            var order = _orderRepo.Get(approval.OrderId);
            if (order.Approved == approval.Approved) return;

            order.Approved = approval.Approved;
            _orderRepo.Update(order);

            ShoppingCartHub.Value.Clients.Client(order.CustomerName).orderApproved(order);

            if (!order.Approved)
            {
                if (!ValidateQuantities(order)) throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Order has illegal quantities!."));

                foreach (var book in order.Books)
                {
                    var originalBook = _bookRepo.Get(book.Id);
                    originalBook.Quantity += book.SelectedQuantity;
                    _bookRepo.Update(originalBook);
                    ShoppingCartHub.Value.Clients.All.updateProductCount(originalBook);
                }
            }
        }
        public static Approval Approval(int? counter)
        {
            var rtValue = new Approval();
            rtValue.User = new User();
            rtValue.Order = new Order();
            rtValue.StatusCode = new OrderStatusCode();

            return rtValue;
        }
Example #5
0
 public static Approval[][] GetApprovalMatrixFromListApproval(List<Approval> listApproval)
 {
     Approval[][] approvalMatrix = new Approval[8][];
     Approval[] approvalArrayBA = new Approval[1];   // Business Analyst
     Approval[] approvalArrayPM = new Approval[1];   // Project Manager
     Approval[] approvalArrayLOBH = new Approval[1]; // LOB Head
     Approval[] approvalArrayBU = new Approval[2];   // Business User
     Approval[] approvalArrayBUH = new Approval[2];  // Business User Head
     Approval[] approvalArrayBUDH = new Approval[1]; // Business User Division Head
     Approval[] approvalArrayITRM = new Approval[1]; // ITRM
     Approval[] approvalArrayS = new Approval[3];    // Stakeholder
     int indexBU = 0;
     int indexBUH = 0;
     int indexS = 0;
     for (int i = 0; i < listApproval.Count; i++)
     {
         switch (listApproval[i].StrRole)
         {
             case "BA":
                 approvalArrayBA[0] = listApproval[i];
                 break;
             case "PM":
                 approvalArrayPM[0] = listApproval[i];
                 break;
             case "LOBH":
                 approvalArrayLOBH[0] = listApproval[i];
                 break;
             case "BU":
                 approvalArrayBU[indexBU] = listApproval[i];
                 indexBU++;
                 break;
             case "BUH":
                 approvalArrayBUH[indexBUH] = listApproval[i];
                 indexBUH++;
                 break;
             case "BUDH":
                 approvalArrayBUDH[0] = listApproval[i];
                 break;
             case "ITRM":
                 approvalArrayITRM[0] = listApproval[i];
                 break;
             case "S":
                 approvalArrayS[indexS] = listApproval[i];
                 indexS++;
                 break;
         }
     }
     approvalMatrix[0] = approvalArrayBA;
     approvalMatrix[1] = approvalArrayPM;
     approvalMatrix[2] = approvalArrayLOBH;
     approvalMatrix[3] = approvalArrayBU;
     approvalMatrix[4] = approvalArrayBUH;
     approvalMatrix[5] = approvalArrayBUDH;
     approvalMatrix[6] = approvalArrayITRM;
     approvalMatrix[7] = approvalArrayS;
     return approvalMatrix;
 }
Example #6
0
 public static Approval[] GetApprovalArrayFromListApproval2(List<Approval> listApproval)
 {
     Approval[] approvalArray = new Approval[4];
     for (int i = 0; i < listApproval.Count; i++)
     {
         switch (listApproval[i].StrRole)
         {
             case "QC":
                 approvalArray[0] = listApproval[i];
                 break;
             case "SA":
                 approvalArray[1] = listApproval[i];
                 break;
             case "PM":
                 approvalArray[2] = listApproval[i];
                 break;
             case "LOBH":
                 approvalArray[3] = listApproval[i];
                 break;
         }
     }
     return approvalArray;
 }
Example #7
0
 /// <summary>
 /// Add an Approved By row view model to the list of <see cref="ApprovedBy"/>
 /// </summary>
 /// <param name="approvedBy">
 /// The <see cref="ApprovedBy"/> that is to be added
 /// </param>
 private ApprovalRowViewModel AddApprovedByRowViewModel(Approval approvedBy)
 {
     return(new ApprovalRowViewModel(approvedBy, this.Session, this));
 }
Example #8
0
 public async Task Create(Approval approval)
 {
     await _context.approval.InsertOneAsync(approval);
 }
Example #9
0
        public void TestOrderCreatedProcessArrival12()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("bender");
            SetupUsers();
            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);

            var approvals = new List <Approval>();
            CreateApprovals(approvals, OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver), order);
            var conditionalApproval = new Approval();
            conditionalApproval.Order = new Order();
            conditionalApproval.Order.SetIdTo(order.Id);
            conditionalApproval.StatusCode    = OrderStatusCodeRepository.GetNullableById(Role.Codes.Approver);
            conditionalApproval.User          = UserRepository.GetNullableById("zoidberg");
            conditionalApproval.SecondaryUser = UserRepository.GetNullableById("zoidberg");
            approvals.Add(conditionalApproval);

            var accountManager = new Approval();
            accountManager.Order = new Order();
            accountManager.Order.SetIdTo(order.Id);
            accountManager.StatusCode    = OrderStatusCodeRepository.GetNullableById(Role.Codes.AccountManager);
            accountManager.User          = UserRepository.GetNullableById("AccManag".ToLower());
            accountManager.SecondaryUser = UserRepository.GetNullableById("AccManag".ToLower());
            approvals.Add(accountManager);

            var purchaser = new Approval();
            purchaser.Order = new Order();
            purchaser.Order.SetIdTo(order.Id);
            purchaser.StatusCode    = OrderStatusCodeRepository.GetNullableById(Role.Codes.AccountManager);
            purchaser.User          = UserRepository.GetNullableById("pur");
            purchaser.SecondaryUser = UserRepository.GetNullableById("pur");
            approvals.Add(purchaser);

            var saveLevel = 0;
            foreach (var approval in approvals)
            {
                if (approval.User != null && approval.User.Id == "hsimpson")
                {
                    saveLevel              = approval.StatusCode.Level;
                    approval.User          = null;
                    approval.SecondaryUser = null;
                }
                order.AddApproval(approval);
            }
            order.Workgroup.Permissions = new List <WorkgroupPermission>();
            var permission = CreateValidEntities.WorkgroupPermission(1);
            permission.User       = new User("Flarg");
            permission.Role       = new Role(OrderStatusCode.Codes.Approver);
            permission.Role.Level = saveLevel;
            order.Workgroup.Permissions.Add(permission);

            permission            = CreateValidEntities.WorkgroupPermission(2);
            permission.User       = new User("Blarg");
            permission.Role       = new Role(OrderStatusCode.Codes.Approver);
            permission.Role.Level = saveLevel;
            order.Workgroup.Permissions.Add(permission);

            order.GenerateRequestNumber();

            var emailPrefs = new List <EmailPreferences>();
            emailPrefs.Add(new EmailPreferences("bender"));
            emailPrefs[0].NotificationType         = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[0].RequesterOrderSubmission = false;

            emailPrefs.Add(new EmailPreferences("Flarg".ToLower()));
            emailPrefs[1].NotificationType         = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[1].RequesterOrderSubmission = true;  //Doesn't Matter, did not create it
            emailPrefs[1].ApproverOrderArrive      = false;

            emailPrefs.Add(new EmailPreferences("Blarg".ToLower()));
            emailPrefs[2].NotificationType         = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[2].RequesterOrderSubmission = false;  //Doesn't Matter, did not create it
            emailPrefs[2].ApproverOrderArrive      = false;

            emailPrefs.Add(new EmailPreferences("zoidberg"));
            emailPrefs[3].NotificationType    = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[3].ApproverOrderArrive = false;
            new FakeEmailPreferences(0, EmailPreferenceRepository, emailPrefs, true);
            new FakeAdminWorkgroups(3, AdminWorkgroupRepository);
            new FakeWorkgroups(3, WorkgroupRepository);
            #endregion Arrange

            #region Act
            NotificationService.OrderCreated(order);
            #endregion Act

            #region Assert
            Assert.AreEqual(0, order.EmailQueuesV2.Count());
            Assert.AreEqual(7, order.Approvals.Count());
            //Assert.AreEqual(string.Format("Order request {0} has been submitted.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[0].Text);
            //Assert.AreEqual("bender", order.EmailQueuesV2[0].User.Id);
            //Assert.AreEqual(string.Format("Order request {0} has arrived at your level (Approver) for review from Bender Rodriguez.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[0].Text);
            //Assert.AreEqual("Flarg", order.EmailQueuesV2[0].User.Id);
            //Assert.AreEqual(string.Format("Order request {0} has arrived at your level (Approver) for review from Bender Rodriguez.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[0].Text);
            //Assert.AreEqual("Blarg", order.EmailQueuesV2[0].User.Id);

            //Assert.AreEqual(string.Format("Order request {0} has arrived at your level (Approver) for review from Bender Rodriguez.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[1].Text);
            //Assert.AreEqual("zoidberg", order.EmailQueuesV2[1].User.Id);
            #endregion Assert
        }
Example #10
0
 public ApprovalTests()
 {
     _it = new Approval();
 }
 public ApprovalController()
 {
     _Approval         = new Approval();
     _ApprovalBusiness = new ApprovalBusiness();
 }
Example #12
0
        public void ProcessArrival(Order order, Approval approval, int level, bool assigned = false)
        {
            // find all the approvals at the next level
            var future = order.Approvals.Where(a => a.StatusCode.Level == level);

            // check for any approvals not specifically assigned to anyone
            var wrkgrp = future.Any(a => a.User == null);

            // get the current user
            var currentUser = _userRepository.GetNullableById(_userIdentity.Current);

            var queues = new List<EmailQueueV2>();

            // there is at least one that is workgroup permissions
            if (wrkgrp)
            {

                var peeps = order.Workgroup.Permissions.Where(a => a.Role.Level == level && (!a.IsAdmin || (a.IsAdmin && a.IsFullFeatured))).Select(a => a.User);

                var apf = future.First(a => a.User == null);

                foreach (var peep in peeps)
                {
                    if (!peep.IsActive) //Not active, we don't want to email them
                    {
                        continue;
                    }
                    var preference = GetEmailPreferences(peep.Id);

                    if (IsMailRequested(preference, apf.StatusCode, approval != null ? approval.StatusCode : null, EventCode.Arrival))
                    {
                        var extraInfo = string.Empty;
                        if (preference.ShowAccountInEmail && apf.StatusCode.Id == OrderStatusCode.Codes.AccountManager)
                        {
                            extraInfo = string.Format(" with accounts {0}", order.AccountNumbers);
                        }
                        //var emailQueue = new EmailQueue(order, preference.NotificationType, string.Format(ArrivalMessage, GenerateLink(_serverLink.Address, order.OrderRequestNumber()), order.Vendor == null ? "Unspecified Vendor" : order.Vendor.Name, apf.StatusCode.Name, currentUser.FullName, extraInfo), peep);
                        var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Arrived", string.Format("At your level ({0}) for review from {1}{2}.", apf.StatusCode.Name, currentUser.FullName, extraInfo), peep);
                        AddToQueue(queues, emailQueue2);
                    }
                }

                // find any that still need to be sent regardless (outside of workgroup)
                var aps = future.Where(a => a.User != null && !peeps.Contains(a.User));

                ProcessApprovalsEmailQueue(order, approval, queues, currentUser, aps, assigned);
            }
            else
            {
                // check each of the approvals
                ProcessApprovalsEmailQueue(order, approval, queues, currentUser, future, assigned);
            }

            AddQueuesToOrder(order, queues);
        }
Example #13
0
        private void SetupPurchaseOrderCost(Cost cost, CostStageRevision latestRevision,
                                            CostUser costOwner, Guid previousRevisionId, Guid latestRevisionId, string poNumber)
        {
            const string brandApproverGdamUserId = "57e5461ed9563f268ef4f1ta";
            const string brandApproverName       = "John Smith";
            var          costId      = Guid.NewGuid();
            var          costOwnerId = Guid.NewGuid();
            var          projectId   = Guid.NewGuid();

            var previousStageId = Guid.NewGuid();
            var latestStageId   = Guid.NewGuid();

            var previousRevision        = new CostStageRevision();
            var previousStage           = new CostStage();
            var latestStage             = new CostStage();
            var project                 = new Project();
            var brand                   = new Brand();
            var agency                  = new Agency();
            var country                 = new Country();
            var brandApproval           = new Approval();
            var brandApprover           = new ApprovalMember();
            var brandApproverAsCostUser = new CostUser();

            previousRevision.CostStage = previousStage;
            previousRevision.Id        = previousRevisionId;

            previousStage.Id = previousRevision.CostStageId = previousStageId;
            latestStage.Id   = latestRevision.CostStageId = latestStageId;

            previousStage.Name = CostStages.OriginalEstimate.ToString();
            latestStage.Name   = CostStages.FinalActual.ToString();

            cost.CostStages.AddRange(new[] { previousStage, latestStage });

            //China non-Cyclone Agencies should create a notification for non-backup approver when the cost total amount has changed
            SetupDataSharedAcrossTests(agency, country, cost, latestRevision, project, costOwner, costOwnerId, latestStage,
                                       brand, costId, latestRevisionId, projectId, Constants.BudgetRegion.China);

            brandApproval.ApprovalMembers = new List <ApprovalMember> {
                brandApprover
            };
            brandApprover.CostUser = brandApproverAsCostUser;

            brandApproval.Type = ApprovalType.Brand;
            brandApproverAsCostUser.GdamUserId = brandApproverGdamUserId;
            brandApproverAsCostUser.FullName   = brandApproverName;

            var approvals = new List <Approval> {
                brandApproval
            };

            ApprovalServiceMock.Setup(a => a.GetApprovalsByCostStageRevisionId(It.IsAny <Guid>(), true)).ReturnsAsync(approvals);

            var pgPaymentDetails = new PgPaymentDetails
            {
                PoNumber = poNumber
            };

            CostStageServiceMock.Setup(cssm => cssm.GetPreviousCostStage(latestStageId)).Returns(Task.FromResult(previousStage));
            CostStageRevisionServiceMock.Setup(csrsm => csrsm.GetLatestRevision(previousStageId)).Returns(Task.FromResult(previousRevision));
            CustomObjectDataServiceMock
            .Setup(codsm => codsm.GetCustomData <PgPaymentDetails>(latestRevisionId, CustomObjectDataKeys.PgPaymentDetails))
            .Returns(Task.FromResult(pgPaymentDetails));
            CustomObjectDataServiceMock
            .Setup(codsm => codsm.GetCustomData <PgPaymentDetails>(previousRevisionId, CustomObjectDataKeys.PgPaymentDetails))
            .Returns(Task.FromResult(pgPaymentDetails));
        }
Example #14
0
        public async Task <ActionResult <Approval> > CreateApproval([FromBody] Approval approval) //we are expecting http request and inside of request we expect product body and .net core will auto convert jason to object
        {
            await _repository.Create(approval);

            return(CreatedAtRoute("GetApproval", new { id = approval.Id }, approval));
        }
Example #15
0
        public void Process(ActivityModel activity, Approval approval, string processor, IWorkflowAuthority auth)
        {
            if (approval == null)
            {
                throw new Exception("审批意见不能为null");
            }
            if (string.IsNullOrEmpty(approval.Remark))
            {
                throw new Exception("审批意见不能为空");
            }
            //已经处理过就不能再处理
            if (activity.Value.Status == (int)ActivityProcessStatus.Processed)
            {
                return;
            }
            ISqlMapper  mapper      = MapperHelper.GetMapper();
            ActivityDao activitydao = new ActivityDao(mapper);
            TaskDao     taskdao     = new TaskDao(mapper);

            activity.Value.Status      = (int)ActivityProcessStatus.Processed;
            activity.Value.ProcessTime = DateTime.Now;
            activity.Value.LastUpdator = processor;
            //新增审批意见
            if (approval != null)
            {
                ApprovalDao ad = new ApprovalDao(mapper);
                approval.Creator    = processor;
                approval.ActivityID = activity.Value.ID;
                approval.WorkflowID = activity.Value.WorkflowID;
                ad.Add(approval);
                activity.OwnerWorkflow.Approval.Add(approval);
            }
            //设置当前活动点状态
            activitydao.Update(new ActivityUpdateForm
            {
                Entity = new Activity {
                    Status = activity.Value.Status, ProcessTime = activity.Value.ProcessTime, LastUpdator = activity.Value.LastUpdator
                },
                ActivityQueryForm = new ActivityQueryForm {
                    ID = activity.Value.ID
                }
            });
            //处理任务
            var task = activity.GetUserProcessingTask(processor);

            if (task == null)
            {
                throw new Exception("环节中没有你的任务,无法进行审批操作");
            }
            task.ProcessTime = DateTime.Now;
            task.Status      = (int)TaskProcessStatus.Processed;
            task.LastUpdator = processor;
            taskdao.Update(new TaskUpdateForm
            {
                Entity = new Task {
                    ProcessTime = DateTime.Now, Status = task.Status, LastUpdator = task.LastUpdator
                },
                TaskQueryForm = new TaskQueryForm {
                    ID = task.ID
                },
            });
            //设置下个活动点的状态
            if (activity.Children.Count > 0)
            {
                foreach (var next in activity.Children)
                {
                    string nextactivityid    = next.Value.ID;
                    var    nextActivityModel = next as ActivityModel;
                    nextActivityModel.Value.Status      = (int)ActivityProcessStatus.Processing;
                    nextActivityModel.Value.LastUpdator = processor;
                    activitydao.Update(new ActivityUpdateForm
                    {
                        Entity = new Activity {
                            Status = nextActivityModel.Value.Status, LastUpdator = nextActivityModel.Value.LastUpdator
                        },
                        ActivityQueryForm = new ActivityQueryForm {
                            ID = nextactivityid
                        },
                    });

                    List <string> useridList = auth.GetUserIDList(nextActivityModel.Auth);
                    //新增下个活动点的任务
                    var tasklist = nextActivityModel.GetTask(processor, useridList);
                    foreach (var t in tasklist)
                    {
                        taskdao.Add(t);
                        nextActivityModel.Tasks.Add(t);
                    }
                }
            }
        }
        public void SaveDocument()
        {
            newCostManagementProcessModel.CostManagementProcess = Cost_Management_Process_tbx.Text;

            List <Information> informations = new List <Information>();
            Information        information  = new Information();
            var DocumentID    = Document_Information_dgv.Rows[0].Cells[1].Value.ToString();
            var DocumentOwner = Document_Information_dgv.Rows[1].Cells[1].Value.ToString();
            var IssueDate     = Document_Information_dgv.Rows[2].Cells[1].Value.ToString();
            var LastSavedDate = Document_Information_dgv.Rows[3].Cells[1].Value.ToString();
            var FileName      = Document_Information_dgv.Rows[4].Cells[1].Value.ToString();

            information.DocumentID    = DocumentID;
            information.DocumentOwner = DocumentOwner;
            information.IssueDate     = IssueDate;
            information.LastSavedDate = LastSavedDate;
            information.FileName      = FileName;
            newCostManagementProcessModel.Information = information;

            List <History> histories = new List <History>();
            int            Document_HistoryRowCount = Document_History_dgv.RowCount;

            for (int i = 0; i < Document_HistoryRowCount - 1; i++)
            {
                History history = new History();
                var     Version = Document_History_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var     IsDate  = Document_History_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var     Changes = Document_History_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                history.Version   = Version;
                history.IssueDate = IsDate;
                history.Changes   = Changes;
                histories.Add(history);
            }
            newCostManagementProcessModel.Histories = histories;

            List <Approval> approvals     = new List <Approval>();
            int             approvalCount = Document_Approvals_dgv.RowCount;

            for (int i = 0; i < approvalCount - 1; i++)
            {
                Approval approval  = new Approval();
                var      Role      = Document_Approvals_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var      Name      = Document_Approvals_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var      Signature = Document_Approvals_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                var      Date      = Document_Approvals_dgv.Rows[i].Cells[3].Value?.ToString() ?? "";

                approval.Name      = Name;
                approval.Role      = Role;
                approval.Signature = Signature;
                approval.Date      = Date;

                approvals.Add(approval);
            }
            newCostManagementProcessModel.Approvals = approvals;

            newCostManagementProcessModel.Overview          = Overview_tbx.Text;
            newCostManagementProcessModel.DocumentExpense   = Document_Expense_tbx.Text;
            newCostManagementProcessModel.ApproveExpense    = Approve_Expense_tbx.Text;
            newCostManagementProcessModel.UpdateProjectPlan = Update_Project_Plan_tbx.Text;
            newCostManagementProcessModel.TeamMembers       = Team_Member_tbx.Text;
            newCostManagementProcessModel.ProjectAdmin      = Project_Administrator_tbx.Text;
            newCostManagementProcessModel.ProjectManager    = Project_Manager_tbx.Text;

            newCostManagementProcessModel.ExpenseForm     = Expense_Form_tbx.Text;
            newCostManagementProcessModel.ExpenseRegister = Expense_Register_tbx.Text;

            List <VersionControl <CostManagementProcessModel> .DocumentModel> documentModels = versionControl.DocumentModels;

            //MessageBox.Show(JsonConvert.SerializeObject(newCostManagementProcessModel), "save", MessageBoxButtons.OK);


            if (!versionControl.isEqual(currentCostManagementProcessModel, newCostManagementProcessModel))
            {
                VersionControl <CostManagementProcessModel> .DocumentModel documentModel = new VersionControl <CostManagementProcessModel> .DocumentModel(newCostManagementProcessModel, DateTime.Now, VersionControl <CostManagementProcessModel> .generateID());

                documentModels.Add(documentModel);

                versionControl.DocumentModels = documentModels;

                string json = JsonConvert.SerializeObject(versionControl);
                currentCostManagementProcessModel = JsonConvert.DeserializeObject <CostManagementProcessModel>(JsonConvert.SerializeObject(newCostManagementProcessModel));
                JsonHelper.saveDocument(json, Settings.Default.ProjectID, "CostManagementProcess");
                MessageBox.Show("Risk plan saved successfully", "save", MessageBoxButtons.OK);
            }
        }
        public void TestOrderEditedShouldCreateEmailQueueWithUserOrEmail()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("hsimpson");
            SetupUsers();
            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);
            var approval = new Approval();
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver);
            approval.Completed = true;
            new FakeEmailPreferences(0, EmailPreferenceRepository);
            #endregion Arrange

            #region Act
            NotificationService.OrderEdited(order, UserRepository.GetNullableById("hsimpson"));
            #endregion Act

            #region Assert
            Assert.AreEqual(1, order.EmailQueuesV2.Count);
            Assert.IsTrue(order.EmailQueuesV2[0].User != null || !string.IsNullOrWhiteSpace(order.EmailQueuesV2[0].Email));
            #endregion Assert
        }
Example #18
0
        protected void SaveNewRecord(object sender, DirectEventArgs e)
        {
            //Getting the id to check if it is an Add or an edit as they are managed within the same form.


            string   obj = e.ExtraParams["values"];
            Approval b   = JsonConvert.DeserializeObject <Approval>(obj);

            string id = e.ExtraParams["id"];

            if (string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(apId.Text))
            {
                id         = apId.Text;
                b.recordId = id;
            }

            // Define the object to add or edit as null

            if (string.IsNullOrEmpty(id))
            {
                try
                {
                    //New Mode
                    //Step 1 : Fill The object and insert in the store
                    PostRequest <Approval> request = new PostRequest <Approval>();

                    request.entity = b;
                    PostResponse <Approval> r = _companyStructureService.ChildAddOrUpdate <Approval>(request);


                    //check if the insert failed
                    if (!r.Success)//it maybe be another condition
                    {
                        //Show an error saving...
                        X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                        Common.errorMessage(r);
                        return;
                    }
                    else
                    {
                        b.recordId = r.recordId;
                        apId.Text  = b.recordId;
                        //Add this record to the store
                        Store1.Reload();

                        //Display successful notification
                        Notification.Show(new NotificationConfig
                        {
                            Title = Resources.Common.Notification,
                            Icon  = Icon.Information,
                            Html  = Resources.Common.RecordSavingSucc
                        });

                        //this.EditRecordWindow.Close();
                        RowSelectionModel sm = this.GridPanel1.GetSelectionModel() as RowSelectionModel;
                        sm.DeselectAll();
                        sm.Select(b.recordId.ToString());
                        //ApprovelDepartmentsGrid.Disabled = false;
                    }
                }
                catch (Exception ex)
                {
                    //Error exception displaying a messsage box
                    X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                    X.Msg.Alert(Resources.Common.Error, Resources.Common.ErrorSavingRecord).Show();
                }
            }
            else
            {
                //Update Mode

                try
                {
                    //getting the id of the record
                    PostRequest <Approval> request = new PostRequest <Approval>();
                    request.entity = b;
                    PostResponse <Approval> r = _companyStructureService.ChildAddOrUpdate <Approval>(request);                      //Step 1 Selecting the object or building up the object for update purpose

                    //Step 2 : saving to store

                    //Step 3 :  Check if request fails
                    if (!r.Success)//it maybe another check
                    {
                        X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                        Common.errorMessage(r);
                        return;
                    }
                    else
                    {
                        //ModelProxy record = this.Store1.GetById(id);
                        //BasicInfoTab.UpdateRecord(record);
                        //record.Commit();
                        Store1.Reload();
                        Notification.Show(new NotificationConfig
                        {
                            Title = Resources.Common.Notification,
                            Icon  = Icon.Information,
                            Html  = Resources.Common.RecordUpdatedSucc
                        });
                        this.EditRecordWindow.Close();
                    }
                }
                catch (Exception ex)
                {
                    X.MessageBox.ButtonText.Ok = Resources.Common.Ok;
                    X.Msg.Alert(Resources.Common.Error, Resources.Common.ErrorUpdatingRecord).Show();
                }
            }
        }
 public static Approval CreateApproval(global::System.DateTimeOffset notBefore, global::System.DateTimeOffset expiresAt, long ID, global::System.Guid tid, string name, long createdById, long modifiedById, global::System.DateTimeOffset created, global::System.DateTimeOffset modified)
 {
     Approval approval = new Approval();
     approval.NotBefore = notBefore;
     approval.ExpiresAt = expiresAt;
     approval.Id = ID;
     approval.Tid = tid;
     approval.Name = name;
     approval.CreatedById = createdById;
     approval.ModifiedById = modifiedById;
     approval.Created = created;
     approval.Modified = modified;
     return approval;
 }
Example #20
0
        public void Process(ActivityModel activity, Approval approval, string processor, IWorkflowAuthority auth)
        {
            if (approval == null)
            {
                throw new Exception("审批意见不能为null");
            }
            if (string.IsNullOrEmpty(approval.Remark))
            {
                throw new Exception("审批意见不能为空");
            }
            //已经处理过就不能再处理
            if (activity.Value.Status == (int)ActivityProcessStatus.Processed)
            {
                return;
            }
            ISqlMapper  mapper      = MapperHelper.GetMapper();
            ActivityDao activitydao = new ActivityDao(mapper);
            TaskDao     taskdao     = new TaskDao(mapper);

            activity.Value.Status      = (int)ActivityProcessStatus.Started;
            activity.Value.ProcessTime = DateTime.Now;
            activity.Value.LastUpdator = processor;

            //设置当前活动点状态
            activitydao.Update(new ActivityUpdateForm
            {
                Entity = new Activity {
                    Status = activity.Value.Status, ProcessTime = activity.Value.ProcessTime, LastUpdator = activity.Value.LastUpdator
                },
                ActivityQueryForm = new ActivityQueryForm {
                    ID = activity.Value.ID
                }
            });
            //新增审批意见
            if (approval != null)
            {
                ApprovalDao ad = new ApprovalDao(mapper);
                approval.Creator    = processor;
                approval.ActivityID = activity.Value.ID;
                approval.WorkflowID = activity.Value.WorkflowID;
                ad.Add(approval);
                activity.OwnerWorkflow.Approval.Add(approval);
            }
            //处理当前流程所有任务,设置为已处理
            var task = activity.GetUserProcessingTask(processor);

            if (task == null)
            {
                throw new Exception("环节中没有你的任务,无法进行审批操作");
            }
            task.ProcessTime = DateTime.Now;
            task.Status      = (int)TaskProcessStatus.Processed;
            task.LastUpdator = processor;
            taskdao.Update(new TaskUpdateForm
            {
                Entity = new Task {
                    ProcessTime = task.ProcessTime, Status = task.Status, LastUpdator = task.LastUpdator
                },
                TaskQueryForm = new TaskQueryForm {
                    ActivityID = task.ActivityID
                },
            });
            //把所有活动点的状态清空
            activity.OwnerWorkflow.Root.GetList().ForEach(t => t.Value.Status = activity.Value.Status);
            activitydao.Update(new ActivityUpdateForm
            {
                Entity = new Activity {
                    Status = activity.Value.Status
                },
                ActivityQueryForm = new ActivityQueryForm {
                    WorkflowID = activity.Value.WorkflowID
                }
            });
            activity.OwnerWorkflow.Root.Value.Status = (int)ActivityProcessStatus.Processing;
            var root = activity.OwnerWorkflow.Root;

            activitydao.Update(new ActivityUpdateForm
            {
                Entity = new Activity {
                    Status = root.Value.Status
                },
                ActivityQueryForm = new ActivityQueryForm {
                    ID = root.Value.ID
                },
            });
            //生成退回任务
            Task roottask = new Task
            {
                ActivityID = root.Value.ID,
                Name       = root.Value.Name,
                Title      = root.Value.Title + "(退回)",
                UserID     = activity.OwnerWorkflow.Value.Creator,
                WorkflowID = activity.OwnerWorkflow.Value.ID,
                Status     = (int)TaskProcessStatus.Started,
                Creator    = processor,
            };

            root.Tasks.Add(roottask);
            taskdao.Add(roottask);
        }
Example #21
0
        public void Seed()
        {
            if (this._context.LogEntries.Count() <= 0)
            {
                for (int i = 0; i < logEntries.Length; i++)
                {
                    var entryInfo = SplitValue(logEntries[i]);
                    var entry     = new LogEntry
                    {
                        UserName           = entryInfo[0],
                        ComputerName       = entryInfo[1],
                        Ip                 = entryInfo[2],
                        ProgramDescription = entryInfo[3],
                        RapportDescription = entryInfo[4],
                        TimeStamp          = DateTime.Today,
                        Note               = null,
                        EditedBy           = null
                    };

                    this._context.LogEntries.Add(entry);
                }
            }

            if (this._context.Approvals.Count() <= 0)
            {
                for (int i = 0; i < approvals.Length; i++)
                {
                    var entryInfo = SplitValue(approvals[i]);
                    var entry     = new Approval
                    {
                        UserName  = entryInfo[0],
                        Reasoning = entryInfo[1],
                        TimeStamp = DateTime.Now,
                        Approver  = entryInfo[2]
                    };

                    this._context.Approvals.Add(entry);
                    this._context.SaveChanges();

                    var groupEntry = new AssignedUserGroup
                    {
                        ApprovalID = entry.ID,
                        Group      = entryInfo[3]
                    };
                    this._context.AssignedUserGroups.Add(groupEntry);
                    this._context.SaveChanges();
                }
            }

            if (this._context.SoftwareEntries.Count() <= 0)
            {
                for (int i = 0; i < softwareEntries.Length; i++)
                {
                    var entryInfo = SplitValue(softwareEntries[i]);
                    var entry     = new SoftwareEntry
                    {
                        Name      = entryInfo[0],
                        Vendor    = entryInfo[1],
                        Reasoning = entryInfo[2],
                        TimeStamp = DateTime.Now,
                        CreatedBy = entryInfo[3],
                        State     = entryInfo[4]
                    };
                    this._context.SoftwareEntries.Add(entry);
                    this._context.SaveChanges();
                }
            }
        }
Example #22
0
        /// <summary>
        /// Will add the proper approval levels to an order.  If a workgroup account or approver/acctManager is passed in, a split is not possible
        /// </summary>
        /// <param name="order">The order.  If it does not contain splits, you must pass along either workgroupAccount or acctManager</param>
        /// <param name="conditionalApprovalIds">The Ids of required conditional approvals for this order (the ones answered "yes")</param>
        /// <param name="accountId">Optional id of an account to use for routing</param>
        /// <param name="approverId">Optional approver userID</param>
        /// <param name="accountManagerId">AccountManager userID, required if account is not supplied</param>
        public void CreateApprovalsForNewOrder(Order order, int[] conditionalApprovalIds = null, string accountId = null, string approverId = null, string accountManagerId = null)
        {
            var approvalInfo = new ApprovalInfo();

            if (order.Splits.Count() == 1) //Order has one split and can thus optionally not have accounts assigned
            {
                var split = order.Splits.Single();

                Check.Require(!string.IsNullOrWhiteSpace(accountId) || !string.IsNullOrWhiteSpace(accountManagerId),
                          "You must either supply the ID of a valid account or provide the userId for an account manager");

                if (!string.IsNullOrWhiteSpace(accountId)) //if we route by account, use that for info
                {
                    //TODO: move this code to a private methods as very similar code is used elsewhere here.
                    var workgroupAccount =
                        _repositoryFactory.WorkgroupAccountRepository.Queryable.FirstOrDefault(x => x.Account.Id == accountId && x.Workgroup.Id == order.Workgroup.Id);

                    approvalInfo.AccountId = accountId;
                    approvalInfo.IsExternal = (workgroupAccount == null); //if we can't find the account in the workgroup it is external

                    if (workgroupAccount != null) //route to the people contained in the workgroup account info
                    {
                        approvalInfo.Approver = workgroupAccount.Approver;
                        approvalInfo.AcctManager = workgroupAccount.AccountManager;
                        approvalInfo.Purchaser = workgroupAccount.Purchaser;
                    }
                    else //account is not in the workgroup, even if we don't find the account, we will still use it
                    {
                        var externalAccount = _repositoryFactory.AccountRepository.GetNullableById(accountId);

                        approvalInfo.Approver = null;
                        approvalInfo.AcctManager = externalAccount != null
                                                       ? _securityService.GetUser(externalAccount.AccountManagerId)
                                                       : null;
                        approvalInfo.Purchaser = null;
                    }

                    split.Account = accountId; //Assign the account to the split
                }
                else //else stick with user provided values
                {
                    approvalInfo.Approver = string.IsNullOrWhiteSpace(approverId) ? null : _repositoryFactory.UserRepository.GetById(approverId);
                    approvalInfo.AcctManager = GetManager(accountManagerId);
                }

                AddApprovalSteps(order, approvalInfo, split);
            }
            else //else order has multiple splits and each one needs an account
            {
                foreach (var split in order.Splits)
                {
                    //Try to find the account in the workgroup so we can route it by users
                    var workgroupAccount = _repositoryFactory.WorkgroupAccountRepository.Queryable.FirstOrDefault(x => x.Account.Id == split.Account && x.Workgroup.Id == order.Workgroup.Id);

                    approvalInfo.AccountId = split.Account;
                    approvalInfo.IsExternal = workgroupAccount == null; //if we can't find the account in the workgroup it is external

                    if (workgroupAccount != null) //route to the people contained in the workgroup account info
                    {
                        approvalInfo.Approver = workgroupAccount.Approver;
                        approvalInfo.AcctManager = workgroupAccount.AccountManager;
                        approvalInfo.Purchaser = workgroupAccount.Purchaser;
                    }
                    else
                    { //account is not in the workgroup
                        var externalAccount = _repositoryFactory.AccountRepository.GetNullableById(split.Account);

                        approvalInfo.Approver = null;
                        approvalInfo.AcctManager = externalAccount != null
                                                       ? _securityService.GetUser(externalAccount.AccountManagerId)
                                                       : null;
                        approvalInfo.Purchaser = null;
                    }

                    AddApprovalSteps(order, approvalInfo, split);
                }
            }

            //If we were passed conditional approval info, go ahead and add them
            if (conditionalApprovalIds != null && conditionalApprovalIds.Any())
            {
                foreach (var conditionalApprovalId in conditionalApprovalIds)
                {
                    var id = conditionalApprovalId;
                    var approverIds =
                        _repositoryFactory.ConditionalApprovalRepository.Queryable.Where(x => x.Id == id)
                            .Select(x =>
                                    new
                                        {
                                            primaryApproverId = x.PrimaryApprover.Id,
                                            secondaryApproverId = x.SecondaryApprover != null ? x.SecondaryApprover.Id : null
                                        }
                            ).Single();

                    var newApproval = new Approval //Add a new 'approver' level approval
                                          {
                                              Completed = false,
                                              User = _repositoryFactory.UserRepository.GetById(approverIds.primaryApproverId),
                                              SecondaryUser = approverIds.secondaryApproverId == null ? null : _repositoryFactory.UserRepository.GetById(approverIds.secondaryApproverId),
                                              StatusCode =
                                                  _repositoryFactory.OrderStatusCodeRepository.Queryable.Single(x => x.Id == OrderStatusCode.Codes.ConditionalApprover)
                                          };

                    order.AddApproval(newApproval);//Add directly to the order since conditional approvals never go against splits
                }
            }
            if (order.Workgroup.RequireApproval && !order.Approvals.Any(a => a.StatusCode.Id == OrderStatusCode.Codes.Approver))
            {
                // Ok, we don't have any approvals (because an external account was used), so we want to add one.
                var missingApproval = new Approval
                                          {
                                              Completed = false,
                                              User = null,
                                              SecondaryUser = null,
                                              StatusCode =
                                                  _repositoryFactory.OrderStatusCodeRepository.Queryable.Single(
                                                      x => x.Id == OrderStatusCode.Codes.Approver)
                                          };
                order.AddApproval(missingApproval);
            }

            order.StatusCode = GetCurrentOrderStatus(order);

            _eventService.OrderCreated(order); //Creating approvals means the order is being created
        }
        public override BaseResource[] SynchronizeIds(BaseResource[] source, Uri subjectUri, BaseResource[] target)
        {
            UkgapEPetition ePetition = source.OfType <UkgapEPetition>().SingleOrDefault();

            ePetition.Id = subjectUri;

            GovernmentResponse governmentResponse = target.OfType <GovernmentResponse>().SingleOrDefault();

            if (governmentResponse != null)
            {
                ePetition.EPetitionHasGovernmentResponse.SingleOrDefault().Id = governmentResponse.Id;
            }
            Parliament.Model.Debate debate = target.OfType <Parliament.Model.Debate>().SingleOrDefault();
            if (debate != null)
            {
                ePetition.EPetitionHasDebate.SingleOrDefault().Id = debate.Id;
            }
            IEnumerable <Approval> approvals          = target.OfType <Approval>();
            List <Approval>        ePetitionApprovals = source.OfType <Approval>().ToList();

            foreach (Approval approval in approvals)
            {
                Approval foundModeration = ePetitionApprovals
                                           .SingleOrDefault(m => m.ApprovedAt == approval.ApprovedAt);
                if (foundModeration != null)
                {
                    foundModeration.Id = approval.Id;
                }
                else
                {
                    ePetitionApprovals.Add(approval);
                }
            }
            foreach (Approval approval in ePetitionApprovals)
            {
                approval.ApprovalHasApprovedEPetition = new ApprovedEPetition[]
                {
                    new ApprovedEPetition()
                    {
                        Id = subjectUri
                    }
                }
            }
            ;

            IEnumerable <Parliament.Model.Rejection> rejects             = target.OfType <Parliament.Model.Rejection>();
            List <Parliament.Model.Rejection>        ePetitionRejections = source.OfType <Parliament.Model.Rejection>().ToList();

            foreach (Parliament.Model.Rejection rejection in rejects)
            {
                Parliament.Model.Rejection foundModeration = ePetitionRejections
                                                             .SingleOrDefault(m => m.RejectedAt == rejection.RejectedAt);
                if (foundModeration != null)
                {
                    foundModeration.Id = rejection.Id;
                }
                else
                {
                    ePetitionRejections.Add(rejection);
                }
            }
            foreach (Parliament.Model.Rejection rejection in ePetitionRejections)
            {
                rejection.RejectionHasRejectedEPetition = new RejectedEPetition[]
                {
                    new RejectedEPetition()
                    {
                        Id = subjectUri
                    }
                }
            }
            ;

            IEnumerable <ThresholdAttainment> thresholdAttainments = target.OfType <ThresholdAttainment>();

            foreach (ThresholdAttainment thresholdAttainment in thresholdAttainments)
            {
                ThresholdAttainment foundThresholdAttainment = ePetition.EPetitionHasThresholdAttainment.SingleOrDefault(t => t.ThresholdAttainmentAt == thresholdAttainment.ThresholdAttainmentAt);
                if (foundThresholdAttainment != null)
                {
                    foundThresholdAttainment.Id = thresholdAttainment.Id;
                }
            }
            IEnumerable <LocatedSignatureCount> signatures = target.OfType <LocatedSignatureCount>();

            foreach (LocatedSignatureCount signature in signatures)
            {
                LocatedSignatureCount foundLocatedSignatureCount = ePetition.EPetitionHasLocatedSignatureCount
                                                                   .SingleOrDefault(s => s.LocatedSignatureCountHasPlace.Id == signature.LocatedSignatureCountHasPlace.Id);
                if (foundLocatedSignatureCount != null)
                {
                    foundLocatedSignatureCount.Id = signature.Id;
                    if (foundLocatedSignatureCount.SignatureCount.SingleOrDefault() == signature.SignatureCount.SingleOrDefault())
                    {
                        foundLocatedSignatureCount.SignatureCountRetrievedAt = signature.SignatureCountRetrievedAt;
                    }
                }
            }
            foreach (LocatedSignatureCount signature in ePetition.EPetitionHasLocatedSignatureCount.Where(s => s.Id == null))
            {
                signature.Id = GenerateNewId();
            }

            return(ePetitionApprovals.AsEnumerable <BaseResource>().Concat(ePetitionRejections).Concat(ePetition.AsEnumerable()).ToArray());
        }
Example #24
0
        private void saveDocument()
        {
            newRiskPlanModel.ProjectName = Project_Name_tbx.Text;

            List <Information> informations = new List <Information>();
            Information        information  = new Information();
            var DocumentID    = Document_Information_dgv.Rows[0].Cells[1].Value.ToString();
            var DocumentOwner = Document_Information_dgv.Rows[1].Cells[1].Value.ToString();
            var IssueDate     = Document_Information_dgv.Rows[2].Cells[1].Value.ToString();
            var LastSavedDate = Document_Information_dgv.Rows[3].Cells[1].Value.ToString();
            var FileName      = Document_Information_dgv.Rows[4].Cells[1].Value.ToString();

            information.DocumentID       = DocumentID;
            information.DocumentOwner    = DocumentOwner;
            information.IssueDate        = IssueDate;
            information.LastSavedDate    = LastSavedDate;
            information.FileName         = FileName;
            newRiskPlanModel.Information = information;

            List <History> histories = new List <History>();
            int            Document_HistoryRowCount = Document_History_dgv.RowCount;

            for (int i = 0; i < Document_HistoryRowCount - 1; i++)
            {
                History history = new History();
                var     Version = Document_History_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var     IsDate  = Document_History_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var     Changes = Document_History_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                history.Version   = Version;
                history.IssueDate = IsDate;
                history.Changes   = Changes;
                histories.Add(history);
            }
            newRiskPlanModel.Histories = histories;

            List <Approval> approvals     = new List <Approval>();
            int             approvalCount = Document_Approvals_dgv.RowCount;

            for (int i = 0; i < Document_HistoryRowCount - 1; i++)
            {
                Approval approval  = new Approval();
                var      Role      = Document_Approvals_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var      Name      = Document_Approvals_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var      Signature = Document_Approvals_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                var      Date      = Document_Approvals_dgv.Rows[i].Cells[3].Value?.ToString() ?? "";

                approval.Name      = Name;
                approval.Role      = Role;
                approval.Signature = Signature;
                approval.Date      = Date;

                approvals.Add(approval);
            }
            newRiskPlanModel.Approvals = approvals;

            newRiskPlanModel.Categories = Categories_tbx.Text;

            List <Risk> risks     = new List <Risk>();
            int         riskCount = Risks_dgv.RowCount;

            for (int i = 0; i < riskCount - 1; i++)
            {
                Risk risk            = new Risk();
                var  RiskCategory    = Risks_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var  RiskDescription = Risks_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var  ID = Risks_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";

                risk.RiskCategory    = RiskCategory;
                risk.RiskDescription = RiskDescription;
                risk.ID = ID;

                risks.Add(risk);
            }
            newRiskPlanModel.Risks = risks;

            List <Likelihood> likelihoods = new List <Likelihood>();
            int LikelihoodrowCount        = Likelihood_dgv.RowCount;

            for (int i = 0; i < LikelihoodrowCount - 1; i++)
            {
                Likelihood likelihood  = new Likelihood();
                var        Title       = Likelihood_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var        Score       = Likelihood_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var        Description = Likelihood_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                likelihood.Title       = Title;
                likelihood.Score       = Score;
                likelihood.Description = Description;

                likelihoods.Add(likelihood);
            }
            newRiskPlanModel.Likelihoods = likelihoods;

            List <Impact> impacts        = new List <Impact>();
            int           impactrowCount = Impact_dgv.RowCount;

            for (int i = 0; i < impactrowCount - 1; i++)
            {
                Impact impact      = new Impact();
                var    Title       = Impact_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var    Score       = Impact_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var    Description = Impact_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";

                impact.Title       = Title;
                impact.Score       = Score;
                impact.Description = Description;

                impacts.Add(impact);
            }
            newRiskPlanModel.Impacts = impacts;

            List <Priority> priorities       = new List <Priority>();
            int             PriorityrowCount = Priority_dgv.RowCount;

            for (int i = 0; i < PriorityrowCount - 1; i++)
            {
                Priority priority        = new Priority();
                var      ID              = Priority_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var      LikelihoodScore = Priority_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var      ImpactScore     = Priority_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                var      PriorityScore   = Priority_dgv.Rows[i].Cells[3].Value?.ToString() ?? "";
                var      PriorityRating  = Priority_dgv.Rows[i].Cells[4].Value?.ToString() ?? "";


                priority.ID = ID;
                priority.LikelihoodScore = LikelihoodScore;
                priority.ImpactScore     = ImpactScore;
                priority.PriorityScore   = PriorityScore;
                priority.PriorityRating  = PriorityRating;

                priorities.Add(priority);
            }
            newRiskPlanModel.Priorities = priorities;

            List <Schedule> schedules        = new List <Schedule>();
            int             SchedulerowCount = Schedule_dgv.RowCount;

            for (int i = 0; i < SchedulerowCount - 1; i++)
            {
                Schedule schedule            = new Schedule();
                var      Rating              = Schedule_dgv.Rows[i].Cells[0].Value?.ToString() ?? "";
                var      ID                  = Schedule_dgv.Rows[i].Cells[1].Value?.ToString() ?? "";
                var      PrevalantiveActions = Schedule_dgv.Rows[i].Cells[2].Value?.ToString() ?? "";
                var      ActionResource1     = Schedule_dgv.Rows[i].Cells[3].Value?.ToString() ?? "";
                var      ActionDate1         = Schedule_dgv.Rows[i].Cells[4].Value?.ToString() ?? "";
                var      ContingentActions   = Schedule_dgv.Rows[i].Cells[5].Value?.ToString() ?? "";
                var      ActionResource2     = Schedule_dgv.Rows[i].Cells[6].Value?.ToString() ?? "";
                var      ActionDate2         = Schedule_dgv.Rows[i].Cells[7].Value?.ToString() ?? "";

                schedule.Rating = Rating;
                schedule.ID     = ID;
                schedule.PrevalantiveActions = PrevalantiveActions;
                schedule.ActionResource1     = ActionResource1;
                schedule.ActionDate1         = ActionDate1;
                schedule.ContingentActions   = ContingentActions;
                schedule.ActionResource2     = ActionResource2;
                schedule.ActionDate2         = ActionDate2;

                schedules.Add(schedule);
            }
            newRiskPlanModel.Schedules = schedules;

            newRiskPlanModel.Assumptions = Assumptions_tbx.Text;
            newRiskPlanModel.Constraints = Constraints_tbx.Text;
            newRiskPlanModel.Activities  = Activities_tbx.Text;
            newRiskPlanModel.Roles       = Roles_tbx.Text;
            newRiskPlanModel.Documents   = Documents_tbx.Text;
            newRiskPlanModel.Appendix    = Appendix_tbx.Text;

            List <VersionControl <RiskPlanModel> .DocumentModel> documentModels = versionControl.DocumentModels;

            //MessageBox.Show(JsonConvert.SerializeObject(newRiskPlanModel), "save", MessageBoxButtons.OK);

            if (!versionControl.isEqual(currentRiskPlanModel, newRiskPlanModel))
            {
                VersionControl <RiskPlanModel> .DocumentModel documentModel = new VersionControl <RiskPlanModel> .DocumentModel(newRiskPlanModel, DateTime.Now, VersionControl <RiskPlanModel> .generateID());

                documentModels.Add(documentModel);

                versionControl.DocumentModels = documentModels;

                string json = JsonConvert.SerializeObject(versionControl);
                currentRiskPlanModel = JsonConvert.DeserializeObject <RiskPlanModel>(JsonConvert.SerializeObject(newRiskPlanModel));
                JsonHelper.saveDocument(json, Settings.Default.ProjectID, "RiskPlan");
                MessageBox.Show("Risk plan saved successfully", "save", MessageBoxButtons.OK);
            }
        }
        public void TestOrderApprovedWhenApprovedFromAccManager04()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("flanders");
            SetupUsers();
            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);
            var approval = new Approval();
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.AccountManager);
            approval.Completed  = true;


            order.Approvals = ApprovalRepository.Queryable.Where(a => a.Order.Id == order.Id).ToList();
            foreach (var approval1 in order.Approvals)
            {
                if (approval1.StatusCode.Id == OrderStatusCode.Codes.AccountManager)
                {
                    approval1.Completed = true;
                }
            }
            order.GenerateRequestNumber();

            var emailPrefs = new List <EmailPreferences>();
            emailPrefs.Add(new EmailPreferences("awong"));
            emailPrefs[0].NotificationType     = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[0].PurchaserOrderArrive = false;

            emailPrefs.Add(new EmailPreferences("hsimpson"));
            emailPrefs[1].NotificationType = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[1].ApproverAccountManagerApproved = false;

            emailPrefs.Add(new EmailPreferences("bender"));
            emailPrefs[2].NotificationType = EmailPreferences.NotificationTypes.Daily;
            emailPrefs[2].RequesterAccountManagerApproved = false;


            new FakeEmailPreferences(0, EmailPreferenceRepository, emailPrefs, true);
            #endregion Arrange

            #region Act
            NotificationService.OrderApproved(order, approval);
            #endregion Act

            #region Assert
            Assert.AreEqual(0, order.EmailQueuesV2.Count);
            //Assert.AreEqual(DateTime.UtcNow.ToPacificTime().Date, order.EmailQueuesV2[0].DateTimeCreated.Date);
            //Assert.IsNull(order.EmailQueuesV2[0].DateTimeSent);
            //Assert.AreEqual(EmailPreferences.NotificationTypes.PerEvent, order.EmailQueuesV2[0].NotificationType);
            //Assert.IsTrue(order.EmailQueuesV2[0].Pending);
            //Assert.IsNull(order.EmailQueuesV2[0].Status);
            //Assert.AreEqual(string.Format("Order request {0} has been approved by Ned Flanders at Account Manager review.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[0].Text);
            //Assert.AreEqual("bender", order.EmailQueuesV2[0].User.Id);

            //Assert.AreEqual(string.Format("Order request {0} has been approved by Ned Flanders at Account Manager review.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[1].Text);
            //Assert.AreEqual("hsimpson", order.EmailQueuesV2[1].User.Id);

            //Assert.AreEqual(string.Format("Order request {0} has arrived at your level (Purchaser) for review from Ned Flanders.", "#testOrg-FT1P9YR"), order.EmailQueuesV2[2].Text);
            //Assert.AreEqual("awong", order.EmailQueuesV2[2].User.Id);

            #endregion Assert
        }
Example #26
0
        public void OrderApproved(Order order, Approval approval)
        {
            var queues = new List<EmailQueueV2>();

            // go through all the tracking history
            foreach (var appr in order.OrderTrackings.Where(a => a.StatusCode.Level < approval.StatusCode.Level).Select(a => new {User = a.User, StatusCode = a.StatusCode}).Distinct())
            {
                var user = appr.User;
                var preference = GetEmailPreferences(user.Id);

                if (IsMailRequested(preference, appr.StatusCode, approval.StatusCode, EventCode.Approval))
                {
                    var currentUser = _userRepository.GetNullableById(_userIdentity.Current);
                    //var emailQueue = new EmailQueue(order, preference.NotificationType, string.Format(ApprovalMessage, GenerateLink(_serverLink.Address, order.OrderRequestNumber()), order.Vendor == null ? "Unspecified Vendor" : order.Vendor.Name, currentUser.FullName, approval.StatusCode.Name), user);
                    var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Approved", string.Format("By {0} at {1} review.", currentUser.FullName, approval.StatusCode.Name), user);
                    AddToQueue(queues, emailQueue2);
                }

            }

            AddQueuesToOrder(order, queues);

            // is the current level complete?
            if (!order.Approvals.Where(a => a.StatusCode.Level == order.StatusCode.Level && !a.Completed).Any())
            {
                // look forward to the next level
                var level = order.StatusCode.Level + 1;

                ProcessArrival(order, approval, level);
            }
        }
 public void Update(int id, Approval approval)
 {
     _context.A.Update(approval);
     _context.SaveChanges();
 }
Example #28
0
        private void ProcessApprovalsEmailQueue(Order order, Approval approval, List<EmailQueueV2> queues, User currentUser, IEnumerable<Approval> aps, bool assigned = false)
        {
            foreach (var ap in aps)
            {
                // load the user and information
                var user = ap.User;

                var preference = GetEmailPreferences(user.Id);

                if (IsMailRequested(preference, ap.StatusCode, approval != null ? approval.StatusCode : null, EventCode.Arrival))
                {
                    var extraInfo = string.Empty;
                    if (preference.ShowAccountInEmail && ap.StatusCode.Id == OrderStatusCode.Codes.AccountManager)
                    {
                        extraInfo = string.Format(" with accounts {0}", order.AccountNumbers);
                    }
                    //var emailQueue = new EmailQueue(order, preference.NotificationType, string.Format(!assigned ? ArrivalMessage : RerouteMessage, GenerateLink(_serverLink.Address, order.OrderRequestNumber()), order.Vendor == null ? "Unspecified Vendor" : order.Vendor.Name, ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.User);
                    if (!assigned)
                    {
                        var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Arrived", string.Format("At your level ({0}) for review from {1}{2}.", ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.User);
                        AddToQueue(queues, emailQueue2);
                    }
                    else
                    {
                        var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Rerouted", string.Format("To you at your level ({0}) for review from {1}{2}.", ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.User);
                        AddToQueue(queues, emailQueue2);
                    }

                }

                if (ap.SecondaryUser != null)
                {
                    if (IsMailRequested(preference, ap.StatusCode, approval != null ? approval.StatusCode : null, EventCode.Arrival))
                    {
                        var extraInfo = string.Empty;
                        if (preference.ShowAccountInEmail && ap.StatusCode.Id == OrderStatusCode.Codes.AccountManager)
                        {
                            extraInfo = string.Format(" with accounts {0}", order.AccountNumbers);
                        }
                        //var emailQueue = new EmailQueue(order, preference.NotificationType, string.Format(!assigned ? ArrivalMessage : RerouteMessage, GenerateLink(_serverLink.Address, order.OrderRequestNumber()), order.Vendor == null ? "Unspecified Vendor" : order.Vendor.Name, ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.SecondaryUser);
                        if (!assigned)
                        {
                            var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Arrived", string.Format("At your level ({0}) for review from {1}{2}.", ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.SecondaryUser);
                            AddToQueue(queues, emailQueue2);
                        }
                        else
                        {
                            var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Rerouted", string.Format("To you at your level ({0}) for review from {1}{2}.", ap.StatusCode.Name, currentUser.FullName, extraInfo), ap.SecondaryUser);
                            AddToQueue(queues, emailQueue2);
                        }
                    }
                }
            }
        }
Example #29
0
        public void TestOrderCreatedProcessArrival7()
        {
            #region Arrange
            UserIdentity.Expect(a => a.Current).Return("bender");
            SetupUsers();
            var order = SetupData1("bender", OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver));
            order.DateCreated = new DateTime(2011, 12, 31, 09, 49, 33);

            var approvals = new List <Approval>();
            CreateApprovals(approvals, OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Approver), order);
            var conditionalApproval = new Approval();
            conditionalApproval.Order = new Order();
            conditionalApproval.Order.SetIdTo(order.Id);
            conditionalApproval.StatusCode    = OrderStatusCodeRepository.GetNullableById(Role.Codes.Approver);
            conditionalApproval.User          = UserRepository.GetNullableById("zoidberg");
            conditionalApproval.SecondaryUser = UserRepository.GetNullableById("zoidberg");
            approvals.Add(conditionalApproval);

            var saveLevel = 0;
            foreach (var approval in approvals)
            {
                if (approval.User != null && approval.User.Id == "hsimpson")
                {
                    saveLevel              = approval.StatusCode.Level;
                    approval.User          = null;
                    approval.SecondaryUser = null;
                }
                order.AddApproval(approval);
            }
            order.Workgroup.Permissions = new List <WorkgroupPermission>();
            var permission = CreateValidEntities.WorkgroupPermission(1);
            permission.User       = new User("Flarg");
            permission.Role       = new Role(OrderStatusCode.Codes.Approver);
            permission.Role.Level = saveLevel;
            order.Workgroup.Permissions.Add(permission);

            permission            = CreateValidEntities.WorkgroupPermission(2);
            permission.User       = new User("Blarg");
            permission.Role       = new Role(OrderStatusCode.Codes.Approver);
            permission.Role.Level = saveLevel;
            order.Workgroup.Permissions.Add(permission);

            order.GenerateRequestNumber();
            new FakeAdminWorkgroups(3, AdminWorkgroupRepository);
            new FakeWorkgroups(3, WorkgroupRepository);
            new FakeEmailPreferences(0, EmailPreferenceRepository);
            #endregion Arrange

            #region Act
            NotificationService.OrderCreated(order);
            #endregion Act

            #region Assert
            Assert.AreEqual(4, order.EmailQueuesV2.Count());
            Assert.AreEqual("Submitted", order.EmailQueuesV2[0].Action);
            Assert.AreEqual(null, order.EmailQueuesV2[0].Details);
            Assert.AreEqual("bender", order.EmailQueuesV2[0].User.Id);
            Assert.AreEqual("Arrived", order.EmailQueuesV2[1].Action);
            Assert.AreEqual("At your level (Approver) for review from Bender Rodriguez.", order.EmailQueuesV2[1].Details);
            Assert.AreEqual("Flarg".ToLower(), order.EmailQueuesV2[1].User.Id);
            Assert.AreEqual("Arrived", order.EmailQueuesV2[2].Action);
            Assert.AreEqual("At your level (Approver) for review from Bender Rodriguez.", order.EmailQueuesV2[2].Details);
            Assert.AreEqual("Blarg".ToLower(), order.EmailQueuesV2[2].User.Id);

            Assert.AreEqual("Arrived", order.EmailQueuesV2[3].Action);
            Assert.AreEqual("At your level (Approver) for review from Bender Rodriguez.", order.EmailQueuesV2[3].Details);
            Assert.AreEqual("zoidberg", order.EmailQueuesV2[3].User.Id);
            #endregion Assert
        }
 public void Add([FromBody] Approval approval)
 {
     _context.A.Add(approval);
     _context.SaveChanges();
 }
        public IActionResult Approve(Guid id, [FromBody] Approval approval)
        {
            logger.LogInformation($"Looking for timesheet {id}");

            Timecard timecard = timesheetRepository.Find(id);

            if (timecard != null)
            {
                if (timecard.Status != TimecardStatus.Submitted)
                {
                    return(StatusCode(409, new InvalidStateError()
                    {
                    }));
                }

                //
                // this is an example of how you might solve the validation
                // requirement. however, this code is so integral to the overall
                // business requirements, and is called so often, that it
                // belongs in a lower-layer service
                //
                var employee = GetEmployee(timecard.Employee);
                if (employee == null)
                {
                    return(StatusCode(400, new NoEmployeeFound()
                    {
                    }));
                }
                if (employee.Status == PersonStatus.PastEmployee)
                {
                    return(StatusCode(400, new EmployeeInactive()
                    {
                    }));
                }

                var manager = GetManagerFor(timecard.Employee);
                if (manager == null)
                {
                    return(StatusCode(400, new NoManagerFound()
                    {
                    }));
                }

                if (CallerIdentity != manager.EmployeeId)
                {
                    return(StatusCode(400, new InvalidIdentityError()
                    {
                    }));
                }

                var transition = new Transition(approval, TimecardStatus.Approved);

                logger.LogInformation($"Adding approval transition {transition}");

                timecard.Transitions.Add(transition);

                timesheetRepository.Update(timecard);

                return(Ok(transition));
            }
            else
            {
                return(NotFound());
            }
        }
Example #32
0
 public void AddAproval(Approval approval)
 {
     this.Session.Save(approval);
 }
    public ContentTypeInformation(SmartFormConfigurationData ContentTypeData)
    {
        this.Name = ContentTypeData.SmartformTitle;
        this.ID = ContentTypeData.Id;

        var typeFields = GetFields(ContentTypeData.FieldList);

        this.Fields = ConvertFieldsToHtml(typeFields);

        this.FieldCount = typeFields.Count();
        this.Volume = GetTypeVolume(ContentTypeData.Id);

        if (this.Volume > 0)
        {
            List<long> folderIds = null;

            decimal tmpVelocity = CalculateVelocity(ContentTypeData.Id, out folderIds);

            List<FolderData> typeFolders = GetFolders(folderIds);
            var folderArray = typeFolders.Select(f => f.NameWithPath).ToArray();
            this.Folders = ConvertFieldsToHtml(folderArray);

            this.Velocity = Math.Round(tmpVelocity, 4);

            this.RequiresApproval = CheckRequiresApproval(typeFolders);
        }
        else
        {
            this.Velocity = 0;
            this.RequiresApproval = Approval.No;
        }
    }
Example #34
0
 public bool DeleteApproval(Approval ToDelete)
 {
     return(DeleteApproval(ToDelete.client_id, ToDelete.resource_owner_id));
 }
Example #35
0
        public ActionResult Edit(EditUser editUser)
        {
            if (ModelState.IsValid)
            {
                editUser.User.IdRoleNavigation = db.EnumRole.Find(editUser.User.IdRole);
                db.Entry(editUser.User).State  = EntityState.Modified;
                if (editUser.User.IdRoleNavigation.Role.Equals("USER"))
                {
                    List <Approval> userApproval = db.Approval.Where(a => a.IdTutor == editUser.User.Id).ToList();
                    foreach (Approval approval in userApproval)
                    {
                        db.Approval.Remove(approval);
                    }

                    List <Event> userEvent = db.Event.Where(a => a.IdTutor == editUser.User.Id).ToList();
                    foreach (Event sscisEvent in userEvent)
                    {
                        int       authorID          = (int)HttpContext.Session.GetInt32("userId");
                        SscisUser currentLoggedUser = db.SscisUser.Find((int)authorID);
                        sscisEvent.IdTutorNavigation  = currentLoggedUser;
                        sscisEvent.CancelationComment = "Tutor fired!";
                        sscisEvent.IsCancelled        = true;
                    }
                }
                else if (editUser.User.IdRoleNavigation.Role.Equals("ADMIN"))
                {
                    List <Approval> userApproval = db.Approval.Where(a => a.IdTutor == editUser.User.Id).ToList();
                    foreach (Approval approval in userApproval)
                    {
                        db.Approval.Remove(approval);
                    }
                    List <EnumSubject> subjects = db.EnumSubject.Where(s => s.IdParent == null && s.Lesson == false).ToList();
                    foreach (EnumSubject subject in subjects)
                    {
                        Approval newApproval = new Approval();
                        newApproval.IdSubject           = subject.Id;
                        newApproval.IdSubjectNavigation = db.EnumSubject.Find(subject.Id);
                        newApproval.IdTutor             = editUser.User.Id;
                        newApproval.IdTutorNavigation   = db.SscisUser.Find(editUser.User.Id);
                        db.Approval.Add(newApproval);
                        db.SaveChanges();
                    }
                }
                else
                {
                    foreach (MetaApproval app in editUser.Approvals)
                    {
                        if (app.Approved == true)
                        {
                            List <Approval> tmp = db.Approval.Where(a => a.IdTutor == editUser.User.Id && a.IdSubject == app.EnumSubject.Id).ToList();
                            if (tmp.Count == 0)
                            {
                                Approval newApproval = new Approval();
                                newApproval.IdSubject           = app.EnumSubject.Id;
                                newApproval.IdSubjectNavigation = db.EnumSubject.Find(app.EnumSubject.Id);
                                newApproval.IdTutor             = editUser.User.Id;
                                newApproval.IdTutorNavigation   = db.SscisUser.Find(editUser.User.Id);
                                db.Approval.Add(newApproval);
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            List <Approval> tmp = db.Approval.Where(a => a.IdTutor == editUser.User.Id && a.IdSubject == app.EnumSubject.Id).ToList();
                            foreach (Approval app2 in tmp)
                            {
                                db.Approval.Remove(app2);
                            }
                        }
                    }
                }
                editUser.Approvals            = null;
                db.Entry(editUser.User).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ViewBag.RoleID        = new SelectList(db.EnumRole, "Id", "Role", editUser.User.IdRole);
            ViewBag.ActivatedByID = new SelectList(db.SscisUser, "Id", "Login", editUser.User.IsActivatedBy);
            return(View(editUser.User));
        }
Example #36
0
 private static void GetApproval(Approval approval)
 {
     Screen.Navigation.PushModalAsync(new ApprovalPage(approval));
 }
 public void AddToApprovals(Approval approval)
 {
     base.AddObject("Approvals", approval);
 }
Example #38
0
        public async Task <bool> Update(Approval approval)
        {
            var UpdateResult = await _context.approval.ReplaceOneAsync(filter : g => g.Id == approval.Id, replacement : approval);

            return(UpdateResult.IsAcknowledged && UpdateResult.ModifiedCount > 0);
        }
        private void CreateApprovals(List<Approval> approvals, OrderStatusCode currentLevel, Order order)
        {
            //var approval = new Approval();
            //approval.Order = new Order();
            //approval.Order.SetIdTo(i + 1 + currentOffSet);
            //approval.StatusCode = OrderStatusCodeRepository.GetNullableById(Role.Codes.Requester);
            //approval.User = createdBy;
            //approval.Approved = true;
            //approvals.Add(approval);

            var approval = new Approval();
            approval.Order = new Order();
            approval.Order.SetIdTo(order.Id);
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(Role.Codes.Approver);
            approval.User = UserRepository.GetNullableById("hsimpson");
            if(approval.StatusCode.Level < currentLevel.Level)
            {
                approval.Completed = true;
            }
            approvals.Add(approval);

            approval = new Approval();
            approval.Order = new Order();
            approval.Order.SetIdTo(order.Id);
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(Role.Codes.AccountManager);
            approval.User = UserRepository.GetNullableById("flanders");
            if(approval.StatusCode.Level < currentLevel.Level)
            {
                approval.Completed = true;
            }
            approvals.Add(approval);

            approval = new Approval();
            approval.Order = new Order();
            approval.Order.SetIdTo(order.Id);
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(Role.Codes.Purchaser);
            approval.User = UserRepository.GetNullableById("awong");
            if(approval.StatusCode.Level < currentLevel.Level)
            {
                approval.Completed = true;
            }
            approvals.Add(approval);

            approval = new Approval();
            approval.Order = new Order();
            approval.Order.SetIdTo(order.Id);
            approval.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.CompleteNotUploadedKfs);
            approval.User = UserRepository.GetNullableById("zoidberg");
            if(approval.StatusCode.Level < currentLevel.Level)
            {
                approval.Completed = true;
            }
            approvals.Add(approval);
        }
 public int Add(Approval approval)
 {
     return(iapproval.Add(approval));
 }
Example #41
0
        public void InsertApproval(Approval model)
        {
            tbl_Approval _tblApproval = new tbl_Approval(model);

            _tblApproval = _tbl_Approval.Insert(_tblApproval);
        }
Example #42
0
        public void ReRouteSingleApprovalForExistingOrder(Approval approval, User user, bool notify = false)
        {
            approval.SecondaryUser = null;
            approval.User = user;

            _eventService.OrderApprovalAdded(approval.Order, approval, notify);
        }
 public ApprovalDetailPage(Approval approval) : this()
 {
     ViewModel.ApprovalDetail = approval;
 }
 public static Approval CreateApproval(long approvalID, string comments, byte approvalEntityTypeID, long orderID)
 {
     Approval approval = new Approval();
     approval.ApprovalID = approvalID;
     approval.Comments = comments;
     approval.ApprovalEntityTypeID = approvalEntityTypeID;
     approval.OrderID = orderID;
     return approval;
 }
Example #45
0
 public async Task <IActionResult> UpdateApproval([FromBody] Approval approval) //we are expecting http request and inside of request we expect product body and .net core will auto convert jason to object
 {
     return(Ok(await _repository.Update(approval)));
 }
Example #46
0
        public Approval Get(int?Id)
        {
            Approval approval = myContext.Approvals.Where(x => x.Id == Id).SingleOrDefault();

            return(approval);
        }
Example #47
0
 public ApprovalBusiness()
 {
     _tbl_Approval = new GenericPattern <tbl_Approval>();
     _Approval     = new Approval();
 }