/// <summary>
        /// <para>Adds a notification recipient for an account.</para>
        /// </summary>
        /// <param name="accountId">The id of the account for which a recipient should be added.</param>
        /// <param name="twitterHandle">The twitter handle for the recipient.</param>
        /// <param name="description">A short description for the recipient.</param>
        /// <returns>Returns a validation result object.</returns>
        internal IValidationResult AddNotificationRecipient(int accountId, string twitterHandle, string description)
        {
            IValidationResult validationResult = new ValidationResult();

            // Populate a new account object.
            NotificationRecipient newNotificationRecipient = new NotificationRecipient();

            // Populate the remaining properties.
            newNotificationRecipient.AccountId            = accountId;
            newNotificationRecipient.TwitterHandle        = twitterHandle;
            newNotificationRecipient.Description          = description;
            newNotificationRecipient.ReceivesDailySummary = true;
            newNotificationRecipient.ReceivesAlerts       = true;
            newNotificationRecipient.AlertIntervalHours   = 12;
            newNotificationRecipient.Method    = NotificationMethod.DirectMessage;
            newNotificationRecipient.LastAlert = DateTime.UtcNow;

            // Validate the new notification recipient.
            validationResult = this.doctrineShipsValidation.NotificationRecipient(newNotificationRecipient);
            if (validationResult.IsValid == true)
            {
                // Add the new notification recipient.
                this.doctrineShipsRepository.CreateNotificationRecipient(newNotificationRecipient);
                this.doctrineShipsRepository.Save();

                // Log the addition.
                logger.LogMessage("Notification Recipient '" + newNotificationRecipient.Description + "' Successfully Added For Account Id: " + newNotificationRecipient.AccountId, 2, "Message", MethodBase.GetCurrentMethod().Name);
            }

            return(validationResult);
        }
        private async Task SendToRecipientAsync(
            Notification notification,
            NotificationRecipient recipient,
            string message)
        {
            if (notification is EmailNotification email)
            {
                await _emailSender.SendEmailAsync(new EmailModel
                {
                    Recipients = new[]
                    {
                        new Address(
                            recipient.RecipientName,
                            recipient.RecipientIdentifier)
                    },
                    Subject  = email.Subject,
                    HtmlBody = message
                });
            }

            if (notification is SmsNotification)
            {
                await _smsSender.SendSmsAsync(recipient.RecipientIdentifier, message);
            }
        }
        public NotificationSendLogRow CreateNotificationMessage(Notification notification,
                                                                 string composedContent,
                                                                 string composedSubject,
                                                                 NotificationRecipient rec,
                                                                 NotificationMessageTemplateTypeDictionary notificationMessageTemplateType,
                                                                 Guid tryGroupId)
        {
            var status = SendStatusDictionary.ErrorOnCompose;
            string sendedSubject = "";
            string sendedContent = "";

            if (composedContent != null && composedSubject != null)
            {
                status = SendStatusDictionary.NeedToSend;
                sendedSubject = composedSubject;
                sendedContent = composedContent;
            }

            var rez = new NotificationSendLogRow
            {
                Notification = notification,
                Recipient = rec,
                SendDateTime = DateTime.Now,
                SendTryGroupId = tryGroupId,
                SendType = notificationMessageTemplateType,
                SendStatus = status,
                SendedSubject = sendedSubject,
                SendedContent = sendedContent,
            };
            return rez;
        }
        public ActionResult UpdateNotificationRecipients(AccountNotificationRecipientsViewModel viewModel)
        {
            if (viewModel != null)
            {
                // Create an Auto Mapper map between the notification recipient entity and the view model.
                Mapper.CreateMap <AccountNotificationRecipientsViewModel, NotificationRecipient>();

                // Convert the currently logged-in account id to an integer.
                viewModel.AccountId = Conversion.StringToInt32(User.Identity.Name);

                // Populate a notification recipient with automapper and pass it back to the service layer for update.
                NotificationRecipient notificationRecipient = Mapper.Map <AccountNotificationRecipientsViewModel, NotificationRecipient>(viewModel);
                IValidationResult     validationResult      = this.doctrineShipsServices.UpdateNotificationRecipient(notificationRecipient);

                // If the validationResult is not valid, something did not validate in the service layer.
                if (validationResult.IsValid)
                {
                    TempData["Status"] = "The notification recipient was successfully updated.";
                }
                else
                {
                    TempData["Status"] = "Error: The notification recipient was not updated, a validation error occured.<br /><b>Error Details: </b>";

                    foreach (var error in validationResult.Errors)
                    {
                        TempData["Status"] += error.Value + "<br />";
                    }
                }
            }

            return(RedirectToAction("NotificationRecipients"));
        }
        /// <summary>
        /// Updates a notification recipient for a particular account.
        /// </summary>
        /// <param name="notificationRecipient">A partially populated notification recipient object to be updated.</param>
        /// <returns>Returns a validation result object.</returns>
        internal IValidationResult UpdateNotificationRecipient(NotificationRecipient notificationRecipient)
        {
            IValidationResult validationResult = new ValidationResult();

            var existingNotificationRecipient = this.doctrineShipsRepository.GetNotificationRecipient(notificationRecipient.NotificationRecipientId);

            if (existingNotificationRecipient != null)
            {
                if (existingNotificationRecipient.AccountId != notificationRecipient.AccountId)
                {
                    validationResult.AddError("NotificationRecipient.Permission", "The notification recipient being modified does not belong to the requesting account.");
                }
                else
                {
                    // Map the updates to the existing notification recipient.
                    existingNotificationRecipient.AlertIntervalHours   = notificationRecipient.AlertIntervalHours;
                    existingNotificationRecipient.ReceivesAlerts       = notificationRecipient.ReceivesAlerts;
                    existingNotificationRecipient.ReceivesDailySummary = notificationRecipient.ReceivesDailySummary;

                    // Validate the notification recipient updates.
                    validationResult = this.doctrineShipsValidation.NotificationRecipient(existingNotificationRecipient);
                    if (validationResult.IsValid == true)
                    {
                        // Update the existing record, save and log.
                        this.doctrineShipsRepository.UpdateNotificationRecipient(existingNotificationRecipient);
                        this.doctrineShipsRepository.Save();
                        logger.LogMessage("Notification Recipient '" + existingNotificationRecipient.Description + "' Successfully Updated For Account Id: " + existingNotificationRecipient.AccountId, 2, "Message", MethodBase.GetCurrentMethod().Name);
                    }
                }
            }

            return(validationResult);
        }
        /// <summary>
        /// Add the EmailSource.
        /// </summary>
        private static void AddEmailSource(PXGraph graph, int?sourceEmailID, RecipientList recipients)
        {
            NotificationRecipient recipient = null;

            EMailAccount emailAccountRow = PXSelect <EMailAccount,
                                                     Where <
                                                         EMailAccount.emailAccountID, Equal <Required <EMailAccount.emailAccountID> > > >
                                           .Select(graph, sourceEmailID);

            if (emailAccountRow != null && emailAccountRow.Address != null)
            {
                recipient = new NotificationRecipient()
                {
                    Active = true,
                    Email  = emailAccountRow.Address,
                    Hidden = false,
                    Format = "H"
                };

                if (recipient != null)
                {
                    recipients.Add(recipient);
                }
            }
        }
