Created new API for creating new tenant #1

Merged
vikas.nale merged 2 commits from Ashutosh_CreateNewTenant into TeanantManagement 2025-03-28 06:17:03 +00:00
13 changed files with 84 additions and 83 deletions
Showing only changes of commit 8014b90487 - Show all commits

View File

@ -4,8 +4,8 @@ namespace Marco.Pms.Model.Dtos.Tenant
{
public class CreateTenantDto
{
[Required]
public string Username { get; set; }
//[Required]
//public string Username { get; set; }
[Required]
[EmailAddress]
@ -25,20 +25,5 @@ namespace Marco.Pms.Model.Dtos.Tenant
public string Name { get; set; }
public string ContactNumber { get; set; }
public DateTime OnBoardingDate { get; set; }
//public string Gender { get; set; }
//public string? BirthDate { get; set; }
//public DateTime JoiningDate { get; set; }
//public string? PeramnentAddress { get; set; }
//public string? CurrentAddress { get; set; }
//public string EmergencyPhoneNumber { get; set; }
//public string EmergencyContactPerson { get; set; }
//public string? AadharNumber { get; set; }
//public string? PanNumber { get; set; }
}
}

View File

@ -1,9 +1,5 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
using Microsoft.AspNetCore.Identity;
namespace Marco.Pms.Model.Entitlements
{

View File

@ -1,5 +1,4 @@
using Marco.Pms.Model.Dtos.Tenant;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Entitlements;
namespace Marco.Pms.Model.Mapper
@ -14,6 +13,8 @@ namespace Marco.Pms.Model.Mapper
Description = createTenant.About,
DomainName = createTenant.Website,
ContactName = createTenant.Name,
//OragnizationSize = OragnizationSize,
//IndustryId = IndustryId,
ContactNumber = createTenant.ContactNumber,
OnBoardingDate = createTenant.OnBoardingDate,
};

View File

@ -217,7 +217,10 @@ namespace MarcoBMS.Services.Controllers
try
{
Attendance attendance = await _context.Attendes.FirstOrDefaultAsync(a => a.EmployeeID == recordAttendanceDot.EmployeeID &&
a.AttendanceDate.Date == recordAttendanceDot.Date.Date && a.TenantId == TenantId); ;
a.AttendanceDate.Date == recordAttendanceDot.Date.Date && a.TenantId == TenantId);
DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
if (attendance != null)
@ -236,13 +239,13 @@ namespace MarcoBMS.Services.Controllers
//string timeString = "10:30 PM"; // Format: "hh:mm tt"
DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
//DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
attendance.OutTime = finalDateTime;
}
else if (recordAttendanceDot.Action == ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE)
{
DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
//DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
attendance.OutTime = finalDateTime;
attendance.Activity = ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE;
@ -277,7 +280,7 @@ namespace MarcoBMS.Services.Controllers
attendance.Date = DateTime.UtcNow;
DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
//DateTime finalDateTime = GetDateFromTimeStamp(recordAttendanceDot, recordAttendanceDot.MarkTime);
attendance.InTime = finalDateTime;
attendance.OutTime = null;
@ -295,7 +298,8 @@ namespace MarcoBMS.Services.Controllers
AttendanceId = attendance.Id, // Use existing or new AttendanceId
Activity = attendance.Activity,
ActivityTime = recordAttendanceDot.Date,
ActivityTime = finalDateTime,
//ActivityTime = recordAttendanceDot.Date,
Comment = recordAttendanceDot.Comment,
EmployeeID = recordAttendanceDot.EmployeeID,
Latitude = recordAttendanceDot.Latitude,
@ -303,7 +307,8 @@ namespace MarcoBMS.Services.Controllers
TenantId = TenantId,
UpdatedBy = GetUserId(),
UpdatedOn = DateTime.UtcNow
UpdatedOn = recordAttendanceDot.Date
//UpdatedOn = DateTime.UtcNow
};
//if (recordAttendanceDot.Image != null && recordAttendanceDot.Image.Count > 0)
//{

View File

