Firebase_Implementation #135

Merged
ashutosh.nehete merged 62 commits from Firebase_Implementation into main 2025-09-20 12:11:54 +00:00
10 changed files with 4623 additions and 81 deletions
Showing only changes of commit 5ac1c2b798 - Show all commits

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Marco.Pms.DataAccess.Migrations
{
/// <inheritdoc />
public partial class Added_Expriy_Date_In_FCMMapping_Table : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "ExpiredAt",
table: "FCMTokenMappings",
type: "datetime(6)",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ExpiredAt",
table: "FCMTokenMappings");
}
}
}

View File

@ -3067,6 +3067,9 @@ namespace Marco.Pms.DataAccess.Migrations
b.Property<Guid>("EmployeeId") b.Property<Guid>("EmployeeId")
.HasColumnType("char(36)"); .HasColumnType("char(36)");
b.Property<DateTime>("ExpiredAt")
.HasColumnType("datetime(6)");
b.Property<string>("FcmToken") b.Property<string>("FcmToken")
.IsRequired() .IsRequired()
.HasColumnType("longtext"); .HasColumnType("longtext");

View File

@ -1,6 +1,8 @@
namespace Marco.Pms.Model.Dtos.Authentication namespace Marco.Pms.Model.Dtos.Authentication
{ {
public class LogoutDto public class LogoutDto
{ public string? RefreshToken { get; set; } {
public required string RefreshToken { get; set; }
public string? FcmToken { get; set; }
} }
} }

View File

@ -2,7 +2,7 @@
{ {
public class RefreshTokenDto public class RefreshTokenDto
{ {
public string? Token { get; set; } public required string Token { get; set; }
public string? RefreshToken { get; set; } public required string RefreshToken { get; set; }
} }
} }

View File

@ -2,8 +2,9 @@
{ {
public class VerifyMPINDto public class VerifyMPINDto
{ {
public Guid EmployeeId { get; set; } public required Guid EmployeeId { get; set; }
public string? MPIN { get; set; } public required string MPIN { get; set; }
public string? MPINToken { get; set; } public required string MPINToken { get; set; }
public required string FcmToken { get; set; }
} }
} }

View File

@ -5,5 +5,6 @@
public Guid Id { get; set; } public Guid Id { get; set; }
public Guid EmployeeId { get; set; } public Guid EmployeeId { get; set; }
public string FcmToken { get; set; } = string.Empty; public string FcmToken { get; set; } = string.Empty;
public DateTime ExpiredAt { get; set; } = DateTime.UtcNow.AddDays(6);
} }
} }

View File