Beispiel #7
0
        internal IValidationResult NotificationRecipient(NotificationRecipient notificationRecipient)
        {
            IValidationResult validationResult = new ValidationResult();

            // Null checks.
            if (notificationRecipient.TwitterHandle == null)
            {
                validationResult.AddError("TwitterHandle.Null", "TwitterHandle cannot be null.");
            }

            if (notificationRecipient.Description == null || notificationRecipient.Description == string.Empty)
            {
                validationResult.AddError("Description.Null", "Description cannot be null or an empty string.");
            }

            // Regex checks.
            if (notificationRecipient.TwitterHandle != null)
            {
                if (!Regex.Match(notificationRecipient.TwitterHandle, "^@(\\w){1,15}$").Success)
                {
                    validationResult.AddError("TwitterHandle.Format", "Invalid twitter handle.");
                }
            }

            // Range checks.
            if (notificationRecipient.AlertIntervalHours < 1 || notificationRecipient.AlertIntervalHours > 168)
            {
                validationResult.AddError("AlertIntervalHours.Range", "AlertIntervalHours is outside of expected ranges. AlertIntervalHours should be between 1 and 168 hours (one week).");
            }

            return(validationResult);
        }
Beispiel #8
0
        private async Task PublishViaMethod(Notification notification, NotificationMethod method, int userId)
        {
            NotificationRecipient model = null;

            switch (method)
            {
            case NotificationMethod.Default:
            {
                model = new NotificationRecipient()
                {
                    Method         = method,
                    NotificationId = notification.Id,
                    ToUserId       = userId,
                };
            }
            break;

            case NotificationMethod.Email:
            {
                model = new NotificationRecipient()
                {
                    Method         = method,
                    NotificationId = notification.Id,
                    ToUserId       = userId,
                    WhenDelivered  = DateTime.UtcNow,
                };

                // send email;
                // notification.DeliveryCount++; // delivery successful
            }
            break;

            case NotificationMethod.SMS:
            {
                model = new NotificationRecipient()
                {
                    Method         = method,
                    NotificationId = notification.Id,
                    ToUserId       = userId,
                    WhenDelivered  = DateTime.UtcNow,
                    WhenViewed     = DateTime.UtcNow,
                    WhenDismissed  = DateTime.UtcNow,
                };

                // send text;
                //notification.DeliveryCount++; // delivery successful
            }
            break;
            }

            if (model != null)
            {
                await _db.Recipients.AddAsync(model);

                await _db.SaveChangesAsync();
            }
        }
