private async Task BuildPendingBrandApprovalNotification(List <EmailNotificationMessage <CostNotificationObject> > notifications,
                                                                 List <Approval> approvals, Cost cost, CostNotificationUsers costUsers, CostStageRevision costStageRevision, DateTime timestamp)
        {
            var costOwner                   = costUsers.CostOwner;
            var agency                      = costOwner.Agency;
            var isCyclone                   = agency.IsCyclone();
            var costStageRevisionId         = costStageRevision.Id;
            var isNorthAmericanBudgetRegion = IsNorthAmericanBudgetRegion(costStageRevisionId);

            var brandApprovals = approvals.Where(a => a.Type == ApprovalType.Brand).ToArray();

            if (isCyclone && isNorthAmericanBudgetRegion)
            {
                //Send notification to Brand Approver in the Platform for Cost in North American Budget Region and Cyclone agencies.
                const string actionType = core.Constants.EmailNotificationActionType.BrandApproverAssigned;
                var          parent     = core.Constants.EmailNotificationParents.BrandApprover;
                foreach (var brandApproval in brandApprovals)
                {
                    foreach (var approvalMember in brandApproval.ApprovalMembers)
                    {
                        //Send notifications to actual Brand Approvers only
                        if (approvalMember.IsSystemApprover())
                        {
                            continue;
                        }

                        var approvalCostUser          = approvalMember.CostUser;
                        var brandApproverNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, approvalCostUser.GdamUserId);
                        AddSharedTo(brandApproverNotification);

                        MapEmailNotificationObject(brandApproverNotification.Object, cost, costOwner, approvalCostUser);
                        PopulateOtherFields(brandApproverNotification, parent, timestamp, cost.Id, costStageRevisionId);
                        await PopulateMetadata(brandApproverNotification.Object, cost.Id);

                        notifications.Add(brandApproverNotification);

                        if (ShouldNotifyInsuranceUsers(costUsers))
                        {
                            var insuranceUserNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, costUsers.InsuranceUsers);
                            AddSharedTo(insuranceUserNotification);

                            MapEmailNotificationObject(insuranceUserNotification.Object, cost, costOwner, approvalCostUser);
                            PopulateOtherFields(insuranceUserNotification, core.Constants.EmailNotificationParents.InsuranceUser, timestamp, cost.Id, costStageRevisionId);
                            await PopulateMetadata(insuranceUserNotification.Object, cost.Id);

                            notifications.Add(insuranceUserNotification);
                        }
                    }
                }

                if (brandApprovals.Any())
                {
                    await AddFinanceManagerNotification(actionType, cost, costUsers, costStageRevision, timestamp, notifications);
                }
            }
            else
            {
                AddCoupaApprovalEmail(notifications, cost, costOwner, costStageRevisionId, timestamp);
            }
        }
        internal async Task<IEnumerable<EmailNotificationMessage<CostNotificationObject>>> Build(Cost cost,
            CostNotificationUsers costUsers, CostStageRevision costStageRevision, DateTime timestamp)
        {
            var notifications = new List<EmailNotificationMessage<CostNotificationObject>>();

            //Cost Owner
            var costOwner = costUsers.CostOwner;
            var recipients = new List<string> { costOwner.GdamUserId };
            recipients.AddRange(costUsers.Watchers);

            var costOwnerNotification = new EmailNotificationMessage<CostNotificationObject>(Constants.EmailNotificationActionType.Cancelled, recipients);
            AddSharedTo(costOwnerNotification);
            MapEmailNotificationObject(costOwnerNotification.Object, cost, costOwner);
            PopulateOtherFields(costOwnerNotification, Constants.EmailNotificationParents.CostOwner, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(costOwnerNotification.Object, cost.Id);
            notifications.Add(costOwnerNotification);

            if (ShouldNotifyInsuranceUsers(costUsers))
            {
                var insuranceUserNotification = new EmailNotificationMessage<CostNotificationObject>(Constants.EmailNotificationActionType.Cancelled, costUsers.InsuranceUsers);
                AddSharedTo(insuranceUserNotification);
                MapEmailNotificationObject(insuranceUserNotification.Object, cost, costOwner);
                PopulateOtherFields(insuranceUserNotification, Constants.EmailNotificationParents.InsuranceUser, timestamp, cost.Id, costStageRevision.Id);
                await PopulateMetadata(insuranceUserNotification.Object, cost.Id);
                notifications.Add(insuranceUserNotification);
            }
            await AddFinanceManagerNotification(Constants.EmailNotificationActionType.Cancelled,
                cost, costUsers, costStageRevision, timestamp, notifications);

            return notifications;
        }
        protected void TestCommonMessageDetails(EmailNotificationMessage <CostNotificationObject> emailNotificationMessage, string expectedActionType, params string[] emailRecipients)
        {
            emailNotificationMessage.Should().NotBeNull();
            emailNotificationMessage.Action.Should().NotBeNull();
            emailNotificationMessage.Action.Type.Should().NotBeNull();
            emailNotificationMessage.Object.Should().NotBeNull();
            emailNotificationMessage.Object.Agency.Should().NotBeNull();
            emailNotificationMessage.Object.Brand.Should().NotBeNull();
            emailNotificationMessage.Object.Cost.Should().NotBeNull();
            emailNotificationMessage.Object.Parents.Should().NotBeNull();
            emailNotificationMessage.Object.Type.Should().NotBeNull();

            emailNotificationMessage.Recipients.Should().NotBeNull();
            emailNotificationMessage.Subject.Should().NotBeNull();
            emailNotificationMessage.Viewers.Should().NotBeNull();

            emailNotificationMessage.Action.Type.Should().Be(expectedActionType);
            emailNotificationMessage.Type.Should().NotBeNull();
            emailNotificationMessage.Type.Should().Be(expectedActionType);             //Paper-Pusher uses .Type, MS uses Action.Type. Both should be same.
            emailNotificationMessage.Object.Type.Length.Should().BeGreaterThan(0);     //Required by Paper-Pusher

            emailNotificationMessage.Timestamp.Should().BeOnOrBefore(DateTime.UtcNow); //Not a future notification

            //Identifiers are set to something other than Null/Empty
            emailNotificationMessage.Id.Should().NotBe(Guid.Empty);
            emailNotificationMessage.Object.Id.Should().NotBe(Guid.Empty.ToString());
            emailNotificationMessage.Subject.Id.Should().NotBe(Guid.Empty.ToString());

            emailNotificationMessage.Object.Agency.Location.Should().NotBeNull();
            emailNotificationMessage.Object.Agency.Location.Should().Be(AgencyLocation);
            emailNotificationMessage.Object.Agency.Name.Should().NotBeNull();
            emailNotificationMessage.Object.Agency.Name.Should().Be(AgencyName);

            emailNotificationMessage.Object.Brand.Name.Should().NotBeNull();
            emailNotificationMessage.Object.Brand.Name.Should().Be(BrandName);

            emailNotificationMessage.Object.Cost.Number.Should().Be(CostNumber);
            emailNotificationMessage.Object.Cost.Title.Should().NotBeNull();
            //TODO: Double check this is correct field to use
            emailNotificationMessage.Object.Cost.Title.Should().Be(CostTitle);
            emailNotificationMessage.Object.Cost.ProductionType.Should().NotBeNull();
            emailNotificationMessage.Object.Cost.ProductionType.Should().Be(CostProductionType);
            emailNotificationMessage.Object.Cost.ContentType.Should().NotBeNull();
            emailNotificationMessage.Object.Cost.ContentType.Should().Be(ContentType);
            emailNotificationMessage.Object.Cost.Owner.Should().NotBeNull();
            emailNotificationMessage.Object.Cost.Owner.Should().Be(CostOwnerFullName);
            emailNotificationMessage.Object.Cost.Url.Should().NotBeNull();
            emailNotificationMessage.Object.Cost.Url.Should().Be(CostUrl);

            emailNotificationMessage.Object.Project.Id.Should().Be(ProjectGdamId);
            emailNotificationMessage.Object.Project.Name.Should().NotBeNull();
            emailNotificationMessage.Object.Project.Name.Should().Be(ProjectName);
            emailNotificationMessage.Object.Project.Number.Should().Be(ProjectNumber);


            emailNotificationMessage.Recipients.Should().Contain(emailRecipients);

            emailNotificationMessage.Action.Share.Should().NotBeNull();
            emailNotificationMessage.Action.Share.To.Count.Should().BeGreaterOrEqualTo(1);
        }
Ejemplo n.º 4
0
        private async Task BuildPendingTechnicalApprovalNotification(List <EmailNotificationMessage <CostNotificationObject> > notifications,
                                                                     List <Approval> approvals, dataAccess.Entity.Cost cost, CostNotificationUsers costUsers,
                                                                     CostUser costOwner, CostStageRevision costStageRevision, DateTime timestamp)
        {
            const string actionType         = core.Constants.EmailNotificationActionType.TechnicalApproverSendReminder;
            var          technicalApprovals = approvals.Where(a => a.Type == ApprovalType.IPM).ToArray();

            foreach (var technicalApproval in technicalApprovals)
            {
                foreach (var approvalMember in technicalApproval.ApprovalMembers)
                {
                    //Send notifications to Technical Approver
                    var approvalCostUser = approvalMember.CostUser;
                    var technicalApproverNotification = new EmailNotificationMessage <CostNotificationObject>(actionType,
                                                                                                              approvalCostUser.GdamUserId);
                    AddSharedTo(technicalApproverNotification);

                    MapEmailNotificationObject(technicalApproverNotification.Object, cost, costOwner, approvalCostUser);
                    PopulateOtherFields(technicalApproverNotification, core.Constants.EmailNotificationParents.TechnicalApprover, timestamp, cost.Id, costStageRevision.Id, approvalCostUser);
                    await PopulateMetadata(technicalApproverNotification.Object, cost.Id);

                    notifications.Add(technicalApproverNotification);
                }
            }
        }
        public async Task InvoiceEmailNotification_SentNotification()
        {
            //Arrange
            var language     = "default";
            var subject      = "Invoice for order - <strong>{{ customer_order.number }}</strong>";
            var body         = TestUtility.GetStringByPath($"Content\\{nameof(InvoiceEmailNotification)}.html");
            var notification = new InvoiceEmailNotification()
            {
                CustomerOrder = new CustomerOrder()
                {
                    Id            = "adsffads",
                    Number        = "123",
                    ShippingTotal = 123456.789m,
                    CreatedDate   = DateTime.Now,
                    Status        = "Paid",
                    Total         = 123456.789m,
                    FeeTotal      = 123456.789m,
                    SubTotal      = 123456.789m,
                    TaxTotal      = 123456.789m,
                    Currency      = "USD",
                    Items         = new[] { new LineItem
                                            {
                                                Name          = "some",
                                                Sku           = "sku",
                                                PlacedPrice   = 12345.6789m,
                                                Quantity      = 1,
                                                ExtendedPrice = 12345.6789m,
                                            } }
                },
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject = subject,
                        Body    = body,
                    }
                }
            };
            var date    = new DateTime(2018, 02, 20, 10, 00, 00);
            var message = new EmailNotificationMessage()
            {
                Id       = "1",
                From     = "*****@*****.**",
                To       = "*****@*****.**",
                Subject  = subject,
                Body     = body,
                SendDate = date
            };

            _messageServiceMock.Setup(ms => ms.SaveNotificationMessagesAsync(new NotificationMessage[] { message }));


            //Act
            var result = await _sender.SendNotificationAsync(notification, language);

            //Assert
            Assert.True(result.IsSuccess);
        }
        private EmailMessage CreateEmailMessage(string title, string emailBody, NotificationMessage <EmailNotificationMessage> notificationMessage)
        {
            EmailNotificationMessage message = notificationMessage.Message;
            string subject = string.IsNullOrWhiteSpace(message.Subject)
                ? title
                : message.Subject;

            return(new EmailMessage(subject, emailBody, message.From, message.To, message.Cс));
        }
