Compare commits

...

3 Commits

18 changed files with 10380 additions and 56 deletions

View File

@ -68,6 +68,7 @@ namespace Marco.Pms.DataAccess.Data
public DbSet<Document> Documents { get; set; }
public DbSet<TicketTag> TicketTags { get; set; }
public DbSet<WorkCategoryMaster> WorkCategoryMasters { get; set; }
public DbSet<WorkStatusMaster> WorkStatusMasters { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<ContactCategoryMaster> ContactCategoryMasters { get; set; }
public DbSet<ContactEmail> ContactsEmails { get; set; }

View File

@ -0,0 +1,102 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Marco.Pms.DataAccess.Migrations
{
/// <inheritdoc />
public partial class Added_Apporved_By_In_TaskAllocation_Table : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ApprovedById",
table: "TaskAllocations",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
migrationBuilder.AddColumn<DateTime>(
name: "ApprovedDate",
table: "TaskAllocations",
type: "datetime(6)",
nullable: true);
migrationBuilder.AddColumn<Guid>(
name: "ReportedById",
table: "TaskAllocations",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
migrationBuilder.AddColumn<int>(
name: "TaskStatus",
table: "TaskAllocations",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateIndex(
name: "IX_TaskAllocations_ApprovedById",
table: "TaskAllocations",
column: "ApprovedById");
migrationBuilder.CreateIndex(
name: "IX_TaskAllocations_ReportedById",
table: "TaskAllocations",
column: "ReportedById");
migrationBuilder.AddForeignKey(
name: "FK_TaskAllocations_Employees_ApprovedById",
table: "TaskAllocations",
column: "ApprovedById",
principalTable: "Employees",
principalColumn: "Id");
migrationBuilder.AddForeignKey(
name: "FK_TaskAllocations_Employees_ReportedById",
table: "TaskAllocations",
column: "ReportedById",
principalTable: "Employees",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TaskAllocations_Employees_ApprovedById",
table: "TaskAllocations");
migrationBuilder.DropForeignKey(
name: "FK_TaskAllocations_Employees_ReportedById",
table: "TaskAllocations");
migrationBuilder.DropIndex(
name: "IX_TaskAllocations_ApprovedById",
table: "TaskAllocations");
migrationBuilder.DropIndex(
name: "IX_TaskAllocations_ReportedById",
table: "TaskAllocations");
migrationBuilder.DropColumn(
name: "ApprovedById",
table: "TaskAllocations");
migrationBuilder.DropColumn(
name: "ApprovedDate",
table: "TaskAllocations");
migrationBuilder.DropColumn(
name: "ReportedById",
table: "TaskAllocations");
migrationBuilder.DropColumn(
name: "TaskStatus",
table: "TaskAllocations");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Marco.Pms.DataAccess.Migrations
{
/// <inheritdoc />
public partial class Added_ParentTask_In_WorkArea_Table : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ParentTaskId",
table: "WorkItems",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ParentTaskId",
table: "WorkItems");
}
}
}

View File

@ -0,0 +1,81 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Marco.Pms.DataAccess.Migrations
{
/// <inheritdoc />
public partial class Added_WorkStatusMaster_Table_And_Forigne_Key_In_TaskAllocation : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TaskStatus",
table: "TaskAllocations");
migrationBuilder.AddColumn<Guid>(
name: "WorkStatusId",
table: "TaskAllocations",
type: "char(36)",
nullable: true,
collation: "ascii_general_ci");
migrationBuilder.CreateTable(
name: "WorkStatusMasters",
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: false)
.Annotation("MySql:CharSet", "utf8mb4"),
IsSystem = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_WorkStatusMasters", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_TaskAllocations_WorkStatusId",
table: "TaskAllocations",
column: "WorkStatusId");
migrationBuilder.AddForeignKey(
name: "FK_TaskAllocations_WorkStatusMasters_WorkStatusId",
table: "TaskAllocations",
column: "WorkStatusId",
principalTable: "WorkStatusMasters",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_TaskAllocations_WorkStatusMasters_WorkStatusId",
table: "TaskAllocations");
migrationBuilder.DropTable(
name: "WorkStatusMasters");
migrationBuilder.DropIndex(
name: "IX_TaskAllocations_WorkStatusId",
table: "TaskAllocations");
migrationBuilder.DropColumn(
name: "WorkStatusId",
table: "TaskAllocations");
migrationBuilder.AddColumn<int>(
name: "TaskStatus",
table: "TaskAllocations",
type: "int",
nullable: false,
defaultValue: 0);
}
}
}