Beispiel #9
0
        public async Task UpdateNotificationRecipientAsync(NotificationRecipient recipient)
        {
            if (recipient == null)
            {
                throw new ArgumentNullException(nameof(recipient));
            }

            await _context.UpdateAsync(recipient);
        }
Beispiel #10
0
        private async Task <List <NotificationRecipient> > GetRecipientsAsync(
            NotificationType notificationType,
            int eventId,
            int?productId,
            Registration.RegistrationStatus[] registrationStatuses,
            Registration.RegistrationType[] registrationTypes)
        {
            var recipients = new List <NotificationRecipient>();

            // Default status if not provided: Verified, attended and finished
            registrationStatuses ??= new[]
            {
                Registration.RegistrationStatus.Verified,
                Registration.RegistrationStatus.Attended,
                Registration.RegistrationStatus.Finished
            };

            // Default registration type is participants
            registrationTypes ??= new[]
            {
                Registration.RegistrationType.Participant
            };

            var reader = new PageReader <Registration>(async(offset, limit, token) =>
                                                       await _registrationRetrievalService.ListRegistrationsAsync(
                                                           new RegistrationListRequest
            {
                Limit  = limit,
                Offset = offset,
                Filter = new RegistrationFilter
                {
                    EventInfoId = eventId,
                    ProductIds  = productId.HasValue
                                ? new[] { productId.Value }
                                : null,
                    ActiveUsersOnly = true,
                    HavingStatuses  = registrationStatuses,
                    HavingTypes     = registrationTypes
                }
            },
                                                           new RegistrationRetrievalOptions
            {
                LoadUser  = true,
                ForUpdate = true
            }, token));

            while (await reader.HasMoreAsync())
            {
                recipients.AddRange((from registration in await reader
                                     .ReadNextAsync()
                                     select NotificationRecipient.Create(registration, notificationType))
                                    .Where(r => r != null)); // user may have no phone, or email
            }

            return(recipients);
        }
Beispiel #11
0
    internal static void AddNotificationRecipient(AdminCenterClient adminCenterClient, string emailAddress, string name)
    {
        var notificationRecipient = new NotificationRecipient
        {
            Email = emailAddress,
            Name  = name,
        };
        NotificationRecipient addedNotificationRecipient = adminCenterClient.SetNotificationRecipient(notificationRecipient);

        Utils.ConsoleWriteLineAsJson(addedNotificationRecipient);
    }
Beispiel #12
0
        /// <summary>
        /// Add the Customer info as a recipient in the Email template generated by Appointment.
        /// </summary>
        private static void AddCustomerRecipient(AppointmentEntry graphAppointmentEntry, NotificationRecipient recSetup, RecipientList recipients)
        {
            NotificationRecipient recipient = null;

            Customer customerRow = PXSelect <Customer,
                                             Where <
                                                 Customer.bAccountID, Equal <Required <Customer.bAccountID> > > >
                                   .Select(graphAppointmentEntry, graphAppointmentEntry.ServiceOrderRelated.Current.CustomerID);

            if (customerRow == null)
            {
                return;
            }

            FSxCustomer fsxCustomerRow = PXCache <Customer> .GetExtension <FSxCustomer>(customerRow);

            if (fsxCustomerRow.SendAppNotification == true)
            {
                if (graphAppointmentEntry.ServiceOrderRelated.Current.EMail != null)
                {
                    recipient = new NotificationRecipient()
                    {
                        Active = true,
                        Email  = graphAppointmentEntry.ServiceOrderRelated.Current.EMail,
                        Hidden = recSetup.Hidden,
                        Format = recSetup.Format
                    };
                }
                else
                {
                    Contact srvOrdContactRow = PXSelect <Contact,
                                                         Where <
                                                             Contact.contactID, Equal <Required <Contact.contactID> > > >
                                               .Select(graphAppointmentEntry, graphAppointmentEntry.ServiceOrderRelated.Current.ContactID);

                    if (srvOrdContactRow != null && srvOrdContactRow.EMail != null)
                    {
                        recipient = new NotificationRecipient()
                        {
                            Active = true,
                            Email  = srvOrdContactRow.EMail,
                            Hidden = recSetup.Hidden,
                            Format = recSetup.Format
                        };
                    }
                }

                if (recipient != null)
                {
                    recipients.Add(recipient);
                }
            }
        }
        public async Task <IActionResult> PostNotificationRecipient([FromBody] NotificationRecipient notificationRecipient)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.NotificationRecipient.Add(notificationRecipient);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetNotificationRecipient", new { id = notificationRecipient.Id }, notificationRecipient));
        }
        /// <summary>
        /// Add the Employee(s) info as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddEmployeeStaffRecipient(AppointmentEntry graphAppointmentEntry,
                                                      int?bAccountID,
                                                      string type,
                                                      NotificationRecipient recSetup,
                                                      RecipientList recipients)
        {
            NotificationRecipient recipient = null;
            Contact contactRow = null;

            if (type == BAccountType.EmployeeType)
            {
                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <
                                                          BAccount.parentBAccountID, Equal <Contact.bAccountID>,
                                                          And <BAccount.defContactID, Equal <Contact.contactID> > > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <
                                                   BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }
            else if (type == BAccountType.VendorType)
            {
                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <
                                                          Contact.contactID, Equal <BAccount.defContactID> > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <
                                                   BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }

            if (contactRow != null && contactRow.EMail != null)
            {
                recipient = new NotificationRecipient()
                {
                    Active = true,
                    Email  = contactRow.EMail,
                    Hidden = recSetup.Hidden,
                    Format = recSetup.Format
                };

                if (recipient != null)
                {
                    recipients.Add(recipient);
                }
            }
        }