Ejemplo n.º 7
0
        private byte[] CreateRestorePasswordMessage(string newPassword)
        {
            var message = new EmailNotificationMessage
            {
                Body    = string.Format("Your new password is: {0}", newPassword),
                Subject = "SweetHome Service - Restore Password"
            };

            return(GetMessageBytes(message));
        }
Ejemplo n.º 8
0
        private byte[] CreateErrorMessage(string error)
        {
            var message = new EmailNotificationMessage
            {
                Body    = error,
                Subject = "SweetHome Service - Error"
            };

            return(GetMessageBytes(message));
        }
Ejemplo n.º 9
0
        private async Task AddApproverNotification(List <EmailNotificationMessage <CostNotificationObject> > notifications,
                                                   Cost cost, CostUser costOwner, CostStageRevision costStageRevision, DateTime timestamp, string actionType, CostUser user)
        {
            var notificationMessage = new EmailNotificationMessage <CostNotificationObject>(actionType, user.GdamUserId);

            AddSharedTo(notificationMessage);
            MapEmailNotificationObject(notificationMessage.Object, cost, costOwner, user);
            await PopulateOtherFieldsForRecall(notificationMessage, Constants.EmailNotificationParents.Approver, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(notificationMessage.Object, cost.Id);

            notifications.Add(notificationMessage);
        }
Ejemplo n.º 10
0
        public async Task OrderSendEmailNotification_SentNotification()
        {
            //Arrange
            var language = "en-US";
            var subject  = "Your order was sent";
            var body     = "Your order <strong>{{ customer_order.number}}</strong> was sent.<br> Number of sent parcels - " +
                           "<strong>{{ customer_order.shipments | size}}</strong>.<br> Parcels tracking numbers:<br> {% for shipment in customer_order.shipments %} " +
                           "<br><strong>{{ shipment.number}}</strong> {% endfor %}<br><br>Sent date - <strong>{{ customer_order.modified_date }}</strong>.";
            var notification = new OrderSentEmailNotification()
            {
                CustomerOrder = new CustomerOrder()
                {
                    Number = "123"
                    ,
                    Shipments = new[] { new Shipment()
                                        {
                                            Number = "some_number"
                                        } }
                    ,
                    ModifiedDate = DateTime.Now
                },
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject      = subject,
                        Body         = body,
                        LanguageCode = "en-US"
                    }
                },
                LanguageCode = language,
                IsActive     = true
            };
            var date    = new DateTime(2018, 02, 20, 10, 00, 00);
            var message = new EmailNotificationMessage()
            {
                Id       = "1",
                From     = "*****@*****.**",
                To       = "*****@*****.**",
                Subject  = subject,
                Body     = body,
                SendDate = date
            };

            _messageServiceMock.Setup(ms => ms.GetNotificationsMessageByIds(It.IsAny <string[]>()))
            .ReturnsAsync(new[] { message });

            //Act
            var result = await _sender.SendNotificationAsync(notification);

            //Assert
            Assert.True(result.IsSuccess);
        }