@ -33,7 +33,7 @@ namespace MarcoBMS.Services.Controllers
private readonly EmployeeHelper _employeeHelper; private readonly EmployeeHelper _employeeHelper;
private readonly ILoggingService _logger; private readonly ILoggingService _logger;
private readonly IFirebaseService _firebase; private readonly IFirebaseService _firebase;
private readonly Guid tenentId; private readonly Guid tenantId;
public AuthController(UserManager<ApplicationUser> userManager, ApplicationDbContext context, JwtSettings jwtSettings, RefreshTokenService refreshTokenService, public AuthController(UserManager<ApplicationUser> userManager, ApplicationDbContext context, JwtSettings jwtSettings, RefreshTokenService refreshTokenService,
IEmailSender emailSender, IConfiguration configuration, EmployeeHelper employeeHelper, UserHelper userHelper, ILoggingService logger, IFirebaseService firebase) IEmailSender emailSender, IConfiguration configuration, EmployeeHelper employeeHelper, UserHelper userHelper, ILoggingService logger, IFirebaseService firebase)
{ {
@ -47,7 +47,7 @@ namespace MarcoBMS.Services.Controllers
_userHelper = userHelper; _userHelper = userHelper;
_logger = logger; _logger = logger;
_firebase = firebase; _firebase = firebase;
tenentId = userHelper.GetTenantId(); tenantId = userHelper.GetTenantId();
} }
[HttpPost("login")] [HttpPost("login")]
@ -225,32 +225,26 @@ namespace MarcoBMS.Services.Controllers
// Return a successful response with the generated tokens. // Return a successful response with the generated tokens.
_logger.LogInfo("User {Username} logged in successfully.", user.UserName); _logger.LogInfo("User {Username} logged in successfully.", user.UserName);
var exsistingFCMMapping = await _context.FCMTokenMappings.FirstOrDefaultAsync(ft => ft.EmployeeId == emp.Id);
if (exsistingFCMMapping == null)
{
var fcmTokenMapping = new FCMTokenMapping var fcmTokenMapping = new FCMTokenMapping
{ {
EmployeeId = emp.Id, EmployeeId = emp.Id,
FcmToken = loginDto.FcmToken, FcmToken = loginDto.FcmToken,
ExpiredAt = DateTime.UtcNow.AddDays(6),
TenantId = emp.TenantId TenantId = emp.TenantId
}; };
_context.FCMTokenMappings.Add(fcmTokenMapping); _context.FCMTokenMappings.Add(fcmTokenMapping);
_logger.LogInfo("New FCM Token registering for employee {EmployeeId}", emp.Id); _logger.LogInfo("New FCM Token registering for employee {EmployeeId}", emp.Id);
}
else
{
var oldFCMToken = exsistingFCMMapping.FcmToken;
exsistingFCMMapping.FcmToken = loginDto.FcmToken;
_logger.LogInfo("Updating FCM Token for employee {EmployeeId}", emp.Id);
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
// --- Push Notification Section --- // --- Push Notification Section ---
// This section attempts to send a test push notification to the user's device. // This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens. // It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
await _firebase.SendLoginOnAnotherDeviceMessageAsync(oldFCMToken); await _firebase.SendLoginOnAnotherDeviceMessageAsync(emp.Id, loginDto.FcmToken, tenantId);
}); });
}
try try
{ {
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@ -267,7 +261,7 @@ namespace MarcoBMS.Services.Controllers
// This section attempts to send a test push notification to the user's device. // This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens. // It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
var name = $"{emp.FirstName} {emp.LastName}"; var name = $"{emp.FirstName} {emp.LastName}";
await _firebase.SendLoginMessageAsync(name); await _firebase.SendLoginMessageAsync(name, tenantId);
}); });
return Ok(ApiResponse<object>.SuccessResponse(responseData, "User logged in successfully.", 200)); return Ok(ApiResponse<object>.SuccessResponse(responseData, "User logged in successfully.", 200));
@ -353,6 +347,37 @@ namespace MarcoBMS.Services.Controllers
return Unauthorized(ApiResponse<object>.ErrorResponse("MPIN mismatch", "MPIN did not match", 401)); return Unauthorized(ApiResponse<object>.ErrorResponse("MPIN mismatch", "MPIN did not match", 401));
} }
if (!string.IsNullOrWhiteSpace(verifyMPIN.FcmToken))
{
var fcmTokenMapping = new FCMTokenMapping
{
EmployeeId = requestEmployee.Id,
FcmToken = verifyMPIN.FcmToken,
ExpiredAt = DateTime.UtcNow.AddDays(6),
TenantId = tenantId
};
_context.FCMTokenMappings.Add(fcmTokenMapping);
_logger.LogInfo("New FCM Token registering for employee {EmployeeId}", requestEmployee.Id);
try
{
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception occured while saving FCM Token for employee {EmployeeId}", requestEmployee.Id);
return StatusCode(500, ApiResponse<object>.ErrorResponse("Internal Error", ex.Message, 500));
}
_ = Task.Run(async () =>
{
// --- Push Notification Section ---
// This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
await _firebase.SendLoginOnAnotherDeviceMessageAsync(requestEmployee.Id, verifyMPIN.FcmToken, tenantId);
});
}
// Generate new tokens // Generate new tokens
var jwtToken = _refreshTokenService.GenerateJwtToken(requestEmployee.Email, tenantId, _jwtSettings); var jwtToken = _refreshTokenService.GenerateJwtToken(requestEmployee.Email, tenantId, _jwtSettings);
var refreshToken = await _refreshTokenService.CreateRefreshToken(requestEmployee.ApplicationUserId, tenantId.ToString(), _jwtSettings); var refreshToken = await _refreshTokenService.CreateRefreshToken(requestEmployee.ApplicationUserId, tenantId.ToString(), _jwtSettings);
@ -399,10 +424,9 @@ namespace MarcoBMS.Services.Controllers
await _refreshTokenService.BlacklistJwtTokenAsync(jwtToken); await _refreshTokenService.BlacklistJwtTokenAsync(jwtToken);
_logger.LogInfo("JWT access token blacklisted successfully"); _logger.LogInfo("JWT access token blacklisted successfully");
} }
string userAgent = HttpContext.Request.Headers["User-Agent"].ToString(); if (!string.IsNullOrWhiteSpace(logoutDto.FcmToken))
if (userAgent.Contains("Dart"))
{ {
var fcmTokenMapping = await _context.FCMTokenMappings.FirstOrDefaultAsync(ft => ft.EmployeeId == loggedInEmployee.Id && ft.TenantId == tenentId); var fcmTokenMapping = await _context.FCMTokenMappings.FirstOrDefaultAsync(ft => ft.EmployeeId == loggedInEmployee.Id && ft.FcmToken == logoutDto.FcmToken && ft.TenantId == tenantId);
if (fcmTokenMapping != null) if (fcmTokenMapping != null)
{ {
_context.FCMTokenMappings.Remove(fcmTokenMapping); _context.FCMTokenMappings.Remove(fcmTokenMapping);
@ -919,25 +943,15 @@ namespace MarcoBMS.Services.Controllers
public async Task<IActionResult> StoreDeviceToken([FromBody] FCMTokenDto model) public async Task<IActionResult> StoreDeviceToken([FromBody] FCMTokenDto model)
{ {
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync(); var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
var tenantId = _userHelper.GetTenantId();
var exsistingFCMMapping = await _context.FCMTokenMappings.FirstOrDefaultAsync(ft => ft.EmployeeId == loggedInEmployee.Id);
if (exsistingFCMMapping == null)
{
var fcmTokenMapping = new FCMTokenMapping var fcmTokenMapping = new FCMTokenMapping
{ {
EmployeeId = loggedInEmployee.Id, EmployeeId = loggedInEmployee.Id,
FcmToken = model.FcmToken, FcmToken = model.FcmToken,
ExpiredAt = DateTime.UtcNow.AddDays(6),
TenantId = tenantId TenantId = tenantId
}; };
_context.FCMTokenMappings.Add(fcmTokenMapping); _context.FCMTokenMappings.Add(fcmTokenMapping);
_logger.LogInfo("New FCM Token registering for employee {EmployeeId}", loggedInEmployee.Id); _logger.LogInfo("New FCM Token registering for employee {EmployeeId}", loggedInEmployee.Id);
}
else
{
exsistingFCMMapping.FcmToken = model.FcmToken;
_logger.LogInfo("Updating FCM Token for employee {EmployeeId}", loggedInEmployee.Id);
}
try try
{ {
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@ -947,6 +961,16 @@ namespace MarcoBMS.Services.Controllers
_logger.LogError(ex, "Exception occured while saving FCM Token for employee {EmployeeId}", loggedInEmployee.Id); _logger.LogError(ex, "Exception occured while saving FCM Token for employee {EmployeeId}", loggedInEmployee.Id);
return StatusCode(500, ApiResponse<object>.ErrorResponse("Internal Error", ex.Message, 500)); return StatusCode(500, ApiResponse<object>.ErrorResponse("Internal Error", ex.Message, 500));
} }
_ = Task.Run(async () =>
{
// --- Push Notification Section ---
// This section attempts to send a test push notification to the user's device.
// It's designed to fail gracefully and handle invalid Firebase Cloud Messaging (FCM) tokens.
await _firebase.SendLoginOnAnotherDeviceMessageAsync(loggedInEmployee.Id, model.FcmToken, tenantId);
});
return Ok(ApiResponse<object>.SuccessResponse(new { }, "FCM Token registered Successfuly", 200)); return Ok(ApiResponse<object>.SuccessResponse(new { }, "FCM Token registered Successfuly", 200));
} }
private static string ComputeSha256Hash(string rawData) private static string ComputeSha256Hash(string rawData)

View File

@ -31,13 +31,17 @@ namespace Marco.Pms.Services.Service
_serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory)); _serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
} }
public async Task SendLoginOnAnotherDeviceMessageAsync(string FcmToken) public async Task SendLoginOnAnotherDeviceMessageAsync(Guid employeeId, string fcmToken, Guid tenentId)
{ {
await using var _context = await _dbContextFactory.CreateDbContextAsync(); await using var _context = await _dbContextFactory.CreateDbContextAsync();
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokens = new List<string> { FcmToken }; var registrationTokens = await _context.FCMTokenMappings
; .Where(ft => ft.EmployeeId == employeeId &&
ft.ExpiredAt >= DateTime.UtcNow &&
ft.FcmToken != fcmToken &&
ft.TenantId == tenentId)
.Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
@ -47,12 +51,15 @@ namespace Marco.Pms.Services.Service
await SendMessageToMultipleDevicesAsync(registrationTokens, notificationFirebase); await SendMessageToMultipleDevicesAsync(registrationTokens, notificationFirebase);
} }
public async Task SendLoginMessageAsync(string name) public async Task SendLoginMessageAsync(string name, Guid tenentId)
{ {
await using var _context = await _dbContextFactory.CreateDbContextAsync(); await using var _context = await _dbContextFactory.CreateDbContextAsync();
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokens = await _context.FCMTokenMappings.Select(ft => ft.FcmToken).ToListAsync(); var registrationTokens = await _context.FCMTokenMappings
.Where(ft => ft.ExpiredAt >= DateTime.UtcNow &&
ft.TenantId == tenentId)
.Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
@ -192,7 +199,7 @@ namespace Marco.Pms.Services.Service
if (mesaageNotificationIds.Any()) if (mesaageNotificationIds.Any())
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => mesaageNotificationIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => mesaageNotificationIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -202,7 +209,7 @@ namespace Marco.Pms.Services.Service
if (dataNotificationIds.Any()) if (dataNotificationIds.Any())
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => dataNotificationIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => dataNotificationIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data);
} }
@ -295,7 +302,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForNotificationTask = Task.Run(async () => var registrationTokensForNotificationTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => teamMembers.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => teamMembers.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
Title = $"Task Assigned for {project?.ProjectName}", Title = $"Task Assigned for {project?.ProjectName}",
@ -307,7 +314,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForDataTask = Task.Run(async () => var registrationTokensForDataTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data);
}); });
@ -446,7 +453,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForNotificationTask = Task.Run(async () => var registrationTokensForNotificationTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => mesaageNotificationIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => mesaageNotificationIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
Title = $"New Task Reported - {project?.ProjectName}", Title = $"New Task Reported - {project?.ProjectName}",
@ -458,7 +465,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForDataTask = Task.Run(async () => var registrationTokensForDataTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => dataNotificationIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => dataNotificationIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data);
}); });
@ -557,7 +564,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
Title = $"New Comment on Task - {project?.ProjectName}", Title = $"New Comment on Task - {project?.ProjectName}",
@ -671,7 +678,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForNotificationTask = Task.Run(async () => var registrationTokensForNotificationTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => teamMembers.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => teamMembers.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
var notificationFirebase = new Notification var notificationFirebase = new Notification
{ {
Title = $"Task Approved - {project?.ProjectName}", Title = $"Task Approved - {project?.ProjectName}",
@ -683,7 +690,7 @@ namespace Marco.Pms.Services.Service
var registrationTokensForDataTask = Task.Run(async () => var registrationTokensForDataTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data);
}); });
@ -824,7 +831,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -939,7 +946,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1047,7 +1054,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1149,7 +1156,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1271,7 +1278,7 @@ namespace Marco.Pms.Services.Service
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1369,14 +1376,14 @@ namespace Marco.Pms.Services.Service
var registrationTokensForNotificationTask = Task.Run(async () => var registrationTokensForNotificationTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => projectAllocation.EmployeeId == ft.EmployeeId).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => projectAllocation.EmployeeId == ft.EmployeeId && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
}); });
var registrationTokensForDataTask = Task.Run(async () => var registrationTokensForDataTask = Task.Run(async () =>
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForData = await dbContext.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForData, data);
}); });
@ -1460,7 +1467,7 @@ namespace Marco.Pms.Services.Service
}; };
// List of device registration tokens to send the message to // List of device registration tokens to send the message to
var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await _context.FCMTokenMappings.Where(ft => employeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1582,7 +1589,7 @@ namespace Marco.Pms.Services.Service
if (notificationFirebase != null) if (notificationFirebase != null)
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => notificationEmployeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => notificationEmployeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForNotification, notificationFirebase, data);
} }
@ -1591,7 +1598,7 @@ namespace Marco.Pms.Services.Service
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => dataEmployeeIds.Contains(ft.EmployeeId)).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForNotification = await dbContext.FCMTokenMappings.Where(ft => dataEmployeeIds.Contains(ft.EmployeeId) && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForNotification, data); await SendMessageToMultipleDevicesOnlyDataAsync(registrationTokensForNotification, data);
@ -1601,7 +1608,7 @@ namespace Marco.Pms.Services.Service
if (notificationCreatedBy != null) if (notificationCreatedBy != null)
{ {
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(); await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
var registrationTokensForemployee = await dbContext.FCMTokenMappings.Where(ft => ft.EmployeeId == expenses.CreatedById).Select(ft => ft.FcmToken).ToListAsync(); var registrationTokensForemployee = await dbContext.FCMTokenMappings.Where(ft => ft.EmployeeId == expenses.CreatedById && ft.ExpiredAt >= DateTime.UtcNow).Select(ft => ft.FcmToken).ToListAsync();
await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForemployee, notificationCreatedBy, data); await SendMessageToMultipleDevicesWithDataAsync(registrationTokensForemployee, notificationCreatedBy, data);
} }

View File

@ -6,8 +6,8 @@ namespace Marco.Pms.Services.Service.ServiceInterfaces
{ {
public interface IFirebaseService public interface IFirebaseService
{ {
Task SendLoginMessageAsync(string name); Task SendLoginMessageAsync(string name, Guid tenentId);
Task SendLoginOnAnotherDeviceMessageAsync(string FcmToken); Task SendLoginOnAnotherDeviceMessageAsync(Guid employeeId, string fcmToken, Guid tenentId);
Task SendAttendanceMessageAsync(Guid projectId, string Name, ATTENDANCE_MARK_TYPE markType, Guid employeeId, Guid tenantId); Task SendAttendanceMessageAsync(Guid projectId, string Name, ATTENDANCE_MARK_TYPE markType, Guid employeeId, Guid tenantId);
Task SendAssignTaskMessageAsync(Guid workItemId, string name, List<Guid> teamMembers, Guid tenantId); Task SendAssignTaskMessageAsync(Guid workItemId, string name, List<Guid> teamMembers, Guid tenantId);
Task SendReportTaskMessageAsync(Guid taskAllocationId, string name, Guid tenantId); Task SendReportTaskMessageAsync(Guid taskAllocationId, string name, Guid tenantId);