@ -1,13 +1,14 @@
using Marco.Pms.DataAccess.Data;
using System.Text.Json;
using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Dtos.Tenant;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Entitlements;
using Marco.Pms.Model.Mapper;
using Marco.Pms.Model.Utilities;
using MarcoBMS.Services.Service;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Marco.Pms.Model.Mapper;
using System.Text.Json;
using Marco.Pms.Model.Utilities;
namespace Marco.Pms.Services.Controllers
{
@ -18,10 +19,12 @@ namespace Marco.Pms.Services.Controllers
private readonly string jsonString = System.IO.File.ReadAllText("Data/RolesCofiguration.json");
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
public TenantController(ApplicationDbContext context,UserManager<IdentityUser> userManager)
private readonly ILoggingService _logger;
public TenantController(ApplicationDbContext context,UserManager<IdentityUser> userManager, ILoggingService logger)
{
_context = context;
_userManager = userManager;
_logger = logger;
}
[HttpPost]
public async Task<IActionResult> CreateTenant([FromForm] CreateTenantDto createTenantDto)
@ -31,7 +34,7 @@ namespace Marco.Pms.Services.Controllers
return BadRequest(ModelState);
}
if (await _userManager.FindByEmailAsync(createTenantDto.Email) != null)
if (await _userManager.FindByEmailAsync(createTenantDto.Email) != null && await _context.Tenants.FirstOrDefaultAsync(t => t.Name == createTenantDto.OrganizatioinName) != null)
{
return BadRequest("Tenant Already Exists");
}
@ -39,46 +42,66 @@ namespace Marco.Pms.Services.Controllers
Tenant newTenant = createTenantDto.CreateDtoToTenant();
_context.Tenants.Add(newTenant);
await _context.SaveChangesAsync();
Tenant? tenant = await _context.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Name == newTenant.Name);
if (tenant != null)
//Tenant? tenant = await _context.Tenants.FirstOrDefaultAsync(t => t.Name == newTenant.Name);
if (newTenant != null)
{
RoleConfiguration settings = JsonSerializer.Deserialize<RoleConfiguration>(jsonString);
var TenantId = tenant.Id;
var TenantId = newTenant.Id;
JobRole jobRole = new JobRole
{
Name = settings.JobRoleName,
Description = settings.JobRoleDescription,
TenantId = TenantId
};
var existingJobRole = await _context.JobRoles.AsNoTracking().FirstOrDefaultAsync(r => r.Name == settings.JobRoleName);
ApplicationRole role = new ApplicationRole
{
Role = settings.RoleName,
Description = settings.JobRoleDescription,
Description = settings.RoleDescription,
TenantId = TenantId
};
if (_context.JobRoles.AsNoTracking().FirstOrDefaultAsync(r => r.Name == "Admin") != null)
var existingRole = await _context.ApplicationRoles.AsNoTracking().FirstOrDefaultAsync(r => r.Role == settings.RoleName);
if (existingJobRole == null)
{
_context.JobRoles.Add(jobRole);
await _context.SaveChangesAsync();
}
if (_context.JobRoles.AsNoTracking().FirstOrDefaultAsync(r => r.Name == "SuperUser") != null)
else
{
jobRole = existingJobRole;
}
if (existingRole == null)
{
_context.ApplicationRoles.Add(role);
await _context.SaveChangesAsync();
}
else
{
role = existingRole;
}
List<FeaturePermission> permissions = await _context.FeaturePermissions.AsNoTracking().ToListAsync();
//List < RolePermissionMappings > = [];
List<RolePermissionMappings> rolePermissionMappings = new List<RolePermissionMappings>();
foreach (var permission in permissions)
{
var item = new RolePermissionMappings() { ApplicationRoleId = role.Id, FeaturePermissionId = permission.Id };
bool assigned = _context.RolePermissionMappings.Any(c => c.ApplicationRoleId == role.Id && c.FeaturePermissionId == permission.Id);
if (permission.IsEnabled && !assigned)
_context.RolePermissionMappings.Add(item);
rolePermissionMappings.Add(item);
}
_context.RolePermissionMappings.AddRange(rolePermissionMappings);
await _context.SaveChangesAsync();
var user = new ApplicationUser
{
UserName = createTenantDto.Username,
UserName = createTenantDto.Email,
Email = createTenantDto.Email,
TenantId = TenantId,
IsRootUser = true,
@ -109,7 +132,7 @@ namespace Marco.Pms.Services.Controllers
foreach (var error in result.Errors)
{
// Log error.Description
Console.WriteLine($"UserManager Error: {error.Description}");
_logger.LogError("{Error}",error.Description);
}
return BadRequest("Failed to create the root user.");
}
@ -122,9 +145,7 @@ namespace Marco.Pms.Services.Controllers
return new Employee
{
ApplicationUserId = ApplicationUserId,
//FirstName = model.FirstName,
FirstName = model.Name,
//LastName = model.LastName,
LastName = "",
Email = model.Email,
TenantId = TenantId,
@ -134,13 +155,11 @@ namespace Marco.Pms.Services.Controllers
EmergencyContactPerson = "",
AadharNumber = "",
Gender = "",
//MiddleName = model.MiddleName,
MiddleName = "",
PanNumber = "",
PeramnentAddress = "",
PhoneNumber = "",
Photo = null, // GetFileDetails(model.Photo).Result.FileData,
//JobRoleId = Convert.ToInt32(model.JobRoleId),
JobRoleId = jobRoleId,
JoiningDate = DateTime.UtcNow,

View File

@ -1,6 +1,6 @@
{
"JobRoleName": "Admin",
"JobRoleDescription": "Admin",
"RoleName": "SuperRole",
"RoleDescription": "SuperRole"
"RoleName": "SuperUser",
"RoleDescription": "SuperUser"
}

View File

@ -1,7 +1,5 @@
using Marco.Pms.Model.Dtos.Employees;
using Marco.Pms.Model.Entitlements;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
namespace MarcoBMS.Services.Helpers
{
@ -29,6 +27,7 @@ namespace MarcoBMS.Services.Helpers
if (string.IsNullOrEmpty(userId))
return null;
var user = await _userManager.FindByEmailAsync(userId);
//var user = await _userManager.FindByNameAsync(userId); // For fetching user using username
return user; //await _userManager.FindByIdAsync(userId);
}

View File

@ -29,7 +29,7 @@ namespace MarcoBMS.Services.Middleware
using (LogContext.PushProperty("TenantId", tenantId))
using (LogContext.PushProperty("TraceId", context.TraceIdentifier))
//using (LogContext.PushProperty("TraceId", context.TraceIdentifier))
using (LogContext.PushProperty("UserAgent", request.Headers["User-Agent"].ToString()))
using (LogContext.PushProperty("HttpMethod", request.Method))
using (LogContext.PushProperty("Timestamp", DateTime.UtcNow))
@ -44,7 +44,7 @@ namespace MarcoBMS.Services.Middleware
using (LogContext.PushProperty("StatusCode", response.StatusCode.ToString()))
using (LogContext.PushProperty("ResponseTimeMs", stopwatch.ElapsedMilliseconds))
using (LogContext.PushProperty("LogLevel", "Information"))
_logger.LogInformation("HTTP {method} {path} responded {statusCode} in {timeTaken} ms", request.Method,request.Path, response.StatusCode.ToString(),stopwatch.ElapsedMilliseconds);
_logger.LogInformation("HTTP {HttpMethod} {RequestPath} responded {statusCode} in {ResponseTimeMs} ms", request.Method,request.Path, response.StatusCode.ToString(),stopwatch.ElapsedMilliseconds);
}
catch (Exception ex)
{
@ -53,7 +53,7 @@ namespace MarcoBMS.Services.Middleware
using (LogContext.PushProperty("StatusCode", "500"))
using (LogContext.PushProperty("ResponseTimeMs", stopwatch.ElapsedMilliseconds))
using (LogContext.PushProperty("LogLevel", "Error"))
_logger.LogError("API Error{error}", ex.Message);
_logger.LogError("API Error: {Error}", ex.Message);
throw;
}
}