Ejemplo n.º 11
0
        private async Task SendEmailNotificationAsync(AppUser appUser, string subject, string message)
        {
            var queueMessageBody = new EmailNotificationMessage
            {
                EmailAddress = appUser.UserPreferences.EmailAddress,
                Subject      = subject,
                Message      = message
            };

            var queueMessageBodyJson = JsonConvert.SerializeObject(queueMessageBody);
            var queueMessage         = new Message(Encoding.UTF8.GetBytes(queueMessageBodyJson));
            await _emailNotificationQueueClient.SendAsync(queueMessage);
        }
        internal async Task <IEnumerable <EmailNotificationMessage <CostNotificationObject> > > Build(dataAccess.Entity.Cost cost,
                                                                                                      CostNotificationUsers costUsers, CostStageRevision costStageRevision, DateTime timestamp)
        {
            var          notifications = new List <EmailNotificationMessage <CostNotificationObject> >();
            var          approvals     = _approvalService.GetApprovalsByCostStageRevisionId(costStageRevision.Id).Result;
            const string actionType    = core.Constants.EmailNotificationActionType.TechnicalApproverAssigned;

            if (approvals == null)
            {
                //No approvals set
                return(notifications);
            }

            var costOwner          = costUsers.CostOwner;
            var technicalApprovals = approvals.Where(a => a.Type == ApprovalType.IPM).ToArray();

            foreach (var technicalApproval in technicalApprovals)
            {
                foreach (var approvalMember in technicalApproval.ApprovalMembers)
                {
                    //Send notifications to Technical Approver
                    var approvalCostUser = approvalMember.CostUser;
                    var technicalApproverNotification = new EmailNotificationMessage <CostNotificationObject>(actionType,
                                                                                                              approvalCostUser.GdamUserId);
                    AddSharedTo(technicalApproverNotification);

                    MapEmailNotificationObject(technicalApproverNotification.Object, cost, costOwner, approvalCostUser);
                    PopulateOtherFields(technicalApproverNotification, core.Constants.EmailNotificationParents.TechnicalApprover, timestamp, cost.Id, costStageRevision.Id, approvalCostUser);
                    await PopulateMetadata(technicalApproverNotification.Object, cost.Id);

                    notifications.Add(technicalApproverNotification);

                    //Insurance User
                    if (ShouldNotifyInsuranceUsers(costUsers))
                    {
                        var insuranceUserNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, costUsers.InsuranceUsers);
                        AddSharedTo(insuranceUserNotification);

                        MapEmailNotificationObject(insuranceUserNotification.Object, cost, costOwner, approvalCostUser);
                        PopulateOtherFields(insuranceUserNotification, core.Constants.EmailNotificationParents.InsuranceUser, timestamp, cost.Id, costStageRevision.Id,
                                            approvalCostUser);
                        await PopulateMetadata(insuranceUserNotification.Object, cost.Id);

                        notifications.Add(insuranceUserNotification);
                    }
                }
            }
            await AddFinanceManagerNotification(actionType, cost, costUsers, costStageRevision, timestamp, notifications);

            return(notifications);
        }
        public void EmailNotificationMessage_InitializingEmailNotificationWithNullValues()
        {
            var sourceAgencyId   = new Guid("FED2106B-5973-4099-8CA7-9998B94E8E12");
            var sourceIdentityId = new Guid("FED2106B-5973-4099-8CA7-9998B94E8E12");

            _emailNotificationMessage = new EmailNotificationMessage(sourceAgencyId, sourceIdentityId, null, null, null, null, null);
            Assert.AreEqual(sourceAgencyId, _emailNotificationMessage.SourceAgencyId);
            Assert.AreEqual(sourceIdentityId, _emailNotificationMessage.SourceIdentityId);
            Assert.IsNull(_emailNotificationMessage.ToEmails);
            Assert.IsNull(_emailNotificationMessage.CcEmails);
            Assert.IsNull(_emailNotificationMessage.BccEmails);
            Assert.IsNull(_emailNotificationMessage.Subject);
            Assert.IsNull(_emailNotificationMessage.Body);
        }
