📦 SafetyEquipmentsController.cs Documentation

Assembly: IrbyImaging.UI
Namespace: IrbyImaging.Controllers
Author: kvamshi
Created: 03-31-2022
Last Modified: 05-17-2022


📋 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Class Definition & Inheritance
  4. Constructor
  5. API Endpoints Overview
  6. Key Functional Areas
  7. View Models & Data Models
  8. Error Handling & Return Types
  9. Helper Methods & Utilities
  10. Third‑party Integrations & Configuration
  11. Sample Code Blocks & Usage Examples
  12. UML Class & Sequence Diagrams
  13. Conclusion

🔍 Overview & Purpose

The SafetyEquipmentsController manages all HTTP requests related to Safety Equipment entities in the Irby Imaging application. It supports typical CRUD operations (Create, Read, Update, Delete) and tracks asset history. Built upon ASP.NET Core MVC, it delegates business logic to an IAssetManager and uses mapping services (ISafetyEquipmentMapper) to convert between domain models and view models.

Primary responsibilities

  • Render list/detail views
  • Handle form submissions for create/edit/delete
  • Record and display history/audit trails

⚙️ Dependencies & Technologies

Technology / Library Purpose
ASP.NET Core MVC Web framework for controllers & views
Microsoft.AspNetCore.Authorization Enforce security policies (commented out by default)
IrbyImaging.BusinessLogic Contains IAssetManager for business operations
IrbyImaging.Services Mapping between domain & view models
IrbyImaging.DomainClasses Domain entities (e.g., SafetyEquipment)
IrbyImaging.Models View models for MVC interactions
IrbyImaging.Utility Utility types (Responses, AssetStatus enum, etc.)
Microsoft.Extensions.Configuration Access to configuration (e.g., connection strings)
IrbyContext (Entity Framework DbContext) Database context for direct queries if needed

🏛 Class Definition & Inheritance

namespace IrbyImaging.Controllers
{
    // [Authorize(Policy = "SafetyAdminOrAdminPolicy")]
    public class SafetyEquipmentsController : BaseController
    {
        // Fields & constructor...
        // Action methods...
    }
}
  • BaseController
    Provides common functionality (e.g., user context, configuration) to all controllers.
  • Authorize Attribute (commented out)
    When enabled, restricts access to users in the “Safety Admin” or “Admin” roles.

🔧 Constructor

public SafetyEquipmentsController(
    IAssetManager manager,
    ISafetyEquipmentMapper mapper,
    IrbyContext context,
    IConfiguration configuration
) : base(context, configuration)
{
    _manager = manager;
    _mapper = mapper;
    _context = context;
    _configuration = configuration;
}
  • IAssetManager _manager: Handles CRUD + history persistence.
  • ISafetyEquipmentMapper _mapper: Transforms between domain entities and view models.
  • IrbyContext _context: EF Core database context (inherited by BaseController).
  • IConfiguration _configuration: Application settings, DI‑injected.

🚀 API Endpoints Overview

Method HTTP Verb Route Purpose
Index GET /SafetyEquipments List and filter safety equipments
Details/{id} GET /SafetyEquipments/Details/{id} Show detail of a single equipment
Create GET /SafetyEquipments/Create Display creation form
CreateAndSaveSafetyEquipment POST /SafetyEquipments/CreateAndSaveSafetyEquipment Process new equipment creation
Edit/{id} GET /SafetyEquipments/Edit/{id} Display edit form
Edit POST /SafetyEquipments/Edit/{id} Save edits
Delete/{id} GET /SafetyEquipments/Delete/{id} Confirm deletion
Delete POST /SafetyEquipments/Delete/{id} Process deletion (logical/history update)
History/{id} GET /SafetyEquipments/History/{id} Show audit history for an equipment

✨ Key Functional Areas

  1. Listing & Searching

    • Index(string search, AssetStatus status)
    • Filters by search term & status (e.g., Active, Retired).
  2. Details View

    • Details(Guid? id)
    • Retrieves single equipment record; returns 404 if not found.
  3. Create New Equipment

    • GET /Create: Prepares blank view model (with optional OwnerId).
    • POST /CreateAndSaveSafetyEquipment: Validates model, maps to domain entity, calls _manager.AddNewAssetWithHistory_Async, handles success/failure.
  4. Edit Existing Equipment

    • GET /Edit/{id}: Loads existing data.
    • POST /Edit/{id}: Maps view model → entity, calls _manager.UpdateAssetAndHistory_Async.
  5. Delete (Soft‑Delete with History)

    • GET /Delete/{id}: Pre‑populate “Reason” & “Notes” fields in view.
    • POST /Delete: Similar to Edit, but calls UpdateAssetAndHistory_Async with deletion reason.
  6. History / Audit Trail

    • History(Guid? id): Retrieves list of revisions and base details, shows unified view model.

