public async Task <IActionResult> SendEmail([FromRoute] string token, [FromBody] EmailParametersModel model)
        {
            if (token != Consts.StaticToken)
            {
                return(new ContentResult {
                    StatusCode = 403
                });
            }

            try
            {
                var emailParams = model.Adapt <EmailParameters>();

                await _mailer.SendMail(emailParams);

                return(Ok());
            }
            catch (ArgumentException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
            catch (ApplicationException ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest(ex.Message));
            }
        }
Exemple #2
0
 public async Task <IActionResult> Email(EmailParametersModel emailParametersModel) => await ProcessPatchRequest(emailParametersModel);
        public async Task <BookLogInfo> AddBookLogAsync(UserInfo model, string uri)
        {
            var clientEmail    = _query.GetClientByEmail(model.Email);
            var isClientExists = clientEmail != null;
            var book           = new BookLogInfo()
            {
            };
            var client = new ClientMaster();

            var booklog = _mapper.Map <BookLog>(model);

            booklog.Guid        = Guid.NewGuid();
            model.RefCode       = booklog.Guid.ToString();
            booklog.BookingType = Convert.ToByte(model.BookType);
            booklog.BookStatus  = model.BookStatus < 1 ? Convert.ToByte((int)BookStatusEnum.Pending) : Convert.ToByte(model.BookStatus);
            if (!model.HaveBookedBefore && !isClientExists)
            {
                client = _mapper.Map <ClientMaster>(model);
                var contacts = model.ContactNumber.ToArray();
                client.ContactNumber1 = contacts[0].ContactNumber;
                client.ContactNumber2 = contacts[1].ContactNumber;

                _context.Add(client);
                //_context.SaveChanges();

                booklog.ClientId = client.ClientId;
            }
            else
            {
                if (isClientExists)
                {
                    booklog.ClientId = clientEmail.ClientId;

                    clientEmail.ContactNumber1 = string.IsNullOrEmpty(model.ContactNumber.ElementAt(0).ContactNumber) ? client.ContactNumber1 : model.ContactNumber.ElementAt(0).ContactNumber;
                    clientEmail.ContactNumber2 = string.IsNullOrEmpty(model.ContactNumber.ElementAt(1).ContactNumber) ? client.ContactNumber2 : model.ContactNumber.ElementAt(1).ContactNumber;

                    _context.Update(clientEmail);
                    //_context.SaveChanges();
                }
                else
                {
                    return(new BookLogInfo()
                    {
                        State = new StatusResponse()
                        {
                            isValid = false,
                            Message = "Can't find client with the specified email."
                        }
                    });
                }
            }

            book = new BookLogInfo()
            {
                Client   = isClientExists ? clientEmail : client,
                BookLog  = booklog,
                BookInfo = new BookInfo()
                {
                    SpaceName      = _method.GetSpaceName(model.SpaceType),
                    FrequencyName  = _method.GetFrequencyName(model.FrequencyType),
                    BookStatusName = _method.GetBookingStatusName(model.BookStatus),
                    BookTypeName   = _method.GetBookingTypeName(model.BookType),
                    SpaceType      = model.SpaceType,
                    FrequencyType  = model.FrequencyType,
                    BookStatus     = model.BookStatus,
                    BookType       = model.BookType,
                    RoomType       = model.RoomType
                },
                State = new StatusResponse()
                {
                    isValid = true
                }
            };

            _context.Add(booklog);
            //_context.SaveChanges();

            if (model.BookType == (int)BookingTypeEnum.DevHub)
            {
                var emailParams = new EmailParametersModel()
                {
                    UserInfo = model,
                    Client   = isClientExists ? clientEmail : client,
                    Uri      = uri,
                    Id       = booklog.Id
                };
                await _email.SendEmail(_method.GetApproveEmailParameter(emailParams, false), "");

                await _email.SendEmail(_method.GetApproveEmailParameter(emailParams, true), "");
            }

            return(book);
        }
        public EmailParameters GetApproveEmailParameter(EmailParametersModel model, bool isAdmin)
        {
            var space     = GetSpaceName(model.UserInfo.SpaceType);
            var firstname = model.UserInfo.HaveBookedBefore ? model.Client.FirstName : model.UserInfo.FirstName;
            var lastname  = model.UserInfo.HaveBookedBefore ? model.Client.LastName : model.UserInfo.LastName;
            var rate      = GetBookRate(model.UserInfo.FrequencyType, model.UserInfo.SpaceType);

            if (!isAdmin)
            {
                var emailParams = new EmailParameters()
                {
                    Subject       = $"Dev Hub: Confirming Booking!",
                    Firstname     = firstname,
                    Lastname      = lastname,
                    Email         = model.Client.Email,
                    Recipient     = model.Client.Email,
                    Template      = "Add-Booking-Template",
                    Date          = model.UserInfo.DateOfArrival.ToString("MMMM dd, yyyy"),
                    Message       = !string.IsNullOrEmpty(model.UserInfo.Remarks) ? model.UserInfo.Remarks : "No Message",
                    ContactNumber = model.Client.ContactNumber1 + ", " + model.Client.ContactNumber2,
                    IsAdmin       = false,
                    Rate          = rate,
                    RoomType      = model.UserInfo.RoomType,
                    GuestCount    = model.UserInfo.PersonCount,
                    Space         = space
                };

                switch (model.UserInfo.SpaceType)
                {
                case (int)SpaceEnum.ConferenceMeeting:

                    emailParams.Template = "Add-Booking-Conference-Template";
                    return(emailParams);

                default:
                    return(emailParams);
                }
            }
            else
            {
                var emailParams = new EmailParameters()
                {
                    Subject       = $"Dev Hub: New Booking Request!",
                    Firstname     = firstname,
                    Lastname      = lastname,
                    Email         = model.Client.Email,
                    Space         = space,
                    Recipient     = model.Client.Email,
                    Template      = "Add-Admin-Booking-Template",
                    Date          = model.UserInfo.DateOfArrival.ToString("MMMM dd, yyyy"),
                    IsFromDevhub  = true,
                    Message       = !string.IsNullOrEmpty(model.UserInfo.Remarks) ? model.UserInfo.Remarks : "No Message",
                    ContactNumber = model.Client.ContactNumber1 + ", " + model.Client.ContactNumber2,
                    IsAdmin       = true,
                    Rate          = rate,
                    RoomType      = model.UserInfo.RoomType,
                    GuestCount    = model.UserInfo.PersonCount,
                    Link          = _options.Value.Protocol + model.Uri + "/#!/Confirm?token=" + model.UserInfo.RefCode + model.Id
                };

                switch (model.UserInfo.SpaceType)
                {
                case (int)SpaceEnum.ConferenceMeeting:
                    emailParams.Template = "Add-Admin-Booking-Conference-Template";
                    return(emailParams);

                default:
                    return(emailParams);
                }
            }
        }
        public async static Task SendAlertByOnlineOfflineOutOfLocationDevice(IServiceScope scope, DeviceNotificationModel deviceModel)
        {
            var      deviceService           = scope.ServiceProvider.GetService <IDeviceService>();
            var      deviceHistoryRepository = scope.ServiceProvider.GetService <IDeviceHistoryRepository>();
            var      httpService             = scope.ServiceProvider.GetService <IHttpService>();
            var      loggerServive           = scope.ServiceProvider.GetService <ILogger <NotificationSender> >();
            DateTime previousHeartBeat       = default;

            var deviceFromDb = await deviceService.GetDeviceByUdidAsync(deviceModel.Udid);

            loggerServive.LogInformation($"Prepare notification for {deviceModel.Udid} ,  Type notification: {deviceModel.FuncType.ToString()}",
                                         deviceModel.Udid, deviceModel.FuncType.ToString());

            if (deviceModel.FuncType == SelectFunc.Online)
            {
                previousHeartBeat = (await deviceHistoryRepository.GetAsync(x => x.DeviceId == deviceFromDb.Id))
                                    .OrderByDescending(x => x.CreatedOn)
                                    .FirstOrDefault(x => x.IsOnline == true)
                                    .CreatedOn;
            }
            else
            {
                previousHeartBeat = DateTime.UtcNow;
            }

            #region Get Branch

            var branch = (await httpService.GetBranchesTrustedAsync()).Find(x => x.Id == deviceFromDb.BranchId);
            #endregion

            #region Get User Role

            var     companyModel = (await httpService.GetCompaniesForTrustedAsync()).Find(x => x.Id == deviceFromDb.CompanyId);
            Filters filter       = new Filters();
            filter.UsersId = companyModel?.UserId;
            filter.Role    = new string[] { "supervisor" };

            string queryUsersByRole = JsonConvert.SerializeObject(filter);

            var users = await httpService.GetUsersByIdTrustedAsync(queryUsersByRole);

            #endregion
            TimeZoneInfo timeZoneInfo;
            try
            {
                timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time");
            }
            catch (TimeZoneNotFoundException)
            {
                loggerServive.LogWarning("Notification Time Zone Exeption");
                timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
            }

            EmailParametersModel model = new EmailParametersModel()
            {
                UDID              = deviceModel.Udid,
                EmailsTo          = Enumerable.Empty <string>(),//TODO: uncomment in future with users.Select(x => x.Email)/
                Cause             = deviceModel.FuncType.ToString().ToLower(),
                Address           = branch?.Address,
                Town              = branch?.City,
                PostCode          = branch?.ZipCode,
                Country           = "USA",
                Notes             = "",
                LastHeartBeat     = TimeZoneInfo.ConvertTimeFromUtc(deviceModel.LastHeartBeat, timeZoneInfo),
                PreviousHeartBeat = TimeZoneInfo.ConvertTimeFromUtc(previousHeartBeat, timeZoneInfo)
            };

            string query = JsonConvert.SerializeObject(model);

            await httpService.PostNotificationEmailAsync(query);

            loggerServive.LogInformation($"Notification for {deviceModel.Udid} sent to service,  Type notification: {deviceModel.FuncType.ToString()}",
                                         deviceModel.Udid, deviceModel.FuncType.ToString());
        }