Ejemplo n.º 14
0
        internal async Task <IEnumerable <EmailNotificationMessage <CostNotificationObject> > > Build(dataAccess.Entity.Cost cost,
                                                                                                      CostNotificationUsers costUsers, string approverName, string approvalType, string comments, CostStageRevision costStageRevision, DateTime timestamp)
        {
            var          notifications = new List <EmailNotificationMessage <CostNotificationObject> >();
            const string actionType    = core.Constants.EmailNotificationActionType.Rejected;

            //Cost Owner
            var costOwner  = costUsers.CostOwner;
            var recipients = new List <string> {
                costOwner.GdamUserId
            };

            recipients.AddRange(costUsers.Watchers);

            var costOwnerNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, recipients);

            AddSharedTo(costOwnerNotification);
            MapEmailNotificationObject(costOwnerNotification.Object, cost, costOwner);
            PopulateOtherFields(costOwnerNotification, core.Constants.EmailNotificationParents.CostOwner, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(costOwnerNotification.Object, cost.Id);

            var obj      = costOwnerNotification.Object;
            var approver = obj.Approver;

            approver.Name = approverName;
            approver.Type = approvalType;
            obj.Comments  = comments;

            notifications.Add(costOwnerNotification);

            if (ShouldNotifyInsuranceUsers(costUsers))
            {
                var insuranceUserNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, costUsers.InsuranceUsers);
                AddSharedTo(insuranceUserNotification);
                MapEmailNotificationObject(insuranceUserNotification.Object, cost, costOwner);
                PopulateOtherFields(insuranceUserNotification, core.Constants.EmailNotificationParents.InsuranceUser, timestamp, cost.Id, costStageRevision.Id);
                await PopulateMetadata(insuranceUserNotification.Object, cost.Id);

                obj           = insuranceUserNotification.Object;
                approver      = obj.Approver;
                approver.Name = approverName;
                approver.Type = approvalType;
                obj.Comments  = comments;

                notifications.Add(insuranceUserNotification);
            }
            await AddFinanceManagerNotification(actionType, cost, costUsers, costStageRevision, timestamp, notifications);

            return(notifications);
        }
        /// <summary>
        /// Creates an email, notifying support that there's a technical problem with submitting this cost
        /// </summary>
        /// <param name="recipientGdamUserId">This can either be an A5 user or an email address. If this is an email address,
        /// ensure the same email address is passed into the <see cref="additionalEmails"/> parameter.
        /// </param>
        /// <param name="costNumber">Unique display-identifier of affected cost</param>
        /// <param name="additionalEmails">An enumerable collection of email addresses to send this email to.</param>
        /// <returns></returns>
        internal EmailNotificationMessage <SubmissionFailedNotificationObject> Build(string recipientGdamUserId, string costNumber, IEnumerable <string> additionalEmails = null)
        {
            var notificationMessage = new EmailNotificationMessage <SubmissionFailedNotificationObject>(core.Constants.EmailNotificationActionType.SubmissionFailed, recipientGdamUserId);

            notificationMessage.Object.CostNumber = costNumber;
            if (additionalEmails != null)
            {
                foreach (var email in additionalEmails)
                {
                    notificationMessage.Parameters.EmailService.AdditionalEmails.Add(email);
                }
            }

            return(notificationMessage);
        }
