using G1.Domain.Entity.Entities;
using G1.Repositories.Repository.Interface;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ECMS.Web.Api.Jobs
private readonly IRepository<User> _userRepository;
private readonly IRepository<Health> _healthRepository;
private readonly SmtpSetting _smtpSetting;
public AlertJob(IRepository<User> userRepository,
IRepository<Health> healthRepository, IOptions<SmtpSetting> smtpOptions)
_userRepository = userRepository;
_healthRepository = healthRepository;
_smtpSetting = smtpOptions.Value;
var date = DateTime.UtcNow.AddMinutes(-15);
var uhFilter = Builders<Health>.Filter;
var unhealthFilters = uhFilter.And(
uhFilter.Eq(x => x.DeletedDate, null),
uhFilter.Eq(x => x.ShowSignal, true),
uhFilter.Gte(x => x.CreatedDate, new BsonDateTime(date))
var unHealths = await _healthRepository.DbSet.Find(unhealthFilters).ToListAsync();
if (unHealths?.Count > 0)
var userIds = unHealths.Select(x => x.UserId).Distinct().ToList();
var userFilter = Builders<User>.Filter;
var uFilter = userFilter.And(
userFilter.In(x => x.Id, userIds)
var projection = Builders<User>.Projection
.Include(x => x.Username);
List<User> users = await _userRepository.DbSet.Find(uFilter).ToListAsync();
foreach (var user in users)
html += $"{user.Username}<br/>";
public void SendEmail(string html)
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(_smtpSetting.From));
var recipients = _smtpSetting.AlertEmail.Split(",");
foreach (var recipient in recipients)
email.To.Add(MailboxAddress.Parse(recipient));
email.Subject = $"[Việt Nam khỏe mạnh] Danh sách khai báo sức khỏe bất thường";
html = $"Hi,<br/>Phát hiện khai báo sức khỏe bất thường 15 phút qua: <br/><br/>{html}";
email.Body = new TextPart(TextFormat.Html) { Text = html };
using (var smtpClient = new SmtpClient())
smtpClient.Connect(_smtpSetting.Host, int.Parse(_smtpSetting.Port), SecureSocketOptions.Auto);
smtpClient.Authenticate(_smtpSetting.Username, _smtpSetting.Password);
smtpClient.Disconnect(true);