Beispiel #15
0
        private void PopulateRecipientStackPanel()
        {
            //First clear the stackpanel.
            RecipientEmailsStack.Children.Clear();

            SettingsPropertyCollection settings = Properties.RecipientSettings.Default.Properties;

            foreach (SettingsProperty setting in settings)
            {
                NotificationRecipient recipient = new NotificationRecipient();
                recipient.RecipientEmail.Text = setting.DefaultValue.ToString();
                RecipientEmailsStack.Children.Add(recipient);
            }
        }
Beispiel #16
0
        public async void CreateNewNotification(string messageBody)
        {
            var activity = new NotificationRecipient()
            {
                Id          = Guid.NewGuid().ToString(),
                MessageBody = messageBody,
                DateSaved   = DateTime.UtcNow
            };

            using (var reps = new AccessCosmos.NotificationRepository())
            {
                await reps.CreateAsync(activity);
            }
        }
Beispiel #17
0
 public static void CheckNotificationRecipient(this JToken token, NotificationRecipient recipient)
 {
     Assert.NotEmpty(token);
     Assert.Equal(recipient.RecipientId, token.Value <int>("recipientId"));
     Assert.Equal(recipient.NotificationId, token.Value <int>("notificationId"));
     Assert.Equal(recipient.RecipientUserId, token.Value <string>("recipientUserId"));
     Assert.Equal(recipient.RegistrationId, token.Value <int?>("registrationId"));
     Assert.Equal(recipient.RecipientName, token.Value <string>("recipientName"));
     Assert.Equal(recipient.RecipientIdentifier, token.Value <string>("recipientIdentifier"));
     Assert.Equal(recipient.Created.ToString("yyyy-MM-ddTHH:mm:ss"),
                  token.Value <DateTime>("created").ToString("yyyy-MM-ddTHH:mm:ss"));
     Assert.Equal(recipient.Sent?.ToString("yyyy-MM-ddTHH:mm:ss"),
                  token.Value <DateTime?>("sent")?.ToString("yyyy-MM-ddTHH:mm:ss"));
     Assert.Equal(recipient.Errors, token.Value <string>("errors"));
 }
Beispiel #18
0
        /// <summary>
        /// Add the Employee email that has assigned the salesperson as a recipient in the Email template generated by Appointment.
        /// </summary>
        private static void AddSalespersonRecipient(AppointmentEntry graphAppointmentEntry, NotificationRecipient recSetup, RecipientList recipients)
        {
            NotificationRecipient recipient = null;
            bool?appNotification            = false;

            PXResult <SalesPerson, EPEmployee, BAccount, Contact> bqlResult =
                (PXResult <SalesPerson, EPEmployee, BAccount, Contact>) PXSelectJoin <SalesPerson,
                                                                                      InnerJoin <EPEmployee,
                                                                                                 On <EPEmployee.salesPersonID, Equal <SalesPerson.salesPersonID> >,
                                                                                                 InnerJoin <BAccount,
                                                                                                            On <BAccount.bAccountID, Equal <EPEmployee.bAccountID> >,
                                                                                                            InnerJoin <Contact,
                                                                                                                       On <BAccount.parentBAccountID, Equal <Contact.bAccountID>,
                                                                                                                           And <BAccount.defContactID, Equal <Contact.contactID> > > > > >,
                                                                                      Where <
                                                                                          SalesPerson.salesPersonID, Equal <Required <FSAppointment.salesPersonID> > > >
                .Select(graphAppointmentEntry, graphAppointmentEntry.AppointmentRecords.Current.SalesPersonID);

            Contact     contactRow     = (Contact)bqlResult;
            BAccount    baccountRow    = (BAccount)bqlResult;
            EPEmployee  epEmployeeRow  = (EPEmployee)bqlResult;
            SalesPerson SalespersonRow = (SalesPerson)bqlResult;

            if (epEmployeeRow != null && SalespersonRow != null)
            {
                FSxEPEmployee fsxEpEmployeeRow = PXCache <EPEmployee> .GetExtension <FSxEPEmployee>(epEmployeeRow);

                appNotification = fsxEpEmployeeRow.SendAppNotification;

                if (appNotification == true)
                {
                    if (contactRow != null && contactRow.EMail != null)
                    {
                        recipient = new NotificationRecipient()
                        {
                            Active = true,
                            Email  = contactRow.EMail,
                            Hidden = recSetup.Hidden,
                            Format = recSetup.Format
                        };
                        if (recipient != null)
                        {
                            recipients.Add(recipient);
                        }
                    }
                }
            }
        }
