JobsController.cs

# πŸ“„ JobsController.cs Documentation

> **File:** `IrbyImaging/Controllers/JobsController.cs`  
> **Assembly:** IrbyImaging.UI  
> **Author:** kvamshi  
> **Created:** 03‑31‑2022  
> **Last Modified:** 05‑17‑2022  

---

## πŸ“‘ Table of Contents
1. [Overview & Purpose](#overview--purpose)  
2. [Dependencies & Technologies](#dependencies--technologies)  
3. [Key Functional Areas](#key-functional-areas)  
   - [Index Action](#1-index-action)  
   - [Details Action](#2-details-action)  
4. [Data Models & ViewModels](#data-models--viewmodels)  
5. [Utilities & Helper Methods](#utilities--helper-methods)  
6. [Error Handling & Return Types](#error-handling--return-types)  
7. [API Endpoints Overview](#api-endpoints-overview)  
8. [Third‑party Integrations](#third-party-integrations)  
9. [Sample Code & Usage Examples](#sample-code--usage-examples)  
10. [UML Diagrams](#uml-diagrams)  
11. [Conclusion](#conclusion)  

---

## πŸ” Overview & Purpose
The **JobsController** is an ASP.NET Core MVC controller responsible for:
- Displaying a **list** of jobs (`Index` action)  
- Showing **detailed** information for a single job (`Details` action)  

It connects the UI to the **business logic** (`IJobManager`), **data context** (`IrbyContext`), and **configuration** (`IConfiguration`).  

**Intended Use:**  
- Render Razor Views for job listings and job details.  
- Leverage asynchronous patterns (`async/await`) to fetch data efficiently.  

---

## πŸ”§ Dependencies & Technologies
| Category         | Technology / Reference                          |
|------------------|-------------------------------------------------|
| Framework        | ASP.NET Core MVC                                |
| Data Access      | Entity Framework Core via `IrbyContext`         |
| DI & Config      | `IServiceCollection` & `IConfiguration`         |
| Business Logic   | `IJobManager` (in `IrbyImaging.BusinessLogic`)   |
| Utility & Models | `IrbyImaging.Utility`, `IrbyImaging.Models`, `IrbyImaging.DomainClasses` |
| Authorization    | `[Authorize]` (commented out – can be enabled)  |

---

## πŸš€ Key Functional Areas

### 1. Index Action
```csharp
public async Task<IActionResult> Index(string search)
  • Purpose: Retrieves a collection of jobs, optionally filtered by a search string.
  • Flow:
    1. Call _manager.GetJobs_Async(search) to fetch raw job DTOs.
    2. Map each DTO into a JobDetails view model.
    3. Store the list in ViewBag.Jobs for the Razor view.
    4. Return the Index view.

Highlights:

  • Mapping Logic: Transforms statuses (enum JobStatus) to string.
  • ViewBag Usage: Temporary container for passing the model to the view.
var Jobs = await _manager.GetJobs_Async(search);
foreach (var job in Jobs) {
    var rec = new JobDetails {
        JobId             = job.JobId,
        JdeNumber         = job.JdeNumber,
        Name              = job.Name,
        SuperintendentId  = job.SuperintendentId,
        Superintendent    = job.SuperintendentName,
        // ... other properties ...
        JobStatus         = ((JobStatus)job.Status).ToString()
    };
    jobs.Add(rec);
}
ViewBag.Jobs = jobs;
return View(jobs);

2. Details Action

public async Task<IActionResult> Details(Guid? id)
  • Purpose: Shows full details of a single job, including associated employees and assets.
  • Flow:
    1. Validate id is not null β†’ return NotFound() if it is.
    2. Fetch the job via _manager.GetJobById_Async(id).
    3. Split employees into current vs former (EmployeeStatus).
    4. Aggregate all employee assets, sort by make/model.
    5. Populate ViewBag with:
      • CurrentEmployees
      • FormerEmployees
      • Assets (sorted)
      • AssetCount
    6. Return the Details view with the job model.
if (id == null) return NotFound();
var job = await _manager.GetJobById_Async(id);
// classify employees
var currentEmployees = job.Employees.Where(e => e.Status == EmployeeStatus.Active).ToList();
var formerEmployees  = job.Employees.Where(e => e.Status != EmployeeStatus.Active).ToList();
// collect assets
var assets = job.Employees.SelectMany(e => e.Assets ?? Enumerable.Empty<Asset>())
                         .OrderBy(a => a.Model.Make.Name)
                         .ThenBy(a => a.Model.Name)
                         .ToList();
ViewBag.CurrentEmployees = currentEmployees;
ViewBag.FormerEmployees  = formerEmployees;
ViewBag.Assets           = assets;
ViewBag.AssetCount       = assets.Count;
return View(job);

πŸ— Data Models & ViewModels

1. JobDetails ViewModel

Property Type Description
JobId Guid Unique identifier
JdeNumber string JDE system job number
Name string Job title/name
SuperintendentId Guid? FK to Superintendent
ProjectEstimatorId Guid? FK to Project Estimator
ManagerId Guid? FK to Manager
CustomerId Guid? FK to Customer
FieldOfficeId Guid? FK to Field Office
Superintendent string Name of Superintendent
ProjectEstimator string Name of Project Estimator
Manager string Name of Manager
Customer string Name of Customer
FieldOffice string Field Office name/code
JobType, ContractType string Various job/contract classifications
WorkType string Scope of work
GeoRegionCode string Geographic region code
GeoRegionDescription string Region description
RevenueDerivative string Revenue category
DateActualStart/Complete DateTime? Actual start/finish dates
DatePlannedStart/Complete DateTime? Planned start/finish dates
JobStatus string Textual status (Active, Closed, etc.)

πŸ›  Utilities & Helper Methods

  • BaseController: Provides common functionality (e.g., user context, logging, configuration).
  • IJobManager: Abstracts business logic related to Job retrieval & mapping.
  • EmployeeStatus Enum: Used to classify Active vs Former employees.
  • LINQ: For sorting & filtering collections of employees/assets.

🚨 Error Handling & Return Types

Condition Action Return Type
search any (nullable str) Fetch list Task<IActionResult> (View)
id == null in Details Parameter missing NotFound() (404)
job == null after lookup Not found in DB NotFound() (404)
Normal flow Render view View(...)

🌐 API Endpoints Overview

HTTP Method Route Action Description
GET /Jobs Index List all jobs (optionally with ?search=)
GET /Jobs/Details/{id} Details Show details for a single job

Note: No JSON APIs are exposed hereβ€”this is strictly MVC/Razor-based.


πŸ”Œ Third‑party Integrations

  • Entity Framework Core for ORM (via IrbyContext).
  • Microsoft.Extensions.Configuration for app settings.
  • Potential for Authorization policies (commented [Authorize(Policy = "AllAuthorizedUsersPolicy")]).

πŸ’‘ Sample Code & Usage Examples

1. Registering the Controller & Services

// Startup.cs -> ConfigureServices(IServiceCollection services)
services.AddDbContext<IrbyContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
);
services.AddScoped<IJobManager, JobManager>();
services.AddControllersWithViews();

2. Calling the Index Action

<!-- Views/Jobs/Index.cshtml -->
@{
    ViewBag.Title = "Job List";
    var jobs = (List<JobDetails>)ViewBag.Jobs;
}
<h2>All Jobs</h2>
<form method="get">
  <input type="text" name="search" placeholder="Search jobs..." />
  <button type="submit">πŸ” Search</button>
</form>
<table>
  <thead><tr><th>JDE #</th><th>Name</th><th>Status</th></tr></thead>
  <tbody>
  @foreach(var job in jobs) {
    <tr>
      <td>@job.JdeNumber</td>
      <td>
        <a asp-action="Details" asp-route-id="@job.JobId">@job.Name</a>
      </td>
      <td>@job.JobStatus</td>
    </tr>
  }
  </tbody>
</table>

3. Calling the Details Action

<!-- Views/Jobs/Details.cshtml -->
@model IrbyImaging.DomainClasses.Job
<h2>Job Details: @Model.Name</h2>
<h3>Employees</h3>
<ul>
@foreach(var emp in (List<Employee>)ViewBag.CurrentEmployees){
  <li>@emp.FullName (Active)</li>
}
@foreach(var emp in (List<Employee>)ViewBag.FormerEmployees){
  <li>@emp.FullName (Former)</li>
}
</ul>
<h3>Assets (@ViewBag.AssetCount)</h3>
<ul>
@foreach(var asset in (List<Asset>)ViewBag.Assets){
  <li>@asset.Model.Make.Name - @asset.Model.Name</li>
}
</ul>

πŸ–₯ UML Diagrams

1. Sequence Diagram

sequenceDiagram
    participant Browser
    participant Controller as JobsController
    participant Manager   as IJobManager
    participant DbContext as IrbyContext

    Browser->>Controller: GET /Jobs?search=term
    Controller->>Manager: GetJobs_Async("term")
    Manager->>DbContext: Query Jobs
    DbContext-->>Manager: Job Entities
    Manager-->>Controller: Job DTOs
    Controller-->>Browser: Render Index view

    Browser->>Controller: GET /Jobs/Details/{id}
    Controller->>Manager: GetJobById_Async(id)
    Manager->>DbContext: Query Job + related Employees/Assets
    DbContext-->>Manager: Aggregated Job Entity
    Manager-->>Controller: Job Entity
    Controller-->>Browser: Render Details view

2. Class Diagram

classDiagram
    BaseController <|-- JobsController
    JobsController o-- IJobManager
    JobsController o-- IrbyContext
    JobsController o-- IConfiguration
    JobsController --> JobDetails

    class JobDetails {
      +Guid JobId
      +string JdeNumber
      +string Name
      +Guid? SuperintendentId
      +string Superintendent
      +DateTime? DateActualStart
      +DateTime? DateActualComplete
      +string JobStatus
      ...
    }

🏁 Conclusion

The JobsController is a straightforward but flexible MVC component that:

  • Fetches and maps domain data via a service layer.
  • Organizes employees and assets for detailed reporting.
  • Handles missing/invalid input gracefully.
  • Leverages standard ASP.NET Core patterns for DI, async operations, and Razor views.

By following this guide, you can easily extend the controller, introduce new filters, or swap out the business logic without touching the UI layer. πŸš€


---

**Happy Coding!** πŸŽ‰  

Generated by AI Assistant on behalf of IrbyImaging.UI documentation needs.