Ejemplo n.º 16
0
        private async Task PopulateOtherFieldsForRecall(EmailNotificationMessage <CostNotificationObject> message, string parent, DateTime timestamp, Guid costId, Guid costStageRevisionId)
        {
            PopulateOtherFields(message, parent, timestamp, costId, costStageRevisionId);

            // Add fields specific to Recall notification message
            var obj           = message.Object;
            var cost          = obj.Cost;
            var stageForm     = _costStageRevisionService.GetStageDetails <PgStageDetailsForm>(costStageRevisionId).Result;
            var buyoutDetails = _costFormService.GetCostFormDetails <BuyoutDetails>(costStageRevisionId).Result;

            cost.AgencyTrackingNumber = stageForm.AgencyTrackingNumber;
            cost.Region          = stageForm.BudgetRegion?.Name;
            cost.AiringCountries = string.Join(";", (buyoutDetails?.AiringCountries ?? new BuyoutDetails.Country[0]).Select(c => c.Name).ToArray());
            cost.Requisition     = (await _customObjectDataService.GetCustomData <PgPurchaseOrderResponse>(costStageRevisionId, CustomObjectDataKeys.PgPurchaseOrderResponse))?.Requisition;
        }
Ejemplo n.º 17
0
        public async Task OrderPaidEmailNotification_SentNotification()
        {
            //Arrange
            var language = "default";
            var subject  = "Your order was fully paid";
            var body     = "Thank you for paying <strong>{{ customer_order.number }}</strong> order.<br> " +
                           "You had paid <strong>{{ customer_order.total | math.format 'N'}} {{ customer_order.currency }}</strong>.<br>" +
                           " Paid date - <strong>{{ customer_order.modified_date }}</strong>.";
            var notification = new OrderPaidEmailNotification()
            {
                CustomerOrder = new CustomerOrder()
                {
                    Number       = "123",
                    Total        = 1234.56m,
                    Currency     = "USD",
                    ModifiedDate = DateTime.Now
                },
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject = subject,
                        Body    = body,
                    }
                },
                LanguageCode = language,
                IsActive     = true
            };
            var date    = new DateTime(2018, 02, 20, 10, 00, 00);
            var message = new EmailNotificationMessage()
            {
                Id       = "1",
                From     = "*****@*****.**",
                To       = "*****@*****.**",
                Subject  = subject,
                Body     = body,
                SendDate = date
            };

            _messageServiceMock.Setup(ms => ms.GetNotificationsMessageByIds(It.IsAny <string[]>()))
            .ReturnsAsync(new[] { message });

            //Act
            var result = await _sender.SendNotificationAsync(notification);

            //Assert
            Assert.True(result.IsSuccess);
        }
