📄 IViewController.cs Documentation
Welcome to the in-depth documentation for IViewController.cs, part of the IrbyImaging.UI.Controllers namespace. This controller powers dashboards, job‑review pages, document imaging, and CRUD operations on WIP data. You'll find explanations, code snippets, UML diagrams, and usage examples.
📑 Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Key Functional Areas
- Class Diagram (UML)
- Public Methods & Endpoints
- View Models & Data Models
- Helper Methods & Utilities
- Error Handling & Return Types
- Third‑Party Integrations
- Sample Code Snippets & Usage Examples
- Conclusion
🧐 Overview & Purpose
The IViewController is a flagship MVC controller that delivers:
- Interactive Dashboards (WIP metrics by type, lead, customer)
- Modal Details (account balances, costs, hours)
- Job‑Review Pages with ledgers, equipment, work orders, employees, assets, and trend charts
- Document Imaging previews, indexing, and metadata editing
- WIP CRUD (extract, insert, update, delete)
It stitches together EF Core for data access, Azure Blob Storage for files, a geocoding service for maps, and Syncfusion/EJ2 for UI components.
🔌 Dependencies & Technologies
| Category | Technology / Library |
|---|---|
| Framework | ASP.NET Core MVC |
| ORM | Entity Framework Core (IrbyContext) |
| Cloud Storage | Azure Blob Storage (BlobServiceClient) |
| HTTP Client | HttpClient |
| Geocoding | Custom GeocodingService |
| UI Components | Syncfusion EJ2 (Syncfusion.EJ2.Base) |
| File Processing | iTextSharp, OpenXML (DocumentFormat.OpenXml) |
| JSON | Newtonsoft.Json |
| Security | Microsoft.AspNetCore.Authorization |
| Misc | BouncyCastle, NuGet.Packaging (some unused) |
🔑 Key Functional Areas
- Dashboard / Index View
- Modal Detail Actions
- Job Review (GET & POST)
- Dynamic Data Endpoints
- Document Imaging (Preview & Indexing)
- WIP Data Extraction & CRUD
📊 Class Diagram (UML)
classDiagram
BaseController <|-- IViewController
IViewController : - IrbyContext _context
IViewController : - IEmployeeAndFieldOfficeManager _manager
IViewController : - IConfiguration _configuration
IViewController : - IHttpContextAccessor _contextAccessor
IViewController : - BlobServiceClient _blobServiceClient
IViewController : - HttpClient _httpClient
IViewController : - GeocodingService _geocodingService
IViewController : + IActionResult Index(string, string, string, string)
IViewController : + IActionResult balancesModal(string, string)
IViewController : + IActionResult JobReview()
IViewController : + IActionResult JobReviewDetails(string)
IViewController : + ActionResult<IEnumerable<JobLocation>> GetJobLocations(string)
IViewController : + IActionResult DocumentPreview(Guid)
IViewController : + IActionResult Insert(CRUDModel<WIP>)
IViewController : + IActionResult Update(CRUDModel<WIP>)
IViewController : + IActionResult Delete(CRUDModel<WIP>)
class DataGrid {
+string JobNumber
+decimal Revenue, Cost, Margin
+string MarginPct
+decimal YTDRevenue, YTDCost, YTDMargin
+string YTDMarginPct, RevPctOfTotal, MarPctOfTotal
+decimal ManHours, BIEC, CIEB, Unbilled
}
class JobLocation {
+string Job
+decimal Latitude, Longitude
+string Manager, Lead, Superintendent
+string EmployeeCount, POCount, WOCount
}
IViewController o-- "0..*" DataGrid
IViewController o-- "0..*" JobLocation
IViewController ..> GeocodingService
IViewController ..> BlobServiceClient
📡 Public Methods & Endpoints
1. Index 🎯
Route: GET /IView/Index
Parameters:
YearMonth(e.g."04/2024")TypeOfWork,Lead,Customer(optional filters)
What it does:
- Determines current user (
identityName) - Finds latest report date or parses from
YearMonth - Queries
WIPrecords, applies filters, groups by TypeOfWork, Lead, Customer - Computes totals & percentages for revenue, cost, margin, YTD, man‑hours, BIEC/CIEB/Unbilled
- Populates multiple
ViewBagdata sources for Syncfusion grids & charts - Prepares dropdowns (
SelectList) for filtering
Return:
View()with dozens ofViewBag.datasource*properties
public IActionResult Index(string YearMonth, string TypeOfWork, string Lead, string Customer)
{
// 1. Identify current user
var fullname = User.Claims.Skip(1).First().Value;
// 2. Determine month/year
var lastRec = _context.WIP
.OrderByDescending(a => a.ReportYear).ThenByDescending(a => a.ReportMonth)
.Select(a => new { a.ReportMonth, a.ReportYear }).First();
int year = lastRec.ReportYear, month = lastRec.ReportMonth;
if (!string.IsNullOrEmpty(YearMonth)) { /* parse YearMonth */ }
// 3. Query & filter WIP
var allData = _context.WIP
.Where(a => a.ReportMonth== month && a.ReportYear== year)
.ToList();
// apply TypeOfWork, Lead, Customer filters if present...
// 4. Group, aggregate, compute DataGrid list
var list = BuildDataGridByType(allData, year, month);
ViewBag.datasource = list;
// 5. Prepare SelectList for filters
ViewBag.YearMonth = new SelectList(...);
ViewBag.TypeOfWork = new SelectList(...);
// ...
return View();
}
2. Modal Detail Actions 🗒️
These actions return partial views showing detailed account balances:
| Action | Partial View | Purpose |
|---|---|---|
balancesModal(id, Year) |
balancesModal |
Revenue entries per GL account |
balancesCostModal(id, Year) |
balancesCostModal |
Cost entries per GL account |
balancesHoursModal(id, Year) |
balancesHoursModal |
Man‑hours per job |
balancesModalYTD(id, Year) |
balancesModalYTD |
Year‑to‑date revenue details |
balancesCostModalYTD(id, Year) |
balancesCostModalYTD |
YTD cost details |
All follow the same pattern:
- Parse
id(JobNumber) andYear(month/year or year only) - Query
AccountBalanceswithRevenue != 0,Cost != 0orManHours != 0 - Wrap in
Balancesmodel &ViewBag.datasource - Return
PartialView(...)
3. JobReview & JobReviewDetails 📋
JobReview (GET)
- Route:
GET /IView/JobReview - Purpose: Show a dropdown of all jobs (JDE numbers + names).
- Return:
View()withViewBag.jobs(List).
JobReviewDetails (POST)
- Route:
POST /IView/JobReviewDetails - Parameters:
jobnumber - What it does:
- Re‑populates
ViewBag.jobs - Queries:
AccountBalances→ViewBag.datasourceAccountLedgers→ViewBag.datasource2- Single
WIPrecord → buildsViewBag.datasource1 - Equipment, PurchaseOrders, WorkOrders → separate ViewBags
- Employees & Assets via navigation properties
- Trend data (
StackedLineChartData) for Revenue, Cost, CIEB, BIEC, Unbilled, Margin
- Packages everything into a
Balancesview model and returnsView(data)
- Re‑populates
4. getAccountBalanceDetailType 🔍
- Route:
GET /IView/getAccountBalanceDetailType?type={lead}&year={MM/yyyy} - Purpose: For a specific
Leadand month/year, group WIP by job and lead, then return partial view showing both child (job) and parent (lead) rows. - Return:
View()withViewBag.datasource8andViewBag.datasource.
5. GetJobLocations 🌐
- Route:
POST /IView/GetJobLocations - Parameters:
key(Lead name) - What it does:
- Groups WIP by
JobNamefor that lead - For each job, retrieves
Jobsentity to get address - Calls
_geocodingService.GetCoordinates(address) - Builds a list of
JobLocation(Job, Latitude, Longitude, Manager, EmployeeCount, etc.)
- Groups WIP by
- Return:
IEnumerable<JobLocation>as JSON
[HttpPost]
public ActionResult<IEnumerable<JobLocation>> GetJobLocations(string key)
{
var allData = _context.WIP.Where(a => a.Lead == key).GroupBy(a => a.JobName);
var jobLocations = new List<JobLocation>();
foreach (var group in allData) {
var jobEntity = _context.Jobs.First(j => j.JdeNumber == group.Key);
string address = $"{jobEntity.AddressLine1},{jobEntity.City},{jobEntity.State},{jobEntity.ZipCode}";
var coord = _geocodingService.GetCoordinates(address).Result;
jobLocations.Add(new JobLocation {
Job = $"{jobEntity.JdeNumber} - {jobEntity.Name}",
Latitude = (decimal) coord.Latitude,
Longitude = (decimal) coord.Longitude,
EmployeeCount = _context.Employees.Count(e => e.JobId == jobEntity.JobId).ToString(),
Manager = jobEntity.ManagerName,
Lead = key
});
}
return jobLocations;
}
6. Document Imaging Actions 📄
| Action | Return Type | Purpose |
|---|---|---|
DocumentView(string) |
PartialView |
Show _viewdoc editor for a single document page |
DocumentPreview(Guid) |
File(...) |
Stream binary from Azure Blob as file download |
ViewDoc(Guid) |
View() |
Render full document viewer with index metadata |
- DocumentPreview uses
BlobServiceClientto fetch blob content andFile(byte[], contentType)to stream to browser.
7. WIP CRUD 🌱
WIPExtract (GET)
- Route:
GET /IView/WIPExtract - Return:
View()withViewBag.WIP(all WIP records)
Insert / Update / Delete
They handle AJAX CRUD on the WIP entity:
-
Insert:
public IActionResult Insert([FromBody] CRUDModel<WIP> value) { value.Value.WIPId = Guid.NewGuid(); _context.WIP.Add(value.Value); _context.SaveChanges(); return Json(value.Value); } -
Update:
- Finds existing record
- Copies all fields from
model.Value - Sets
updatedDate,updatedBy - Saves
-
Delete:
- Deserializes
Value.KeytoWIP - Removes matching record
- Deserializes
🗃️ View Models & Data Models
| Class | Description |
|---|---|
| DataGrid | DTO for grid rows: job, metrics, percentages |
| CRUDModel | Wrapper for bulk changes (Added/Changed/Deleted) |
| JobLocation | Contains job coordinates & metadata |
| StackedLineChartData | Chart point: x‑axis label, y (revenue), y1 (cost) |
| Balances | ViewModel for list of AccountBalances |
| Ledgers | ViewModel for list of AccountLedger |
🛠️ Helper Methods & Utilities
- Percentage Calculations: Inline rounding and
string + "%". - GeocodingService: Transforms address → latitude/longitude.
- BlobServiceClient: Downloads blobs from Azure storage.
- JsonConvert: Serializes/deserializes document index metadata.
⚠️ Error Handling & Return Types
- Most actions return
IActionResultorActionResult<T>. - Insert/Update/Delete respond with JSON or partial view.
- No explicit
try/catch—rely on global exception filters and middleware.
🌐 Third‑Party Integrations
- Azure.Storage.Blobs: Document preview.
- Syncfusion.EJ2: DataGrid sources & charts.
- Newtonsoft.Json: Index metadata.
- iTextSharp & OpenXML: PDF & Excel utilities (namespaced).
💡 Sample Code Snippets & Usage Examples
1. AJAX Insert of WIP
fetch('/IView/Insert', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ Value: newWipRecord })
})
.then(r => r.json())
.then(json => console.log('Inserted:', json));
2. Syncfusion Grid Initialization
$("#gridContainer").ej2Grid({
dataSource: @Html.Raw(JsonConvert.SerializeObject(ViewBag.datasource)),
allowPaging: true,
columns: [
{ field: 'Type', headerText: 'Work Type', width: 120 },
{ field: 'Revenue', headerText: 'Revenue', format: 'C2', textAlign: 'Right' },
// ...
]
});
3. Document Preview Link
<a href="@Url.Action("DocumentPreview", "IView", new { id = Model.DocumentImageId })"
target="_blank">
📄 Preview Document
</a>
✅ Conclusion
The IViewController is a cornerstone of the IrbyImaging UI layer. It harmonizes data retrieval (via EF Core), file streaming (via Azure Blob), geolocation, and rich UI components (Syncfusion) to deliver:
- Dynamic Dashboards
- Detail Modals
- Comprehensive Job Reviews
- Document Imaging Interfaces
- CRUD on WIP Data
Armed with this documentation, you can confidently maintain, extend, or integrate new features into this controller. Happy coding! 🚀