📄 EditTimesheet.cshtml Documentation

Location: IrbyImaging/Views/FieldLog/EditTimesheet.cshtml
Purpose: Provides the UI and client‐side logic for editing an existing timesheet, including employees, equipment entries, signatures, comments, and submission workflows.


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. View Model
  4. Layout & Razor Setup
  5. HTML Structure
  6. CSS & Styling
  7. JavaScript & Helper Functions
  8. API Endpoints Overview
  9. Sample Code Snippets
  10. UML Diagrams
  11. Usage Examples
  12. Conclusion

1. Overview & Purpose

This Edit Timesheet view enables users to:

  • Load an existing timesheet by TimesheetId.
  • Edit crew selection, work date, foreman signature, comments.
  • Dynamically add/remove employee and equipment entries.
  • Record multiple work entries under each employee/equipment.
  • Validate and calculate total hours in real-time.
  • Prompt warnings and confirmations before overwriting previous data.
  • Submit changes via AJAX to /TimeEntry/SubmitEditedTimesheet.

2. Dependencies & Technologies

Library / Framework Version Usage
ASP.NET Core Razor Pages — Server-side view templating
Syncfusion EJ2 (ej2-inputs) v[latest] DropdownLists, DatePicker, TimePicker, NumericTextBox
jQuery 3.7.1 DOM manipulation, AJAX
Tailwind CSS 2.2.19 Utility-first styling
Font Awesome 6.4.0 Icons (<i> elements)
Signature Pad 4.1.7 Capturing foreman’s signature
JSON.NET / Json.Serialize — Serializing Model data into JS

3. View Model

The Razor view is strongly typed to:

@model IrbyImaging.UI.Models.TimesheetEditViewModel

Key properties:

Property Type Description
TimesheetId Guid Unique timesheet identifier
CrewId string/int Currently selected crew
CreatedDate DateTime Original creation date (fallback work date)
ForemanSignature string (Base64) Existing signature image
Comments string Free-form progress/comments
EmployeeTimesheets List<EmployeeTimesheetViewModel> Pre-loaded employee entries
EquipmentTimesheets List<EquipmentTimesheetViewModel> Pre-loaded equipment entries
AvailableCrews, Employees, Jobs, CostCodes, Classes, WorkOrders, UnionCodes, PayCodes, Equipment
IEnumerable<SelectListItem> or POCO lists Data sources for dropdowns

4. Layout & Razor Setup

@using Syncfusion.EJ2
@addTagHelper *, Syncfusion.EJ2

@{
    ViewData["Title"] = "Edit Timesheet";
    Layout = "~/Views/Shared/_TimeLayout.cshtml";
}

// Compute `workDate` from first existing entry (employee → equipment) or fallback to CreatedDate
@{ 
    DateTime workDate = Model.CreatedDate;
    // … logic selecting first WorkDate …
}
  • Layout: Uses _TimeLayout.cshtml for common header/footer.
  • TagHelpers: Syncfusion EJ2 TagHelpers loaded for <ejs-*> components.

5. HTML Structure

5.1 Main Container & Header

<div class="mx-auto p-6 bg-white time-container" style="width:95%;">
  <h1 class="main-header text-2xl font-bold">Edit Timesheet</h1>
  <input type="hidden" id="timesheetId" value="@Model.TimesheetId" />
  …
</div>
  • .time-container: Centers & pads content.
  • <h1 class="main-header">: Blue header bar with white text.

5.2 Crew & Work Date Selection

<div class="grid grid-cols-2 gap-4 mb-6">
  <!-- Crew Dropdown -->
  <ejs-dropdownlist id="crewId" dataSource="@Model.AvailableCrews"
    placeholder="Select Crew" cssClass="w-full" allowFiltering="true"
    value="@Model.CrewId">
    <e-dropdownlist-fields text="Text" value="Value"></e-dropdownlist-fields>
  </ejs-dropdownlist>

  <!-- Work Date Picker -->
  <ejs-datepicker id="commonWorkDate" value="@workDate"
    placeholder="Select Work Date" cssClass="w-full" required="true">
  </ejs-datepicker>
</div>
  • Crew: Syncfusion DropDownList bound to AvailableCrews.
  • Work Date: Syncfusion DatePicker defaulted to first entry date.

5.3 Foreman’s Signature Pad

<div class="border rounded-md p-2 bg-white">
  <canvas id="signaturePad" class="border rounded-md w-full" height="100"></canvas>
  <div class="flex justify-end gap-2 mt-2">
    <button id="clearSignature">Clear</button>
    <button id="saveSignature">Save</button>
  </div>
</div>
  • Uses Signature Pad to capture freehand signature.
  • Buttons to Clear or Save the drawing.

5.4 Employees Section

<div class="mb-8">
  <h2 class="section-header">Employees</h2>
  <button id="addEmployee" class="action-button">Add Employee</button>
  <div id="employeesContainer" class="space-y-4"></div>