View File

@ -28,6 +28,12 @@ namespace Marco.Pms.DataAccess.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<Guid?>("ApprovedById")
.HasColumnType("char(36)");
b.Property<DateTime?>("ApprovedDate")
.HasColumnType("datetime(6)");
b.Property<Guid>("AssignedBy")
.HasColumnType("char(36)");
@ -43,6 +49,9 @@ namespace Marco.Pms.DataAccess.Migrations
b.Property<double>("PlannedTask")
.HasColumnType("double");
b.Property<Guid?>("ReportedById")
.HasColumnType("char(36)");
b.Property<DateTime?>("ReportedDate")
.HasColumnType("datetime(6)");
@ -52,14 +61,23 @@ namespace Marco.Pms.DataAccess.Migrations
b.Property<Guid>("WorkItemId")
.HasColumnType("char(36)");
b.Property<Guid?>("WorkStatusId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("ApprovedById");
b.HasIndex("AssignedBy");
b.HasIndex("ReportedById");
b.HasIndex("TenantId");
b.HasIndex("WorkItemId");
b.HasIndex("WorkStatusId");
b.ToTable("TaskAllocations");
});
@ -1903,6 +1921,28 @@ namespace Marco.Pms.DataAccess.Migrations
});
});
modelBuilder.Entity("Marco.Pms.Model.Master.WorkStatusMaster", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsSystem")
.HasColumnType("tinyint(1)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("WorkStatusMasters");
});
modelBuilder.Entity("Marco.Pms.Model.Projects.Building", b =>
{
b.Property<Guid>("Id")
@ -2082,6 +2122,9 @@ namespace Marco.Pms.DataAccess.Migrations
b.Property<double>("CompletedWork")
.HasColumnType("double");
b.Property<Guid?>("ParentTaskId")
.HasColumnType("char(36)");
b.Property<double>("PlannedWork")
.HasColumnType("double");
@ -2412,12 +2455,20 @@ namespace Marco.Pms.DataAccess.Migrations
modelBuilder.Entity("Marco.Pms.Model.Activities.TaskAllocation", b =>
{
b.HasOne("Marco.Pms.Model.Employees.Employee", "ApprovedBy")
.WithMany()
.HasForeignKey("ApprovedById");
b.HasOne("Marco.Pms.Model.Employees.Employee", "Employee")
.WithMany()
.HasForeignKey("AssignedBy")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Marco.Pms.Model.Employees.Employee", "ReportedBy")
.WithMany()
.HasForeignKey("ReportedById");
b.HasOne("Marco.Pms.Model.Entitlements.Tenant", "Tenant")
.WithMany()
.HasForeignKey("TenantId")
@ -2430,11 +2481,21 @@ namespace Marco.Pms.DataAccess.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Marco.Pms.Model.Master.WorkStatusMaster", "WorkStatus")
.WithMany()
.HasForeignKey("WorkStatusId");
b.Navigation("ApprovedBy");
b.Navigation("Employee");
b.Navigation("ReportedBy");
b.Navigation("Tenant");
b.Navigation("WorkItem");
b.Navigation("WorkStatus");
});
modelBuilder.Entity("Marco.Pms.Model.Activities.TaskComment", b =>

View File

@ -1,5 +1,6 @@
using System.ComponentModel.DataAnnotations.Schema;
using Marco.Pms.Model.Employees;
using Marco.Pms.Model.Master;
using Marco.Pms.Model.Projects;
using Marco.Pms.Model.Utilities;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
@ -16,19 +17,30 @@ namespace Marco.Pms.Model.Activities
public double PlannedTask { get; set; }
public double CompletedTask { get; set; }
public DateTime? ReportedDate { get; set; }
public DateTime? ApprovedDate { get; set; }
public string? Description { get; set; }
//public int? WorkItemMappingId { get; set; }
//[ForeignKey("WorkItemMappingId")]
//[ValidateNever]
//public WorkItemMapping? WorkItemMapping { get; set; }
public Guid? WorkStatusId { get; set; }
[ForeignKey("WorkStatusId")]
[ValidateNever]
public WorkStatusMaster? WorkStatus { get; set; }
public Guid AssignedBy { get; set; } //Employee Id
[ForeignKey("AssignedBy")]
[ValidateNever]
public Employee? Employee { get; set; }
public Guid? ReportedById { get; set; } //Employee Id
[ForeignKey("ReportedById")]
[ValidateNever]
public Employee? ReportedBy { get; set; }
public Guid? ApprovedById { get; set; } //Employee Id
[ForeignKey("ApprovedById")]
[ValidateNever]
public Employee? ApprovedBy { get; set; }
public Guid WorkItemId { get; set; }
[ForeignKey("WorkItemId")]
[ValidateNever]

View File

@ -0,0 +1,9 @@
namespace Marco.Pms.Model.Dtos.Activities
{
public class ApproveTaskDto
{
public Guid Id { get; set; }
public Guid WorkStatus { get; set; }
public long ApprovedTask { get; set; }
}
}

View File

@ -8,5 +8,11 @@
public List<Guid>? TaskTeam { get; set; } //Employee Ids
public Guid WorkItemId { get; set; }
}
public enum TASK_STATUS
{
PENDING_UC = 0, APPROVED = 1, SEMI_APPROVED = 2, NCR = 3
}
}

View File

@ -8,6 +8,7 @@ namespace Marco.Pms.Model.Dtos.Project
public Guid? Id { get; set; }
public Guid WorkAreaID { get; set; }
public Guid WorkCategoryId { get; set; }
public Guid? ParentTaskId { get; set; }
public Guid ActivityID { get; set; }
public int PlannedWork { get; set; }
public int CompletedWork { get; set; }

View File

@ -55,6 +55,7 @@ namespace Marco.Pms.Model.Mapper
Id = model.Id != null ? model.Id.Value : Guid.Empty,
ActivityId = model.ActivityID,
CompletedWork = model.CompletedWork,
ParentTaskId = model.ParentTaskId,
PlannedWork = model.PlannedWork,
WorkCategoryId = model.WorkCategoryId,
TaskDate = DateTime.Now,

View File

@ -0,0 +1,10 @@
namespace Marco.Pms.Model.Master
{
public class WorkStatusMaster
{
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public bool IsSystem { get; set; } = false;
}
}

View File

@ -23,6 +23,7 @@ namespace Marco.Pms.Model.Projects
[ForeignKey("WorkCategoryId")]
[ValidateNever]
public WorkCategoryMaster? WorkCategoryMaster { get; set; }
public Guid? ParentTaskId { get; set; }
public double PlannedWork { get; set; }
public double CompletedWork { get; set; }
public DateTime TaskDate { get; set; }

View File

@ -8,12 +8,12 @@ using Marco.Pms.Model.Projects;
using Marco.Pms.Model.Utilities;
using Marco.Pms.Model.ViewModels.Employee;
using Marco.Pms.Model.ViewModels.Projects;
using Marco.Pms.Services.Service;
using MarcoBMS.Services.Helpers;
using MarcoBMS.Services.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace MarcoBMS.Services.Controllers
{
@ -27,15 +27,19 @@ namespace MarcoBMS.Services.Controllers
private readonly ILoggingService _logger;
private readonly RolesHelper _rolesHelper;
private readonly ProjectsHelper _projectsHelper;
private readonly PermissionServices _permissionServices;
private readonly Guid Approve_Task;
public ProjectController(ApplicationDbContext context, UserHelper userHelper, ILoggingService logger, RolesHelper rolesHelper, ProjectsHelper projectHelper)
public ProjectController(ApplicationDbContext context, UserHelper userHelper, ILoggingService logger, RolesHelper rolesHelper, ProjectsHelper projectHelper, PermissionServices permissionServices)
{
_context = context;
_userHelper = userHelper;
_logger = logger;
_rolesHelper = rolesHelper;
_projectsHelper = projectHelper;
_permissionServices = permissionServices;
Approve_Task = Guid.Parse("db4e40c5-2ba9-4b6d-b8a6-a16a250ff99c");
}
[HttpGet("list/basic")]
@ -572,48 +576,75 @@ namespace MarcoBMS.Services.Controllers
}
/// <summary>
/// Creates or updates project work items (tasks) based on provided data.
/// </summary>
/// <param name="workItemDot">List of work item DTOs.</param>
/// <returns>API response with created/updated work items.</returns>
[HttpPost("task")]
public async Task<IActionResult> CreateProjectTask(List<WorkItemDot> workItemDot)
{
Guid tenantId = GetTenantId();
List<WorkItemVM> workItems = new List<WorkItemVM> { };
string responseMessage = "";
if (workItemDot != null)
if (workItemDot == null || !workItemDot.Any())
{
_logger.LogWarning("CreateProjectTask called with empty workItemDot list.");
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid details.", "Work Item Details are not valid.", 400));
}
Guid tenantId = GetTenantId();
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
var hasApproveTaskPermission = await _permissionServices.HasPermission(Approve_Task, loggedInEmployee.Id);
var workItems = new List<WorkItemVM>();
string responseMessage = ""; // Default fallback
foreach (var item in workItemDot)
{
try
{
WorkItem workItem = item.ToWorkItemFromWorkItemDto(tenantId);
if (item.Id != null)
{
//update
// Update existing work item
_context.WorkItems.Update(workItem);
await _context.SaveChangesAsync();
responseMessage = "Task Added Successfully";
responseMessage = "Task Updated Successfully";
_logger.LogInfo("Work item {WorkItemId} updated by employee {EmployeeId}", item.Id, loggedInEmployee.Id);
}
else
{
//create
_context.WorkItems.Add(workItem);
await _context.SaveChangesAsync();
responseMessage = "Task Updated Successfully";
// Check permission if task is a subtask
if (item.ParentTaskId != null && !hasApproveTaskPermission)
{
_logger.LogWarning("Employee {EmployeeId} attempted to create subtask without permission.", loggedInEmployee.Id);
return StatusCode(403, ApiResponse<object>.ErrorResponse("You don't have access", "User is forbidden to access this feature", 403));
}
var result = new WorkItemVM
// Create new work item
_context.WorkItems.Add(workItem);
responseMessage = "Task Added Successfully";
_logger.LogInfo("New work item created by employee {EmployeeId}", loggedInEmployee.Id);
}
await _context.SaveChangesAsync();
workItems.Add(new WorkItemVM
{
WorkItemId = workItem.Id,
WorkItem = workItem
};
workItems.Add(result);
});
}
var activity = await _context.ActivityMasters.ToListAsync();
var category = await _context.WorkCategoryMasters.ToListAsync();
catch (Exception ex)
{
_logger.LogError("Error processing work item with temporary ID {TempId} by employee {EmployeeId} : {Error}", item.Id ?? Guid.Empty, loggedInEmployee.Id, ex.Message);
return StatusCode(500, ApiResponse<object>.ErrorResponse("Internal server error", ex.Message, 500));
}
}
return Ok(ApiResponse<object>.SuccessResponse(workItems, responseMessage, 200));
}
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid details.", "Work Item Details are not valid.", 400));
}
[HttpDelete("task/{id}")]
public async Task<IActionResult> DeleteProjectTask(Guid id)
{

View File

@ -8,7 +8,9 @@ using Marco.Pms.Model.Projects;
using Marco.Pms.Model.Utilities;
using Marco.Pms.Model.ViewModels.Activities;
using Marco.Pms.Model.ViewModels.Employee;
using Marco.Pms.Services.Service;
using MarcoBMS.Services.Helpers;
using MarcoBMS.Services.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
@ -23,12 +25,18 @@ namespace MarcoBMS.Services.Controllers
{
private readonly ApplicationDbContext _context;
private readonly UserHelper _userHelper;
private readonly ILoggingService _logger;
private readonly PermissionServices _permissionServices;
private readonly Guid Approve_Task;
public TaskController(ApplicationDbContext context, UserHelper userHelper)
public TaskController(ApplicationDbContext context, UserHelper userHelper, ILoggingService logger, PermissionServices permissionServices)
{
_context = context;
_userHelper = userHelper;
_logger = logger;
_permissionServices = permissionServices;
Approve_Task = Guid.Parse("db4e40c5-2ba9-4b6d-b8a6-a16a250ff99c");
}
private Guid GetTenantId()
@ -84,77 +92,109 @@ namespace MarcoBMS.Services.Controllers
return Ok(ApiResponse<object>.SuccessResponse(response, "Task assignned successfully", 200));
}
/// <summary>
/// Reports progress on a specific task allocation including checklist updates and comments.
/// </summary>
/// <param name="reportTask">Task progress details submitted by the employee.</param>
/// <returns>Returns the updated task report along with checklist and comments.</returns>
[HttpPost("report")]
public async Task<IActionResult> ReportTaskProgress([FromBody] ReportTaskDto reportTask)
{
// Validate model
if (!ModelState.IsValid)
{
var errors = ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage)
.ToList();
_logger.LogWarning("Invalid model state while reporting task. Errors: {@Errors}", errors);
return BadRequest(ApiResponse<object>.ErrorResponse("Invalid data", errors, 400));
}
var tenantId = GetTenantId();
var Employee = await _userHelper.GetCurrentEmployeeAsync();
var employee = await _userHelper.GetCurrentEmployeeAsync();
var taskAllocation = await _context.TaskAllocations.Include(t => t.WorkItem).FirstOrDefaultAsync(t => t.Id == reportTask.Id);
// Get task allocation and associated work item
var taskAllocation = await _context.TaskAllocations
.Include(t => t.WorkItem)
.FirstOrDefaultAsync(t => t.Id == reportTask.Id);
var checkListIds = reportTask.CheckList != null ? reportTask.CheckList.Select(c => c.Id).ToList() : new List<Guid>();
var checkList = await _context.ActivityCheckLists.Where(c => checkListIds.Contains(c.Id)).ToListAsync();
if (taskAllocation == null)
{
_logger.LogWarning("TaskAllocation not found. TaskId: {TaskId}, EmployeeId: {EmployeeId}", reportTask.Id, employee.Id);
return BadRequest(ApiResponse<object>.ErrorResponse("No such task has been allocated.", "No such task has been allocated.", 400));
}
// Update completed work in the work item if applicable
if (taskAllocation.WorkItem != null)
{
if (taskAllocation.CompletedTask != 0)
{
taskAllocation.WorkItem.CompletedWork -= taskAllocation.CompletedTask;
}
taskAllocation.ReportedDate = reportTask.ReportedDate;
taskAllocation.CompletedTask = reportTask.CompletedTask;
taskAllocation.WorkItem.CompletedWork += reportTask.CompletedTask;
}
// Update task progress
taskAllocation.ReportedDate = reportTask.ReportedDate;
taskAllocation.ReportedById = employee.Id;
taskAllocation.CompletedTask = reportTask.CompletedTask;
// Process checklist
List<CheckListMappings> checkListMappings = new List<CheckListMappings>();
List<CheckListVM> checkListVMs = new List<CheckListVM>();
if (reportTask.CheckList != null)
if (reportTask.CheckList != null && reportTask.CheckList.Any())
{
var checkListIds = reportTask.CheckList.Select(c => c.Id).ToList();
var checkList = await _context.ActivityCheckLists
.Where(c => checkListIds.Contains(c.Id))
.ToListAsync();
foreach (var checkDto in reportTask.CheckList)
{
checkListVMs.Add(checkDto.ToCheckListVMFromReportCheckListDto(taskAllocation.WorkItem != null ? taskAllocation.WorkItem.ActivityId : Guid.Empty));
// Map checklist DTO to ViewModel
var activityId = taskAllocation.WorkItem?.ActivityId ?? Guid.Empty;
checkListVMs.Add(checkDto.ToCheckListVMFromReportCheckListDto(activityId));
// If checked, prepare mapping
if (checkDto.IsChecked)
{
var check = checkList.Find(c => c.Id == checkDto.Id);
var check = checkList.FirstOrDefault(c => c.Id == checkDto.Id);
if (check != null)
{
CheckListMappings checkListMapping = new CheckListMappings
checkListMappings.Add(new CheckListMappings
{
CheckListId = check.Id,
TaskAllocationId = reportTask.Id
};
checkListMappings.Add(checkListMapping);
});
}
}
}
}
_context.CheckListMappings.AddRange(checkListMappings);
var comment = reportTask.ToCommentFromReportTaskDto(tenantId, Employee.Id);
_context.CheckListMappings.AddRange(checkListMappings);
}
// Add task comment
var comment = reportTask.ToCommentFromReportTaskDto(tenantId, employee.Id);
_context.TaskComments.Add(comment);
await _context.SaveChangesAsync();
_logger.LogInfo("Task {TaskId} progress reported by Employee {EmployeeId}", reportTask.Id, employee.Id);
// Prepare response
var response = taskAllocation.ToReportTaskVMFromTaskAllocation();
List<TaskComment> comments = await _context.TaskComments.Where(c => c.TaskAllocationId == taskAllocation.Id).ToListAsync();
List<CommentVM> resultComments = new List<CommentVM> { };
foreach (var result in comments)
{
resultComments.Add(result.ToCommentVMFromTaskComment());
}
response.Comments = resultComments;
var comments = await _context.TaskComments
.Where(c => c.TaskAllocationId == taskAllocation.Id)
.ToListAsync();
response.Comments = comments.Select(c => c.ToCommentVMFromTaskComment()).ToList();
response.checkList = checkListVMs;
return Ok(ApiResponse<object>.SuccessResponse(response, "Task reported successfully", 200));
}
@ -300,5 +340,67 @@ namespace MarcoBMS.Services.Controllers
return NotFound(ApiResponse<object>.ErrorResponse("Task Not Found", "Task not Found", 404));
}
/// <summary>
/// Approves a task allocation by the logged-in employee.
/// </summary>
/// <param name="id">The ID of the task to approve.</param>
/// <returns>Returns success or error response based on operation outcome.</returns>
[HttpPost("approve")]
public async Task<IActionResult> ApproveTask(ApproveTaskDto approveTask)
{
// Get the current tenant ID from the logged-in user context
Guid tenantId = _userHelper.GetTenantId();
// Get the currently logged-in employee
var loggedInEmployee = await _userHelper.GetCurrentEmployeeAsync();
_logger.LogInfo("Employee {EmployeeId} is attempting to approve Task {TaskId}", loggedInEmployee.Id, approveTask.Id);
// Fetch the task allocation by ID and tenant
var taskAllocation = await _context.TaskAllocations
.Include(t => t.WorkItem)
.FirstOrDefaultAsync(t => t.Id == approveTask.Id && t.TenantId == tenantId && t.ReportedDate != null);
// If the task allocation does not exist
if (taskAllocation == null)
{
_logger.LogWarning("Task {TaskId} not found for Tenant {TenantId} by Employee {EmployeeId}", approveTask.Id, tenantId, loggedInEmployee.Id);
return NotFound(ApiResponse<object>.ErrorResponse("Task not found", "Task not found", 404));
}
// Check if the employee has permission to approve the task
var hasPermission = await _permissionServices.HasPermission(Approve_Task, loggedInEmployee.Id);
if (!hasPermission)
{
_logger.LogWarning("Employee {EmployeeId} attempted to approve Task {TaskId} without proper permissions", loggedInEmployee.Id, approveTask.Id);
return StatusCode(403, ApiResponse<object>.ErrorResponse("You don't have access", "Don't have access to take action", 403));
}
// Update completed work in the work item if applicable
if (taskAllocation.WorkItem != null)
{
if (taskAllocation.CompletedTask != 0)
{
taskAllocation.WorkItem.CompletedWork -= taskAllocation.CompletedTask;
}
taskAllocation.WorkItem.CompletedWork += approveTask.ApprovedTask;
}
// Update task allocation with approval details
taskAllocation.ApprovedById = loggedInEmployee.Id;
taskAllocation.ApprovedDate = DateTime.UtcNow;
taskAllocation.WorkStatusId = approveTask.WorkStatus;
taskAllocation.CompletedTask = approveTask.ApprovedTask;
// Save changes to the database
await _context.SaveChangesAsync();
_logger.LogInfo("Employee {EmployeeId} successfully approved Task {TaskId}", loggedInEmployee.Id, approveTask.Id);
// Return success response
return Ok(ApiResponse<object>.SuccessResponse("Task has been approved", "Task has been approved", 200));
}
}
}

View File

@ -903,11 +903,11 @@ namespace Marco.Pms.Services.Helpers
List<ContactNote> notes = new List<ContactNote>();
if (active)
{
notes = await _context.ContactNotes.Where(n => n.ContactId == contact.Id && n.IsActive && n.TenantId == tenantId).ToListAsync();
notes = await _context.ContactNotes.Include(n => n.Createdby).Where(n => n.ContactId == contact.Id && n.IsActive && n.TenantId == tenantId).ToListAsync();
}
else
{
notes = await _context.ContactNotes.Where(n => n.ContactId == contact.Id && n.TenantId == tenantId).ToListAsync();
notes = await _context.ContactNotes.Include(n => n.Createdby).Where(n => n.ContactId == contact.Id && n.TenantId == tenantId).ToListAsync();
}
var noteIds = notes.Select(n => n.Id).ToList();
List<DirectoryUpdateLog>? updateLogs = await _context.DirectoryUpdateLogs.Include(l => l.Employee).Where(l => noteIds.Contains(l.RefereanceId)).ToListAsync();