Compare commits
50 Commits
main
...
Payment_Ga
| Author | SHA1 | Date | |
|---|---|---|---|
| 68aec35028 | |||
| a684556cff | |||
| ee48d7372a | |||
| c3b93022fd | |||
| 7e634e3a47 | |||
| e94210a341 | |||
| 918f856632 | |||
| 663d94093c | |||
| dc83aa72a6 | |||
| ef597b2bb7 | |||
| 4acc61f03a | |||
| c47b0da7b8 | |||
| d180d5d60e | |||
| 60eefa78c0 | |||
| b1af96b923 | |||
| 629c4541d6 | |||
| e93408c00d | |||
| 16e509ccbd | |||
| 8a4a056c2d | |||
| f6e8a0d5e2 | |||
| 0561e356d8 | |||
| e2ee3f325c | |||
| 6441103e30 | |||
| d380dfebd2 | |||
| 658fa8cd23 | |||
| 3afdad29b2 | |||
| 8f463ce90d | |||
| 590476a8aa | |||
| 548e714ea9 | |||
| 91f4305995 | |||
| 7e15c517ac | |||
| 9332d9cc0b | |||
| 541ed28bd2 | |||
| 0e1d20156f | |||
| 87c5de87a1 | |||
| 5eda1773b7 | |||
| b3f54962ab | |||
| 040e7df32b | |||
| 0066e20c43 | |||
| 7659eadd00 | |||
| 824381bb49 | |||
| 207a44acd7 | |||
| 7775f58d69 | |||
| 91be729b41 | |||
| 0bd57d29d8 | |||
| b442bb4bbc | |||
| ca3e47c1e6 | |||
| 061512d501 | |||
| 71cc442054 | |||
| bab03a8e47 |
@ -1,6 +1,7 @@
|
||||
using Marco.Pms.Model.Activities;
|
||||
using Marco.Pms.Model.AttendanceModule;
|
||||
using Marco.Pms.Model.Authentication;
|
||||
using Marco.Pms.Model.Collection;
|
||||
using Marco.Pms.Model.Directory;
|
||||
using Marco.Pms.Model.DocumentManager;
|
||||
using Marco.Pms.Model.Employees;
|
||||
@ -10,6 +11,7 @@ using Marco.Pms.Model.Forum;
|
||||
using Marco.Pms.Model.Mail;
|
||||
using Marco.Pms.Model.Master;
|
||||
using Marco.Pms.Model.OrganizationModel;
|
||||
using Marco.Pms.Model.PaymentGetway;
|
||||
using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.Roles;
|
||||
using Marco.Pms.Model.TenantModels;
|
||||
@ -133,6 +135,16 @@ namespace Marco.Pms.DataAccess.Data
|
||||
public DbSet<ProjectServiceMapping> ProjectServiceMappings { get; set; }
|
||||
public DbSet<ProjectOrgMapping> ProjectOrgMappings { get; set; }
|
||||
|
||||
// Collection
|
||||
public DbSet<Invoice> Invoices { get; set; }
|
||||
public DbSet<InvoiceComment> InvoiceComments { get; set; }
|
||||
public DbSet<InvoiceAttachment> InvoiceAttachments { get; set; }
|
||||
public DbSet<ReceivedInvoicePayment> ReceivedInvoicePayments { get; set; }
|
||||
public DbSet<PaymentAdjustmentHead> PaymentAdjustmentHeads { get; set; }
|
||||
|
||||
public DbSet<PaymentDetail> PaymentDetails { get; set; }
|
||||
public DbSet<TenantEnquire> TenantEnquires { get; set; }
|
||||
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@ -775,6 +787,65 @@ namespace Marco.Pms.DataAccess.Data
|
||||
}
|
||||
);
|
||||
|
||||
modelBuilder.Entity<PaymentAdjustmentHead>().HasData(
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("dbdc047f-a2d2-4db0-b0e6-b9d9f923a0f1"),
|
||||
Name = "Advance payment",
|
||||
Description = "An advance payment is a sum paid before receiving goods or services, often to secure a transaction or cover initial costs.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("66c3c241-8b52-4327-a5ad-c1faf102583e"),
|
||||
Name = "Base Amount",
|
||||
Description = "The base amount refers to the principal sum or original value used as a reference in financial calculations, excluding taxes, fees, or additional charges.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("0d70cb2e-827e-44fc-90a5-c2c55ba51ba9"),
|
||||
Name = "Tax Deducted at Source (TDS)",
|
||||
Description = "TDS, or Tax Deducted at Source, is a system under the Indian Income Tax Act where tax is deducted at the point of income generation—such as salary, interest, or rent—and remitted to the government to prevent tax evasion and ensure timely collection.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("95f35acd-d979-4177-91ea-fd03a00e49ff"),
|
||||
Name = "Retention",
|
||||
Description = "Retention refers to a company's ability to keep customers, employees, or profits over time, commonly measured as a percentage and critical for long-term business sustainability and growth.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("3f09b19a-8d45-4cf2-be27-f4f09b38b9f7"),
|
||||
Name = "Tax",
|
||||
Description = "Tax is a mandatory financial charge imposed by a government on individuals or entities to fund public services and government operations, without direct benefit to the taxpayer.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("ec5e6a5f-ce62-44e5-8911-8426bbb4dde8"),
|
||||
Name = "Penalty",
|
||||
Description = "A penalty in the context of taxation is a financial sanction imposed by the government on individuals or entities for non-compliance with tax laws, such as late filing, underreporting income, or failure to pay taxes, and is typically calculated as a percentage of the tax due or a fixed amount.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new PaymentAdjustmentHead
|
||||
{
|
||||
Id = Guid.Parse("50584332-1cb7-4359-9721-c8ea35040881"),
|
||||
Name = "Utility fees",
|
||||
Description = "Utility fees are recurring charges for essential services such as electricity, water, gas, sewage, waste disposal, internet, and telecommunications, typically based on usage and necessary for operating a home or business.",
|
||||
IsActive = true,
|
||||
TenantId = Guid.Parse("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
}
|
||||
);
|
||||
|
||||
modelBuilder.Entity<EntityTypeMaster>().HasData(
|
||||
new EntityTypeMaster
|
||||
{
|
||||
@ -1039,6 +1110,7 @@ namespace Marco.Pms.DataAccess.Data
|
||||
// Project Module
|
||||
new Feature { Id = new Guid("53176ebf-c75d-42e5-839f-4508ffac3def"), Description = "Manage Project", Name = "Project Management", ModuleId = new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"), IsActive = true },
|
||||
new Feature { Id = new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), Description = "Expense Management is the systematic process of tracking, controlling, and reporting business-related expenditures.", Name = "Expense Management", ModuleId = new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"), IsActive = true },
|
||||
new Feature { Id = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), Description = "Collection Management is a feature that enables organizations to track, organize, and manage the status and recovery of receivables or assets efficiently throughout their lifecycle, supporting systematic follow-up and resolution of outstanding accounts.", Name = "Collection Management", ModuleId = new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"), IsActive = true },
|
||||
new Feature { Id = new Guid("9d4b5489-2079-40b9-bd77-6e1bf90bc19f"), Description = "Manage Tasks", Name = "Task Management", ModuleId = new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"), IsActive = true },
|
||||
|
||||
// Employee Module
|
||||
@ -1110,6 +1182,13 @@ namespace Marco.Pms.DataAccess.Data
|
||||
new FeaturePermission { Id = new Guid("ea5a1529-4ee8-4828-80ea-0e23c9d4dd11"), FeatureId = new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), IsEnabled = true, Name = "Process", Description = "Allows a user to handle post-approval actions such as recording payments, updating financial records, or marking expenses as reimbursed or settled." },
|
||||
new FeaturePermission { Id = new Guid("bdee29a2-b73b-402d-8dd1-c4b1f81ccbc3"), FeatureId = new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), IsEnabled = true, Name = "Manage", Description = "Allows a user to configure and control system settings, such as managing expense types, payment modes, permissions, and overall workflow rules." },
|
||||
|
||||
// Collection Management Feature
|
||||
new FeaturePermission { Id = new Guid("dbf17591-09fe-4c93-9e1a-12db8f5cc5de"), FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), IsEnabled = true, Name = "Collection Admin", Description = "Collection Admin is a permission that grants a user full administrative control over collections, including creating, editing, managing access, and deleting collections within a system." },
|
||||
new FeaturePermission { Id = new Guid("c8d7eea5-4033-4aad-9ebe-76de49896830"), FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), IsEnabled = true, Name = "View Collection", Description = "View Collection is a permission that allows users to see and browse assets or items within a collection without making any modifications or edits to its contents." },
|
||||
new FeaturePermission { Id = new Guid("b93141fd-dbd3-4051-8f57-bf25d18e3555"), FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), IsEnabled = true, Name = "Create Collection", Description = "Authorizes users to create new collections for organizing related resources and managing access" },
|
||||
new FeaturePermission { Id = new Guid("455187b4-fef1-41f9-b3d0-025d0b6302c3"), FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), IsEnabled = true, Name = "Edit Collection", Description = "Ability to modify collection properties, content, and access rights." },
|
||||
new FeaturePermission { Id = new Guid("061d9ccd-85b4-4cb0-be06-2f9f32cebb72"), FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), IsEnabled = true, Name = "Add Payment", Description = " Enables entry and processing of payment transactions." },
|
||||
|
||||
// Organization Management Feature
|
||||
new FeaturePermission { Id = new Guid("068cb3c1-49c5-4746-9f29-1fce16e820ac"), FeatureId = new Guid("6d4c82d6-dbce-48ab-b8b8-f785f4d8c914"), IsEnabled = true, Name = "Add Organization", Description = "Allow user to create new organization" },
|
||||
new FeaturePermission { Id = new Guid("c1ae1363-ab8a-4bd9-a9d1-8c2c6083873a"), FeatureId = new Guid("6d4c82d6-dbce-48ab-b8b8-f785f4d8c914"), IsEnabled = true, Name = "Edit Organization", Description = "Allow the user to update the basic information of the organization" },
|
||||
|
||||
6209
Marco.Pms.DataAccess/Migrations/20251003093145_Added_ExpenceUID_In_Expense_Table.Designer.cs
generated
Normal file
6209
Marco.Pms.DataAccess/Migrations/20251003093145_Added_ExpenceUID_In_Expense_Table.Designer.cs
generated
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Marco.Pms.DataAccess.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Added_ExpenceUID_In_Expense_Table : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "ExpenseUId",
|
||||
table: "Expenses",
|
||||
type: "longtext",
|
||||
nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ExpenseUId",
|
||||
table: "Expenses");
|
||||
}
|
||||
}
|
||||
}
|
||||
6226
Marco.Pms.DataAccess/Migrations/20251008121556_Added_Requested_In_Attendance_Table.Designer.cs
generated
Normal file
6226
Marco.Pms.DataAccess/Migrations/20251008121556_Added_Requested_In_Attendance_Table.Designer.cs
generated
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Marco.Pms.DataAccess.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Added_Requested_In_Attendance_Table : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "ApprovedAt",
|
||||
table: "Attendes",
|
||||
type: "datetime(6)",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "RequestedAt",
|
||||
table: "Attendes",
|
||||
type: "datetime(6)",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "RequestedById",
|
||||
table: "Attendes",
|
||||
type: "char(36)",
|
||||
nullable: true,
|
||||
collation: "ascii_general_ci");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Attendes_RequestedById",
|
||||
table: "Attendes",
|
||||
column: "RequestedById");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Attendes_Employees_RequestedById",
|
||||
table: "Attendes",
|
||||
column: "RequestedById",
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Attendes_Employees_RequestedById",
|
||||
table: "Attendes");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Attendes_RequestedById",
|
||||
table: "Attendes");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ApprovedAt",
|
||||
table: "Attendes");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RequestedAt",
|
||||
table: "Attendes");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "RequestedById",
|
||||
table: "Attendes");
|
||||
}
|
||||
}
|
||||
}
|
||||
6783
Marco.Pms.DataAccess/Migrations/20251029065544_Added_Payment_Related_Tables.Designer.cs
generated
Normal file
6783
Marco.Pms.DataAccess/Migrations/20251029065544_Added_Payment_Related_Tables.Designer.cs
generated
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,469 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
|
||||
|
||||
namespace Marco.Pms.DataAccess.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class Added_Payment_Related_Tables : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "PaymentDetailId",
|
||||
table: "TenantSubscriptions",
|
||||
type: "char(36)",
|
||||
nullable: true,
|
||||
collation: "ascii_general_ci");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Invoices",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Title = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Description = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
InvoiceNumber = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
EInvoiceNumber = table.Column<string>(type: "longtext", nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
ProjectId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
InvoiceDate = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
ClientSubmitedDate = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
ExceptedPaymentDate = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
BasicAmount = table.Column<double>(type: "double", nullable: false),
|
||||
TaxAmount = table.Column<double>(type: "double", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
MarkAsCompleted = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
CreatedById = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
UpdatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
|
||||
UpdatedById = table.Column<Guid>(type: "char(36)", nullable: true, collation: "ascii_general_ci"),
|
||||
TenantId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Invoices", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_Invoices_Employees_CreatedById",
|
||||
column: x => x.CreatedById,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_Invoices_Employees_UpdatedById",
|
||||
column: x => x.UpdatedById,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id");
|
||||
table.ForeignKey(
|
||||
name: "FK_Invoices_Projects_ProjectId",
|
||||
column: x => x.ProjectId,
|
||||
principalTable: "Projects",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_Invoices_Tenants_TenantId",
|
||||
column: x => x.TenantId,
|
||||
principalTable: "Tenants",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PaymentAdjustmentHeads",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Name = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Description = table.Column<string>(type: "longtext", nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
TenantId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PaymentAdjustmentHeads", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_PaymentAdjustmentHeads_Tenants_TenantId",
|
||||
column: x => x.TenantId,
|
||||
principalTable: "Tenants",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "PaymentDetails",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
PaymentId = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
OrderId = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Status = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Method = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
EncryptedDetails = table.Column<byte[]>(type: "longblob", nullable: true),
|
||||
Nonce = table.Column<byte[]>(type: "longblob", nullable: true),
|
||||
Tag = table.Column<byte[]>(type: "longblob", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_PaymentDetails", x => x.Id);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "TenantEnquires",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FirstName = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
LastName = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
OrganizationName = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Email = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
ContactNumber = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
BillingAddress = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
OrganizationSize = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
IndustryId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Reference = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_TenantEnquires", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_TenantEnquires_Industries_IndustryId",
|
||||
column: x => x.IndustryId,
|
||||
principalTable: "Industries",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "InvoiceAttachments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
InvoiceId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
DocumentId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
TenantId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_InvoiceAttachments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceAttachments_Documents_DocumentId",
|
||||
column: x => x.DocumentId,
|
||||
principalTable: "Documents",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceAttachments_Invoices_InvoiceId",
|
||||
column: x => x.InvoiceId,
|
||||
principalTable: "Invoices",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceAttachments_Tenants_TenantId",
|
||||
column: x => x.TenantId,
|
||||
principalTable: "Tenants",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "InvoiceComments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Comment = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
CreatedById = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
InvoiceId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
TenantId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_InvoiceComments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceComments_Employees_CreatedById",
|
||||
column: x => x.CreatedById,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceComments_Invoices_InvoiceId",
|
||||
column: x => x.InvoiceId,
|
||||
principalTable: "Invoices",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_InvoiceComments_Tenants_TenantId",
|
||||
column: x => x.TenantId,
|
||||
principalTable: "Tenants",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ReceivedInvoicePayments",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
InvoiceId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
PaymentReceivedDate = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
TransactionId = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
Amount = table.Column<double>(type: "double", nullable: false),
|
||||
Comment = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
PaymentAdjustmentHeadId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
CreatedById = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
TenantId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ReceivedInvoicePayments", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ReceivedInvoicePayments_Employees_CreatedById",
|
||||
column: x => x.CreatedById,
|
||||
principalTable: "Employees",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_ReceivedInvoicePayments_Invoices_InvoiceId",
|
||||
column: x => x.InvoiceId,
|
||||
principalTable: "Invoices",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_ReceivedInvoicePayments_PaymentAdjustmentHeads_PaymentAdjust~",
|
||||
column: x => x.PaymentAdjustmentHeadId,
|
||||
principalTable: "PaymentAdjustmentHeads",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_ReceivedInvoicePayments_Tenants_TenantId",
|
||||
column: x => x.TenantId,
|
||||
principalTable: "Tenants",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Features",
|
||||
columns: new[] { "Id", "Description", "IsActive", "ModuleId", "Name" },
|
||||
values: new object[] { new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), "Collection Management is a feature that enables organizations to track, organize, and manage the status and recovery of receivables or assets efficiently throughout their lifecycle, supporting systematic follow-up and resolution of outstanding accounts.", true, new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"), "Collection Management" });
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "PaymentAdjustmentHeads",
|
||||
columns: new[] { "Id", "Description", "IsActive", "Name", "TenantId" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ new Guid("0d70cb2e-827e-44fc-90a5-c2c55ba51ba9"), "TDS, or Tax Deducted at Source, is a system under the Indian Income Tax Act where tax is deducted at the point of income generation—such as salary, interest, or rent—and remitted to the government to prevent tax evasion and ensure timely collection.", true, "Tax Deducted at Source (TDS)", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("3f09b19a-8d45-4cf2-be27-f4f09b38b9f7"), "Tax is a mandatory financial charge imposed by a government on individuals or entities to fund public services and government operations, without direct benefit to the taxpayer.", true, "Tax", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("50584332-1cb7-4359-9721-c8ea35040881"), "Utility fees are recurring charges for essential services such as electricity, water, gas, sewage, waste disposal, internet, and telecommunications, typically based on usage and necessary for operating a home or business.", true, "Utility fees", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("66c3c241-8b52-4327-a5ad-c1faf102583e"), "The base amount refers to the principal sum or original value used as a reference in financial calculations, excluding taxes, fees, or additional charges.", true, "Base Amount", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("95f35acd-d979-4177-91ea-fd03a00e49ff"), "Retention refers to a company's ability to keep customers, employees, or profits over time, commonly measured as a percentage and critical for long-term business sustainability and growth.", true, "Retention", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("dbdc047f-a2d2-4db0-b0e6-b9d9f923a0f1"), "An advance payment is a sum paid before receiving goods or services, often to secure a transaction or cover initial costs.", true, "Advance payment", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") },
|
||||
{ new Guid("ec5e6a5f-ce62-44e5-8911-8426bbb4dde8"), "A penalty in the context of taxation is a financial sanction imposed by the government on individuals or entities for non-compliance with tax laws, such as late filing, underreporting income, or failure to pay taxes, and is typically calculated as a percentage of the tax due or a fixed amount.", true, "Penalty", new Guid("b3466e83-7e11-464c-b93a-daf047838b26") }
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "FeaturePermissions",
|
||||
columns: new[] { "Id", "Description", "FeatureId", "IsEnabled", "Name" },
|
||||
values: new object[,]
|
||||
{
|
||||
{ new Guid("061d9ccd-85b4-4cb0-be06-2f9f32cebb72"), " Enables entry and processing of payment transactions.", new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), true, "Add Payment" },
|
||||
{ new Guid("455187b4-fef1-41f9-b3d0-025d0b6302c3"), "Ability to modify collection properties, content, and access rights.", new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), true, "Edit Collection" },
|
||||
{ new Guid("b93141fd-dbd3-4051-8f57-bf25d18e3555"), "Authorizes users to create new collections for organizing related resources and managing access", new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), true, "Create Collection" },
|
||||
{ new Guid("c8d7eea5-4033-4aad-9ebe-76de49896830"), "View Collection is a permission that allows users to see and browse assets or items within a collection without making any modifications or edits to its contents.", new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), true, "View Collection" },
|
||||
{ new Guid("dbf17591-09fe-4c93-9e1a-12db8f5cc5de"), "Collection Admin is a permission that grants a user full administrative control over collections, including creating, editing, managing access, and deleting collections within a system.", new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"), true, "Collection Admin" }
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TenantSubscriptions_PaymentDetailId",
|
||||
table: "TenantSubscriptions",
|
||||
column: "PaymentDetailId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceAttachments_DocumentId",
|
||||
table: "InvoiceAttachments",
|
||||
column: "DocumentId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceAttachments_InvoiceId",
|
||||
table: "InvoiceAttachments",
|
||||
column: "InvoiceId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceAttachments_TenantId",
|
||||
table: "InvoiceAttachments",
|
||||
column: "TenantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceComments_CreatedById",
|
||||
table: "InvoiceComments",
|
||||
column: "CreatedById");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceComments_InvoiceId",
|
||||
table: "InvoiceComments",
|
||||
column: "InvoiceId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_InvoiceComments_TenantId",
|
||||
table: "InvoiceComments",
|
||||
column: "TenantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Invoices_CreatedById",
|
||||
table: "Invoices",
|
||||
column: "CreatedById");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Invoices_ProjectId",
|
||||
table: "Invoices",
|
||||
column: "ProjectId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Invoices_TenantId",
|
||||
table: "Invoices",
|
||||
column: "TenantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Invoices_UpdatedById",
|
||||
table: "Invoices",
|
||||
column: "UpdatedById");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_PaymentAdjustmentHeads_TenantId",
|
||||
table: "PaymentAdjustmentHeads",
|
||||
column: "TenantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ReceivedInvoicePayments_CreatedById",
|
||||
table: "ReceivedInvoicePayments",
|
||||
column: "CreatedById");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ReceivedInvoicePayments_InvoiceId",
|
||||
table: "ReceivedInvoicePayments",
|
||||
column: "InvoiceId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ReceivedInvoicePayments_PaymentAdjustmentHeadId",
|
||||
table: "ReceivedInvoicePayments",
|
||||
column: "PaymentAdjustmentHeadId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ReceivedInvoicePayments_TenantId",
|
||||
table: "ReceivedInvoicePayments",
|
||||
column: "TenantId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_TenantEnquires_IndustryId",
|
||||
table: "TenantEnquires",
|
||||
column: "IndustryId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_TenantSubscriptions_PaymentDetails_PaymentDetailId",
|
||||
table: "TenantSubscriptions",
|
||||
column: "PaymentDetailId",
|
||||
principalTable: "PaymentDetails",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_TenantSubscriptions_PaymentDetails_PaymentDetailId",
|
||||
table: "TenantSubscriptions");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "InvoiceAttachments");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "InvoiceComments");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "PaymentDetails");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ReceivedInvoicePayments");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "TenantEnquires");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Invoices");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "PaymentAdjustmentHeads");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_TenantSubscriptions_PaymentDetailId",
|
||||
table: "TenantSubscriptions");
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "FeaturePermissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("061d9ccd-85b4-4cb0-be06-2f9f32cebb72"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "FeaturePermissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("455187b4-fef1-41f9-b3d0-025d0b6302c3"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "FeaturePermissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("b93141fd-dbd3-4051-8f57-bf25d18e3555"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "FeaturePermissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("c8d7eea5-4033-4aad-9ebe-76de49896830"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "FeaturePermissions",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("dbf17591-09fe-4c93-9e1a-12db8f5cc5de"));
|
||||
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Features",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"));
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "PaymentDetailId",
|
||||
table: "TenantSubscriptions");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -172,6 +172,9 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.Property<int>("Activity")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTime?>("ApprovedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid?>("ApprovedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
@ -200,6 +203,12 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.Property<Guid>("ProjectID")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime?>("RequestedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid?>("RequestedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
@ -209,6 +218,8 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
|
||||
b.HasIndex("EmployeeId");
|
||||
|
||||
b.HasIndex("RequestedById");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.ToTable("Attendes");
|
||||
@ -358,6 +369,273 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.Invoice", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<double>("BasicAmount")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<DateTime>("ClientSubmitedDate")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("CreatedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("EInvoiceNumber")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTime>("ExceptedPaymentDate")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<DateTime>("InvoiceDate")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<string>("InvoiceNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("MarkAsCompleted")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<Guid>("ProjectId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<double>("TaxAmount")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTime?>("UpdatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid?>("UpdatedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedById");
|
||||
|
||||
b.HasIndex("ProjectId");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.HasIndex("UpdatedById");
|
||||
|
||||
b.ToTable("Invoices");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.InvoiceAttachment", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("DocumentId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("InvoiceId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("DocumentId");
|
||||
|
||||
b.HasIndex("InvoiceId");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.ToTable("InvoiceAttachments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.InvoiceComment", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Comment")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("CreatedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("InvoiceId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedById");
|
||||
|
||||
b.HasIndex("InvoiceId");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.ToTable("InvoiceComments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.PaymentAdjustmentHead", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.ToTable("PaymentAdjustmentHeads");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = new Guid("dbdc047f-a2d2-4db0-b0e6-b9d9f923a0f1"),
|
||||
Description = "An advance payment is a sum paid before receiving goods or services, often to secure a transaction or cover initial costs.",
|
||||
IsActive = true,
|
||||
Name = "Advance payment",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("66c3c241-8b52-4327-a5ad-c1faf102583e"),
|
||||
Description = "The base amount refers to the principal sum or original value used as a reference in financial calculations, excluding taxes, fees, or additional charges.",
|
||||
IsActive = true,
|
||||
Name = "Base Amount",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("0d70cb2e-827e-44fc-90a5-c2c55ba51ba9"),
|
||||
Description = "TDS, or Tax Deducted at Source, is a system under the Indian Income Tax Act where tax is deducted at the point of income generation—such as salary, interest, or rent—and remitted to the government to prevent tax evasion and ensure timely collection.",
|
||||
IsActive = true,
|
||||
Name = "Tax Deducted at Source (TDS)",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("95f35acd-d979-4177-91ea-fd03a00e49ff"),
|
||||
Description = "Retention refers to a company's ability to keep customers, employees, or profits over time, commonly measured as a percentage and critical for long-term business sustainability and growth.",
|
||||
IsActive = true,
|
||||
Name = "Retention",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("3f09b19a-8d45-4cf2-be27-f4f09b38b9f7"),
|
||||
Description = "Tax is a mandatory financial charge imposed by a government on individuals or entities to fund public services and government operations, without direct benefit to the taxpayer.",
|
||||
IsActive = true,
|
||||
Name = "Tax",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("ec5e6a5f-ce62-44e5-8911-8426bbb4dde8"),
|
||||
Description = "A penalty in the context of taxation is a financial sanction imposed by the government on individuals or entities for non-compliance with tax laws, such as late filing, underreporting income, or failure to pay taxes, and is typically calculated as a percentage of the tax due or a fixed amount.",
|
||||
IsActive = true,
|
||||
Name = "Penalty",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("50584332-1cb7-4359-9721-c8ea35040881"),
|
||||
Description = "Utility fees are recurring charges for essential services such as electricity, water, gas, sewage, waste disposal, internet, and telecommunications, typically based on usage and necessary for operating a home or business.",
|
||||
IsActive = true,
|
||||
Name = "Utility fees",
|
||||
TenantId = new Guid("b3466e83-7e11-464c-b93a-daf047838b26")
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.ReceivedInvoicePayment", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<double>("Amount")
|
||||
.HasColumnType("double");
|
||||
|
||||
b.Property<string>("Comment")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("CreatedById")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("InvoiceId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<Guid>("PaymentAdjustmentHeadId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("PaymentReceivedDate")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("TenantId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("TransactionId")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CreatedById");
|
||||
|
||||
b.HasIndex("InvoiceId");
|
||||
|
||||
b.HasIndex("PaymentAdjustmentHeadId");
|
||||
|
||||
b.HasIndex("TenantId");
|
||||
|
||||
b.ToTable("ReceivedInvoicePayments");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Directory.Bucket", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@ -1677,6 +1955,46 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
Name = "Manage"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("dbf17591-09fe-4c93-9e1a-12db8f5cc5de"),
|
||||
Description = "Collection Admin is a permission that grants a user full administrative control over collections, including creating, editing, managing access, and deleting collections within a system.",
|
||||
FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
IsEnabled = true,
|
||||
Name = "Collection Admin"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("c8d7eea5-4033-4aad-9ebe-76de49896830"),
|
||||
Description = "View Collection is a permission that allows users to see and browse assets or items within a collection without making any modifications or edits to its contents.",
|
||||
FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
IsEnabled = true,
|
||||
Name = "View Collection"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("b93141fd-dbd3-4051-8f57-bf25d18e3555"),
|
||||
Description = "Authorizes users to create new collections for organizing related resources and managing access",
|
||||
FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
IsEnabled = true,
|
||||
Name = "Create Collection"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("455187b4-fef1-41f9-b3d0-025d0b6302c3"),
|
||||
Description = "Ability to modify collection properties, content, and access rights.",
|
||||
FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
IsEnabled = true,
|
||||
Name = "Edit Collection"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("061d9ccd-85b4-4cb0-be06-2f9f32cebb72"),
|
||||
Description = " Enables entry and processing of payment transactions.",
|
||||
FeatureId = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
IsEnabled = true,
|
||||
Name = "Add Payment"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("068cb3c1-49c5-4746-9f29-1fce16e820ac"),
|
||||
Description = "Allow user to create new organization",
|
||||
@ -1832,6 +2150,10 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ExpenseUId")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("ExpensesTypeId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
@ -2814,6 +3136,14 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
Name = "Expense Management"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("fc586e7d-ed1a-45e5-bb51-9f34af98ec13"),
|
||||
Description = "Collection Management is a feature that enables organizations to track, organize, and manage the status and recovery of receivables or assets efficiently throughout their lifecycle, supporting systematic follow-up and resolution of outstanding accounts.",
|
||||
IsActive = true,
|
||||
ModuleId = new Guid("bf59fd88-b57a-4d67-bf01-3780f385896b"),
|
||||
Name = "Collection Management"
|
||||
},
|
||||
new
|
||||
{
|
||||
Id = new Guid("9d4b5489-2079-40b9-bd77-6e1bf90bc19f"),
|
||||
Description = "Manage Tasks",
|
||||
@ -3794,6 +4124,45 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.ToTable("TenantOrgMappings");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.PaymentGetway.PaymentDetail", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<byte[]>("EncryptedDetails")
|
||||
.HasColumnType("longblob");
|
||||
|
||||
b.Property<string>("Method")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<byte[]>("Nonce")
|
||||
.HasColumnType("longblob");
|
||||
|
||||
b.Property<string>("OrderId")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("PaymentId")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<byte[]>("Tag")
|
||||
.HasColumnType("longblob");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("PaymentDetails");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Projects.Building", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@ -4253,6 +4622,54 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.TenantModels.TenantEnquire", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("BillingAddress")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("ContactNumber")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid>("IndustryId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("LastName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("OrganizationName")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("OrganizationSize")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<string>("Reference")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("IndustryId");
|
||||
|
||||
b.ToTable("TenantEnquires");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.TenantModels.TenantSubscriptions", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@ -4289,6 +4706,9 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.Property<DateTime>("NextBillingDate")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid?>("PaymentDetailId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("PlanId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
@ -4313,6 +4733,8 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
|
||||
b.HasIndex("CurrencyId");
|
||||
|
||||
b.HasIndex("PaymentDetailId");
|
||||
|
||||
b.HasIndex("PlanId");
|
||||
|
||||
b.HasIndex("StatusId");
|
||||
@ -4711,6 +5133,10 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "RequestedBy")
|
||||
.WithMany()
|
||||
.HasForeignKey("RequestedById");
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
@ -4721,6 +5147,8 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
|
||||
b.Navigation("Employee");
|
||||
|
||||
b.Navigation("RequestedBy");
|
||||
|
||||
b.Navigation("Tenant");
|
||||
});
|
||||
|
||||
@ -4773,6 +5201,139 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.Invoice", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "CreatedBy")
|
||||
.WithMany()
|
||||
.HasForeignKey("CreatedById")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Projects.Project", "Project")
|
||||
.WithMany()
|
||||
.HasForeignKey("ProjectId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "UpdatedBy")
|
||||
.WithMany()
|
||||
.HasForeignKey("UpdatedById");
|
||||
|
||||
b.Navigation("CreatedBy");
|
||||
|
||||
b.Navigation("Project");
|
||||
|
||||
b.Navigation("Tenant");
|
||||
|
||||
b.Navigation("UpdatedBy");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.InvoiceAttachment", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.DocumentManager.Document", "Document")
|
||||
.WithMany()
|
||||
.HasForeignKey("DocumentId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Collection.Invoice", "Invoice")
|
||||
.WithMany()
|
||||
.HasForeignKey("InvoiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Document");
|
||||
|
||||
b.Navigation("Invoice");
|
||||
|
||||
b.Navigation("Tenant");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.InvoiceComment", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "CreatedBy")
|
||||
.WithMany()
|
||||
.HasForeignKey("CreatedById")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Collection.Invoice", "Invoice")
|
||||
.WithMany()
|
||||
.HasForeignKey("InvoiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("CreatedBy");
|
||||
|
||||
b.Navigation("Invoice");
|
||||
|
||||
b.Navigation("Tenant");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.PaymentAdjustmentHead", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Tenant");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Collection.ReceivedInvoicePayment", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "CreatedBy")
|
||||
.WithMany()
|
||||
.HasForeignKey("CreatedById")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Collection.Invoice", "Invoice")
|
||||
.WithMany()
|
||||
.HasForeignKey("InvoiceId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.Collection.PaymentAdjustmentHead", "PaymentAdjustmentHead")
|
||||
.WithMany()
|
||||
.HasForeignKey("PaymentAdjustmentHeadId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.Tenant", "Tenant")
|
||||
.WithMany()
|
||||
.HasForeignKey("TenantId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("CreatedBy");
|
||||
|
||||
b.Navigation("Invoice");
|
||||
|
||||
b.Navigation("PaymentAdjustmentHead");
|
||||
|
||||
b.Navigation("Tenant");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.Directory.Bucket", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "CreatedBy")
|
||||
@ -6076,6 +6637,17 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
b.Navigation("TenantStatus");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.TenantModels.TenantEnquire", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Master.Industry", "Industry")
|
||||
.WithMany()
|
||||
.HasForeignKey("IndustryId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Industry");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Marco.Pms.Model.TenantModels.TenantSubscriptions", b =>
|
||||
{
|
||||
b.HasOne("Marco.Pms.Model.Employees.Employee", "CreatedBy")
|
||||
@ -6090,6 +6662,10 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Marco.Pms.Model.PaymentGetway.PaymentDetail", "PaymentDetail")
|
||||
.WithMany()
|
||||
.HasForeignKey("PaymentDetailId");
|
||||
|
||||
b.HasOne("Marco.Pms.Model.TenantModels.SubscriptionPlanDetails", "Plan")
|
||||
.WithMany()
|
||||
.HasForeignKey("PlanId")
|
||||
@ -6116,6 +6692,8 @@ namespace Marco.Pms.DataAccess.Migrations
|
||||
|
||||
b.Navigation("Currency");
|
||||
|
||||
b.Navigation("PaymentDetail");
|
||||
|
||||
b.Navigation("Plan");
|
||||
|
||||
b.Navigation("Status");
|
||||
|
||||
@ -234,6 +234,27 @@ namespace Marco.Pms.Helpers.CacheHelper
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public async Task<bool> ClearAllEmployeesFromCacheByTenantId(Guid tenantId)
|
||||
{
|
||||
var tenantIdString = tenantId.ToString();
|
||||
|
||||
try
|
||||
{
|
||||
var filter = Builders<EmployeePermissionMongoDB>.Filter.Eq(e => e.TenantId, tenantIdString);
|
||||
|
||||
var result = await _collection.DeleteManyAsync(filter);
|
||||
|
||||
if (result.DeletedCount == 0)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error occured while deleting employee profile");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// A private method to handle the one-time setup of the collection's indexes.
|
||||
private async Task InitializeCollectionAsync()
|
||||
|
||||
@ -19,6 +19,8 @@ namespace Marco.Pms.Model.AttendanceModule
|
||||
public Guid ProjectID { get; set; }
|
||||
|
||||
public DateTime AttendanceDate { get; set; }
|
||||
public DateTime? RequestedAt { get; set; }
|
||||
public DateTime? ApprovedAt { get; set; }
|
||||
public DateTime? InTime { get; set; }
|
||||
public DateTime? OutTime { get; set; }
|
||||
public bool IsApproved { get; set; }
|
||||
@ -29,5 +31,10 @@ namespace Marco.Pms.Model.AttendanceModule
|
||||
[ForeignKey("ApprovedById")]
|
||||
[ValidateNever]
|
||||
public Employee? Approver { get; set; }
|
||||
public Guid? RequestedById { get; set; }
|
||||
|
||||
[ForeignKey("RequestedById")]
|
||||
[ValidateNever]
|
||||
public Employee? RequestedBy { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
41
Marco.Pms.Model/Collection/Invoice.cs
Normal file
41
Marco.Pms.Model/Collection/Invoice.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Marco.Pms.Model.Collection
|
||||
{
|
||||
public class Invoice : TenantRelation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Title { get; set; } = default!;
|
||||
public string Description { get; set; } = default!;
|
||||
public string InvoiceNumber { get; set; } = default!;
|
||||
public string? EInvoiceNumber { get; set; }
|
||||
public Guid ProjectId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("ProjectId")]
|
||||
public Project? Project { get; set; }
|
||||
public DateTime InvoiceDate { get; set; }
|
||||
public DateTime ClientSubmitedDate { get; set; }
|
||||
public DateTime ExceptedPaymentDate { get; set; }
|
||||
public double BasicAmount { get; set; }
|
||||
public double TaxAmount { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
public bool MarkAsCompleted { get; set; } = true;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public Guid CreatedById { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("CreatedById")]
|
||||
public Employee? CreatedBy { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public Guid? UpdatedById { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("UpdatedById")]
|
||||
public Employee? UpdatedBy { get; set; }
|
||||
}
|
||||
}
|
||||
22
Marco.Pms.Model/Collection/InvoiceAttachment.cs
Normal file
22
Marco.Pms.Model/Collection/InvoiceAttachment.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using Marco.Pms.Model.DocumentManager;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Marco.Pms.Model.Collection
|
||||
{
|
||||
public class InvoiceAttachment : TenantRelation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("InvoiceId")]
|
||||
public Invoice? Invoice { get; set; }
|
||||
public Guid DocumentId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("DocumentId")]
|
||||
public Document? Document { get; set; }
|
||||
}
|
||||
}
|
||||
24
Marco.Pms.Model/Collection/InvoiceComment.cs
Normal file
24
Marco.Pms.Model/Collection/InvoiceComment.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Marco.Pms.Model.Collection
|
||||
{
|
||||
public class InvoiceComment : TenantRelation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Comment { get; set; } = default!;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public Guid CreatedById { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("CreatedById")]
|
||||
public Employee? CreatedBy { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("InvoiceId")]
|
||||
public Invoice? Invoice { get; set; }
|
||||
}
|
||||
}
|
||||
12
Marco.Pms.Model/Collection/PaymentAdjustmentHead.cs
Normal file
12
Marco.Pms.Model/Collection/PaymentAdjustmentHead.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using Marco.Pms.Model.Utilities;
|
||||
|
||||
namespace Marco.Pms.Model.Collection
|
||||
{
|
||||
public class PaymentAdjustmentHead : TenantRelation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Name { get; set; } = default!;
|
||||
public string? Description { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
}
|
||||
33
Marco.Pms.Model/Collection/ReceivedInvoicePayment.cs
Normal file
33
Marco.Pms.Model/Collection/ReceivedInvoicePayment.cs
Normal file
@ -0,0 +1,33 @@
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Marco.Pms.Model.Collection
|
||||
{
|
||||
public class ReceivedInvoicePayment : TenantRelation
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("InvoiceId")]
|
||||
public Invoice? Invoice { get; set; }
|
||||
public DateTime PaymentReceivedDate { get; set; }
|
||||
public string TransactionId { get; set; } = default!;
|
||||
public double Amount { get; set; }
|
||||
public string Comment { get; set; } = default!;
|
||||
public bool IsActive { get; set; } = true;
|
||||
public Guid PaymentAdjustmentHeadId { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("PaymentAdjustmentHeadId")]
|
||||
public PaymentAdjustmentHead? PaymentAdjustmentHead { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public Guid CreatedById { get; set; }
|
||||
|
||||
[ValidateNever]
|
||||
[ForeignKey("CreatedById")]
|
||||
public Employee? CreatedBy { get; set; }
|
||||
}
|
||||
}
|
||||
@ -2,7 +2,7 @@
|
||||
{
|
||||
public class CreateWorkStatusMasterDto
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string Description { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
public class UpdateWorkStatusMasterDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string Description { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,6 +5,5 @@
|
||||
public required Guid EmployeeId { get; set; }
|
||||
public required string MPIN { get; set; }
|
||||
public required string MPINToken { get; set; }
|
||||
public required string FcmToken { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
8
Marco.Pms.Model/Dtos/Collection/InvoiceCommentDto.cs
Normal file
8
Marco.Pms.Model/Dtos/Collection/InvoiceCommentDto.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Model.Dtos.Collection
|
||||
{
|
||||
public class InvoiceCommentDto
|
||||
{
|
||||
public required string Comment { get; set; }
|
||||
public required Guid InvoiceId { get; set; }
|
||||
}
|
||||
}
|
||||
20
Marco.Pms.Model/Dtos/Collection/InvoiceDto.cs
Normal file
20
Marco.Pms.Model/Dtos/Collection/InvoiceDto.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using Marco.Pms.Model.Utilities;
|
||||
|
||||
namespace Marco.Pms.Model.Dtos.Collection
|
||||
{
|
||||
public class InvoiceDto
|
||||
{
|
||||
public Guid? Id { get; set; }
|
||||
public required string Title { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string InvoiceNumber { get; set; }
|
||||
public string? EInvoiceNumber { get; set; }
|
||||
public required Guid ProjectId { get; set; }
|
||||
public required DateTime InvoiceDate { get; set; }
|
||||
public required DateTime ClientSubmitedDate { get; set; }
|
||||
public required DateTime ExceptedPaymentDate { get; set; }
|
||||
public double BasicAmount { get; set; }
|
||||
public double TaxAmount { get; set; }
|
||||
public List<FileUploadModel>? Attachments { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
namespace Marco.Pms.Model.Dtos.Collection
|
||||
{
|
||||
public class PaymentAdjustmentHeadDto
|
||||
{
|
||||
public Guid? Id { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
}
|
||||
13
Marco.Pms.Model/Dtos/Collection/ReceivedInvoicePaymentDto.cs
Normal file
13
Marco.Pms.Model/Dtos/Collection/ReceivedInvoicePaymentDto.cs
Normal file
@ -0,0 +1,13 @@
|
||||
namespace Marco.Pms.Model.Dtos.Collection
|
||||
{
|
||||
public class ReceivedInvoicePaymentDto
|
||||
{
|
||||
public Guid? Id { get; set; }
|
||||
public required Guid InvoiceId { get; set; }
|
||||
public required DateTime PaymentReceivedDate { get; set; }
|
||||
public required string TransactionId { get; set; }
|
||||
public required Guid PaymentAdjustmentHeadId { get; set; }
|
||||
public required double Amount { get; set; }
|
||||
public required string Comment { get; set; }
|
||||
}
|
||||
}
|
||||
@ -19,7 +19,7 @@
|
||||
public string? EmergencyPhoneNumber { get; set; }
|
||||
public string? EmergencyContactPerson { get; set; }
|
||||
public Guid JobRoleId { get; set; }
|
||||
public required Guid OrganizationId { get; set; }
|
||||
public Guid? OrganizationId { get; set; }
|
||||
public required bool HasApplicationAccess { get; set; }
|
||||
}
|
||||
public class MobileUserManageDto
|
||||
@ -33,7 +33,7 @@
|
||||
public required string Gender { get; set; }
|
||||
public Guid JobRoleId { get; set; }
|
||||
public string? ProfileImage { get; set; }
|
||||
public required Guid OrganizationId { get; set; }
|
||||
public Guid? OrganizationId { get; set; }
|
||||
public required bool HasApplicationAccess { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
{
|
||||
public class CreateContactCategoryDto
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string Description { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
{
|
||||
public class CreateContactTagDto
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
public class UpdateContactCategoryDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public required string Name { get; set; }
|
||||
public required string Description { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
7
Marco.Pms.Model/Dtos/PaymentGetway/CreateOrderDto.cs
Normal file
7
Marco.Pms.Model/Dtos/PaymentGetway/CreateOrderDto.cs
Normal file
@ -0,0 +1,7 @@
|
||||
namespace Marco.Pms.Model.Dtos.PaymentGetway
|
||||
{
|
||||
public class CreateOrderDto
|
||||
{
|
||||
public double Amount { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
namespace Marco.Pms.Model.Dtos.PaymentGetway
|
||||
{
|
||||
public class PaymentVerificationRequest
|
||||
{
|
||||
public required Guid TenantEnquireId { get; set; }
|
||||
public required Guid PlanId { get; set; }
|
||||
public required string OrderId { get; set; }
|
||||
public required string PaymentId { get; set; }
|
||||
public required string Signature { get; set; }
|
||||
}
|
||||
}
|
||||
@ -27,7 +27,7 @@ namespace Marco.Pms.Model.Dtos.Project
|
||||
[DisplayName("Project Status")]
|
||||
[Required(ErrorMessage = "Project Status is required!")]
|
||||
public required Guid ProjectStatusId { get; set; }
|
||||
public required Guid PromoterId { get; set; }
|
||||
public required Guid PMCId { get; set; }
|
||||
public Guid? PromoterId { get; set; }
|
||||
public Guid? PMCId { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -27,7 +27,7 @@ namespace Marco.Pms.Model.Dtos.Project
|
||||
[DisplayName("Project Status")]
|
||||
[Required(ErrorMessage = "Project Status is required!")]
|
||||
public required Guid ProjectStatusId { get; set; }
|
||||
public required Guid PromoterId { get; set; }
|
||||
public required Guid PMCId { get; set; }
|
||||
public Guid? PromoterId { get; set; }
|
||||
public Guid? PMCId { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
8
Marco.Pms.Model/Dtos/Tenant/RenewSubscriptionDto.cs
Normal file
8
Marco.Pms.Model/Dtos/Tenant/RenewSubscriptionDto.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Model.Dtos.Tenant
|
||||
{
|
||||
public class RenewSubscriptionDto
|
||||
{
|
||||
public Guid PaymentDetailId { get; set; }
|
||||
public Guid PlanId { get; set; }
|
||||
}
|
||||
}
|
||||
9
Marco.Pms.Model/Dtos/Tenant/SelfSubscriptionDto.cs
Normal file
9
Marco.Pms.Model/Dtos/Tenant/SelfSubscriptionDto.cs
Normal file
@ -0,0 +1,9 @@
|
||||
namespace Marco.Pms.Model.Dtos.Tenant
|
||||
{
|
||||
public class SelfSubscriptionDto
|
||||
{
|
||||
public Guid TenantEnquireId { get; set; }
|
||||
public Guid PaymentDetailId { get; set; }
|
||||
public Guid PlanId { get; set; }
|
||||
}
|
||||
}
|
||||
15
Marco.Pms.Model/Dtos/Tenant/TenantEnquireDto.cs
Normal file
15
Marco.Pms.Model/Dtos/Tenant/TenantEnquireDto.cs
Normal file
@ -0,0 +1,15 @@
|
||||
namespace Marco.Pms.Model.Dtos.Tenant
|
||||
{
|
||||
public class TenantEnquireDto
|
||||
{
|
||||
public required string FirstName { get; set; }
|
||||
public required string LastName { get; set; }
|
||||
public required string OrganizationName { get; set; }
|
||||
public required string Email { get; set; }
|
||||
public required string ContactNumber { get; set; }
|
||||
public required string BillingAddress { get; set; }
|
||||
public required string OrganizationSize { get; set; }
|
||||
public required Guid IndustryId { get; set; }
|
||||
public required string Reference { get; set; }
|
||||
}
|
||||
}
|
||||
@ -47,6 +47,12 @@
|
||||
public static readonly Guid DownloadDocument = Guid.Parse("404373d0-860f-490e-a575-1c086ffbce1d");
|
||||
public static readonly Guid VerifyDocument = Guid.Parse("13a1f30f-38d1-41bf-8e7a-b75189aab8e0");
|
||||
|
||||
public static readonly Guid CollectionAdmin = Guid.Parse("dbf17591-09fe-4c93-9e1a-12db8f5cc5de");
|
||||
public static readonly Guid ViewCollection = Guid.Parse("c8d7eea5-4033-4aad-9ebe-76de49896830");
|
||||
public static readonly Guid CreateCollection = Guid.Parse("b93141fd-dbd3-4051-8f57-bf25d18e3555");
|
||||
public static readonly Guid EditCollection = Guid.Parse("455187b4-fef1-41f9-b3d0-025d0b6302c3");
|
||||
public static readonly Guid AddPayment = Guid.Parse("061d9ccd-85b4-4cb0-be06-2f9f32cebb72");
|
||||
|
||||
public static readonly Guid AddOrganization = Guid.Parse("068cb3c1-49c5-4746-9f29-1fce16e820ac");
|
||||
public static readonly Guid EditOrganization = Guid.Parse("c1ae1363-ab8a-4bd9-a9d1-8c2c6083873a");
|
||||
public static readonly Guid ViewOrganization = Guid.Parse("7a6cf830-0008-4e03-b31d-0d050cb634f4");
|
||||
|
||||
@ -54,6 +54,7 @@ namespace Marco.Pms.Model.Expenses
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public string? TransactionId { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string ExpenseUId { get; set; } = string.Empty;
|
||||
public string? Location { get; set; }
|
||||
public string? GSTNumber { get; set; }
|
||||
public string SupplerName { get; set; } = string.Empty;
|
||||
|
||||
@ -6,6 +6,7 @@
|
||||
public List<Guid>? StatusIds { get; set; }
|
||||
public List<Guid>? CreatedByIds { get; set; }
|
||||
public List<Guid>? PaidById { get; set; }
|
||||
public List<Guid>? ExpenseTypeIds { get; set; }
|
||||
public bool IsTransactionDate { get; set; } = false;
|
||||
public DateTime? StartDate { get; set; }
|
||||
public DateTime? EndDate { get; set; }
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
public List<Guid>? BuildingIds { get; set; }
|
||||
public List<Guid>? FloorIds { get; set; }
|
||||
public List<Guid>? ActivityIds { get; set; }
|
||||
public List<Guid>? ServiceIds { get; set; }
|
||||
public DateTime? dateFrom { get; set; }
|
||||
public DateTime? dateTo { get; set; }
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@ namespace Marco.Pms.Model.MongoDBModels.Expenses
|
||||
public DateTime ExpireAt { get; set; } = DateTime.UtcNow.Date.AddDays(1);
|
||||
public string SupplerName { get; set; } = string.Empty;
|
||||
public double Amount { get; set; }
|
||||
public string? ExpenseUId { get; set; }
|
||||
public ExpensesStatusMasterMongoDB Status { get; set; } = new ExpensesStatusMasterMongoDB();
|
||||
public List<ExpensesStatusMasterMongoDB> NextStatus { get; set; } = new List<ExpensesStatusMasterMongoDB>();
|
||||
public bool PreApproved { get; set; } = false;
|
||||
|
||||
16
Marco.Pms.Model/PaymentGetway/PaymentDetail.cs
Normal file
16
Marco.Pms.Model/PaymentGetway/PaymentDetail.cs
Normal file
@ -0,0 +1,16 @@
|
||||
namespace Marco.Pms.Model.PaymentGetway
|
||||
{
|
||||
public class PaymentDetail
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string PaymentId { get; set; } = string.Empty;
|
||||
public string OrderId { get; set; } = string.Empty;
|
||||
public string Status { get; set; } = string.Empty; // created, authorized, captured, refunded, failed
|
||||
public string Method { get; set; } = string.Empty;
|
||||
public byte[]? EncryptedDetails { get; set; }
|
||||
public byte[]? Nonce { get; set; }
|
||||
public byte[]? Tag { get; set; }
|
||||
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
|
||||
|
||||
}
|
||||
}
|
||||
24
Marco.Pms.Model/TenantModels/TenantEnquire.cs
Normal file
24
Marco.Pms.Model/TenantModels/TenantEnquire.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using Marco.Pms.Model.Master;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Marco.Pms.Model.TenantModels
|
||||
{
|
||||
public class TenantEnquire
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string FirstName { get; set; } = default!;
|
||||
public string LastName { get; set; } = default!;
|
||||
public string OrganizationName { get; set; } = default!;
|
||||
public string Email { get; set; } = default!;
|
||||
public string ContactNumber { get; set; } = default!;
|
||||
public string BillingAddress { get; set; } = default!;
|
||||
public string OrganizationSize { get; set; } = default!;
|
||||
public Guid IndustryId { get; set; }
|
||||
|
||||
[ForeignKey("IndustryId")]
|
||||
[ValidateNever]
|
||||
public Industry? Industry { get; set; }
|
||||
public string Reference { get; set; } = default!;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Master;
|
||||
using Marco.Pms.Model.PaymentGetway;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
@ -28,6 +29,11 @@ namespace Marco.Pms.Model.TenantModels
|
||||
[ForeignKey("CurrencyId")]
|
||||
[ValidateNever]
|
||||
public CurrencyMaster? Currency { get; set; }
|
||||
public Guid? PaymentDetailId { get; set; }
|
||||
|
||||
[ForeignKey("PaymentDetailId")]
|
||||
[ValidateNever]
|
||||
public PaymentDetail? PaymentDetail { get; set; }
|
||||
public DateTime NextBillingDate { get; set; }
|
||||
public DateTime? CancellationDate { get; set; }
|
||||
public bool AutoRenew { get; set; } = true;
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using Marco.Pms.Model.Dtos.Attendance;
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.AttendanceVM
|
||||
{
|
||||
@ -6,15 +7,20 @@ namespace Marco.Pms.Model.ViewModels.AttendanceVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid EmployeeId { get; set; }
|
||||
public Guid ProjectId { get; set; }
|
||||
public string? FirstName { get; set; }
|
||||
public string? LastName { get; set; }
|
||||
public string? EmployeeAvatar { get; set; }
|
||||
public string? OrganizationName { get; set; }
|
||||
public string? ProjectName { get; set; }
|
||||
public DateTime? CheckInTime { get; set; }
|
||||
public DateTime? CheckOutTime { get; set; }
|
||||
public DateTime? RequestedAt { get; set; }
|
||||
public DateTime? ApprovedAt { get; set; }
|
||||
public string? JobRoleName { get; set; }
|
||||
public ATTENDANCE_MARK_TYPE Activity { get; set; }
|
||||
|
||||
public BasicEmployeeVM? Approver { get; set; }
|
||||
public BasicEmployeeVM? RequestedBy { get; set; }
|
||||
public Guid? DocumentId { get; set; }
|
||||
public string? ThumbPreSignedUrl { get; set; }
|
||||
public string? PreSignedUrl { get; set; }
|
||||
|
||||
16
Marco.Pms.Model/ViewModels/Collection/InvoiceAttachmentVM.cs
Normal file
16
Marco.Pms.Model/ViewModels/Collection/InvoiceAttachmentVM.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class InvoiceAttachmentVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
public Guid DocumentId { get; set; }
|
||||
public string? FileName { get; set; }
|
||||
public string? ContentType { get; set; }
|
||||
public string? PreSignedUrl { get; set; }
|
||||
public BasicEmployeeVM? UploadedBy { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
13
Marco.Pms.Model/ViewModels/Collection/InvoiceCommentVM.cs
Normal file
13
Marco.Pms.Model/ViewModels/Collection/InvoiceCommentVM.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class InvoiceCommentVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Comment { get; set; } = default!;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public BasicEmployeeVM? CreatedBy { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
}
|
||||
}
|
||||
31
Marco.Pms.Model/ViewModels/Collection/InvoiceDetailsVM.cs
Normal file
31
Marco.Pms.Model/ViewModels/Collection/InvoiceDetailsVM.cs
Normal file
@ -0,0 +1,31 @@
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.Projects;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class InvoiceDetailsVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Title { get; set; } = default!;
|
||||
public string Description { get; set; } = default!;
|
||||
public string InvoiceNumber { get; set; } = default!;
|
||||
public string? EInvoiceNumber { get; set; }
|
||||
public BasicProjectVM? Project { get; set; }
|
||||
public DateTime InvoiceDate { get; set; }
|
||||
public DateTime ClientSubmitedDate { get; set; }
|
||||
public DateTime ExceptedPaymentDate { get; set; }
|
||||
public double BasicAmount { get; set; }
|
||||
public double TaxAmount { get; set; }
|
||||
public double BalanceAmount { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
public bool MarkAsCompleted { get; set; } = true;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public BasicEmployeeVM? CreatedBy { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public BasicEmployeeVM? UpdatedBy { get; set; }
|
||||
public List<InvoiceAttachmentVM>? Attachments { get; set; }
|
||||
public List<ReceivedInvoicePaymentVM>? ReceivedInvoicePayments { get; set; }
|
||||
public List<InvoiceCommentVM>? Comments { get; set; }
|
||||
|
||||
}
|
||||
}
|
||||
27
Marco.Pms.Model/ViewModels/Collection/InvoiceListVM.cs
Normal file
27
Marco.Pms.Model/ViewModels/Collection/InvoiceListVM.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.Projects;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class InvoiceListVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Title { get; set; } = default!;
|
||||
public string Description { get; set; } = default!;
|
||||
public string InvoiceNumber { get; set; } = default!;
|
||||
public string? EInvoiceNumber { get; set; }
|
||||
public BasicProjectVM? Project { get; set; }
|
||||
public DateTime InvoiceDate { get; set; }
|
||||
public DateTime ClientSubmitedDate { get; set; }
|
||||
public DateTime ExceptedPaymentDate { get; set; }
|
||||
public double BasicAmount { get; set; }
|
||||
public double TaxAmount { get; set; }
|
||||
public double BalanceAmount { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public bool MarkAsCompleted { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public BasicEmployeeVM? CreatedBy { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public BasicEmployeeVM? UpdatedBy { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class PaymentAdjustmentHeadVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,18 @@
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Collection
|
||||
{
|
||||
public class ReceivedInvoicePaymentVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid InvoiceId { get; set; }
|
||||
public DateTime PaymentReceivedDate { get; set; }
|
||||
public PaymentAdjustmentHeadVM? PaymentAdjustmentHead { get; set; }
|
||||
public string TransactionId { get; set; } = default!;
|
||||
public double Amount { get; set; }
|
||||
public string? Comment { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public BasicEmployeeVM? CreatedBy { get; set; }
|
||||
}
|
||||
}
|
||||
@ -26,6 +26,7 @@ namespace Marco.Pms.Model.ViewModels.Expenses
|
||||
public string? TransactionId { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string? Location { get; set; }
|
||||
public string? ExpenseUId { get; set; }
|
||||
public List<BasicDocumentVM> Documents { get; set; } = new List<BasicDocumentVM>();
|
||||
public List<ExpenseLogVM> ExpenseLogs { get; set; } = new List<ExpenseLogVM>();
|
||||
public string? GSTNumber { get; set; }
|
||||
|
||||
@ -18,6 +18,7 @@ namespace Marco.Pms.Model.ViewModels.Expanses
|
||||
public DateTime TransactionDate { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public string SupplerName { get; set; } = string.Empty;
|
||||
public string? ExpenseUId { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string TransactionId { get; set; } = string.Empty;
|
||||
public double Amount { get; set; }
|
||||
|
||||
8
Marco.Pms.Model/ViewModels/PaymentGetway/BankDetails.cs
Normal file
8
Marco.Pms.Model/ViewModels/PaymentGetway/BankDetails.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class BankDetails
|
||||
{
|
||||
public string? Bank { get; set; }
|
||||
public string? BankCode { get; set; }
|
||||
}
|
||||
}
|
||||
14
Marco.Pms.Model/ViewModels/PaymentGetway/CardDetails.cs
Normal file
14
Marco.Pms.Model/ViewModels/PaymentGetway/CardDetails.cs
Normal file
@ -0,0 +1,14 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class CardDetails
|
||||
{
|
||||
public string? CardId { get; set; }
|
||||
public string? Last4Digits { get; set; }
|
||||
public string? Network { get; set; } // Visa, MasterCard, Amex, RuPay
|
||||
public string? CardType { get; set; } // credit, debit, prepaid
|
||||
public string? Issuer { get; set; } // Bank name
|
||||
public bool International { get; set; }
|
||||
public bool Emi { get; set; }
|
||||
public string? SubType { get; set; } // consumer, business
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class CreateOrderVM
|
||||
{
|
||||
public string? OrderId { get; set; }
|
||||
public string? Key { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class PaymentDetailsVM
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public RazorpayPaymentDetails? RazorpayPaymentDetails { get; set; }
|
||||
public RazorpayOrderDetails? RazorpayOrderDetails { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class RazorpayOrderDetails
|
||||
{
|
||||
public string? OrderId { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string? Currency { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? Receipt { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public decimal AmountPaid { get; set; }
|
||||
public decimal AmountDue { get; set; }
|
||||
public int Attempts { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,35 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class RazorpayPaymentDetails
|
||||
{
|
||||
public string? PaymentId { get; set; }
|
||||
public string? OrderId { get; set; }
|
||||
public decimal Amount { get; set; }
|
||||
public string? Currency { get; set; }
|
||||
public string? Status { get; set; } // created, authorized, captured, refunded, failed
|
||||
public string? Method { get; set; } // card, netbanking, wallet, upi
|
||||
public string? Email { get; set; }
|
||||
public string? Contact { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? CustomerName { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
// Payment method specific details
|
||||
public CardDetails? CardDetails { get; set; }
|
||||
public BankDetails? BankDetails { get; set; }
|
||||
public UpiDetails? UpiDetails { get; set; }
|
||||
public WalletDetails? WalletDetails { get; set; }
|
||||
|
||||
// Fee and tax
|
||||
public decimal Fee { get; set; }
|
||||
public decimal Tax { get; set; }
|
||||
|
||||
// Error details (if payment failed)
|
||||
public string? ErrorCode { get; set; }
|
||||
public string? ErrorDescription { get; set; }
|
||||
|
||||
// Additional flags
|
||||
public bool InternationalPayment { get; set; }
|
||||
public bool Captured { get; set; }
|
||||
}
|
||||
}
|
||||
8
Marco.Pms.Model/ViewModels/PaymentGetway/UpiDetails.cs
Normal file
8
Marco.Pms.Model/ViewModels/PaymentGetway/UpiDetails.cs
Normal file
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class UpiDetails
|
||||
{
|
||||
public string? Vpa { get; set; } // UPI ID
|
||||
public string? Provider { get; set; }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
namespace Marco.Pms.Model.ViewModels.PaymentGetway
|
||||
{
|
||||
public class WalletDetails
|
||||
{
|
||||
public string? WalletName { get; set; } // paytm, phonepe, amazonpay, freecharge, jiomoney, olamoney
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
using Marco.Pms.Model.Master;
|
||||
using Marco.Pms.Model.TenantModels;
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.PaymentGetway;
|
||||
|
||||
namespace Marco.Pms.Model.ViewModels.Tenant
|
||||
{
|
||||
@ -16,6 +17,7 @@ namespace Marco.Pms.Model.ViewModels.Tenant
|
||||
public DateTime EndDate { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public PaymentDetailsVM? PaymentDetail { get; set; }
|
||||
public BasicEmployeeVM? CreatedBy { get; set; }
|
||||
public BasicEmployeeVM? updatedBy { get; set; }
|
||||
public CurrencyMaster? Currency { get; set; }
|
||||
|
||||
@ -470,6 +470,19 @@ namespace Marco.Pms.Services.Controllers
|
||||
|
||||
foreach (var item in menu.Items)
|
||||
{
|
||||
if (item.Text == "Projects")
|
||||
{
|
||||
allowedItems.Add(new MenuItem
|
||||
{
|
||||
Text = "Projects",
|
||||
Icon = "bx bx-building-house",
|
||||
Available = true,
|
||||
Link = "/projects",
|
||||
PermissionIds = new List<string>(),
|
||||
Submenu = new List<SubMenuItem>()
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// --- Item permission check ---
|
||||
if (!item.PermissionIds.Any())
|
||||
{
|
||||
@ -577,7 +590,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
new MasterMenuVM { Id = 3, Name = "Work Category" },
|
||||
new MasterMenuVM { Id = 8, Name = "Services" }
|
||||
//new MasterMenuVM { Id = 10, Name = "Payment Mode" }
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -591,7 +603,8 @@ namespace Marco.Pms.Services.Controllers
|
||||
ExpenseManagement, new List<MasterMenuVM>
|
||||
{
|
||||
new MasterMenuVM { Id = 6, Name = "Expense Type" },
|
||||
new MasterMenuVM { Id = 7, Name = "Payment Mode" }
|
||||
new MasterMenuVM { Id = 7, Name = "Payment Mode" },
|
||||
new MasterMenuVM { Id = 10, Name = "Payment Adjustment Head" }
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -608,6 +621,20 @@ namespace Marco.Pms.Services.Controllers
|
||||
var featureIds = await generalHelper.GetFeatureIdsByTenentIdAsync(tenantId);
|
||||
_logger.LogInfo("Enabled features for TenantId: {TenantId} -> {FeatureIds}", tenantId, string.Join(",", featureIds));
|
||||
|
||||
//if (!(featureIds?.Any() ?? false))
|
||||
//{
|
||||
// featureIds = new List<Guid>
|
||||
// {
|
||||
// new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), // Expense Management feature
|
||||
// new Guid("81ab8a87-8ccd-4015-a917-0627cee6a100"), // Employee Management feature
|
||||
// new Guid("52c9cf54-1eb2-44d2-81bb-524cf29c0a94"), // Attendance Management feature
|
||||
// new Guid("a8cf4331-8f04-4961-8360-a3f7c3cc7462"), // Document Management feature
|
||||
// new Guid("be3b3afc-6ccf-4566-b9b6-aafcb65546be"), // Masters Management feature
|
||||
// new Guid("39e66f81-efc6-446c-95bd-46bff6cfb606"), // Directory Management feature
|
||||
// new Guid("6d4c82d6-dbce-48ab-b8b8-f785f4d8c914") // Organization Management feature
|
||||
// };
|
||||
//}
|
||||
|
||||
// Aggregate menus based on enabled features
|
||||
var response = featureIds
|
||||
.Where(id => featureMenus.ContainsKey(id))
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using AutoMapper;
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using Marco.Pms.Model.AttendanceModule;
|
||||
using Marco.Pms.Model.Dtos.Attendance;
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Entitlements;
|
||||
using Marco.Pms.Model.Mapper;
|
||||
using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.AttendanceVM;
|
||||
using Marco.Pms.Services.Hubs;
|
||||
using Marco.Pms.Services.Service;
|
||||
@ -28,48 +29,41 @@ namespace MarcoBMS.Services.Controllers
|
||||
public class AttendanceController : ControllerBase
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly EmployeeHelper _employeeHelper;
|
||||
private readonly IProjectServices _projectServices;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly UserHelper _userHelper;
|
||||
private readonly S3UploadService _s3Service;
|
||||
private readonly PermissionServices _permission;
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly IHubContext<MarcoHub> _signalR;
|
||||
private readonly IFirebaseService _firebase;
|
||||
private readonly Guid tenantId;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public AttendanceController(
|
||||
ApplicationDbContext context, EmployeeHelper employeeHelper, IProjectServices projectServices, UserHelper userHelper,
|
||||
S3UploadService s3Service, ILoggingService logger, PermissionServices permission, IHubContext<MarcoHub> signalR, IFirebaseService firebase)
|
||||
ApplicationDbContext context,
|
||||
UserHelper userHelper,
|
||||
IServiceScopeFactory serviceScopeFactory,
|
||||
ILoggingService logger,
|
||||
PermissionServices permission,
|
||||
IMapper mapper)
|
||||
{
|
||||
_context = context;
|
||||
_employeeHelper = employeeHelper;
|
||||
_projectServices = projectServices;
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_userHelper = userHelper;
|
||||
_s3Service = s3Service;
|
||||
_logger = logger;
|
||||
_permission = permission;
|
||||
_signalR = signalR;
|
||||
_firebase = firebase;
|
||||
}
|
||||
|
||||
private Guid GetTenantId()
|
||||
{
|
||||
return _userHelper.GetTenantId();
|
||||
//var tenant = User.FindFirst("TenantId")?.Value;
|
||||
//return (tenant != null ? Convert.ToInt32(tenant) : 1);
|
||||
_mapper = mapper;
|
||||
tenantId = userHelper.GetTenantId();
|
||||
}
|
||||
|
||||
[HttpGet("log/attendance/{attendanceid}")]
|
||||
|
||||
public async Task<IActionResult> GetAttendanceLogById(Guid attendanceid)
|
||||
{
|
||||
Guid TenantId = GetTenantId();
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _s3Service = scope.ServiceProvider.GetRequiredService<S3UploadService>();
|
||||
|
||||
List<AttendanceLog> lstAttendance = await _context.AttendanceLogs
|
||||
.Include(a => a.Document)
|
||||
.Include(a => a.Employee)
|
||||
.Include(a => a.UpdatedByEmployee)
|
||||
.Where(c => c.AttendanceId == attendanceid && c.TenantId == TenantId)
|
||||
.Where(c => c.AttendanceId == attendanceid && c.TenantId == tenantId)
|
||||
.ToListAsync();
|
||||
|
||||
List<AttendanceLogVM> attendanceLogVMs = new List<AttendanceLogVM>();
|
||||
@ -85,30 +79,42 @@ namespace MarcoBMS.Services.Controllers
|
||||
}
|
||||
|
||||
[HttpGet("log/employee/{employeeId}")]
|
||||
public async Task<IActionResult> GetAttendanceLogByEmployeeId(Guid employeeId, [FromQuery] string? dateFrom = null, [FromQuery] string? dateTo = null)
|
||||
public async Task<IActionResult> GetAttendanceLogByEmployeeId(Guid employeeId, [FromQuery] DateTime? dateFrom = null, [FromQuery] DateTime? dateTo = null)
|
||||
{
|
||||
Guid TenantId = GetTenantId();
|
||||
DateTime fromDate = new DateTime();
|
||||
DateTime toDate = new DateTime();
|
||||
|
||||
if (dateFrom != null && DateTime.TryParse(dateFrom, out fromDate) == false)
|
||||
{
|
||||
_logger.LogWarning("User sent Invalid from Date while featching attendance logs");
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid Date", "Invalid Date", 400));
|
||||
}
|
||||
if (dateTo != null && DateTime.TryParse(dateTo, out toDate) == false)
|
||||
{
|
||||
_logger.LogWarning("User sent Invalid to Date while featching attendance logs");
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid Date", "Invalid Date", 400));
|
||||
}
|
||||
|
||||
if (employeeId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("The employee Id sent by user is empty");
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Employee ID is required and must not be Empty.", "Employee ID is required and must not be empty.", 400));
|
||||
}
|
||||
List<Attendance> attendances = await _context.Attendes.Where(c => c.EmployeeId == employeeId && c.TenantId == TenantId && c.AttendanceDate.Date >= fromDate && c.AttendanceDate.Date <= toDate).ToListAsync();
|
||||
Employee? employee = await _context.Employees.Include(e => e.JobRole).FirstOrDefaultAsync(e => e.Id == employeeId && e.TenantId == TenantId && e.IsActive);
|
||||
|
||||
Employee? employee = await _context.Employees.Include(e => e.JobRole).FirstOrDefaultAsync(e => e.Id == employeeId && e.TenantId == tenantId);
|
||||
if (employee == null)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} not found", employeeId);
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Employee not found", "Employee not found in database", 404));
|
||||
}
|
||||
|
||||
if (!dateFrom.HasValue)
|
||||
{
|
||||
dateFrom = DateTime.UtcNow;
|
||||
}
|
||||
if (!dateTo.HasValue)
|
||||
{
|
||||
var days = 0 - 7;
|
||||
dateTo = dateFrom.Value.AddDays(days);
|
||||
}
|
||||
|
||||
List<Attendance> attendances = await _context.Attendes
|
||||
.Include(a => a.RequestedBy)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Include(a => a.RequestedBy)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Where(c => c.EmployeeId == employeeId && c.TenantId == tenantId && c.AttendanceDate.Date >= dateFrom && c.AttendanceDate.Date <= dateTo).ToListAsync();
|
||||
|
||||
var projectIds = attendances.Select(a => a.ProjectID).Distinct().ToList();
|
||||
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
List<EmployeeAttendanceVM> results = new List<EmployeeAttendanceVM>();
|
||||
|
||||
if (employee != null)
|
||||
@ -121,11 +127,17 @@ namespace MarcoBMS.Services.Controllers
|
||||
EmployeeId = employee.Id,
|
||||
FirstName = employee.FirstName,
|
||||
LastName = employee.LastName,
|
||||
ProjectId = attendance.ProjectID,
|
||||
ProjectName = projects.Where(p => p.Id == attendance.ProjectID).Select(p => p.Name).FirstOrDefault(),
|
||||
CheckInTime = attendance.InTime,
|
||||
CheckOutTime = attendance.OutTime,
|
||||
JobRoleName = employee.JobRole != null ? employee.JobRole.Name : "",
|
||||
Activity = attendance.Activity,
|
||||
EmployeeAvatar = null
|
||||
EmployeeAvatar = null,
|
||||
RequestedAt = attendance.RequestedAt,
|
||||
RequestedBy = _mapper.Map<BasicEmployeeVM>(attendance.RequestedBy),
|
||||
ApprovedAt = attendance.ApprovedAt,
|
||||
Approver = _mapper.Map<BasicEmployeeVM>(attendance.Approver)
|
||||
};
|
||||
results.Add(result);
|
||||
}
|
||||
@ -145,28 +157,12 @@ namespace MarcoBMS.Services.Controllers
|
||||
/// <returns></returns>
|
||||
|
||||
[HttpGet("project/log")]
|
||||
|
||||
public async Task<IActionResult> EmployeeAttendanceByDateRange([FromQuery] Guid projectId, [FromQuery] Guid? organizationId, [FromQuery] string? dateFrom = null, [FromQuery] string? dateTo = null)
|
||||
public async Task<IActionResult> EmployeeAttendanceByDateRange([FromQuery] Guid? projectId, [FromQuery] Guid? organizationId, [FromQuery] string? dateFrom = null, [FromQuery] string? dateTo = null)
|
||||
{
|
||||
Guid tenantId = GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
var project = await _context.Projects.AsNoTracking().FirstOrDefaultAsync(p => p.Id == projectId && p.TenantId == tenantId);
|
||||
if (project == null)
|
||||
{
|
||||
_logger.LogWarning("Project {ProjectId} not found in database", projectId);
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Project not found."));
|
||||
}
|
||||
|
||||
var hasTeamAttendancePermission = await _permission.HasPermission(PermissionsMaster.TeamAttendance, LoggedInEmployee.Id);
|
||||
var hasSelfAttendancePermission = await _permission.HasPermission(PermissionsMaster.SelfAttendance, LoggedInEmployee.Id);
|
||||
var hasProjectPermission = await _permission.HasProjectPermission(LoggedInEmployee, projectId);
|
||||
|
||||
if (!hasProjectPermission)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} tries to access attendance of project {ProjectId}, but don't have access", LoggedInEmployee.Id, projectId);
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("Unauthorized access", "Unauthorized access", 404));
|
||||
}
|
||||
|
||||
DateTime fromDate = new DateTime();
|
||||
DateTime toDate = new DateTime();
|
||||
@ -182,26 +178,46 @@ namespace MarcoBMS.Services.Controllers
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid Date", "Invalid Date", 400));
|
||||
}
|
||||
|
||||
if (projectId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("The project Id sent by user is less than or equal to zero");
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Project ID is required and must be greater than zero.", "Project ID is required and must be greater than zero.", 400));
|
||||
}
|
||||
|
||||
var result = new List<EmployeeAttendanceVM>();
|
||||
//Attendance? attendance = null;
|
||||
ProjectAllocation? teamMember = null;
|
||||
|
||||
if (dateFrom == null) fromDate = DateTime.UtcNow.Date;
|
||||
if (dateTo == null && dateFrom != null) toDate = fromDate.AddDays(-1);
|
||||
|
||||
var lstAttendanceQuery = _context.Attendes
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.Organization)
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Where(a =>
|
||||
a.AttendanceDate.Date >= fromDate.Date &&
|
||||
a.AttendanceDate.Date <= toDate.Date &&
|
||||
a.TenantId == tenantId &&
|
||||
a.Employee != null &&
|
||||
a.Employee.Organization != null &&
|
||||
a.Employee.JobRole != null);
|
||||
|
||||
if (organizationId.HasValue)
|
||||
{
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.Employee != null && a.Employee.OrganizationId == organizationId);
|
||||
}
|
||||
|
||||
if (projectId.HasValue)
|
||||
{
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.ProjectID == projectId);
|
||||
}
|
||||
|
||||
if (hasTeamAttendancePermission)
|
||||
{
|
||||
List<Attendance> lstAttendance = await _context.Attendes.Where(c => c.ProjectID == projectId && c.AttendanceDate.Date >= fromDate.Date && c.AttendanceDate.Date <= toDate.Date && c.TenantId == tenantId).ToListAsync();
|
||||
List<Attendance> lstAttendance = await lstAttendanceQuery.ToListAsync();
|
||||
|
||||
var projectIds = lstAttendance.Select(a => a.ProjectID).ToList();
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
List<ProjectAllocation> projectteam = await _projectServices.GetTeamByProject(tenantId, projectId, organizationId, true);
|
||||
var jobRole = await _context.JobRoles.ToListAsync();
|
||||
foreach (Attendance? attendance in lstAttendance)
|
||||
{
|
||||
var result1 = new EmployeeAttendanceVM()
|
||||
@ -209,77 +225,59 @@ namespace MarcoBMS.Services.Controllers
|
||||
Id = attendance.Id,
|
||||
CheckInTime = attendance.InTime,
|
||||
CheckOutTime = attendance.OutTime,
|
||||
Activity = attendance.Activity
|
||||
Activity = attendance.Activity,
|
||||
EmployeeId = attendance.EmployeeId,
|
||||
FirstName = attendance.Employee?.FirstName,
|
||||
LastName = attendance.Employee?.LastName,
|
||||
JobRoleName = attendance.Employee?.JobRole?.Name,
|
||||
ProjectId = attendance.ProjectID,
|
||||
ProjectName = projects.Where(p => p.Id == attendance.ProjectID).Select(p => p.Name).FirstOrDefault(),
|
||||
OrganizationName = attendance.Employee?.Organization?.Name,
|
||||
RequestedAt = attendance.RequestedAt,
|
||||
RequestedBy = _mapper.Map<BasicEmployeeVM>(attendance.RequestedBy),
|
||||
ApprovedAt = attendance.ApprovedAt,
|
||||
Approver = _mapper.Map<BasicEmployeeVM>(attendance.Approver)
|
||||
};
|
||||
teamMember = projectteam.Find(x => x.EmployeeId == attendance.EmployeeId);
|
||||
if (teamMember != null)
|
||||
{
|
||||
result1.EmployeeAvatar = null;
|
||||
result1.EmployeeId = teamMember.EmployeeId;
|
||||
if (teamMember.Employee != null)
|
||||
{
|
||||
result1.FirstName = teamMember.Employee.FirstName;
|
||||
result1.LastName = teamMember.Employee.LastName;
|
||||
result1.JobRoleName = teamMember.Employee.JobRole != null ? teamMember.Employee.JobRole.Name : null;
|
||||
result1.OrganizationName = teamMember.Employee.Organization?.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
result1.FirstName = null;
|
||||
result1.LastName = null;
|
||||
result1.JobRoleName = null;
|
||||
result1.OrganizationName = null;
|
||||
}
|
||||
|
||||
result.Add(result1);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else if (hasSelfAttendancePermission)
|
||||
{
|
||||
List<Attendance> lstAttendances = await _context.Attendes
|
||||
.Where(c => c.ProjectID == projectId && c.EmployeeId == LoggedInEmployee.Id && c.AttendanceDate.Date >= fromDate.Date && c.AttendanceDate.Date <= toDate.Date && c.TenantId == tenantId)
|
||||
.ToListAsync();
|
||||
|
||||
var projectAllocationQuery = _context.ProjectAllocations
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.Organization)
|
||||
.Where(pa => pa.ProjectId == projectId && pa.EmployeeId == LoggedInEmployee.Id && pa.TenantId == tenantId && pa.IsActive);
|
||||
var lstAttendances = await lstAttendanceQuery.Where(a => a.EmployeeId == LoggedInEmployee.Id).ToListAsync();
|
||||
|
||||
if (organizationId.HasValue)
|
||||
{
|
||||
projectAllocationQuery = projectAllocationQuery.Where(pa => pa.Employee != null && pa.Employee.OrganizationId == organizationId);
|
||||
}
|
||||
var projectIds = lstAttendances.Select(a => a.ProjectID).ToList();
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
var projectAllocation = await projectAllocationQuery.FirstOrDefaultAsync();
|
||||
|
||||
foreach (var attendance in lstAttendances)
|
||||
{
|
||||
if (projectAllocation != null)
|
||||
{
|
||||
EmployeeAttendanceVM result1 = new EmployeeAttendanceVM
|
||||
{
|
||||
Id = attendance.Id,
|
||||
EmployeeAvatar = null,
|
||||
EmployeeId = projectAllocation.EmployeeId,
|
||||
FirstName = projectAllocation.Employee?.FirstName,
|
||||
LastName = projectAllocation.Employee?.LastName,
|
||||
JobRoleName = projectAllocation.Employee?.JobRole?.Name,
|
||||
OrganizationName = projectAllocation.Employee?.Organization?.Name,
|
||||
EmployeeId = attendance.EmployeeId,
|
||||
FirstName = attendance.Employee?.FirstName,
|
||||
LastName = attendance.Employee?.LastName,
|
||||
JobRoleName = attendance.Employee?.JobRole?.Name,
|
||||
ProjectId = attendance.ProjectID,
|
||||
ProjectName = projects.Where(p => p.Id == attendance.ProjectID).Select(p => p.Name).FirstOrDefault(),
|
||||
OrganizationName = attendance.Employee?.Organization?.Name,
|
||||
CheckInTime = attendance.InTime,
|
||||
CheckOutTime = attendance.OutTime,
|
||||
Activity = attendance.Activity
|
||||
Activity = attendance.Activity,
|
||||
RequestedAt = attendance.RequestedAt,
|
||||
RequestedBy = _mapper.Map<BasicEmployeeVM>(attendance.RequestedBy),
|
||||
ApprovedAt = attendance.ApprovedAt,
|
||||
Approver = _mapper.Map<BasicEmployeeVM>(attendance.Approver)
|
||||
};
|
||||
result.Add(result1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_logger.LogInfo("{count} Attendance records fetched successfully", result.Count);
|
||||
return Ok(ApiResponse<object>.SuccessResponse(result, System.String.Format("{0} Attendance records fetched successfully", result.Count), 200));
|
||||
}
|
||||
|
||||
[HttpGet("project/team")]
|
||||
/// <summary>
|
||||
/// Retrieves employee attendance records for a specified project and date.
|
||||
/// The result is filtered based on the logged-in employee's permissions (Team or Self).
|
||||
@ -289,13 +287,14 @@ namespace MarcoBMS.Services.Controllers
|
||||
/// <param name="includeInactive">Optional. Includes inactive employees in the team list if true.</param>
|
||||
/// <param name="date">Optional. The date for which to fetch attendance, in "yyyy-MM-dd" format. Defaults to the current UTC date.</param>
|
||||
/// <returns>An IActionResult containing a list of employee attendance records or an error response.</returns>
|
||||
public async Task<IActionResult> EmployeeAttendanceByProjectAsync([FromQuery] Guid projectId, [FromQuery] Guid? organizationId, [FromQuery] bool includeInactive, [FromQuery] string? date = null)
|
||||
|
||||
[HttpGet("project/team")]
|
||||
public async Task<IActionResult> EmployeeAttendanceByProjectAsync([FromQuery] Guid? projectId, [FromQuery] Guid? organizationId, [FromQuery] bool includeInactive, [FromQuery] string? date = null)
|
||||
{
|
||||
var tenantId = GetTenantId();
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
// --- 1. Initial Validation and Permission Checks ---
|
||||
_logger.LogInfo("Fetching attendance for ProjectId: {ProjectId}, TenantId: {TenantId}", projectId, tenantId);
|
||||
_logger.LogInfo("Fetching attendance for ProjectId: {ProjectId}, TenantId: {TenantId}", projectId ?? Guid.Empty, tenantId);
|
||||
|
||||
// Validate date format
|
||||
if (!DateTime.TryParse(date, out var forDate))
|
||||
@ -303,20 +302,6 @@ namespace MarcoBMS.Services.Controllers
|
||||
forDate = DateTime.UtcNow.Date; // Default to today's date
|
||||
}
|
||||
|
||||
// Check if the project exists and if the employee has access
|
||||
var project = await _context.Projects.AsNoTracking().FirstOrDefaultAsync(p => p.Id == projectId && p.TenantId == tenantId);
|
||||
if (project == null)
|
||||
{
|
||||
_logger.LogWarning("Project {ProjectId} not found in database", projectId);
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Project not found."));
|
||||
}
|
||||
|
||||
if (!await _permission.HasProjectPermission(loggedInEmployee, projectId))
|
||||
{
|
||||
_logger.LogWarning("Unauthorized access attempt by EmployeeId: {EmployeeId} for ProjectId: {ProjectId}", loggedInEmployee.Id, projectId);
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("You do not have permission to access this project."));
|
||||
}
|
||||
|
||||
// --- 2. Delegate to Specific Logic Based on Permissions ---
|
||||
try
|
||||
{
|
||||
@ -325,13 +310,17 @@ namespace MarcoBMS.Services.Controllers
|
||||
|
||||
if (hasTeamAttendancePermission)
|
||||
{
|
||||
if (!organizationId.HasValue)
|
||||
{
|
||||
organizationId = loggedInEmployee.OrganizationId;
|
||||
}
|
||||
_logger.LogInfo("EmployeeId: {EmployeeId} has Team Attendance permission. Fetching team attendance.", loggedInEmployee.Id);
|
||||
result = await GetTeamAttendanceAsync(tenantId, projectId, organizationId, forDate, includeInactive);
|
||||
result = await GetTeamAttendanceAsync(tenantId, projectId, organizationId.Value, forDate, includeInactive);
|
||||
}
|
||||
else if (await _permission.HasPermission(PermissionsMaster.SelfAttendance, loggedInEmployee.Id))
|
||||
{
|
||||
_logger.LogInfo("EmployeeId: {EmployeeId} has Self Attendance permission. Fetching self attendance.", loggedInEmployee.Id);
|
||||
result = await GetSelfAttendanceAsync(tenantId, projectId, loggedInEmployee.Id, organizationId, forDate);
|
||||
result = await GetSelfAttendanceAsync(tenantId, projectId, loggedInEmployee.Id, forDate);
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -339,41 +328,48 @@ namespace MarcoBMS.Services.Controllers
|
||||
return StatusCode(403, ApiResponse<object>.ErrorResponse("You do not have permission to view attendance.", new { }, 403));
|
||||
}
|
||||
|
||||
_logger.LogInfo("Successfully fetched {Count} attendance records for ProjectId: {ProjectId}", result.Count, projectId);
|
||||
_logger.LogInfo("Successfully fetched {Count} attendance records for ProjectId: {ProjectId}", result.Count, projectId ?? Guid.Empty);
|
||||
return Ok(ApiResponse<object>.SuccessResponse(result, $"{result.Count} attendance records fetched successfully."));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "An error occurred while fetching attendance for ProjectId: {ProjectId}", projectId);
|
||||
_logger.LogError(ex, "An error occurred while fetching attendance for ProjectId: {ProjectId}", projectId ?? Guid.Empty);
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("An internal server error occurred."));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("regularize")]
|
||||
public async Task<IActionResult> GetRequestRegularizeAttendance([FromQuery] Guid projectId, [FromQuery] Guid? organizationId, [FromQuery] bool IncludeInActive)
|
||||
public async Task<IActionResult> GetRequestRegularizeAttendance([FromQuery] Guid? projectId, [FromQuery] Guid? organizationId, [FromQuery] bool IncludeInActive)
|
||||
{
|
||||
Guid TenantId = GetTenantId();
|
||||
Employee LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var result = new List<EmployeeAttendanceVM>();
|
||||
var hasProjectPermission = await _permission.HasProjectPermission(LoggedInEmployee, projectId);
|
||||
|
||||
if (!hasProjectPermission)
|
||||
var lstAttendanceQuery = _context.Attendes
|
||||
.Include(a => a.RequestedBy)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.Organization)
|
||||
.Include(a => a.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
|
||||
.Where(c => c.Activity == ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE && c.Employee != null && c.Employee.JobRole != null && c.TenantId == tenantId);
|
||||
|
||||
if (organizationId.HasValue)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} tries to access attendance of project {ProjectId}, but don't have access", LoggedInEmployee.Id, projectId);
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("Unauthorized access", "Unauthorized access", 404));
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.Employee != null && a.Employee.OrganizationId == organizationId);
|
||||
}
|
||||
|
||||
List<Attendance> lstAttendance = await _context.Attendes.Where(c => c.ProjectID == projectId && c.Activity == ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE && c.TenantId == TenantId).ToListAsync();
|
||||
if (projectId.HasValue)
|
||||
{
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.ProjectID == projectId);
|
||||
}
|
||||
|
||||
List<ProjectAllocation> projectteam = await _projectServices.GetTeamByProject(TenantId, projectId, organizationId, true);
|
||||
var idList = projectteam.Select(p => p.EmployeeId).ToList();
|
||||
var jobRole = await _context.JobRoles.ToListAsync();
|
||||
List<Attendance> lstAttendance = await lstAttendanceQuery.ToListAsync();
|
||||
|
||||
var projectIds = lstAttendance.Select(a => a.ProjectID).ToList();
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
foreach (Attendance attende in lstAttendance)
|
||||
{
|
||||
var teamMember = projectteam.Find(m => m.EmployeeId == attende.EmployeeId);
|
||||
if (teamMember != null && teamMember.Employee != null && teamMember.Employee.JobRole != null)
|
||||
{
|
||||
var result1 = new EmployeeAttendanceVM()
|
||||
{
|
||||
@ -383,13 +379,16 @@ namespace MarcoBMS.Services.Controllers
|
||||
Activity = attende.Activity,
|
||||
EmployeeAvatar = null,
|
||||
EmployeeId = attende.EmployeeId,
|
||||
FirstName = teamMember.Employee.FirstName,
|
||||
LastName = teamMember.Employee.LastName,
|
||||
JobRoleName = teamMember.Employee.JobRole.Name,
|
||||
OrganizationName = teamMember.Employee.Organization?.Name
|
||||
ProjectId = attende.ProjectID,
|
||||
FirstName = attende.Employee?.FirstName,
|
||||
ProjectName = projects.Where(p => p.Id == attende.ProjectID).Select(p => p.Name).FirstOrDefault(),
|
||||
LastName = attende.Employee?.LastName,
|
||||
JobRoleName = attende.Employee?.JobRole?.Name,
|
||||
OrganizationName = attende.Employee?.Organization?.Name,
|
||||
RequestedAt = attende.RequestedAt,
|
||||
RequestedBy = _mapper.Map<BasicEmployeeVM>(attende.RequestedBy)
|
||||
};
|
||||
result.Add(result1);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -402,8 +401,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
return Ok(ApiResponse<object>.SuccessResponse(result, System.String.Format("{0} Attendance records fetched successfully", result.Count), 200));
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("record")]
|
||||
[HttpPost("record")]
|
||||
public async Task<IActionResult> RecordAttendance([FromBody] RecordAttendanceDot recordAttendanceDot)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
@ -416,13 +414,16 @@ namespace MarcoBMS.Services.Controllers
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid data", errors, 400));
|
||||
}
|
||||
|
||||
Guid TenantId = GetTenantId();
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _signalR = scope.ServiceProvider.GetRequiredService<IHubContext<MarcoHub>>();
|
||||
var _employeeHelper = scope.ServiceProvider.GetRequiredService<EmployeeHelper>();
|
||||
|
||||
var currentEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
using var transaction = await _context.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
Attendance? attendance = await _context.Attendes.FirstOrDefaultAsync(a => a.Id == recordAttendanceDot.Id && a.TenantId == TenantId); ;
|
||||
Attendance? attendance = await _context.Attendes.FirstOrDefaultAsync(a => a.Id == recordAttendanceDot.Id && a.TenantId == tenantId); ;
|
||||
|
||||
if (recordAttendanceDot.MarkTime == null)
|
||||
{
|
||||
@ -460,10 +461,12 @@ namespace MarcoBMS.Services.Controllers
|
||||
{
|
||||
DateTime date = attendance.AttendanceDate;
|
||||
finalDateTime = GetDateFromTimeStamp(date.Date, recordAttendanceDot.MarkTime);
|
||||
if (attendance.InTime < finalDateTime)
|
||||
if (attendance.InTime <= finalDateTime)
|
||||
{
|
||||
attendance.OutTime = finalDateTime;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE;
|
||||
attendance.RequestedAt = DateTime.UtcNow;
|
||||
attendance.RequestedById = currentEmployee.Id;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -477,12 +480,15 @@ namespace MarcoBMS.Services.Controllers
|
||||
attendance.IsApproved = true;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REGULARIZE;
|
||||
attendance.ApprovedById = currentEmployee.Id;
|
||||
attendance.ApprovedAt = DateTime.UtcNow;
|
||||
// do nothing
|
||||
}
|
||||
else if (recordAttendanceDot.Action == ATTENDANCE_MARK_TYPE.REGULARIZE_REJECT)
|
||||
{
|
||||
attendance.IsApproved = false;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REGULARIZE_REJECT;
|
||||
attendance.ApprovedById = currentEmployee.Id;
|
||||
attendance.ApprovedAt = DateTime.UtcNow;
|
||||
// do nothing
|
||||
}
|
||||
attendance.Date = DateTime.UtcNow;
|
||||
@ -493,7 +499,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
else
|
||||
{
|
||||
attendance = new Attendance();
|
||||
attendance.TenantId = TenantId;
|
||||
attendance.TenantId = tenantId;
|
||||
attendance.AttendanceDate = recordAttendanceDot.Date;
|
||||
// attendance.Activity = recordAttendanceDot.Action;
|
||||
attendance.Comment = recordAttendanceDot.Comment;
|
||||
@ -525,7 +531,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
Latitude = recordAttendanceDot.Latitude,
|
||||
Longitude = recordAttendanceDot.Longitude,
|
||||
|
||||
TenantId = TenantId,
|
||||
TenantId = tenantId,
|
||||
UpdatedBy = currentEmployee.Id,
|
||||
UpdatedOn = recordAttendanceDot.Date
|
||||
};
|
||||
@ -549,11 +555,13 @@ namespace MarcoBMS.Services.Controllers
|
||||
CheckOutTime = attendance.OutTime,
|
||||
EmployeeAvatar = null,
|
||||
EmployeeId = recordAttendanceDot.EmployeeID,
|
||||
ProjectId = attendance.ProjectID,
|
||||
FirstName = employee.FirstName,
|
||||
LastName = employee.LastName,
|
||||
Id = attendance.Id,
|
||||
Activity = attendance.Activity,
|
||||
JobRoleName = employee.JobRole.Name
|
||||
JobRoleName = employee.JobRole.Name,
|
||||
OrganizationName = employee.Organization?.Name
|
||||
};
|
||||
var sendActivity = 0;
|
||||
if (recordAttendanceDot.Id == Guid.Empty)
|
||||
@ -569,10 +577,10 @@ namespace MarcoBMS.Services.Controllers
|
||||
// --- 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.
|
||||
|
||||
var _firebase = scope.ServiceProvider.GetRequiredService<IFirebaseService>();
|
||||
var name = $"{vm.FirstName} {vm.LastName}";
|
||||
|
||||
await _firebase.SendAttendanceMessageAsync(attendance.ProjectID, name, recordAttendanceDot.Action, attendance.EmployeeId, TenantId);
|
||||
await _firebase.SendAttendanceMessageAsync(attendance.ProjectID, name, recordAttendanceDot.Action, attendance.EmployeeId, tenantId);
|
||||
|
||||
});
|
||||
|
||||
@ -608,7 +616,12 @@ namespace MarcoBMS.Services.Controllers
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid data", errors, 400));
|
||||
}
|
||||
|
||||
Guid tenantId = GetTenantId();
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _s3Service = scope.ServiceProvider.GetRequiredService<S3UploadService>();
|
||||
var _employeeHelper = scope.ServiceProvider.GetRequiredService<EmployeeHelper>();
|
||||
var _firebase = scope.ServiceProvider.GetRequiredService<IFirebaseService>();
|
||||
var _signalR = scope.ServiceProvider.GetRequiredService<IHubContext<MarcoHub>>();
|
||||
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var batchId = Guid.NewGuid();
|
||||
|
||||
@ -672,6 +685,8 @@ namespace MarcoBMS.Services.Controllers
|
||||
{
|
||||
attendance.OutTime = finalDateTime;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REQUEST_REGULARIZE;
|
||||
attendance.RequestedAt = DateTime.UtcNow;
|
||||
attendance.RequestedById = loggedInEmployee.Id;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -682,10 +697,14 @@ namespace MarcoBMS.Services.Controllers
|
||||
case ATTENDANCE_MARK_TYPE.REGULARIZE:
|
||||
attendance.IsApproved = true;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REGULARIZE;
|
||||
attendance.ApprovedAt = DateTime.UtcNow;
|
||||
attendance.ApprovedById = loggedInEmployee.Id;
|
||||
break;
|
||||
case ATTENDANCE_MARK_TYPE.REGULARIZE_REJECT:
|
||||
attendance.IsApproved = false;
|
||||
attendance.Activity = ATTENDANCE_MARK_TYPE.REGULARIZE_REJECT;
|
||||
attendance.ApprovedAt = DateTime.UtcNow;
|
||||
attendance.ApprovedById = loggedInEmployee.Id;
|
||||
break;
|
||||
}
|
||||
|
||||
@ -751,6 +770,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
{
|
||||
Id = attendance.Id,
|
||||
EmployeeId = employee.Id,
|
||||
ProjectId = attendance.ProjectID,
|
||||
FirstName = employee.FirstName,
|
||||
LastName = employee.LastName,
|
||||
CheckInTime = attendance.InTime,
|
||||
@ -813,56 +833,54 @@ namespace MarcoBMS.Services.Controllers
|
||||
/// <summary>
|
||||
/// Fetches attendance for an entire project team using a single, optimized database query.
|
||||
/// </summary>
|
||||
private async Task<List<EmployeeAttendanceVM>> GetTeamAttendanceAsync(Guid tenantId, Guid projectId, Guid? organizationId, DateTime forDate, bool includeInactive)
|
||||
private async Task<List<EmployeeAttendanceVM>> GetTeamAttendanceAsync(Guid tenantId, Guid? projectId, Guid organizationId, DateTime forDate, bool includeInactive)
|
||||
{
|
||||
// This single query joins ProjectAllocations with Employees and performs a LEFT JOIN with Attendances.
|
||||
// This is far more efficient than fetching collections and joining them in memory.
|
||||
var query = _context.ProjectAllocations
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.Organization)
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Where(pa => pa.TenantId == tenantId && pa.ProjectId == projectId);
|
||||
var query = _context.Employees
|
||||
.Include(e => e!.Organization)
|
||||
.Include(e => e!.JobRole)
|
||||
.Where(e => e.OrganizationId == organizationId && e.Organization != null && e.JobRole != null && e.IsActive);
|
||||
|
||||
// Apply filters based on optional parameters
|
||||
if (!includeInactive)
|
||||
|
||||
var lstAttendanceQuery = _context.Attendes.Where(c => c.AttendanceDate.Date == forDate && c.TenantId == tenantId);
|
||||
|
||||
if (projectId.HasValue)
|
||||
{
|
||||
query = query.Where(pa => pa.IsActive);
|
||||
}
|
||||
if (organizationId.HasValue)
|
||||
{
|
||||
query = query.Where(pa => pa.Employee != null && pa.Employee.OrganizationId == organizationId);
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.ProjectID == projectId);
|
||||
}
|
||||
|
||||
List<Attendance> lstAttendance = await _context.Attendes.Where(c => c.ProjectID == projectId && c.AttendanceDate.Date == forDate && c.TenantId == tenantId).ToListAsync();
|
||||
List<Attendance> lstAttendance = await lstAttendanceQuery.ToListAsync();
|
||||
|
||||
var teamAttendance = await query
|
||||
var employees = await query
|
||||
.AsNoTracking()
|
||||
.ToListAsync();
|
||||
|
||||
var response = teamAttendance
|
||||
.Select(teamMember =>
|
||||
var projectIds = lstAttendance.Select(a => a.ProjectID).ToList();
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
var response = employees
|
||||
.Select(employee =>
|
||||
{
|
||||
var result1 = new EmployeeAttendanceVM()
|
||||
{
|
||||
EmployeeAvatar = null,
|
||||
EmployeeId = teamMember.EmployeeId,
|
||||
FirstName = teamMember.Employee?.FirstName,
|
||||
LastName = teamMember.Employee?.LastName,
|
||||
OrganizationName = teamMember.Employee?.Organization?.Name,
|
||||
JobRoleName = teamMember.Employee?.JobRole?.Name,
|
||||
EmployeeId = employee.Id,
|
||||
FirstName = employee.FirstName,
|
||||
LastName = employee.LastName,
|
||||
OrganizationName = employee.Organization!.Name,
|
||||
JobRoleName = employee.JobRole!.Name,
|
||||
};
|
||||
|
||||
//var member = emp.Where(e => e.Id == teamMember.EmployeeId);
|
||||
|
||||
|
||||
var attendance = lstAttendance.Find(x => x.EmployeeId == teamMember.EmployeeId) ?? new Attendance();
|
||||
var attendance = lstAttendance.Find(x => x.EmployeeId == employee.Id) ?? new Attendance();
|
||||
if (attendance != null)
|
||||
{
|
||||
result1.Id = attendance.Id;
|
||||
result1.ProjectId = attendance.ProjectID;
|
||||
result1.CheckInTime = attendance.InTime;
|
||||
result1.CheckOutTime = attendance.OutTime;
|
||||
result1.Activity = attendance.Activity;
|
||||
result1.ProjectName = projects.Where(p => p.Id == attendance.ProjectID).Select(p => p.Name).FirstOrDefault();
|
||||
}
|
||||
return result1;
|
||||
})
|
||||
@ -875,43 +893,51 @@ namespace MarcoBMS.Services.Controllers
|
||||
/// <summary>
|
||||
/// Fetches a single attendance record for the logged-in employee.
|
||||
/// </summary>
|
||||
private async Task<List<EmployeeAttendanceVM>> GetSelfAttendanceAsync(Guid tenantId, Guid projectId, Guid employeeId, Guid? organizationId, DateTime forDate)
|
||||
private async Task<List<EmployeeAttendanceVM>> GetSelfAttendanceAsync(Guid tenantId, Guid? projectId, Guid employeeId, DateTime forDate)
|
||||
{
|
||||
List<EmployeeAttendanceVM> result = new List<EmployeeAttendanceVM>();
|
||||
|
||||
// This query fetches the employee's project allocation and their attendance in a single trip.
|
||||
Attendance lstAttendance = await _context.Attendes
|
||||
.FirstOrDefaultAsync(c => c.ProjectID == projectId && c.EmployeeId == employeeId && c.AttendanceDate.Date == forDate && c.TenantId == tenantId) ?? new Attendance();
|
||||
var lstAttendanceQuery = _context.Attendes
|
||||
.Where(c => c.EmployeeId == employeeId && c.AttendanceDate.Date == forDate && c.TenantId == tenantId);
|
||||
|
||||
var projectAllocationQuery = _context.ProjectAllocations
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.Organization)
|
||||
.Where(pa => pa.ProjectId == projectId && pa.EmployeeId == employeeId && pa.TenantId == tenantId && pa.IsActive);
|
||||
|
||||
if (organizationId.HasValue)
|
||||
if (projectId.HasValue)
|
||||
{
|
||||
projectAllocationQuery = projectAllocationQuery.Where(pa => pa.Employee != null && pa.Employee.OrganizationId == organizationId);
|
||||
lstAttendanceQuery = lstAttendanceQuery.Where(a => a.ProjectID == projectId);
|
||||
}
|
||||
|
||||
var projectAllocation = await projectAllocationQuery.FirstOrDefaultAsync();
|
||||
List<Attendance> lstAttendances = await lstAttendanceQuery.ToListAsync() ?? new List<Attendance>();
|
||||
|
||||
if (projectAllocation != null)
|
||||
var projectIds = lstAttendances.Select(a => a.ProjectID).ToList();
|
||||
var projects = await _context.Projects.Where(p => projectIds.Contains(p.Id) && p.TenantId == tenantId).ToListAsync();
|
||||
|
||||
var employee = await _context.Employees
|
||||
.Include(e => e.Organization)
|
||||
.Include(e => e.JobRole)
|
||||
.FirstOrDefaultAsync(e => e.Id == employeeId && e.IsActive);
|
||||
|
||||
if (employee != null && employee.JobRole != null && employee.Organization != null)
|
||||
{
|
||||
foreach (var lstAttendance in lstAttendances)
|
||||
{
|
||||
EmployeeAttendanceVM result1 = new EmployeeAttendanceVM
|
||||
{
|
||||
Id = lstAttendance.Id,
|
||||
EmployeeAvatar = null,
|
||||
EmployeeId = projectAllocation.EmployeeId,
|
||||
FirstName = projectAllocation.Employee?.FirstName,
|
||||
OrganizationName = projectAllocation.Employee?.Organization?.Name,
|
||||
LastName = projectAllocation.Employee?.LastName,
|
||||
JobRoleName = projectAllocation.Employee?.JobRole?.Name,
|
||||
ProjectId = lstAttendance.ProjectID,
|
||||
EmployeeId = employee.Id,
|
||||
FirstName = employee.FirstName,
|
||||
OrganizationName = employee.Organization.Name,
|
||||
ProjectName = projects.Where(p => p.Id == lstAttendance.ProjectID).Select(p => p.Name).FirstOrDefault(),
|
||||
LastName = employee.LastName,
|
||||
JobRoleName = employee.JobRole.Name,
|
||||
CheckInTime = lstAttendance.InTime,
|
||||
CheckOutTime = lstAttendance.OutTime,
|
||||
Activity = lstAttendance.Activity
|
||||
};
|
||||
result.Add(result1);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -59,7 +59,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
{
|
||||
|
||||
var user = await _context.ApplicationUsers
|
||||
.FirstOrDefaultAsync(u => u.Email == loginDto.Username || u.PhoneNumber == loginDto.Username);
|
||||
.FirstOrDefaultAsync(u => u.Email == loginDto.Username || u.UserName == loginDto.Username);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
@ -103,9 +103,13 @@ namespace MarcoBMS.Services.Controllers
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Username not found", "Username not found", 404));
|
||||
}
|
||||
|
||||
var tenants = await _context.Tenants.Where(t => t.OrganizationId == emp.OrganizationId).ToListAsync();
|
||||
|
||||
var tenant = tenants.OrderBy(t => t.OnBoardingDate).FirstOrDefault();
|
||||
|
||||
// Generate tokens
|
||||
var token = _refreshTokenService.GenerateJwtToken(user.UserName, emp.TenantId ?? Guid.Empty, emp.OrganizationId, _jwtSettings);
|
||||
var refreshToken = await _refreshTokenService.CreateRefreshToken(user.Id, emp.TenantId.ToString(), emp.OrganizationId, _jwtSettings);
|
||||
var token = _refreshTokenService.GenerateJwtToken(user.UserName, tenant?.Id ?? Guid.Empty, emp.OrganizationId, _jwtSettings);
|
||||
var refreshToken = await _refreshTokenService.CreateRefreshToken(user.Id, tenant?.Id.ToString(), emp.OrganizationId, _jwtSettings);
|
||||
|
||||
_logger.LogInfo("User login successful - UserId: {UserId}", user.Id);
|
||||
return Ok(ApiResponse<object>.SuccessResponse(new
|
||||
@ -201,12 +205,17 @@ namespace MarcoBMS.Services.Controllers
|
||||
}
|
||||
_logger.LogInfo("Successfully found employee details for tenant ID: {TenantId}", emp.TenantId ?? Guid.Empty);
|
||||
|
||||
|
||||
var tenants = await _context.Tenants.Where(t => t.OrganizationId == emp.OrganizationId).ToListAsync();
|
||||
|
||||
var tenant = tenants.OrderBy(t => t.OnBoardingDate).FirstOrDefault();
|
||||
|
||||
// Generate JWT token
|
||||
var token = _refreshTokenService.GenerateJwtToken(user.UserName, emp.TenantId ?? Guid.Empty, emp.OrganizationId, _jwtSettings);
|
||||
var token = _refreshTokenService.GenerateJwtToken(user.UserName, tenant?.Id ?? Guid.Empty, emp.OrganizationId, _jwtSettings);
|
||||
|
||||
// Generate a new refresh token and store it in the database.
|
||||
_logger.LogInfo("Generating and storing Refresh Token for user: {Username}", user.UserName);
|
||||
var refreshToken = await _refreshTokenService.CreateRefreshToken(user.Id, emp.TenantId.ToString(), emp.OrganizationId, _jwtSettings);
|
||||
var refreshToken = await _refreshTokenService.CreateRefreshToken(user.Id, tenant?.Id.ToString(), emp.OrganizationId, _jwtSettings);
|
||||
|
||||
// Fetch MPIN Token
|
||||
var mpinToken = await _context.MPINDetails.FirstOrDefaultAsync(p => p.UserId == Guid.Parse(user.Id));
|
||||
@ -264,31 +273,32 @@ namespace MarcoBMS.Services.Controllers
|
||||
}
|
||||
|
||||
string? tokenType = claimsPrincipal.FindFirst("token_type")?.Value;
|
||||
string? tokenTenantId = claimsPrincipal.FindFirst("TenantId")?.Value;
|
||||
string? tokenUserId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
// Validate essential claims
|
||||
if (string.IsNullOrWhiteSpace(tokenType) || string.IsNullOrWhiteSpace(tokenTenantId) || string.IsNullOrWhiteSpace(tokenUserId))
|
||||
if (string.IsNullOrWhiteSpace(tokenType) || string.IsNullOrWhiteSpace(tokenUserId))
|
||||
{
|
||||
_logger.LogWarning("MPIN token claims are incomplete");
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("Invalid token claims", "MPIN token does not match your identity", 401));
|
||||
}
|
||||
|
||||
Guid tenantId = Guid.Parse(tokenTenantId);
|
||||
|
||||
// Fetch employee by ID and tenant
|
||||
var requestEmployee = await _context.Employees
|
||||
.Include(e => e.ApplicationUser)
|
||||
.FirstOrDefaultAsync(e => e.Id == verifyMPIN.EmployeeId && e.TenantId == tenantId && e.ApplicationUserId == tokenUserId && e.IsActive);
|
||||
.FirstOrDefaultAsync(e => e.Id == verifyMPIN.EmployeeId && e.HasApplicationAccess && e.ApplicationUserId == tokenUserId && e.IsActive);
|
||||
|
||||
if (requestEmployee == null || string.IsNullOrWhiteSpace(requestEmployee.ApplicationUserId))
|
||||
{
|
||||
_logger.LogWarning("Employee not found or invalid for verification - EmployeeId: {EmployeeId}", verifyMPIN.EmployeeId);
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid request", "Provided invalid employee information", 400));
|
||||
}
|
||||
var tenants = await _context.Tenants.Where(t => t.OrganizationId == requestEmployee.OrganizationId).ToListAsync();
|
||||
|
||||
var tenant = tenants.OrderBy(t => t.OnBoardingDate).FirstOrDefault();
|
||||
Guid tenantId = tenant?.Id ?? Guid.Empty;
|
||||
|
||||
// Validate that the token belongs to the same employee making the request
|
||||
if (requestEmployee.ApplicationUserId != tokenUserId || tokenType != "mpin")
|
||||
if (requestEmployee.ApplicationUserId != tokenUserId || tokenType != "mpin" || tenantId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("Token identity does not match employee info - EmployeeId: {EmployeeId}", requestEmployee.Id);
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("Unauthorized", "MPIN token does not match your identity", 401));
|
||||
@ -319,36 +329,6 @@ namespace MarcoBMS.Services.Controllers
|
||||
return Unauthorized(ApiResponse<object>.ErrorResponse("MPIN mismatch", "MPIN did not match", 401));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(verifyMPIN.FcmToken))
|
||||
{
|
||||
var existingFCMTokenMapping = await _context.FCMTokenMappings.Where(ft => ft.FcmToken == verifyMPIN.FcmToken).ToListAsync();
|
||||
|
||||
if (existingFCMTokenMapping.Any())
|
||||
{
|
||||
_context.FCMTokenMappings.RemoveRange(existingFCMTokenMapping);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Generate new tokens
|
||||
var jwtToken = _refreshTokenService.GenerateJwtToken(requestEmployee.Email, tenantId, requestEmployee.OrganizationId, _jwtSettings);
|
||||
var refreshToken = await _refreshTokenService.CreateRefreshToken(requestEmployee.ApplicationUserId, tenantId.ToString(), requestEmployee.OrganizationId, _jwtSettings);
|
||||
@ -431,7 +411,9 @@ namespace MarcoBMS.Services.Controllers
|
||||
//var accessToken = _refreshTokenService.GenerateJwtTokenWithOrganization(requestEmployee.ApplicationUser?.UserName, requestEmployee.OrganizationId, _jwtSettings);
|
||||
//var refreshToken = await _refreshTokenService.CreateRefreshTokenWithOrganization(requestEmployee.ApplicationUserId, requestEmployee.OrganizationId, _jwtSettings);
|
||||
|
||||
var tenant = await _context.Tenants.FirstOrDefaultAsync(t => t.OrganizationId == requestEmployee.OrganizationId);
|
||||
var tenants = await _context.Tenants.Where(t => t.OrganizationId == requestEmployee.OrganizationId).ToListAsync();
|
||||
|
||||
var tenant = tenants.OrderBy(t => t.OnBoardingDate).FirstOrDefault();
|
||||
|
||||
var accessToken = _refreshTokenService.GenerateJwtToken(requestEmployee.ApplicationUser?.UserName,
|
||||
tenant?.Id ?? Guid.Empty, requestEmployee.OrganizationId, _jwtSettings);
|
||||
|
||||
1284
Marco.Pms.Services/Controllers/CollectionController.cs
Normal file
1284
Marco.Pms.Services/Controllers/CollectionController.cs
Normal file
File diff suppressed because it is too large
Load Diff
@ -2,6 +2,8 @@
|
||||
using Marco.Pms.Model.Activities;
|
||||
using Marco.Pms.Model.Dtos.Attendance;
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Entitlements;
|
||||
using Marco.Pms.Model.Expenses;
|
||||
using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Marco.Pms.Model.ViewModels.DashBoard;
|
||||
@ -12,6 +14,7 @@ using MarcoBMS.Services.Service;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
@ -25,19 +28,35 @@ namespace Marco.Pms.Services.Controllers
|
||||
private readonly IProjectServices _projectServices;
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly PermissionServices _permissionServices;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
public static readonly Guid ActiveId = Guid.Parse("b74da4c2-d07e-46f2-9919-e75e49b12731");
|
||||
public DashboardController(ApplicationDbContext context, UserHelper userHelper, IProjectServices projectServices, ILoggingService logger, PermissionServices permissionServices)
|
||||
private static readonly Guid Draft = Guid.Parse("297e0d8f-f668-41b5-bfea-e03b354251c8");
|
||||
private static readonly Guid Review = Guid.Parse("6537018f-f4e9-4cb3-a210-6c3b2da999d7");
|
||||
private static readonly Guid Approve = Guid.Parse("4068007f-c92f-4f37-a907-bc15fe57d4d8");
|
||||
private static readonly Guid ProcessPending = Guid.Parse("f18c5cfd-7815-4341-8da2-2c2d65778e27");
|
||||
private static readonly Guid Processed = Guid.Parse("61578360-3a49-4c34-8604-7b35a3787b95");
|
||||
private static readonly Guid RejectedByReviewer = Guid.Parse("965eda62-7907-4963-b4a1-657fb0b2724b");
|
||||
private static readonly Guid RejectedByApprover = Guid.Parse("d1ee5eec-24b6-4364-8673-a8f859c60729");
|
||||
private readonly Guid tenantId;
|
||||
|
||||
public DashboardController(ApplicationDbContext context,
|
||||
UserHelper userHelper,
|
||||
IProjectServices projectServices,
|
||||
IServiceScopeFactory serviceScopeFactory,
|
||||
ILoggingService logger,
|
||||
PermissionServices permissionServices)
|
||||
{
|
||||
_context = context;
|
||||
_userHelper = userHelper;
|
||||
_projectServices = projectServices;
|
||||
_logger = logger;
|
||||
_serviceScopeFactory = serviceScopeFactory;
|
||||
_permissionServices = permissionServices;
|
||||
tenantId = userHelper.GetTenantId();
|
||||
}
|
||||
[HttpGet("progression")]
|
||||
public async Task<IActionResult> GetGraph([FromQuery] double days, [FromQuery] string FromDate, [FromQuery] Guid? projectId)
|
||||
{
|
||||
var tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
DateTime fromDate = new DateTime();
|
||||
@ -149,7 +168,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
[HttpGet("projects")]
|
||||
public async Task<IActionResult> GetProjectCount()
|
||||
{
|
||||
var tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
var projects = await _context.Projects.Where(p => p.TenantId == tenantId).ToListAsync();
|
||||
@ -176,7 +194,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
try
|
||||
{
|
||||
var tenantId = _userHelper.GetTenantId();
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
_logger.LogInfo("GetTotalEmployees called by user {UserId} for ProjectId: {ProjectId}", loggedInEmployee.Id, projectId ?? Guid.Empty);
|
||||
@ -269,7 +286,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
try
|
||||
{
|
||||
var tenantId = _userHelper.GetTenantId();
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
_logger.LogInfo("GetTotalTasks called by user {UserId} for ProjectId: {ProjectId}", loggedInEmployee.Id, projectId ?? Guid.Empty);
|
||||
@ -348,10 +364,10 @@ namespace Marco.Pms.Services.Controllers
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("An internal server error occurred.", null, 500));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("pending-attendance")]
|
||||
public async Task<IActionResult> GetPendingAttendance()
|
||||
{
|
||||
Guid tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
var attendance = await _context.Attendes.Where(a => a.EmployeeId == LoggedInEmployee.Id && a.TenantId == tenantId).ToListAsync();
|
||||
@ -374,7 +390,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
[HttpGet("project-attendance/{projectId}")]
|
||||
public async Task<IActionResult> GetProjectAttendance(Guid projectId, [FromQuery] string? date)
|
||||
{
|
||||
Guid tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
DateTime currentDate = DateTime.UtcNow;
|
||||
@ -428,7 +443,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
[HttpGet("activities/{projectId}")]
|
||||
public async Task<IActionResult> GetActivities(Guid projectId, [FromQuery] string? date)
|
||||
{
|
||||
Guid tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
DateTime currentDate = DateTime.UtcNow;
|
||||
@ -600,5 +614,317 @@ namespace Marco.Pms.Services.Controllers
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(sortedResult, $"{sortedResult.Count} records fetched for attendance overview", 200));
|
||||
}
|
||||
|
||||
[HttpGet("expense/monthly")]
|
||||
public async Task<IActionResult> GetExpenseReportByProjectsAsync([FromQuery] Guid? projectId, [FromQuery] Guid? categoryId, [FromQuery] int months)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
// Read-only base filter with tenant scope and non-draft
|
||||
var baseQuery = _context.Expenses
|
||||
.AsNoTracking()
|
||||
.Where(e =>
|
||||
e.TenantId == tenantId
|
||||
&& e.IsActive
|
||||
&& e.StatusId != Draft); // [Server Filters]
|
||||
|
||||
if (months != 0)
|
||||
{
|
||||
months = 0 - months;
|
||||
var end = DateTime.UtcNow.Date;
|
||||
var start = end.AddMonths(months); // inclusive EOD
|
||||
baseQuery = baseQuery.Where(e => e.TransactionDate >= start
|
||||
&& e.TransactionDate <= end);
|
||||
}
|
||||
|
||||
if (projectId.HasValue)
|
||||
baseQuery = baseQuery.Where(e => e.ProjectId == projectId);
|
||||
|
||||
if (categoryId.HasValue)
|
||||
baseQuery = baseQuery.Where(e => e.ExpensesTypeId == categoryId);
|
||||
|
||||
// Single server-side group/aggregate by project
|
||||
var report = await baseQuery
|
||||
.AsNoTracking()
|
||||
.GroupBy(e => new { e.TransactionDate.Year, e.TransactionDate.Month })
|
||||
.Select(g => new
|
||||
{
|
||||
Year = g.Key.Year,
|
||||
Month = g.Key.Month,
|
||||
Total = g.Sum(x => x.Amount),
|
||||
Count = g.Count()
|
||||
})
|
||||
.OrderBy(x => x.Year).ThenBy(x => x.Month)
|
||||
.ToListAsync();
|
||||
|
||||
var culture = CultureInfo.GetCultureInfo("en-IN"); // pick desired locale
|
||||
|
||||
var response = report
|
||||
.Select(x => new
|
||||
{
|
||||
MonthName = culture.DateTimeFormat.GetMonthName(x.Month), // e.g., "January"
|
||||
Year = x.Year,
|
||||
Total = x.Total,
|
||||
Count = x.Count
|
||||
}).ToList();
|
||||
|
||||
_logger.LogInfo(
|
||||
"GetExpenseReportByProjects completed. TenantId={TenantId}, Rows={Rows}",
|
||||
tenantId, report.Count); // [Completion Log]
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Expense report by project fetched successfully", 200)); // [Success Response]
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning("GetExpenseReportByProjects canceled by client. TenantId={TenantId}", tenantId); // [Cancel Log]
|
||||
return StatusCode(499, ApiResponse<object>.ErrorResponse("Client has canceled the opration", "Client has canceled the opration", 499)); // [Cancel Response]
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"GetExpenseReportByProjects failed. TenantId={TenantId}",
|
||||
tenantId); // [Error Log]
|
||||
return StatusCode(500,
|
||||
ApiResponse<object>.ErrorResponse("An error occurred while fetching the expense report.", 500)); // [Error Response]
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("expense/type")]
|
||||
public async Task<IActionResult> GetExpenseReportByExpenseTypeAsync([FromQuery] Guid? projectId, [FromQuery] DateTime startDate, [FromQuery] DateTime endDate)
|
||||
{
|
||||
// Structured log: entering action with filters
|
||||
_logger.LogDebug(
|
||||
"GetExpenseReportByExpenseType started. TenantId={TenantId}, ProjectId={ProjectId}, StartDate={StartDate}, EndDate={EndDate}",
|
||||
tenantId, projectId ?? Guid.Empty, startDate, endDate); // [Start Log] [memory:4][memory:1]
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
// Compose base query: push filters to DB, avoid client evaluation
|
||||
IQueryable<Expenses> baseQuery = _context.Expenses
|
||||
.AsNoTracking() // Reduce tracking overhead for read-only endpoint
|
||||
.Where(e => e.TenantId == tenantId
|
||||
&& e.IsActive
|
||||
&& e.StatusId != Draft
|
||||
&& e.TransactionDate >= startDate
|
||||
&& e.TransactionDate <= endDate.AddDays(1).AddTicks(-1));
|
||||
|
||||
if (projectId.HasValue)
|
||||
baseQuery = baseQuery.Where(e => e.ProjectId == projectId.Value); // [Filter] [memory:7]
|
||||
|
||||
// Project to a minimal shape before grouping to avoid loading navigation graphs
|
||||
// Group by expense type name; adjust to the correct key if ExpensesCategory is an enum or navigation
|
||||
var query = baseQuery
|
||||
.Where(e => e.ExpensesType != null)
|
||||
.Select(e => new
|
||||
{
|
||||
ExpenseTypeName = e.ExpensesType!.Name, // If enum, use e.ExpensesCategory.ToString()
|
||||
Amount = e.Amount,
|
||||
StatusId = e.StatusId
|
||||
})
|
||||
.GroupBy(x => x.ExpenseTypeName)
|
||||
.Select(g => new
|
||||
{
|
||||
ProjectName = g.Key, // Original code used g.Key!.Name; here the grouping key is already a string
|
||||
TotalApprovedAmount = g.Where(x => x.StatusId == Processed
|
||||
|| x.StatusId == ProcessPending).Sum(x => x.Amount),
|
||||
TotalPendingAmount = g.Where(x => x.StatusId != Processed
|
||||
&& x.StatusId != RejectedByReviewer
|
||||
&& x.StatusId != RejectedByApprover)
|
||||
.Sum(x => x.Amount),
|
||||
TotalRejectedAmount = g.Where(x => x.StatusId == RejectedByReviewer
|
||||
|| x.StatusId == RejectedByApprover)
|
||||
.Sum(x => x.Amount),
|
||||
TotalProcessedAmount = g.Where(x => x.StatusId == Processed)
|
||||
.Sum(x => x.Amount)
|
||||
})
|
||||
.OrderBy(r => r.ProjectName); // Server-side order [memory:7]
|
||||
|
||||
var report = await query.ToListAsync(); // Single round-trip [memory:7]
|
||||
|
||||
var response = new
|
||||
{
|
||||
Report = report,
|
||||
TotalAmount = report.Sum(r => r.TotalApprovedAmount)
|
||||
};
|
||||
|
||||
_logger.LogInfo(
|
||||
"GetExpenseReportByExpenseType completed. TenantId={TenantId}, Filters: ProjectId={ProjectId}, StartDate={StartDate}, EndDate={EndDate}, Rows={RowCount}, TotalAmount={TotalAmount}",
|
||||
tenantId, projectId ?? Guid.Empty, startDate, endDate, report.Count, response.TotalAmount); // [Completion Log] [memory:4]
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Expense report by expense type fetched successfully", 200)); // [Success Response] [memory:1]
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning("GetExpenseReportByExpenseType canceled by client. TenantId={TenantId}", tenantId); // [Cancel Log] [memory:4]
|
||||
return StatusCode(499, ApiResponse<object>.ErrorResponse("Client has canceled the opration", "Client has canceled the opration", 499)); // [Cancel Response] [memory:1]
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"GetExpenseReportByExpenseType failed. TenantId={TenantId}, ProjectId={ProjectId}, StartDate={StartDate}, EndDate={EndDate}",
|
||||
tenantId, projectId ?? Guid.Empty, startDate, endDate); // [Error Log] [memory:4]
|
||||
return StatusCode(StatusCodes.Status500InternalServerError,
|
||||
ApiResponse<object>.ErrorResponse("An error occurred while fetching the expense report.", 500)); // [Error Response] [memory:1]
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("expense/pendings")]
|
||||
public async Task<IActionResult> GetPendingExpenseListAsync([FromQuery] Guid? projectId)
|
||||
{
|
||||
// Start log with correlation fields
|
||||
_logger.LogDebug(
|
||||
"GetPendingExpenseListAsync started. Project={ProjectId} TenantId={TenantId}", projectId ?? Guid.Empty, tenantId); // [Start Log]
|
||||
|
||||
try
|
||||
{
|
||||
// Resolve current employee once; avoid using scoped services inside Task.Run
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync(); // [User Context]
|
||||
|
||||
// Resolve permission service from current scope once
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
|
||||
// Fire permission checks concurrently without Task.Run; these are async I/O methods
|
||||
|
||||
var hasReviewPermissionTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ExpenseReview, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
var hasApprovePermissionTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ExpenseApprove, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
var hasProcessPermissionTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ExpenseProcess, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
var hasManagePermissionTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ExpenseManage, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
await Task.WhenAll(hasReviewPermissionTask, hasApprovePermissionTask, hasProcessPermissionTask, hasManagePermissionTask); // [Parallel Await]
|
||||
|
||||
var hasReviewPermission = hasReviewPermissionTask.Result;
|
||||
var hasApprovePermission = hasApprovePermissionTask.Result;
|
||||
var hasProcessPermission = hasProcessPermissionTask.Result;
|
||||
var hasManagePermission = hasManagePermissionTask.Result;
|
||||
|
||||
_logger.LogInfo(
|
||||
"Permissions resolved: Review={Review}, Approve={Approve}, Process={Process}",
|
||||
hasReviewPermission, hasApprovePermission, hasProcessPermission); // [Permissions Log]
|
||||
|
||||
// Build base query: read-only, tenant-scoped
|
||||
var baseQuery = _context.Expenses
|
||||
.Include(e => e.Status)
|
||||
.AsNoTracking() // Reduce tracking overhead for read-only list
|
||||
.Where(e => e.IsActive && e.TenantId == tenantId && e.StatusId != Processed && e.Status != null); // [Base Filter]
|
||||
|
||||
// Project to DTO in SQL to avoid heavy Include graph.
|
||||
if (projectId.HasValue)
|
||||
baseQuery = baseQuery.Where(e => e.ProjectId == projectId);
|
||||
|
||||
// Prefer ProjectTo when profiles exist; otherwise project minimal fields
|
||||
var expenses = await baseQuery
|
||||
.ToListAsync(); // Single round-trip; no Include needed for this shape
|
||||
|
||||
var draftExpenses = expenses.Where(e => e.StatusId == Draft && e.CreatedById == loggedInEmployee.Id).ToList();
|
||||
var reviewExpenses = expenses.Where(e => (hasReviewPermission || e.CreatedById == loggedInEmployee.Id) && e.StatusId == Review).ToList();
|
||||
var approveExpenses = expenses.Where(e => (hasApprovePermission || e.CreatedById == loggedInEmployee.Id) && e.StatusId == Approve).ToList();
|
||||
var processPendingExpenses = expenses.Where(e => (hasProcessPermission || e.CreatedById == loggedInEmployee.Id) && e.StatusId == ProcessPending).ToList();
|
||||
var submitedExpenses = expenses.Where(e => e.StatusId != Draft && e.CreatedById == loggedInEmployee.Id).ToList();
|
||||
var totalAmount = expenses.Where(e => e.StatusId != Draft).Sum(e => e.Amount);
|
||||
|
||||
if (hasManagePermission)
|
||||
{
|
||||
var response = new
|
||||
{
|
||||
Draft = new
|
||||
{
|
||||
Count = draftExpenses.Count,
|
||||
TotalAmount = draftExpenses.Sum(e => e.Amount)
|
||||
},
|
||||
ReviewPending = new
|
||||
{
|
||||
Count = reviewExpenses.Count,
|
||||
TotalAmount = reviewExpenses.Sum(e => e.Amount)
|
||||
},
|
||||
ApprovePending = new
|
||||
{
|
||||
Count = approveExpenses.Count,
|
||||
TotalAmount = approveExpenses.Sum(e => e.Amount)
|
||||
},
|
||||
ProcessPending = new
|
||||
{
|
||||
Count = processPendingExpenses.Count,
|
||||
TotalAmount = processPendingExpenses.Sum(e => e.Amount)
|
||||
},
|
||||
Submited = new
|
||||
{
|
||||
Count = submitedExpenses.Count,
|
||||
TotalAmount = submitedExpenses.Sum(e => e.Amount)
|
||||
},
|
||||
TotalAmount = totalAmount
|
||||
};
|
||||
_logger.LogInfo(
|
||||
"GetPendingExpenseListAsync completed. TenantId={TenantId}",
|
||||
tenantId); // [Completion Log]
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Pending Expenses fetched successfully", 200)); // [Success Response]
|
||||
}
|
||||
else
|
||||
{
|
||||
var response = new
|
||||
{
|
||||
Draft = new
|
||||
{
|
||||
Count = draftExpenses.Count
|
||||
},
|
||||
ReviewPending = new
|
||||
{
|
||||
Count = reviewExpenses.Count
|
||||
},
|
||||
ApprovePending = new
|
||||
{
|
||||
Count = approveExpenses.Count
|
||||
},
|
||||
ProcessPending = new
|
||||
{
|
||||
Count = processPendingExpenses.Count
|
||||
},
|
||||
Submited = new
|
||||
{
|
||||
Count = submitedExpenses.Count
|
||||
},
|
||||
TotalAmount = totalAmount
|
||||
};
|
||||
_logger.LogInfo(
|
||||
"GetPendingExpenseListAsync completed. TenantId={TenantId}",
|
||||
tenantId); // [Completion Log]
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Pending Expenses fetched successfully", 200)); // [Success Response]
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning("GetPendingExpenseListAsync canceled by client. TenantId={TenantId}", tenantId); // [Cancel Log]
|
||||
return StatusCode(499, ApiResponse<object>.ErrorResponse("Client has canceled the opration", "Client has canceled the opration", 499)); // [Cancel Response]
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "GetPendingExpenseListAsync failed. TenantId={TenantId}", tenantId); // [Error Log]
|
||||
return StatusCode(500,
|
||||
ApiResponse<object>.ErrorResponse("An error occurred while fetching pending expenses.", "An error occurred while fetching pending expenses.", 500)); // [Error Response]
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -33,25 +33,25 @@ namespace Marco.Pms.Services.Controllers
|
||||
#region =================================================================== Contact Get APIs ===================================================================
|
||||
|
||||
[HttpGet("list")]
|
||||
public async Task<IActionResult> GetContactList([FromQuery] string? search, [FromQuery] string? filter, [FromQuery] Guid? projectId, [FromQuery] bool active = true,
|
||||
public async Task<IActionResult> GetContactList([FromQuery] string? searchString, [FromQuery] string? filter, [FromQuery] Guid? projectId, [FromQuery] bool active = true,
|
||||
[FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 20)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var response = await _directoryService.GetListOfContactsAsync(search: search, filter: filter, projectId: projectId, active: active, pageSize: pageSize, pageNumber: pageNumber, tenantId, loggedInEmployee);
|
||||
var response = await _directoryService.GetListOfContactsAsync(search: searchString, filter: filter, projectId: projectId, active: active, pageSize: pageSize, pageNumber: pageNumber, tenantId, loggedInEmployee);
|
||||
|
||||
return StatusCode(response.StatusCode, response);
|
||||
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetContactList([FromQuery] string? search, [FromQuery] List<Guid>? bucketIds, [FromQuery] List<Guid>? categoryIds, [FromQuery] Guid? projectId, [FromQuery] bool active = true)
|
||||
public async Task<IActionResult> GetContactList([FromQuery] string? searchString, [FromQuery] List<Guid>? bucketIds, [FromQuery] List<Guid>? categoryIds, [FromQuery] Guid? projectId, [FromQuery] bool active = true)
|
||||
{
|
||||
ContactFilterDto filterDto = new ContactFilterDto
|
||||
{
|
||||
BucketIds = bucketIds,
|
||||
CategoryIds = categoryIds
|
||||
};
|
||||
var response = await _directoryService.GetListOfContactsOld(search, active, filterDto, projectId);
|
||||
var response = await _directoryService.GetListOfContactsOld(searchString, active, filterDto, projectId);
|
||||
|
||||
|
||||
return StatusCode(response.StatusCode, response);
|
||||
|
||||
@ -35,6 +35,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly Guid tenantId;
|
||||
private readonly Guid organizationId;
|
||||
|
||||
private static readonly Guid ProjectEntity = Guid.Parse("c8fe7115-aa27-43bc-99f4-7b05fabe436e");
|
||||
private static readonly Guid EmployeeEntity = Guid.Parse("dbb9555a-7a0c-40f2-a9ed-f0463f1ceed7");
|
||||
@ -52,6 +53,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
|
||||
tenantId = userHelper.GetTenantId();
|
||||
organizationId = _userHelper.GetCurrentOrganizationId();
|
||||
}
|
||||
|
||||
[HttpGet("list/{entityTypeId}/entity/{entityId}")]
|
||||
@ -93,21 +95,21 @@ namespace Marco.Pms.Services.Controllers
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Entity type not found", "Entity Type not found in database", 404));
|
||||
}
|
||||
|
||||
// Project permission check
|
||||
if (ProjectEntity == entityTypeId)
|
||||
{
|
||||
var hasProjectPermission = await _permission.HasProjectPermission(loggedInEmployee, entityId);
|
||||
if (!hasProjectPermission)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} does not have project access for ProjectId {ProjectId}", loggedInEmployee.Id, entityId);
|
||||
return StatusCode(403, ApiResponse<object>.ErrorResponse("Access Denied.", "You do not have permission to access project documents", 403));
|
||||
}
|
||||
}
|
||||
//// Project permission check
|
||||
//if (ProjectEntity == entityTypeId)
|
||||
//{
|
||||
// var hasProjectPermission = await _permission.HasProjectPermission(loggedInEmployee, entityId);
|
||||
// if (!hasProjectPermission)
|
||||
// {
|
||||
// _logger.LogWarning("Employee {EmployeeId} does not have project access for ProjectId {ProjectId}", loggedInEmployee.Id, entityId);
|
||||
// return StatusCode(403, ApiResponse<object>.ErrorResponse("Access Denied.", "You do not have permission to access project documents", 403));
|
||||
// }
|
||||
//}
|
||||
// Employee validation
|
||||
else if (EmployeeEntity == entityTypeId)
|
||||
{
|
||||
var isEmployeeExists = await _context.Employees
|
||||
.AnyAsync(e => e.Id == entityId && e.TenantId == tenantId);
|
||||
.AnyAsync(e => e.Id == entityId && e.OrganizationId == organizationId);
|
||||
|
||||
if (!isEmployeeExists)
|
||||
{
|
||||
@ -691,7 +693,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
bool entityExists = false;
|
||||
if (entityType.Equals(EmployeeEntity))
|
||||
{
|
||||
entityExists = await _context.Employees.AnyAsync(e => e.Id == model.EntityId && e.TenantId == tenantId);
|
||||
entityExists = await _context.Employees.AnyAsync(e => e.Id == model.EntityId && e.OrganizationId == organizationId);
|
||||
}
|
||||
else if (entityType.Equals(ProjectEntity))
|
||||
{
|
||||
@ -1078,15 +1080,15 @@ namespace Marco.Pms.Services.Controllers
|
||||
bool entityExists;
|
||||
if (entityType.Equals(EmployeeEntity))
|
||||
{
|
||||
entityExists = await _context.Employees.AnyAsync(e => e.Id == oldAttachment.EntityId && e.TenantId == tenantId);
|
||||
entityExists = await _context.Employees.AnyAsync(e => e.Id == oldAttachment.EntityId && e.OrganizationId == organizationId);
|
||||
}
|
||||
else if (entityType.Equals(ProjectEntity))
|
||||
{
|
||||
entityExists = await _context.Projects.AnyAsync(p => p.Id == oldAttachment.EntityId && p.TenantId == tenantId);
|
||||
if (entityExists)
|
||||
{
|
||||
entityExists = await _permission.HasProjectPermission(loggedInEmployee, oldAttachment.EntityId);
|
||||
}
|
||||
//if (entityExists)
|
||||
//{
|
||||
// entityExists = await _permission.HasProjectPermission(loggedInEmployee, oldAttachment.EntityId);
|
||||
//}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@ -233,84 +233,12 @@ namespace MarcoBMS.Services.Controllers
|
||||
_logger.LogInfo("GetEmployeesByProject called. EmployeeId: {EmployeeId}, ProjectId: {ProjectId}, showInactive: {ShowInactive}",
|
||||
loggedInEmployee.Id, projectId ?? Guid.Empty, showInactive);
|
||||
|
||||
// Step 3: Fetch permissions concurrently
|
||||
var viewAllTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ViewAllEmployees, loggedInEmployee.Id);
|
||||
});
|
||||
var viewTeamTask = Task.Run(async () =>
|
||||
{
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await _permission.HasPermission(PermissionsMaster.ViewTeamMembers, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
await Task.WhenAll(viewAllTask, viewTeamTask);
|
||||
|
||||
var hasViewAllEmployeesPermission = viewAllTask.Result;
|
||||
var hasViewTeamMembersPermission = viewTeamTask.Result;
|
||||
|
||||
List<Employee> employees = new List<Employee>();
|
||||
|
||||
// Step 4: Query based on permission
|
||||
if (hasViewAllEmployeesPermission && !projectId.HasValue)
|
||||
{
|
||||
// OrganizationId needs to be retrieved from loggedInEmployee or context based on your app's structure
|
||||
var employeeQuery = _context.Employees
|
||||
.AsNoTracking() // Optimize EF query for read-only operation[web:1][web:13][web:18]
|
||||
var employees = await _context.Employees
|
||||
.Include(e => e.JobRole)
|
||||
.Where(e => e.OrganizationId == organizationId);
|
||||
|
||||
employeeQuery = showInactive
|
||||
? employeeQuery.Where(e => !e.IsActive)
|
||||
: employeeQuery.Where(e => e.IsActive);
|
||||
|
||||
employees = await employeeQuery.ToListAsync();
|
||||
_logger.LogInfo("Employee list fetched with full access. Count: {Count}", employees.Count);
|
||||
}
|
||||
else if (hasViewTeamMembersPermission && !showInactive && !projectId.HasValue)
|
||||
{
|
||||
// Only active team members with limited permission
|
||||
var projectIds = await _projectServices.GetMyProjectIdsAsync(tenantId, loggedInEmployee);
|
||||
|
||||
employees = await _context.ProjectAllocations
|
||||
.AsNoTracking()
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Where(pa =>
|
||||
projectIds.Contains(pa.ProjectId)
|
||||
&& pa.IsActive
|
||||
&& pa.Employee != null
|
||||
&& pa.Employee.IsActive
|
||||
&& pa.TenantId == tenantId)
|
||||
.Select(pa => pa.Employee!)
|
||||
.Distinct()
|
||||
.Include(e => e.Organization)
|
||||
.Where(e => e.OrganizationId == loggedInEmployee.OrganizationId && e.IsActive != showInactive)
|
||||
.ToListAsync();
|
||||
|
||||
_logger.LogInfo("Employee list fetched with limited access (active only). Count: {Count}", employees.Count);
|
||||
}
|
||||
|
||||
// If a specific projectId is provided, override employee fetching to ensure strict project context
|
||||
if (projectId.HasValue)
|
||||
{
|
||||
employees = await _context.ProjectAllocations
|
||||
.AsNoTracking()
|
||||
.Include(pa => pa.Employee)
|
||||
.ThenInclude(e => e!.JobRole)
|
||||
.Where(pa =>
|
||||
pa.ProjectId == projectId
|
||||
&& pa.IsActive
|
||||
&& pa.Employee != null
|
||||
&& pa.Employee.IsActive
|
||||
&& pa.TenantId == tenantId)
|
||||
.Select(pa => pa.Employee!)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
_logger.LogInfo("Employee list fetched for specific project. ProjectId: {ProjectId}. Count: {Count}",
|
||||
projectId, employees.Count);
|
||||
}
|
||||
|
||||
// Step 5: Map to view model
|
||||
result = employees.Select(e => _mapper.Map<EmployeeVM>(e)).Distinct().ToList();
|
||||
|
||||
@ -329,7 +257,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
|
||||
|
||||
[HttpGet("basic")]
|
||||
public async Task<IActionResult> GetEmployeesByProjectBasic(Guid? projectId, [FromQuery] string? searchString)
|
||||
public async Task<IActionResult> GetEmployeesByProjectBasic(Guid? projectId, [FromQuery] string? searchString, [FromQuery] bool sendAll = false)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var employeeQuery = _context.Employees.Where(e => e.IsActive);
|
||||
@ -353,8 +281,11 @@ namespace MarcoBMS.Services.Controllers
|
||||
var searchStringLower = searchString.ToLower();
|
||||
employeeQuery = employeeQuery.Where(e => (e.FirstName + " " + e.LastName).ToLower().Contains(searchStringLower));
|
||||
}
|
||||
|
||||
var response = await employeeQuery.Take(10).Select(e => _mapper.Map<BasicEmployeeVM>(e)).ToListAsync();
|
||||
if (!sendAll)
|
||||
{
|
||||
employeeQuery = employeeQuery.Take(10);
|
||||
}
|
||||
var response = await employeeQuery.Select(e => _mapper.Map<BasicEmployeeVM>(e)).ToListAsync();
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, $"{response.Count} records of employees fetched successfully", 200));
|
||||
}
|
||||
|
||||
@ -470,6 +401,9 @@ namespace MarcoBMS.Services.Controllers
|
||||
Guid tenantId = _userHelper.GetTenantId();
|
||||
var LoggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
Guid employeeId = Guid.Empty;
|
||||
|
||||
|
||||
|
||||
if (model == null)
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid data", "Invaild Data", 400));
|
||||
|
||||
@ -602,6 +536,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
{
|
||||
// Correlation and context capture for logs
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
Guid organizationId = model.OrganizationId ?? loggedInEmployee.OrganizationId;
|
||||
|
||||
{
|
||||
if (model == null)
|
||||
@ -625,10 +560,10 @@ namespace MarcoBMS.Services.Controllers
|
||||
if (model.Id.HasValue && model.Id.Value != Guid.Empty)
|
||||
{
|
||||
existingEmployee = await _context.Employees
|
||||
.FirstOrDefaultAsync(e => e.Id == model.Id && e.OrganizationId == model.OrganizationId);
|
||||
.FirstOrDefaultAsync(e => e.Id == model.Id && e.OrganizationId == organizationId);
|
||||
if (existingEmployee == null)
|
||||
{
|
||||
_logger.LogInfo("Employee not found for update. Id={EmployeeId}, Org={OrgId}", model.Id, model.OrganizationId);
|
||||
_logger.LogInfo("Employee not found for update. Id={EmployeeId}, Org={OrgId}", model.Id, organizationId);
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Employee not found", "Employee not found in database", 404));
|
||||
}
|
||||
}
|
||||
@ -680,10 +615,10 @@ namespace MarcoBMS.Services.Controllers
|
||||
if (!string.IsNullOrWhiteSpace(model.Email))
|
||||
{
|
||||
var emailExists = await _context.Employees
|
||||
.AnyAsync(e => e.Email == model.Email && e.OrganizationId == model.OrganizationId);
|
||||
.AnyAsync(e => e.Email == model.Email);
|
||||
if (emailExists)
|
||||
{
|
||||
_logger.LogInfo("Employee email already exists in org. Email={Email}, Org={OrgId}", model.Email, model.OrganizationId);
|
||||
_logger.LogInfo("Employee email already exists. Email={Email}", model.Email);
|
||||
return StatusCode(403, ApiResponse<object>.ErrorResponse(
|
||||
"Employee with email already exists",
|
||||
"Employee with this email already exists", 403));
|
||||
@ -723,7 +658,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
existingEmployee.ApplicationUserId = createdIdentityUser.Id;
|
||||
await SendResetIfApplicableAsync(createdIdentityUser, existingEmployee.FirstName ?? "User");
|
||||
}
|
||||
|
||||
existingEmployee.OrganizationId = organizationId;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
employeeId = existingEmployee.Id;
|
||||
@ -745,7 +680,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
newEmployee.ApplicationUserId = createdIdentityUser.Id;
|
||||
await SendResetIfApplicableAsync(createdIdentityUser, newEmployee.FirstName ?? "User");
|
||||
}
|
||||
|
||||
newEmployee.OrganizationId = organizationId;
|
||||
await _context.Employees.AddAsync(newEmployee);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@ -877,6 +812,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
public async Task<IActionResult> CreateUserMobileAsync([FromBody] MobileUserManageDto model)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
Guid organizationId = model.OrganizationId ?? loggedInEmployee.OrganizationId;
|
||||
if (tenantId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("Tenant resolution failed in CreateUserMobile"); // structured warning
|
||||
@ -912,11 +848,11 @@ namespace MarcoBMS.Services.Controllers
|
||||
if (model.Id == null || model.Id == Guid.Empty)
|
||||
{
|
||||
var emailExists = await _context.Employees
|
||||
.AnyAsync(e => e.Email == model.Email && e.OrganizationId == model.OrganizationId);
|
||||
.AnyAsync(e => e.Email == model.Email);
|
||||
|
||||
if (emailExists)
|
||||
{
|
||||
_logger.LogInfo("Employee email already exists in org. Email={Email}, Org={OrgId}", model.Email ?? string.Empty, model.OrganizationId);
|
||||
_logger.LogInfo("Employee email already exists in org. Email={Email}, Org={OrgId}", model.Email ?? string.Empty, organizationId);
|
||||
return StatusCode(409, ApiResponse<object>.ErrorResponse("Employee with email already exists", "Employee with this email already exists", 409));
|
||||
}
|
||||
|
||||
@ -933,7 +869,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
JoiningDate = model.JoiningDate,
|
||||
JobRoleId = model.JobRoleId,
|
||||
Photo = imageBytes,
|
||||
OrganizationId = model.OrganizationId,
|
||||
OrganizationId = organizationId,
|
||||
HasApplicationAccess = model.HasApplicationAccess,
|
||||
};
|
||||
|
||||
@ -1001,7 +937,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
existingEmployee.PhoneNumber = model.PhoneNumber;
|
||||
existingEmployee.JoiningDate = model.JoiningDate;
|
||||
existingEmployee.JobRoleId = model.JobRoleId;
|
||||
existingEmployee.OrganizationId = model.OrganizationId;
|
||||
existingEmployee.OrganizationId = organizationId;
|
||||
existingEmployee.HasApplicationAccess = model.HasApplicationAccess;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(existingEmployee.Email) && !string.IsNullOrWhiteSpace(model.Email))
|
||||
@ -1011,7 +947,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
|
||||
if (emailExists)
|
||||
{
|
||||
_logger.LogInfo("Employee email already exists in org. Email={Email}, Org={OrgId}", model.Email, model.OrganizationId);
|
||||
_logger.LogInfo("Employee email already exists in org. Email={Email}, Org={OrgId}", model.Email, organizationId);
|
||||
return StatusCode(409, ApiResponse<object>.ErrorResponse("Employee with email already exists", "Employee with this email already exists", 409));
|
||||
}
|
||||
existingEmployee.Email = model.Email;
|
||||
@ -1075,7 +1011,7 @@ namespace MarcoBMS.Services.Controllers
|
||||
|
||||
Guid tenantId = _userHelper.GetTenantId();
|
||||
var LoggedEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
Employee? employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == id && e.TenantId == tenantId);
|
||||
Employee? employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == id && e.OrganizationId == organizationId);
|
||||
if (employee == null)
|
||||
{
|
||||
_logger.LogWarning("Employee with ID {EmploueeId} not found in database", id);
|
||||
@ -1248,11 +1184,14 @@ namespace MarcoBMS.Services.Controllers
|
||||
|
||||
// Prepare reset link sender helper
|
||||
private async Task SendResetIfApplicableAsync(ApplicationUser u, string firstName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(u.Email))
|
||||
{
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(u);
|
||||
var resetLink = $"{_configuration["AppSettings:WebFrontendUrl"]}/reset-password?token={WebUtility.UrlEncode(token)}";
|
||||
await _emailSender.SendResetPasswordEmailOnRegister(u.Email ?? "", firstName, resetLink);
|
||||
_logger.LogInfo("Reset password email queued. Email={Email}", u.Email ?? "");
|
||||
await _emailSender.SendResetPasswordEmailOnRegister(u.Email, firstName, resetLink);
|
||||
_logger.LogInfo("Reset password email queued. Email={Email}", u.Email);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using Marco.Pms.Model.Dtos.Activities;
|
||||
using Marco.Pms.Model.Dtos.Collection;
|
||||
using Marco.Pms.Model.Dtos.DocumentManager;
|
||||
using Marco.Pms.Model.Dtos.Master;
|
||||
using Marco.Pms.Model.Forum;
|
||||
@ -975,5 +976,38 @@ namespace Marco.Pms.Services.Controllers
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region =================================================================== Payment Adjustment Head APIs ===================================================================
|
||||
[HttpGet("payment-adjustment-head/list")]
|
||||
public async Task<IActionResult> GetpaymentAdjustmentHeadsList([FromQuery] bool isActive = true)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var response = await _masterService.GetPaymentAdjustmentHeadListAsync(isActive, loggedInEmployee, tenantId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
[HttpPost("payment-adjustment-head")]
|
||||
public async Task<IActionResult> CreatePaymentAdjustmentHead([FromBody] PaymentAdjustmentHeadDto dto)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var response = await _masterService.CreatePaymentAdjustmentHeadAsync(dto, loggedInEmployee, tenantId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
|
||||
[HttpPut("payment-adjustment-head/edit/{id}")]
|
||||
public async Task<IActionResult> UpdatePaymentAdjustmentHead(Guid id, [FromBody] PaymentAdjustmentHeadDto dto)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var response = await _masterService.UpdatePaymentAdjustmentHeadAsync(id, dto, loggedInEmployee, tenantId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
|
||||
[HttpDelete("payment-adjustment-head/delete/{id}")]
|
||||
public async Task<IActionResult> DeletePaymentAdjustmentHead(Guid id, [FromQuery] bool isActive = false)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
var response = await _masterService.DeletePaymentAdjustmentHeadAsync(id, isActive, loggedInEmployee, tenantId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
108
Marco.Pms.Services/Controllers/PaymentController.cs
Normal file
108
Marco.Pms.Services/Controllers/PaymentController.cs
Normal file
@ -0,0 +1,108 @@
|
||||
using Marco.Pms.Model.Dtos.PaymentGetway;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Marco.Pms.Services.Service.ServiceInterfaces;
|
||||
using MarcoBMS.Services.Helpers;
|
||||
using MarcoBMS.Services.Service;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class PaymentController : ControllerBase
|
||||
{
|
||||
private readonly UserHelper _userHelper;
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly IRazorpayService _razorpayService;
|
||||
private readonly Guid tenantId;
|
||||
private readonly Guid organizaionId;
|
||||
public PaymentController(UserHelper userHelper, ILoggingService logger, IRazorpayService razorpayService)
|
||||
{
|
||||
_userHelper = userHelper;
|
||||
_logger = logger;
|
||||
_razorpayService = razorpayService;
|
||||
tenantId = userHelper.GetTenantId();
|
||||
organizaionId = userHelper.GetCurrentOrganizationId();
|
||||
}
|
||||
|
||||
[HttpPost("create-order")]
|
||||
public async Task<IActionResult> CreateOrder([FromBody] CreateOrderDto model)
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
try
|
||||
{
|
||||
var response = _razorpayService.CreateOrder(model.Amount, loggedInEmployee, tenantId);
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Payment created successfully", 200));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("Error occured While creating the payment", new
|
||||
{
|
||||
Message = ex.Message,
|
||||
StackTrace = ex.StackTrace,
|
||||
Source = ex.Source,
|
||||
InnerException = new
|
||||
{
|
||||
Message = ex.InnerException?.Message,
|
||||
StackTrace = ex.InnerException?.StackTrace,
|
||||
Source = ex.InnerException?.Source,
|
||||
}
|
||||
}, 500));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("verify-payment")]
|
||||
public async Task<IActionResult> VerifyPayment([FromBody] PaymentVerificationRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInfo("Payment verification started for OrderId: {OrderId}, PaymentId: {PaymentId}",
|
||||
request.OrderId ?? "", request.PaymentId ?? "");
|
||||
|
||||
// Validate request
|
||||
if (string.IsNullOrEmpty(request.OrderId) || string.IsNullOrEmpty(request.PaymentId) || string.IsNullOrEmpty(request.Signature))
|
||||
{
|
||||
_logger.LogWarning("Payment verification failed - Missing required parameters");
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Missing required parameters", 400));
|
||||
}
|
||||
|
||||
// Verify signature
|
||||
string payload = request.OrderId + "|" + request.PaymentId;
|
||||
string actualSignature = request.Signature;
|
||||
string expectedSignature = _razorpayService.GetExpectedSignature(payload);
|
||||
|
||||
if (actualSignature == expectedSignature)
|
||||
{
|
||||
_logger.LogInfo("Payment signature verified successfully for OrderId: {OrderId}", request.OrderId);
|
||||
|
||||
// Fetch complete payment details from Razorpay including card details
|
||||
var response = await _razorpayService.GetPaymentDetails(request.PaymentId);
|
||||
|
||||
_logger.LogInfo("Invoice generated and saved for OrderId: {OrderId}", request.OrderId);
|
||||
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Payment verified successfully", 200));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Payment signature verification failed for OrderId: {OrderId}", request.OrderId);
|
||||
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid signature - Payment verification failed", "Invalid signature - Payment verification failed", 400));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during payment verification for OrderId: {OrderId}", request.OrderId ?? "");
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("An error occurred during payment verification", "An error occurred during payment verification", 500));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("get/payment-details/{id}")]
|
||||
public async Task<IActionResult> GetPaymentDetails(Guid id)
|
||||
{
|
||||
var paymentsDetails = await _razorpayService.GetPaymentDetailsFromDataBase(id);
|
||||
return Ok(ApiResponse<object>.SuccessResponse(paymentsDetails, "Payment fetched Successfully", 200));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -482,6 +482,13 @@ namespace MarcoBMS.Services.Controllers
|
||||
taskAllocationQuery = taskAllocationQuery.Where(t => t.WorkItem != null &&
|
||||
taskFilter.ActivityIds.Contains(t.WorkItem.ActivityId));
|
||||
}
|
||||
if (taskFilter.ServiceIds?.Any() ?? false)
|
||||
{
|
||||
taskAllocationQuery = taskAllocationQuery.Where(t => t.WorkItem != null &&
|
||||
t.WorkItem.ActivityMaster != null &&
|
||||
t.WorkItem.ActivityMaster.ActivityGroup != null &&
|
||||
taskFilter.ServiceIds.Contains(t.WorkItem.ActivityMaster.ActivityGroup.ServiceId));
|
||||
}
|
||||
if (taskFilter.dateFrom.HasValue && taskFilter.dateTo.HasValue)
|
||||
{
|
||||
taskAllocationQuery = taskAllocationQuery.Where(t => t.AssignmentDate.Date >= taskFilter.dateFrom.Value.Date &&
|
||||
@ -745,6 +752,97 @@ namespace MarcoBMS.Services.Controllers
|
||||
return Ok(ApiResponse<object>.SuccessResponse(taskVM, "Success", 200));
|
||||
}
|
||||
|
||||
[HttpGet("filter/{projectId}")]
|
||||
public async Task<IActionResult> GetTaskFilterObject(Guid projectId)
|
||||
{
|
||||
// Get the current tenant from claims/context
|
||||
Guid tenantId = GetTenantId();
|
||||
|
||||
// Log API invocation with the project and tenant for traceability
|
||||
_logger.LogInfo("Fetching filter objects for ProjectId={ProjectId}, TenantId={TenantId}", projectId, tenantId);
|
||||
|
||||
try
|
||||
{
|
||||
// AsNoTracking for improved performance—no intention to update these records
|
||||
// Only fetch & project properties actually required (DTO projection)
|
||||
var tasks = await _context.TaskAllocations
|
||||
.Include(t => t.WorkItem)
|
||||
.ThenInclude(wi => wi!.WorkArea)
|
||||
.ThenInclude(wa => wa!.Floor)
|
||||
.ThenInclude(f => f!.Building)
|
||||
.Include(t => t.WorkItem)
|
||||
.ThenInclude(wi => wi!.ActivityMaster)
|
||||
.ThenInclude(a => a!.ActivityGroup)
|
||||
.ThenInclude(ag => ag!.Service)
|
||||
.Where(t => t.WorkItem != null &&
|
||||
t.WorkItem.WorkArea != null &&
|
||||
t.WorkItem.WorkArea.Floor != null &&
|
||||
t.WorkItem.WorkArea.Floor.Building != null &&
|
||||
t.WorkItem.WorkArea.Floor.Building.ProjectId == projectId &&
|
||||
t.TenantId == tenantId).ToListAsync();
|
||||
|
||||
// Distinct by Id (since projection doesn't guarantee uniqueness across different allocations)
|
||||
var buildings = tasks.Where(t => t.WorkItem != null && t.WorkItem.WorkArea != null && t.WorkItem.WorkArea.Floor != null && t.WorkItem.WorkArea.Floor.Building != null)
|
||||
.Select(t => t.WorkItem!.WorkArea!.Floor!.Building!)
|
||||
.Select(b => new
|
||||
{
|
||||
Id = b.Id,
|
||||
Name = b.Name
|
||||
}).Distinct().ToList();
|
||||
|
||||
var floors = tasks.Where(t => t.WorkItem != null && t.WorkItem.WorkArea != null && t.WorkItem.WorkArea.Floor != null)
|
||||
.Select(t => t.WorkItem!.WorkArea!.Floor!)
|
||||
.Select(f => new
|
||||
{
|
||||
Id = f.Id,
|
||||
Name = f.FloorName,
|
||||
BuildingId = f.BuildingId
|
||||
}).Distinct().ToList();
|
||||
|
||||
var activities = tasks.Where(t => t.WorkItem != null &&
|
||||
t.WorkItem.ActivityMaster != null &&
|
||||
t.WorkItem.ActivityMaster.ActivityGroup != null &&
|
||||
t.WorkItem.ActivityMaster.ActivityGroup.Service != null)
|
||||
.Select(t => t.WorkItem!.ActivityMaster!)
|
||||
.Select(a => new
|
||||
{
|
||||
Id = a.Id,
|
||||
Name = a.ActivityName
|
||||
}).Distinct().ToList();
|
||||
|
||||
var services = tasks.Where(t => t.WorkItem != null &&
|
||||
t.WorkItem.ActivityMaster != null &&
|
||||
t.WorkItem.ActivityMaster.ActivityGroup != null &&
|
||||
t.WorkItem.ActivityMaster.ActivityGroup.Service != null)
|
||||
.Select(t => t.WorkItem!.ActivityMaster!.ActivityGroup!.Service!)
|
||||
.Select(s => new
|
||||
{
|
||||
Id = s.Id,
|
||||
Name = s.Name
|
||||
}).Distinct().ToList();
|
||||
|
||||
var response = new
|
||||
{
|
||||
Buildings = buildings,
|
||||
Floors = floors,
|
||||
Activities = activities,
|
||||
Services = services
|
||||
};
|
||||
|
||||
_logger.LogInfo("Successfully fetched filter objects for ProjectId={ProjectId}, TenantId={TenantId}", projectId, tenantId);
|
||||
|
||||
// Use DTO in API response for clarity and easier frontend usage
|
||||
return Ok(ApiResponse<object>.SuccessResponse(response, "Filter object for task fetched successfully", 200));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to fetch filter objects for ProjectId={ProjectId}, TenantId={TenantId}", projectId, tenantId);
|
||||
// Return a standard error result
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("Failed to fetch filter object.", 500));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Approves a reported task after validation, updates status, and stores attachments/comments.
|
||||
/// </summary>
|
||||
|
||||
@ -16,6 +16,7 @@ using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.Tenant;
|
||||
using Marco.Pms.Services.Helpers;
|
||||
using Marco.Pms.Services.Service;
|
||||
using Marco.Pms.Services.Service.ServiceInterfaces;
|
||||
using MarcoBMS.Services.Helpers;
|
||||
using MarcoBMS.Services.Service;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@ -230,6 +231,8 @@ namespace Marco.Pms.Services.Controllers
|
||||
{
|
||||
_logger.LogInfo("GetTenantDetails started for TenantId: {TenantId}", id);
|
||||
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
|
||||
// Get currently logged-in employee info
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
if (loggedInEmployee == null)
|
||||
@ -240,10 +243,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
|
||||
// Check permissions using a single service scope to avoid overhead
|
||||
bool hasManagePermission, hasModifyPermission, hasViewPermission;
|
||||
using (var scope = _serviceScopeFactory.CreateScope())
|
||||
{
|
||||
|
||||
|
||||
var manageTask = Task.Run(async () =>
|
||||
{
|
||||
var permissionService = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
@ -265,7 +264,6 @@ namespace Marco.Pms.Services.Controllers
|
||||
hasManagePermission = manageTask.Result;
|
||||
hasModifyPermission = modifyTask.Result;
|
||||
hasViewPermission = viewTask.Result;
|
||||
}
|
||||
|
||||
if (!hasManagePermission && !hasModifyPermission && !hasViewPermission)
|
||||
{
|
||||
@ -273,12 +271,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
return StatusCode(403,
|
||||
ApiResponse<object>.ErrorResponse("Access denied", "User does not have the required permissions for this action.", 403));
|
||||
}
|
||||
if (!hasManagePermission && (hasModifyPermission || hasViewPermission) && id != loggedInEmployee.TenantId)
|
||||
{
|
||||
_logger.LogWarning("Permission denied: User {EmployeeId} attempted to access tenant details of other tenant.", loggedInEmployee.Id);
|
||||
return StatusCode(403,
|
||||
ApiResponse<object>.ErrorResponse("Access denied", "User does not have the required permissions for this action.", 403));
|
||||
}
|
||||
|
||||
|
||||
// Create a single DbContext for main tenant fetch and related data requests
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
@ -297,6 +290,13 @@ namespace Marco.Pms.Services.Controllers
|
||||
}
|
||||
_logger.LogInfo("Tenant {TenantId} found.", tenant.Id);
|
||||
|
||||
if (!hasManagePermission && (tenant.OrganizationId != loggedInEmployee.OrganizationId || (!hasModifyPermission && !hasViewPermission)))
|
||||
{
|
||||
_logger.LogWarning("Permission denied: User {EmployeeId} attempted to access tenant details of other tenant.", loggedInEmployee.Id);
|
||||
return StatusCode(403,
|
||||
ApiResponse<object>.ErrorResponse("Access denied", "User does not have the required permissions for this action.", 403));
|
||||
}
|
||||
|
||||
// Fetch dependent data in parallel to improve performance
|
||||
var employeesTask = Task.Run(async () =>
|
||||
{
|
||||
@ -351,6 +351,11 @@ namespace Marco.Pms.Services.Controllers
|
||||
var plans = plansTask.Result;
|
||||
var projects = projectsTask.Result;
|
||||
|
||||
var _razorpayService = scope.ServiceProvider.GetRequiredService<IRazorpayService>();
|
||||
|
||||
var paymentDetailIds = plans.Where(ts => ts.PaymentDetailId.HasValue).Select(ts => ts.PaymentDetailId!.Value).ToList();
|
||||
var paymentsDetails = await _razorpayService.GetPaymentDetailsListFromDataBase(paymentDetailIds);
|
||||
|
||||
// Calculate active/inactive employees count
|
||||
var activeEmployeesCount = employees.Count(e => e.IsActive);
|
||||
var inActiveEmployeesCount = employees.Count - activeEmployeesCount;
|
||||
@ -379,9 +384,16 @@ namespace Marco.Pms.Services.Controllers
|
||||
response.CreatedBy = createdBy;
|
||||
|
||||
response.CurrentPlan = _mapper.Map<SubscriptionPlanDetailsVM>(currentPlan);
|
||||
response.CurrentPlan.PaymentDetail = paymentsDetails.FirstOrDefault(pd => currentPlan != null && pd.Id == currentPlan.PaymentDetailId);
|
||||
|
||||
response.CurrentPlanFeatures = await _featureDetailsHelper.GetFeatureDetails(currentPlan?.Plan?.FeaturesId ?? Guid.Empty);
|
||||
// Map subscription history plans to DTO
|
||||
response.SubscriptionHistery = _mapper.Map<List<SubscriptionPlanDetailsVM>>(plans);
|
||||
response.SubscriptionHistery = plans.Select(ts =>
|
||||
{
|
||||
var result = _mapper.Map<SubscriptionPlanDetailsVM>(ts);
|
||||
result.PaymentDetail = paymentsDetails.FirstOrDefault(pd => ts != null && pd.Id == ts.PaymentDetailId);
|
||||
return result;
|
||||
}).ToList();
|
||||
|
||||
_logger.LogInfo("Tenant details fetched successfully for TenantId: {TenantId}", tenant.Id);
|
||||
|
||||
@ -550,7 +562,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
JobRole = adminJobRole, // Link to the newly created role
|
||||
CurrentAddress = model.BillingAddress,
|
||||
IsActive = true,
|
||||
IsSystem = false,
|
||||
IsSystem = true,
|
||||
IsPrimary = true,
|
||||
OrganizationId = organization.Id,
|
||||
HasApplicationAccess = true
|
||||
@ -566,43 +578,36 @@ namespace Marco.Pms.Services.Controllers
|
||||
};
|
||||
_context.ApplicationRoles.Add(applicationRole);
|
||||
|
||||
var rolePermissionMappigs = new List<RolePermissionMappings> {
|
||||
new RolePermissionMappings
|
||||
var featureIds = new List<Guid>
|
||||
{
|
||||
new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), // Expense Management feature
|
||||
new Guid("81ab8a87-8ccd-4015-a917-0627cee6a100"), // Employee Management feature
|
||||
new Guid("52c9cf54-1eb2-44d2-81bb-524cf29c0a94"), // Attendance Management feature
|
||||
new Guid("a8cf4331-8f04-4961-8360-a3f7c3cc7462"), // Document Management feature
|
||||
new Guid("be3b3afc-6ccf-4566-b9b6-aafcb65546be"), // Masters Management feature
|
||||
new Guid("39e66f81-efc6-446c-95bd-46bff6cfb606"), // Directory Management feature
|
||||
new Guid("6d4c82d6-dbce-48ab-b8b8-f785f4d8c914") // Organization Management feature
|
||||
};
|
||||
|
||||
var permissionIds = await _context.FeaturePermissions.Where(fp => featureIds.Contains(fp.FeatureId)).Select(fp => fp.Id).ToListAsync();
|
||||
|
||||
var rolePermissionMappigs = permissionIds.Select(p => new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = p
|
||||
}).ToList();
|
||||
|
||||
rolePermissionMappigs.Add(new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ModifyTenant
|
||||
},
|
||||
new RolePermissionMappings
|
||||
});
|
||||
rolePermissionMappigs.Add(new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewTenant
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ManageMasters
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewMasters
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewOrganization
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.AddOrganization
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.EditOrganization
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
_context.RolePermissionMappings.AddRange(rolePermissionMappigs);
|
||||
|
||||
_context.EmployeeRoleMappings.Add(new EmployeeRoleMapping
|
||||
@ -651,6 +656,22 @@ namespace Marco.Pms.Services.Controllers
|
||||
_context.OrgServiceMappings.AddRange(serviceOrgMappings);
|
||||
}
|
||||
|
||||
var _masteData = scope.ServiceProvider.GetRequiredService<MasterDataService>();
|
||||
|
||||
var expensesTypeMaster = _masteData.GetExpensesTypeesData(tenant.Id);
|
||||
var paymentModeMatser = _masteData.GetPaymentModesData(tenant.Id);
|
||||
var documentCategoryMaster = _masteData.GetDocumentCategoryData(tenant.Id);
|
||||
|
||||
var employeeDocumentId = documentCategoryMaster.Where(dc => dc.Name == "Employee Documents").Select(dc => dc.Id).FirstOrDefault();
|
||||
var projectDocumentId = documentCategoryMaster.Where(dc => dc.Name == "Project Documents").Select(dc => dc.Id).FirstOrDefault();
|
||||
|
||||
var documentTypeMaster = _masteData.GetDocumentTypeData(tenant.Id, employeeDocumentId, projectDocumentId);
|
||||
|
||||
_context.ExpensesTypeMaster.AddRange(expensesTypeMaster);
|
||||
_context.PaymentModeMatser.AddRange(paymentModeMatser);
|
||||
_context.DocumentCategoryMasters.AddRange(documentCategoryMaster);
|
||||
_context.DocumentTypeMasters.AddRange(documentTypeMaster);
|
||||
|
||||
// All entities are now added to the context. Save them all in a single database operation.
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@ -913,6 +934,58 @@ namespace Marco.Pms.Services.Controllers
|
||||
return Ok(ApiResponse<object>.SuccessResponse(responseData, successMessage, 200));
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("self/create")]
|
||||
public async Task<IActionResult> SelfRegistrationTenant([FromBody] TenantEnquireDto model)
|
||||
{
|
||||
// Log the start of the registration attempt
|
||||
_logger.LogInfo("Self-registration request received at {Timestamp}.", DateTime.UtcNow);
|
||||
try
|
||||
{
|
||||
// Create db context asynchronously for optimized resource use
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
|
||||
// 2. --- VALIDATION ---
|
||||
// Check if a user with the same email already exists.
|
||||
var existingUser = await _userManager.FindByEmailAsync(model.Email);
|
||||
if (existingUser != null)
|
||||
{
|
||||
_logger.LogWarning("Tenant creation failed for email {Email}: an application user with this email already exists.", model.Email);
|
||||
return StatusCode(409, ApiResponse<object>.ErrorResponse("Tenant cannot be created", "A user with the specified email already exists.", 409));
|
||||
}
|
||||
|
||||
var industry = await context.Industries.FirstOrDefaultAsync(i => i.Id == model.IndustryId);
|
||||
if (industry == null)
|
||||
{
|
||||
_logger.LogWarning("Industry not found while creating the tenant enquire");
|
||||
return NotFound(ApiResponse<object>.ErrorResponse("Industry not found", "Industry not found", 404));
|
||||
}
|
||||
|
||||
// Map DTO to domain model and assign new Guid
|
||||
var tenantEnquire = _mapper.Map<TenantEnquire>(model);
|
||||
tenantEnquire.Id = Guid.NewGuid();
|
||||
|
||||
// Add new tenant enquiry to the database
|
||||
await context.TenantEnquires.AddAsync(tenantEnquire);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Log successful registration
|
||||
_logger.LogInfo("Tenant enquiry created successfully. ID: {TenantEnquireId}", tenantEnquire.Id);
|
||||
|
||||
// Return success response with proper status code and user information
|
||||
return Ok(ApiResponse<object>.SuccessResponse(tenantEnquire, "Tenant enquiry added successfully.", 201));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Log error with detailed exception information at Error level
|
||||
_logger.LogError(ex, "Error occurred during self-registration: {Message}", ex.Message);
|
||||
|
||||
// Return standardized error response to the client
|
||||
var errorResponse = ApiResponse<object>.ErrorResponse("Failed to add tenant enquiry, please try again later.", "Failed to add tenant enquiry, please try again later.", 500);
|
||||
|
||||
return StatusCode(500, errorResponse);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@ -1127,6 +1200,9 @@ namespace Marco.Pms.Services.Controllers
|
||||
_logger.LogInfo("Removed {Count} role permission mappings for role {RoleId}", deleteMappings.Count, roleId);
|
||||
}
|
||||
|
||||
var _cache = scope.ServiceProvider.GetRequiredService<CacheUpdateHelper>();
|
||||
await _cache.ClearAllEmployeesFromCacheByTenantId(tenant.Id);
|
||||
|
||||
var _masteData = scope.ServiceProvider.GetRequiredService<MasterDataService>();
|
||||
|
||||
if (features.Modules?.ProjectManagement?.Enabled ?? false)
|
||||
@ -1301,7 +1377,7 @@ namespace Marco.Pms.Services.Controllers
|
||||
PlanId = model.PlanId,
|
||||
StatusId = activePlanStatus,
|
||||
CreatedAt = utcNow,
|
||||
MaxUsers = model.MaxUsers ?? (currentSubscription?.MaxUsers ?? subscriptionPlan.MaxUser),
|
||||
MaxUsers = subscriptionPlan.MaxUser,
|
||||
CreatedById = loggedInEmployee.Id,
|
||||
CurrencyId = model.CurrencyId,
|
||||
StartDate = utcNow,
|
||||
@ -1439,6 +1515,9 @@ namespace Marco.Pms.Services.Controllers
|
||||
_logger.LogInfo("Permissions revoked: {Count} for Role={RoleId}", mappingsToRemove.Count, rootRoleId);
|
||||
}
|
||||
|
||||
var _cache = scope.ServiceProvider.GetRequiredService<CacheUpdateHelper>();
|
||||
await _cache.ClearAllEmployeesFromCacheByTenantId(tenant.Id);
|
||||
|
||||
var _masteData = scope.ServiceProvider.GetRequiredService<MasterDataService>();
|
||||
|
||||
if (features.Modules?.ProjectManagement?.Enabled ?? false)
|
||||
@ -1523,6 +1602,43 @@ namespace Marco.Pms.Services.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
[HttpPost("self/subscription")]
|
||||
public async Task<IActionResult> SelfSubscriptionAsync(SelfSubscriptionDto model)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _tenantService = scope.ServiceProvider.GetRequiredService<ITenantService>();
|
||||
var response = await _tenantService.CreateTenantAsync(model.TenantEnquireId, model.PaymentDetailId, model.PlanId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error occured while add self subscription");
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("Error Occured while self subscription", "Error Occured while self subscription", 500));
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("renew/subscription")]
|
||||
public async Task<IActionResult> RenewSubscriptionAsync(RenewSubscriptionDto model)
|
||||
{
|
||||
try
|
||||
{
|
||||
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
|
||||
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _tenantService = scope.ServiceProvider.GetRequiredService<ITenantService>();
|
||||
var response = await _tenantService.RenewSubscriptionAsync(tenantId, loggedInEmployee.Id, model.PaymentDetailId, model.PlanId);
|
||||
return StatusCode(response.StatusCode, response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error occured while add renewing subscription");
|
||||
return StatusCode(500, ApiResponse<object>.ErrorResponse("Error Occured while renewing subscription", "Error Occured while renewing subscription", 500));
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region =================================================================== Subscription Plan APIs ===================================================================
|
||||
|
||||
@ -956,6 +956,18 @@ namespace Marco.Pms.Services.Helpers
|
||||
_logger.LogError(ex, "Error occured while deleting all employees from Cache");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ClearAllEmployeesFromCacheByTenantId(Guid tenantId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _employeeCache.ClearAllEmployeesFromCacheByTenantId(tenantId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error occured while deleting all employees from Cache");
|
||||
}
|
||||
}
|
||||
public async Task ClearAllEmployees()
|
||||
{
|
||||
try
|
||||
|
||||
@ -24,7 +24,7 @@ namespace MarcoBMS.Services.Helpers
|
||||
public async Task<Employee> GetEmployeeByID(Guid EmployeeID)
|
||||
{
|
||||
|
||||
return await _context.Employees.Include(e => e.JobRole).FirstOrDefaultAsync(e => e.Id == EmployeeID) ?? new Employee { };
|
||||
return await _context.Employees.Include(e => e.JobRole).Include(e => e.Organization).FirstOrDefaultAsync(e => e.Id == EmployeeID) ?? new Employee { };
|
||||
}
|
||||
|
||||
public async Task<Employee> GetEmployeeByApplicationUserID(string ApplicationUserID)
|
||||
|
||||
@ -253,17 +253,29 @@ namespace Marco.Pms.Services.Helpers
|
||||
!ts.IsCancelled &&
|
||||
ts.EndDate.Date >= DateTime.UtcNow.Date); // FIX: Subscription should not be expired
|
||||
|
||||
//var featureIds = new List<Guid>
|
||||
//{
|
||||
// new Guid("a4e25142-449b-4334-a6e5-22f70e4732d7"), // Expense Management feature
|
||||
// new Guid("81ab8a87-8ccd-4015-a917-0627cee6a100"), // Employee Management feature
|
||||
// new Guid("52c9cf54-1eb2-44d2-81bb-524cf29c0a94"), // Attendance Management feature
|
||||
// new Guid("a8cf4331-8f04-4961-8360-a3f7c3cc7462"), // Document Management feature
|
||||
// new Guid("be3b3afc-6ccf-4566-b9b6-aafcb65546be"), // Masters Management feature
|
||||
// new Guid("39e66f81-efc6-446c-95bd-46bff6cfb606"), // Directory Management feature
|
||||
// new Guid("6d4c82d6-dbce-48ab-b8b8-f785f4d8c914") // Organization Management feature
|
||||
// //new Guid("2f3509b7-160d-410a-b9b6-daadd96c986d") // Tenant Management feature
|
||||
//};
|
||||
|
||||
var featureIds = new List<Guid> { new Guid("be3b3afc-6ccf-4566-b9b6-aafcb65546be") };
|
||||
|
||||
if (tenantSubscription == null)
|
||||
{
|
||||
_logger.LogWarning("No active subscription found for tenant: {TenantId}", tenantId);
|
||||
return new List<Guid>();
|
||||
return featureIds;
|
||||
}
|
||||
|
||||
_logger.LogDebug("Active subscription found for tenant: {TenantId}, PlanId: {PlanId}",
|
||||
tenantId, tenantSubscription.Plan!.Id);
|
||||
|
||||
var featureIds = new List<Guid> { new Guid("2f3509b7-160d-410a-b9b6-daadd96c986d"), new Guid("be3b3afc-6ccf-4566-b9b6-aafcb65546be") };
|
||||
|
||||
// Step 2: Get feature details from Plan
|
||||
var featureDetails = await _featureDetailsHelper.GetFeatureDetails(tenantSubscription.Plan!.FeaturesId);
|
||||
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
using MarcoBMS.Services.Service;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
|
||||
namespace Marco.Pms.Services.Hubs
|
||||
{
|
||||
[Authorize]
|
||||
//[Authorize]
|
||||
public class MarcoHub : Hub
|
||||
{
|
||||
private readonly ILoggingService _logger;
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
using AutoMapper;
|
||||
using Marco.Pms.Model.AppMenu;
|
||||
using Marco.Pms.Model.Collection;
|
||||
using Marco.Pms.Model.Directory;
|
||||
using Marco.Pms.Model.DocumentManager;
|
||||
using Marco.Pms.Model.Dtos.Activities;
|
||||
using Marco.Pms.Model.Dtos.AppMenu;
|
||||
using Marco.Pms.Model.Dtos.Collection;
|
||||
using Marco.Pms.Model.Dtos.Directory;
|
||||
using Marco.Pms.Model.Dtos.DocumentManager;
|
||||
using Marco.Pms.Model.Dtos.Employees;
|
||||
@ -26,6 +28,7 @@ using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.TenantModels;
|
||||
using Marco.Pms.Model.TenantModels.MongoDBModel;
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.Collection;
|
||||
using Marco.Pms.Model.ViewModels.Directory;
|
||||
using Marco.Pms.Model.ViewModels.DocumentManager;
|
||||
using Marco.Pms.Model.ViewModels.Employee;
|
||||
@ -58,6 +61,7 @@ namespace Marco.Pms.Services.MappingProfiles
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Tenant =======================================================
|
||||
CreateMap<TenantEnquireDto, TenantEnquire>();
|
||||
CreateMap<Tenant, TenantVM>();
|
||||
CreateMap<Tenant, TenantListVM>();
|
||||
CreateMap<Tenant, TenantDetailsVM>();
|
||||
@ -248,6 +252,7 @@ namespace Marco.Pms.Services.MappingProfiles
|
||||
dest => dest.Id,
|
||||
opt => opt.MapFrom(src => Guid.Parse(src.Id)));
|
||||
|
||||
CreateMap<Expenses, ExpenseDetailsVM>();
|
||||
CreateMap<ExpenseDetailsMongoDB, ExpenseDetailsVM>()
|
||||
.ForMember(
|
||||
dest => dest.Id,
|
||||
@ -255,6 +260,19 @@ namespace Marco.Pms.Services.MappingProfiles
|
||||
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Collection =======================================================
|
||||
CreateMap<InvoiceDto, Invoice>();
|
||||
CreateMap<Invoice, InvoiceListVM>();
|
||||
CreateMap<Invoice, InvoiceDetailsVM>();
|
||||
|
||||
CreateMap<ReceivedInvoicePaymentDto, ReceivedInvoicePayment>();
|
||||
CreateMap<ReceivedInvoicePayment, ReceivedInvoicePaymentVM>();
|
||||
|
||||
CreateMap<InvoiceComment, InvoiceCommentVM>();
|
||||
|
||||
CreateMap<InvoiceAttachment, InvoiceAttachmentVM>();
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Master =======================================================
|
||||
|
||||
CreateMap<FeaturePermission, FeaturePermissionVM>();
|
||||
@ -379,6 +397,35 @@ namespace Marco.Pms.Services.MappingProfiles
|
||||
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Contact Category Master =======================================================
|
||||
CreateMap<CreateContactCategoryDto, ContactCategoryMaster>();
|
||||
CreateMap<UpdateContactCategoryDto, ContactCategoryMaster>();
|
||||
CreateMap<ContactCategoryMaster, ContactCategoryVM>();
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Contact Tag Master =======================================================
|
||||
CreateMap<CreateContactTagDto, ContactTagMaster>();
|
||||
CreateMap<UpdateContactTagDto, ContactTagMaster>();
|
||||
CreateMap<ContactTagMaster, ContactTagVM>();
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Payment Adjustment Head Master =======================================================
|
||||
CreateMap<PaymentAdjustmentHeadDto, PaymentAdjustmentHead>();
|
||||
CreateMap<PaymentAdjustmentHead, PaymentAdjustmentHeadVM>();
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Expenses Status Master =======================================================
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Expenses Status Master =======================================================
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Expenses Status Master =======================================================
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Expenses Status Master =======================================================
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region ======================================================= Document =======================================================
|
||||
|
||||
@ -34,6 +34,7 @@
|
||||
<PackageReference Include="Mime-Detective" Version="24.12.2" />
|
||||
<PackageReference Include="Mime-Detective.Definitions.Exhaustive" Version="24.12.2" />
|
||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
|
||||
<PackageReference Include="Razorpay" Version="3.3.2" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
using Marco.Pms.CacheHelper;
|
||||
using FirebaseAdmin;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Marco.Pms.CacheHelper;
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using Marco.Pms.Helpers;
|
||||
using Marco.Pms.Helpers.CacheHelper;
|
||||
@ -55,7 +55,7 @@ builder.Services.AddCors(options =>
|
||||
policy.AllowAnyOrigin()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders("Authorization");
|
||||
.WithExposedHeaders("Authorization", "X-Request-ID", "X-Correlation-ID");
|
||||
});
|
||||
|
||||
// A stricter policy for production (loaded from config)
|
||||
@ -65,7 +65,8 @@ builder.Services.AddCors(options =>
|
||||
{
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader();
|
||||
.AllowAnyHeader()
|
||||
.WithExposedHeaders("Authorization", "X-Request-ID", "X-Correlation-ID");
|
||||
});
|
||||
});
|
||||
#endregion
|
||||
@ -182,6 +183,9 @@ builder.Services.AddScoped<IExpensesService, ExpensesService>();
|
||||
builder.Services.AddScoped<IMasterService, MasterService>();
|
||||
builder.Services.AddScoped<IDirectoryService, DirectoryService>();
|
||||
builder.Services.AddScoped<IFirebaseService, FirebaseService>();
|
||||
builder.Services.AddScoped<IRazorpayService, RazorpayService>();
|
||||
builder.Services.AddScoped<IAesEncryption, AesEncryption>();
|
||||
builder.Services.AddScoped<ITenantService, TenantService>();
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
36
Marco.Pms.Services/Service/AesEncryption.cs
Normal file
36
Marco.Pms.Services/Service/AesEncryption.cs
Normal file
@ -0,0 +1,36 @@
|
||||
using Marco.Pms.Services.Service.ServiceInterfaces;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Marco.Pms.Services.Service
|
||||
{
|
||||
public class AesEncryption : IAesEncryption
|
||||
{
|
||||
public (byte[] ciphertext, byte[] nonce, byte[] tag) Encrypt(string plaintext, byte[] key)
|
||||
{
|
||||
byte[] autoKey = new byte[32]; // 32 bytes = 256 bits
|
||||
RandomNumberGenerator.Fill(autoKey);
|
||||
var stringKey = Convert.ToBase64String(autoKey);
|
||||
|
||||
byte[] nonce = RandomNumberGenerator.GetBytes(12);
|
||||
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
byte[] ciphertext = new byte[plaintextBytes.Length];
|
||||
byte[] tag = new byte[16];
|
||||
|
||||
using var aes = new AesGcm(key, 16);
|
||||
aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
|
||||
|
||||
return (ciphertext, nonce, tag);
|
||||
}
|
||||
|
||||
public string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key)
|
||||
{
|
||||
byte[] plaintext = new byte[ciphertext.Length];
|
||||
|
||||
using var aes = new AesGcm(key, 16);
|
||||
aes.Decrypt(nonce, ciphertext, tag, plaintext);
|
||||
|
||||
return Encoding.UTF8.GetString(plaintext);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1533,9 +1533,11 @@ namespace Marco.Pms.Services.Service
|
||||
return ApiResponse<object>.ErrorResponse("Contact ID is empty", "Contact ID is empty", 400);
|
||||
}
|
||||
|
||||
var (hasAdminPermission, hasManagerPermission, hasUserPermission) = await CheckPermissionsAsync(loggedInEmployee.Id);
|
||||
|
||||
var bucketIds = await _context.ContactBucketMappings.Where(cb => cb.ContactId == id).Select(cb => cb.BucketId).ToListAsync();
|
||||
var hasContactAccess = await _context.EmployeeBucketMappings.AnyAsync(eb => bucketIds.Contains(eb.BucketId) && eb.EmployeeId == loggedInEmployee.Id);
|
||||
if (hasContactAccess)
|
||||
if (!hasAdminPermission && !hasContactAccess)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} does not have permission to delete contact {ContactId}",
|
||||
loggedInEmployee.Id, id);
|
||||
@ -2131,7 +2133,7 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
var bucketIds = await _context.ContactBucketMappings.Where(cb => cb.ContactId == noteDto.ContactId).Select(cb => cb.BucketId).ToListAsync();
|
||||
var hasContactAccess = await _context.EmployeeBucketMappings.AnyAsync(eb => bucketIds.Contains(eb.BucketId) && eb.EmployeeId == loggedInEmployee.Id);
|
||||
if (!hasAdminPermission && hasContactAccess)
|
||||
if (!hasAdminPermission && !hasContactAccess)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} does not have permission to delete contact {ContactId}",
|
||||
loggedInEmployee.Id, noteDto.ContactId);
|
||||
@ -2270,10 +2272,11 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
return ApiResponse<object>.ErrorResponse("Note not found", "Note not found", 404);
|
||||
}
|
||||
var (hasAdminPermission, hasManagerPermission, hasUserPermission) = await CheckPermissionsAsync(loggedInEmployee.Id);
|
||||
|
||||
var bucketIds = await _context.ContactBucketMappings.Where(cb => cb.ContactId == note.ContactId).Select(cb => cb.BucketId).ToListAsync();
|
||||
var hasContactAccess = await _context.EmployeeBucketMappings.AnyAsync(eb => bucketIds.Contains(eb.BucketId) && eb.EmployeeId == loggedInEmployee.Id);
|
||||
if (hasContactAccess)
|
||||
if (!hasAdminPermission && !hasContactAccess)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} does not have permission to delete contact {ContactId}",
|
||||
loggedInEmployee.Id, note.ContactId);
|
||||
|
||||
@ -23,6 +23,7 @@ using MarcoBMS.Services.Service;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Document = Marco.Pms.Model.DocumentManager.Document;
|
||||
|
||||
namespace Marco.Pms.Services.Service
|
||||
@ -129,6 +130,16 @@ namespace Marco.Pms.Services.Service
|
||||
// 3. --- Build Base Query and Apply Permissions ---
|
||||
// Start with a base IQueryable. Filters will be chained onto this.
|
||||
var expensesQuery = _context.Expenses
|
||||
.Include(e => e.PaidBy)
|
||||
.Include(e => e.CreatedBy)
|
||||
.Include(e => e.ProcessedBy)
|
||||
.Include(e => e.ApprovedBy)
|
||||
.Include(e => e.ReviewedBy)
|
||||
.Include(e => e.PaymentMode)
|
||||
.Include(e => e.Project)
|
||||
.Include(e => e.PaymentMode)
|
||||
.Include(e => e.ExpensesType)
|
||||
.Include(e => e.Status)
|
||||
.Where(e => e.TenantId == tenantId); // Always filter by TenantId first.
|
||||
|
||||
if (cacheList == null)
|
||||
@ -176,6 +187,10 @@ namespace Marco.Pms.Services.Service
|
||||
{
|
||||
expensesQuery = expensesQuery.Where(e => expenseFilter.PaidById.Contains(e.PaidById));
|
||||
}
|
||||
if (expenseFilter.ExpenseTypeIds?.Any() == true)
|
||||
{
|
||||
expensesQuery = expensesQuery.Where(e => expenseFilter.ExpenseTypeIds.Contains(e.ExpensesTypeId));
|
||||
}
|
||||
|
||||
// Only allow filtering by 'CreatedBy' if the user has 'View All' permission.
|
||||
if (expenseFilter.CreatedByIds?.Any() == true && hasViewAllPermissionTask.Result)
|
||||
@ -213,7 +228,8 @@ namespace Marco.Pms.Services.Service
|
||||
return ApiResponse<object>.SuccessResponse(new List<ExpenseList>(), "No expenses found for the given criteria.", 200);
|
||||
}
|
||||
|
||||
expenseVM = await GetAllExpnesRelatedTables(expensesList, tenantId);
|
||||
//expenseVM = await GetAllExpnesRelatedTables(expensesList, tenantId);
|
||||
expenseVM = _mapper.Map<List<ExpenseList>>(expensesList);
|
||||
totalPages = (int)Math.Ceiling((double)totalEntites / pageSize);
|
||||
|
||||
}
|
||||
@ -276,7 +292,18 @@ namespace Marco.Pms.Services.Service
|
||||
ExpenseDetailsMongoDB? expenseDetails = null;
|
||||
if (expenseDetails == null)
|
||||
{
|
||||
var expense = await _context.Expenses.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id && e.TenantId == tenantId);
|
||||
var expense = await _context.Expenses
|
||||
.Include(e => e.PaidBy)
|
||||
.Include(e => e.CreatedBy)
|
||||
.Include(e => e.ProcessedBy)
|
||||
.Include(e => e.ApprovedBy)
|
||||
.Include(e => e.ReviewedBy)
|
||||
.Include(e => e.PaymentMode)
|
||||
.Include(e => e.Project)
|
||||
.Include(e => e.PaymentMode)
|
||||
.Include(e => e.ExpensesType)
|
||||
.Include(e => e.Status)
|
||||
.AsNoTracking().FirstOrDefaultAsync(e => e.Id == id && e.TenantId == tenantId);
|
||||
|
||||
if (expense == null)
|
||||
{
|
||||
@ -318,6 +345,13 @@ namespace Marco.Pms.Services.Service
|
||||
{
|
||||
status.PermissionIds = permissionStatusMappings.Where(ps => ps.StatusId == status.Id).Select(ps => ps.PermissionIds).FirstOrDefault();
|
||||
}
|
||||
int index = vm.NextStatus.FindIndex(ns => ns.DisplayName == "Reject");
|
||||
if (index > -1)
|
||||
{
|
||||
var item = vm.NextStatus[index];
|
||||
vm.NextStatus.RemoveAt(index);
|
||||
vm.NextStatus.Insert(0, item);
|
||||
}
|
||||
}
|
||||
vm.ExpensesReimburse = _mapper.Map<ExpensesReimburseVM>(expensesReimburse);
|
||||
|
||||
@ -361,66 +395,25 @@ namespace Marco.Pms.Services.Service
|
||||
{
|
||||
try
|
||||
{
|
||||
// Task 1: Get all distinct projects associated with the tenant's expenses.
|
||||
var projectsTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Expenses
|
||||
.Where(e => e.TenantId == tenantId && e.Project != null)
|
||||
.Select(e => e.Project!)
|
||||
.Distinct()
|
||||
.Select(p => new { p.Id, Name = $"{p.Name}" })
|
||||
var expenses = await _context.Expenses
|
||||
.Include(e => e.PaidBy)
|
||||
.Include(e => e.Project)
|
||||
.Include(e => e.CreatedBy)
|
||||
.Include(e => e.Status)
|
||||
.Include(e => e.ExpensesType)
|
||||
.Where(e => e.TenantId == tenantId)
|
||||
.ToListAsync();
|
||||
});
|
||||
|
||||
// Task 2: Get all distinct users who paid for the tenant's expenses.
|
||||
var paidByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Expenses
|
||||
.Where(e => e.TenantId == tenantId && e.PaidBy != null)
|
||||
.Select(e => e.PaidBy!)
|
||||
.Distinct()
|
||||
.Select(u => new { u.Id, Name = $"{u.FirstName} {u.LastName}" })
|
||||
.ToListAsync();
|
||||
});
|
||||
|
||||
// Task 3: Get all distinct users who created the tenant's expenses.
|
||||
var createdByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Expenses
|
||||
.Where(e => e.TenantId == tenantId && e.CreatedBy != null)
|
||||
.Select(e => e.CreatedBy!)
|
||||
.Distinct()
|
||||
.Select(u => new { u.Id, Name = $"{u.FirstName} {u.LastName}" })
|
||||
.ToListAsync();
|
||||
});
|
||||
|
||||
// Task 4: Get all distinct statuses associated with the tenant's expenses.
|
||||
var statusTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Expenses
|
||||
.Where(e => e.TenantId == tenantId && e.Status != null)
|
||||
.Select(e => e.Status!)
|
||||
.Distinct()
|
||||
.Select(s => new { s.Id, s.Name })
|
||||
.ToListAsync();
|
||||
});
|
||||
|
||||
// Execute all four queries concurrently. The total wait time will be determined
|
||||
// by the longest-running query, not the sum of all four.
|
||||
await Task.WhenAll(projectsTask, paidByTask, createdByTask, statusTask);
|
||||
|
||||
// Construct the final object from the results of the completed tasks.
|
||||
return ApiResponse<object>.SuccessResponse(new
|
||||
var response = new
|
||||
{
|
||||
Projects = await projectsTask,
|
||||
PaidBy = await paidByTask,
|
||||
CreatedBy = await createdByTask,
|
||||
Status = await statusTask
|
||||
}, "Successfully fetched the filter list", 200);
|
||||
Projects = expenses.Where(e => e.Project != null).Select(e => new { Id = e.Project!.Id, Name = e.Project.Name }).Distinct().ToList(),
|
||||
PaidBy = expenses.Where(e => e.PaidBy != null).Select(e => new { Id = e.PaidBy!.Id, Name = $"{e.PaidBy.FirstName} {e.PaidBy.LastName}" }).Distinct().ToList(),
|
||||
CreatedBy = expenses.Where(e => e.CreatedBy != null).Select(e => new { Id = e.CreatedBy!.Id, Name = $"{e.CreatedBy.FirstName} {e.CreatedBy.LastName}" }).Distinct().ToList(),
|
||||
Status = expenses.Where(e => e.Status != null).Select(e => new { Id = e.Status!.Id, Name = e.Status.Name }).Distinct().ToList(),
|
||||
ExpensesType = expenses.Where(e => e.ExpensesType != null).Select(e => new { Id = e.ExpensesType!.Id, Name = e.ExpensesType.Name }).Distinct().ToList()
|
||||
};
|
||||
return ApiResponse<object>.SuccessResponse(response, "Successfully fetched the filter list", 200);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -458,13 +451,6 @@ namespace Marco.Pms.Services.Service
|
||||
return await permissionService.HasPermission(PermissionsMaster.ExpenseUpload, loggedInEmployee.Id);
|
||||
});
|
||||
|
||||
var hasProjectPermissionTask = Task.Run(async () =>
|
||||
{
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var permissionService = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
return await permissionService.HasProjectPermission(loggedInEmployee, dto.ProjectId);
|
||||
});
|
||||
|
||||
// VALIDATION CHECKS: Use IDbContextFactory for thread-safe, parallel database queries.
|
||||
// Each task gets its own DbContext instance.
|
||||
var projectTask = Task.Run(async () =>
|
||||
@ -487,6 +473,15 @@ namespace Marco.Pms.Services.Service
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.PaymentModeMatser.AsNoTracking().FirstOrDefaultAsync(pm => pm.Id == dto.PaymentModeId);
|
||||
});
|
||||
var expenseUIdTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
var result = await dbContext.Expenses
|
||||
.Where(e => !string.IsNullOrWhiteSpace(e.ExpenseUId)).ToListAsync();
|
||||
return result
|
||||
.Select(e => ExtractNumber(e.ExpenseUId))
|
||||
.OrderByDescending(id => id).FirstOrDefault();
|
||||
});
|
||||
var statusMappingTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
@ -506,13 +501,10 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
|
||||
// Await all prerequisite checks at once.
|
||||
await Task.WhenAll(
|
||||
hasUploadPermissionTask, hasProjectPermissionTask,
|
||||
projectTask, expenseTypeTask, paymentModeTask, statusMappingTask, paidByTask
|
||||
);
|
||||
await Task.WhenAll(hasUploadPermissionTask, projectTask, expenseTypeTask, paymentModeTask, statusMappingTask, paidByTask, expenseUIdTask);
|
||||
|
||||
// 2. Aggregate and Check Results
|
||||
if (!await hasUploadPermissionTask || !await hasProjectPermissionTask)
|
||||
if (!await hasUploadPermissionTask)
|
||||
{
|
||||
_logger.LogWarning("Access DENIED for employee {EmployeeId} on project {ProjectId}.", loggedInEmployee.Id, dto.ProjectId);
|
||||
return ApiResponse<object>.ErrorResponse("Access Denied.", "You do not have permission to upload expenses for this project.", 403);
|
||||
@ -524,6 +516,7 @@ namespace Marco.Pms.Services.Service
|
||||
var paymentMode = await paymentModeTask;
|
||||
var statusMapping = await statusMappingTask;
|
||||
var paidBy = await paidByTask;
|
||||
var lastExpenseUId = expenseUIdTask.Result;
|
||||
|
||||
if (project == null) validationErrors.Add("Project not found.");
|
||||
if (paidBy == null) validationErrors.Add("Paid by employee not found");
|
||||
@ -540,8 +533,11 @@ namespace Marco.Pms.Services.Service
|
||||
return ApiResponse<object>.ErrorResponse("Invalid input data.", errorMessage, 400);
|
||||
}
|
||||
|
||||
var currentexpenseUId = (lastExpenseUId + 1).ToString("D5");
|
||||
|
||||
// 3. Entity Creation
|
||||
var expense = _mapper.Map<Expenses>(dto);
|
||||
expense.ExpenseUId = $"EX-{currentexpenseUId}";
|
||||
expense.CreatedById = loggedInEmployee.Id;
|
||||
expense.CreatedAt = DateTime.UtcNow;
|
||||
expense.TenantId = tenantId;
|
||||
@ -1084,6 +1080,14 @@ namespace Marco.Pms.Services.Service
|
||||
#endregion
|
||||
|
||||
#region =================================================================== Helper Functions ===================================================================
|
||||
|
||||
private int ExtractNumber(string id)
|
||||
{
|
||||
// Extract trailing number; handles EX_0001, EX-0001, EX0001
|
||||
var m = Regex.Match(id ?? string.Empty, @"(\d+)$");
|
||||
return m.Success ? int.Parse(m.Value) : int.MinValue; // put invalid IDs at the bottom
|
||||
}
|
||||
|
||||
private static object ExceptionMapper(Exception ex)
|
||||
{
|
||||
return new
|
||||
@ -1217,46 +1221,6 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
private async Task<ExpenseDetailsMongoDB> GetAllExpnesRelatedTablesForSingle(Expenses model, Guid tenantId)
|
||||
{
|
||||
var projectTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Projects.AsNoTracking().FirstOrDefaultAsync(p => p.Id == model.ProjectId && p.TenantId == tenantId);
|
||||
});
|
||||
var paidByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Employees.Include(e => e.JobRole).AsNoTracking().FirstOrDefaultAsync(e => e.Id == model.PaidById && e.TenantId == tenantId);
|
||||
});
|
||||
var createdByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Employees.Include(e => e.JobRole).AsNoTracking().FirstOrDefaultAsync(e => e.Id == model.CreatedById && e.TenantId == tenantId);
|
||||
});
|
||||
var reviewedByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Employees.Include(e => e.JobRole).AsNoTracking().FirstOrDefaultAsync(e => e.Id == model.ReviewedById && e.TenantId == tenantId);
|
||||
});
|
||||
var approvedByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Employees.Include(e => e.JobRole).AsNoTracking().FirstOrDefaultAsync(e => e.Id == model.ApprovedById && e.TenantId == tenantId);
|
||||
});
|
||||
var processedByTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.Employees.Include(e => e.JobRole).AsNoTracking().FirstOrDefaultAsync(e => e.Id == model.ProcessedById && e.TenantId == tenantId);
|
||||
});
|
||||
var expenseTypeTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.ExpensesTypeMaster.AsNoTracking().FirstOrDefaultAsync(et => et.Id == model.ExpensesTypeId && et.TenantId == tenantId);
|
||||
});
|
||||
var paymentModeTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await dbContext.PaymentModeMatser.AsNoTracking().FirstOrDefaultAsync(pm => pm.Id == model.PaymentModeId && pm.TenantId == tenantId);
|
||||
});
|
||||
var statusMappingTask = Task.Run(async () =>
|
||||
{
|
||||
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
@ -1304,29 +1268,20 @@ namespace Marco.Pms.Services.Service
|
||||
});
|
||||
|
||||
// Await all prerequisite checks at once.
|
||||
await Task.WhenAll(projectTask, expenseTypeTask, paymentModeTask, statusMappingTask, paidByTask, createdByTask, reviewedByTask, approvedByTask,
|
||||
processedByTask, statusTask, billAttachmentsTask);
|
||||
await Task.WhenAll(statusTask, billAttachmentsTask);
|
||||
|
||||
var project = projectTask.Result;
|
||||
var expenseType = expenseTypeTask.Result;
|
||||
var paymentMode = paymentModeTask.Result;
|
||||
var statusMapping = statusMappingTask.Result;
|
||||
var paidBy = paidByTask.Result;
|
||||
var createdBy = createdByTask.Result;
|
||||
var reviewedBy = reviewedByTask.Result;
|
||||
var approvedBy = approvedByTask.Result;
|
||||
var processedBy = processedByTask.Result;
|
||||
var billAttachment = billAttachmentsTask.Result;
|
||||
|
||||
|
||||
var response = _mapper.Map<ExpenseDetailsMongoDB>(model);
|
||||
|
||||
response.Project = _mapper.Map<ProjectBasicMongoDB>(project);
|
||||
response.PaidBy = _mapper.Map<BasicEmployeeMongoDB>(paidBy);
|
||||
response.CreatedBy = _mapper.Map<BasicEmployeeMongoDB>(createdBy);
|
||||
response.ReviewedBy = _mapper.Map<BasicEmployeeMongoDB>(reviewedBy);
|
||||
response.ApprovedBy = _mapper.Map<BasicEmployeeMongoDB>(approvedBy);
|
||||
response.ProcessedBy = _mapper.Map<BasicEmployeeMongoDB>(processedBy);
|
||||
response.Project = _mapper.Map<ProjectBasicMongoDB>(model.Project);
|
||||
response.PaidBy = _mapper.Map<BasicEmployeeMongoDB>(model.PaidBy);
|
||||
response.CreatedBy = _mapper.Map<BasicEmployeeMongoDB>(model.CreatedBy);
|
||||
response.ReviewedBy = _mapper.Map<BasicEmployeeMongoDB>(model.ReviewedBy);
|
||||
response.ApprovedBy = _mapper.Map<BasicEmployeeMongoDB>(model.ApprovedBy);
|
||||
response.ProcessedBy = _mapper.Map<BasicEmployeeMongoDB>(model.ProcessedBy);
|
||||
if (statusMapping != null)
|
||||
{
|
||||
response.Status = _mapper.Map<ExpensesStatusMasterMongoDB>(statusMapping.Status);
|
||||
@ -1337,8 +1292,8 @@ namespace Marco.Pms.Services.Service
|
||||
var status = statusTask.Result;
|
||||
response.Status = _mapper.Map<ExpensesStatusMasterMongoDB>(status);
|
||||
}
|
||||
response.PaymentMode = _mapper.Map<PaymentModeMatserMongoDB>(paymentMode);
|
||||
response.ExpensesType = _mapper.Map<ExpensesTypeMasterMongoDB>(expenseType);
|
||||
response.PaymentMode = _mapper.Map<PaymentModeMatserMongoDB>(model.PaymentMode);
|
||||
response.ExpensesType = _mapper.Map<ExpensesTypeMasterMongoDB>(model.ExpensesType);
|
||||
if (billAttachment != null) response.Documents = billAttachment.Documents;
|
||||
|
||||
return response;
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
using Marco.Pms.Model.Forum;
|
||||
using Marco.Pms.Model.DocumentManager;
|
||||
using Marco.Pms.Model.Forum;
|
||||
using Marco.Pms.Model.Master;
|
||||
|
||||
namespace Marco.Pms.Services.Service
|
||||
@ -335,6 +336,194 @@ namespace Marco.Pms.Services.Service
|
||||
}
|
||||
};
|
||||
}
|
||||
public List<DocumentCategoryMaster> GetDocumentCategoryData(Guid tenantId)
|
||||
{
|
||||
return new List<DocumentCategoryMaster> {
|
||||
new DocumentCategoryMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Project Documents",
|
||||
Description = "Project documents are formal records that outline the plans, progress, and details necessary to execute and manage a project effectively.",
|
||||
EntityTypeId = Guid.Parse("c8fe7115-aa27-43bc-99f4-7b05fabe436e"),
|
||||
CreatedAt = new DateTime(2025, 9, 15, 12, 42, 3, 202, DateTimeKind.Utc),
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentCategoryMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Employee Documents",
|
||||
Description = "Employment details along with legal IDs like passports or driver’s licenses to verify identity and work authorization.",
|
||||
EntityTypeId = Guid.Parse("dbb9555a-7a0c-40f2-a9ed-f0463f1ceed7"),
|
||||
CreatedAt = new DateTime(2025, 9, 15, 12, 42, 3, 202, DateTimeKind.Utc),
|
||||
TenantId = tenantId
|
||||
}
|
||||
};
|
||||
}
|
||||
public List<DocumentTypeMaster> GetDocumentTypeData(Guid tenantId, Guid employeeDocumentId, Guid projectDocumentId)
|
||||
{
|
||||
return new List<DocumentTypeMaster> {
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Aadhaar card",
|
||||
RegexExpression = "^[2-9][0-9]{11}$",
|
||||
AllowedContentType = "application/pdf,image/jpeg",
|
||||
MaxSizeAllowedInMB = 2,
|
||||
IsValidationRequired = true,
|
||||
IsMandatory = true,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = employeeDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Pan Card",
|
||||
RegexExpression = "^[A-Z]{5}[0-9]{4}[A-Z]{1}$",
|
||||
AllowedContentType = "application/pdf,image/jpeg",
|
||||
MaxSizeAllowedInMB = 2,
|
||||
IsValidationRequired = true,
|
||||
IsMandatory = true,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = employeeDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Voter Card",
|
||||
RegexExpression = "^[A-Z]{3}[0-9]{7}$",
|
||||
AllowedContentType = "application/pdf,image/jpeg",
|
||||
MaxSizeAllowedInMB = 2,
|
||||
IsValidationRequired = true,
|
||||
IsMandatory = true,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = employeeDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Passport",
|
||||
RegexExpression = "^[A-PR-WY][1-9]\\d\\s?\\d{4}[1-9]$",
|
||||
AllowedContentType = "application/pdf,image/jpeg",
|
||||
MaxSizeAllowedInMB = 2,
|
||||
IsValidationRequired = true,
|
||||
IsMandatory = true,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = employeeDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Bank Passbook",
|
||||
RegexExpression = "^\\d{9,18}$",
|
||||
AllowedContentType = "application/pdf,image/jpeg",
|
||||
MaxSizeAllowedInMB = 2,
|
||||
IsValidationRequired = true,
|
||||
IsMandatory = true,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = employeeDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Bill of Quantities (BOQ)",
|
||||
AllowedContentType = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
MaxSizeAllowedInMB = 1,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Work Order",
|
||||
AllowedContentType = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
MaxSizeAllowedInMB = 1,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Letter of Agreement",
|
||||
AllowedContentType = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
MaxSizeAllowedInMB = 1,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Health and Safety Document",
|
||||
AllowedContentType = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
MaxSizeAllowedInMB = 1,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Standard Operating Procedure (SOP)",
|
||||
AllowedContentType = "application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
MaxSizeAllowedInMB = 1,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
},
|
||||
new DocumentTypeMaster
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Drawings",
|
||||
AllowedContentType = "application/pdf,image/vnd.dwg,application/acad",
|
||||
MaxSizeAllowedInMB = 20,
|
||||
IsValidationRequired = false,
|
||||
IsMandatory = false,
|
||||
CreatedAt = new DateTime(2025, 9, 3, 10, 46, 49, 955, DateTimeKind.Utc),
|
||||
IsSystem = true,
|
||||
IsActive = true,
|
||||
DocumentCategoryId = projectDocumentId,
|
||||
TenantId = tenantId
|
||||
}
|
||||
};
|
||||
}
|
||||
public List<object> GetData(Guid tenantId)
|
||||
{
|
||||
return new List<object>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -67,7 +67,7 @@ namespace Marco.Pms.Services.Service
|
||||
_logger.LogInfo("Basic project list requested by EmployeeId {EmployeeId}", loggedInEmployee.Id);
|
||||
|
||||
// Step 2: Get the list of project IDs the user has access to
|
||||
List<Guid> accessibleProjectIds = await GetMyProjects(tenantId, loggedInEmployee);
|
||||
List<Guid> accessibleProjectIds = await _context.Projects.Where(p => p.TenantId == tenantId).Select(p => p.Id).ToListAsync();
|
||||
|
||||
if (accessibleProjectIds == null || !accessibleProjectIds.Any())
|
||||
{
|
||||
@ -96,7 +96,7 @@ namespace Marco.Pms.Services.Service
|
||||
_logger.LogInfo("Starting GetAllProjects for TenantId: {TenantId}, User: {UserId}", tenantId, loggedInEmployee.Id);
|
||||
|
||||
// --- Step 1: Get a list of project IDs the user can access ---
|
||||
List<Guid> projectIds = await GetMyProjects(tenantId, loggedInEmployee);
|
||||
List<Guid> projectIds = await _context.Projects.Where(p => p.TenantId == tenantId).Select(p => p.Id).ToListAsync();
|
||||
if (!projectIds.Any())
|
||||
{
|
||||
_logger.LogInfo("User has no assigned projects. Returning empty list.");
|
||||
@ -201,21 +201,21 @@ namespace Marco.Pms.Services.Service
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var _permission = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
|
||||
// Step 1: Check global view project permission
|
||||
var hasViewProjectPermission = await _permission.HasPermission(PermissionsMaster.ViewProject, loggedInEmployee.Id, id);
|
||||
if (!hasViewProjectPermission)
|
||||
{
|
||||
_logger.LogWarning("ViewProjects permission denied for EmployeeId: {EmployeeId}", loggedInEmployee.Id);
|
||||
return ApiResponse<object>.ErrorResponse("Access denied", "You don't have permission to view projects", 403);
|
||||
}
|
||||
//// Step 1: Check global view project permission
|
||||
//var hasViewProjectPermission = await _permission.HasPermission(PermissionsMaster.ViewProject, loggedInEmployee.Id, id);
|
||||
//if (!hasViewProjectPermission)
|
||||
//{
|
||||
// _logger.LogWarning("ViewProjects permission denied for EmployeeId: {EmployeeId}", loggedInEmployee.Id);
|
||||
// return ApiResponse<object>.ErrorResponse("Access denied", "You don't have permission to view projects", 403);
|
||||
//}
|
||||
|
||||
// Step 2: Check permission for this specific project
|
||||
var hasProjectPermission = await _permission.HasProjectPermission(loggedInEmployee, id);
|
||||
if (!hasProjectPermission)
|
||||
{
|
||||
_logger.LogWarning("Project-specific access denied. EmployeeId: {EmployeeId}, ProjectId: {ProjectId}", loggedInEmployee.Id, id);
|
||||
return ApiResponse<object>.ErrorResponse("Access denied", "You don't have access to this project", 403);
|
||||
}
|
||||
//// Step 2: Check permission for this specific project
|
||||
//var hasProjectPermission = await _permission.HasProjectPermission(loggedInEmployee, id);
|
||||
//if (!hasProjectPermission)
|
||||
//{
|
||||
// _logger.LogWarning("Project-specific access denied. EmployeeId: {EmployeeId}, ProjectId: {ProjectId}", loggedInEmployee.Id, id);
|
||||
// return ApiResponse<object>.ErrorResponse("Access denied", "You don't have access to this project", 403);
|
||||
//}
|
||||
|
||||
// Step 3: Fetch project with status
|
||||
var projectDetails = await _cache.GetProjectDetails(id);
|
||||
@ -368,17 +368,20 @@ namespace Marco.Pms.Services.Service
|
||||
return ApiResponse<object>.ErrorResponse("Access Denied", "You do not have permission to create a project for this tenant.", 403);
|
||||
}
|
||||
|
||||
var promoterId = model.PromoterId ?? loggedInEmployee.OrganizationId;
|
||||
var pmcId = model.PMCId ?? loggedInEmployee.OrganizationId;
|
||||
|
||||
// Step 2: Concurrent validation for Promoter and PMC organization existence.
|
||||
// Run database queries in parallel for better performance.
|
||||
var promoterTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == model.PromoterId);
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == promoterId);
|
||||
});
|
||||
var pmcTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == model.PMCId);
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == pmcId);
|
||||
});
|
||||
|
||||
await Task.WhenAll(promoterTask, pmcTask);
|
||||
@ -388,18 +391,20 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
if (promoter == null)
|
||||
{
|
||||
_logger.LogWarning("Promoter check failed. PromoterId={PromoterId} not found.", model.PromoterId);
|
||||
_logger.LogWarning("Promoter check failed. PromoterId={PromoterId} not found.", promoterId);
|
||||
return ApiResponse<object>.ErrorResponse("Promoter not found", "Promoter not found in database.", 404);
|
||||
}
|
||||
if (pmc == null)
|
||||
{
|
||||
_logger.LogWarning("PMC check failed. PMCId={PMCId} not found.", model.PMCId);
|
||||
_logger.LogWarning("PMC check failed. PMCId={PMCId} not found.", pmcId);
|
||||
return ApiResponse<object>.ErrorResponse("PMC not found", "PMC not found in database.", 404);
|
||||
}
|
||||
|
||||
// Step 3: Prepare the project entity.
|
||||
var loggedInUserId = loggedInEmployee.Id;
|
||||
var project = _mapper.Map<Project>(model);
|
||||
project.PromoterId = promoterId;
|
||||
project.PMCId = pmcId;
|
||||
project.TenantId = tenantId;
|
||||
|
||||
// Step 4: Save the new project to the database.
|
||||
@ -476,6 +481,7 @@ namespace Marco.Pms.Services.Service
|
||||
// --- Step 1: Fetch the Existing Entity from the Database ---
|
||||
// This is crucial to avoid the data loss bug. We only want to modify an existing record.
|
||||
var existingProject = await _context.Projects
|
||||
.AsNoTracking()
|
||||
.Where(p => p.Id == id && p.TenantId == tenantId)
|
||||
.SingleOrDefaultAsync();
|
||||
|
||||
@ -496,17 +502,20 @@ namespace Marco.Pms.Services.Service
|
||||
return ApiResponse<object>.ErrorResponse("Access Denied", "You do not have permission to update a project for this tenant.", 403);
|
||||
}
|
||||
|
||||
var promoterId = model.PromoterId ?? loggedInEmployee.OrganizationId;
|
||||
var pmcId = model.PMCId ?? loggedInEmployee.OrganizationId;
|
||||
|
||||
// 1bb. Concurrent validation for Promoter and PMC organization existence.
|
||||
// Run database queries in parallel for better performance.
|
||||
var promoterTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == model.PromoterId);
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == promoterId);
|
||||
});
|
||||
var pmcTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == model.PMCId);
|
||||
return await context.Organizations.FirstOrDefaultAsync(o => o.Id == pmcId);
|
||||
});
|
||||
|
||||
await Task.WhenAll(promoterTask, pmcTask);
|
||||
@ -516,12 +525,12 @@ namespace Marco.Pms.Services.Service
|
||||
|
||||
if (promoter == null)
|
||||
{
|
||||
_logger.LogWarning("Promoter check failed. PromoterId={PromoterId} not found.", model.PromoterId);
|
||||
_logger.LogWarning("Promoter check failed. PromoterId={PromoterId} not found.", promoterId);
|
||||
return ApiResponse<object>.ErrorResponse("Promoter not found", "Promoter not found in database.", 404);
|
||||
}
|
||||
if (pmc == null)
|
||||
{
|
||||
_logger.LogWarning("PMC check failed. PMCId={PMCId} not found.", model.PMCId);
|
||||
_logger.LogWarning("PMC check failed. PMCId={PMCId} not found.", pmcId);
|
||||
return ApiResponse<object>.ErrorResponse("PMC not found", "PMC not found in database.", 404);
|
||||
}
|
||||
|
||||
@ -538,8 +547,11 @@ namespace Marco.Pms.Services.Service
|
||||
// This only modifies the properties defined in the mapping, preventing data loss.
|
||||
_mapper.Map(model, existingProject);
|
||||
|
||||
existingProject.PromoterId = promoterId;
|
||||
existingProject.PMCId = pmcId;
|
||||
|
||||
// Mark the entity as modified (if your mapping doesn't do it automatically).
|
||||
_context.Entry(existingProject).State = EntityState.Modified;
|
||||
_context.Projects.Update(existingProject);
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
418
Marco.Pms.Services/Service/RazorpayService.cs
Normal file
418
Marco.Pms.Services/Service/RazorpayService.cs
Normal file
@ -0,0 +1,418 @@
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.PaymentGetway;
|
||||
using Marco.Pms.Model.ViewModels.PaymentGetway;
|
||||
using Marco.Pms.Services.Service.ServiceInterfaces;
|
||||
using MarcoBMS.Services.Service;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Newtonsoft.Json;
|
||||
using Razorpay.Api;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Marco.Pms.Services.Service
|
||||
{
|
||||
public class RazorpayService : IRazorpayService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly RazorpayClient _razorpayClient;
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IAesEncryption _aesEncryption;
|
||||
private readonly string key;
|
||||
private readonly string secret;
|
||||
private readonly byte[] encryptionKey;
|
||||
|
||||
public RazorpayService(ApplicationDbContext context, IConfiguration configuration, ILoggingService logger, IAesEncryption aesEncryption)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
_configuration = configuration;
|
||||
_aesEncryption = aesEncryption;
|
||||
|
||||
key = configuration["Razorpay:Key"] ?? "";
|
||||
secret = configuration["Razorpay:Secret"] ?? "";
|
||||
_razorpayClient = new RazorpayClient(key, secret);
|
||||
|
||||
string stringKey = configuration["Encryption:PaymentKey"] ?? "";
|
||||
encryptionKey = Convert.FromBase64String(stringKey);
|
||||
}
|
||||
|
||||
public CreateOrderVM CreateOrder(double amount, Employee loggedInEmployee, Guid tenantId)
|
||||
{
|
||||
RazorpayClient client = new RazorpayClient(key, secret);
|
||||
|
||||
var receipt = $"rec_{Guid.NewGuid()}";
|
||||
var length = receipt.Length;
|
||||
|
||||
Dictionary<string, object> options = new Dictionary<string, object>
|
||||
{
|
||||
{ "amount", amount * 100 }, // amount in paise
|
||||
{ "currency", "INR" },
|
||||
{ "receipt", receipt},
|
||||
{ "payment_capture", 1 }
|
||||
};
|
||||
|
||||
Order order = client.Order.Create(options);
|
||||
var response = new CreateOrderVM
|
||||
{
|
||||
OrderId = order["id"],
|
||||
Key = key
|
||||
};
|
||||
return response;
|
||||
}
|
||||
|
||||
public string GetExpectedSignature(string payload)
|
||||
{
|
||||
string expectedSignature;
|
||||
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
|
||||
{
|
||||
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
|
||||
expectedSignature = Convert.ToHexString(hash).ToLower();
|
||||
}
|
||||
|
||||
return expectedSignature;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetch complete payment details from Razorpay including card details
|
||||
/// </summary>
|
||||
/// <param name="paymentId">Razorpay Payment ID</param>
|
||||
/// <returns>Complete payment details with card information</returns>
|
||||
public async Task<PaymentDetailsVM> GetPaymentDetails(string paymentId)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInfo("Fetching payment details from Razorpay for PaymentId: {PaymentId}", paymentId);
|
||||
|
||||
// Fetch payment details from Razorpay
|
||||
Payment payment = _razorpayClient.Payment.Fetch(paymentId);
|
||||
|
||||
// Extract customer name from notes or fetch from customer API
|
||||
string customerName = ExtractCustomerName(payment);
|
||||
|
||||
Guid paymentDetailsId = Guid.NewGuid();
|
||||
|
||||
// Map to custom model with all details
|
||||
var paymentDetails = new RazorpayPaymentDetails
|
||||
{
|
||||
PaymentId = payment.Attributes["id"]?.ToString(),
|
||||
OrderId = payment.Attributes["order_id"]?.ToString(),
|
||||
Amount = Convert.ToDecimal(payment.Attributes["amount"]) / 100, // Convert from paise to rupees
|
||||
Currency = payment.Attributes["currency"]?.ToString(),
|
||||
Status = payment.Attributes["status"]?.ToString(),
|
||||
Method = payment.Attributes["method"]?.ToString(),
|
||||
Email = payment.Attributes["email"]?.ToString(),
|
||||
Contact = payment.Attributes["contact"]?.ToString(),
|
||||
Description = payment.Attributes["description"]?.ToString(),
|
||||
CustomerName = customerName,
|
||||
CreatedAt = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(payment.Attributes["created_at"])).DateTime,
|
||||
|
||||
// Card details (if payment method is card)
|
||||
CardDetails = payment.Attributes["method"]?.ToString() == "card"
|
||||
? ExtractCardDetails(payment)
|
||||
: null,
|
||||
|
||||
// Bank details (if payment method is netbanking)
|
||||
BankDetails = payment.Attributes["method"]?.ToString() == "netbanking"
|
||||
? ExtractBankDetails(payment)
|
||||
: null,
|
||||
|
||||
// UPI details (if payment method is upi)
|
||||
UpiDetails = payment.Attributes["method"]?.ToString() == "upi"
|
||||
? ExtractUpiDetails(payment)
|
||||
: null,
|
||||
|
||||
// Wallet details (if payment method is wallet)
|
||||
WalletDetails = payment.Attributes["method"]?.ToString() == "wallet"
|
||||
? ExtractWalletDetails(payment)
|
||||
: null,
|
||||
|
||||
// Additional details
|
||||
Fee = payment.Attributes["fee"] != null
|
||||
? Convert.ToDecimal(payment.Attributes["fee"]) / 100
|
||||
: 0,
|
||||
Tax = payment.Attributes["tax"] != null
|
||||
? Convert.ToDecimal(payment.Attributes["tax"]) / 100
|
||||
: 0,
|
||||
ErrorCode = payment.Attributes["error_code"]?.ToString(),
|
||||
ErrorDescription = payment.Attributes["error_description"]?.ToString(),
|
||||
InternationalPayment = Convert.ToBoolean(payment.Attributes["international"] ?? false),
|
||||
Captured = Convert.ToBoolean(payment.Attributes["captured"] ?? false)
|
||||
};
|
||||
|
||||
var razorpayOrderDetails = GetOrderDetails(paymentDetails.OrderId ?? "");
|
||||
|
||||
var response = new PaymentDetailsVM
|
||||
{
|
||||
Id = paymentDetailsId,
|
||||
RazorpayPaymentDetails = paymentDetails,
|
||||
RazorpayOrderDetails = razorpayOrderDetails
|
||||
};
|
||||
|
||||
string jsonString = JsonConvert.SerializeObject(response);
|
||||
|
||||
var data = _aesEncryption.Encrypt(jsonString, encryptionKey);
|
||||
|
||||
var paymentDetail = new PaymentDetail
|
||||
{
|
||||
Id = paymentDetailsId,
|
||||
PaymentId = paymentDetails.PaymentId ?? "",
|
||||
OrderId = paymentDetails.OrderId ?? "",
|
||||
Status = paymentDetails.Status ?? "",
|
||||
Method = paymentDetails.Method ?? "",
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
EncryptedDetails = data.ciphertext,
|
||||
Nonce = data.nonce,
|
||||
Tag = data.tag
|
||||
};
|
||||
|
||||
_context.PaymentDetails.Add(paymentDetail);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
_logger.LogInfo("Payment details fetched successfully from Razorpay for PaymentId: {PaymentId}", paymentId);
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error fetching payment details from Razorpay for PaymentId: {PaymentId}", paymentId);
|
||||
return new PaymentDetailsVM();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetch order details from Razorpay
|
||||
/// </summary>
|
||||
/// <param name="orderId">Razorpay Order ID</param>
|
||||
/// <returns>Order details</returns>
|
||||
public RazorpayOrderDetails? GetOrderDetails(string orderId)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInfo("Fetching order details from Razorpay for OrderId: {OrderId}", orderId);
|
||||
|
||||
Order order = _razorpayClient.Order.Fetch(orderId);
|
||||
|
||||
var orderDetails = new RazorpayOrderDetails
|
||||
{
|
||||
OrderId = order.Attributes["id"]?.ToString(),
|
||||
Amount = Convert.ToDecimal(order.Attributes["amount"]) / 100,
|
||||
Currency = order.Attributes["currency"]?.ToString(),
|
||||
Status = order.Attributes["status"]?.ToString(),
|
||||
Receipt = order.Attributes["receipt"]?.ToString(),
|
||||
CreatedAt = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(order.Attributes["created_at"])).DateTime,
|
||||
AmountPaid = order.Attributes["amount_paid"] != null
|
||||
? Convert.ToDecimal(order.Attributes["amount_paid"]) / 100
|
||||
: 0,
|
||||
AmountDue = order.Attributes["amount_due"] != null
|
||||
? Convert.ToDecimal(order.Attributes["amount_due"]) / 100
|
||||
: 0,
|
||||
Attempts = Convert.ToInt32(order.Attributes["attempts"] ?? 0)
|
||||
};
|
||||
|
||||
_logger.LogInfo("Order details fetched successfully from Razorpay for OrderId: {OrderId}", orderId);
|
||||
return orderDetails;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error fetching order details from Razorpay for OrderId: {OrderId}", orderId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PaymentDetailsVM> GetPaymentDetailsFromDataBase(Guid id)
|
||||
{
|
||||
var projectDetails = await _context.PaymentDetails.FirstOrDefaultAsync(pd => pd.Id == id);
|
||||
if (projectDetails == null)
|
||||
{
|
||||
return new PaymentDetailsVM();
|
||||
}
|
||||
string decrypedData = _aesEncryption.Decrypt(projectDetails.EncryptedDetails ?? new byte[32], projectDetails.Nonce ?? new byte[12], projectDetails.Tag ?? new byte[16], encryptionKey);
|
||||
// Deserialize JSON string to a Department object
|
||||
PaymentDetailsVM? vm = JsonConvert.DeserializeObject<PaymentDetailsVM>(decrypedData);
|
||||
if (vm == null)
|
||||
{
|
||||
return new PaymentDetailsVM();
|
||||
}
|
||||
else
|
||||
{
|
||||
return vm;
|
||||
}
|
||||
}
|
||||
public async Task<List<PaymentDetailsVM>> GetPaymentDetailsListFromDataBase(List<Guid> paymentDetailsIds)
|
||||
{
|
||||
var projectDetails = await _context.PaymentDetails.Where(pd => paymentDetailsIds.Contains(pd.Id)).ToListAsync();
|
||||
List<PaymentDetailsVM> response = new List<PaymentDetailsVM>();
|
||||
|
||||
foreach (var projectDetail in projectDetails)
|
||||
{
|
||||
string decrypedData = _aesEncryption.Decrypt(projectDetail.EncryptedDetails ?? new byte[32], projectDetail.Nonce ?? new byte[12], projectDetail.Tag ?? new byte[16], encryptionKey);
|
||||
// Deserialize JSON string to a Department object
|
||||
PaymentDetailsVM? vm = JsonConvert.DeserializeObject<PaymentDetailsVM>(decrypedData);
|
||||
if (vm != null)
|
||||
{
|
||||
response.Add(vm);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract card details from payment
|
||||
/// </summary>
|
||||
private CardDetails? ExtractCardDetails(Payment payment)
|
||||
{
|
||||
try
|
||||
{
|
||||
var cardObj = payment.Attributes["card"];
|
||||
if (cardObj == null) return null;
|
||||
|
||||
string json = JsonConvert.SerializeObject(cardObj);
|
||||
Dictionary<string, object>? cardDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
|
||||
|
||||
return new CardDetails
|
||||
{
|
||||
CardId = cardDict?["id"]?.ToString(),
|
||||
Last4Digits = cardDict?["last4"]?.ToString(),
|
||||
Network = cardDict?["network"]?.ToString(), // Visa, MasterCard, Amex, etc.
|
||||
CardType = cardDict?["type"]?.ToString(), // credit, debit, prepaid
|
||||
Issuer = cardDict?["issuer"]?.ToString(), // Bank name
|
||||
International = Convert.ToBoolean(cardDict?["international"] ?? false),
|
||||
Emi = Convert.ToBoolean(cardDict?["emi"] ?? false),
|
||||
SubType = cardDict?["sub_type"]?.ToString() // consumer, business
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error extracting card details");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract bank details from payment
|
||||
/// </summary>
|
||||
private BankDetails? ExtractBankDetails(Payment payment)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new BankDetails
|
||||
{
|
||||
Bank = payment.Attributes["bank"]?.ToString(),
|
||||
BankCode = payment.Attributes["bank_code"]?.ToString()
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error extracting bank details");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract UPI details from payment
|
||||
/// </summary>
|
||||
private UpiDetails? ExtractUpiDetails(Payment payment)
|
||||
{
|
||||
try
|
||||
{
|
||||
var vpaObj = payment.Attributes["vpa"];
|
||||
|
||||
return new UpiDetails
|
||||
{
|
||||
Vpa = vpaObj?.ToString(), // UPI ID
|
||||
Provider = payment.Attributes["provider"]?.ToString()
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error extracting UPI details");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract wallet details from payment
|
||||
/// </summary>
|
||||
private WalletDetails? ExtractWalletDetails(Payment payment)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new WalletDetails
|
||||
{
|
||||
WalletName = payment.Attributes["wallet"]?.ToString() // paytm, phonepe, amazonpay, etc.
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error extracting wallet details");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extract customer name from payment object
|
||||
/// </summary>
|
||||
private string ExtractCustomerName(Payment payment)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Option 1: Get from notes (if you passed customer name during order creation)
|
||||
var notesObj = payment.Attributes["notes"];
|
||||
if (notesObj != null)
|
||||
{
|
||||
var notesDict = notesObj as Dictionary<string, object>;
|
||||
if (notesDict != null && notesDict.ContainsKey("customer_name"))
|
||||
{
|
||||
return notesDict["customer_name"]?.ToString() ?? "CustomerName";
|
||||
}
|
||||
if (notesDict != null && notesDict.ContainsKey("name"))
|
||||
{
|
||||
return notesDict["name"]?.ToString() ?? "CustomerName";
|
||||
}
|
||||
}
|
||||
|
||||
// Option 2: Get from customer ID and fetch customer details
|
||||
var customerId = payment.Attributes["customer_id"]?.ToString();
|
||||
if (!string.IsNullOrEmpty(customerId))
|
||||
{
|
||||
try
|
||||
{
|
||||
Customer customer = _razorpayClient.Customer.Fetch(customerId);
|
||||
return customer.Attributes["name"]?.ToString() ?? "CustomerName";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error fetching customer details for CustomerId: {CustomerId}", customerId);
|
||||
}
|
||||
}
|
||||
|
||||
// Option 3: Extract from card holder name (if available)
|
||||
if (payment.Attributes["method"]?.ToString() == "card")
|
||||
{
|
||||
var cardObj = payment.Attributes["card"];
|
||||
if (cardObj != null)
|
||||
{
|
||||
string json = JsonConvert.SerializeObject(cardObj);
|
||||
Dictionary<string, object>? dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
|
||||
|
||||
var cardName = dictionary?["name"]?.ToString();
|
||||
if (!string.IsNullOrEmpty(cardName))
|
||||
{
|
||||
return cardName;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Option 4: Use email as fallback
|
||||
return payment.Attributes["email"]?.ToString() ?? "Customer";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error extracting customer name from payment");
|
||||
return "Customer";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,8 @@
|
||||
namespace Marco.Pms.Services.Service.ServiceInterfaces
|
||||
{
|
||||
public interface IAesEncryption
|
||||
{
|
||||
(byte[] ciphertext, byte[] nonce, byte[] tag) Encrypt(string plaintext, byte[] key);
|
||||
string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key);
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
using Marco.Pms.Model.Dtos.Activities;
|
||||
using Marco.Pms.Model.Dtos.Collection;
|
||||
using Marco.Pms.Model.Dtos.DocumentManager;
|
||||
using Marco.Pms.Model.Dtos.Master;
|
||||
using Marco.Pms.Model.Employees;
|
||||
@ -46,6 +47,7 @@ namespace Marco.Pms.Services.Service.ServiceInterfaces
|
||||
Task<ApiResponse<object>> DeleteActivityGroupAsync(Guid id, bool isActive, Employee loggedInEmployee, Guid tenantId);
|
||||
|
||||
#endregion
|
||||
|
||||
#region =================================================================== Contact Category APIs ===================================================================
|
||||
Task<ApiResponse<object>> CreateContactCategory(CreateContactCategoryDto contactCategoryDto, Employee loggedInEmployee, Guid tenantId);
|
||||
Task<ApiResponse<object>> UpdateContactCategory(Guid id, UpdateContactCategoryDto contactCategoryDto, Employee loggedInEmployee, Guid tenantId);
|
||||
@ -104,5 +106,12 @@ namespace Marco.Pms.Services.Service.ServiceInterfaces
|
||||
Task<ApiResponse<object>> UpdateDocumentTypeMasterAsync(Guid id, CreateDocumentTypeDto model, Employee loggedInEmployee, Guid tenantId);
|
||||
Task<ApiResponse<object>> DeleteDocumentTypeMasterAsync(Guid id, bool isActive, Employee loggedInEmployee, Guid tenantId);
|
||||
#endregion
|
||||
|
||||
#region =================================================================== Payment Adjustment Head APIs ===================================================================
|
||||
Task<ApiResponse<object>> GetPaymentAdjustmentHeadListAsync(bool isActive, Employee loggedInEmployee, Guid tenantId);
|
||||
Task<ApiResponse<object>> CreatePaymentAdjustmentHeadAsync(PaymentAdjustmentHeadDto model, Employee loggedInEmployee, Guid tenantId);
|
||||
Task<ApiResponse<object>> UpdatePaymentAdjustmentHeadAsync(Guid id, PaymentAdjustmentHeadDto model, Employee loggedInEmployee, Guid tenantId);
|
||||
Task<ApiResponse<object>> DeletePaymentAdjustmentHeadAsync(Guid id, bool isActive, Employee loggedInEmployee, Guid tenantId);
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,15 @@
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.ViewModels.PaymentGetway;
|
||||
|
||||
namespace Marco.Pms.Services.Service.ServiceInterfaces
|
||||
{
|
||||
public interface IRazorpayService
|
||||
{
|
||||
CreateOrderVM CreateOrder(double amount, Employee loggedInEmployee, Guid tenantId);
|
||||
string GetExpectedSignature(string payload);
|
||||
Task<PaymentDetailsVM> GetPaymentDetails(string paymentId);
|
||||
Task<PaymentDetailsVM> GetPaymentDetailsFromDataBase(Guid id);
|
||||
Task<List<PaymentDetailsVM>> GetPaymentDetailsListFromDataBase(List<Guid> paymentDetailsIds);
|
||||
RazorpayOrderDetails? GetOrderDetails(string orderId);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,10 @@
|
||||
using Marco.Pms.Model.Utilities;
|
||||
|
||||
namespace Marco.Pms.Services.Service.ServiceInterfaces
|
||||
{
|
||||
public interface ITenantService
|
||||
{
|
||||
Task<ApiResponse<object>> CreateTenantAsync(Guid enquireId, Guid paymentDetailId, Guid planId);
|
||||
Task<ApiResponse<object>> RenewSubscriptionAsync(Guid tenantId, Guid employeeId, Guid paymentDetailId, Guid planId);
|
||||
}
|
||||
}
|
||||
999
Marco.Pms.Services/Service/TenantService.cs
Normal file
999
Marco.Pms.Services/Service/TenantService.cs
Normal file
@ -0,0 +1,999 @@
|
||||
using AutoMapper;
|
||||
using Marco.Pms.DataAccess.Data;
|
||||
using Marco.Pms.Helpers.Utility;
|
||||
using Marco.Pms.Model.Dtos.Tenant;
|
||||
using Marco.Pms.Model.Employees;
|
||||
using Marco.Pms.Model.Entitlements;
|
||||
using Marco.Pms.Model.OrganizationModel;
|
||||
using Marco.Pms.Model.Projects;
|
||||
using Marco.Pms.Model.Roles;
|
||||
using Marco.Pms.Model.TenantModels;
|
||||
using Marco.Pms.Model.TenantModels.MongoDBModel;
|
||||
using Marco.Pms.Model.Utilities;
|
||||
using Marco.Pms.Model.ViewModels.Activities;
|
||||
using Marco.Pms.Model.ViewModels.Tenant;
|
||||
using Marco.Pms.Services.Helpers;
|
||||
using Marco.Pms.Services.Service.ServiceInterfaces;
|
||||
using MarcoBMS.Services.Service;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Net;
|
||||
using Tenant = Marco.Pms.Model.TenantModels.Tenant;
|
||||
|
||||
namespace Marco.Pms.Services.Service
|
||||
{
|
||||
public class TenantService : ITenantService
|
||||
{
|
||||
private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
|
||||
private readonly IServiceScopeFactory _serviceScopeFactory;
|
||||
private readonly ILoggingService _logger;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly FeatureDetailsHelper _featureDetailsHelper;
|
||||
|
||||
private readonly static Guid projectActiveStatus = Guid.Parse("b74da4c2-d07e-46f2-9919-e75e49b12731");
|
||||
private readonly static Guid projectInProgressStatus = Guid.Parse("cdad86aa-8a56-4ff4-b633-9c629057dfef");
|
||||
private readonly static Guid projectOnHoldStatus = Guid.Parse("603e994b-a27f-4e5d-a251-f3d69b0498ba");
|
||||
private readonly static Guid projectInActiveStatus = Guid.Parse("ef1c356e-0fe0-42df-a5d3-8daee355492d");
|
||||
private readonly static Guid projectCompletedStatus = Guid.Parse("33deaef9-9af1-4f2a-b443-681ea0d04f81");
|
||||
|
||||
private readonly static Guid tenantActiveStatus = Guid.Parse("62b05792-5115-4f99-8ff5-e8374859b191");
|
||||
private readonly static Guid activePlanStatus = Guid.Parse("cd3a68ea-41fd-42f0-bd0c-c871c7337727");
|
||||
private readonly static Guid EmployeeFeatureId = Guid.Parse("81ab8a87-8ccd-4015-a917-0627cee6a100");
|
||||
private readonly static string AdminRoleName = "Admin";
|
||||
public TenantService(IDbContextFactory<ApplicationDbContext> dbContextFactory,
|
||||
IServiceScopeFactory serviceScopeFactory,
|
||||
ILoggingService logger,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IMapper mapper,
|
||||
FeatureDetailsHelper featureDetailsHelper)
|
||||
{
|
||||
_dbContextFactory = dbContextFactory ?? throw new ArgumentNullException(nameof(dbContextFactory));
|
||||
_serviceScopeFactory = serviceScopeFactory ?? throw new ArgumentNullException(nameof(serviceScopeFactory));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
|
||||
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
|
||||
_featureDetailsHelper = featureDetailsHelper ?? throw new ArgumentNullException(nameof(featureDetailsHelper));
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<object>> CreateTenantAsync(Guid enquireId, Guid paymentDetailId, Guid planId)
|
||||
{
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
|
||||
var _configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
|
||||
var _emailSender = scope.ServiceProvider.GetRequiredService<IEmailSender>();
|
||||
|
||||
var tenantEnquireTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.TenantEnquires.FirstOrDefaultAsync(te => te.Id == enquireId);
|
||||
});
|
||||
var subscriptionPlanTask = Task.Run(async () =>
|
||||
{
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await context.SubscriptionPlanDetails.Include(sp => sp.Plan).FirstOrDefaultAsync(sp => sp.Id == planId);
|
||||
});
|
||||
|
||||
await Task.WhenAll(tenantEnquireTask, subscriptionPlanTask);
|
||||
|
||||
var tenantEnquire = tenantEnquireTask.Result;
|
||||
var subscriptionPlan = subscriptionPlanTask.Result;
|
||||
|
||||
if (tenantEnquire == null)
|
||||
{
|
||||
_logger.LogWarning("Tenant Enquire {TenantEnquireId} not found in database", enquireId);
|
||||
return ApiResponse<object>.ErrorResponse("Tenant Enquire not found", "Tenant Enquire not found", 404);
|
||||
}
|
||||
if (subscriptionPlan == null)
|
||||
{
|
||||
_logger.LogWarning("Subscription plan {PlanId} not found in database", planId);
|
||||
return ApiResponse<object>.ErrorResponse("Subscription plan not found", "Subscription plan not found", 404);
|
||||
}
|
||||
|
||||
var existingUser = await _userManager.FindByEmailAsync(tenantEnquire.Email);
|
||||
if (existingUser != null)
|
||||
{
|
||||
_logger.LogWarning("Tenant creation failed for email {Email}: an application user with this email already exists.", tenantEnquire.Email);
|
||||
return ApiResponse<object>.ErrorResponse("Tenant cannot be created", "A user with the specified email already exists.", 409);
|
||||
}
|
||||
|
||||
await using var transaction = await _context.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
Guid employeeId = Guid.NewGuid();
|
||||
DateTime onBoardingDate = DateTime.UtcNow;
|
||||
Guid tenantId = Guid.NewGuid();
|
||||
|
||||
// Get last SPRID and increment for new organization
|
||||
var lastOrganization = await _context.Organizations.OrderByDescending(sp => sp.SPRID).FirstOrDefaultAsync();
|
||||
double lastSPRID = lastOrganization?.SPRID ?? 5400;
|
||||
|
||||
// Map DTO to entity and set defaults
|
||||
Organization organization = new Organization
|
||||
{
|
||||
Name = tenantEnquire.OrganizationName,
|
||||
Email = tenantEnquire.Email,
|
||||
ContactPerson = $"{tenantEnquire.FirstName} {tenantEnquire.LastName}",
|
||||
Address = tenantEnquire.BillingAddress,
|
||||
ContactNumber = tenantEnquire.ContactNumber,
|
||||
SPRID = lastSPRID + 1,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
CreatedById = employeeId,
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
_context.Organizations.Add(organization);
|
||||
|
||||
// Create the primary Tenant entity
|
||||
|
||||
var tenant = new Tenant
|
||||
{
|
||||
Id = tenantId,
|
||||
Name = tenantEnquire.OrganizationName,
|
||||
Email = tenantEnquire.Email,
|
||||
ContactName = $"{tenantEnquire.FirstName} {tenantEnquire.LastName}",
|
||||
ContactNumber = tenantEnquire.ContactNumber,
|
||||
OrganizationSize = tenantEnquire.OrganizationSize,
|
||||
BillingAddress = tenantEnquire.BillingAddress,
|
||||
IndustryId = tenantEnquire.IndustryId,
|
||||
Reference = tenantEnquire.Reference,
|
||||
OnBoardingDate = onBoardingDate,
|
||||
TenantStatusId = tenantActiveStatus,
|
||||
OrganizationId = organization.Id,
|
||||
CreatedById = employeeId,
|
||||
IsActive = true,
|
||||
IsSuperTenant = false
|
||||
};
|
||||
|
||||
_context.Tenants.Add(tenant);
|
||||
|
||||
// Create the root ApplicationUser for the new tenant
|
||||
var applicationUser = new ApplicationUser
|
||||
{
|
||||
Email = tenantEnquire.Email,
|
||||
UserName = tenantEnquire.Email, // Best practice to use email as username for simplicity
|
||||
IsRootUser = true,
|
||||
EmailConfirmed = true // Auto-confirming email as it's part of a trusted setup process
|
||||
};
|
||||
|
||||
// SECURITY WARNING: Hardcoded passwords are a major vulnerability.
|
||||
// Replace "User@123" with a securely generated random password.
|
||||
var initialPassword = "User@123"; // TODO: Replace with password generation service.
|
||||
var result = await _userManager.CreateAsync(applicationUser, initialPassword);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
// If user creation fails, roll back the transaction immediately and return the errors.
|
||||
await transaction.RollbackAsync();
|
||||
var errors = result.Errors.Select(e => e.Description).ToList();
|
||||
_logger.LogWarning("Failed to create ApplicationUser for tenant {TenantName}. Errors: {Errors}", tenantEnquire.OrganizationName, string.Join(", ", errors));
|
||||
return ApiResponse<object>.ErrorResponse("Failed to create user", errors, 400);
|
||||
}
|
||||
|
||||
// Create the default "Admin" Job Role for the tenant
|
||||
var adminJobRole = new JobRole
|
||||
{
|
||||
Name = AdminRoleName,
|
||||
Description = "Default administrator role for the tenant.",
|
||||
TenantId = tenantId
|
||||
};
|
||||
_context.JobRoles.Add(adminJobRole);
|
||||
|
||||
// Create the primary Employee record and link it to the ApplicationUser and JobRole
|
||||
var employeeUser = new Employee
|
||||
{
|
||||
Id = employeeId,
|
||||
FirstName = tenantEnquire.FirstName,
|
||||
LastName = tenantEnquire.LastName,
|
||||
Email = tenantEnquire.Email,
|
||||
PhoneNumber = tenantEnquire.ContactNumber,
|
||||
JoiningDate = onBoardingDate,
|
||||
ApplicationUserId = applicationUser.Id,
|
||||
JobRole = adminJobRole, // Link to the newly created role
|
||||
CurrentAddress = tenantEnquire.BillingAddress,
|
||||
IsActive = true,
|
||||
IsSystem = false,
|
||||
IsPrimary = true,
|
||||
OrganizationId = organization.Id,
|
||||
HasApplicationAccess = true
|
||||
};
|
||||
_context.Employees.Add(employeeUser);
|
||||
|
||||
var applicationRole = new ApplicationRole
|
||||
{
|
||||
Role = "Super User",
|
||||
Description = "Super User",
|
||||
IsSystem = true,
|
||||
TenantId = tenantId
|
||||
};
|
||||
_context.ApplicationRoles.Add(applicationRole);
|
||||
|
||||
var rolePermissionMappigs = new List<RolePermissionMappings> {
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ModifyTenant
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewTenant
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ManageMasters
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewMasters
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.ViewOrganization
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.AddOrganization
|
||||
},
|
||||
new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = applicationRole.Id,
|
||||
FeaturePermissionId = PermissionsMaster.EditOrganization
|
||||
}
|
||||
};
|
||||
_context.RolePermissionMappings.AddRange(rolePermissionMappigs);
|
||||
|
||||
_context.EmployeeRoleMappings.Add(new EmployeeRoleMapping
|
||||
{
|
||||
EmployeeId = employeeUser.Id,
|
||||
RoleId = applicationRole.Id,
|
||||
IsEnabled = true,
|
||||
TenantId = tenantId
|
||||
});
|
||||
|
||||
// Create a default project for the new tenant
|
||||
var project = new Project
|
||||
{
|
||||
Name = "Default Project",
|
||||
ProjectStatusId = Guid.Parse("b74da4c2-d07e-46f2-9919-e75e49b12731"), // Consider using a constant for this GUID
|
||||
ProjectAddress = tenantEnquire.BillingAddress,
|
||||
StartDate = onBoardingDate,
|
||||
EndDate = DateTime.MaxValue,
|
||||
PromoterId = organization.Id,
|
||||
PMCId = organization.Id,
|
||||
ContactPerson = tenant.ContactName,
|
||||
TenantId = tenantId
|
||||
};
|
||||
_context.Projects.Add(project);
|
||||
|
||||
var projectAllocation = new ProjectAllocation
|
||||
{
|
||||
ProjectId = project.Id,
|
||||
EmployeeId = employeeUser.Id,
|
||||
AllocationDate = onBoardingDate,
|
||||
IsActive = true,
|
||||
JobRoleId = adminJobRole.Id,
|
||||
TenantId = tenantId
|
||||
};
|
||||
_context.ProjectAllocations.Add(projectAllocation);
|
||||
|
||||
// All entities are now added to the context. Save them all in a single database operation.
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// 4. --- POST-CREATION ACTIONS ---
|
||||
// Generate a password reset token so the new user can set their own password.
|
||||
_logger.LogInfo("User {Email} created. Sending password setup email.", applicationUser.Email);
|
||||
var token = await _userManager.GeneratePasswordResetTokenAsync(applicationUser);
|
||||
var resetLink = $"{_configuration["AppSettings:WebFrontendUrl"]}/reset-password?token={WebUtility.UrlEncode(token)}&email={WebUtility.UrlEncode(applicationUser.Email)}";
|
||||
await _emailSender.SendResetPasswordEmailOnRegister(applicationUser.Email, employeeUser.FirstName, resetLink);
|
||||
|
||||
// Map the result to a ViewModel for the API response.
|
||||
var tenantVM = _mapper.Map<TenantVM>(tenant);
|
||||
tenantVM.CreatedBy = _mapper.Map<BasicEmployeeVM>(employeeUser);
|
||||
|
||||
// Commit the transaction as all operations were successful.
|
||||
await transaction.CommitAsync();
|
||||
|
||||
await AddSubscriptionAsync(tenantId, employeeId, paymentDetailId, planId);
|
||||
|
||||
_logger.LogInfo("Successfully created tenant {TenantId} for organization {OrganizationName}.", tenant.Id, tenant.Name);
|
||||
return ApiResponse<object>.SuccessResponse(tenantVM, "Tenant created successfully.", 201);
|
||||
}
|
||||
catch (DbUpdateException dbEx)
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
// Log the detailed database exception, including the inner exception if available.
|
||||
_logger.LogError(dbEx, "A database update exception occurred while creating tenant for email {Email}. Inner Exception: {InnerException}",
|
||||
tenantEnquire.Email, dbEx.InnerException?.Message ?? string.Empty);
|
||||
return ApiResponse<object>.ErrorResponse("An internal database error occurred.", ExceptionMapper(dbEx), 500);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Log the general exception.
|
||||
_logger.LogError(ex, "An unexpected exception occurred while creating tenant for email {Email}.", tenantEnquire.Email);
|
||||
return ApiResponse<object>.ErrorResponse("An unexpected internal error occurred.", ExceptionMapper(ex), 500);
|
||||
}
|
||||
}
|
||||
public async Task<ApiResponse<object>> AddSubscriptionAsync(Guid tenantId, Guid employeeId, Guid paymentDetailId, Guid planId)
|
||||
{
|
||||
|
||||
_logger.LogInfo("AddSubscription called for Tenant {TenantId} and Plan {PlanId}", tenantId, planId);
|
||||
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
|
||||
var paymentDetail = await _context.PaymentDetails.FirstOrDefaultAsync(pd => pd.Id == paymentDetailId);
|
||||
if (paymentDetail == null)
|
||||
{
|
||||
_logger.LogWarning("Payment Details {PaymentDetailsId} not found in database", paymentDetailId);
|
||||
return ApiResponse<object>.ErrorResponse("Payment Details not found", "Payment Details not found", 404);
|
||||
}
|
||||
|
||||
var tenant = await _context.Tenants.FirstOrDefaultAsync(t => t.Id == tenantId);
|
||||
if (tenant == null)
|
||||
{
|
||||
_logger.LogWarning("Tenant {TenantId} not found in database", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Tenant not found", "Tenant not found", 404);
|
||||
}
|
||||
|
||||
var subscriptionPlan = await _context.SubscriptionPlanDetails.Include(sp => sp.Plan).FirstOrDefaultAsync(sp => sp.Id == planId);
|
||||
if (subscriptionPlan == null)
|
||||
{
|
||||
_logger.LogWarning("Subscription plan {PlanId} not found in database", planId);
|
||||
return ApiResponse<object>.ErrorResponse("Subscription plan not found", "Subscription plan not found", 404);
|
||||
}
|
||||
var activeUsers = await _context.Employees.CountAsync(e => e.Email != null && e.ApplicationUserId != null && e.TenantId == tenant.Id && e.IsActive);
|
||||
if (activeUsers > subscriptionPlan.MaxUser)
|
||||
{
|
||||
_logger.LogWarning("Add less max user than the active user in the tenant {TenantId}", tenant.Id);
|
||||
return ApiResponse<object>.ErrorResponse("Invalid Max user count", "Max User count must be higher than active user count", 400);
|
||||
}
|
||||
await using var transaction = await _context.Database.BeginTransactionAsync();
|
||||
var utcNow = DateTime.UtcNow;
|
||||
|
||||
// Prepare subscription dates based on frequency
|
||||
var endDate = subscriptionPlan.Frequency switch
|
||||
{
|
||||
PLAN_FREQUENCY.MONTHLY => utcNow.AddDays(30),
|
||||
PLAN_FREQUENCY.QUARTERLY => utcNow.AddDays(90),
|
||||
PLAN_FREQUENCY.HALF_YEARLY => utcNow.AddDays(120),
|
||||
PLAN_FREQUENCY.YEARLY => utcNow.AddDays(360),
|
||||
_ => utcNow // default if unknown
|
||||
};
|
||||
|
||||
var tenantSubscription = new TenantSubscriptions
|
||||
{
|
||||
TenantId = tenantId,
|
||||
PlanId = planId,
|
||||
StatusId = activePlanStatus,
|
||||
CreatedAt = utcNow,
|
||||
MaxUsers = subscriptionPlan.MaxUser,
|
||||
CreatedById = employeeId,
|
||||
CurrencyId = subscriptionPlan.CurrencyId,
|
||||
PaymentDetailId = paymentDetailId,
|
||||
IsTrial = false,
|
||||
StartDate = utcNow,
|
||||
EndDate = endDate,
|
||||
NextBillingDate = endDate,
|
||||
AutoRenew = false
|
||||
};
|
||||
|
||||
_context.TenantSubscriptions.Add(tenantSubscription);
|
||||
|
||||
try
|
||||
{
|
||||
await _context.SaveChangesAsync();
|
||||
_logger.LogInfo("Tenant subscription added successfully for Tenant {TenantId}, Plan {PlanId}",
|
||||
tenantId, planId);
|
||||
}
|
||||
catch (DbUpdateException dbEx)
|
||||
{
|
||||
_logger.LogError(dbEx, "Database exception while adding subscription plan to tenant {TenantId}", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Internal error occured", ExceptionMapper(dbEx), 500);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var features = await _featureDetailsHelper.GetFeatureDetails(subscriptionPlan.FeaturesId);
|
||||
if (features == null)
|
||||
{
|
||||
_logger.LogInfo("No features found for subscription plan {PlanId}", planId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(tenantSubscription, "Tenant subscription successfully added", 200);
|
||||
}
|
||||
|
||||
// Helper to get permissions for a module asynchronously
|
||||
async Task<List<Guid>> GetPermissionsForModuleAsync(List<Guid>? featureIds)
|
||||
{
|
||||
if (featureIds == null || featureIds.Count == 0) return new List<Guid>();
|
||||
|
||||
await using var ctx = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await ctx.FeaturePermissions.AsNoTracking()
|
||||
.Where(fp => featureIds.Contains(fp.FeatureId))
|
||||
.Select(fp => fp.Id)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
// Fetch permission tasks for all modules in parallel
|
||||
var projectPermissionTask = GetPermissionsForModuleAsync(features.Modules?.ProjectManagement?.FeatureId);
|
||||
var attendancePermissionTask = GetPermissionsForModuleAsync(features.Modules?.Attendance?.FeatureId);
|
||||
var directoryPermissionTask = GetPermissionsForModuleAsync(features.Modules?.Directory?.FeatureId);
|
||||
var expensePermissionTask = GetPermissionsForModuleAsync(features.Modules?.Expense?.FeatureId);
|
||||
var employeePermissionTask = GetPermissionsForModuleAsync(new List<Guid> { EmployeeFeatureId });
|
||||
|
||||
await Task.WhenAll(projectPermissionTask, attendancePermissionTask, directoryPermissionTask, expensePermissionTask, employeePermissionTask);
|
||||
|
||||
var newPermissionIds = new List<Guid>();
|
||||
var deletePermissionIds = new List<Guid>();
|
||||
|
||||
// Add or remove permissions based on modules enabled status
|
||||
void ProcessPermissions(bool? enabled, List<Guid> permissions)
|
||||
{
|
||||
if (enabled == true)
|
||||
newPermissionIds.AddRange(permissions);
|
||||
else
|
||||
deletePermissionIds.AddRange(permissions);
|
||||
}
|
||||
|
||||
ProcessPermissions(features.Modules?.ProjectManagement?.Enabled, projectPermissionTask.Result);
|
||||
ProcessPermissions(features.Modules?.Attendance?.Enabled, attendancePermissionTask.Result);
|
||||
ProcessPermissions(features.Modules?.Directory?.Enabled, directoryPermissionTask.Result);
|
||||
ProcessPermissions(features.Modules?.Expense?.Enabled, expensePermissionTask.Result);
|
||||
|
||||
newPermissionIds = newPermissionIds.Distinct().ToList();
|
||||
deletePermissionIds = deletePermissionIds.Distinct().ToList();
|
||||
|
||||
// Get root employee and role for this tenant
|
||||
var rootEmployee = await _context.Employees
|
||||
.Include(e => e.ApplicationUser)
|
||||
.FirstOrDefaultAsync(e => e.ApplicationUser != null && (e.ApplicationUser.IsRootUser ?? false) && e.OrganizationId == tenant.OrganizationId);
|
||||
|
||||
if (rootEmployee == null)
|
||||
{
|
||||
_logger.LogWarning("Root employee not found for tenant {TenantId}", tenantId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(tenantSubscription, "Tenant subscription successfully added", 200);
|
||||
}
|
||||
|
||||
var roleId = await _context.EmployeeRoleMappings
|
||||
.AsNoTracking()
|
||||
.Where(er => er.EmployeeId == rootEmployee.Id && er.TenantId == tenantId)
|
||||
.Select(er => er.RoleId)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (roleId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("RoleId for root employee {EmployeeId} in tenant {TenantId} not found", rootEmployee.Id, tenantId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(tenantSubscription, "Tenant subscription successfully added", 200);
|
||||
}
|
||||
|
||||
var oldRolePermissionMappings = await _context.RolePermissionMappings
|
||||
.Where(rp => rp.ApplicationRoleId == roleId)
|
||||
.ToListAsync();
|
||||
|
||||
var oldPermissionIds = oldRolePermissionMappings.Select(rp => rp.FeaturePermissionId).ToList();
|
||||
|
||||
// Prevent accidentally deleting essential employee permissions
|
||||
var permissionIdCount = oldPermissionIds.Count - deletePermissionIds.Count;
|
||||
if (permissionIdCount <= 4 && deletePermissionIds.Any())
|
||||
{
|
||||
var employeePermissionIds = employeePermissionTask.Result;
|
||||
deletePermissionIds = deletePermissionIds.Where(p => !employeePermissionIds.Contains(p)).ToList();
|
||||
}
|
||||
|
||||
// Prepare mappings to delete and add
|
||||
var deleteMappings = oldRolePermissionMappings.Where(rp => deletePermissionIds.Contains(rp.FeaturePermissionId)).ToList();
|
||||
var addRolePermissionMappings = newPermissionIds
|
||||
.Where(p => !oldPermissionIds.Contains(p))
|
||||
.Select(p => new RolePermissionMappings
|
||||
{
|
||||
ApplicationRoleId = roleId,
|
||||
FeaturePermissionId = p
|
||||
})
|
||||
.ToList();
|
||||
|
||||
if (addRolePermissionMappings.Any())
|
||||
{
|
||||
_context.RolePermissionMappings.AddRange(addRolePermissionMappings);
|
||||
_logger.LogInfo("Added {Count} new role permission mappings for role {RoleId}", addRolePermissionMappings.Count, roleId);
|
||||
}
|
||||
if (deleteMappings.Any())
|
||||
{
|
||||
_context.RolePermissionMappings.RemoveRange(deleteMappings);
|
||||
_logger.LogInfo("Removed {Count} role permission mappings for role {RoleId}", deleteMappings.Count, roleId);
|
||||
}
|
||||
|
||||
var _cache = scope.ServiceProvider.GetRequiredService<CacheUpdateHelper>();
|
||||
await _cache.ClearAllEmployeesFromCacheByTenantId(tenant.Id);
|
||||
|
||||
var _masteData = scope.ServiceProvider.GetRequiredService<MasterDataService>();
|
||||
|
||||
if (features.Modules?.ProjectManagement?.Enabled ?? false)
|
||||
{
|
||||
var workCategoryMaster = _masteData.GetWorkCategoriesData(tenant.Id);
|
||||
var workStatusMaster = _masteData.GetWorkStatusesData(tenant.Id);
|
||||
|
||||
_context.WorkCategoryMasters.AddRange(workCategoryMaster);
|
||||
_context.WorkStatusMasters.AddRange(workStatusMaster);
|
||||
}
|
||||
if (features.Modules?.Expense?.Enabled ?? false)
|
||||
{
|
||||
var expensesTypeMaster = _masteData.GetExpensesTypeesData(tenant.Id);
|
||||
var paymentModeMatser = _masteData.GetPaymentModesData(tenant.Id);
|
||||
|
||||
_context.ExpensesTypeMaster.AddRange(expensesTypeMaster);
|
||||
_context.PaymentModeMatser.AddRange(paymentModeMatser);
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
await transaction.CommitAsync();
|
||||
|
||||
_logger.LogInfo("Permissions updated successfully for tenant {TenantId} subscription", tenantId);
|
||||
|
||||
return ApiResponse<object>.SuccessResponse(tenantSubscription, "Tenant Subscription Successfully", 200);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
_logger.LogError(ex, "Exception occurred while updating permissions for tenant {TenantId}", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Internal error occured", ExceptionMapper(ex), 500);
|
||||
}
|
||||
}
|
||||
public async Task<ApiResponse<object>> RenewSubscriptionAsync(Guid tenantId, Guid employeeId, Guid paymentDetailId, Guid planId)
|
||||
{
|
||||
// 2. Create a new DbContext instance for this request.
|
||||
await using var context = await _dbContextFactory.CreateDbContextAsync();
|
||||
|
||||
// 3. Get PermissionServices from DI inside a fresh scope (rarely needed, but retained for your design).
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
var permissionService = scope.ServiceProvider.GetRequiredService<PermissionServices>();
|
||||
var _updateLogHelper = scope.ServiceProvider.GetRequiredService<UtilityMongoDBHelper>();
|
||||
|
||||
// 4. Check user permissions: must be both Root user and have ManageTenants permission.
|
||||
var hasPermission = await permissionService.HasPermission(PermissionsMaster.ManageTenants, employeeId);
|
||||
|
||||
if (!hasPermission)
|
||||
{
|
||||
_logger.LogWarning("Permission denied for EmployeeId={EmployeeId}. HasPermission: {HasPermission}",
|
||||
employeeId, hasPermission);
|
||||
return ApiResponse<object>.ErrorResponse("Access denied", "User does not have the required permissions.", 403);
|
||||
}
|
||||
|
||||
// 5. Fetch Tenant, SubscriptionPlan, and TenantSubscription in parallel (efficiently).
|
||||
var tenantTask = _dbContextFactory.CreateDbContextAsync().ContinueWith(ctx =>
|
||||
ctx.Result.Tenants.AsNoTracking().FirstOrDefaultAsync(t => t.Id == tenantId)).Unwrap();
|
||||
|
||||
var planDetailsTask = _dbContextFactory.CreateDbContextAsync().ContinueWith(ctx =>
|
||||
ctx.Result.SubscriptionPlanDetails.Include(sp => sp.Plan).AsNoTracking().FirstOrDefaultAsync(sp => sp.Id == planId)).Unwrap();
|
||||
|
||||
var currentSubscriptionTask = _dbContextFactory.CreateDbContextAsync().ContinueWith(ctx =>
|
||||
ctx.Result.TenantSubscriptions.Include(ts => ts.Currency).AsNoTracking().FirstOrDefaultAsync(ts => ts.TenantId == tenantId && !ts.IsCancelled)).Unwrap();
|
||||
|
||||
var paymentDetailsTask = _dbContextFactory.CreateDbContextAsync().ContinueWith(ctx =>
|
||||
ctx.Result.PaymentDetails.AsNoTracking().FirstOrDefaultAsync(pd => pd.Id == paymentDetailId)).Unwrap();
|
||||
|
||||
|
||||
await Task.WhenAll(tenantTask, planDetailsTask, currentSubscriptionTask, paymentDetailsTask);
|
||||
|
||||
var tenant = tenantTask.Result;
|
||||
if (tenant == null)
|
||||
{
|
||||
_logger.LogWarning("Tenant {TenantId} not found.", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Tenant not found", "Tenant not found", 404);
|
||||
}
|
||||
|
||||
var subscriptionPlan = planDetailsTask.Result;
|
||||
if (subscriptionPlan == null)
|
||||
{
|
||||
_logger.LogWarning("Subscription plan {PlanId} not found.", planId);
|
||||
return ApiResponse<object>.ErrorResponse("Subscription plan not found", "Subscription plan not found", 404);
|
||||
}
|
||||
|
||||
var paymentDetail = paymentDetailsTask.Result;
|
||||
if (paymentDetail == null)
|
||||
{
|
||||
_logger.LogWarning("Payment details {PaymentDetailId} not found", paymentDetailId);
|
||||
return ApiResponse<object>.ErrorResponse("Payment details not found", "Payment details not found", 404);
|
||||
}
|
||||
|
||||
var currentSubscription = currentSubscriptionTask.Result;
|
||||
var utcNow = DateTime.UtcNow;
|
||||
|
||||
var activeUsers = await context.Employees.CountAsync(e => e.Email != null && e.ApplicationUserId != null && e.TenantId == tenant.Id && e.IsActive);
|
||||
if (activeUsers > subscriptionPlan.MaxUser)
|
||||
{
|
||||
_logger.LogWarning("Employee {EmployeeId} add less max user than the active user in the tenant {TenantId}", employeeId, tenant.Id);
|
||||
return ApiResponse<object>.ErrorResponse("Invalid Max user count", "Max User count must be higher than active user count", 400);
|
||||
}
|
||||
|
||||
// 7. Else, change plan: new subscription record, close the old if exists.
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
// 7a. Compute new plan dates
|
||||
var endDate = subscriptionPlan.Frequency switch
|
||||
{
|
||||
PLAN_FREQUENCY.MONTHLY => utcNow.AddDays(30),
|
||||
PLAN_FREQUENCY.QUARTERLY => utcNow.AddDays(90),
|
||||
PLAN_FREQUENCY.HALF_YEARLY => utcNow.AddDays(120),
|
||||
PLAN_FREQUENCY.YEARLY => utcNow.AddDays(360),
|
||||
_ => utcNow // default if unknown
|
||||
};
|
||||
|
||||
var newSubscription = new TenantSubscriptions
|
||||
{
|
||||
TenantId = tenantId,
|
||||
PlanId = planId,
|
||||
StatusId = activePlanStatus,
|
||||
CreatedAt = utcNow,
|
||||
MaxUsers = subscriptionPlan.MaxUser,
|
||||
CreatedById = employeeId,
|
||||
CurrencyId = subscriptionPlan.CurrencyId,
|
||||
PaymentDetailId = paymentDetailId,
|
||||
StartDate = utcNow,
|
||||
EndDate = endDate,
|
||||
NextBillingDate = endDate,
|
||||
IsTrial = currentSubscription?.IsTrial ?? false,
|
||||
AutoRenew = currentSubscription?.AutoRenew ?? false
|
||||
};
|
||||
context.TenantSubscriptions.Add(newSubscription);
|
||||
|
||||
// 7b. If an old subscription exists, cancel it.
|
||||
if (currentSubscription != null)
|
||||
{
|
||||
currentSubscription.IsCancelled = true;
|
||||
currentSubscription.CancellationDate = utcNow;
|
||||
currentSubscription.UpdateAt = utcNow;
|
||||
currentSubscription.UpdatedById = employeeId;
|
||||
context.TenantSubscriptions.Update(currentSubscription);
|
||||
}
|
||||
await context.SaveChangesAsync();
|
||||
_logger.LogInfo("Subscription plan changed: Tenant={TenantId}, NewPlan={PlanId}",
|
||||
tenantId, planId);
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await ClearPermissionForTenant(tenantId);
|
||||
});
|
||||
|
||||
// 8. Update tenant permissions based on subscription features.
|
||||
var features = await _featureDetailsHelper.GetFeatureDetails(subscriptionPlan.FeaturesId);
|
||||
if (features == null)
|
||||
{
|
||||
_logger.LogInfo("No features for Plan={PlanId}.", planId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(newSubscription, "Tenant subscription updated (no features)", 200);
|
||||
}
|
||||
|
||||
// 8a. Async helper to get all permission IDs for a given module.
|
||||
async Task<List<Guid>> GetPermissionsForFeaturesAsync(List<Guid>? featureIds)
|
||||
{
|
||||
if (featureIds == null || featureIds.Count == 0) return new List<Guid>();
|
||||
|
||||
await using var ctx = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await ctx.FeaturePermissions.AsNoTracking()
|
||||
.Where(fp => featureIds.Contains(fp.FeatureId))
|
||||
.Select(fp => fp.Id)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
// 8b. Fetch all module permissions concurrently.
|
||||
var projectPermTask = GetPermissionsForFeaturesAsync(features.Modules?.ProjectManagement?.FeatureId);
|
||||
var attendancePermTask = GetPermissionsForFeaturesAsync(features.Modules?.Attendance?.FeatureId);
|
||||
var directoryPermTask = GetPermissionsForFeaturesAsync(features.Modules?.Directory?.FeatureId);
|
||||
var expensePermTask = GetPermissionsForFeaturesAsync(features.Modules?.Expense?.FeatureId);
|
||||
var employeePermTask = GetPermissionsForFeaturesAsync(new List<Guid> { EmployeeFeatureId }); // assumed defined
|
||||
|
||||
await Task.WhenAll(projectPermTask, attendancePermTask, directoryPermTask, expensePermTask, employeePermTask);
|
||||
|
||||
// 8c. Find root employee & role for this tenant.
|
||||
var rootEmployee = await context.Employees
|
||||
.Include(e => e.ApplicationUser)
|
||||
.FirstOrDefaultAsync(e => e.ApplicationUser != null && (e.ApplicationUser.IsRootUser ?? false) && e.TenantId == tenantId);
|
||||
|
||||
if (rootEmployee == null)
|
||||
{
|
||||
_logger.LogWarning("No root employee for Tenant={TenantId}.", tenantId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(newSubscription, "Tenant subscription updated (no root employee)", 200);
|
||||
}
|
||||
|
||||
var rootRoleId = await context.EmployeeRoleMappings
|
||||
.AsNoTracking()
|
||||
.Where(er => er.EmployeeId == rootEmployee.Id && er.TenantId == tenantId)
|
||||
.Select(er => er.RoleId)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (rootRoleId == Guid.Empty)
|
||||
{
|
||||
_logger.LogWarning("No root role for Employee={EmployeeId}, Tenant={TenantId}.", rootEmployee.Id, tenantId);
|
||||
await transaction.CommitAsync();
|
||||
return ApiResponse<object>.SuccessResponse(newSubscription, "Tenant subscription updated (no root role)", 200);
|
||||
}
|
||||
|
||||
var dbOldRolePerms = await context.RolePermissionMappings.Where(x => x.ApplicationRoleId == rootRoleId).ToListAsync();
|
||||
var oldPermIds = dbOldRolePerms.Select(rp => rp.FeaturePermissionId).ToList();
|
||||
|
||||
// 8d. Prepare add and remove permission lists.
|
||||
var newPermissionIds = new List<Guid>();
|
||||
var revokePermissionIds = new List<Guid>();
|
||||
var employeePerms = employeePermTask.Result;
|
||||
var isOldEmployeePermissionIdExist = oldPermIds.Any(fp => employeePerms.Contains(fp));
|
||||
|
||||
void ProcessPerms(bool? enabled, List<Guid> ids)
|
||||
{
|
||||
var isOldPermissionIdExist = oldPermIds.Any(fp => ids.Contains(fp) && !employeePerms.Contains(fp));
|
||||
|
||||
if (enabled == true && !isOldPermissionIdExist) newPermissionIds.AddRange(ids);
|
||||
if (enabled == true && !isOldEmployeePermissionIdExist) newPermissionIds.AddRange(ids);
|
||||
if (enabled == false && isOldPermissionIdExist)
|
||||
revokePermissionIds.AddRange(ids);
|
||||
}
|
||||
ProcessPerms(features.Modules?.ProjectManagement?.Enabled, projectPermTask.Result);
|
||||
ProcessPerms(features.Modules?.Attendance?.Enabled, attendancePermTask.Result);
|
||||
ProcessPerms(features.Modules?.Directory?.Enabled, directoryPermTask.Result);
|
||||
ProcessPerms(features.Modules?.Expense?.Enabled, expensePermTask.Result);
|
||||
|
||||
newPermissionIds = newPermissionIds.Distinct().ToList();
|
||||
revokePermissionIds = revokePermissionIds.Distinct().ToList();
|
||||
|
||||
|
||||
// 8e. Prevent accidental loss of basic employee permissions.
|
||||
if ((features.Modules?.ProjectManagement?.Enabled == true ||
|
||||
features.Modules?.Attendance?.Enabled == true ||
|
||||
features.Modules?.Directory?.Enabled == true ||
|
||||
features.Modules?.Expense?.Enabled == true) && isOldEmployeePermissionIdExist)
|
||||
{
|
||||
revokePermissionIds = revokePermissionIds.Where(pid => !employeePerms.Contains(pid)).ToList();
|
||||
}
|
||||
|
||||
// 8f. Prepare permission-mapping records to add/remove.
|
||||
var mappingsToRemove = dbOldRolePerms.Where(rp => revokePermissionIds.Contains(rp.FeaturePermissionId)).ToList();
|
||||
var mappingsToAdd = newPermissionIds
|
||||
.Where(pid => !oldPermIds.Contains(pid))
|
||||
.Select(pid => new RolePermissionMappings { ApplicationRoleId = rootRoleId, FeaturePermissionId = pid })
|
||||
.ToList();
|
||||
|
||||
if (mappingsToAdd.Any())
|
||||
{
|
||||
context.RolePermissionMappings.AddRange(mappingsToAdd);
|
||||
_logger.LogInfo("Permissions granted: {Count} for Role={RoleId}", mappingsToAdd.Count, rootRoleId);
|
||||
}
|
||||
if (mappingsToRemove.Any())
|
||||
{
|
||||
context.RolePermissionMappings.RemoveRange(mappingsToRemove);
|
||||
_logger.LogInfo("Permissions revoked: {Count} for Role={RoleId}", mappingsToRemove.Count, rootRoleId);
|
||||
}
|
||||
|
||||
var _cache = scope.ServiceProvider.GetRequiredService<CacheUpdateHelper>();
|
||||
await _cache.ClearAllEmployeesFromCacheByTenantId(tenant.Id);
|
||||
|
||||
var _masteData = scope.ServiceProvider.GetRequiredService<MasterDataService>();
|
||||
|
||||
if (features.Modules?.ProjectManagement?.Enabled ?? false)
|
||||
{
|
||||
var workCategoryMaster = _masteData.GetWorkCategoriesData(tenant.Id);
|
||||
var workStatusMaster = _masteData.GetWorkStatusesData(tenant.Id);
|
||||
|
||||
var workCategoryTask = Task.Run(async () =>
|
||||
{
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await _context.WorkCategoryMasters.AnyAsync(wc => wc.IsSystem && wc.TenantId == tenant.Id);
|
||||
});
|
||||
var workStatusTask = Task.Run(async () =>
|
||||
{
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
return await _context.WorkStatusMasters.AnyAsync(ws => ws.IsSystem && ws.TenantId == tenant.Id);
|
||||
});
|
||||
|
||||
await Task.WhenAll(workCategoryTask, workStatusTask);
|
||||
|
||||
var workCategoryExist = workCategoryTask.Result;
|
||||
var workStatusExist = workStatusTask.Result;
|
||||
if (!workCategoryExist)
|
||||
{
|
||||
context.WorkCategoryMasters.AddRange(workCategoryMaster);
|
||||
}
|
||||
if (!workStatusExist)
|
||||
{
|
||||
context.WorkStatusMasters.AddRange(workStatusMaster);
|
||||
}
|
||||
}
|
||||
if (features.Modules?.Expense?.Enabled ?? false)
|
||||
{
|
||||
var expensesTypeMaster = _masteData.GetExpensesTypeesData(tenant.Id);
|
||||
var paymentModeMatser = _masteData.GetPaymentModesData(tenant.Id);
|
||||
|
||||
var expensesTypeTask = Task.Run(async () =>
|
||||
{
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
var expensesTypeNames = expensesTypeMaster.Select(et => et.Name).ToList();
|
||||
return await _context.ExpensesTypeMaster.AnyAsync(et => expensesTypeNames.Contains(et.Name) && et.TenantId == tenant.Id);
|
||||
});
|
||||
var paymentModeTask = Task.Run(async () =>
|
||||
{
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
var paymentModeNames = paymentModeMatser.Select(py => py.Name).ToList();
|
||||
return await _context.PaymentModeMatser.AnyAsync(py => paymentModeNames.Contains(py.Name) && py.TenantId == tenant.Id);
|
||||
});
|
||||
|
||||
await Task.WhenAll(expensesTypeTask, paymentModeTask);
|
||||
|
||||
var expensesTypeExist = expensesTypeTask.Result;
|
||||
var paymentModeExist = paymentModeTask.Result;
|
||||
if (!expensesTypeExist)
|
||||
{
|
||||
context.ExpensesTypeMaster.AddRange(expensesTypeMaster);
|
||||
}
|
||||
if (!paymentModeExist)
|
||||
{
|
||||
context.PaymentModeMatser.AddRange(paymentModeMatser);
|
||||
}
|
||||
}
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
await transaction.CommitAsync();
|
||||
|
||||
_logger.LogInfo("Tenant subscription and permissions updated: Tenant={TenantId}", tenantId);
|
||||
|
||||
return ApiResponse<object>.SuccessResponse(newSubscription, "Tenant subscription successfully updated", 200);
|
||||
}
|
||||
catch (DbUpdateException dbEx)
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
_logger.LogError(dbEx, "Database exception updating subscription for TenantId={TenantId}", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Internal database error", ExceptionMapper(dbEx), 500);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await transaction.RollbackAsync();
|
||||
_logger.LogError(ex, "General exception for TenantId={TenantId}", tenantId);
|
||||
return ApiResponse<object>.ErrorResponse("Internal error occurred", ExceptionMapper(ex), 500);
|
||||
}
|
||||
}
|
||||
|
||||
#region =================================================================== Helper Functions ===================================================================
|
||||
private static object ExceptionMapper(Exception ex)
|
||||
{
|
||||
return new
|
||||
{
|
||||
Message = ex.Message,
|
||||
StackTrace = ex.StackTrace,
|
||||
Source = ex.Source,
|
||||
InnerException = new
|
||||
{
|
||||
Message = ex.InnerException?.Message,
|
||||
StackTrace = ex.InnerException?.StackTrace,
|
||||
Source = ex.InnerException?.Source,
|
||||
}
|
||||
};
|
||||
}
|
||||
private bool IsBase64String(string? input)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string base64Data = input;
|
||||
const string dataUriMarker = "base64,";
|
||||
int markerIndex = input.IndexOf(dataUriMarker, StringComparison.Ordinal);
|
||||
|
||||
// If the marker is found, extract the actual Base64 data
|
||||
if (markerIndex >= 0)
|
||||
{
|
||||
base64Data = input.Substring(markerIndex + dataUriMarker.Length);
|
||||
}
|
||||
|
||||
// Now, validate the extracted payload
|
||||
base64Data = base64Data.Trim();
|
||||
|
||||
// Check for valid length (must be a multiple of 4) and non-empty
|
||||
if (base64Data.Length == 0 || base64Data.Length % 4 != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// The most reliable test is to simply try to convert it.
|
||||
// The .NET converter is strict and will throw a FormatException
|
||||
// for invalid characters or incorrect padding.
|
||||
try
|
||||
{
|
||||
Convert.FromBase64String(base64Data);
|
||||
return true;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
// The string is not a valid Base64 payload.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the creation and persistence of SubscriptionPlanDetails for a particular frequency.
|
||||
/// </summary>
|
||||
private async Task<ApiResponse<SubscriptionPlanVM>> CreateSubscriptionPlanDetails(SubscriptionPlanDetailsDto? model, SubscriptionPlan plan, Employee loggedInEmployee, PLAN_FREQUENCY frequency)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
_logger.LogInfo("No plan detail provided for {Frequency} - skipping.", frequency);
|
||||
return ApiResponse<SubscriptionPlanVM>.ErrorResponse("Invalid", "No data provided for this frequency", 400);
|
||||
}
|
||||
|
||||
await using var _dbContext = await _dbContextFactory.CreateDbContextAsync();
|
||||
|
||||
// Fetch currency master record
|
||||
var currencyMaster = await _dbContext.CurrencyMaster.AsNoTracking().FirstOrDefaultAsync(c => c.Id == model.CurrencyId);
|
||||
if (currencyMaster == null)
|
||||
{
|
||||
_logger.LogWarning("Currency with Id {CurrencyId} not found for plan {PlanId}/{Frequency}.", model.CurrencyId, plan.Id, frequency);
|
||||
return ApiResponse<SubscriptionPlanVM>.ErrorResponse("Currency not found", "Specified currency not found", 404);
|
||||
}
|
||||
|
||||
// Map to entity and create related feature details
|
||||
var planDetails = _mapper.Map<SubscriptionPlanDetails>(model);
|
||||
var features = _mapper.Map<FeatureDetails>(model.Features);
|
||||
|
||||
try
|
||||
{
|
||||
await _featureDetailsHelper.AddFeatureDetails(features);
|
||||
_logger.LogInfo("FeatureDetails for plan {PlanId}/{Frequency} saved in MongoDB.", plan.Id, frequency);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception occurred while saving features in MongoDB for {PlanId}/{Frequency}.", plan.Id, frequency);
|
||||
return ApiResponse<SubscriptionPlanVM>.ErrorResponse("Internal error occurred", ExceptionMapper(ex), 500);
|
||||
}
|
||||
|
||||
planDetails.PlanId = plan.Id;
|
||||
planDetails.Frequency = frequency;
|
||||
planDetails.FeaturesId = features.Id;
|
||||
planDetails.CreatedById = loggedInEmployee.Id;
|
||||
planDetails.CreateAt = DateTime.UtcNow;
|
||||
|
||||
_dbContext.SubscriptionPlanDetails.Add(planDetails);
|
||||
|
||||
// Prepare view model
|
||||
var VM = _mapper.Map<SubscriptionPlanVM>(planDetails);
|
||||
VM.PlanName = plan.PlanName;
|
||||
VM.Description = plan.Description;
|
||||
VM.Features = features;
|
||||
VM.Currency = currencyMaster;
|
||||
|
||||
try
|
||||
{
|
||||
await _dbContext.SaveChangesAsync();
|
||||
_logger.LogInfo("Subscription plan details for {PlanId}/{Frequency} saved to SQL.", plan.Id, frequency);
|
||||
}
|
||||
catch (DbUpdateException dbEx)
|
||||
{
|
||||
_logger.LogError(dbEx, "Database exception occurred while saving plan details for {PlanId}/{Frequency}.", plan.Id, frequency);
|
||||
return ApiResponse<SubscriptionPlanVM>.ErrorResponse("Internal error occurred", ExceptionMapper(dbEx), 500);
|
||||
}
|
||||
|
||||
return ApiResponse<SubscriptionPlanVM>.SuccessResponse(VM, "Success", 200);
|
||||
}
|
||||
|
||||
private async Task ClearPermissionForTenant(Guid tenantId)
|
||||
{
|
||||
await using var _context = await _dbContextFactory.CreateDbContextAsync();
|
||||
using var scope = _serviceScopeFactory.CreateScope();
|
||||
|
||||
var _cache = scope.ServiceProvider.GetRequiredService<CacheUpdateHelper>();
|
||||
var _cacheLogger = scope.ServiceProvider.GetRequiredService<ILoggingService>();
|
||||
|
||||
var employeeIds = await _context.Employees.Where(e => e.TenantId == tenantId).Select(e => e.Id).ToListAsync();
|
||||
await _cache.ClearAllEmployeesFromCacheByEmployeeIds(employeeIds, tenantId);
|
||||
_cacheLogger.LogInfo("{EmployeeCount} number of employee deleted", employeeIds.Count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@ -48,7 +48,15 @@
|
||||
},
|
||||
"MongoDB": {
|
||||
"SerilogDatabaseUrl": "mongodb://localhost:27017/DotNetLogs",
|
||||
"ConnectionString": "mongodb://localhost:27017/MarcoBMS_Caches?socketTimeoutMS=500&serverSelectionTimeoutMS=500&connectTimeoutMS=500",
|
||||
"ModificationConnectionString": "mongodb://devuser:DevPass123@147.93.98.152:27017/MarcoBMSLocalDev?authSource=admin&eplicaSet=rs01&directConnection=true"
|
||||
"ConnectionString": "mongodb://devuser:DevPass123@147.93.98.152:27017/MarcoBMSCacheLocalDev?authSource=admin&replicaSet=rs01",
|
||||
"ModificationConnectionString": "mongodb://devuser:DevPass123@147.93.98.152:27017/MarcoBMSLocalDev?authSource=admin&replicaSet=rs01&directConnection=true"
|
||||
},
|
||||
"Razorpay": {
|
||||
"Key": "rzp_test_RXCzgEcXucbuAi",
|
||||
"Secret": "YNAVBXxRsDg8Oat4M1C3m09W"
|
||||
},
|
||||
"Encryption": {
|
||||
"PaymentKey": "+V47lEWiolUZOUZcHq/3M6SEd3kPraGJpnJ+K5ni0Oo=",
|
||||
"CollectionKey": "9bVvYrbL1uB+v6TjWRsJ8N8VFI8rE7e7hVhVSKg3JZU="
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user