Beispiel #19
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap   = context.JobDetail.JobDataMap;
            var        groupGuid = dataMap.Get("NotificationGroup").ToString().AsGuid();

            var rockContext = new RockContext();
            var group       = new GroupService(rockContext).Get(groupGuid);

            if (group != null)
            {
                var notifications = Utility.SparkLinkHelper.SendToSpark(rockContext);
                if (notifications.Count == 0)
                {
                    return;
                }

                var notificationService = new NotificationService(rockContext);
                foreach (var notification in notifications.ToList())
                {
                    if (notificationService.Get(notification.Guid) == null)
                    {
                        notificationService.Add(notification);
                    }
                    else
                    {
                        notifications.Remove(notification);
                    }
                }
                rockContext.SaveChanges();

                var notificationRecipientService = new NotificationRecipientService(rockContext);
                foreach (var notification in notifications)
                {
                    foreach (var member in group.Members)
                    {
                        if (member.Person.PrimaryAliasId.HasValue)
                        {
                            var recipientNotification = new NotificationRecipient();
                            recipientNotification.NotificationId = notification.Id;
                            recipientNotification.PersonAliasId  = member.Person.PrimaryAliasId.Value;
                            notificationRecipientService.Add(recipientNotification);
                        }
                    }
                }
                rockContext.SaveChanges();
            }
        }
Beispiel #20
0
        /// <summary>
        /// Add the Employee info defined in the Notification tab defined in the <c>SrvOrdType</c> as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddEmployeeRecipient(PXGraph graph, NotificationRecipient recSetup, RecipientList recipients)
        {
            NotificationRecipient recipient = null;
            bool?appNotification            = false;

            PXResult <Contact, BAccount, EPEmployee> bqlResult =
                (PXResult <Contact, BAccount, EPEmployee>) PXSelectJoin <Contact,
                                                                         InnerJoin <BAccount,
                                                                                    On <Contact.bAccountID, Equal <BAccount.parentBAccountID>,
                                                                                        And <Contact.contactID, Equal <BAccount.defContactID> > >,
                                                                                    InnerJoin <EPEmployee,
                                                                                               On <EPEmployee.bAccountID, Equal <BAccount.bAccountID> > > >,
                                                                         Where <
                                                                             Contact.contactID, Equal <Required <Contact.contactID> >,
                                                                             And <BAccount.type, Equal <Required <BAccount.type> > > > >
                .Select(graph, recSetup.ContactID, BAccountType.EmployeeType);

            Contact    contactRow    = (Contact)bqlResult;
            BAccount   baccountRow   = (BAccount)bqlResult;
            EPEmployee epEmployeeRow = (EPEmployee)bqlResult;

            if (epEmployeeRow != null)
            {
                FSxEPEmployee fsxEpEmployeeRow = PXCache <EPEmployee> .GetExtension <FSxEPEmployee>(epEmployeeRow);

                appNotification = fsxEpEmployeeRow.SendAppNotification;

                if (appNotification == true)
                {
                    if (contactRow != null && contactRow.EMail != null)
                    {
                        recipient = new NotificationRecipient()
                        {
                            Active = true,
                            Email  = contactRow.EMail,
                            Hidden = recSetup.Hidden,
                            Format = recSetup.Format
                        };
                        if (recipient != null)
                        {
                            recipients.Add(recipient);
                        }
                    }
                }
            }
        }
        public NotificationRecipientDto(NotificationRecipient recipient)
        {
            if (recipient == null)
            {
                throw new ArgumentNullException(nameof(recipient));
            }

            RecipientId         = recipient.RecipientId;
            NotificationId      = recipient.NotificationId;
            RecipientUserId     = recipient.RecipientUserId;
            RegistrationId      = recipient.RegistrationId;
            RecipientName       = recipient.RecipientName;
            RecipientIdentifier = recipient.RecipientIdentifier;
            Created             = recipient.Created;
            Sent   = recipient.Sent;
            Errors = recipient.Errors;
        }
