📋 TimeSheetController.cs Documentation


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Data Models & View Models
  4. Key Functional Areas
  5. Helper Methods & Utilities 🔧
  6. API Endpoints Overview 🚀
  7. Third‑party Integrations
  8. Sample Code Blocks & Usage Examples 📝
  9. Class Diagram (UML)
  10. Conclusion

📌 Overview & Purpose

The TimeSheetController is a part of the IrbyImaging web application (ASP.NET Core MVC). It manages the weekly timesheet for a set of employees by:

  • Displaying a multi-user timesheet view (Monday–Sunday).
  • Allowing navigation between weeks (Previous / Next).
  • Aggregating and rendering time entry data by TimeEntryType.
  • Supporting CRUD operations for time entries.
  • Posting bulk time data from the UI form.

This controller interacts with:

  • IrbyContext (Entity Framework Core)
  • IHttpContextAccessor for user/session info
  • IWebHostEnvironment for file/storage context
  • BlobServiceClient (Azure Blob Storage)
  • IConfiguration for app settings

It extends a custom BaseController to share common behavior (e.g., authentication).


🔗 Dependencies & Technologies

Dependency Purpose
Microsoft.AspNetCore.Mvc MVC controller base
Microsoft.AspNetCore.Http HTTP context & form handling
Microsoft.Extensions.Configuration Configuration settings
Azure.Storage.Blobs Blob storage client (unused in timesheet but injected)
IrbyImaging.BusinessLogic Business logic layer (domain services)
IrbyImaging.DomainClasses EF Core entity classes & IrbyContext
IrbyImaging.Services Application services (e.g., IUploadService)
IrbyImaging.UI.Models View models: TimeSheet, EmployeeTimeSheet
System.Data DataTable for pivoting data
System.Globalization Date formatting

🗂️ Data Models & View Models

  1. Domain Entities (EF Core)

    • Employee
    • TimeEntryType
    • TimeSheetEntry
  2. UI Models

    // Represents a single row (time‐card type) for 1 employee
    public class TimeSheet {
      public string EmployeeNumber { get; set; }
      public string EmployeeName   { get; set; }
      public string TimeCardTypeDesc { get; set; }
      public string TimeCardType     { get; set; }
      public string Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
      public string Total; 
      public string Notes;
      public string MondayYear; // Year label for header
      public List<TimeSheet> TimeEntry; // For EmployeeTimeSheet
      public string MondayTotal, TuesdayTotal, …, SundayTotal, GrandTotal;
    }
    
    // Aggregates all `TimeSheet` rows per employee
    public class EmployeeTimeSheet {
      public string EmployeeNumber, EmployeeName;
      public List<TimeSheet> TimeEntry;
      public string MondayTotal, …, SundayTotal, GrandTotal;
    }
    

🔑 Key Functional Areas

1. Index (GET)

Signature:

public ActionResult Index(string employeeId)
  • Initializes week start/end using DisplayTimeSheetHeader().
  • Populates ViewData for header labels (Mon–Sun).
  • Calls GetTimeSheet(WeekStartDate, WeekEndDate, header).
  • Returns the default Index.cshtml view with a List<EmployeeTimeSheet> model.
// Example: /TimeSheet/Index
var header     = DisplayTimeSheetHeader();
var timesheets = GetTimeSheet(WeekStartDate, WeekEndDate, header);
return View(timesheets);

2. DisplayTimeSheetHeader 🔄

Signature:

public TimeSheet DisplayTimeSheetHeader()
  • Finds current Monday via GetMonday(DateTime.Now).
  • Formats each day as MMM dd (uppercase).
  • Sets WeekStartDate & WeekEndDate fields.
  • Returns a TimeSheet instance containing header labels.

3. Previous & Next Week Navigation

Two [HttpPost] actions, Previous and Next, allow week‐by‐week navigation.

[HttpPost]
public ActionResult Previous(IFormCollection collection) { /* … */ }

[HttpPost]
public ActionResult Next(IFormCollection collection) { /* … */ }
  • Parse hidden fields (hdnmondayprev, hdnmondayprevyear) from the form.
  • Subtract/Add 7 days to the parsed Monday.
  • Rebuild header, compute new WeekStartDate/WeekEndDate.
  • Re-call GetTimeSheet() and return "Index" view.

4. GetTimeSheet (Core Data Generator)

Signature:

public List<EmployeeTimeSheet> GetTimeSheet(
    DateTime StartDate,
    DateTime EndDate,
    TimeSheet timesheetHeader
)

Responsibilities:

  1. Filter Employees
    Select only active employees with specific titles:

    Titles Included
    Information Systems Director
    IT Solutions Specialist
    IT Technical Support
    …
  2. Load Raw Time Entries
    Joins TimeEntryTypes with TimeSheetEntries in the date range for those employees.

  3. Pivot Data by Day

    • Uses 7 DataTables (dt1–dt7) for Monday→Sunday.
    • Dynamically builds columns: Desc, Type, MMM dd for that day.
    • Stores per‐day hours & “slots” in TempData.
  4. Merge & Add Totals

    • Merges all day‐tables into one weekly DataTable.
    • Adds a Total column summarizing hours per row.
    • Orders by a custom Priority column for sorting.
  5. Project into View Models

    • Iterates each Employee and each TimeCard Type row.
    • Fetches existing TimeSheetEntry for each day & employee → populates hours & notes.
    • Accumulates daily & grand totals.
    • Returns List<EmployeeTimeSheet>.

Return Type: List<EmployeeTimeSheet> — consumed by the Razor view for rendering.


5. Time Entry CRUD 🛠️

AddTimeSheet

