Пример #1
0
        public async Task ProcessWarningsForReferralStakes()
        {
            var referralStakesForWarning = await _referralStakesRepository.GetStakesForWarningAsync();

            foreach (var stake in referralStakesForWarning)
            {
                var campaignResult = await _campaignClient.History.GetEarnRuleByIdAsync(Guid.Parse(stake.CampaignId));

                if (campaignResult.ErrorCode != CampaignServiceErrorCodes.None)
                {
                    _log.Error(message: "Cannot find campaign for existing stake", context: stake);
                }

                var evt = new PushNotificationEvent
                {
                    CustomerId         = stake.CustomerId,
                    MessageTemplateId  = _pushNotificationsSettingsService.ReferralStakeWarningTemplateId,
                    Source             = _componentSourceName,
                    TemplateParameters =
                        new Dictionary <string, string>
                    {
                        { "Amount", _moneyFormatter.FormatAmountToDisplayString(stake.Amount) },
                        { "Offer", campaignResult.Name }
                    },
                };

                await _pushNotificationsPublisher.PublishAsync(evt);

                await _referralStakesRepository.SetWarningSentAsync(stake.ReferralId);
            }
        }
Пример #2
0
        public void HandlePushNotificationExistingConversationTest()
        {
            List <List <ConversationModel> > conversations = new List <List <ConversationModel> >();
            List <UserModel> owners = new List <UserModel>();

            this.LoadConversations(conversations, owners);

            for (int i = 0; i < conversations.Count; i++)
            {
                if (conversations[i].Count == 0)
                {
                    return;
                }

                MockServiceProxy serviceProxy = new MockServiceProxy()
                {
                    Conversations = conversations[i]
                };
                MockUserSettings       userSettings       = new MockUserSettings();
                MockDataContextWrapper dataContextWrapper = new MockDataContextWrapper(new MockDatabase()
                {
                    Conversations = conversations[i]
                });
                userSettings.Save(owners[i]);

                using (AllConversationsViewModel allConversations = new AllConversationsViewModel(serviceProxy, userSettings, dataContextWrapper))
                {
                    allConversations.LoadInitialConversations();

                    NotifyCollectionChangedTester <ConversationModel> collectionChangedTester = new NotifyCollectionChangedTester <ConversationModel>(allConversations.Conversations);
                    long existingConversationId     = conversations[i].Count > 0 ? conversations[i][0].ConversationId : long.MaxValue;
                    int  existingConversationUserId = -1;

                    foreach (UserModel user in conversations[i][0].ConversationParticipants)
                    {
                        if (user.Id != owners[i].Id)
                        {
                            existingConversationUserId = user.Id;
                        }
                    }

                    foreach (ConversationModel conversation in conversations[i])
                    {
                        foreach (UserModel user in conversation.ConversationParticipants)
                        {
                            if (user.Id != owners[i].Id)
                            {
                                Assert.AreEqual(conversation, allConversations.GetConversationFromConversationId(conversation.ConversationId), "Conversation cannot be retrieved by guid");
                                Assert.AreEqual(conversation, allConversations.GetConversation(user.Id), "Conversation cannot be retrieved by recipient");
                            }
                        }
                    }

                    PushNotificationEvent pushEvent = new PushNotificationEvent(this, (long)2000, existingConversationId, "test", DateTime.Now.Ticks, "HandlePushNotificationExistingConversationTest" + i.ToString(), existingConversationUserId);
                    Messenger.Default.Send <PushNotificationEvent>(pushEvent);

                    Assert.AreEqual(collectionChangedTester.Count, 1, "Push notification was not handled. The new conversation was not added to the collection");
                }
            }
        }
