mirror of
https://github.com/Sea-Haven-Industries/shoc-backend.git
synced 2026-09-30 08:23:12 +00:00
feat(uplifts): add approval queue read contract (SH-207)
This commit is contained in:
parent
d204536215
commit
3cb1e3e3f3
8 changed files with 682 additions and 2 deletions
|
|
@ -52,6 +52,56 @@ public class UpliftControllerTests
|
|||
envelope.Status.Should().Be("Success");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_PassesStatusAndTierFiltersToService()
|
||||
{
|
||||
var service = new Mock<IUpliftService>();
|
||||
service.Setup(x => x.ListAsync(It.IsAny<ClaimsPrincipal>(), "Approved", 2, 3, 50, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new UpliftListResultDTO());
|
||||
|
||||
var controller = NewController(service);
|
||||
|
||||
await controller.List("Approved", 2, 3, 50);
|
||||
|
||||
service.Verify(
|
||||
x => x.ListAsync(It.IsAny<ClaimsPrincipal>(), "Approved", 2, 3, 50, It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_ReturnsQueueContractFieldsInEnvelope()
|
||||
{
|
||||
var service = new Mock<IUpliftService>();
|
||||
var item = new UpliftListItemDTO
|
||||
{
|
||||
Id = 7,
|
||||
WorkOrderId = 11,
|
||||
WorkOrderNumber = "WO-77",
|
||||
WorkOrderSite = "SITE-EAST",
|
||||
WorkOrderService = "HVAC",
|
||||
RequestedByName = "Gateway",
|
||||
WorkOrderAutoApprovedTotal = 150m,
|
||||
WorkOrderAdminApprovedTotal = 300m,
|
||||
WorkOrderApprovedExposureTotal = 450m
|
||||
};
|
||||
service.Setup(x => x.ListAsync(It.IsAny<ClaimsPrincipal>(), It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new UpliftListResultDTO { Total = 1, Page = 1, PageSize = 25, Items = new[] { item } });
|
||||
|
||||
var controller = NewController(service);
|
||||
|
||||
var result = await controller.List();
|
||||
|
||||
var ok = result.Should().BeOfType<OkObjectResult>().Subject;
|
||||
var envelope = ok.Value.Should().BeOfType<DataResponse>().Subject;
|
||||
var data = envelope.Data as UpliftListResultDTO;
|
||||
var returned = data!.Items.Should().ContainSingle().Subject;
|
||||
returned.WorkOrderNumber.Should().Be("WO-77");
|
||||
returned.WorkOrderSite.Should().Be("SITE-EAST");
|
||||
returned.WorkOrderService.Should().Be("HVAC");
|
||||
returned.RequestedByName.Should().Be("Gateway");
|
||||
returned.WorkOrderApprovedExposureTotal.Should().Be(450m);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_NotFound_Returns404()
|
||||
{
|
||||
|
|
|
|||
465
Api.SeaHavenIndustries.Tests/UpliftQueueReadTests.cs
Normal file
465
Api.SeaHavenIndustries.Tests/UpliftQueueReadTests.cs
Normal file
|
|
@ -0,0 +1,465 @@
|
|||
using Data.SeaHavenIndustries;
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using SeaHaven.DataServices.Implementation;
|
||||
using SeaHaven.Services.Configuration;
|
||||
using SeaHaven.Services.DTOs;
|
||||
using SeaHaven.Services.Implementation;
|
||||
using SeaHaven.Services.Interfaces;
|
||||
using System.Security.Claims;
|
||||
using Xunit;
|
||||
|
||||
namespace Api.SeaHavenIndustries.Tests;
|
||||
|
||||
// Behavior tests for the approval queue read contract. These exercise the real
|
||||
// service + data-service layers against an in-memory DbContext so that queue
|
||||
// ordering, filters, flattened work-order fields, exposure aggregation, and
|
||||
// per-tier read authorization are validated through the public contract.
|
||||
public sealed class UpliftQueueReadTests
|
||||
{
|
||||
private static ApplicationDbContext NewContext()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
return new ApplicationDbContext(options);
|
||||
}
|
||||
|
||||
private static ApprovalsOptions NewOptions() => new()
|
||||
{
|
||||
UpliftTier1MaxUsd = 2500m,
|
||||
Tier1Roles = new[] { "Approver" },
|
||||
Tier2Roles = new[] { "Manager" },
|
||||
Tier1NotificationRecipients = new[] { "tier1@example.com" },
|
||||
Tier2NotificationRecipients = new[] { "tier2@example.com" },
|
||||
EscalationRecipients = new[] { "escalate@example.com" }
|
||||
};
|
||||
|
||||
private static UpliftService NewService(ApplicationDbContext context) =>
|
||||
new(new UpliftDataService(context),
|
||||
new DispatchDataService(context),
|
||||
Mock.Of<IVendorDocumentStoragePort>(),
|
||||
TimeProvider.System,
|
||||
Microsoft.Extensions.Options.Options.Create(NewOptions()));
|
||||
|
||||
private static ClaimsPrincipal UserWithRoles(params string[] roles)
|
||||
{
|
||||
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, "user-42") };
|
||||
claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Test"));
|
||||
}
|
||||
|
||||
private static DispatchUpliftRequest Request(
|
||||
Dispatch dispatch,
|
||||
string status,
|
||||
DateTime created,
|
||||
DateTime? decided = null,
|
||||
int tier = 1,
|
||||
decimal requested = 100m,
|
||||
string? reason = null,
|
||||
string? requestedBy = null,
|
||||
string? createdBy = null,
|
||||
decimal? currentNte = null) => new()
|
||||
{
|
||||
DispatchId = dispatch.Id,
|
||||
Status = status,
|
||||
CreatedDate = created,
|
||||
DecidedAt = decided,
|
||||
RequiredTier = tier,
|
||||
RequestedNTE = requested,
|
||||
CurrentNTE = currentNte,
|
||||
VendorReason = reason,
|
||||
RequestedByVendorName = requestedBy,
|
||||
createdby = createdBy,
|
||||
NotificationStatus = "Pending"
|
||||
};
|
||||
|
||||
private static async Task<(Vendor Vendor, WorkOrder WorkOrder)> SeedWorkOrderAsync(
|
||||
ApplicationDbContext context,
|
||||
string number,
|
||||
string site,
|
||||
string service,
|
||||
string vendorName = "Gateway")
|
||||
{
|
||||
var vendor = new Vendor { CompanyName = vendorName, IsActive = true };
|
||||
var workOrder = new WorkOrder
|
||||
{
|
||||
WorkerOrderNumber = number,
|
||||
SiteCode = site,
|
||||
Service = service,
|
||||
WorkerOrderTitle = "Repair"
|
||||
};
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
return (vendor, workOrder);
|
||||
}
|
||||
|
||||
private static async Task<Dispatch> SeedDispatchAsync(
|
||||
ApplicationDbContext context, Vendor vendor, WorkOrder workOrder, string number)
|
||||
{
|
||||
var dispatch = new Dispatch
|
||||
{
|
||||
VendorId = vendor.Id,
|
||||
WorkOrderId = workOrder.Id,
|
||||
DispatchNumber = number,
|
||||
Status = "Completed",
|
||||
NTEAmount = 1000m
|
||||
};
|
||||
context.Dispatches.Add(dispatch);
|
||||
await context.SaveChangesAsync();
|
||||
return dispatch;
|
||||
}
|
||||
|
||||
// --- Ordering ---
|
||||
|
||||
[Fact]
|
||||
public async Task List_PendingStatus_OrdersOldestRequestFirst()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 3)),
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 1)),
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 2)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Items.Select(i => i.RequestedAt).Should().Equal(
|
||||
new DateTime(2026, 3, 1),
|
||||
new DateTime(2026, 3, 2),
|
||||
new DateTime(2026, 3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_ApprovedStatus_OrdersMostRecentlyDecidedFirst()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 10)),
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 2), decided: new DateTime(2026, 3, 20)),
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 3), decided: new DateTime(2026, 3, 15)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Approved", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Items.Select(i => i.DecidedAt).Should().Equal(
|
||||
new DateTime(2026, 3, 20),
|
||||
new DateTime(2026, 3, 15),
|
||||
new DateTime(2026, 3, 10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_WithoutStatusFilter_KeepsHistoricalNewestRequestFirstOrder()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Rejected", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 2)),
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 10), decided: new DateTime(2026, 3, 11)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), null, null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Items.Select(i => i.RequestedAt).Should().ContainInOrder(
|
||||
new DateTime(2026, 3, 10),
|
||||
new DateTime(2026, 3, 1));
|
||||
}
|
||||
|
||||
// --- Filters and scoping ---
|
||||
|
||||
[Fact]
|
||||
public async Task List_StatusAndTierFilters_Combine()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 1), tier: 1),
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 2), tier: 2),
|
||||
Request(dispatch, "Approved", new DateTime(2026, 3, 3), decided: new DateTime(2026, 3, 4), tier: 2));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Manager"), "Pending", 2, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Total.Should().Be(1);
|
||||
result.Items.Should().ContainSingle(i => i.RequiredTier == 2 && i.Status == "Pending");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_ExcludesDeletedRequestsAndRequestsOnDeletedDispatches()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var vendor = new Vendor { CompanyName = "Gateway", IsActive = true };
|
||||
var workOrder = new WorkOrder { WorkerOrderTitle = "Repair" };
|
||||
context.AddRange(vendor, workOrder);
|
||||
await context.SaveChangesAsync();
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
var deletedDispatch = new Dispatch
|
||||
{
|
||||
VendorId = vendor.Id,
|
||||
WorkOrderId = workOrder.Id,
|
||||
DispatchNumber = "DIS-DELETED",
|
||||
Status = "Completed",
|
||||
IsDeleted = true
|
||||
};
|
||||
context.Dispatches.Add(deletedDispatch);
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 1)),
|
||||
new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatch.Id,
|
||||
Status = "Pending",
|
||||
CreatedDate = new DateTime(2026, 3, 2),
|
||||
IsDeleted = true,
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 100m
|
||||
},
|
||||
Request(deletedDispatch, "Pending", new DateTime(2026, 3, 3)));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Total.Should().Be(1);
|
||||
result.Items.Should().ContainSingle(i => i.RequestedAt == new DateTime(2026, 3, 1));
|
||||
}
|
||||
|
||||
// --- Flattened queue fields ---
|
||||
|
||||
[Fact]
|
||||
public async Task List_MapsFlattenedWorkOrderAndRequesterFields()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendor, workOrder) = await SeedWorkOrderAsync(context, "WO-77", "SITE-EAST", "HVAC");
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.Users.Add(new ApplicationUser { Id = "user-7", FirstName = "Ada", LastName = "Smith" });
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.Add(Request(
|
||||
dispatch, "Pending", new DateTime(2026, 3, 2),
|
||||
tier: 2, requested: 400m, reason: "Scope grew",
|
||||
requestedBy: "Gateway", createdBy: "user-7", currentNte: 100m));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Manager"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
var item = result.Items.Should().ContainSingle().Subject;
|
||||
item.WorkOrderId.Should().Be(workOrder.Id);
|
||||
item.WorkOrderNumber.Should().Be("WO-77");
|
||||
item.WorkOrderSite.Should().Be("SITE-EAST");
|
||||
item.WorkOrderService.Should().Be("HVAC");
|
||||
item.VendorCompanyName.Should().Be("Gateway");
|
||||
item.RequestedByName.Should().Be("Gateway");
|
||||
item.RequestedAt.Should().Be(new DateTime(2026, 3, 2));
|
||||
item.VendorReason.Should().Be("Scope grew");
|
||||
item.Delta.Should().Be(300m);
|
||||
item.Status.Should().Be("Pending");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_RequesterLabelFallsBackToCreatingUserName()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendor, workOrder) = await SeedWorkOrderAsync(context, "WO-77", "SITE-EAST", "HVAC");
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.Users.Add(new ApplicationUser { Id = "user-7", FirstName = "Ada", LastName = "Smith" });
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.Add(Request(
|
||||
dispatch, "Pending", new DateTime(2026, 3, 2),
|
||||
requestedBy: null, createdBy: "user-7"));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
result.Items.Single().RequestedByName.Should().Be("Ada Smith");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_MapsEvidenceAttachmentSummary()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendor, workOrder) = await SeedWorkOrderAsync(context, "WO-77", "SITE-EAST", "HVAC");
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
var evidence = new VendorCompletionDocument
|
||||
{
|
||||
VendorId = vendor.Id,
|
||||
DispatchId = dispatch.Id,
|
||||
WorkOrderId = workOrder.Id,
|
||||
OriginalFileName = "quote.pdf",
|
||||
StoredFileName = "evidence.bin",
|
||||
ContentType = "application/pdf",
|
||||
SizeBytes = 512,
|
||||
ScanStatus = "Passed",
|
||||
ReviewStatus = "Approved",
|
||||
Purpose = "UpliftEvidence",
|
||||
Version = 1
|
||||
};
|
||||
context.VendorCompletionDocuments.Add(evidence);
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.Add(new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatch.Id,
|
||||
Status = "Pending",
|
||||
CreatedDate = new DateTime(2026, 3, 2),
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 200m,
|
||||
EvidenceDocumentId = evidence.Id
|
||||
});
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
var item = result.Items.Single();
|
||||
item.EvidenceDocumentId.Should().Be(evidence.Id);
|
||||
item.EvidenceFileName.Should().Be("quote.pdf");
|
||||
item.EvidenceContentType.Should().Be("application/pdf");
|
||||
item.EvidenceSizeBytes.Should().Be(512);
|
||||
}
|
||||
|
||||
// --- Approved-on-WO exposure totals ---
|
||||
|
||||
[Fact]
|
||||
public async Task List_AggregatesApprovedExposurePerWorkOrder_ExcludingNonApprovedStatuses()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendorA, workOrderA) = await SeedWorkOrderAsync(context, "WO-A", "SITE-A", "HVAC", "Gateway-A");
|
||||
var (vendorB, workOrderB) = await SeedWorkOrderAsync(context, "WO-B", "SITE-B", "Plumbing", "Gateway-B");
|
||||
var dispatchA = await SeedDispatchAsync(context, vendorA, workOrderA, "DIS-A");
|
||||
var dispatchB = await SeedDispatchAsync(context, vendorB, workOrderB, "DIS-B");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatchA, "Approved", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 2), requested: 300m),
|
||||
new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatchA.Id,
|
||||
Status = "NoApprovalRequired",
|
||||
CreatedDate = new DateTime(2026, 3, 1),
|
||||
RequiredTier = 0,
|
||||
RequestedNTE = 150m
|
||||
},
|
||||
Request(dispatchA, "Pending", new DateTime(2026, 3, 1), requested: 999m),
|
||||
Request(dispatchA, "Rejected", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 2), requested: 999m),
|
||||
new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatchA.Id,
|
||||
Status = "Withdrawn",
|
||||
CreatedDate = new DateTime(2026, 3, 1),
|
||||
DecidedAt = new DateTime(2026, 3, 2),
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 999m
|
||||
},
|
||||
new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatchA.Id,
|
||||
Status = "Revoked",
|
||||
CreatedDate = new DateTime(2026, 3, 1),
|
||||
DecidedAt = new DateTime(2026, 3, 2),
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 999m
|
||||
},
|
||||
new DispatchUpliftRequest
|
||||
{
|
||||
DispatchId = dispatchA.Id,
|
||||
Status = "Expired",
|
||||
CreatedDate = new DateTime(2026, 3, 1),
|
||||
RequiredTier = 1,
|
||||
RequestedNTE = 999m
|
||||
},
|
||||
Request(dispatchB, "Approved", new DateTime(2026, 3, 5), decided: new DateTime(2026, 3, 6), requested: 75m));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var result = await service.ListAsync(UserWithRoles("Approver"), "Approved", null, 1, 25, CancellationToken.None);
|
||||
|
||||
var itemA = result.Items.Single(i => i.WorkOrderNumber == "WO-A");
|
||||
itemA.WorkOrderAutoApprovedTotal.Should().Be(150m);
|
||||
itemA.WorkOrderAdminApprovedTotal.Should().Be(300m);
|
||||
itemA.WorkOrderApprovedExposureTotal.Should().Be(450m);
|
||||
|
||||
var itemB = result.Items.Single(i => i.WorkOrderNumber == "WO-B");
|
||||
itemB.WorkOrderAutoApprovedTotal.Should().Be(0m);
|
||||
itemB.WorkOrderAdminApprovedTotal.Should().Be(75m);
|
||||
itemB.WorkOrderApprovedExposureTotal.Should().Be(75m);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Exposure_IncludesLinkedDispatchesViaServerDerivedWorkOrderLinks()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendorA, workOrderA) = await SeedWorkOrderAsync(context, "WO-A", "SITE-A", "HVAC");
|
||||
var dispatchA = await SeedDispatchAsync(context, vendorA, workOrderA, "DIS-A");
|
||||
var linkedDispatch = new Dispatch
|
||||
{
|
||||
VendorId = vendorA.Id,
|
||||
DispatchNumber = "DIS-LINKED",
|
||||
Status = "Completed"
|
||||
};
|
||||
context.Dispatches.Add(linkedDispatch);
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchWorkOrders.Add(new DispatchWorkOrder
|
||||
{
|
||||
DispatchId = linkedDispatch.Id,
|
||||
WorkOrderId = workOrderA.Id
|
||||
});
|
||||
await context.SaveChangesAsync();
|
||||
context.DispatchUpliftRequests.Add(Request(
|
||||
linkedDispatch, "Approved", new DateTime(2026, 3, 1), decided: new DateTime(2026, 3, 2), requested: 60m));
|
||||
await context.SaveChangesAsync();
|
||||
var data = new UpliftDataService(context);
|
||||
|
||||
var exposure = await data.GetApprovedExposureForWorkOrdersAsync(
|
||||
new[] { workOrderA.Id }, CancellationToken.None);
|
||||
|
||||
var total = exposure.Should().ContainSingle(e => e.WorkOrderId == workOrderA.Id).Subject;
|
||||
total.AdminApprovedTotal.Should().Be(60m);
|
||||
total.AutoApprovedTotal.Should().Be(0m);
|
||||
}
|
||||
|
||||
// --- Read authorization (tier roles) ---
|
||||
|
||||
[Fact]
|
||||
public async Task List_CanDecide_ReflectsTierRolesForTheCaller()
|
||||
{
|
||||
using var context = NewContext();
|
||||
var (vendor, workOrder) = await SeedWorkOrderAsync(context, "WO-77", "SITE-EAST", "HVAC");
|
||||
var dispatch = await SeedDispatchAsync(context, vendor, workOrder, "DIS-1");
|
||||
context.DispatchUpliftRequests.AddRange(
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 1), tier: 1),
|
||||
Request(dispatch, "Pending", new DateTime(2026, 3, 2), tier: 2));
|
||||
await context.SaveChangesAsync();
|
||||
var service = NewService(context);
|
||||
|
||||
var tier1Only = await service.ListAsync(UserWithRoles("Approver"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
var tier2User = await service.ListAsync(UserWithRoles("Manager"), "Pending", null, 1, 25, CancellationToken.None);
|
||||
|
||||
tier1Only.Items.Single(i => i.RequiredTier == 1).CanDecide.Should().BeTrue();
|
||||
tier1Only.Items.Single(i => i.RequiredTier == 2).CanDecide.Should().BeFalse();
|
||||
tier2User.Items.Single(i => i.RequiredTier == 2).CanDecide.Should().BeTrue();
|
||||
tier2User.Items.Single(i => i.RequiredTier == 1).CanDecide.Should().BeFalse();
|
||||
}
|
||||
}
|
||||
|
|
@ -81,6 +81,13 @@ namespace Data.SeaHavenIndustries
|
|||
public string? PONumber { get; set; }
|
||||
public int? WorkOrderId { get; set; }
|
||||
public string? VendorCompanyName { get; set; }
|
||||
// Approval queue read contract: flattened work-order context.
|
||||
public string? WorkOrderNumber { get; set; }
|
||||
public string? WorkOrderSiteCode { get; set; }
|
||||
public string? WorkOrderService { get; set; }
|
||||
public string? RequestedByVendorName { get; set; }
|
||||
public string? RequestedByFirstName { get; set; }
|
||||
public string? RequestedByLastName { get; set; }
|
||||
public decimal? CurrentNTE { get; set; }
|
||||
public decimal RequestedNTE { get; set; }
|
||||
public string? VendorReason { get; set; }
|
||||
|
|
@ -130,6 +137,16 @@ namespace Data.SeaHavenIndustries
|
|||
public bool EvidenceScanPassed { get; set; }
|
||||
}
|
||||
|
||||
// Approval queue read contract: per-work-order exposure totals. Approved exposure is
|
||||
// the sum of uplift amounts that were auto-approved or admin-approved on the work
|
||||
// order; pending, rejected, cancelled/withdrawn, and revoked requests are excluded.
|
||||
public class WorkOrderUpliftExposureData
|
||||
{
|
||||
public int WorkOrderId { get; set; }
|
||||
public decimal AutoApprovedTotal { get; set; }
|
||||
public decimal AdminApprovedTotal { get; set; }
|
||||
}
|
||||
|
||||
// SH-101: internal evidence-download projection. Server-side join enforces that the
|
||||
// returned document is the one linked to this specific uplift request and dispatch.
|
||||
public class UpliftEvidenceDownloadData
|
||||
|
|
|
|||
|
|
@ -24,8 +24,13 @@ namespace SeaHaven.DataServices.Implementation
|
|||
from v in vendors.DefaultIfEmpty()
|
||||
join ev in _context.VendorCompletionDocuments on u.EvidenceDocumentId equals ev.Id into evidences
|
||||
from ev in evidences.DefaultIfEmpty()
|
||||
join wo in _context.workOrders on d.WorkOrderId equals wo.Id into workOrders
|
||||
from wo in workOrders.DefaultIfEmpty()
|
||||
join reqUser in _context.Users on u.createdby equals reqUser.Id into requestUsers
|
||||
from reqUser in requestUsers.DefaultIfEmpty()
|
||||
where (u.IsDeleted == null || u.IsDeleted == false)
|
||||
select new { u, d, v, ev };
|
||||
&& (d.IsDeleted == null || d.IsDeleted == false)
|
||||
select new { u, d, v, ev, wo, reqUser };
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(status))
|
||||
query = query.Where(x => x.u.Status == status);
|
||||
|
|
@ -34,8 +39,18 @@ namespace SeaHaven.DataServices.Implementation
|
|||
|
||||
var total = await query.CountAsync(cancellationToken);
|
||||
|
||||
// Approval queue read contract: the actionable queue (Pending) surfaces the
|
||||
// oldest request first; the decision log (Approved) surfaces the most
|
||||
// recently decided first. Every other read keeps the historical
|
||||
// newest-request-first order. Id is the deterministic tiebreaker.
|
||||
if (string.Equals(status, "Pending", StringComparison.Ordinal))
|
||||
query = query.OrderBy(x => x.u.CreatedDate).ThenBy(x => x.u.Id);
|
||||
else if (string.Equals(status, "Approved", StringComparison.Ordinal))
|
||||
query = query.OrderByDescending(x => x.u.DecidedAt).ThenByDescending(x => x.u.Id);
|
||||
else
|
||||
query = query.OrderByDescending(x => x.u.CreatedDate).ThenByDescending(x => x.u.Id);
|
||||
|
||||
var items = await query
|
||||
.OrderByDescending(x => x.u.CreatedDate)
|
||||
.Skip((Math.Max(page, 1) - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.Select(x => new UpliftListItemData
|
||||
|
|
@ -46,6 +61,12 @@ namespace SeaHaven.DataServices.Implementation
|
|||
PONumber = x.d.PONumber,
|
||||
WorkOrderId = x.d.WorkOrderId,
|
||||
VendorCompanyName = x.v != null ? x.v.CompanyName : x.u.RequestedByVendorName,
|
||||
WorkOrderNumber = x.wo != null ? x.wo.WorkerOrderNumber : null,
|
||||
WorkOrderSiteCode = x.wo != null ? x.wo.SiteCode : null,
|
||||
WorkOrderService = x.wo != null ? x.wo.Service : null,
|
||||
RequestedByVendorName = x.u.RequestedByVendorName,
|
||||
RequestedByFirstName = x.reqUser != null ? x.reqUser.FirstName : null,
|
||||
RequestedByLastName = x.reqUser != null ? x.reqUser.LastName : null,
|
||||
CurrentNTE = x.u.CurrentNTE,
|
||||
RequestedNTE = x.u.RequestedNTE,
|
||||
VendorReason = x.u.VendorReason,
|
||||
|
|
@ -252,6 +273,78 @@ namespace SeaHaven.DataServices.Implementation
|
|||
.SumAsync(u => u.RequestedNTE, cancellationToken);
|
||||
}
|
||||
|
||||
// Approval queue read contract: set-based exposure aggregation. Dispatches map to
|
||||
// work orders through the server-derived linkage (primary work order plus linked
|
||||
// work orders), matching the ForWorkOrder scope; approved amounts are summed per
|
||||
// dispatch in SQL and folded into per-work-order totals in memory (three set-based
|
||||
// round trips, no query-per-work-order).
|
||||
public async Task<IReadOnlyList<WorkOrderUpliftExposureData>> GetApprovedExposureForWorkOrdersAsync(
|
||||
IReadOnlyCollection<int> workOrderIds, CancellationToken cancellationToken)
|
||||
{
|
||||
var workOrderIdsScope = workOrderIds.Distinct().ToList();
|
||||
if (workOrderIdsScope.Count == 0)
|
||||
return Array.Empty<WorkOrderUpliftExposureData>();
|
||||
|
||||
var primaryPairs = await _context.Dispatches
|
||||
.Where(d => (d.IsDeleted == null || d.IsDeleted == false)
|
||||
&& d.WorkOrderId != null
|
||||
&& workOrderIdsScope.Contains(d.WorkOrderId.Value))
|
||||
.Select(d => new { DispatchId = d.Id, WorkOrderId = d.WorkOrderId!.Value })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var linkedPairs = await _context.DispatchWorkOrders
|
||||
.Where(l => workOrderIdsScope.Contains(l.WorkOrderId)
|
||||
&& l.Dispatch != null
|
||||
&& (l.Dispatch.IsDeleted == null || l.Dispatch.IsDeleted == false))
|
||||
.Select(l => new { l.DispatchId, l.WorkOrderId })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var workOrdersByDispatch = primaryPairs
|
||||
.Concat(linkedPairs)
|
||||
.GroupBy(p => p.DispatchId)
|
||||
.ToDictionary(g => g.Key, g => g.Select(p => p.WorkOrderId).ToHashSet());
|
||||
|
||||
if (workOrdersByDispatch.Count == 0)
|
||||
return Array.Empty<WorkOrderUpliftExposureData>();
|
||||
|
||||
var dispatchIds = workOrdersByDispatch.Keys.ToList();
|
||||
var sums = await _context.DispatchUpliftRequests
|
||||
.Where(u => (u.IsDeleted == null || u.IsDeleted == false)
|
||||
&& dispatchIds.Contains(u.DispatchId)
|
||||
&& (u.Status == "Approved" || u.Status == "NoApprovalRequired"))
|
||||
.GroupBy(u => u.DispatchId)
|
||||
.Select(g => new
|
||||
{
|
||||
DispatchId = g.Key,
|
||||
AutoApproved = g.Where(x => x.Status == "NoApprovalRequired")
|
||||
.Sum(x => (decimal?)x.RequestedNTE),
|
||||
AdminApproved = g.Where(x => x.Status == "Approved")
|
||||
.Sum(x => (decimal?)x.RequestedNTE)
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var totals = new Dictionary<int, WorkOrderUpliftExposureData>();
|
||||
foreach (var sum in sums)
|
||||
{
|
||||
if (!workOrdersByDispatch.TryGetValue(sum.DispatchId, out var linkedWorkOrders))
|
||||
continue;
|
||||
|
||||
foreach (var workOrderId in linkedWorkOrders)
|
||||
{
|
||||
if (!totals.TryGetValue(workOrderId, out var total))
|
||||
{
|
||||
total = new WorkOrderUpliftExposureData { WorkOrderId = workOrderId };
|
||||
totals[workOrderId] = total;
|
||||
}
|
||||
|
||||
total.AutoApprovedTotal += sum.AutoApproved ?? 0m;
|
||||
total.AdminApprovedTotal += sum.AdminApproved ?? 0m;
|
||||
}
|
||||
}
|
||||
|
||||
return totals.Values.ToList();
|
||||
}
|
||||
|
||||
public Task<List<DispatchUpliftRequest>> GetPendingForWorkOrderAsync(
|
||||
int workOrderId,
|
||||
CancellationToken cancellationToken)
|
||||
|
|
|
|||
|
|
@ -18,6 +18,12 @@ namespace SeaHaven.DataServices.Interfaces
|
|||
Task<bool> HasPendingAsync(int dispatchId, CancellationToken cancellationToken);
|
||||
Task<bool> HasPendingForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken);
|
||||
Task<decimal> SumAutoApprovedAmountForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken);
|
||||
// Approval queue read contract: set-based per-work-order exposure totals covering
|
||||
// auto-approved and admin-approved uplift amounts (pending, rejected,
|
||||
// cancelled/withdrawn, and revoked requests are excluded). Work orders absent
|
||||
// from the result have no approved exposure.
|
||||
Task<IReadOnlyList<WorkOrderUpliftExposureData>> GetApprovedExposureForWorkOrdersAsync(
|
||||
IReadOnlyCollection<int> workOrderIds, CancellationToken cancellationToken);
|
||||
Task<List<DispatchUpliftRequest>> GetPendingForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken);
|
||||
// SH-101: active = Pending or ChangesRequested (the only states that block a new request).
|
||||
Task<bool> HasActiveAsync(int dispatchId, CancellationToken cancellationToken);
|
||||
|
|
|
|||
|
|
@ -8,6 +8,11 @@ namespace SeaHaven.Services.DTOs
|
|||
public string? PONumber { get; set; }
|
||||
public int? WorkOrderId { get; set; }
|
||||
public string? VendorCompanyName { get; set; }
|
||||
// Approval queue read contract: flattened work-order context and requester.
|
||||
public string? WorkOrderNumber { get; set; }
|
||||
public string? WorkOrderSite { get; set; }
|
||||
public string? WorkOrderService { get; set; }
|
||||
public string? RequestedByName { get; set; }
|
||||
public decimal? CurrentNTE { get; set; }
|
||||
public decimal RequestedNTE { get; set; }
|
||||
public decimal Delta { get; set; }
|
||||
|
|
@ -26,6 +31,12 @@ namespace SeaHaven.Services.DTOs
|
|||
public DateTime? ExpiresAt { get; set; }
|
||||
public string? NotificationStatus { get; set; }
|
||||
public string? NotificationError { get; set; }
|
||||
// Approved-on-WO exposure totals for this item's work order: auto-approved and
|
||||
// admin-approved amounts; pending, rejected, cancelled/withdrawn, and revoked
|
||||
// requests are excluded.
|
||||
public decimal WorkOrderAutoApprovedTotal { get; set; }
|
||||
public decimal WorkOrderAdminApprovedTotal { get; set; }
|
||||
public decimal WorkOrderApprovedExposureTotal { get; set; }
|
||||
}
|
||||
|
||||
public class UpliftListResultDTO
|
||||
|
|
|
|||
|
|
@ -42,6 +42,10 @@ namespace SeaHaven.Services.Implementation
|
|||
PONumber = r.PONumber,
|
||||
WorkOrderId = r.WorkOrderId,
|
||||
VendorCompanyName = r.VendorCompanyName,
|
||||
WorkOrderNumber = r.WorkOrderNumber,
|
||||
WorkOrderSite = r.WorkOrderSiteCode,
|
||||
WorkOrderService = r.WorkOrderService,
|
||||
RequestedByName = ResolveRequestedByName(r.RequestedByVendorName, r.RequestedByFirstName, r.RequestedByLastName),
|
||||
CurrentNTE = r.CurrentNTE,
|
||||
RequestedNTE = r.RequestedNTE,
|
||||
Delta = r.RequestedNTE - (r.CurrentNTE ?? 0m),
|
||||
|
|
@ -61,6 +65,26 @@ namespace SeaHaven.Services.Implementation
|
|||
NotificationError = r.NotificationError
|
||||
}).ToList();
|
||||
|
||||
// Approved-on-WO exposure totals are aggregated once for the whole page
|
||||
// (single set-based data-service call) and then attached per item.
|
||||
var workOrderIds = mapped
|
||||
.Where(i => i.WorkOrderId.HasValue)
|
||||
.Select(i => i.WorkOrderId!.Value)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
var exposureByWorkOrder = (await _upliftData
|
||||
.GetApprovedExposureForWorkOrdersAsync(workOrderIds, cancellationToken))
|
||||
.ToDictionary(e => e.WorkOrderId);
|
||||
foreach (var item in mapped)
|
||||
{
|
||||
if (!item.WorkOrderId.HasValue) continue;
|
||||
if (!exposureByWorkOrder.TryGetValue(item.WorkOrderId.Value, out var exposure)) continue;
|
||||
|
||||
item.WorkOrderAutoApprovedTotal = exposure.AutoApprovedTotal;
|
||||
item.WorkOrderAdminApprovedTotal = exposure.AdminApprovedTotal;
|
||||
item.WorkOrderApprovedExposureTotal = exposure.AutoApprovedTotal + exposure.AdminApprovedTotal;
|
||||
}
|
||||
|
||||
return new UpliftListResultDTO
|
||||
{
|
||||
Total = total,
|
||||
|
|
@ -275,6 +299,19 @@ namespace SeaHaven.Services.Implementation
|
|||
return false;
|
||||
}
|
||||
|
||||
// Approval queue read contract: the requester label prefers the recorded
|
||||
// requester (vendor or internal display name captured at creation) and falls
|
||||
// back to the creating user's name resolved server-side.
|
||||
private static string? ResolveRequestedByName(string? vendorName, string? firstName, string? lastName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(vendorName))
|
||||
return vendorName;
|
||||
|
||||
var composed = string.Join(" ", new[] { firstName, lastName }
|
||||
.Where(s => !string.IsNullOrWhiteSpace(s))).Trim();
|
||||
return composed.Length > 0 ? composed : null;
|
||||
}
|
||||
|
||||
private string[] RolesForTier(int requiredTier) => requiredTier switch
|
||||
{
|
||||
1 => _approvalsOptions.Tier1Roles,
|
||||
|
|
|
|||
|
|
@ -441,6 +441,7 @@ public class WorkOrderBoardCancelServiceTests
|
|||
public Task<bool> HasPendingAsync(int dispatchId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<bool> HasPendingForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<decimal> SumAutoApprovedAmountForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<WorkOrderUpliftExposureData>> GetApprovedExposureForWorkOrdersAsync(IReadOnlyCollection<int> workOrderIds, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<List<DispatchUpliftRequest>> GetPendingForWorkOrderAsync(int workOrderId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<bool> HasActiveAsync(int dispatchId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
public Task<DispatchUpliftRequest?> GetActiveRequestAsync(int dispatchId, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue