🎫 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

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Architecture & UML Diagram
  4. Interface: ITicketService
  5. Implementation: TicketService
    • Constructor & DI
    • Core Methods
      • GetTicketById
      • GetTicketsForUser
      • GetTicketsForAdmin, GetArchivedTicketsForAdmin, GetArchivedTickets
      • GetBigBuckets
      • CreateTicketDetailsViewModel
      • CreateIncidentViewModel, CreateRequestViewModel
      • AddTicket (Incident & Request)
      • EditTicket, EditIncident
      • CreateTicketUpdateViewModel
      • UpdateTicket
      • RequestApproval
  6. Supporting Models & ViewModels
  7. Error Handling & Return Types
  8. Third‑Party Integrations
  9. Sample Code Blocks & Usage Examples
  10. 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 context
  • IEmailGenerationService – helps format email subjects & bodies
  • IActiveDirectoryService – fetches user/employee data from Azure AD
  • IConfiguration – 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 Ticket entity with its Updates navigation 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 TicketViewModel for tickets created by a user.
  • Enhancement: Populates LastUpdate by querying the most recent Update.

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 closer parameter (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 include
    • includeReviewAfter: Exclude tickets marked ReviewAfter
  • Returns: BigBucketsViewModel containing:
    • Counts for each request type
    • A list of OpenAndInProgressRequestViewModel detailing 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:

  1. Determine new TicketNumber (last + 1)
  2. Map ViewModel → Ticket entity, JSON‑serialize details
  3. Seed initial Update record
  4. _context.SaveChangesAsync()
  5. Fire-and-forget email via MailService

7. EditTicket & EditIncident ✏️

  • Merge new details into existing Ticket
  • Append a new Update entry
  • Send an update email

8. UpdateTicket 🔄

Admin-side status updates:

  • Accepts TicketUpdateViewModel (new JSON, status, review flags)
  • Persists new Update
  • Adjusts Ticket.Status, ReviewAfter fields
  • 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: true only if all emails are sent successfully.

🎛️ Supporting Models & ViewModels

  1. EmployeeDetails
    • Holds basic AD user info: EmployeeNumber, JobNumber, JobTitle, JobDepartment.
  2. TicketOptions
    • Used for JSON‑serialize/deserialize of request items in tickets (Index, Type, Item, IsCompleted, ApprovalRequired).

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: EditIncident throws InvalidOperationException if no ticket found.
  • JSON Errors: GetBigBuckets catches JsonException when deserializing.
  • Email Failures: RequestApproval aggregates 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! 🚀