🗂 View Models & Data Models

ViewModel Usage
SafetyEquipmentListViewModel For Index listing with filter & status.
SafetyEquipmentDetailViewModel For Details & embedded in History view.
SafetyEquipmentCreateViewModel Blank or postback in Create GET/POST.
SafetyEquipmentEditViewModel For both Edit and Delete actions.
SafetyEquipmentHistoryListViewModel Aggregates revision history + current detail.

Domain Entity: SafetyEquipment (in IrbyImaging.DomainClasses)

  • Fields: Id, Name, OwnerId, Status, Notes, etc.

🚨 Error Handling & Return Types

  • All action methods return IActionResult.
  • NotFound() (404) when id is null or entity not found.
  • ModelState.IsValid
    • If false, redisplay the view with validation messages.
  • Manager calls return (Responses response, string message)
    • Responses.Failure: Show message in view’s ErrorMessage.
    • Responses.Success: Redirect to appropriate action (Index, Create, etc.).

🔄 Helper Methods & Utilities

  • Mapping
    _mapper.GenerateSafetyEquipmentListViewModel(...)
    _mapper.CreateViewModelToSafetyEquipment(...)
    _mapper.EditViewModelToSafetyEquipment(...)
    
  • History Tracking
    • Manager methods:
      • AddNewAssetWithHistory_Async
      • UpdateAssetAndHistory_Async
      • GetHistoryByAssetId_Async

🔗 Third‑party Integrations & Configuration

  • Entity Framework Core via IrbyContext.
  • IConfiguration: Access appsettings.json for DB connections or feature flags.
  • [Authorize(Policy="SafetyAdminOrAdminPolicy")] can secure endpoints via ASP.NET Core Policy-based Auth.

📝 Sample Code Blocks & Usage Examples

1. Calling Index (Filter by “Helmet” & Active status)

GET /SafetyEquipments?search=Helmet&status=Active

Controller snippet:

public async Task<IActionResult> Index(string search, AssetStatus status)
{
    var items = await _manager.GetSafetyEquipments_Async(search);
    var vm = _mapper.GenerateSafetyEquipmentListViewModel(items, status);
    return View(vm);
}

2. Creating a New Safety Equipment

POST /SafetyEquipments/CreateAndSaveSafetyEquipment
Content-Type: application/x-www-form-urlencoded

Name=Gloves&OwnerId=1234-5678-90ab-cdef&Status=Active
  • Validates ModelState.
  • On success: redirects back to Create (for bulk entry).
  • On failure: redisplay with ErrorMessage.

🏷 UML Class & Sequence Diagrams

Class Diagram (Mermaid)

classDiagram
    class SafetyEquipmentsController {
        - IAssetManager _manager
        - ISafetyEquipmentMapper _mapper
        - IrbyContext _context
        - IConfiguration _configuration
        + Index(string, AssetStatus): IActionResult
        + Details(Guid?): IActionResult
        + Create(Guid): IActionResult
        + CreateAndSaveSafetyEquipment(SafetyEquipmentCreateViewModel): IActionResult
        + Edit(Guid?): IActionResult
        + Edit(Guid, SafetyEquipmentEditViewModel): IActionResult
        + Delete(Guid?): IActionResult
        + Delete(Guid, SafetyEquipmentEditViewModel): IActionResult
        + History(Guid?): IActionResult
    }
    SafetyEquipmentsController --|> BaseController

Sequence Diagram for Create

sequenceDiagram
    participant U as User (Browser)
    participant C as SafetyEquipmentsController
    participant M as IAssetManager
    participant P as ISafetyEquipmentMapper

    U->>C: POST /CreateAndSaveSafetyEquipment(viewModel)
    C->>P: CreateViewModelToSafetyEquipment(viewModel)
    activate P
    P-->>C: domainEntity
    deactivate P
    C->>M: AddNewAssetWithHistory_Async(entity, UserName)
    activate M
    M-->>C: (Responses.Success, null)
    deactivate M
    C-->>U: RedirectToAction(Create?OwnerId=...)

🏁 Conclusion

The SafetyEquipmentsController orchestrates all interactions for Safety Equipment assets: listing, details, creation, editing, deletion (with audit history), and viewing change logs. By leveraging dependency‑injected services (IAssetManager, ISafetyEquipmentMapper), it maintains a clean separation of concerns:

  • Controller: Handles HTTP requests/responses, validation, and view selection.
  • Manager: Executes business logic & persistence.
  • Mapper: Transforms domain models ↔ view models.

This design promotes testability, maintainability, and adherence to the Single Responsibility Principle. 🚀