Ejemplo n.º 18
0
        public async Task SendNotification_SetCustomValidationError_NotSend()
        {
            //Arrange
            var language     = "default";
            var subject      = "some subject";
            var body         = "some body";
            var notification = new RegistrationEmailNotification()
            {
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject = subject,
                        Body    = body,
                    }
                },
                LanguageCode = language
            };

            notification.SetCustomValidationError("some error");

            var message = new EmailNotificationMessage()
            {
                Id       = "1",
                From     = "*****@*****.**",
                To       = "*****@*****.**",
                Subject  = subject,
                Body     = body,
                SendDate = DateTime.Now
            };

            _messageServiceMock.Setup(ms => ms.SaveNotificationMessagesAsync(new NotificationMessage[] { message }));
            _messageSenderMock.Setup(ms => ms.SendNotificationAsync(It.IsAny <NotificationMessage>())).Throws(new SmtpException());
            _messageServiceMock.Setup(ms => ms.GetNotificationsMessageByIds(It.IsAny <string[]>())).ReturnsAsync(new[] { message })
            .Callback(() =>
            {
                message.Status = NotificationMessageStatus.Error;
            });

            var sender = GetNotificationSender();

            //Act
            var sendResult = await sender.SendNotificationAsync(notification);

            //Assert
            Assert.False(sendResult.IsSuccess);
            Assert.Equal("Can't send notification message by . There are errors.", sendResult.ErrorMessage);
        }
        // TODO cover this logc by unit tests
        private void AddCoupaApprovalEmail(List <EmailNotificationMessage <CostNotificationObject> > notifications,
                                           Cost cost, CostUser costOwner, Guid costStageRevisionId, DateTime timestamp)
        {
            var previousCostStage = _costStageService.GetPreviousCostStage(cost.LatestCostStageRevision.CostStageId).Result;

            if (previousCostStage == null)
            {
                // No need to send COUPA apprvoal email because this is the first time cost gets submitted for Brand Approval
                return;
            }

            var latestRevisionOfPreviousStage = CostStageRevisionService.GetLatestRevision(previousCostStage.Id).Result;

            if (latestRevisionOfPreviousStage == null)
            {
                throw new Exception($"Couldn't find latest revision for stage {previousCostStage.Id}");
            }

            var previousPaymentAmount = _pgPaymentService.GetPaymentAmount(latestRevisionOfPreviousStage.Id, false).Result;
            var currentPaymentAmount  = _pgPaymentService.GetPaymentAmount(costStageRevisionId, false).Result;

            if (currentPaymentAmount.TotalCostAmount == previousPaymentAmount.TotalCostAmount)
            {
                return;
            }

            // Send COUPA approval email because total amount changed
            var paymentDetails = _customObjectDataService.GetCustomData <PgPaymentDetails>(costStageRevisionId, CustomObjectDataKeys.PgPaymentDetails).Result;

            if (!string.IsNullOrEmpty(paymentDetails?.PoNumber))
            {
                var actionType        = core.Constants.EmailNotificationActionType.Submitted;
                var parent            = core.Constants.EmailNotificationParents.Coupa;
                var coupaNotification = new EmailNotificationMessage <CostNotificationObject>(actionType);

                MapEmailNotificationObject(coupaNotification.Object, cost, costOwner);
                PopulateOtherFields(coupaNotification, parent, timestamp, cost.Id, cost.LatestCostStageRevision.Id);
                AddSharedTo(coupaNotification);
                var notificationCost = coupaNotification.Object.Cost;
                notificationCost.PurchaseOrder = new PurchaseOrder();
                Mapper.Map(currentPaymentAmount, notificationCost.PurchaseOrder);
                Mapper.Map(paymentDetails, notificationCost.PurchaseOrder);
                coupaNotification.Parameters.EmailService.AdditionalEmails.Add(AppSettings.CoupaApprovalEmail);

                notifications.Add(coupaNotification);
            }
        }