</div>
  • Add Employee: clones a hidden .employee-template.
  • employeesContainer: placeholder for dynamic rows.

5.5 Equipment Section

<div class="mb-8">
  <h2 class="section-header">Equipment</h2>
  <button id="addEquipment" class="action-button">Add Equipment</button>
  <div id="equipmentContainer" class="space-y-4"></div>
</div>
  • Similar to Employees, but for equipment.
  • Templates: .equipment-template.

5.6 Comments & Submit Button

<ejs-textbox id="comments" rows="4" width="50%"
    placeholder="Project Progress and Comments"
    multiline="true" floatLabelType="Auto"
    value="@Model.Comments">
</ejs-textbox>

<button id="submitTimesheet" class="action-button px-4 py-2">Save Changes</button>
  • Syncfusion TextBox for comments.
  • Save Changes triggers a confirmation modal.

5.7 Hidden Templates for Dynamic Rows

  • .employee-template
  • .employee-workentry-template
  • .equipment-template
  • .equipment-workentry-template

These snippets are cloned in JS, assigned unique IDs, and enhanced with Syncfusion components.

5.8 Alerts & Modals

Element Purpose
#editAlert Yellow banner: “You are editing a previous timesheet.”
#editWarningModal Blocking modal on load: acknowledges overwrite risks.
#submitConfirmModal Asks user to confirm submission before AJAX POST.
#successModal Displays after successful submission; redirects to view list.

6. CSS & Styling

  • Tailwind for layout & spacing.
  • Custom CSS overrides Syncfusion styling, dropdown z‐indexes, scrollbar styling, input heights, etc.
  • Key classes:
    • .main-header, .section-header
    • .action-button (crew, employees, submit buttons)
    • .employee-row, .equipment-row (blue left border)
    • .custom-dropdown-* for enhanced select styling

7. JavaScript & Helper Functions

7.1 Global Data Initialization

window.timesheetModel = {
  TimesheetId: '@Model.TimesheetId',
  CrewId: '@Model.CrewId',
  WorkDate: '@Model.CreatedDate.ToString("yyyy-MM-dd")',
  ForemanSignature: '@(Model.ForemanSignature ?? "")',
  Comments: '@(Model.Comments ?? "")',
  EmployeeTimesheets: @Html.Raw(Json.Serialize(Model.EmployeeTimesheets)),
  EquipmentTimesheets: @Html.Raw(Json.Serialize(Model.EquipmentTimesheets))
};

window.ViewBag = {
  Crews: @Html.Raw(Json.Serialize(Model.AvailableCrews)),
  Employees: @Html.Raw(Json.Serialize(Model.AvailableEmployees)),
  Jobs: @Html.Raw(Json.Serialize(Model.AvailableJobs)),
  CostCodes: @Html.Raw(Json.Serialize(Model.AvailableCostCodes)),
  Classes: @Html.Raw(Json.Serialize(Model.AvailableClasses)),
  WorkOrders: @Html.Raw(Json.Serialize(Model.AvailableWorkOrders)),
  UnionCodes: @Html.Raw(Json.Serialize(Model.AvailableUnionCodes)),
  PayCodes: @Html.Raw(Json.Serialize(Model.AvailablePayCodes)),
  Equipment: @Html.Raw(Json.Serialize(Model.AvailableEquipment))
};
  • Stores ASP.NET Model & ViewBag data into JS globals for easy reference.
  • Used for dynamically building dropdowns & pre-filling existing entries.

7.2 Document Ready & Event Wiring

$(document).ready(function() {
  // 1️⃣ Show “editWarningModal” after 500ms
  // 2️⃣ Override Syncfusion mobile detection & popup behavior
  // 3️⃣ Clone templates: employees & equipment
  // 4️⃣ initSignaturePad(); renderExistingTimesheet();
  // 5️⃣ Wire up Add buttons, input listeners, submit button handlers
  // 6️⃣ forceUpdateAllTotals() with delays
});
  • Patch: Forces Syncfusion dropdowns out of fullscreen mode on “device” detection.
  • Cloning Templates: Caches jQuery clones for reuse.

7.3 Signature Pad Integration

function initSignaturePad() {
  let canvas = document.getElementById('signaturePad');
  signaturePad = new SignaturePad(canvas, {
    backgroundColor: 'rgb(255,255,255)',
    penColor: 'rgb(17,70,126)'
  });
  // Responsive resizing & clear/save bindings…
}
  • Resizes to device ratio.
  • .clearSignature clears canvas.
  • .saveSignature logs Base64 data URL.

7.4 Dynamic Row Creation & Binding

  • Employees

    • addNewEmployee(empData)
    • bindEmployeeRowEvents($row)
    • addNewEmployeeWorkEntry($row, weData)
  • Equipment

    • addNewEquipment(eqData)
    • bindEquipmentRowEvents($row)
    • addNewEquipmentEntry($row, eweData)

Each row:

  1. Clones template
  2. Appends hidden ID fields
  3. Initializes Syncfusion DropDownLists & TimePickers
  4. Pre-fills data if provided
  5. Binds .toggle-entries, .remove-*, .add-* events