View File

@ -12,6 +12,7 @@ using Microsoft.OpenApi.Models;
using Serilog;
using System.Text;
Serilog.Debugging.SelfLog.Enable(Console.Error);
var builder = WebApplication.CreateBuilder(args);

View File

@ -6,7 +6,7 @@ namespace MarcoBMS.Services.Service
{
void LogInfo(string? message, params object[]? args);
void LogWarning(string? message, params object[]? args);
void LogError(Exception? ex, string? message, params object[]? args);
void LogError(string? message, params object[]? args);
}
}

View File

@ -11,9 +11,8 @@ namespace MarcoBMS.Services.Service
_logger = logger;
}
public void LogError(Exception? ex, string? message, params object[]? args)
public void LogError(string? message, params object[]? args)
{
using (LogContext.PushProperty("Error", ex))
using (LogContext.PushProperty("LogLevel", "Error"))
_logger.LogError(message, args);
}

View File

@ -1,16 +1,11 @@
using Marco.Pms.DataAccess.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Marco.Pms.DataAccess.Data;
using Marco.Pms.Model.Authentication;
using Marco.Pms.Model.Entitlements;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using SharpCompress.Common;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
namespace MarcoBMS.Services.Service

View File

@ -22,7 +22,7 @@
{
"Name": "MongoDB",
"Args": {
"databaseUrl": "mongodb://localhost:27017/DotNetLogs",
"databaseUrl": "mongodb+srv://ashutoshnehete:OL1Cy0pTQaGn4hcP@marcopms.m32uppx.mongodb.net/MarcoPMS?retryWrites=true&w=majority",
//"databaseUrl": "mongodb://devuser:xxxxx@147.93.98.152:27017/MarcoPMS?authSource=admin",
"collectionName": "application_logs",
"batchPostingLimit": 50,
@ -64,8 +64,9 @@
"ConnectionStrings": {
// "DefaultConnectionString": "Server=103.50.160.45;User ID=marcowvh_admin;Password=Marcoemp@123;Database=marcowvh_empattendanceci",
"DefaultConnectionString": "Server=localhost;port=3333;User ID=root;Password=root;Database=MarcoBMS1",
//"DefaultConnectionString": "Server=147.93.98.152;User ID=devuser;Password=AppUser@123$;Database=MarcoBMS1"
//"DefaultConnectionString": "Server=localhost;port=3306;User ID=root;Password=Ashutosh;Database=MarcoBMS1"
//"DefaultConnectionString": "Server=localhost;port=3333;User ID=root;Password=root;Database=MarcoBMS1",
"DefaultConnectionString": "Server=147.93.98.152;User ID=devuser;Password=AppUser@123$;Database=MarcoBMS1"
},
"AppSettings": {
"WebFrontendUrl": "http://localhost:5173",