public void AddTimeSheet(
    decimal Hours,
    DateTime DateWorked,
    Guid employeeid,
    Guid Type,
    string Notes
)
  • Creates new TimeSheetEntry, sets audit fields, IsDeleted = false.
  • _context.TimeSheetEntries.Add(...); _context.SaveChanges().

UpdateTimeSheet

public void UpdateTimeSheet(
    decimal Hours,
    DateTime DateWorked,
    Guid employeeid,
    Guid Type,
    string Notes
)
  • Finds existing non-deleted entry, updates fields, audit info, saves.

DeleteTimeSheet

public void DeleteTimeSheet(
    decimal Hours,
    DateTime DateWorked,
    Guid employeeid,
    Guid Type
)
  • Marks the entry’s IsDeleted = true (soft‐delete), updates audit, saves.

6. InsertTimeEntries (Bulk Processing)

Signature:

public void InsertTimeEntries(
    string[] Time,
    string day,
    Guid employeeid,
    string[] Details
)
  • Parameters:
    • Time[] — hours for each TimeSheetType (e.g., Regular, PTO).
    • day — date string (MM/dd/yyyy).
    • Details[] — notes per entry.
  • Logic:
    • Parse each hour & type (by enum index).
    • Determine if Add, Update, or Delete is needed.
    • Delegate to the CRUD methods above.

7. TimeSheetView (Form Post Processor)

Signature:

[HttpPost]
public ActionResult TimeSheetView(IFormCollection coll, string Command)
  • Receives the entire form as a IFormCollection.
  • Parses arrays of hours & notes for all days (Mon–Sun) and all employees.
  • Loops through each day & employee, calls InsertTimeEntries().
  • Reloads the week (DisplayTimeSheetHeader() + GetTimeSheet()) and returns "Index" with updated model.

🔧 Helper Methods & Utilities

Method Purpose
IEnumerable<DateTime> EachDay(DateTime from, DateTime thru) Yields each date in a range (inclusive).
static DateTime GetMonday(DateTime time) Returns the Monday of the week for a given date.
string MonthDateFormat(DateTime date) Formats date as MMM dd in uppercase (e.g., JAN 01).

🚀 API Endpoints Overview

HTTP Verb Route Action Method Description
GET /TimeSheet/Index Index(string) Display current week timesheet.
POST /TimeSheet/Previous Previous(...) Move to previous week.
POST /TimeSheet/Next Next(...) Move to next week.
POST /TimeSheet/TimeSheetView TimeSheetView(...) Bulk save of weekly time entries.
POST /TimeSheet/Print Print(DateTime,DateTime) (Stub) Print view.

🔗 Third‑party Integrations

  • Azure Blob Storage (BlobServiceClient) — injected but not yet used in this controller.
  • Entity Framework Core for data access via IrbyContext.

📝 Sample Code Blocks & Usage Examples

1. Display the Current Week

// Controller call:
[HttpGet]
public ActionResult Index(string employeeId) {
    var header = DisplayTimeSheetHeader();
    var model  = GetTimeSheet(WeekStartDate, WeekEndDate, header);
    return View(model);
}

2. Format a Date

var date = new DateTime(2023,1,1);
Console.WriteLine(MonthDateFormat(date)); // → "JAN 01"

3. Bulk Insert from Form

<form asp-action="TimeSheetView" method="post">
  <!-- hidden fields for days and employees -->
  <button type="submit">Save Timesheet</button>
</form>
[HttpPost]
public ActionResult TimeSheetView(IFormCollection coll, string Command) {
    // Parses and delegates to InsertTimeEntries(...)
    // Redirects back to Index with updated data
}

📊 Class Diagram (UML)

classDiagram
    class TimeSheetController {
      - IrbyContext _context
      - IHttpContextAccessor _httpContextAccessor
      - IWebHostEnvironment _hostingEnvironment
      - BlobServiceClient _blobServiceClient
      - IConfiguration _configuration
      + ActionResult Index(string employeeId)
      + ActionResult Previous(IFormCollection)
      + ActionResult Next(IFormCollection)
      + List<EmployeeTimeSheet> GetTimeSheet(DateTime, DateTime, TimeSheet)
      + void InsertTimeEntries(string[], string, Guid, string[])
      + void AddTimeSheet(decimal, DateTime, Guid, Guid, string)
      + void UpdateTimeSheet(decimal, DateTime, Guid, Guid, string)
      + void DeleteTimeSheet(decimal, DateTime, Guid, Guid)
      + ActionResult TimeSheetView(IFormCollection, string)
      + ActionResult Print(DateTime, DateTime)
      # TimeSheet DisplayTimeSheetHeader()
      # IEnumerable<DateTime> EachDay(DateTime, DateTime)
      # static DateTime GetMonday(DateTime)
      # string MonthDateFormat(DateTime)
    }

✅ Conclusion

The TimeSheetController is a comprehensive ASP.NET Core MVC controller managing the display, navigation, and CRUD operations of a weekly timesheet for selected employees.

  • Navigation between weeks is simple via Previous/Next.
  • Data pivoting uses DataTable to restructure raw entries into a row‑and‑column format.
  • Bulk form processing and incremental updates assure minimal database writes.
  • Designed for extensibility (e.g., Azure Blob injection) and clear separation of responsibilities.

Feel free to extend or refactor:

  • Move the pivot logic into a dedicated service for testing.
  • Leverage LINQ or EF Core group transforms to reduce DataTable complexity.
  • Add authorization filters to secure endpoints.
  • Utilize the injected BlobServiceClient to store/export timesheet PDFs.

Happy coding! 🚀