Beispiel #22
0
        public void WithNotificationDelayGtLastNotificationSentAtReturnsCorrectResult()
        {
            //Arrange
            var  sentAt = DateTime.UtcNow.AddMinutes(-5);
            User user   = new User {
                EmailAdress = "*****@*****.**"
            };
            Notification notification = new Notification {
                IsEnabled = true, Name = "Test Notification", Type = NotificationType.Warning
            };
            NotificationRecipient notificationRecipient = new NotificationRecipient {
                Delay = new TimeSpan(0, 0, 30), DeliveryMode = DeliveryMode.Email, Notification = notification, NotificationsPerEvent = 5, User = user
            };
            NotificationEvent notificationEvent = new NotificationEvent {
                Active = true, LastAlertTime = DateTime.UtcNow, Notification = notification, Value = "Test Failed"
            };
            NotificationEventLog notificationEventLog = new NotificationEventLog {
                NotificationEvent = notificationEvent, NotificationRecipient = notificationRecipient, SentAt = sentAt
            };
            NotificationEvent result;

            using (var context = new AppDbContext())
            {
                context.Users.Add(user);
                context.NotificationEventLogs.Add(notificationEventLog);
                context.SaveChanges();
            }
            //Act
            using (var context = new AppDbContext())
            {
                result = context.NotificationEvents.WithNotificationDelayGtLastNotificationSentAt(DateTime.UtcNow).FirstOrDefault();
            }

            using (var context = new AppDbContext())
            {
                context.NotificationEventLogs.Remove(notificationEventLog);
                context.NotificationEvents.Remove(notificationEvent);
                context.NotificationRecipients.Remove(notificationRecipient);
                context.Notifications.Remove(notification);
                context.Users.Remove(user);
                context.SaveChanges();
            }
            //Assert
            Assert.IsNotNull(result);
        }
        /// <summary>
        /// Add the Vendor(s) info as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddVendorStaffRecipient(AppointmentEntry graphAppointmentEntry,
                                                    FSAppointmentEmployee fsAppointmentEmployee,
                                                    NotificationRecipient recSetup,
                                                    RecipientList recipients)
        {
            //TODO: AC-142850 6082 validate Vendor's AppNotification flag

            /*
             *  select * from Contact
             *  inner join BAccount on (BAccount.BAccountID = Contact.BAccountID
             *              and BAccount.DefContactID = Contact.ContactID)
             *  where
             *  BAccount.BAccountID = xx
             *  and BAccount.Type = 'VE'
             */

            //BAccountType.VendorType
        }
Beispiel #24
0
        public void SendSensorNotificationsWithActiveNotifyingEventSensEmail()
        {
            var lastAlertTime = DateTime.UtcNow.AddMinutes(-5);
            var notification  = new Notification {
                IsEnabled = true, Type = NotificationType.Warning, Name = "Test Notification"
            };
            var notificationEvent = new NotificationEvent {
                LastAlertTime = lastAlertTime, Notification = notification, Active = true, Value = "Alert 1"
            };
            var user = new User {
                EmailAdress = "*****@*****.**"
            };
            var recipient = new NotificationRecipient {
                User = user, Delay = new TimeSpan(0, 0, 30), DeliveryMode = DeliveryMode.Email, Notification = notification
            };

            //Setup Mock for Add
            var mockSet     = new Mock <DbSet <NotificationEventLog> >();
            var mockContext = new Mock <AppDbContext>();

            mockContext.Setup(m => m.NotificationEventLogs).Returns(mockSet.Object);

            var mockEmailService = new Mock <IMessageService>();

            var mockNotificationEventService = new Mock <INotificationEventService>();

            mockNotificationEventService.Setup(m => m.GetActiveSignalingNotificationEvents(It.IsAny <DateTime>())).Returns(new List <NotificationEvent> {
                notificationEvent
            });
            mockNotificationEventService.Setup(m => m.GetActiveSignallingRecipientsForNotificationEvent(notificationEvent, It.IsAny <DateTime>())).Returns(new List <NotificationRecipient> {
                recipient
            });

            //Act
            var sensorNotificationService = new NotificationService(mockContext.Object, mockNotificationEventService.Object, mockEmailService.Object, null);

            sensorNotificationService.SendNotifications(DateTime.UtcNow);

            //Assert
            mockSet.Verify(m => m.Add(It.IsAny <NotificationEventLog>()), Times.Once());
            mockContext.Verify(m => m.SaveChangesAsync(), Times.Once());
            mockEmailService.Verify(m => m.SendAsync(It.IsAny <Message>()), Times.Once);
        }
        /// <summary>
        /// Add the Billing Customer info as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddBillingRecipient(AppointmentEntry graphAppointmentEntry, NotificationRecipient recSetup, RecipientList recipients)
        {
            NotificationRecipient recipient = null;

            if (graphAppointmentEntry.ServiceOrderRelated.Current.BillCustomerID != null)
            {
                Customer customerRow = PXSelect <Customer,
                                                 Where <
                                                     Customer.bAccountID, Equal <Required <Customer.bAccountID> > > >
                                       .Select(graphAppointmentEntry, graphAppointmentEntry.ServiceOrderRelated.Current.BillCustomerID);

                if (customerRow == null)
                {
                    return;
                }

                Contact contactRow = PXSelectJoin <Contact,
                                                   InnerJoin <Customer,
                                                              On <
                                                                  Contact.bAccountID, Equal <Customer.bAccountID>,
                                                                  And <Contact.contactID, Equal <Customer.defBillContactID> > > >,
                                                   Where <
                                                       Customer.bAccountID, Equal <Required <Customer.bAccountID> > > >
                                     .Select(graphAppointmentEntry, graphAppointmentEntry.ServiceOrderRelated.Current.BillCustomerID);

                if (contactRow != null && contactRow.EMail != null)
                {
                    recipient = new NotificationRecipient()
                    {
                        Active = true,
                        Email  = contactRow.EMail,
                        Hidden = recSetup.Hidden,
                        Format = recSetup.Format
                    };
                }
            }

            if (recipient != null)
            {
                recipients.Add(recipient);
            }
        }
