🎫 TicketService.cs Documentation
Welcome to the comprehensive documentation for IrbyImaging/Services/TicketService.cs! This guide covers everything from an overview and purpose to detailed API descriptions, UML diagrams, code snippets, usage examples, and conclusions. Use the Table of Contents below to navigate.
📑 Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Architecture & UML Diagram
- Interface: ITicketService
- Implementation: TicketService
- Constructor & DI
- Core Methods
GetTicketByIdGetTicketsForUserGetTicketsForAdmin,GetArchivedTicketsForAdmin,GetArchivedTicketsGetBigBucketsCreateTicketDetailsViewModelCreateIncidentViewModel,CreateRequestViewModelAddTicket(Incident & Request)EditTicket,EditIncidentCreateTicketUpdateViewModelUpdateTicketRequestApproval
- Supporting Models & ViewModels
- Error Handling & Return Types
- Third‑Party Integrations
- Sample Code Blocks & Usage Examples
- Conclusion
📝 Overview & Purpose
TicketService is the central business‑logic component in the IrbyImaging UI layer responsible for:
- Managing Incidents and Requests tickets
- Performing CRUD operations on tickets and updates
- Generating view models for UI consumption
- Sending email notifications on key ticket events
- Aggregating big‑bucket reports for admin dashboards
It abstracts away database operations, email workflows, Active Directory lookups, and JSON serialization details to provide a clean interface (ITicketService) for controllers.
🛠️ Dependencies & Technologies
| Dependency | Purpose |
|---|---|
| Microsoft.EntityFrameworkCore | ORM for database operations (IrbyContext) |
| Newtonsoft.Json | JSON (de)serialization for request/status payloads |
| Microsoft.AspNetCore.Mvc.Rendering | SelectList for populating dropdowns in view models |
| Microsoft.Extensions.Configuration | Access to app configuration (e.g., email credentials) |
| IrbyImaging.BusinessLogic | Email template generation via IEmailGenerationService |
| IrbyImaging.Utility | Utility classes (e.g., AzureADRead for AD integration) |
| IrbyImaging.DomainClasses | Domain entities (Ticket, Update, etc.) |
| IrbyImaging.ViewModels | ViewModels used by UI (TicketViewModel, IncidentViewModel, etc.) |
| MailService (custom) | Sends email via Microsoft Graph or SMTP |
🏗️ Architecture & UML Diagram
classDiagram
ITicketService <|.. TicketService
TicketService o-- IrbyContext
TicketService o-- IEmailGenerationService
TicketService o-- IActiveDirectoryService
TicketService o-- IConfiguration
TicketService ..> MailService
TicketService "1" --> "*" TicketViewModel
TicketService "1" --> "*" TicketDetailsViewModel
TicketService "1" --> "*" TicketUpdateViewModel
🔌 Interface: ITicketService
public interface ITicketService
{
Task<Ticket> GetTicketById(Guid? id);
List<TicketViewModel> GetTicketsForUser(string username);
List<TicketViewModel> GetTicketsForAdmin(string filter, TicketType type, string search);
List<TicketViewModel> GetArchivedTicketsForAdmin(string filter, TicketType type, string search);
List<TicketViewModel> GetArchivedTickets(string filter, string closer);
BigBucketsViewModel GetBigBuckets(List<string> columns, bool includeReviewAfter);
TicketDetailsViewModel CreateTicketDetailsViewModel(Ticket ticket, bool excludeCompletedItems);
IncidentViewModel CreateIncidentViewModel(string username);
Task<Guid> AddTicket(IncidentViewModel incident, string createdByUsername, string user);
RequestViewModel CreateRequestViewModel(string username);
Task<Guid> AddTicket(RequestViewModel request, string createdByUsername, string user);
Task<Guid> EditTicket(RequestViewModel request, string createdByUsername);
Task<Guid> EditIncident(IncidentViewModel incident, string createdByUsername);
TicketUpdateViewModel CreateTicketUpdateViewModel(Ticket ticket);
Task<bool> UpdateTicket(TicketUpdateViewModel updateFromAdmin, string updatedByUsername);
Task<bool> RequestApproval(Guid id, string item, string createdByUsername, string approvalDepartment);
}
Purpose: Defines all public operations that the UI controllers can invoke to manage tickets.
🚀 Implementation: TicketService
Constructor & Dependency Injection
public TicketService(
IrbyContext context,
IEmailGenerationService emailGeneration,
IActiveDirectoryService activeDirectory,
IConfiguration configuration)
{
_context = context;
_emailGeneration = emailGeneration;
_activeDirectory = activeDirectory;
_configuration = configuration;
}
IrbyContext– EF Core DB contextIEmailGenerationService– helps format email subjects & bodiesIActiveDirectoryService– fetches user/employee data from Azure ADIConfiguration– retrieves secrets (e.g., HelpDesk email client ID/secret)
Core Methods
1. GetTicketById 🎯
public async Task<Ticket> GetTicketById(Guid? id) {
return await _context.Tickets
.Include(t => t.Updates)
.FirstOrDefaultAsync(m => m.Id == id);
}
- Returns: A
Ticketentity with itsUpdatesnavigation property populated. - Use Case: Display details on the ticket details page.
2. GetTicketsForUser 👤
public List<TicketViewModel> GetTicketsForUser(string username) {
// filter by CreatedBy and sort by Status/CreatedOn
}
- Returns: List of
TicketViewModelfor tickets created by a user. - Enhancement: Populates
LastUpdateby querying the most recentUpdate.
3. GetTicketsForAdmin & Archived Variants 🛂
- GetTicketsForAdmin – fetches open/in‑progress tickets, with optional filter, type, search.
- GetArchivedTicketsForAdmin – fetches closed/cancelled tickets for admins, with the same filters.
- GetArchivedTickets – simplified archived retrieval with a
closerparameter (maps to username).
All methods return a list of TicketViewModel, each with a LastUpdate snippet.
4. GetBigBuckets 📊
Produces a dashboard summarizing open Request tickets, grouping by categories (Phones, Tablets, Software, etc.) based on JSON‑serialized requests.
- Parameters:
columns: Which categories to includeincludeReviewAfter: Exclude tickets marked ReviewAfter
- Returns:
BigBucketsViewModelcontaining:- Counts for each request type
- A list of
OpenAndInProgressRequestViewModeldetailing each ticket
5. ViewModel Creators 🖥️
CreateTicketDetailsViewModel(Ticket ticket, bool excludeCompletedItems)CreateTicketUpdateViewModel(Ticket ticket)CreateIncidentViewModel(string username)CreateRequestViewModel(string username)
These methods instantiate and populate rich view models (TicketDetailsViewModel, TicketUpdateViewModel, etc.) based on the Ticket entity and related AD lookups.
6. AddTicket ✍️
- Incident:
Task<Guid> AddTicket(IncidentViewModel incident, ...) - Request:
Task<Guid> AddTicket(RequestViewModel request, ...)
Common flow:
- Determine new TicketNumber (last + 1)
- Map ViewModel → Ticket entity, JSON‑serialize details
- Seed initial
Updaterecord _context.SaveChangesAsync()- Fire-and-forget email via
MailService
7. EditTicket & EditIncident ✏️
- Merge new details into existing
Ticket - Append a new
Updateentry - Send an update email
8. UpdateTicket 🔄
Admin-side status updates:
- Accepts
TicketUpdateViewModel(new JSON, status, review flags) - Persists new
Update - Adjusts
Ticket.Status,ReviewAfterfields - Sends Close / Cancel / General Update emails conditionally
9. RequestApproval ✅
Bulk‑emails all department approvers (UARApprover) when a specific request item requires approval.
public async Task<bool> RequestApproval(
Guid id, string item, string createdByUsername, string approvalDepartment)
- Returns:
trueonly if all emails are sent successfully.
🎛️ Supporting Models & ViewModels
- EmployeeDetails
- Holds basic AD user info:
EmployeeNumber,JobNumber,JobTitle,JobDepartment.
- Holds basic AD user info:
- TicketOptions
- Used for JSON‑serialize/deserialize of request items in tickets (
Index,Type,Item,IsCompleted,ApprovalRequired).
- Used for JSON‑serialize/deserialize of request items in tickets (
Other complex view models reside in
IrbyImaging.ViewModels(e.g.,TicketViewModel,OpenAndInProgressRequestViewModel).
⚠️ Error Handling & Return Types
- Async Methods: Return
Task<T>/Task<bool>. - NotFound Cases:
EditIncidentthrowsInvalidOperationExceptionif no ticket found. - JSON Errors:
GetBigBucketscatchesJsonExceptionwhen deserializing. - Email Failures:
RequestApprovalaggregates success flags; other email calls are fire‑and‑forget (you may log failures separately).
🔗 Third‑Party Integrations
- EF Core: for data persistence.
- Newtonsoft.Json: for flexible JSON fields on
Ticket.Updates. - Azure AD (Microsoft.Graph): to fetch user details and drop‑down data.
- MailService: a custom wrapper (likely using Microsoft Graph API or SMTP) to send emails.
- IEmailGenerationService: provides templated subjects & bodies for email events.
💻 Sample Code Blocks & Usage Examples
1. Registering the Service
In Startup.cs or Program.cs:
services.AddScoped<ITicketService, TicketService>();
2. Injecting into a Controller
public class TicketsController : Controller
{
private readonly ITicketService _ticketService;
public TicketsController(ITicketService ticketService) {
_ticketService = ticketService;
}
public async Task<IActionResult> Details(Guid id) {
var ticket = await _ticketService.GetTicketById(id);
if (ticket == null) return NotFound();
var vm = _ticketService.CreateTicketDetailsViewModel(ticket, excludeCompletedItems: false);
return View(vm);
}
}
3. Creating a New Request Ticket
[HttpPost]
public async Task<IActionResult> CreateRequest(RequestViewModel model) {
if (!ModelState.IsValid) return View(model);
var ticketId = await _ticketService.AddTicket(model, User.Identity.Name, User.Identity.Name);
return RedirectToAction("Details", new { id = ticketId });
}
🏁 Conclusion
TicketService.cs orchestrates the full lifecycle of Incident and Request tickets in the IrbyImaging UI, from creation and editing to comprehensive reporting and email notifications. By abstracting data access and business rules behind ITicketService, controllers remain thin, focusing purely on HTTP concerns and view rendering.
Feel free to extend or refactor individual methods—such as extracting the email‑sending logic into a dedicated Notification component or modularizing the giant GetBigBuckets logic into smaller services—to improve testability and maintainability.
Happy coding! 🚀