Ejemplo n.º 20
0
        private void SendToEmailNotification(BackCushionMngEntities context, string emailSubject, string emailBody)
        {
            try
            {
                string        sendToEmail    = string.Empty;
                List <string> emailAddresses = new List <string>();

                // My(AVT)[20] and Thanh(AVT)[74].
                emailAddresses = context.EmployeeMng_Employee_View.Where(o => o.UserID == 20 || o.UserID == 74).Select(s => s.Email1).ToList();
                foreach (var emailAddress in emailAddresses)
                {
                    if (!string.IsNullOrEmpty(sendToEmail))
                    {
                        sendToEmail += "; ";
                    }

                    sendToEmail += emailAddress;
                }

                List <int> listUser = new List <int>();
                listUser.Add(20);
                listUser.Add(74);
                foreach (var item in listUser)
                {
                    // add to NotificationMessage table
                    NotificationMessage notification = new NotificationMessage();
                    notification.UserID = item;
                    notification.NotificationMessageTag     = Module.Framework.ConstantIdentifier.MOBILE_APP_MESSAGE_TAG_PRODUCTDEVELOPMENT;
                    notification.NotificationMessageTitle   = emailSubject;
                    notification.NotificationMessageContent = emailBody;
                    context.NotificationMessage.Add(notification);
                }

                // Create data EmailNotificationMessage.
                EmailNotificationMessage emailNotificationMessage = new EmailNotificationMessage();
                emailNotificationMessage.EmailSubject = emailSubject;
                emailNotificationMessage.EmailBody    = emailBody;
                emailNotificationMessage.SendTo       = sendToEmail;

                context.EmailNotificationMessage.Add(emailNotificationMessage);
                context.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
        void ISubscribeTo <EmailNotificationMessage> .MessageHandler(EmailNotificationMessage message)
        {
            try
            {
                using (var subscriber = DependencyContainer.Resolve <IEmailNotificationService>())
                {
                    subscriber.Instance.SendEmailNotificationMessage(message);
                }
            }
            catch (Exception exception)
            {
                Log.Error("EmailNotificationMessagingFacade EmailNotificationMessage Messaging Error: " + exception);

                // Rethrow exception so that MassTransit will place the message in an error queue
                throw;
            }
        }
        private void AssignApproverType(EmailNotificationMessage <CostNotificationObject> message, CostUser approvalCostUser = null)
        {
            CostNotificationObject obj = message.Object;

            if (message.Type == core.Constants.EmailNotificationActionType.TechnicalApproverAssigned)
            {
                //IPM should be default
                obj.Approver.Type = (approvalCostUser?.UserBusinessRoles == null ||
                                     approvalCostUser.UserBusinessRoles.Any(br => br.BusinessRole != null && br.BusinessRole.Key == Constants.BusinessRole.Ipm))
                        ? core.Constants.EmailApprovalType.IPM
                        : core.Constants.EmailApprovalType.CC;
            }
            if (message.Type == core.Constants.EmailNotificationActionType.BrandApproverAssigned)
            {
                obj.Approver.Type = core.Constants.EmailApprovalType.Brand;
            }
        }
        protected void AddSharedTo(EmailNotificationMessage <CostNotificationObject> message)
        {
            var users = EFContext.CostUser.Include(cu => cu.Agency).Where(cu => message.Recipients.Contains(cu.GdamUserId)).ToList();

            message.Recipients.ForEach(gdamUserId =>
            {
                var selectedUser = users.FirstOrDefault(a => a.GdamUserId == gdamUserId);
                message.Action.Share.To.Add(new To
                {
                    Id       = gdamUserId,
                    FullName = selectedUser?.FullName,
                    Agency   = new EmailAgency
                    {
                        // This overrides Agency URL but only for adcosts (its a known behaviour) and only when it exists!
                        Url = selectedUser?.EmailUrl ?? selectedUser?.Agency?.NotificationUrl
                    }
                });
            });
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="recipientGdamUserId">This can either be an A5 user or an email address. If this is an email address,
        /// ensure the same email address is passed into the <see cref="additionalEmails"/> parameter.
        /// </param>
        /// <param name="subject">The email subject</param>
        /// <param name="header">The header of the email, like a H1 for the email.</param>
        /// <param name="body">The main content of the email.</param>
        /// <param name="additionalEmails">An enumerable collection of email addresses to send this email to.</param>
        /// <returns></returns>
        internal EmailNotificationMessage <GenericNotificationObject> Build(string recipientGdamUserId, string subject, string header, string body, IEnumerable <string> additionalEmails = null)
        {
            var notificationMessage       = new EmailNotificationMessage <GenericNotificationObject>(core.Constants.EmailNotificationActionType.GenericAdCost, recipientGdamUserId);
            GenericNotificationObject obj = notificationMessage.Object;

            obj.Body    = body;
            obj.Header  = header;
            obj.Subject = subject;

            if (additionalEmails != null)
            {
                foreach (var email in additionalEmails)
                {
                    notificationMessage.Parameters.EmailService.AdditionalEmails.Add(email);
                }
            }

            return(notificationMessage);
        }
        public void EmailNotificationMessage_InitializingEmailNotification()
        {
            var sourceAgencyId   = new Guid("FED2106B-5973-4099-8CA7-9998B94E8E12");
            var sourceIdentityId = new Guid("FED2106B-5973-4099-8CA7-9998B94E8E12");
            var toEmails         = new[] { "*****@*****.**", "*****@*****.**" };
            var ccEmails         = new[] { "*****@*****.**", "*****@*****.**" };
            var bccEmails        = new[] { "*****@*****.**", "*****@*****.**" };
            var subject          = "Sample test";
            var body             = "Welcome Notification";

            _emailNotificationMessage = new EmailNotificationMessage(sourceAgencyId, sourceIdentityId, toEmails, ccEmails, bccEmails, subject, body);
            Assert.AreEqual(sourceAgencyId, _emailNotificationMessage.SourceAgencyId);
            Assert.AreEqual(sourceIdentityId, _emailNotificationMessage.SourceIdentityId);
            Assert.AreEqual(toEmails, _emailNotificationMessage.ToEmails);
            Assert.AreEqual(ccEmails, _emailNotificationMessage.CcEmails);
            Assert.AreEqual(bccEmails, _emailNotificationMessage.BccEmails);
            Assert.AreEqual(subject, _emailNotificationMessage.Subject);
            Assert.AreEqual(body, _emailNotificationMessage.Body);
        }
        internal async Task <IEnumerable <EmailNotificationMessage <CostNotificationObject> > > Build(dataAccess.Entity.Cost cost, CostNotificationUsers costUsers, string approvedByName, CostStageRevision costStageRevision, DateTime timestamp)
        {
            var notifications = new List <EmailNotificationMessage <CostNotificationObject> >();

            //Cost Owner
            var costOwner             = costUsers.CostOwner;
            var costOwnerNotification = new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.ReopenApproved, costOwner.GdamUserId);

            AddSharedTo(costOwnerNotification);

            MapEmailNotificationObject(costOwnerNotification.Object, cost, costOwner);
            PopulateOtherFields(costOwnerNotification, string.Empty, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(costOwnerNotification.Object, cost.Id);

            costOwnerNotification.Object.Approver.Name = approvedByName;
            notifications.Add(costOwnerNotification);

            return(notifications);
        }
Ejemplo n.º 27
0
        public async Task RegistrationEmailNotification_SentNotification()
        {
            //Arrange
            var language     = "default";
            var subject      = "Your login - {{ login }}.";
            var body         = "Thank you for registration {{ firstname }} {{ lastname }}!!!";
            var notification = new RegistrationEmailNotification()
            {
                FirstName = "First Name",
                LastName  = "Last Name",
                Login     = "******",
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject = subject,
                        Body    = body,
                    }
                },
                LanguageCode = language,
                IsActive     = true
            };
            var date    = new DateTime(2018, 02, 20, 10, 00, 00);
            var message = new EmailNotificationMessage()
            {
                Id       = "1",
                From     = "*****@*****.**",
                To       = "*****@*****.**",
                Subject  = subject,
                Body     = body,
                SendDate = date
            };

            _messageServiceMock.Setup(ms => ms.GetNotificationsMessageByIds(It.IsAny <string[]>()))
            .ReturnsAsync(new[] { message });

            //Act
            var result = await _sender.SendNotificationAsync(notification);

            //Assert
            Assert.True(result.IsSuccess);
        }
        internal async Task <IEnumerable <EmailNotificationMessage <CostNotificationObject> > > Build(
            Cost cost,
            CostNotificationUsers costUsers,
            CostStageRevision costStageRevision,
            DateTime timestamp,
            CostUser changeApprover,
            CostUser previousOwner)
        {
            var    notifications = new List <EmailNotificationMessage <CostNotificationObject> >();
            string actionType    = core.Constants.EmailNotificationActionType.CostOwnerChanged;
            var    costOwner     = costUsers.CostOwner;

            //add recipients
            var recipients = new List <string> {
                costOwner.GdamUserId
            };

            if (costUsers.Watchers != null)
            {
                recipients.AddRange(costUsers.Watchers);
            }
            if (costUsers.Approvers != null)
            {
                recipients.AddRange(costUsers.Approvers);
            }
            recipients.Add(previousOwner.GdamUserId);

            var costOwnerNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, recipients.Distinct());

            AddSharedTo(costOwnerNotification);
            MapEmailNotificationObject(costOwnerNotification.Object, cost, costOwner);
            costOwnerNotification.Object.Cost.PreviousOwner = previousOwner.FullName;
            var approver = costOwnerNotification.Object.Approver;

            approver.Name = changeApprover.FullName;
            PopulateOtherFields(costOwnerNotification, core.Constants.EmailNotificationParents.CostOwner, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(costOwnerNotification.Object, cost.Id);

            notifications.Add(costOwnerNotification);

            return(notifications);
        }
Ejemplo n.º 29
0
        public async Task EmailNotification_SuccessSend()
        {
            //Arrange
            string language     = null;
            var    subject      = "some subject";
            var    body         = "some body";
            var    notification = new RegistrationEmailNotification()
            {
                Templates = new List <NotificationTemplate>()
                {
                    new EmailNotificationTemplate()
                    {
                        Subject = subject,
                        Body    = body,
                    }
                },
                TenantIdentity = new TenantIdentity(null, null),
                LanguageCode   = language,
                IsActive       = true
            };

            var message = new EmailNotificationMessage()
            {
                Id             = "1",
                From           = "*****@*****.**",
                To             = "*****@*****.**",
                Subject        = subject,
                Body           = body,
                SendDate       = DateTime.Now,
                TenantIdentity = new TenantIdentity(null, null)
            };

            _messageServiceMock.Setup(ms => ms.GetNotificationsMessageByIds(It.IsAny <string[]>()))
            .ReturnsAsync(new[] { message });

            //Act
            var result = await _sender.SendNotificationAsync(notification);

            //Assert
            Assert.True(result.IsSuccess);
        }
        protected async Task <EmailNotificationMessage <CostNotificationObject> > AddFinanceManagerNotification(
            string actionType,
            Cost cost,
            CostNotificationUsers costUsers,
            CostStageRevision costStageRevision,
            DateTime timestamp,
            List <EmailNotificationMessage <CostNotificationObject> > notifications
            )
        {
            //Only send to North American P&G Finance Users when Budget Region is North America and Cyclone costs
            if (costUsers.FinanceManagementUsers == null ||
                !costUsers.FinanceManagementUsers.Any() ||
                Constants.BudgetRegion.NorthAmerica != GetBudgetRegion(costStageRevision) ||
                !costUsers.CostOwner.Agency.IsCyclone())
            {
                return(null);
            }

            //Send to FinanceManagement as well
            var financeManagementNotification =
                new EmailNotificationMessage <CostNotificationObject>(actionType, costUsers.FinanceManagementUsers);
            var notificationObject = new FinanceManagerCostNotificationObject();

            financeManagementNotification.Object = notificationObject;
            var parent = core.Constants.EmailNotificationParents.FinanceManagement;

            AddSharedTo(financeManagementNotification);
            MapEmailNotificationObject(financeManagementNotification.Object, cost, costUsers);
            PopulateOtherFields(financeManagementNotification, parent, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(financeManagementNotification.Object, cost.Id);

            notifications.Add(financeManagementNotification);

            if (cost.Status == CostStageRevisionStatus.Approved && cost.LatestCostStageRevision.CostStage.Key == Models.Stage.CostStages.OriginalEstimate.ToString())
            {
                notificationObject.CanAssignIONumber = true;
            }

            return(financeManagementNotification);
        }