7.5 Filtering Logic (Jobs → Cost Codes → Classes)

  • Employee WorkEntry:

    • On Job change: filters CostCodes by JobId & updates CostCode dropdown.
    • On CostCode change: filters Classes by JobId & CostCodeNumber.
    • Priority: Always include classes containing “JDEC” or “BES”.
  • Equipment WorkEntry:

    • On Job change: filters equipment-specific CostCodes (CostCodeType === 2).

Helper functions:

function sortClassesPriority(classes) { … }
function filterEmployeeCostCode(dropdown, jobId) { … }
function filterEmployeeClass(dropdown, jobId, costCodeNumber) { … }

7.6 Totals Calculation

Real-time sum of hours:

function updateTotalHours($employeeRow) {
  // Sum regular, overtime, doubletime ⇒ .total-hours
}
function updateTotalEquipmentHours($equipmentRow) {
  // Sum worked, idle ⇒ .total-worked & .total-idle
}
  • Bound on input events for dynamic elements.
  • Triggered after add/remove & initial render.

7.7 Building & Submitting the Timesheet Object

function buildTimesheetObject() {
  let result = {
    TimesheetId, CrewId, CreatedDate, ForemanSignature, Comments,
    EmployeeTimesheets: [], EquipmentTimesheets: []
  };

  // Iterate $('.employee-row') & $('.equipment-row'),
  // collect dropdown values, inputs, checkboxes,
  // include existing IDs for updates, skip new empty rows.

  return result;
}
  • Submission Flow:
    1. User clicks Save Changes → opens #submitConfirmModal.
    2. On Confirm: buildTimesheetObject() ⇒ $.ajax POST '/TimeEntry/SubmitEditedTimesheet'.
    3. On success: show #successModal, then redirect to /TimeEntry/ViewTimesheets.
    4. Error handling logs to console & shows alert().

8. API Endpoints Overview

Endpoint Method Payload Success Behavior
/TimeEntry/SubmitEditedTimesheet POST JSON: Timesheet object with employees & equipment Returns { success: true/false, message }. On success → success modal.

9. Sample Code Snippets

Build Timesheet Object (Excerpt)

$('.employee-row').each(function() {
  let empVal = $(this).find('.employee-dropdown-container').data('ejDropDownList').value;
  if (!empVal) return; // Skip empty
  let empObj = { EmployeeId: empVal, WorkEntries: [] };

  $(this).find('.work-entry').each(function() {
    let jobNo = $(this).find('.employee-jobno-dropdown').data('ejDropDownList').value;
    if (!jobNo) return;
    let hou = parseFloat($(this).find('.hours-regular').val()) || 0;
    empObj.WorkEntries.push({
      JobNo: jobNo,
      RegularHours: hou,
      // …
    });
  });

  if (empObj.WorkEntries.length)
    result.EmployeeTimesheets.push(empObj);
});

10. UML Diagrams

classDiagram
    class TimesheetEditViewModel {
      +Guid TimesheetId
      +int CrewId
      +DateTime CreatedDate
      +string ForemanSignature
      +string Comments
      +List<EmployeeTimesheetVm> EmployeeTimesheets
      +List<EquipmentTimesheetVm> EquipmentTimesheets
    }
    class EmployeeTimesheetVm {
      +Guid? EmployeeTimesheetId
      +Guid EmployeeId
      +List<WorkEntryVm> WorkEntries
    }
    class WorkEntryVm {
      +Guid? WorkEntryId
      +string JobNo
      +string CostCode
      +string Class
      +decimal RegularHours
      +decimal OvertimeHours
      +decimal DoubletimeHours
      +DateTime WorkDate
    }
    class EquipmentTimesheetVm {
      +Guid? EquipmentTimesheetId
      +Guid EquipmentId
      +List<EquipmentEntryVm> EquipmentEntries
    }
    class EquipmentEntryVm {
      +Guid? EquipmentEntryId
      +string JobNo
      +string CostCode
      +decimal WorkedHours
      +decimal IdleHours
      +DateTime WorkDate
    }

11. Usage Examples

  1. Open the “Edit Timesheet” page for a specific TimesheetId.
  2. Review the yellow alert & click I Understand.
  3. Modify crew, work date, comments as needed.
  4. Add or remove employees/equipment.
  5. Enter work entries: job, cost code, times, meals, per diem.
  6. Submit: confirm and wait for success modal → redirected to list.

12. Conclusion

✅ This view provides a robust, interactive interface for editing timesheets with full-fledged dynamic row management, client-side validation, and AJAX persistence.

  • Extensible: Add more fields easily via templates & JS logic.
  • User-Friendly: Live totals, confirmations, signature capture.
  • Maintainable: Clear separation (Razor for layout, JS for behavior, CSS for styling).

Feel free to extend filtering rules, validation logic, or integrate additional third‑party widgets as needed! 🚀