Beispiel #26
0
        private void SendEmail(NotificationRecipient notificationRecipient,
                               NotificationSourceModel notificationSourceModel, ComplianceDocument complianceDocument)
        {
            var email = RecipientEmailDataProvider
                        .GetRecipientEmail(notificationRecipient, notificationSourceModel.VendorId);

            if (email != null)
            {
                var report = GetReportInAppropriateFormat(notificationRecipient.Format,
                                                          notificationSourceModel, complianceDocument);
                var sender = TemplateNotificationGenerator.Create(complianceDocument,
                                                                  notificationSourceModel.NotificationSource.NotificationID);
                sender.MailAccountId = notificationSourceModel.NotificationSource.EMailAccountID;
                sender.RefNoteID     = complianceDocument.NoteID;
                sender.To            = email;
                sender.AddAttachmentLink(report.ReportFileInfo.UID.GetValueOrDefault());
                sender.Send();
                UpdateLienWaiverProcessedStatus(complianceDocument);
            }
        }
        /// <summary>
        /// <para>Deletes a notification recipient from an accountId and a notificationRecipientId.</para>
        /// </summary>
        /// <param name="accountId">The account Id of the requestor. The account Id should own the notification recipient being deleted.</param>
        /// <param name="notificationRecipientId">The Id of the notification recipient to be deleted.</param>
        /// <returns>Returns true if the deletion was successful or false if not.</returns>
        internal bool DeleteNotificationRecipient(int accountId, int notificationRecipientId)
        {
            NotificationRecipient notificationRecipient = this.doctrineShipsRepository.GetNotificationRecipient(notificationRecipientId);

            if (notificationRecipient != null)
            {
                // If the account Id matches the account Id of the notification recipient being deleted, continue.
                if (accountId == notificationRecipient.AccountId)
                {
                    // Delete the notification recipient and log the event.
                    this.doctrineShipsRepository.DeleteNotificationRecipient(notificationRecipient.NotificationRecipientId);
                    this.doctrineShipsRepository.Save();
                    logger.LogMessage("Notification Recipient '" + notificationRecipient.Description + "' Successfully Deleted For Account Id: " + notificationRecipient.AccountId, 1, "Message", MethodBase.GetCurrentMethod().Name);

                    return(true);
                }
            }

            return(false);
        }
        public string GetRecipientEmail(NotificationRecipient notificationRecipient, int?vendorId)
        {
            switch (notificationRecipient.ContactType)
            {
            case NotificationContactType.Primary:
                return(GetEmailForPrimaryVendor(vendorId));

            case NotificationContactType.Employee:
                return(GetContactEmail(notificationRecipient.ContactID));

            case NotificationContactType.Remittance:
                return(GetEmailForRemittanceContact(vendorId));

            case NotificationContactType.Shipping:
                return(GetEmailForShippingContact(vendorId));

            default:
                return(GetContactEmail(notificationRecipient.ContactID));
            }
        }
        public void WithNotificationDelayGtLastNotificationSentAtReturnsCorrectResult()
        {
            var sentAt       = DateTime.UtcNow.AddMinutes(-5);
            var notification = new Notification {
                IsEnabled = true
            };
            var notificationRecipient1 = new NotificationRecipient {
                Delay = new TimeSpan(0, 0, 10), Notification = notification
            };
            var notificationEvent1 = new NotificationEvent {
                Notification = notification, Active = true
            };
            var notificationEventLog1 = new NotificationEventLog
            {
                NotificationEvent     = notificationEvent1,
                NotificationRecipient = notificationRecipient1,
                SentAt = sentAt
            };
            var notificationRecipients = new List <NotificationRecipient>
            {
                notificationRecipient1
            };
            var notificationEvents = new List <NotificationEvent>
            {
                notificationEvent1
            };
            var notificationEventLogs = new List <NotificationEventLog>
            {
                notificationEventLog1
            };

            //Add collections
            notification.NotificationRecipients          = notificationRecipients;
            notification.NotificationEvents              = notificationEvents;
            notificationEvent1.NotificationEventLogs     = notificationEventLogs;
            notificationRecipient1.NotificationEventLogs = notificationEventLogs;

            var result = notificationEvents.AsQueryable().WithNotificationDelayGtLastNotificationSentAt(DateTime.UtcNow).FirstOrDefault();

            Assert.IsNotNull(result);
        }