Пример #3
0
        private async Task ProcessMessageAsync(PushNotificationEvent message)
        {
            var context = new { message.CustomerId, message.MessageTemplateId, message.Source };

            _log.Info("Push notification subscriber received message", context);

            try
            {
                await _messageService.ProcessPushNotificationAsync(_mapper.Map <PushNotification>(message), CallType.RabbitMq);
            }
            catch (Exception e)
            {
                _log.Error(e, "Failed to process push notification message", context);
                return;
            }

            _log.Info("Push notification subscriber processed message", context);
        }
        public void HandlePushNotificationTest()
        {
            for (int i = 0; i < this.conversationMessages.Count; i++)
            {
                for (int j = 0; j < this.conversationMessages[i].Count; j++)
                {
                    MockServiceProxy serviceProxy = new MockServiceProxy()
                    {
                        Messages = this.conversationMessages[i][j].m_Item2
                    };
                    MockUserSettings userSettings = new MockUserSettings();
                    userSettings.Save(owners[i]);

                    UserModel recipient = null;
                    foreach (UserModel user in this.conversationMessages[i][j].m_Item1.ConversationParticipants)
                    {
                        if (!user.Equals(userSettings.Me))
                        {
                            recipient = user;
                        }
                    }

                    ConversationMessagesViewModel messages = new ConversationMessagesViewModel(serviceProxy, userSettings, this.conversationMessages[i][j].m_Item1.ConversationId, recipient);

                    messages.LoadMessagesForConversations();

                    Random random = new Random((int)DateTime.Now.Ticks);
                    long   existingConversationId     = this.conversationMessages[i][j].m_Item2.Count > 0 ? this.conversationMessages[i][j].m_Item2[0].ConversationId : long.MaxValue;
                    int    existingConversationUserId = this.conversationMessages[i][j].m_Item2.Count > 0 ? this.conversationMessages[i][j].m_Item2[0].Sender.Id : random.Next(1000, 2000);

                    PushNotificationEvent pushEvent = new PushNotificationEvent(this, (long)2000, existingConversationId, "test", DateTime.Now.Ticks, "ConversationMessagesHandlePushNotificationTest" + i.ToString(), existingConversationUserId);

                    int messageCountBeforePush = messages.Messages.Count;
                    NotifyCollectionChangedTester <MessageModel> collectionChangedTester = new NotifyCollectionChangedTester <MessageModel>(messages.Messages);
                    Messenger.Default.Send <PushNotificationEvent>(pushEvent);

                    Assert.AreEqual(1, collectionChangedTester.Count, "Collection changed event was not generated");
                    Assert.AreEqual(messageCountBeforePush + 1, messages.Messages.Count, "Push notification was not handled properly");
                }
            }
        }
        private async Task CreateSalesforceAccountAsync(Guid customerId, string note, IEnumerable <Image> images)
        {
            var registrationResponse = await _tokenPropertyIntegrationClient.Api
                                       .RegisterConnectorAsync(new ConnectorRegisterRequestModel
            {
                CustomerId = customerId.ToString(),
                Note       = note,
                Images     = images.Select(o => new AgentImage
                {
                    ImageName    = o.Name,
                    ImageBase64  = o.Content,
                    DocumentType = Enum.Parse <ImageDocumentType>(o.DocumentType.ToString())
                }).ToList()
            });

            switch (registrationResponse.Status)
            {
            case ConnectorRegisterStatus.Ok:
                await _agentRepository.UpdateStatusAsync(customerId, registrationResponse.ConnectorSalesforceId,
                                                         AgentStatus.ApprovedAgent);

                var approvedEvent = new PushNotificationEvent
                {
                    CustomerId        = customerId.ToString(),
                    MessageTemplateId = _agentApprovedPushTemplateId,
                    Source            = _componentSourceName,
                };
                await _pushNotificationPublisher.PublishAsync(approvedEvent);

                break;

            case ConnectorRegisterStatus.AlreadyExists:
                await _agentRepository.UpdateStatusAsync(customerId, AgentStatus.Rejected);

                var rejectedEvent = new PushNotificationEvent
                {
                    CustomerId        = customerId.ToString(),
                    MessageTemplateId = _agentRejectedPushTemplateId,
                    Source            = _componentSourceName,
                };
                await _pushNotificationPublisher.PublishAsync(rejectedEvent);

                var evt = new EmailMessageEvent
                {
                    CustomerId        = customerId.ToString(),
                    SubjectTemplateId = _agentRejectedEmailSubjectTemplateId,
                    MessageTemplateId = _agentRejectedEmailTemplateId,
                    Source            = _componentSourceName,
                };
                await _emailNotificationPublisher.PublishAsync(evt);

                throw new SalesforceAccountAlreadyExistsException();

            case ConnectorRegisterStatus.ImageUploadError:
                throw new SalesforceImageUploadFailException();

            case ConnectorRegisterStatus.ConnectorRegistrationError:
                throw new SalesforceAccountRegistrationFailException();

            default:
                throw new InvalidOperationException("Received unknown status while creating salesforce account.");
            }
        }
Пример #6
0
        /// <summary>
        /// Event handler for when a toast notification arrives while your application is running.
        /// The toast will not display if your application is running so you must add this
        /// event handler if you want to do something with the toast notification.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            // Parse out the information that was part of the message.
            string message           = null;
            string messageSenderName = null;
            Guid   conversationId    = Guid.Empty;
            int    senderId          = -1;
            Guid   messageId         = Guid.Empty;
            long   messagePostDate   = -1;
            bool   isGroup           = false;
            string groupName         = null;
            int    groupId           = -1;

            foreach (string key in e.Collection.Keys)
            {
                if (string.Compare(
                        key,
                        "wp:Param",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.CompareOptions.IgnoreCase) == 0)
                {
                    PushNotification.GetMessageProperties(
                        e.Collection[key].Substring(PushNotification.RelativeUriPrefix.Length),
                        out conversationId,
                        out senderId,
                        out messageId,
                        out messagePostDate,
                        out groupId,
                        out groupName);

                    if (conversationId == Guid.Empty ||
                        messageId == Guid.Empty ||
                        senderId == -1 ||
                        messagePostDate == -1)
                    {
                        return;
                    }
                }

                if (string.Compare(
                        key,
                        "wp:Text2",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.CompareOptions.IgnoreCase) == 0)
                {
                    message = e.Collection[key];
                }

                if (string.Compare(
                        key,
                        "wp:Text1",
                        System.Globalization.CultureInfo.InvariantCulture,
                        System.Globalization.CompareOptions.IgnoreCase) == 0)
                {
                    messageSenderName = e.Collection[key];
                }
            }

            // Handle the push only if it's not from this user
            // Or this is from group notifications
            if (senderId != UserSettingsModel.Instance.UserId)
            {
                PushNotificationEvent pushEvent =
                    new PushNotificationEvent(
                        this,
                        messageId,
                        conversationId,
                        message,
                        messagePostDate,
                        messageSenderName,
                        senderId,
                        groupId,
                        groupName);

                Messenger.Default.Send <PushNotificationEvent>(pushEvent);
                this.ClearTileCount();
            }
        }
        public async Task <MessagesPostResponse> SendMessageAsync(MessagesPostRequest contract)
        {
            _log.Info("Send Message Async started",
                      new
            {
                contract.CustomerId,
                LocationId = contract.ExternalLocationId,
                contract.PartnerId,
                contract.SendPushNotification,
                contract.PosId,
                contract.Subject
            });

            //Check customer id
            var customerBlockState =
                await _customerManagementServiceClient.CustomersApi.GetCustomerBlockStateAsync(contract.CustomerId);

            if (customerBlockState.Error == CustomerBlockStatusError.CustomerNotFound)
            {
                _log.Warning("Customer Not Found", null,
                             new { contract.CustomerId, contract.PartnerId, contract.ExternalLocationId });

                return(new MessagesPostResponse
                {
                    PartnerMessageId = null, ErrorCode = MessagesErrorCode.CustomerNotFound
                });
            }
            else if (customerBlockState.Status == CustomerActivityStatus.Blocked)
            {
                _log.Warning("Customer Is Blocked", null,
                             new { contract.CustomerId, contract.PartnerId, contract.ExternalLocationId });

                return(new MessagesPostResponse
                {
                    PartnerMessageId = null, ErrorCode = MessagesErrorCode.CustomerIsBlocked
                });
            }

            //Check location
            LocationInfoResponse locationInfoResponse = null;

            if (!string.IsNullOrWhiteSpace(contract.ExternalLocationId))
            {
                locationInfoResponse =
                    await _partnerManagementClient.Locations.GetByExternalId2Async(contract.ExternalLocationId);

                if (locationInfoResponse == null)
                {
                    _log.Warning("Location Not Found", null,
                                 new { contract.CustomerId, contract.PartnerId, contract.ExternalLocationId });

                    return(new MessagesPostResponse
                    {
                        PartnerMessageId = null, ErrorCode = MessagesErrorCode.LocationNotFound
                    });
                }
            }

            //Check partner and location id
            var partnerAndLocationStatus =
                await _partnerAndLocationHelper.ValidatePartnerInfo(contract.PartnerId, locationInfoResponse);

            if (partnerAndLocationStatus != PartnerAndLocationStatus.OK)
            {
                var(message, errorCode) = partnerAndLocationStatus == PartnerAndLocationStatus.LocationNotFound
                    ? ("Location Not Found", MessagesErrorCode.LocationNotFound)
                    : ("Partner Not Found", MessagesErrorCode.PartnerNotFound);

                _log.Warning(message, null, new { contract.CustomerId, contract.PartnerId, contract.ExternalLocationId });

                return(new MessagesPostResponse {
                    PartnerMessageId = null, ErrorCode = errorCode
                });
            }

            var messageId = await _messagesRepository.InsertAsync(contract);

            _log.Info("Message saved", messageId);

            try
            {
                await _messageContentRepository.SaveContentAsync(messageId.ToString(), contract.Message);
            }
            catch (Exception ex)
            {
                _log.Error(ex, "Failed to save message content", new { messageId, contract.Message });

                await _messagesRepository.DeleteMessageAsync(messageId.ToString());

                throw;
            }

            _log.Info("Message content saved", messageId);

            //Send push notification via Rabbit
            if (contract.SendPushNotification.HasValue && contract.SendPushNotification.Value)
            {
                var evt = new PushNotificationEvent
                {
                    CustomerId         = contract.CustomerId,
                    MessageTemplateId  = _partnerMessageTemplateId,
                    Source             = _componentSourceName,
                    TemplateParameters =
                        new Dictionary <string, string>
                    {
                        { "Subject", contract.Subject },
                        { "PartnerMessageId", messageId.ToString() }
                    }
                };

                await _partnerMessagesPublisher.PublishAsync(evt);

                _log.Info("Partner message published", new { messageId, contract.CustomerId, contract.Subject });
            }

            return(new MessagesPostResponse
            {
                ErrorCode = MessagesErrorCode.OK, PartnerMessageId = messageId.ToString()
            });
        }