Beispiel #30
0
        /// <summary>
        /// Add the Employee(s) info as a recipient(s) in the Email template generated by Appointment.
        /// </summary>
        private static void AddEmployeeStaffRecipient(
            AppointmentEntry graphAppointmentEntry,
            int?bAccountID,
            string type,
            NotificationRecipient recSetup,
            RecipientList recipients)
        {
            NotificationRecipient recipient = null;
            bool?   appNotification         = false;
            Contact contactRow = null;

            if (type == BAccountType.EmployeeType)
            {
                EPEmployee epEmployeeRow = PXSelect <EPEmployee,
                                                     Where <
                                                         EPEmployee.bAccountID, Equal <Required <EPEmployee.bAccountID> > > >
                                           .Select(graphAppointmentEntry, bAccountID);

                FSxEPEmployee fsxEpEmployeeRow = PXCache <EPEmployee> .GetExtension <FSxEPEmployee>(epEmployeeRow);

                appNotification = fsxEpEmployeeRow.SendAppNotification;

                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <BAccount.parentBAccountID, Equal <Contact.bAccountID>,
                                                          And <BAccount.defContactID, Equal <Contact.contactID> > > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }
            else if (type == BAccountType.VendorType)
            {
                Vendor vendorRow = PXSelect <Vendor,
                                             Where <
                                                 Vendor.bAccountID, Equal <Required <Vendor.bAccountID> > > >
                                   .Select(graphAppointmentEntry, bAccountID);

                FSxVendor fsxVendorRow = PXCache <Vendor> .GetExtension <FSxVendor>(vendorRow);

                appNotification = fsxVendorRow.SendAppNotification;

                contactRow = PXSelectJoin <Contact,
                                           InnerJoin <BAccount,
                                                      On <Contact.contactID, Equal <BAccount.defContactID> > >,
                                           Where <
                                               BAccount.bAccountID, Equal <Required <BAccount.bAccountID> >,
                                               And <BAccount.type, Equal <Required <BAccount.type> > > > >
                             .Select(graphAppointmentEntry, bAccountID, type);
            }

            if (appNotification == true)
            {
                if (contactRow != null && contactRow.EMail != null)
                {
                    recipient = new NotificationRecipient()
                    {
                        Active = true,
                        Email  = contactRow.EMail,
                        Hidden = recSetup.Hidden,
                        Format = recSetup.Format
                    };
                    if (recipient != null)
                    {
                        recipients.Add(recipient);
                    }
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Adds the Employee(s) belonging to the Appointment's Service Area as recipients in the Email template generated by Appointment.
        /// </summary>
        private static void AddGeoZoneStaffRecipient(AppointmentEntry graphAppointmentEntry, NotificationRecipient recSetup, RecipientList recipients)
        {
            List <FSGeoZoneEmp> geoZoneEmpList = new List <FSGeoZoneEmp>();

            if (graphAppointmentEntry.ServiceOrderRelated.Current.PostalCode != null)
            {
                FSGeoZonePostalCode fsGeoZoneRow = StaffSelectionHelper.GetMatchingGeoZonePostalCode(graphAppointmentEntry, graphAppointmentEntry.ServiceOrderRelated.Current.PostalCode);

                if (fsGeoZoneRow != null)
                {
                    var fsGeoZonePostalCodeSet = PXSelectJoin <FSGeoZonePostalCode,
                                                               InnerJoin <FSGeoZoneEmp,
                                                                          On <FSGeoZoneEmp.geoZoneID, Equal <FSGeoZonePostalCode.geoZoneID> > >,
                                                               Where <
                                                                   FSGeoZonePostalCode.postalCode, Equal <Required <FSGeoZonePostalCode.postalCode> > > >
                                                 .Select(graphAppointmentEntry, fsGeoZoneRow.PostalCode);

                    foreach (PXResult <FSGeoZonePostalCode, FSGeoZoneEmp> bqlResult in fsGeoZonePostalCodeSet)
                    {
                        geoZoneEmpList.Add((FSGeoZoneEmp)bqlResult);
                    }
                }
            }

            List <FSGeoZoneEmp> fsGeoZoneEmpGroupByEmployeeID = geoZoneEmpList.GroupBy(x => x.EmployeeID).Select(grp => grp.First()).ToList();

            if (fsGeoZoneEmpGroupByEmployeeID.Count > 0)
            {
                foreach (FSGeoZoneEmp fsGeoZoneEmpRow in fsGeoZoneEmpGroupByEmployeeID)
                {
                    AddEmployeeStaffRecipient(graphAppointmentEntry, fsGeoZoneEmpRow.EmployeeID, BAccountType.EmployeeType, recSetup, recipients);
                }
            }
        }