Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e67675a12a | |||
| 2ecda623ac | |||
| da9caa855a | |||
| 5c4e1b590a | |||
| 75b5035354 | |||
| c0432a448f | |||
| bfbfe352ee | |||
| 320da0e1c9 | |||
| f0d7f939ef | |||
| 8b84c8aeb3 | |||
| 9febae6d63 | |||
| df27d58089 | |||
| 4e12e9f8f1 | |||
| 39eab2e3a2 | |||
| 889ca0795d | |||
| a7801a2bc2 | |||
| f4db83654c | |||
| d414ec8e38 | |||
| dc7e7a70fc | |||
| 20b82a2734 | |||
| 83d3272784 | |||
| d6cd9ccd08 | |||
| 1bee5f91c6 | |||
| 08ad17f15b | |||
| 97a1db1343 | |||
| 3268a50c3e | |||
| f1c036d1d8 | |||
| 92fef1dfa8 | |||
| b279a121ad |
@@ -1,4 +1,5 @@
|
||||
using Distribution.Features.Region;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
using Moq;
|
||||
@@ -10,11 +11,14 @@ public class RegionServiceTests
|
||||
{
|
||||
private readonly Mock<IRegionRepository> _repo = new();
|
||||
private readonly Mock<IUnitOfWork> _uow = new();
|
||||
private readonly Mock<ICurrentUserService> _currentUser = new();
|
||||
private readonly Mock<IScopeAccessService> _scopeAccess = new();
|
||||
private readonly RegionService _sut;
|
||||
|
||||
public RegionServiceTests()
|
||||
{
|
||||
_sut = new RegionService(_repo.Object, _uow.Object);
|
||||
_currentUser.Setup(u => u.RoleLevel).Returns(60);
|
||||
_sut = new RegionService(_repo.Object, _uow.Object, _currentUser.Object, _scopeAccess.Object);
|
||||
}
|
||||
|
||||
private static Region ActiveRegion(string name = "North") =>
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
using Distribution.Features.Region;
|
||||
using Distribution.Features.Route;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace Distribution.Tests.Services;
|
||||
|
||||
public class RouteServiceTests
|
||||
{
|
||||
private readonly Mock<IRouteRepository> _repo = new();
|
||||
private readonly Mock<IRegionRepository> _regionRepo = new();
|
||||
private readonly Mock<IUnitOfWork> _uow = new();
|
||||
private readonly Mock<ICurrentUserService> _currentUser = new();
|
||||
private readonly Mock<IScopeAccessService> _scopeAccess = new();
|
||||
private readonly RouteService _sut;
|
||||
|
||||
private static readonly Guid RepUserId = Guid.NewGuid();
|
||||
|
||||
public RouteServiceTests()
|
||||
{
|
||||
_currentUser.Setup(u => u.RoleLevel).Returns(20);
|
||||
_currentUser.Setup(u => u.UserId).Returns(RepUserId);
|
||||
_sut = new RouteService(_repo.Object, _regionRepo.Object, _uow.Object, _currentUser.Object, _scopeAccess.Object);
|
||||
}
|
||||
|
||||
private static Models.Route ActiveRoute(Guid? ownerId = null) =>
|
||||
new() { Id = Guid.NewGuid(), RouteName = "R1", StartPoint = "A", EndPoint = "B", Length = 10, IsActive = true, FK_OwnerUserId = ownerId };
|
||||
|
||||
private static Models.Route InactiveRoute() =>
|
||||
new() { Id = Guid.NewGuid(), RouteName = "Old", StartPoint = "A", EndPoint = "B", Length = 10, IsActive = false };
|
||||
|
||||
private static Store ActiveStore(Guid routeId, decimal lat = 10m, decimal lon = 20m) =>
|
||||
new() { Id = Guid.NewGuid(), FK_RouteId = routeId, IsActive = true, Latitude = lat, Longitude = lon };
|
||||
|
||||
// AssignStoresToRouteAsync
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_ReturnsNull_WhenRouteNotFound()
|
||||
{
|
||||
_repo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync((Models.Route?)null);
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(Guid.NewGuid(), new AssignStoresToRouteRequest([Guid.NewGuid()]));
|
||||
|
||||
Assert.Null(result);
|
||||
_uow.Verify(u => u.BeginAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_ReturnsNull_WhenRouteInactive()
|
||||
{
|
||||
_repo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync(InactiveRoute());
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(Guid.NewGuid(), new AssignStoresToRouteRequest([Guid.NewGuid()]));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_ReturnsNull_WhenCallerLacksRouteScope()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(false);
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(route.Id, new AssignStoresToRouteRequest([Guid.NewGuid()]));
|
||||
|
||||
Assert.Null(result);
|
||||
_uow.Verify(u => u.BeginAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_ReturnsNull_WhenCallerBelowRoleFloor()
|
||||
{
|
||||
_currentUser.Setup(u => u.RoleLevel).Returns(10);
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(route.Id, new AssignStoresToRouteRequest([Guid.NewGuid()]));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_ReturnsNull_WhenAnyStoreIdMissing()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
var storeIds = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() };
|
||||
_repo.Setup(r => r.GetStoresByIdsAsync(storeIds)).ReturnsAsync([ActiveStore(route.Id)]); // only one of two found
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(route.Id, new AssignStoresToRouteRequest(storeIds));
|
||||
|
||||
Assert.Null(result);
|
||||
_uow.Verify(u => u.BeginAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_UpdatesEachStore_AndCommits()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var otherRouteId = Guid.NewGuid();
|
||||
var stores = new List<Store> { ActiveStore(otherRouteId), ActiveStore(otherRouteId) };
|
||||
var storeIds = stores.Select(s => s.Id).ToList();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoresByIdsAsync(storeIds)).ReturnsAsync(stores);
|
||||
|
||||
var result = await _sut.AssignStoresToRouteAsync(route.Id, new AssignStoresToRouteRequest(storeIds));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.All(stores, s => Assert.Equal(route.Id, s.FK_RouteId));
|
||||
_repo.Verify(r => r.UpdateStore(It.IsAny<Store>()), Times.Exactly(2));
|
||||
_uow.Verify(u => u.CommitAsync(default), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignStoresToRouteAsync_Rollbacks_WhenUpdateThrows()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var stores = new List<Store> { ActiveStore(route.Id) };
|
||||
var storeIds = stores.Select(s => s.Id).ToList();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoresByIdsAsync(storeIds)).ReturnsAsync(stores);
|
||||
_repo.Setup(r => r.UpdateStore(It.IsAny<Store>())).Throws(new Exception("db error"));
|
||||
|
||||
await Assert.ThrowsAsync<Exception>(() => _sut.AssignStoresToRouteAsync(route.Id, new AssignStoresToRouteRequest(storeIds)));
|
||||
|
||||
_uow.Verify(u => u.RollbackAsync(default), Times.Once);
|
||||
_uow.Verify(u => u.CommitAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
// AssignOwnerAsync
|
||||
|
||||
[Fact]
|
||||
public async Task AssignOwnerAsync_ReturnsNull_WhenRouteNotFound()
|
||||
{
|
||||
_repo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync((Models.Route?)null);
|
||||
|
||||
var result = await _sut.AssignOwnerAsync(Guid.NewGuid(), new AssignRouteOwnerRequest(Guid.NewGuid()));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignOwnerAsync_ReturnsNull_WhenTargetUserNotActive()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetActiveUserAsync(It.IsAny<Guid>())).ReturnsAsync((User?)null);
|
||||
|
||||
var result = await _sut.AssignOwnerAsync(route.Id, new AssignRouteOwnerRequest(Guid.NewGuid()));
|
||||
|
||||
Assert.Null(result);
|
||||
_uow.Verify(u => u.BeginAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignOwnerAsync_SetsOwner_AndCommits()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var salesRep = new User { Id = Guid.NewGuid(), IsActive = true };
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetActiveUserAsync(salesRep.Id)).ReturnsAsync(salesRep);
|
||||
|
||||
var result = await _sut.AssignOwnerAsync(route.Id, new AssignRouteOwnerRequest(salesRep.Id));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(salesRep.Id, result.OwnerUserId);
|
||||
Assert.Equal(salesRep.Id, route.FK_OwnerUserId);
|
||||
_uow.Verify(u => u.CommitAsync(default), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AssignOwnerAsync_AllowsReassignment_ToDifferentSalesRep()
|
||||
{
|
||||
var firstOwner = Guid.NewGuid();
|
||||
var route = ActiveRoute(firstOwner);
|
||||
var newRep = new User { Id = Guid.NewGuid(), IsActive = true };
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetActiveUserAsync(newRep.Id)).ReturnsAsync(newRep);
|
||||
|
||||
var result = await _sut.AssignOwnerAsync(route.Id, new AssignRouteOwnerRequest(newRep.Id));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(newRep.Id, result.OwnerUserId);
|
||||
Assert.NotEqual(firstOwner, result.OwnerUserId);
|
||||
}
|
||||
|
||||
// RecordCheckInAsync
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_ReturnsNull_WhenCallerNotAuthenticated()
|
||||
{
|
||||
_currentUser.Setup(u => u.UserId).Returns((Guid?)null);
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(Guid.NewGuid(), new RecordCheckInRequest(Guid.NewGuid(), 1, 2, null));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_ReturnsNull_WhenRouteNotFoundOrInactive()
|
||||
{
|
||||
_repo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync(InactiveRoute());
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(Guid.NewGuid(), new RecordCheckInRequest(Guid.NewGuid(), 1, 2, null));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_ReturnsNull_WhenCallerLacksRouteScope()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(false);
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(route.Id, new RecordCheckInRequest(Guid.NewGuid(), 1, 2, null));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_ReturnsNull_WhenStoreNotOnRoute()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var store = ActiveStore(Guid.NewGuid()); // belongs to a different route
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoreByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(route.Id, new RecordCheckInRequest(store.Id, 1, 2, null));
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_NotFlagged_WhenGpsMatchesStoreLocation()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var store = ActiveStore(route.Id, lat: 12.9716m, lon: 77.5946m);
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoreByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(route.Id, new RecordCheckInRequest(store.Id, 12.9716m, 77.5946m, null));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.False(result.IsDeviationFlagged);
|
||||
_repo.Verify(r => r.AddVisitLogAsync(It.IsAny<RouteVisitLog>()), Times.Once);
|
||||
_uow.Verify(u => u.CommitAsync(default), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_Flagged_WhenGpsFarFromStoreLocation()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var store = ActiveStore(route.Id, lat: 12.9716m, lon: 77.5946m); // Bengaluru
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoreByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
|
||||
// Mumbai coordinates - hundreds of km away
|
||||
var result = await _sut.RecordCheckInAsync(route.Id, new RecordCheckInRequest(store.Id, 19.0760m, 72.8777m, null));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.True(result.IsDeviationFlagged);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckInAsync_UsesCurrentUserId_AsVisitingRep()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var store = ActiveStore(route.Id);
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetStoreByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
|
||||
var result = await _sut.RecordCheckInAsync(route.Id, new RecordCheckInRequest(store.Id, store.Latitude, store.Longitude, null));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(RepUserId, result.UserId);
|
||||
}
|
||||
|
||||
// RecordCheckOutAsync
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckOutAsync_ReturnsNull_WhenNoOpenVisit()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetOpenVisitAsync(route.Id, It.IsAny<Guid>())).ReturnsAsync((RouteVisitLog?)null);
|
||||
|
||||
var result = await _sut.RecordCheckOutAsync(route.Id, new RecordCheckOutRequest(Guid.NewGuid(), null));
|
||||
|
||||
Assert.Null(result);
|
||||
_uow.Verify(u => u.BeginAsync(default), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckOutAsync_SetsCheckOutAt_AndCommits()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var storeId = Guid.NewGuid();
|
||||
var log = new RouteVisitLog { Id = Guid.NewGuid(), FK_RouteId = route.Id, FK_StoreId = storeId, FK_UserId = RepUserId, CheckInAt = DateTime.Now.AddHours(-1) };
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetOpenVisitAsync(route.Id, storeId)).ReturnsAsync(log);
|
||||
|
||||
var result = await _sut.RecordCheckOutAsync(route.Id, new RecordCheckOutRequest(storeId, null));
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.NotNull(result.CheckOutAt);
|
||||
Assert.NotNull(log.CheckOutAt);
|
||||
_repo.Verify(r => r.UpdateVisitLog(log), Times.Once);
|
||||
_uow.Verify(u => u.CommitAsync(default), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordCheckOutAsync_Rollbacks_WhenUpdateThrows()
|
||||
{
|
||||
var route = ActiveRoute();
|
||||
var storeId = Guid.NewGuid();
|
||||
var log = new RouteVisitLog { Id = Guid.NewGuid(), FK_RouteId = route.Id, FK_StoreId = storeId, FK_UserId = RepUserId, CheckInAt = DateTime.Now };
|
||||
_repo.Setup(r => r.GetByIdAsync(route.Id)).ReturnsAsync(route);
|
||||
_scopeAccess.Setup(s => s.HasRouteScopeAsync(RepUserId, route.Id)).ReturnsAsync(true);
|
||||
_repo.Setup(r => r.GetOpenVisitAsync(route.Id, storeId)).ReturnsAsync(log);
|
||||
_repo.Setup(r => r.UpdateVisitLog(It.IsAny<RouteVisitLog>())).Throws(new Exception("db error"));
|
||||
|
||||
await Assert.ThrowsAsync<Exception>(() => _sut.RecordCheckOutAsync(route.Id, new RecordCheckOutRequest(storeId, null)));
|
||||
|
||||
_uow.Verify(u => u.RollbackAsync(default), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Distribution.Features.Item;
|
||||
using Distribution.Features.Order;
|
||||
using Distribution.Features.Route;
|
||||
using Distribution.Features.Scheme;
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Features.Store;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace Distribution.Tests.Services;
|
||||
|
||||
public class StoreServiceTests
|
||||
{
|
||||
private readonly Mock<IStoreRepository> _repo = new();
|
||||
private readonly Mock<IUnitOfWork> _uow = new();
|
||||
private readonly Mock<ICurrentUserService> _currentUser = new();
|
||||
private readonly Mock<IScopeAccessService> _scopeAccess = new();
|
||||
private readonly Mock<IRouteRepository> _routeRepo = new();
|
||||
private readonly StoreService _sut;
|
||||
|
||||
public StoreServiceTests()
|
||||
{
|
||||
_currentUser.Setup(u => u.RoleLevel).Returns(50); // global scope, skips per-store scope lookups
|
||||
var schemeService = new SchemeService(
|
||||
Mock.Of<ISchemeRepository>(),
|
||||
Mock.Of<IOrderRepository>(),
|
||||
Mock.Of<IItemRepository>(),
|
||||
_repo.Object,
|
||||
Mock.Of<IStockRepository>(),
|
||||
_uow.Object);
|
||||
_sut = new StoreService(_repo.Object, _uow.Object, _currentUser.Object, _scopeAccess.Object, schemeService, _routeRepo.Object);
|
||||
}
|
||||
|
||||
private static Store ActiveStore() =>
|
||||
new() { Id = Guid.NewGuid(), IsActive = true };
|
||||
|
||||
// GetVisitHistoryAsync
|
||||
|
||||
[Fact]
|
||||
public async Task GetVisitHistoryAsync_ReturnsNull_WhenStoreNotFound()
|
||||
{
|
||||
_repo.Setup(r => r.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync((Store?)null);
|
||||
|
||||
var result = await _sut.GetVisitHistoryAsync(Guid.NewGuid());
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetVisitHistoryAsync_ReturnsEmpty_WhenNoVisitsLogged()
|
||||
{
|
||||
var store = ActiveStore();
|
||||
_repo.Setup(r => r.GetByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
_routeRepo.Setup(r => r.GetVisitsByStoreIdAsync(store.Id)).ReturnsAsync([]);
|
||||
|
||||
var result = await _sut.GetVisitHistoryAsync(store.Id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Empty(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetVisitHistoryAsync_MapsVisits_MostRecentFirst()
|
||||
{
|
||||
var store = ActiveStore();
|
||||
var repId = Guid.NewGuid();
|
||||
var older = new RouteVisitLog { Id = Guid.NewGuid(), FK_StoreId = store.Id, FK_UserId = repId, CheckInAt = DateTime.Now.AddDays(-2), CheckOutAt = DateTime.Now.AddDays(-2).AddHours(1) };
|
||||
var newer = new RouteVisitLog { Id = Guid.NewGuid(), FK_StoreId = store.Id, FK_UserId = repId, CheckInAt = DateTime.Now.AddDays(-1), CheckOutAt = null };
|
||||
_repo.Setup(r => r.GetByIdAsync(store.Id)).ReturnsAsync(store);
|
||||
_routeRepo.Setup(r => r.GetVisitsByStoreIdAsync(store.Id)).ReturnsAsync([older, newer]);
|
||||
|
||||
var result = await _sut.GetVisitHistoryAsync(store.Id);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, result.Count);
|
||||
Assert.Equal(newer.Id, result[0].VisitId);
|
||||
Assert.Equal("In Progress", result[0].Outcome);
|
||||
Assert.Equal(older.Id, result[1].VisitId);
|
||||
Assert.Equal("Completed", result[1].Outcome);
|
||||
Assert.Equal(repId, result[0].RepUserId);
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,11 @@ public class AppDBContext(DbContextOptions<AppDBContext> options) : DbContext(op
|
||||
public DbSet<Claim> Claims { get; set; }
|
||||
public DbSet<SupplierClaim> SupplierClaims { get; set; }
|
||||
public DbSet<SupplierClaimItem> SupplierClaimItems { get; set; }
|
||||
public DbSet<RegionalTarget> RegionalTargets { get; set; }
|
||||
public DbSet<RegionalBudget> RegionalBudgets { get; set; }
|
||||
public DbSet<RegionAgencyMap> RegionAgencyMaps { get; set; }
|
||||
public DbSet<RegionalTaxRule> RegionalTaxRules { get; set; }
|
||||
public DbSet<RouteVisitLog> RouteVisitLogs { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -373,6 +378,28 @@ public class AppDBContext(DbContextOptions<AppDBContext> options) : DbContext(op
|
||||
.HasForeignKey(t => t.FK_OrderId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<RegionalTarget>()
|
||||
.HasIndex(t => new { t.FK_RegionId, t.Period })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<RegionalBudget>()
|
||||
.HasIndex(b => new { b.FK_RegionId, b.Period })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<RegionAgencyMap>()
|
||||
.HasIndex(m => new { m.FK_RegionId, m.FK_AgencyUserId })
|
||||
.IsUnique();
|
||||
|
||||
modelBuilder.Entity<RegionAgencyMap>()
|
||||
.HasOne(m => m.AgencyUser)
|
||||
.WithMany()
|
||||
.HasForeignKey(m => m.FK_AgencyUserId)
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
modelBuilder.Entity<RegionalTaxRule>()
|
||||
.HasIndex(r => r.FK_RegionId)
|
||||
.IsUnique();
|
||||
|
||||
Seed.RoleAndPermissionSeed.Apply(modelBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,37 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies all authentication traffic from the Next.js frontend to the
|
||||
/// external Auth Service. The frontend must never call the Auth Service
|
||||
/// directly — all auth goes through this controller.
|
||||
///
|
||||
/// TODO: Implement endpoints once Auth Service contract is agreed.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController(IAuthServiceClient authServiceClient) : ControllerBase
|
||||
public class AuthController(AuthService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
// TODO: replace stub endpoints below with real proxy calls once
|
||||
// the Auth Service API contract is finalised.
|
||||
private static IActionResult ToActionResult(AuthHexResponse result) =>
|
||||
result.Success ? new OkObjectResult(result) : new ObjectResult(result) { StatusCode = result.StatusCode is >= 400 and < 600 ? result.StatusCode : 401 };
|
||||
|
||||
[HttpPost("login")]
|
||||
public Task<IActionResult> Login()
|
||||
public async Task<IActionResult> Login(LoginRequest request, CancellationToken ct) =>
|
||||
ToActionResult(await service.LoginAsync(request, ct));
|
||||
|
||||
[HttpPost("register")]
|
||||
public async Task<IActionResult> Register(RegisterRequest request, CancellationToken ct) =>
|
||||
ToActionResult(await service.RegisterAsync(request, ct));
|
||||
|
||||
[HttpGet("me")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Me(CancellationToken ct)
|
||||
{
|
||||
// TODO: accept login request shape from Auth Service contract,
|
||||
// forward to authServiceClient, relay response (token / session) back.
|
||||
return Task.FromResult<IActionResult>(StatusCode(501, new { error = "Auth integration not yet implemented." }));
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
return ToActionResult(await service.GetUserDetailsAsync(userId, ct));
|
||||
}
|
||||
|
||||
// TODO: add further endpoints as needed (refresh, logout, etc.)
|
||||
[HttpPost("logout")]
|
||||
[Authorize]
|
||||
public async Task<IActionResult> Logout(CancellationToken ct)
|
||||
{
|
||||
var token = Request.Headers.Authorization.ToString().Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
|
||||
return ToActionResult(await service.LogoutAsync(token, ct));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
// TODO: Define request/response shapes once the Auth Service contract is agreed.
|
||||
// These will be the DTOs passed between the Next.js frontend and this proxy controller,
|
||||
// which should mirror (or adapt) whatever the Auth Service expects/returns.
|
||||
public record LoginRequest(string Username, string Password);
|
||||
|
||||
public record RegisterRequest(string Username, string Password, string? FullName);
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
|
||||
namespace Distribution.Features.Auth;
|
||||
|
||||
// TODO: This service previously contained local password validation logic.
|
||||
// It has been replaced by the IAuthServiceClient connector which proxies
|
||||
// to the external Auth Service. Remove this file or repurpose it for any
|
||||
// local orchestration logic once the Auth Service contract is defined.
|
||||
/// <summary>
|
||||
/// Own-user auth is fully delegated to AuthHex — this service only proxies the four functions
|
||||
/// AuthHex exposes (loginUser/registerUser/getUserDetails/LogoutUser). No local password check or
|
||||
/// token issuance happens here; AuthHex owns credentials and signs the JWT this app validates
|
||||
/// (see Program.cs's JwtBearer registration + OnTokenValidated role mapping).
|
||||
/// </summary>
|
||||
public class AuthService(IAuthHexClient authHex)
|
||||
{
|
||||
public Task<AuthHexResponse> LoginAsync(LoginRequest request, CancellationToken ct = default) =>
|
||||
authHex.CallAsync("loginUser", request, reference: Guid.NewGuid().ToString(), ct: ct);
|
||||
|
||||
public Task<AuthHexResponse> RegisterAsync(RegisterRequest request, CancellationToken ct = default) =>
|
||||
authHex.CallAsync("registerUser", request, reference: Guid.NewGuid().ToString(), ct: ct);
|
||||
|
||||
public Task<AuthHexResponse> GetUserDetailsAsync(Guid userId, CancellationToken ct = default) =>
|
||||
authHex.CallAsync("getUserDetails", new { userId }, ct: ct);
|
||||
|
||||
public Task<AuthHexResponse> LogoutAsync(string token, CancellationToken ct = default) =>
|
||||
authHex.CallAsync("LogoutUser", new { token }, ct: ct);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Brand;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/brands")]
|
||||
[Authorize]
|
||||
public class BrandController(BrandService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class BrandController(BrandService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "items.create")]
|
||||
public async Task<IActionResult> Create(CreateBrandRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class BrandController(BrandService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "items.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateBrandRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class BrandController(BrandService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "items.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Category;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class CategoryController(CategoryService service) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/categories")]
|
||||
[Authorize(Policy = "categories.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("api/categories/{id:guid}")]
|
||||
[Authorize(Policy = "categories.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -21,7 +17,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost("api/categories")]
|
||||
[Authorize(Policy = "categories.create")]
|
||||
public async Task<IActionResult> Create(CreateCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -29,7 +24,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("api/categories/{id:guid}")]
|
||||
[Authorize(Policy = "categories.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -37,7 +31,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("api/categories/{id:guid}")]
|
||||
[Authorize(Policy = "categories.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
@@ -45,7 +38,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost("api/categories/{categoryId:guid}/subcategories")]
|
||||
[Authorize(Policy = "categories.create")]
|
||||
public async Task<IActionResult> CreateSubCategory(Guid categoryId, CreateSubCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateSubCategoryAsync(categoryId, request, ct);
|
||||
@@ -53,7 +45,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("api/subcategories/{id:guid}")]
|
||||
[Authorize(Policy = "categories.update")]
|
||||
public async Task<IActionResult> UpdateSubCategory(Guid id, UpdateSubCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateSubCategoryAsync(id, request, ct);
|
||||
@@ -61,7 +52,6 @@ public class CategoryController(CategoryService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("api/subcategories/{id:guid}")]
|
||||
[Authorize(Policy = "categories.delete")]
|
||||
public async Task<IActionResult> DeleteSubCategory(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteSubCategoryAsync(id, ct);
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Claims;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ClaimController(ClaimService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/claims/{id:guid}")]
|
||||
@@ -27,7 +25,6 @@ public class ClaimController(ClaimService service, ICurrentUserService currentUs
|
||||
}
|
||||
|
||||
[HttpPost("api/claims/{id:guid}/settle")]
|
||||
[Authorize(Policy = "claims.settle")]
|
||||
public async Task<IActionResult> Settle(Guid id, SettleClaimRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.DeliveryRide;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api")]
|
||||
public class DeliveryTaskController(DeliveryTaskService service) : ControllerBase
|
||||
{
|
||||
@@ -21,6 +19,7 @@ public class DeliveryTaskController(DeliveryTaskService service) : ControllerBas
|
||||
}
|
||||
|
||||
[HttpGet("rides/{rideId:guid}/tasks")]
|
||||
[HttpGet("rides/{rideId:guid}/delivery-tasks")]
|
||||
public async Task<IActionResult> GetByRide(Guid rideId)
|
||||
{
|
||||
var result = await service.GetByRideIdAsync(rideId);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.DriverComplianceConfig;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/driver-compliance-config")]
|
||||
[Authorize]
|
||||
public class DriverComplianceConfigController(DriverComplianceConfigService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "compliance.manage")]
|
||||
public async Task<IActionResult> Get()
|
||||
{
|
||||
var result = await service.GetAsync();
|
||||
return result is null ? NoContent() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
[Authorize(Policy = "compliance.manage")]
|
||||
public async Task<IActionResult> Upsert(UpdateDriverComplianceConfigRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
var result = await service.UpsertAsync(request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Features.DriverComplianceConfig;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/driver-profiles")]
|
||||
[Authorize]
|
||||
public class DriverProfileController(DriverProfileService service) : ControllerBase
|
||||
public class DriverProfileController(
|
||||
DriverProfileService service,
|
||||
DriverComplianceConfigService complianceService,
|
||||
ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "driver_profiles.view")]
|
||||
public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(page, pageSize);
|
||||
@@ -17,7 +19,6 @@ public class DriverProfileController(DriverProfileService service) : ControllerB
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -25,15 +26,24 @@ public class DriverProfileController(DriverProfileService service) : ControllerB
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "driver_profiles.create")]
|
||||
public async Task<IActionResult> Create(CreateDriverProfileRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
try
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
return NotFound(new { error = ex.Message });
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return Conflict(new { error = ex.Message });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateDriverProfileRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -41,10 +51,24 @@ public class DriverProfileController(DriverProfileService service) : ControllerB
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "driver_profiles.deactivate")]
|
||||
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
|
||||
{
|
||||
var success = await service.DeactivateAsync(id, ct);
|
||||
return success ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
[HttpGet("compliance")]
|
||||
public async Task<IActionResult> GetCompliance()
|
||||
{
|
||||
var result = await complianceService.GetAsync();
|
||||
return result is null ? NoContent() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("compliance")]
|
||||
public async Task<IActionResult> UpsertCompliance(UpdateDriverComplianceConfigRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
var result = await complianceService.UpsertAsync(request, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ public record DriverProfileResponse(
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateDriverProfileRequest(
|
||||
Guid FK_UserId,
|
||||
Guid UserId,
|
||||
string LicenseNumber,
|
||||
DateTime LicenseExpiry,
|
||||
DateTime MedicalClearanceExpiry);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Features.User;
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.DriverProfile;
|
||||
|
||||
public class DriverProfileService(IDriverProfileRepository repo, IUnitOfWork uow)
|
||||
public class DriverProfileService(IDriverProfileRepository repo, IUnitOfWork uow, IUserRepository userRepo)
|
||||
{
|
||||
public async Task<PagedResponse<DriverProfileResponse>> GetAllAsync(int page, int pageSize)
|
||||
{
|
||||
@@ -21,13 +22,17 @@ public class DriverProfileService(IDriverProfileRepository repo, IUnitOfWork uow
|
||||
|
||||
public async Task<DriverProfileResponse> CreateAsync(CreateDriverProfileRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var existing = await repo.GetByUserIdAsync(request.FK_UserId);
|
||||
var user = await userRepo.GetByIdAsync(request.UserId);
|
||||
if (user is null)
|
||||
throw new KeyNotFoundException($"User {request.UserId} not found");
|
||||
|
||||
var existing = await repo.GetByUserIdAsync(request.UserId);
|
||||
if (existing is not null && existing.IsActive)
|
||||
throw new InvalidOperationException("An active driver profile already exists for this user");
|
||||
|
||||
var profile = new global::Distribution.Models.DriverProfile
|
||||
{
|
||||
FK_UserId = request.FK_UserId,
|
||||
FK_UserId = request.UserId,
|
||||
LicenseNumber = request.LicenseNumber,
|
||||
LicenseExpiry = request.LicenseExpiry,
|
||||
MedicalClearanceExpiry = request.MedicalClearanceExpiry
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Grn;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class GrnController(GrnService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/goods-receipts")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? purchaseOrderId,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(purchaseOrderId, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("api/goods-receipts/{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
@@ -15,6 +23,19 @@ public class GrnController(GrnService service, ICurrentUserService currentUser)
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("api/goods-receipts")]
|
||||
public async Task<IActionResult> CreateFlat(CreateFlatGrnRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var inner = new CreateGrnRequest(request.WarehouseId, request.Items);
|
||||
var result = await service.CreateAsync(request.PurchaseOrderId, inner, userId, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (InvalidOperationException ex) { return Conflict(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpGet("api/purchase-orders/{id:guid}/goods-receipts")]
|
||||
public async Task<IActionResult> GetByPurchaseOrder(Guid id) =>
|
||||
Ok(await service.GetByPurchaseOrderIdAsync(id));
|
||||
|
||||
@@ -4,6 +4,8 @@ public record GrnItemRequest(Guid PurchaseOrderItemId, int AcceptedQuantity, int
|
||||
|
||||
public record CreateGrnRequest(Guid WarehouseId, List<GrnItemRequest> Items);
|
||||
|
||||
public record CreateFlatGrnRequest(Guid PurchaseOrderId, Guid WarehouseId, List<GrnItemRequest> Items);
|
||||
|
||||
public record GrnItemResponse(
|
||||
Guid Id,
|
||||
Guid PurchaseOrderItemId,
|
||||
|
||||
@@ -11,6 +11,21 @@ public class GrnRepository(AppDBContext context) : IGrnRepository
|
||||
.Include(gr => gr.Items).ThenInclude(i => i.PurchaseOrderItem).ThenInclude(poi => poi.Item)
|
||||
.FirstOrDefaultAsync(gr => gr.Id == id);
|
||||
|
||||
public async Task<List<Models.GoodsReceipt>> GetAllAsync(Guid? purchaseOrderId, int page, int pageSize) =>
|
||||
await context.GoodsReceipts
|
||||
.Include(gr => gr.Warehouse)
|
||||
.Include(gr => gr.Items).ThenInclude(i => i.PurchaseOrderItem).ThenInclude(poi => poi.Item)
|
||||
.Where(gr => gr.IsActive && (purchaseOrderId == null || gr.FK_PurchaseOrderId == purchaseOrderId))
|
||||
.OrderByDescending(gr => gr.ReceivedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? purchaseOrderId) =>
|
||||
await context.GoodsReceipts
|
||||
.Where(gr => gr.IsActive && (purchaseOrderId == null || gr.FK_PurchaseOrderId == purchaseOrderId))
|
||||
.CountAsync();
|
||||
|
||||
public async Task<List<Models.GoodsReceipt>> GetByPurchaseOrderIdAsync(Guid purchaseOrderId) =>
|
||||
await context.GoodsReceipts
|
||||
.Include(gr => gr.Warehouse)
|
||||
|
||||
@@ -19,6 +19,13 @@ public class GrnService(
|
||||
new(gr.Id, gr.FK_PurchaseOrderId, gr.FK_ReceivedByUserId, gr.FK_WarehouseId, gr.Warehouse?.Name ?? string.Empty,
|
||||
gr.ReceivedAt, gr.CreatedAt, gr.Items.Where(i => i.IsActive).Select(MapItem).ToList());
|
||||
|
||||
public async Task<PagedResponse<GrnResponse>> GetAllAsync(Guid? purchaseOrderId, int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync(purchaseOrderId);
|
||||
var items = await repo.GetAllAsync(purchaseOrderId, page, pageSize);
|
||||
return new PagedResponse<GrnResponse>(page, pageSize, total, items.Select(Map).ToList());
|
||||
}
|
||||
|
||||
public async Task<GrnResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var gr = await repo.GetByIdAsync(id);
|
||||
|
||||
@@ -3,6 +3,8 @@ namespace Distribution.Features.Grn;
|
||||
public interface IGrnRepository
|
||||
{
|
||||
Task<Models.GoodsReceipt?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.GoodsReceipt>> GetAllAsync(Guid? purchaseOrderId, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? purchaseOrderId);
|
||||
Task<List<Models.GoodsReceipt>> GetByPurchaseOrderIdAsync(Guid purchaseOrderId);
|
||||
Task AddAsync(Models.GoodsReceipt entity);
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Item;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/items")]
|
||||
[Authorize]
|
||||
public class ItemController(ItemService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? categoryId,
|
||||
[FromQuery] Guid? subCategoryId,
|
||||
@@ -17,7 +14,6 @@ public class ItemController(ItemService service) : ControllerBase
|
||||
Ok(await service.GetAllAsync(categoryId, subCategoryId, brandId));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -25,7 +21,6 @@ public class ItemController(ItemService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "items.create")]
|
||||
public async Task<IActionResult> Create(CreateItemRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -40,7 +35,6 @@ public class ItemController(ItemService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "items.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateItemRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -48,7 +42,6 @@ public class ItemController(ItemService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "items.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
@@ -56,7 +49,6 @@ public class ItemController(ItemService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/uom-conversions")]
|
||||
[Authorize(Policy = "items.update")]
|
||||
public async Task<IActionResult> ReplaceConversions(Guid id, ReplaceConversionsRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.ReplaceConversionsAsync(id, request, ct);
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
using Distribution.Models;
|
||||
using Distribution.Models;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.LoadingEvent;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/loading-sheets")]
|
||||
[Authorize]
|
||||
public class LoadingSheetController(LoadingSheetService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "loading.view")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? rideId,
|
||||
[FromQuery] LoadingSheetStatus? status,
|
||||
@@ -23,7 +20,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "loading.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -31,7 +27,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> Create(CreateLoadingSheetRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -44,7 +39,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/items")]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> SetItems(Guid id, SetItemsRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -57,7 +51,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm-dispatch")]
|
||||
[Authorize(Policy = "loading.dispatch")]
|
||||
public async Task<IActionResult> ConfirmDispatch(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -71,7 +64,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/receipt-items")]
|
||||
[Authorize(Policy = "loading.receive")]
|
||||
public async Task<IActionResult> SetReceiptItems(Guid id, SetReceiptItemsRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -84,7 +76,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm-receipt")]
|
||||
[Authorize(Policy = "loading.receive")]
|
||||
public async Task<IActionResult> ConfirmReceipt(Guid id, ConfirmReceiptRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -98,7 +89,6 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/resolve")]
|
||||
[Authorize(Policy = "loading.resolve")]
|
||||
public async Task<IActionResult> Resolve(Guid id, ResolveDiscrepancyRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -110,4 +100,43 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/dispatch")]
|
||||
public async Task<IActionResult> PatchDispatch(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ConfirmDispatchAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/receipt")]
|
||||
public async Task<IActionResult> PatchReceipt(Guid id, PatchReceiptRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.PatchReceiptAsync(id, request.Items, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/resolve")]
|
||||
public async Task<IActionResult> PatchResolve(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.PatchResolveAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,3 +35,7 @@ public record ConfirmReceiptRequest(int Meterstart);
|
||||
|
||||
public record ResolveDiscrepancyRequest(List<ResolveItemInput> Items, int Meterstart);
|
||||
public record ResolveItemInput(Guid FK_ItemId, decimal QuantityResolved);
|
||||
|
||||
// Combined PATCH endpoints used by the frontend
|
||||
public record PatchReceiptItemInput(Guid ItemId, decimal QuantityReceived);
|
||||
public record PatchReceiptRequest(List<PatchReceiptItemInput> Items);
|
||||
|
||||
@@ -225,6 +225,98 @@ public class LoadingSheetService(
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> PatchReceiptAsync(Guid id, List<PatchReceiptItemInput> items, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.DispatchConfirmed)
|
||||
throw new InvalidOperationException($"Cannot set receipt for a sheet in {sheet.Status} status");
|
||||
|
||||
foreach (var input in items)
|
||||
{
|
||||
var sheetItem = sheet.Items.FirstOrDefault(i => i.FK_ItemId == input.ItemId)
|
||||
?? throw new InvalidOperationException($"Item {input.ItemId} is not on this loading sheet");
|
||||
sheetItem.QuantityReceived = input.QuantityReceived;
|
||||
}
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(sheet.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
var hasDiscrepancy = sheet.Items.Any(i => i.QuantityReceived != i.QuantityDispatched);
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (hasDiscrepancy)
|
||||
{
|
||||
sheet.Status = LoadingSheetStatus.DiscrepancyFlagged;
|
||||
}
|
||||
else
|
||||
{
|
||||
sheet.Status = LoadingSheetStatus.ReceiptConfirmed;
|
||||
sheet.ReceiptConfirmedAt = DateTime.Now;
|
||||
sheet.ReceiptConfirmedBy = userId;
|
||||
|
||||
var lines = sheet.Items.Select(i => (i.FK_ItemId, i.QuantityReceived!.Value)).ToList();
|
||||
await ApplyLoadMovementsAsync(sheet, ride.FK_VehicleId, lines, userId);
|
||||
|
||||
ride.Status = RideStatus.Active;
|
||||
ride.ActivatedAt = DateTime.Now;
|
||||
ride.Meterstart = 0;
|
||||
rideRepo.Update(ride);
|
||||
}
|
||||
|
||||
repo.Update(sheet);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
public async Task<LoadingSheetResponse> PatchResolveAsync(Guid id, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var sheet = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Loading sheet not found");
|
||||
|
||||
if (sheet.Status != LoadingSheetStatus.DiscrepancyFlagged)
|
||||
throw new InvalidOperationException($"Cannot resolve a sheet in {sheet.Status} status");
|
||||
|
||||
foreach (var item in sheet.Items)
|
||||
{
|
||||
if (!item.QuantityReceived.HasValue)
|
||||
throw new InvalidOperationException($"Item {item.FK_ItemId} has no received quantity to resolve from");
|
||||
item.QuantityResolved = item.QuantityReceived.Value;
|
||||
}
|
||||
|
||||
var ride = await rideRepo.GetByIdAsync(sheet.FK_RideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
sheet.Status = LoadingSheetStatus.Resolved;
|
||||
sheet.ReceiptConfirmedAt = DateTime.Now;
|
||||
sheet.ReceiptConfirmedBy = userId;
|
||||
|
||||
var lines = sheet.Items.Select(i => (i.FK_ItemId, i.QuantityResolved!.Value)).ToList();
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await ApplyLoadMovementsAsync(sheet, ride.FK_VehicleId, lines, userId);
|
||||
|
||||
ride.Status = RideStatus.Active;
|
||||
ride.ActivatedAt = DateTime.Now;
|
||||
ride.Meterstart = 0;
|
||||
rideRepo.Update(ride);
|
||||
|
||||
repo.Update(sheet);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(sheet);
|
||||
}
|
||||
|
||||
private async Task ApplyLoadMovementsAsync(LoadingSheet sheet, Guid vehicleId, List<(Guid ItemId, decimal Qty)> lines, Guid userId)
|
||||
{
|
||||
foreach (var (itemId, qty) in lines.Where(l => l.Qty > 0))
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Order;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/orders")]
|
||||
[Authorize]
|
||||
public class OrderController(OrderService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class OrderController(OrderService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("store/{storeId:guid}")]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetByStore(Guid storeId)
|
||||
{
|
||||
var result = await service.GetByStoreIdAsync(storeId);
|
||||
@@ -30,7 +25,6 @@ public class OrderController(OrderService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "orders.create")]
|
||||
public async Task<IActionResult> Create(CreateOrderRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -42,7 +36,6 @@ public class OrderController(OrderService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "orders.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateOrderRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -54,7 +47,6 @@ public class OrderController(OrderService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "orders.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Payment;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/payments")]
|
||||
public class FlatPaymentController(PaymentService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? storeId,
|
||||
[FromQuery] Guid? saleId,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(storeId, saleId, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreateFlatPaymentRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var inner = new CreatePaymentRequest(request.Amount, request.Method);
|
||||
var result = await service.CreateAsync(request.SaleId, inner, ct);
|
||||
return result is null ? NotFound(new { error = "Sale not found or access denied" }) : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ namespace Distribution.Features.Payment;
|
||||
|
||||
public interface IPaymentRepository
|
||||
{
|
||||
Task<Models.Payment?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.Payment>> GetAllAsync(Guid? storeId, Guid? saleId, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? storeId, Guid? saleId);
|
||||
Task<List<Models.Payment>> GetBySaleIdAsync(Guid saleId);
|
||||
Task AddAsync(Models.Payment payment);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Payment;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/sales/{saleId:guid}/payments")]
|
||||
public class PaymentController(PaymentService service) : ControllerBase
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Distribution.Features.Payment;
|
||||
|
||||
public record CreatePaymentRequest(decimal Amount, PaymentMethod Method);
|
||||
|
||||
public record CreateFlatPaymentRequest(Guid SaleId, decimal Amount, PaymentMethod Method);
|
||||
|
||||
public record PaymentResponse(
|
||||
Guid Id,
|
||||
Guid SaleId,
|
||||
|
||||
@@ -6,6 +6,26 @@ namespace Distribution.Features.Payment;
|
||||
|
||||
public class PaymentRepository(AppDBContext context) : IPaymentRepository
|
||||
{
|
||||
public async Task<Models.Payment?> GetByIdAsync(Guid id) =>
|
||||
await context.Payments.FirstOrDefaultAsync(p => p.Id == id && p.IsActive);
|
||||
|
||||
public async Task<List<Models.Payment>> GetAllAsync(Guid? storeId, Guid? saleId, int page, int pageSize) =>
|
||||
await context.Payments
|
||||
.Where(p => p.IsActive
|
||||
&& (storeId == null || p.FK_StoreId == storeId)
|
||||
&& (saleId == null || p.FK_SaleId == saleId))
|
||||
.OrderByDescending(p => p.CollectedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? storeId, Guid? saleId) =>
|
||||
await context.Payments
|
||||
.Where(p => p.IsActive
|
||||
&& (storeId == null || p.FK_StoreId == storeId)
|
||||
&& (saleId == null || p.FK_SaleId == saleId))
|
||||
.CountAsync();
|
||||
|
||||
public async Task<List<Models.Payment>> GetBySaleIdAsync(Guid saleId) =>
|
||||
await context.Payments
|
||||
.Where(p => p.FK_SaleId == saleId && p.IsActive)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Distribution.Features.Sale;
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
@@ -14,6 +15,19 @@ public class PaymentService(
|
||||
private static PaymentResponse ToResponse(Models.Payment p) =>
|
||||
new(p.Id, p.FK_SaleId, p.FK_StoreId, p.Amount, p.Method, p.CollectedAt, p.CollectedBy, p.CreatedAt);
|
||||
|
||||
public async Task<PagedResponse<PaymentResponse>> GetAllAsync(Guid? storeId, Guid? saleId, int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync(storeId, saleId);
|
||||
var items = await repo.GetAllAsync(storeId, saleId, page, pageSize);
|
||||
return new PagedResponse<PaymentResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<PaymentResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var payment = await repo.GetByIdAsync(id);
|
||||
return payment is null ? null : ToResponse(payment);
|
||||
}
|
||||
|
||||
public async Task<List<PaymentResponse>?> GetBySaleIdAsync(Guid saleId)
|
||||
{
|
||||
var sale = await saleRepo.GetByIdAsync(saleId);
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.PriceList;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/price-lists")]
|
||||
[Authorize]
|
||||
public class PriceListController(PriceListService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Po;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/purchase-orders")]
|
||||
[Authorize]
|
||||
public class PoController(PoService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.PurchaseReturn;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class PurchaseReturnController(PurchaseReturnService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/purchase-returns/{id:guid}")]
|
||||
|
||||
@@ -7,4 +7,26 @@ public interface IRegionRepository
|
||||
Task AddAsync(Models.Region entity);
|
||||
void Update(Models.Region entity);
|
||||
void Remove(Models.Region entity);
|
||||
|
||||
Task<Models.RegionalTarget?> GetTargetAsync(Guid regionId, string period);
|
||||
Task AddTargetAsync(Models.RegionalTarget target);
|
||||
void UpdateTarget(Models.RegionalTarget target);
|
||||
|
||||
Task<Models.RegionalBudget?> GetBudgetAsync(Guid regionId, string period);
|
||||
Task AddBudgetAsync(Models.RegionalBudget budget);
|
||||
void UpdateBudget(Models.RegionalBudget budget);
|
||||
|
||||
Task<Models.RegionAgencyMap?> GetAgencyMapAsync(Guid regionId, Guid agencyUserId);
|
||||
Task AddAgencyMapAsync(Models.RegionAgencyMap map);
|
||||
|
||||
Task<Models.RegionalTaxRule?> GetTaxRuleAsync(Guid regionId);
|
||||
Task AddTaxRuleAsync(Models.RegionalTaxRule rule);
|
||||
void UpdateTaxRule(Models.RegionalTaxRule rule);
|
||||
|
||||
Task<int?> GetUserRoleLevelAsync(Guid userId);
|
||||
|
||||
Task<List<Models.Route>> GetRoutesAsync(Guid regionId);
|
||||
Task<List<Models.Store>> GetStoresByRouteIdsAsync(List<Guid> routeIds);
|
||||
|
||||
Task<List<Models.Order>> GetOrdersForDashboardAsync(Guid regionId, DateTime periodStart, DateTime periodEndExclusive);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Region;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/regions")]
|
||||
[Authorize]
|
||||
public class RegionController(RegionService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "regions.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "regions.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class RegionController(RegionService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "regions.create")]
|
||||
public async Task<IActionResult> Create(CreateRegionRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class RegionController(RegionService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "regions.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateRegionRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,10 +32,51 @@ public class RegionController(RegionService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "regions.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/targets/{period}")]
|
||||
public async Task<IActionResult> SetTarget(Guid id, string period, SetRegionalTargetRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.SetTargetAsync(id, period, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/budgets/{period}")]
|
||||
public async Task<IActionResult> SetBudget(Guid id, string period, SetRegionalBudgetRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.SetBudgetAsync(id, period, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/agencies")]
|
||||
public async Task<IActionResult> MapAgency(Guid id, MapAgencyToRegionRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.MapAgencyAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/tax-rule")]
|
||||
public async Task<IActionResult> SetTaxRule(Guid id, SetRegionalTaxRuleRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.SetTaxRuleAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/hierarchy")]
|
||||
public async Task<IActionResult> GetHierarchy(Guid id)
|
||||
{
|
||||
var result = await service.GetHierarchyAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/dashboard")]
|
||||
public async Task<IActionResult> GetDashboard(Guid id, [FromQuery] string period)
|
||||
{
|
||||
var result = await service.GetDashboardAsync(id, period);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,3 +5,32 @@ public record CreateRegionRequest(string Name);
|
||||
public record UpdateRegionRequest(string Name);
|
||||
|
||||
public record RegionResponse(Guid Id, string Name, bool IsActive, DateTime CreatedAt);
|
||||
|
||||
public record SetRegionalTargetRequest(decimal TargetValue);
|
||||
|
||||
public record SetRegionalBudgetRequest(decimal BudgetAmount);
|
||||
|
||||
public record MapAgencyToRegionRequest(Guid AgencyUserId);
|
||||
|
||||
public record SetRegionalTaxRuleRequest(string RuleConfig);
|
||||
|
||||
public record RegionalTargetResponse(Guid RegionId, string Period, decimal TargetValue);
|
||||
|
||||
public record RegionalBudgetResponse(Guid RegionId, string Period, decimal BudgetAmount);
|
||||
|
||||
public record RegionAgencyMapResponse(Guid RegionId, Guid AgencyUserId);
|
||||
|
||||
public record RegionalTaxRuleResponse(Guid RegionId, string RuleConfig);
|
||||
|
||||
public record RegionHierarchyRouteItem(Guid RouteId, string RouteName, List<Guid> StoreIds);
|
||||
|
||||
public record RegionHierarchyResponse(Guid RegionId, string RegionName, List<RegionHierarchyRouteItem> Routes);
|
||||
|
||||
public record RegionDashboardResponse(
|
||||
Guid RegionId,
|
||||
string Period,
|
||||
decimal? TargetValue,
|
||||
decimal? BudgetAmount,
|
||||
int OrderCount,
|
||||
decimal ActualSales,
|
||||
DateTime? LastOrderDate);
|
||||
|
||||
@@ -22,4 +22,60 @@ public class RegionRepository(AppDBContext context) : IRegionRepository
|
||||
entity.IsActive = false;
|
||||
context.Regions.Update(entity);
|
||||
}
|
||||
|
||||
public async Task<Models.RegionalTarget?> GetTargetAsync(Guid regionId, string period) =>
|
||||
await context.RegionalTargets.FirstOrDefaultAsync(t =>
|
||||
t.FK_RegionId == regionId && t.Period == period && t.IsActive);
|
||||
|
||||
public async Task AddTargetAsync(Models.RegionalTarget target) =>
|
||||
await context.RegionalTargets.AddAsync(target);
|
||||
|
||||
public void UpdateTarget(Models.RegionalTarget target) =>
|
||||
context.RegionalTargets.Update(target);
|
||||
|
||||
public async Task<Models.RegionalBudget?> GetBudgetAsync(Guid regionId, string period) =>
|
||||
await context.RegionalBudgets.FirstOrDefaultAsync(b =>
|
||||
b.FK_RegionId == regionId && b.Period == period && b.IsActive);
|
||||
|
||||
public async Task AddBudgetAsync(Models.RegionalBudget budget) =>
|
||||
await context.RegionalBudgets.AddAsync(budget);
|
||||
|
||||
public void UpdateBudget(Models.RegionalBudget budget) =>
|
||||
context.RegionalBudgets.Update(budget);
|
||||
|
||||
public async Task<Models.RegionAgencyMap?> GetAgencyMapAsync(Guid regionId, Guid agencyUserId) =>
|
||||
await context.RegionAgencyMaps.FirstOrDefaultAsync(m =>
|
||||
m.FK_RegionId == regionId && m.FK_AgencyUserId == agencyUserId && m.IsActive);
|
||||
|
||||
public async Task AddAgencyMapAsync(Models.RegionAgencyMap map) =>
|
||||
await context.RegionAgencyMaps.AddAsync(map);
|
||||
|
||||
public async Task<Models.RegionalTaxRule?> GetTaxRuleAsync(Guid regionId) =>
|
||||
await context.RegionalTaxRules.FirstOrDefaultAsync(r => r.FK_RegionId == regionId && r.IsActive);
|
||||
|
||||
public async Task AddTaxRuleAsync(Models.RegionalTaxRule rule) =>
|
||||
await context.RegionalTaxRules.AddAsync(rule);
|
||||
|
||||
public void UpdateTaxRule(Models.RegionalTaxRule rule) =>
|
||||
context.RegionalTaxRules.Update(rule);
|
||||
|
||||
public async Task<int?> GetUserRoleLevelAsync(Guid userId) =>
|
||||
await context.Users
|
||||
.Where(u => u.Id == userId && u.IsActive)
|
||||
.Select(u => (int?)u.Role.Level)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
public async Task<List<Models.Route>> GetRoutesAsync(Guid regionId) =>
|
||||
await context.Routes.Where(r => r.FK_RegionId == regionId && r.IsActive).ToListAsync();
|
||||
|
||||
public async Task<List<Models.Store>> GetStoresByRouteIdsAsync(List<Guid> routeIds) =>
|
||||
await context.Stores.Where(s => routeIds.Contains(s.FK_RouteId) && s.IsActive).ToListAsync();
|
||||
|
||||
public async Task<List<Models.Order>> GetOrdersForDashboardAsync(Guid regionId, DateTime periodStart, DateTime periodEndExclusive) =>
|
||||
await (from o in context.Orders
|
||||
join s in context.Stores on o.FK_StoreId equals s.Id
|
||||
join r in context.Routes on s.FK_RouteId equals r.Id
|
||||
where r.FK_RegionId == regionId && o.IsActive && s.IsActive && r.IsActive
|
||||
&& o.OrderDate >= periodStart && o.OrderDate < periodEndExclusive
|
||||
select o).ToListAsync();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.Region;
|
||||
|
||||
public class RegionService(IRegionRepository repo, IUnitOfWork uow)
|
||||
public class RegionService(IRegionRepository repo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess)
|
||||
{
|
||||
private const int RegionalManagerRoleLevel = 50;
|
||||
private const int RegionalAgencyRoleLevel = 60;
|
||||
|
||||
private async Task<bool> CanManageRegionAsync(Guid regionId)
|
||||
{
|
||||
if (currentUser.RoleLevel >= RegionalAgencyRoleLevel) return true;
|
||||
if (currentUser.RoleLevel < RegionalManagerRoleLevel || currentUser.UserId is null) return false;
|
||||
return await scopeAccess.HasRegionScopeAsync(currentUser.UserId.Value, regionId);
|
||||
}
|
||||
|
||||
public async Task<List<RegionResponse>> GetAllAsync() =>
|
||||
(await repo.GetAllAsync())
|
||||
.Where(r => r.IsActive)
|
||||
@@ -70,4 +81,161 @@ public class RegionService(IRegionRepository repo, IUnitOfWork uow)
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<RegionalTargetResponse?> SetTargetAsync(Guid regionId, string period, SetRegionalTargetRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
if (!await CanManageRegionAsync(regionId)) return null;
|
||||
|
||||
var target = await repo.GetTargetAsync(regionId, period);
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (target is null)
|
||||
{
|
||||
target = new Models.RegionalTarget { FK_RegionId = regionId, Period = period, TargetValue = request.TargetValue };
|
||||
await repo.AddTargetAsync(target);
|
||||
}
|
||||
else
|
||||
{
|
||||
target.TargetValue = request.TargetValue;
|
||||
repo.UpdateTarget(target);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RegionalTargetResponse(regionId, period, target.TargetValue);
|
||||
}
|
||||
|
||||
public async Task<RegionalBudgetResponse?> SetBudgetAsync(Guid regionId, string period, SetRegionalBudgetRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
if (!await CanManageRegionAsync(regionId)) return null;
|
||||
|
||||
var budget = await repo.GetBudgetAsync(regionId, period);
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (budget is null)
|
||||
{
|
||||
budget = new Models.RegionalBudget { FK_RegionId = regionId, Period = period, BudgetAmount = request.BudgetAmount };
|
||||
await repo.AddBudgetAsync(budget);
|
||||
}
|
||||
else
|
||||
{
|
||||
budget.BudgetAmount = request.BudgetAmount;
|
||||
repo.UpdateBudget(budget);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RegionalBudgetResponse(regionId, period, budget.BudgetAmount);
|
||||
}
|
||||
|
||||
public async Task<RegionAgencyMapResponse?> MapAgencyAsync(Guid regionId, MapAgencyToRegionRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
if (!await CanManageRegionAsync(regionId)) return null;
|
||||
|
||||
var agencyRoleLevel = await repo.GetUserRoleLevelAsync(request.AgencyUserId);
|
||||
if (agencyRoleLevel is null || agencyRoleLevel < RegionalAgencyRoleLevel) return null;
|
||||
|
||||
var existing = await repo.GetAgencyMapAsync(regionId, request.AgencyUserId);
|
||||
if (existing is not null) return new RegionAgencyMapResponse(regionId, request.AgencyUserId);
|
||||
|
||||
var map = new Models.RegionAgencyMap { FK_RegionId = regionId, FK_AgencyUserId = request.AgencyUserId };
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddAgencyMapAsync(map);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RegionAgencyMapResponse(regionId, request.AgencyUserId);
|
||||
}
|
||||
|
||||
public async Task<RegionalTaxRuleResponse?> SetTaxRuleAsync(Guid regionId, SetRegionalTaxRuleRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
if (!await CanManageRegionAsync(regionId)) return null;
|
||||
|
||||
var rule = await repo.GetTaxRuleAsync(regionId);
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
if (rule is null)
|
||||
{
|
||||
rule = new Models.RegionalTaxRule { FK_RegionId = regionId, RuleConfig = request.RuleConfig };
|
||||
await repo.AddTaxRuleAsync(rule);
|
||||
}
|
||||
else
|
||||
{
|
||||
rule.RuleConfig = request.RuleConfig;
|
||||
repo.UpdateTaxRule(rule);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RegionalTaxRuleResponse(regionId, rule.RuleConfig);
|
||||
}
|
||||
|
||||
public async Task<RegionHierarchyResponse?> GetHierarchyAsync(Guid regionId)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
|
||||
var routes = await repo.GetRoutesAsync(regionId);
|
||||
var stores = await repo.GetStoresByRouteIdsAsync(routes.Select(r => r.Id).ToList());
|
||||
var routeItems = routes
|
||||
.Select(r => new RegionHierarchyRouteItem(
|
||||
r.Id,
|
||||
r.RouteName,
|
||||
stores.Where(s => s.FK_RouteId == r.Id).Select(s => s.Id).ToList()))
|
||||
.ToList();
|
||||
return new RegionHierarchyResponse(region.Id, region.Name, routeItems);
|
||||
}
|
||||
|
||||
public async Task<RegionDashboardResponse?> GetDashboardAsync(Guid regionId, string period)
|
||||
{
|
||||
var region = await repo.GetByIdAsync(regionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
|
||||
if (!DateTime.TryParseExact(period, "yyyy-MM", null, System.Globalization.DateTimeStyles.None, out var periodStart))
|
||||
periodStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
|
||||
var normalizedPeriod = periodStart.ToString("yyyy-MM");
|
||||
var periodEndExclusive = periodStart.AddMonths(1);
|
||||
|
||||
var target = await repo.GetTargetAsync(regionId, normalizedPeriod);
|
||||
var budget = await repo.GetBudgetAsync(regionId, normalizedPeriod);
|
||||
var orders = await repo.GetOrdersForDashboardAsync(regionId, periodStart, periodEndExclusive);
|
||||
|
||||
return new RegionDashboardResponse(
|
||||
regionId,
|
||||
normalizedPeriod,
|
||||
target?.TargetValue,
|
||||
budget?.BudgetAmount,
|
||||
orders.Count,
|
||||
orders.Sum(o => o.TotalAmount),
|
||||
orders.Count == 0 ? null : orders.Max(o => o.OrderDate));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Returns;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ReturnController(ReturnService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/returns/{id:guid}")]
|
||||
|
||||
@@ -1,17 +1,14 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Ride;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/rides")]
|
||||
[Authorize]
|
||||
public class RideController(RideService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] RideStatus? status,
|
||||
[FromQuery] RideType? type,
|
||||
@@ -25,7 +22,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -33,7 +29,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "rides.create")]
|
||||
public async Task<IActionResult> Create(CreateRideRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -41,7 +36,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/driver")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> AssignDriver(Guid id, AssignRideDriverRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -54,7 +48,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/open")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Open(Guid id, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -66,8 +59,8 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/activate")]
|
||||
[HttpPost("{id:guid}/activate")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Activate(Guid id, ActivateRideRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -79,8 +72,8 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/close")]
|
||||
[HttpPost("{id:guid}/close")]
|
||||
[Authorize(Policy = "rides.manage")]
|
||||
public async Task<IActionResult> Close(Guid id, CloseRideRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -93,7 +86,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/cancel-request")]
|
||||
[Authorize(Policy = "rides.cancel.request")]
|
||||
public async Task<IActionResult> RaiseCancelRequest(Guid id, RaiseCancelRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -107,7 +99,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpGet("cancel-requests")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetCancelRequests(
|
||||
[FromQuery] CancelRequestStatus? status,
|
||||
[FromQuery] int page = 1,
|
||||
@@ -118,7 +109,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPost("cancel-requests/{id:guid}/approve")]
|
||||
[Authorize(Policy = "rides.cancel.approve")]
|
||||
public async Task<IActionResult> ApproveCancelRequest(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -132,7 +122,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpPost("cancel-requests/{id:guid}/reject")]
|
||||
[Authorize(Policy = "rides.cancel.approve")]
|
||||
public async Task<IActionResult> RejectCancelRequest(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -146,7 +135,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/cancel-request")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetCancelRequest(Guid id)
|
||||
{
|
||||
var result = await service.GetCancelRequestAsync(id);
|
||||
@@ -154,7 +142,6 @@ public class RideController(RideService service, ICurrentUserService currentUser
|
||||
}
|
||||
|
||||
[HttpGet("breakdown-assist/{rideId:guid}")]
|
||||
[Authorize(Policy = "rides.view")]
|
||||
public async Task<IActionResult> GetBreakdownAssist(Guid rideId)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Role;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/roles")]
|
||||
[Authorize]
|
||||
public class RoleController(RoleService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
|
||||
@@ -7,4 +7,14 @@ public interface IRouteRepository
|
||||
Task AddAsync(Models.Route entity);
|
||||
void Update(Models.Route entity);
|
||||
void Remove(Models.Route entity);
|
||||
|
||||
Task<Models.User?> GetActiveUserAsync(Guid userId);
|
||||
Task<List<Models.Store>> GetStoresByIdsAsync(List<Guid> storeIds);
|
||||
Task<Models.Store?> GetStoreByIdAsync(Guid storeId);
|
||||
void UpdateStore(Models.Store store);
|
||||
|
||||
Task<Models.RouteVisitLog?> GetOpenVisitAsync(Guid routeId, Guid storeId);
|
||||
Task AddVisitLogAsync(Models.RouteVisitLog log);
|
||||
void UpdateVisitLog(Models.RouteVisitLog log);
|
||||
Task<List<Models.RouteVisitLog>> GetVisitsByStoreIdAsync(Guid storeId);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Route;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/routes")]
|
||||
[Authorize]
|
||||
public class RouteController(RouteService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "routes.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "routes.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class RouteController(RouteService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "routes.create")]
|
||||
public async Task<IActionResult> Create(CreateRouteRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,18 +25,55 @@ public class RouteController(RouteService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "routes.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateRouteRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/region")]
|
||||
public async Task<IActionResult> AssignToRegion(Guid id, AssignRouteToRegionRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.AssignToRegionAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "routes.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
return deleted ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/stores")]
|
||||
public async Task<IActionResult> AssignStores(Guid id, AssignStoresToRouteRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.AssignStoresToRouteAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/owner")]
|
||||
public async Task<IActionResult> AssignOwner(Guid id, AssignRouteOwnerRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.AssignOwnerAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/optimize")]
|
||||
public IActionResult OptimizeSequence(Guid id) =>
|
||||
StatusCode(StatusCodes.Status501NotImplemented);
|
||||
|
||||
[HttpPost("{id:guid}/visits/check-in")]
|
||||
public async Task<IActionResult> CheckIn(Guid id, RecordCheckInRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.RecordCheckInAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/visits/check-out")]
|
||||
public async Task<IActionResult> CheckOut(Guid id, RecordCheckOutRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.RecordCheckOutAsync(id, request, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,4 +4,16 @@ public record CreateRouteRequest(Guid RegionId, string RouteName, string StartPo
|
||||
|
||||
public record UpdateRouteRequest(Guid RegionId, string RouteName, string StartPoint, string EndPoint, decimal Length);
|
||||
|
||||
public record RouteResponse(Guid Id, Guid RegionId, string RouteName, string StartPoint, string EndPoint, decimal Length, bool IsActive, DateTime CreatedAt);
|
||||
public record RouteResponse(Guid Id, Guid RegionId, string RouteName, string StartPoint, string EndPoint, decimal Length, Guid? OwnerUserId, bool IsActive, DateTime CreatedAt);
|
||||
|
||||
public record AssignRouteToRegionRequest(Guid RegionId);
|
||||
|
||||
public record AssignStoresToRouteRequest(List<Guid> StoreIds);
|
||||
|
||||
public record AssignRouteOwnerRequest(Guid SalesRepId);
|
||||
|
||||
public record RecordCheckInRequest(Guid StoreId, decimal Latitude, decimal Longitude, DateTime? Timestamp);
|
||||
|
||||
public record RecordCheckOutRequest(Guid StoreId, DateTime? Timestamp);
|
||||
|
||||
public record RouteVisitResponse(Guid Id, Guid RouteId, Guid StoreId, Guid UserId, DateTime CheckInAt, bool IsDeviationFlagged, DateTime? CheckOutAt);
|
||||
|
||||
@@ -22,4 +22,31 @@ public class RouteRepository(AppDBContext context) : IRouteRepository
|
||||
entity.IsActive = false;
|
||||
context.Routes.Update(entity);
|
||||
}
|
||||
|
||||
public async Task<Models.User?> GetActiveUserAsync(Guid userId) =>
|
||||
await context.Users.FirstOrDefaultAsync(u => u.Id == userId && u.IsActive);
|
||||
|
||||
public async Task<List<Models.Store>> GetStoresByIdsAsync(List<Guid> storeIds) =>
|
||||
await context.Stores.Where(s => storeIds.Contains(s.Id)).ToListAsync();
|
||||
|
||||
public async Task<Models.Store?> GetStoreByIdAsync(Guid storeId) =>
|
||||
await context.Stores.FindAsync(storeId);
|
||||
|
||||
public void UpdateStore(Models.Store store) =>
|
||||
context.Stores.Update(store);
|
||||
|
||||
public async Task<Models.RouteVisitLog?> GetOpenVisitAsync(Guid routeId, Guid storeId) =>
|
||||
await context.RouteVisitLogs
|
||||
.Where(v => v.FK_RouteId == routeId && v.FK_StoreId == storeId && v.CheckOutAt == null)
|
||||
.OrderByDescending(v => v.CheckInAt)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
public async Task AddVisitLogAsync(Models.RouteVisitLog log) =>
|
||||
await context.RouteVisitLogs.AddAsync(log);
|
||||
|
||||
public void UpdateVisitLog(Models.RouteVisitLog log) =>
|
||||
context.RouteVisitLogs.Update(log);
|
||||
|
||||
public async Task<List<Models.RouteVisitLog>> GetVisitsByStoreIdAsync(Guid storeId) =>
|
||||
await context.RouteVisitLogs.Where(v => v.FK_StoreId == storeId).ToListAsync();
|
||||
}
|
||||
|
||||
@@ -1,20 +1,50 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
|
||||
namespace Distribution.Features.Route;
|
||||
|
||||
public class RouteService(IRouteRepository repo, IUnitOfWork uow)
|
||||
public class RouteService(IRouteRepository repo, Region.IRegionRepository regionRepo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess)
|
||||
{
|
||||
private const int RouteManagerRoleLevel = 20;
|
||||
private const double DeviationThresholdMeters = 500;
|
||||
|
||||
private async Task<bool> CanManageRouteAsync(Guid routeId)
|
||||
{
|
||||
if (currentUser.RoleLevel < RouteManagerRoleLevel || currentUser.UserId is null) return false;
|
||||
return await scopeAccess.HasRouteScopeAsync(currentUser.UserId.Value, routeId);
|
||||
}
|
||||
|
||||
private static double DistanceMeters(decimal lat1, decimal lon1, decimal lat2, decimal lon2)
|
||||
{
|
||||
const double earthRadiusMeters = 6371000;
|
||||
var dLat = ToRadians((double)(lat2 - lat1));
|
||||
var dLon = ToRadians((double)(lon2 - lon1));
|
||||
var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
|
||||
Math.Cos(ToRadians((double)lat1)) * Math.Cos(ToRadians((double)lat2)) *
|
||||
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
|
||||
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
|
||||
return earthRadiusMeters * c;
|
||||
}
|
||||
|
||||
private static double ToRadians(double degrees) => degrees * Math.PI / 180;
|
||||
|
||||
private static RouteResponse ToResponse(Models.Route route) =>
|
||||
new(route.Id, route.FK_RegionId, route.RouteName, route.StartPoint, route.EndPoint, route.Length, route.FK_OwnerUserId, route.IsActive, route.CreatedAt);
|
||||
|
||||
private static RouteVisitResponse ToVisitResponse(Models.RouteVisitLog log) =>
|
||||
new(log.Id, log.FK_RouteId, log.FK_StoreId, log.FK_UserId, log.CheckInAt, log.IsDeviationFlagged, log.CheckOutAt);
|
||||
|
||||
public async Task<List<RouteResponse>> GetAllAsync() =>
|
||||
(await repo.GetAllAsync())
|
||||
.Where(r => r.IsActive)
|
||||
.Select(r => new RouteResponse(r.Id, r.FK_RegionId, r.RouteName, r.StartPoint, r.EndPoint, r.Length, r.IsActive, r.CreatedAt))
|
||||
.Select(r => new RouteResponse(r.Id, r.FK_RegionId, r.RouteName, r.StartPoint, r.EndPoint, r.Length, r.FK_OwnerUserId, r.IsActive, r.CreatedAt))
|
||||
.ToList();
|
||||
|
||||
public async Task<RouteResponse?> GetByIdAsync(Guid id)
|
||||
{
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
return new RouteResponse(route.Id, route.FK_RegionId, route.RouteName, route.StartPoint, route.EndPoint, route.Length, route.IsActive, route.CreatedAt);
|
||||
return new RouteResponse(route.Id, route.FK_RegionId, route.RouteName, route.StartPoint, route.EndPoint, route.Length, route.FK_OwnerUserId, route.IsActive, route.CreatedAt);
|
||||
}
|
||||
|
||||
public async Task<RouteResponse> CreateAsync(CreateRouteRequest request, CancellationToken ct = default)
|
||||
@@ -38,7 +68,7 @@ public class RouteService(IRouteRepository repo, IUnitOfWork uow)
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RouteResponse(route.Id, route.FK_RegionId, route.RouteName, route.StartPoint, route.EndPoint, route.Length, route.IsActive, route.CreatedAt);
|
||||
return ToResponse(route);
|
||||
}
|
||||
|
||||
public async Task<RouteResponse?> UpdateAsync(Guid id, UpdateRouteRequest request, CancellationToken ct = default)
|
||||
@@ -61,7 +91,30 @@ public class RouteService(IRouteRepository repo, IUnitOfWork uow)
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return new RouteResponse(route.Id, route.FK_RegionId, route.RouteName, route.StartPoint, route.EndPoint, route.Length, route.IsActive, route.CreatedAt);
|
||||
return ToResponse(route);
|
||||
}
|
||||
|
||||
public async Task<RouteResponse?> AssignToRegionAsync(Guid id, AssignRouteToRegionRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
|
||||
var region = await regionRepo.GetByIdAsync(request.RegionId);
|
||||
if (region is null || !region.IsActive) return null;
|
||||
|
||||
route.FK_RegionId = request.RegionId;
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.Update(route);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return ToResponse(route);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(Guid id, CancellationToken ct = default)
|
||||
@@ -81,4 +134,119 @@ public class RouteService(IRouteRepository repo, IUnitOfWork uow)
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<RouteResponse?> AssignStoresToRouteAsync(Guid id, AssignStoresToRouteRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
if (!await CanManageRouteAsync(id)) return null;
|
||||
|
||||
var stores = await repo.GetStoresByIdsAsync(request.StoreIds);
|
||||
if (stores.Count != request.StoreIds.Distinct().Count()) return null;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
foreach (var store in stores)
|
||||
{
|
||||
store.FK_RouteId = id;
|
||||
repo.UpdateStore(store);
|
||||
}
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return ToResponse(route);
|
||||
}
|
||||
|
||||
public async Task<RouteResponse?> AssignOwnerAsync(Guid id, AssignRouteOwnerRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
if (!await CanManageRouteAsync(id)) return null;
|
||||
|
||||
var salesRep = await repo.GetActiveUserAsync(request.SalesRepId);
|
||||
if (salesRep is null) return null;
|
||||
|
||||
route.FK_OwnerUserId = request.SalesRepId;
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.Update(route);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return ToResponse(route);
|
||||
}
|
||||
|
||||
public async Task<RouteVisitResponse?> RecordCheckInAsync(Guid id, RecordCheckInRequest request, CancellationToken ct = default)
|
||||
{
|
||||
if (currentUser.UserId is null) return null;
|
||||
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
if (!await scopeAccess.HasRouteScopeAsync(currentUser.UserId.Value, id)) return null;
|
||||
|
||||
var store = await repo.GetStoreByIdAsync(request.StoreId);
|
||||
if (store is null || !store.IsActive || store.FK_RouteId != id) return null;
|
||||
|
||||
var distance = DistanceMeters(request.Latitude, request.Longitude, store.Latitude, store.Longitude);
|
||||
|
||||
var log = new Models.RouteVisitLog
|
||||
{
|
||||
FK_RouteId = id,
|
||||
FK_StoreId = request.StoreId,
|
||||
FK_UserId = currentUser.UserId.Value,
|
||||
CheckInAt = request.Timestamp ?? DateTime.Now,
|
||||
CheckInLatitude = request.Latitude,
|
||||
CheckInLongitude = request.Longitude,
|
||||
IsDeviationFlagged = distance > DeviationThresholdMeters
|
||||
};
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddVisitLogAsync(log);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return ToVisitResponse(log);
|
||||
}
|
||||
|
||||
public async Task<RouteVisitResponse?> RecordCheckOutAsync(Guid id, RecordCheckOutRequest request, CancellationToken ct = default)
|
||||
{
|
||||
if (currentUser.UserId is null) return null;
|
||||
|
||||
var route = await repo.GetByIdAsync(id);
|
||||
if (route is null || !route.IsActive) return null;
|
||||
if (!await scopeAccess.HasRouteScopeAsync(currentUser.UserId.Value, id)) return null;
|
||||
|
||||
var log = await repo.GetOpenVisitAsync(id, request.StoreId);
|
||||
if (log is null) return null;
|
||||
|
||||
log.CheckOutAt = request.Timestamp ?? DateTime.Now;
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
repo.UpdateVisitLog(log);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await uow.RollbackAsync(ct);
|
||||
throw;
|
||||
}
|
||||
return ToVisitResponse(log);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,8 @@ namespace Distribution.Features.Sale;
|
||||
public interface ISaleRepository
|
||||
{
|
||||
Task<Models.Sale?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.Sale>> GetAllAsync();
|
||||
Task<List<Models.Sale>> GetAllAsync(Guid? rideId, IEnumerable<Guid>? storeIds, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? rideId, IEnumerable<Guid>? storeIds);
|
||||
Task<List<Models.Sale>> GetByStoreIdAsync(Guid storeId);
|
||||
Task AddAsync(Models.Sale sale);
|
||||
void Update(Models.Sale sale);
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Sale;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/sales")]
|
||||
[Authorize]
|
||||
public class SaleController(SaleService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? rideId,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20) =>
|
||||
Ok(await service.GetAllAsync(rideId, page, pageSize));
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +21,6 @@ public class SaleController(SaleService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("store/{storeId:guid}")]
|
||||
[Authorize(Policy = "orders.view")]
|
||||
public async Task<IActionResult> GetByStore(Guid storeId)
|
||||
{
|
||||
var result = await service.GetByStoreIdAsync(storeId);
|
||||
@@ -30,10 +28,20 @@ public class SaleController(SaleService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "orders.create")]
|
||||
public async Task<IActionResult> Create(CreateSaleRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
return result is null ? Forbid() : CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/cancel")]
|
||||
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CancelAsync(id, ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
catch (InvalidOperationException ex) { return Conflict(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,21 @@ public class SaleRepository(AppDBContext context) : ISaleRepository
|
||||
public async Task<Models.Sale?> GetByIdAsync(Guid id) =>
|
||||
await context.Sales.FindAsync(id);
|
||||
|
||||
public async Task<List<Models.Sale>> GetAllAsync() =>
|
||||
await context.Sales.ToListAsync();
|
||||
public async Task<List<Models.Sale>> GetAllAsync(Guid? rideId, IEnumerable<Guid>? storeIds, int page, int pageSize) =>
|
||||
await context.Sales
|
||||
.Where(s => s.IsActive &&
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(storeIds == null || storeIds.Contains(s.FK_StoreId)))
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? rideId, IEnumerable<Guid>? storeIds) =>
|
||||
await context.Sales
|
||||
.CountAsync(s => s.IsActive &&
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(storeIds == null || storeIds.Contains(s.FK_StoreId)));
|
||||
|
||||
public async Task<List<Models.Sale>> GetByStoreIdAsync(Guid storeId) =>
|
||||
await context.Sales.Where(s => s.FK_StoreId == storeId && s.IsActive).ToListAsync();
|
||||
|
||||
@@ -71,14 +71,14 @@ public class SaleService(
|
||||
sale.IsActive,
|
||||
sale.CreatedAt);
|
||||
|
||||
public async Task<List<SaleResponse>> GetAllAsync()
|
||||
public async Task<PagedResponse<SaleResponse>> GetAllAsync(Guid? rideId, int page, int pageSize)
|
||||
{
|
||||
var sales = (await repo.GetAllAsync()).Where(s => s.IsActive).ToList();
|
||||
IEnumerable<Guid>? storeIds = null;
|
||||
if (!HasGlobalScope && currentUser.UserId is not null)
|
||||
{
|
||||
var accessibleStoreIds = (await scopeAccess.GetAccessibleStoreIdsAsync(currentUser.UserId.Value)).ToHashSet();
|
||||
sales = sales.Where(s => accessibleStoreIds.Contains(s.FK_StoreId)).ToList();
|
||||
}
|
||||
storeIds = await scopeAccess.GetAccessibleStoreIdsAsync(currentUser.UserId.Value);
|
||||
|
||||
var total = await repo.GetCountAsync(rideId, storeIds);
|
||||
var sales = await repo.GetAllAsync(rideId, storeIds, page, pageSize);
|
||||
|
||||
var result = new List<SaleResponse>();
|
||||
foreach (var sale in sales)
|
||||
@@ -88,7 +88,7 @@ public class SaleService(
|
||||
var items = await orderRepo.GetItemsByOrderIdAsync(order.Id);
|
||||
result.Add(ToResponse(sale, order, items));
|
||||
}
|
||||
return result;
|
||||
return new PagedResponse<SaleResponse>(page, pageSize, total, result);
|
||||
}
|
||||
|
||||
public async Task<SaleResponse?> GetByIdAsync(Guid id)
|
||||
@@ -119,6 +119,26 @@ public class SaleService(
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<SaleResponse?> CancelAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var sale = await repo.GetByIdAsync(id);
|
||||
if (sale is null || !sale.IsActive) return null;
|
||||
if (!await HasStoreScopeAsync(sale.FK_StoreId)) return null;
|
||||
if (sale.Status == SaleStatus.Cancelled)
|
||||
throw new InvalidOperationException("Sale is already cancelled");
|
||||
|
||||
sale.Status = SaleStatus.Cancelled;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(sale); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var order = await repo.GetOrderBySaleIdAsync(id);
|
||||
if (order is null) return null;
|
||||
var items = await orderRepo.GetItemsByOrderIdAsync(order.Id);
|
||||
return ToResponse(sale, order, items);
|
||||
}
|
||||
|
||||
public async Task<SaleResponse?> CreateAsync(CreateSaleRequest request, CancellationToken ct = default)
|
||||
{
|
||||
if (!await HasStoreScopeAsync(request.StoreId)) return null;
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Scheme;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/schemes")]
|
||||
[Authorize]
|
||||
public class SchemeController(SchemeService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
@@ -120,7 +118,6 @@ public class SchemeController(SchemeService service) : ControllerBase
|
||||
|
||||
[ApiController]
|
||||
[Route("api/orders")]
|
||||
[Authorize]
|
||||
public class SchemeOrderController(SchemeService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("{id:guid}/apply-scheme")]
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Stock;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/stock")]
|
||||
[Authorize]
|
||||
public class StockController(StockService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
// ── Query ──────────────────────────────────────────────────────────────
|
||||
// ── Query ──────────────────────────────────────────────────────────────
|
||||
|
||||
[HttpGet("balances")]
|
||||
public async Task<IActionResult> GetBalances(
|
||||
@@ -46,7 +44,7 @@ public class StockController(StockService service, ICurrentUserService currentUs
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// ── Write ──────────────────────────────────────────────────────────────
|
||||
// ── Write ──────────────────────────────────────────────────────────────
|
||||
|
||||
[HttpPost("transfer")]
|
||||
public async Task<IActionResult> Transfer(TransferRequest request, CancellationToken ct)
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Store.Kyc;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/stores/{storeId:guid}/kyc-documents")]
|
||||
[Authorize]
|
||||
public class StoreKycDocumentController(StoreKycDocumentService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetByStoreId(Guid storeId)
|
||||
{
|
||||
var result = await service.GetByStoreIdAsync(storeId);
|
||||
@@ -17,7 +14,6 @@ public class StoreKycDocumentController(StoreKycDocumentService service) : Contr
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "stores.update")]
|
||||
public async Task<IActionResult> Upload(Guid storeId, [FromForm] UploadKycDocumentRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UploadAsync(storeId, request, ct);
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Store;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/stores")]
|
||||
[Authorize]
|
||||
public class StoreController(StoreService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "stores.create")]
|
||||
public async Task<IActionResult> Create(CreateStoreRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "stores.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateStoreRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "stores.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
@@ -46,7 +39,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/credit-limit")]
|
||||
[Authorize(Policy = "stores.credit.update")]
|
||||
public async Task<IActionResult> UpdateCreditLimit(Guid id, UpdateCreditLimitRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateCreditLimitAsync(id, request, ct);
|
||||
@@ -54,7 +46,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/outstanding-balance")]
|
||||
[Authorize(Policy = "stores.credit.update")]
|
||||
public async Task<IActionResult> UpdateOutstandingBalance(Guid id, UpdateOutstandingBalanceRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateOutstandingBalanceAsync(id, request, ct);
|
||||
@@ -62,7 +53,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/outstanding-balance")]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetOutstandingBalance(Guid id)
|
||||
{
|
||||
var result = await service.GetOutstandingBalanceAsync(id);
|
||||
@@ -70,7 +60,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/kyc/verify")]
|
||||
[Authorize(Policy = "stores.kyc.verify")]
|
||||
public async Task<IActionResult> VerifyKyc(Guid id, VerifyKycRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.VerifyKycAsync(id, request, ct);
|
||||
@@ -78,7 +67,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/segment")]
|
||||
[Authorize(Policy = "stores.update")]
|
||||
public async Task<IActionResult> ClassifySegment(Guid id, ClassifySegmentRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.ClassifySegmentAsync(id, request, ct);
|
||||
@@ -86,7 +74,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/visit-history")]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetVisitHistory(Guid id)
|
||||
{
|
||||
var result = await service.GetVisitHistoryAsync(id);
|
||||
@@ -94,7 +81,6 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/schemes/{schemeId:guid}/eligibility")]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> CheckSchemeEligibility(Guid id, Guid schemeId)
|
||||
{
|
||||
var result = await service.CheckSchemeEligibilityAsync(id, schemeId);
|
||||
@@ -102,10 +88,16 @@ public class StoreController(StoreService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("{id:guid}/dashboard")]
|
||||
[Authorize(Policy = "stores.view")]
|
||||
public async Task<IActionResult> GetDashboard(Guid id, [FromQuery] string period)
|
||||
{
|
||||
var result = await service.GetDashboardAsync(id, period);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPatch("{id:guid}/kyc-status")]
|
||||
public async Task<IActionResult> PatchKycStatus(Guid id, PatchKycStatusRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.VerifyKycAsync(id, new VerifyKycRequest(request.KycStatus, null), ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,4 +53,6 @@ public record StoreVisitHistoryItem(Guid VisitId, DateTime VisitDate, Guid RepUs
|
||||
|
||||
public record SchemeEligibilityResponse(bool Eligible, string? Reason);
|
||||
|
||||
public record PatchKycStatusRequest(KycStatus KycStatus);
|
||||
|
||||
public record StoreDashboardResponse(Guid StoreId, string Period, int OrderCount, decimal TotalOrderValue, DateTime? LastOrderDate);
|
||||
|
||||
@@ -5,7 +5,7 @@ using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Store;
|
||||
|
||||
public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess, SchemeService schemeService)
|
||||
public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserService currentUser, IScopeAccessService scopeAccess, SchemeService schemeService, Route.IRouteRepository routeRepo)
|
||||
{
|
||||
private const int GlobalScopeRoleLevel = 50;
|
||||
private const int CreditApproverRoleLevel = 20;
|
||||
@@ -209,8 +209,12 @@ public class StoreService(IStoreRepository repo, IUnitOfWork uow, ICurrentUserSe
|
||||
var store = await repo.GetByIdAsync(id);
|
||||
if (store is null || !store.IsActive) return null;
|
||||
if (!await HasStoreScopeAsync(id)) return null;
|
||||
// Wired to Step 11 (Route & Sales Management) once ride/visit tracking exists.
|
||||
return [];
|
||||
|
||||
var visits = await routeRepo.GetVisitsByStoreIdAsync(id);
|
||||
return visits
|
||||
.OrderByDescending(v => v.CheckInAt)
|
||||
.Select(v => new StoreVisitHistoryItem(v.Id, v.CheckInAt, v.FK_UserId, v.CheckOutAt is null ? "In Progress" : "Completed"))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public async Task<SchemeEligibilityResponse?> CheckSchemeEligibilityAsync(Guid id, Guid schemeId)
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Supplier;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/suppliers")]
|
||||
[Authorize]
|
||||
public class SupplierController(SupplierService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.SupplierClaims;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class SupplierClaimController(SupplierClaimService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet("api/supplier-claims/{id:guid}")]
|
||||
@@ -32,7 +30,6 @@ public class SupplierClaimController(SupplierClaimService service, ICurrentUserS
|
||||
}
|
||||
|
||||
[HttpPost("api/supplier-claims/{id:guid}/approve")]
|
||||
[Authorize(Policy = "suppliers.claims.approve")]
|
||||
public async Task<IActionResult> Approve(Guid id, ApproveSupplierClaimRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
@@ -46,7 +43,6 @@ public class SupplierClaimController(SupplierClaimService service, ICurrentUserS
|
||||
}
|
||||
|
||||
[HttpPost("api/supplier-claims/{id:guid}/reject")]
|
||||
[Authorize(Policy = "suppliers.claims.approve")]
|
||||
public async Task<IActionResult> Reject(Guid id, RejectSupplierClaimRequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Sync;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/sync")]
|
||||
[Authorize(Policy = "items.create")]
|
||||
public class SyncController(SyncService service) : ControllerBase
|
||||
{
|
||||
[HttpPost("uoms")]
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Uom;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/uoms")]
|
||||
[Authorize]
|
||||
public class UomController(UomService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "items.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class UomController(UomService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "items.create")]
|
||||
public async Task<IActionResult> Create(CreateUomRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class UomController(UomService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "items.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateUomRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class UomController(UomService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "items.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.User;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
[Authorize]
|
||||
public class UserController(UserService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "users.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "users.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class UserController(UserService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "users.create")]
|
||||
public async Task<IActionResult> Create(CreateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class UserController(UserService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "users.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateUserRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class UserController(UserService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/role")]
|
||||
[Authorize(Policy = "users.assign_role")]
|
||||
public async Task<IActionResult> AssignRole(Guid id, AssignUserRoleRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.AssignRoleAsync(id, request, ct);
|
||||
@@ -46,7 +39,6 @@ public class UserController(UserService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/scope")]
|
||||
[Authorize(Policy = "users.assign_scope")]
|
||||
public async Task<IActionResult> AssignScope(Guid id, AssignUserScopeRequest request, CancellationToken ct)
|
||||
{
|
||||
var updated = await service.AssignScopeAsync(id, request, ct);
|
||||
@@ -54,7 +46,6 @@ public class UserController(UserService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "users.deactivate")]
|
||||
public async Task<IActionResult> Deactivate(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deactivated = await service.DeactivateAsync(id, ct);
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Vehicle;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/vehicles")]
|
||||
[Authorize]
|
||||
public class VehicleController(VehicleService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "vehicles.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "vehicles.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class VehicleController(VehicleService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "vehicles.create")]
|
||||
public async Task<IActionResult> Create(CreateVehicleRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class VehicleController(VehicleService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "vehicles.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateVehicleRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class VehicleController(VehicleService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "vehicles.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.Warehouse;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/warehouses")]
|
||||
[Authorize]
|
||||
public class WarehouseController(WarehouseService service) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
[Authorize(Policy = "warehouses.view")]
|
||||
public async Task<IActionResult> GetAll() =>
|
||||
Ok(await service.GetAllAsync());
|
||||
|
||||
[HttpGet("{id:guid}")]
|
||||
[Authorize(Policy = "warehouses.view")]
|
||||
public async Task<IActionResult> GetById(Guid id)
|
||||
{
|
||||
var result = await service.GetByIdAsync(id);
|
||||
@@ -22,7 +18,6 @@ public class WarehouseController(WarehouseService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize(Policy = "warehouses.create")]
|
||||
public async Task<IActionResult> Create(CreateWarehouseRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.CreateAsync(request, ct);
|
||||
@@ -30,7 +25,6 @@ public class WarehouseController(WarehouseService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}")]
|
||||
[Authorize(Policy = "warehouses.update")]
|
||||
public async Task<IActionResult> Update(Guid id, UpdateWarehouseRequest request, CancellationToken ct)
|
||||
{
|
||||
var result = await service.UpdateAsync(id, request, ct);
|
||||
@@ -38,7 +32,6 @@ public class WarehouseController(WarehouseService service) : ControllerBase
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
[Authorize(Policy = "warehouses.delete")]
|
||||
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
|
||||
{
|
||||
var deleted = await service.DeleteAsync(id, ct);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies own-user auth calls (login/register/getUserDetails/logout) to the external AuthHex
|
||||
/// identity service. AuthHex owns credentials and issues the RS256-signed JWT this app validates
|
||||
/// (see JwtTokenService's replacement — token generation is no longer done locally); this app
|
||||
/// never sees or stores a plaintext/hashed password for the AuthHex-authenticated flow.
|
||||
/// </summary>
|
||||
public class AuthHexClient(HttpClient http) : IAuthHexClient
|
||||
{
|
||||
public async Task<AuthHexResponse> CallAsync(string functionName, object? payload, string? reference = null, CancellationToken ct = default)
|
||||
{
|
||||
var body = new { functionName, payload, reference };
|
||||
var response = await http.PostAsJsonAsync("/api/user", body, ct);
|
||||
|
||||
var result = await response.Content.ReadFromJsonAsync<AuthHexResponse>(cancellationToken: ct);
|
||||
return result ?? new AuthHexResponse((int)response.StatusCode, false, "Empty response from AuthHex.", null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
/// <summary>Raw response shape returned by AuthHex's `/api/user` endpoint for every functionName.</summary>
|
||||
public record AuthHexResponse(
|
||||
[property: JsonPropertyName("statusCode")] int StatusCode,
|
||||
[property: JsonPropertyName("success")] bool Success,
|
||||
[property: JsonPropertyName("message")] string? Message,
|
||||
[property: JsonPropertyName("data")] JsonElement? Data);
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
public interface IAuthHexClient
|
||||
{
|
||||
Task<AuthHexResponse> CallAsync(string functionName, object? payload, string? reference = null, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class AuthenticatedAttribute : Attribute, IAuthorizationFilter
|
||||
{
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
if (context.HttpContext.User.Identity?.IsAuthenticated != true)
|
||||
context.Result = new UnauthorizedResult();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/authorization")]
|
||||
[Authorize]
|
||||
public class AuthorizationController(
|
||||
IPermissionService permissionService,
|
||||
IScopeAccessService scopeAccessService,
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
public interface IJwtTokenService
|
||||
{
|
||||
string GenerateToken(Models.User user);
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
public class JwtTokenService : IJwtTokenService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public JwtTokenService(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public string GenerateToken(Models.User user)
|
||||
{
|
||||
var jwtSection = _configuration.GetSection("Jwt");
|
||||
var key = jwtSection["Key"] ?? throw new InvalidOperationException("Jwt:Key is not configured.");
|
||||
var issuer = jwtSection["Issuer"];
|
||||
var audience = jwtSection["Audience"];
|
||||
var expiryMinutes = int.TryParse(jwtSection["ExpiryMinutes"], out var m) ? m : 120;
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new("sub", user.Id.ToString()),
|
||||
new("username", user.Username),
|
||||
new("role", user.Role?.Name ?? string.Empty),
|
||||
new("role_id", user.FK_RoleId.ToString()),
|
||||
new("role_level", (user.Role?.Level ?? 0).ToString())
|
||||
};
|
||||
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
||||
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: issuer,
|
||||
audience: audience,
|
||||
claims: claims,
|
||||
expires: DateTime.Now.AddMinutes(expiryMinutes),
|
||||
signingCredentials: credentials);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Parses an XML-format RSA public key (`<RSAKeyValue>...</RSAKeyValue>`, as issued by
|
||||
/// AuthHex) into an <see cref="RSA"/> instance. Written by hand instead of relying on
|
||||
/// RSA.FromXmlString, which is Windows-only in .NET (throws PlatformNotSupportedException on
|
||||
/// Linux/macOS) — this keeps token validation portable across hosts.
|
||||
/// </summary>
|
||||
public static class RsaXmlKeyReader
|
||||
{
|
||||
public static RSA ReadPublicKey(string xml)
|
||||
{
|
||||
var root = XElement.Parse(xml);
|
||||
var modulus = root.Element("Modulus")?.Value
|
||||
?? throw new InvalidOperationException("RSA XML key is missing <Modulus>.");
|
||||
var exponent = root.Element("Exponent")?.Value
|
||||
?? throw new InvalidOperationException("RSA XML key is missing <Exponent>.");
|
||||
|
||||
var parameters = new RSAParameters
|
||||
{
|
||||
Modulus = Convert.FromBase64String(modulus),
|
||||
Exponent = Convert.FromBase64String(exponent)
|
||||
};
|
||||
|
||||
var rsa = RSA.Create();
|
||||
rsa.ImportParameters(parameters);
|
||||
return rsa;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Distribution.Infra.Authorization.Middleware;
|
||||
|
||||
/// <summary>Stand-in for OSMCore's OMSCore.Common.Models.IOs.ApiResponse<T>, which has no equivalent in this project.</summary>
|
||||
public sealed record ApiResponse<T>
|
||||
{
|
||||
public int StatusCode { get; init; }
|
||||
public bool Success { get; init; }
|
||||
public string? Message { get; init; }
|
||||
public T? Data { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using Distribution.Features.User;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Distribution.Infra.Authorization.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Ported from OSMCore's System/Authentication/AuthMiddleware.cs (global path-skip-based
|
||||
/// middleware). NOT registered in Program.cs — this project's actual token validation is the
|
||||
/// standard AddJwtBearer handler (see Program.cs), same as OSMCore's own recommendation. Kept here
|
||||
/// unregistered, exactly like OSMCore's own copy, for reference/reuse if a project needs a
|
||||
/// middleware-based (rather than AddJwtBearer-based) validation entry point.
|
||||
///
|
||||
/// Two adaptations from the OSMCore original, both required for this to actually work against
|
||||
/// this project's authorization system rather than just compiling:
|
||||
/// 1. RSA key parsing goes through <see cref="RsaXmlKeyReader"/> instead of RSA.FromXmlString,
|
||||
/// which is Windows-only in modern .NET (see docs/authentication_flow.md §2.2 Gotcha).
|
||||
/// 2. After validating the token, the user id is mapped onto a local User/Role row and
|
||||
/// role_id/role_level/username claims are attached — the same step Program.cs's
|
||||
/// OnTokenValidated performs for the AddJwtBearer path. Without this, a request authenticated
|
||||
/// through this middleware would have no role_id claim, and every
|
||||
/// [Authorize(Policy = "resource.action")] check (PermissionAuthorizationHandler) would fail.
|
||||
/// </summary>
|
||||
public sealed class AuthMiddleware(RequestDelegate next, IConfiguration configuration, ILogger<AuthMiddleware> logger)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
if (ShouldSkipAuthentication(context.Request.Path))
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TryGetToken(context, out var token))
|
||||
{
|
||||
await RejectAsync(context, "Authentication token is missing.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var principal = ValidateToken(token);
|
||||
var userRepo = context.RequestServices.GetRequiredService<IUserRepository>();
|
||||
if (!await TryAttachLocalRoleClaimsAsync(principal, userRepo))
|
||||
{
|
||||
await RejectAsync(context, "User not found or inactive.");
|
||||
return;
|
||||
}
|
||||
|
||||
context.User = principal;
|
||||
PopulateContextItems(context, principal);
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex) when (ex is SecurityTokenException or ArgumentException or CryptographicException)
|
||||
{
|
||||
logger.LogInformation(ex, "JWT validation failed for request path {Path}", context.Request.Path);
|
||||
await RejectAsync(context, "Invalid or expired token.");
|
||||
}
|
||||
}
|
||||
|
||||
private ClaimsPrincipal ValidateToken(string token)
|
||||
{
|
||||
var jwtOptions = configuration.GetSection("Jwt").Get<JwtOptions>()
|
||||
?? throw new InvalidOperationException("Jwt configuration is missing.");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(jwtOptions.PublicKey))
|
||||
{
|
||||
throw new InvalidOperationException("Jwt:PublicKey configuration is missing.");
|
||||
}
|
||||
|
||||
using var rsa = RsaXmlKeyReader.ReadPublicKey(jwtOptions.PublicKey);
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var parameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtOptions.Issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtOptions.Audience,
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new RsaSecurityKey(rsa),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
|
||||
return handler.ValidateToken(token, parameters, out _);
|
||||
}
|
||||
|
||||
/// <summary>Mirrors Program.cs's OnTokenValidated mapping — see class remarks.</summary>
|
||||
private static async Task<bool> TryAttachLocalRoleClaimsAsync(ClaimsPrincipal principal, IUserRepository userRepo)
|
||||
{
|
||||
var subClaim = principal.FindFirst("sub")?.Value ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (!Guid.TryParse(subClaim, out var userId))
|
||||
return false;
|
||||
|
||||
var user = await userRepo.GetByIdAsync(userId);
|
||||
if (user is null || !user.IsActive)
|
||||
return false;
|
||||
|
||||
var identity = (ClaimsIdentity)principal.Identity!;
|
||||
identity.AddClaim(new Claim("username", user.Username));
|
||||
identity.AddClaim(new Claim("role_id", user.FK_RoleId.ToString()));
|
||||
identity.AddClaim(new Claim("role_level", (user.Role?.Level ?? 0).ToString()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryGetToken(HttpContext context, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
|
||||
if (TryGetBearerToken(context.Request.Headers.Authorization, out token))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var headerToken = context.Request.Headers["MobileAuthToken"].FirstOrDefault();
|
||||
if (TryGetBearerToken(headerToken, out token))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var cookieToken = context.Request.Cookies["access_token"];
|
||||
if (!string.IsNullOrWhiteSpace(cookieToken))
|
||||
{
|
||||
token = cookieToken.Trim();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryGetBearerToken(string? authorizationHeader, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const string bearerPrefix = "Bearer ";
|
||||
if (!authorizationHeader.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
token = authorizationHeader.Trim();
|
||||
return !string.IsNullOrWhiteSpace(token);
|
||||
}
|
||||
|
||||
token = authorizationHeader[bearerPrefix.Length..].Trim();
|
||||
return !string.IsNullOrWhiteSpace(token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adapted from OSMCore's path list: this project has no Shopify-style webhook route, so that
|
||||
/// skip is dropped; /api/auth is narrowed to just login/register (this project's /api/auth/me
|
||||
/// and /api/auth/logout are meant to require auth, unlike a blanket "/api/auth" skip).
|
||||
/// </summary>
|
||||
private static bool ShouldSkipAuthentication(PathString path)
|
||||
=> path.Equals("/health", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.Equals("/api/auth/login", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.Equals("/api/auth/register", StringComparison.OrdinalIgnoreCase)
|
||||
|| path.StartsWithSegments("/swagger", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static void PopulateContextItems(HttpContext context, ClaimsPrincipal principal)
|
||||
{
|
||||
context.Items["UserId"] = principal.FindFirst("sub")?.Value ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
context.Items["Username"] = principal.FindFirst("username")?.Value;
|
||||
context.Items["RoleId"] = principal.FindFirst("role_id")?.Value;
|
||||
context.Items["RoleLevel"] = principal.FindFirst("role_level")?.Value;
|
||||
}
|
||||
|
||||
private static async Task RejectAsync(HttpContext context, string message)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
await context.Response.WriteAsJsonAsync(new ApiResponse<object>
|
||||
{
|
||||
StatusCode = StatusCodes.Status401Unauthorized,
|
||||
Success = false,
|
||||
Message = message,
|
||||
Data = null
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using Distribution.Features.User;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Distribution.Infra.Authorization.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Ported from OSMCore's System/Authentication/JwtMiddleware.cs (action-filter attribute pattern,
|
||||
/// applied per controller/action as [JwtMiddleware.CustomMiddleware]). Not applied anywhere in
|
||||
/// this project — the standard AddJwtBearer handler (Program.cs) is this project's actual
|
||||
/// validation path.
|
||||
///
|
||||
/// docs/authentication_flow.md explicitly calls out not running this alongside AuthMiddleware or
|
||||
/// AddJwtBearer at the same time — all three independently re-validate the same RSA-signed token,
|
||||
/// which is wasteful and error-prone (this is the same duplication OSMCore's own guide flags as a
|
||||
/// Gotcha). Kept here, unregistered, only as a ported reference implementation.
|
||||
///
|
||||
/// Same two adaptations as AuthMiddleware: portable RSA parsing via
|
||||
/// <see cref="RsaXmlKeyReader"/>, and local User/Role → role_id/role_level claim mapping after
|
||||
/// validation (see AuthMiddleware's remarks for why this is required, not optional).
|
||||
/// </summary>
|
||||
public sealed class JwtMiddleware
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public sealed class CustomMiddlewareAttribute : Attribute, IAsyncActionFilter
|
||||
{
|
||||
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
|
||||
{
|
||||
var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();
|
||||
|
||||
if (!TryGetToken(context.HttpContext, out var token))
|
||||
{
|
||||
await RejectAsync(context.HttpContext, "Authentication token is missing.");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (configuration is null)
|
||||
{
|
||||
throw new InvalidOperationException("Jwt configuration is missing.");
|
||||
}
|
||||
|
||||
var principal = ValidateToken(token, configuration);
|
||||
|
||||
var userRepo = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
|
||||
if (!await TryAttachLocalRoleClaimsAsync(principal, userRepo))
|
||||
{
|
||||
await RejectAsync(context.HttpContext, "User not found or inactive.");
|
||||
return;
|
||||
}
|
||||
|
||||
context.HttpContext.User = principal;
|
||||
PopulateContextItems(context.HttpContext, principal);
|
||||
|
||||
await next();
|
||||
}
|
||||
catch (Exception ex) when (ex is SecurityTokenException or ArgumentException or CryptographicException or InvalidOperationException)
|
||||
{
|
||||
await RejectAsync(context.HttpContext, "Invalid or expired token.");
|
||||
}
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal ValidateToken(string token, IConfiguration configuration)
|
||||
{
|
||||
var xmlKey = configuration["Jwt:PublicKey"];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(xmlKey))
|
||||
throw new SecurityTokenException("JWT public key not configured.");
|
||||
|
||||
using var rsa = RsaXmlKeyReader.ReadPublicKey(xmlKey);
|
||||
var rsaParameters = rsa.ExportParameters(false);
|
||||
|
||||
var key = new RsaSecurityKey(rsaParameters)
|
||||
{
|
||||
KeyId = ComputeKeyId(rsaParameters)
|
||||
};
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var parameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = configuration["Jwt:Issuer"],
|
||||
ValidateAudience = true,
|
||||
ValidAudience = configuration["Jwt:Audience"],
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = key,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
|
||||
return handler.ValidateToken(token, parameters, out _);
|
||||
}
|
||||
|
||||
/// <summary>Mirrors Program.cs's OnTokenValidated mapping — see class remarks.</summary>
|
||||
private static async Task<bool> TryAttachLocalRoleClaimsAsync(ClaimsPrincipal principal, IUserRepository userRepo)
|
||||
{
|
||||
var subClaim = principal.FindFirst("sub")?.Value ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (!Guid.TryParse(subClaim, out var userId))
|
||||
return false;
|
||||
|
||||
var user = await userRepo.GetByIdAsync(userId);
|
||||
if (user is null || !user.IsActive)
|
||||
return false;
|
||||
|
||||
var identity = (ClaimsIdentity)principal.Identity!;
|
||||
identity.AddClaim(new Claim("username", user.Username));
|
||||
identity.AddClaim(new Claim("role_id", user.FK_RoleId.ToString()));
|
||||
identity.AddClaim(new Claim("role_level", (user.Role?.Level ?? 0).ToString()));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryGetToken(HttpContext context, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
|
||||
if (TryGetBearerToken(context.Request.Headers.Authorization, out token))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var headerToken = context.Request.Headers["MobileAuthToken"].FirstOrDefault();
|
||||
if (TryGetBearerToken(headerToken, out token))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var cookieToken = context.Request.Cookies["access_token"];
|
||||
if (!string.IsNullOrWhiteSpace(cookieToken))
|
||||
{
|
||||
token = cookieToken.Trim();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryGetBearerToken(string? authorizationHeader, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const string bearerPrefix = "Bearer ";
|
||||
if (!authorizationHeader.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
token = authorizationHeader.Trim();
|
||||
return !string.IsNullOrWhiteSpace(token);
|
||||
}
|
||||
|
||||
token = authorizationHeader[bearerPrefix.Length..].Trim();
|
||||
return !string.IsNullOrWhiteSpace(token);
|
||||
}
|
||||
|
||||
private static void PopulateContextItems(HttpContext context, ClaimsPrincipal principal)
|
||||
{
|
||||
context.Items["UserId"] = principal.FindFirst("sub")?.Value ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
context.Items["Username"] = principal.FindFirst("username")?.Value;
|
||||
context.Items["RoleId"] = principal.FindFirst("role_id")?.Value;
|
||||
context.Items["RoleLevel"] = principal.FindFirst("role_level")?.Value;
|
||||
}
|
||||
|
||||
private static async Task RejectAsync(HttpContext context, string message)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
await context.Response.WriteAsJsonAsync(new ApiResponse<object>
|
||||
{
|
||||
StatusCode = StatusCodes.Status401Unauthorized,
|
||||
Success = false,
|
||||
Message = message,
|
||||
Data = null
|
||||
});
|
||||
}
|
||||
|
||||
private static string ComputeKeyId(RSAParameters publicParameters)
|
||||
{
|
||||
var modulus = publicParameters.Modulus ?? [];
|
||||
var exponent = publicParameters.Exponent ?? [];
|
||||
var payload = $"{Convert.ToBase64String(modulus)}.{Convert.ToBase64String(exponent)}";
|
||||
var hash = SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(payload));
|
||||
return Base64UrlEncoder.Encode(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Distribution.Infra.Authorization.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Ported from OSMCore's System/Authentication/JwtOptions.cs. Binds to the same "Jwt" config
|
||||
/// section already used by Program.cs's AddJwtBearer setup (Jwt:PublicKey/Audience/Issuer) — no
|
||||
/// new config keys needed.
|
||||
/// </summary>
|
||||
public sealed record JwtOptions
|
||||
{
|
||||
public string PublicKey { get; init; } = string.Empty;
|
||||
public string Audience { get; init; } = string.Empty;
|
||||
public string Issuer { get; init; } = string.Empty;
|
||||
}
|
||||
@@ -1,24 +1,23 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
//namespace Distribution.Infra.Authorization;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
//public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
|
||||
//{
|
||||
// private readonly IPermissionService _permissionService;
|
||||
|
||||
public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionRequirement>
|
||||
{
|
||||
private readonly IPermissionService _permissionService;
|
||||
// public PermissionAuthorizationHandler(IPermissionService permissionService)
|
||||
// {
|
||||
// _permissionService = permissionService;
|
||||
// }
|
||||
|
||||
public PermissionAuthorizationHandler(IPermissionService permissionService)
|
||||
{
|
||||
_permissionService = permissionService;
|
||||
}
|
||||
// protected override async Task HandleRequirementAsync(
|
||||
// AuthorizationHandlerContext context, PermissionRequirement requirement)
|
||||
// {
|
||||
// var roleIdClaim = context.User.FindFirst("role_id")?.Value;
|
||||
// if (!Guid.TryParse(roleIdClaim, out var roleId))
|
||||
// return;
|
||||
|
||||
protected override async Task HandleRequirementAsync(
|
||||
AuthorizationHandlerContext context, PermissionRequirement requirement)
|
||||
{
|
||||
var roleIdClaim = context.User.FindFirst("role_id")?.Value;
|
||||
if (!Guid.TryParse(roleIdClaim, out var roleId))
|
||||
return;
|
||||
|
||||
if (await _permissionService.HasPermissionAsync(roleId, requirement.PermissionCode))
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
}
|
||||
// if (await _permissionService.HasPermissionAsync(roleId, requirement.PermissionCode))
|
||||
// context.Succeed(requirement);
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -1,32 +1,31 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Options;
|
||||
//using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
//namespace Distribution.Infra.Authorization;
|
||||
|
||||
public class PermissionPolicyProvider : IAuthorizationPolicyProvider
|
||||
{
|
||||
private readonly DefaultAuthorizationPolicyProvider _fallback;
|
||||
//public class PermissionPolicyProvider : IAuthorizationPolicyProvider
|
||||
//{
|
||||
// private readonly DefaultAuthorizationPolicyProvider _fallback;
|
||||
|
||||
public PermissionPolicyProvider(IOptions<AuthorizationOptions> options)
|
||||
{
|
||||
_fallback = new DefaultAuthorizationPolicyProvider(options);
|
||||
}
|
||||
// public PermissionPolicyProvider(IOptions<AuthorizationOptions> options)
|
||||
// {
|
||||
// _fallback = new DefaultAuthorizationPolicyProvider(options);
|
||||
// }
|
||||
|
||||
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
|
||||
// public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
|
||||
|
||||
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
|
||||
// public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
|
||||
|
||||
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
|
||||
{
|
||||
if (policyName.Contains('.'))
|
||||
{
|
||||
var policy = new AuthorizationPolicyBuilder()
|
||||
.RequireAuthenticatedUser()
|
||||
.AddRequirements(new PermissionRequirement(policyName))
|
||||
.Build();
|
||||
return Task.FromResult<AuthorizationPolicy?>(policy);
|
||||
}
|
||||
// public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
|
||||
// {
|
||||
// if (policyName.Contains('.'))
|
||||
// {
|
||||
// var policy = new AuthorizationPolicyBuilder()
|
||||
// .RequireAuthenticatedUser()
|
||||
// .AddRequirements(new PermissionRequirement(policyName))
|
||||
// .Build();
|
||||
// return Task.FromResult<AuthorizationPolicy?>(policy);
|
||||
// }
|
||||
|
||||
return _fallback.GetPolicyAsync(policyName);
|
||||
}
|
||||
}
|
||||
// return _fallback.GetPolicyAsync(policyName);
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
//namespace Distribution.Infra.Authorization;
|
||||
|
||||
namespace Distribution.Infra.Authorization;
|
||||
//public class PermissionRequirement : IAuthorizationRequirement
|
||||
//{
|
||||
// public string PermissionCode { get; }
|
||||
|
||||
public class PermissionRequirement : IAuthorizationRequirement
|
||||
{
|
||||
public string PermissionCode { get; }
|
||||
|
||||
public PermissionRequirement(string permissionCode)
|
||||
{
|
||||
PermissionCode = permissionCode;
|
||||
}
|
||||
}
|
||||
// public PermissionRequirement(string permissionCode)
|
||||
// {
|
||||
// PermissionCode = permissionCode;
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Text;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Distribution.Middleware;
|
||||
|
||||
public class AuthMiddleware(RequestDelegate next, IConfiguration config)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var token = context.Request.Headers.Authorization
|
||||
.ToString()
|
||||
.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase)
|
||||
.Trim();
|
||||
|
||||
if (!string.IsNullOrEmpty(token))
|
||||
{
|
||||
var key = config["Jwt:Key"];
|
||||
if (!string.IsNullOrEmpty(key))
|
||||
{
|
||||
try
|
||||
{
|
||||
var principal = new JwtSecurityTokenHandler().ValidateToken(token,
|
||||
new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = config["Jwt:Issuer"],
|
||||
ValidateAudience = true,
|
||||
ValidAudience = config["Jwt:Audience"],
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
}, out _);
|
||||
|
||||
context.User = principal;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,159 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Distribution.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddRegionManagement : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RegionAgencyMaps",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_RegionId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_AgencyUserId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RegionAgencyMaps", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RegionAgencyMaps_Regions_FK_RegionId",
|
||||
column: x => x.FK_RegionId,
|
||||
principalTable: "Regions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_RegionAgencyMaps_Users_FK_AgencyUserId",
|
||||
column: x => x.FK_AgencyUserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RegionalBudgets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_RegionId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Period = table.Column<string>(type: "varchar(255)", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
BudgetAmount = table.Column<decimal>(type: "decimal(65,30)", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RegionalBudgets", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RegionalBudgets_Regions_FK_RegionId",
|
||||
column: x => x.FK_RegionId,
|
||||
principalTable: "Regions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RegionalTargets",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_RegionId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
Period = table.Column<string>(type: "varchar(255)", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
TargetValue = table.Column<decimal>(type: "decimal(65,30)", nullable: false),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RegionalTargets", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RegionalTargets_Regions_FK_RegionId",
|
||||
column: x => x.FK_RegionId,
|
||||
principalTable: "Regions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RegionalTaxRules",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_RegionId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
RuleConfig = table.Column<string>(type: "longtext", nullable: false)
|
||||
.Annotation("MySql:CharSet", "utf8mb4"),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RegionalTaxRules", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RegionalTaxRules_Regions_FK_RegionId",
|
||||
column: x => x.FK_RegionId,
|
||||
principalTable: "Regions",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RegionAgencyMaps_FK_AgencyUserId",
|
||||
table: "RegionAgencyMaps",
|
||||
column: "FK_AgencyUserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RegionAgencyMaps_FK_RegionId_FK_AgencyUserId",
|
||||
table: "RegionAgencyMaps",
|
||||
columns: new[] { "FK_RegionId", "FK_AgencyUserId" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RegionalBudgets_FK_RegionId_Period",
|
||||
table: "RegionalBudgets",
|
||||
columns: new[] { "FK_RegionId", "Period" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RegionalTargets_FK_RegionId_Period",
|
||||
table: "RegionalTargets",
|
||||
columns: new[] { "FK_RegionId", "Period" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RegionalTaxRules_FK_RegionId",
|
||||
table: "RegionalTaxRules",
|
||||
column: "FK_RegionId",
|
||||
unique: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "RegionAgencyMaps");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "RegionalBudgets");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "RegionalTargets");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "RegionalTaxRules");
|
||||
}
|
||||
}
|
||||
}
|
||||
+2895
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Distribution.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddRouteVisitManagement : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "FK_OwnerUserId",
|
||||
table: "Routes",
|
||||
type: "char(36)",
|
||||
nullable: true,
|
||||
collation: "ascii_general_ci");
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RouteVisitLogs",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_RouteId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_StoreId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
FK_UserId = table.Column<Guid>(type: "char(36)", nullable: false, collation: "ascii_general_ci"),
|
||||
CheckInAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
CheckInLatitude = table.Column<decimal>(type: "decimal(65,30)", nullable: false),
|
||||
CheckInLongitude = table.Column<decimal>(type: "decimal(65,30)", nullable: false),
|
||||
IsDeviationFlagged = table.Column<bool>(type: "tinyint(1)", nullable: false),
|
||||
CheckOutAt = table.Column<DateTime>(type: "datetime(6)", nullable: true),
|
||||
CreatedAt = table.Column<DateTime>(type: "datetime(6)", nullable: false),
|
||||
IsActive = table.Column<bool>(type: "tinyint(1)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RouteVisitLogs", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RouteVisitLogs_Routes_FK_RouteId",
|
||||
column: x => x.FK_RouteId,
|
||||
principalTable: "Routes",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_RouteVisitLogs_Stores_FK_StoreId",
|
||||
column: x => x.FK_StoreId,
|
||||
principalTable: "Stores",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_RouteVisitLogs_Users_FK_UserId",
|
||||
column: x => x.FK_UserId,
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
})
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Routes_FK_OwnerUserId",
|
||||
table: "Routes",
|
||||
column: "FK_OwnerUserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RouteVisitLogs_FK_RouteId",
|
||||
table: "RouteVisitLogs",
|
||||
column: "FK_RouteId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RouteVisitLogs_FK_StoreId",
|
||||
table: "RouteVisitLogs",
|
||||
column: "FK_StoreId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RouteVisitLogs_FK_UserId",
|
||||
table: "RouteVisitLogs",
|
||||
column: "FK_UserId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_Routes_Users_FK_OwnerUserId",
|
||||
table: "Routes",
|
||||
column: "FK_OwnerUserId",
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_Routes_Users_FK_OwnerUserId",
|
||||
table: "Routes");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "RouteVisitLogs");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_Routes_FK_OwnerUserId",
|
||||
table: "Routes");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "FK_OwnerUserId",
|
||||
table: "Routes");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -851,6 +851,121 @@ namespace Distribution.Migrations
|
||||
b.ToTable("Regions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionAgencyMap", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("FK_AgencyUserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("FK_RegionId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_AgencyUserId");
|
||||
|
||||
b.HasIndex("FK_RegionId", "FK_AgencyUserId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RegionAgencyMaps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalBudget", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<decimal>("BudgetAmount")
|
||||
.HasColumnType("decimal(65,30)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("FK_RegionId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Period")
|
||||
.IsRequired()
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_RegionId", "Period")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RegionalBudgets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalTarget", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("FK_RegionId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("Period")
|
||||
.IsRequired()
|
||||
.HasColumnType("varchar(255)");
|
||||
|
||||
b.Property<decimal>("TargetValue")
|
||||
.HasColumnType("decimal(65,30)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_RegionId", "Period")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RegionalTargets");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalTaxRule", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("FK_RegionId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<string>("RuleConfig")
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_RegionId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("RegionalTaxRules");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RideCancelRequest", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -1000,6 +1115,9 @@ namespace Distribution.Migrations
|
||||
.IsRequired()
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<Guid?>("FK_OwnerUserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("FK_RegionId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
@@ -1019,11 +1137,60 @@ namespace Distribution.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_OwnerUserId");
|
||||
|
||||
b.HasIndex("FK_RegionId");
|
||||
|
||||
b.ToTable("Routes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RouteVisitLog", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<DateTime>("CheckInAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<decimal>("CheckInLatitude")
|
||||
.HasColumnType("decimal(65,30)");
|
||||
|
||||
b.Property<decimal>("CheckInLongitude")
|
||||
.HasColumnType("decimal(65,30)");
|
||||
|
||||
b.Property<DateTime?>("CheckOutAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
b.Property<Guid>("FK_RouteId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("FK_StoreId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<Guid>("FK_UserId")
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<bool>("IsActive")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.Property<bool>("IsDeviationFlagged")
|
||||
.HasColumnType("tinyint(1)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("FK_RouteId");
|
||||
|
||||
b.HasIndex("FK_StoreId");
|
||||
|
||||
b.HasIndex("FK_UserId");
|
||||
|
||||
b.ToTable("RouteVisitLogs");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.Sale", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -2185,6 +2352,58 @@ namespace Distribution.Migrations
|
||||
b.Navigation("PurchaseReturn");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionAgencyMap", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.User", "AgencyUser")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_AgencyUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Distribution.Models.Region", "Region")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RegionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("AgencyUser");
|
||||
|
||||
b.Navigation("Region");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalBudget", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.Region", "Region")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RegionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Region");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalTarget", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.Region", "Region")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RegionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Region");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RegionalTaxRule", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.Region", "Region")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RegionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Region");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RideCancelRequest", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.DeliveryRun", "Ride")
|
||||
@@ -2217,15 +2436,48 @@ namespace Distribution.Migrations
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.Route", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.User", "OwnerUser")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_OwnerUserId");
|
||||
|
||||
b.HasOne("Distribution.Models.Region", "Region")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RegionId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("OwnerUser");
|
||||
|
||||
b.Navigation("Region");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.RouteVisitLog", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.Route", "Route")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_RouteId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Distribution.Models.Store", "Store")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_StoreId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Distribution.Models.User", "User")
|
||||
.WithMany()
|
||||
.HasForeignKey("FK_UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Route");
|
||||
|
||||
b.Navigation("Store");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Distribution.Models.Sale", b =>
|
||||
{
|
||||
b.HasOne("Distribution.Models.User", "CreatedByUser")
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RegionAgencyMap : Template
|
||||
{
|
||||
public Guid FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region Region { get; set; }
|
||||
|
||||
/// <summary>User holding the RegionalAgency role that is mapped to this region.</summary>
|
||||
public Guid FK_AgencyUserId { get; set; }
|
||||
[ForeignKey("FK_AgencyUserId")]
|
||||
public User AgencyUser { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RegionalBudget : Template
|
||||
{
|
||||
public Guid FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region Region { get; set; }
|
||||
|
||||
public string Period { get; set; }
|
||||
public decimal BudgetAmount { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RegionalTarget : Template
|
||||
{
|
||||
public Guid FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region Region { get; set; }
|
||||
|
||||
public string Period { get; set; }
|
||||
public decimal TargetValue { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RegionalTaxRule : Template
|
||||
{
|
||||
public Guid FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region Region { get; set; }
|
||||
|
||||
public string RuleConfig { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -12,5 +12,9 @@ namespace Distribution.Models
|
||||
public Guid FK_RegionId { get; set; }
|
||||
[ForeignKey("FK_RegionId")]
|
||||
public Region Region { get; set; }
|
||||
|
||||
public Guid? FK_OwnerUserId { get; set; }
|
||||
[ForeignKey("FK_OwnerUserId")]
|
||||
public User? OwnerUser { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace Distribution.Models
|
||||
{
|
||||
public class RouteVisitLog : Template
|
||||
{
|
||||
public Guid FK_RouteId { get; set; }
|
||||
[ForeignKey("FK_RouteId")]
|
||||
public Route Route { get; set; }
|
||||
|
||||
public Guid FK_StoreId { get; set; }
|
||||
[ForeignKey("FK_StoreId")]
|
||||
public Store Store { get; set; }
|
||||
|
||||
public Guid FK_UserId { get; set; }
|
||||
[ForeignKey("FK_UserId")]
|
||||
public User User { get; set; }
|
||||
|
||||
public DateTime CheckInAt { get; set; }
|
||||
public decimal CheckInLatitude { get; set; }
|
||||
public decimal CheckInLongitude { get; set; }
|
||||
public bool IsDeviationFlagged { get; set; } = false;
|
||||
|
||||
public DateTime? CheckOutAt { get; set; }
|
||||
}
|
||||
}
|
||||
+16
-49
@@ -1,6 +1,6 @@
|
||||
using System.Text;
|
||||
using Distribution.Data;
|
||||
using Distribution.Features.Auth;
|
||||
using Distribution.Middleware;
|
||||
using Distribution.Features.Brand;
|
||||
using Distribution.Features.Category;
|
||||
using Distribution.Features.DeliveryRide;
|
||||
@@ -34,10 +34,7 @@ using Distribution.Features.Stock;
|
||||
using Distribution.Features.Warehouse;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Infra.UoW;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -91,6 +88,7 @@ builder.Services.AddScoped<OrderService>();
|
||||
builder.Services.AddScoped<SaleService>();
|
||||
builder.Services.AddScoped<UserService>();
|
||||
builder.Services.AddScoped<RoleService>();
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
builder.Services.AddScoped<CategoryService>();
|
||||
builder.Services.AddScoped<BrandService>();
|
||||
builder.Services.AddScoped<UomService>();
|
||||
@@ -116,16 +114,16 @@ builder.Services.AddScoped<PaymentService>();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<ICurrentUserService, CurrentUserService>();
|
||||
builder.Services.AddHttpClient<IAuthHexClient, AuthHexClient>(client =>
|
||||
{
|
||||
var baseUrl = builder.Configuration["AuthHex:BaseUrl"] ?? throw new InvalidOperationException("AuthHex:BaseUrl is not configured.");
|
||||
client.BaseAddress = new Uri(baseUrl);
|
||||
});
|
||||
builder.Services.AddScoped<IPermissionRepository, PermissionRepository>();
|
||||
builder.Services.AddScoped<IScopeRepository, ScopeRepository>();
|
||||
builder.Services.AddScoped<IPermissionService, PermissionService>();
|
||||
builder.Services.AddScoped<IScopeAccessService, ScopeAccessService>();
|
||||
builder.Services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
|
||||
builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
|
||||
|
||||
// ── Auth Service connector ───────────────────────────────────────────────────
|
||||
// TODO: replace placeholder BaseAddress with real Auth Service URL once decided.
|
||||
// The AuthServiceOptions:BaseUrl value in appsettings.json drives this.
|
||||
builder.Services.Configure<AuthServiceOptions>(
|
||||
builder.Configuration.GetSection(AuthServiceOptions.SectionName));
|
||||
|
||||
@@ -133,49 +131,18 @@ var authServiceBaseUrl = builder.Configuration[$"{AuthServiceOptions.SectionName
|
||||
|
||||
builder.Services.AddHttpClient<AuthServiceClient>(client =>
|
||||
{
|
||||
// TODO: set BaseAddress once Auth Service URL is known.
|
||||
if (!string.IsNullOrWhiteSpace(authServiceBaseUrl))
|
||||
client.BaseAddress = new Uri(authServiceBaseUrl);
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<IAuthServiceClient, AuthServiceClient>();
|
||||
|
||||
// ── Authentication ───────────────────────────────────────────────────────────
|
||||
// TODO: replace this JWT configuration with the token validation strategy
|
||||
// dictated by the Auth Service (symmetric key, JWKS/OIDC, etc.) once decided.
|
||||
var jwtSection = builder.Configuration.GetSection("Jwt");
|
||||
var jwtKey = jwtSection["Key"];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(jwtKey))
|
||||
{
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtSection["Issuer"],
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtSection["Audience"],
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
// Auth Service integration not yet configured — all [Authorize] checks will
|
||||
// fail until the token validation strategy is wired up.
|
||||
builder.Services.AddAuthentication();
|
||||
}
|
||||
|
||||
builder.Services.AddAuthorization();
|
||||
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
|
||||
builder.Services.AddCors(options =>
|
||||
options.AddDefaultPolicy(policy =>
|
||||
policy.WithOrigins(allowedOrigins)
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()));
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
@@ -191,9 +158,9 @@ if (app.Environment.IsDevelopment())
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
//app.UseHttpsRedirection();
|
||||
app.UseCors();
|
||||
app.UseMiddleware<AuthMiddleware>();
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Urls": "http://localhost:5089",
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=187.127.102.190;Port=3306;Database=distribution;User=kalana;Password=kalana@hexdive"
|
||||
},
|
||||
@@ -9,11 +10,18 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Cors": {
|
||||
"AllowedOrigins": [ "http://localhost:3000" ]
|
||||
},
|
||||
"Jwt": {
|
||||
"Key": "CHANGE_ME_dev_only_replace_with_a_long_random_secret_before_deploying",
|
||||
"Issuer": "Distribution.Api",
|
||||
"Audience": "Distribution.Api",
|
||||
"ExpiryMinutes": 120
|
||||
"PublicKey": "<RSAKeyValue><Modulus>1LlNkMBQNdpXJiDal7XMxkG/3ad+YBsMCuY9JD/abHMzniFXtQlovjfbeaaHJ0v1kvSo9731CJ0YC1qhPU5rPQwZwxOWZ9BOBZlMDghONdjOH/HyCUbb5Z18ibqc0QenFSnEYz+jkVZiayj8DV/+VUe+eKzpQTlU6aWtHvlbwfuXaDu+QvFlpLJ7/m8na+0s2nYhLX8Wfi4C/2AoNaYhFkIwYhMMGoaSHuIoQ5R6181Rh0gKvYopRW+IpTD5RV8bXV3AM6zOcoisOifBYROHwA5ZZpoHXuTvHYmPWW8kL8PKme7BwBldPi8KrJUroRE+WXA87aAA5Wtt1oxePcXvhQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>",
|
||||
"Audience": "AuthHexClient",
|
||||
"Issuer": "AuthHex"
|
||||
// "ExpiryMinutes": 120
|
||||
|
||||
},
|
||||
"AuthHex": {
|
||||
"BaseUrl": "http://localhost:6102"
|
||||
},
|
||||
"StoreManagement": {
|
||||
"UnverifiedKycOrderThreshold": 0
|
||||
|
||||
@@ -29,6 +29,10 @@ function reference (`assignAreaToRegion`, `getRegionHierarchy`) and any region-s
|
||||
via the API even though `Store.FK_RouteId` exists on the model. Blocks `assignOutletsToRoute` (§3)
|
||||
and route/region-scoped authorization for Stores and Orders.
|
||||
|
||||
> **Resolved** — `StoreDTOs.cs`'s `CreateStoreRequest`/`UpdateStoreRequest` now carry `RouteId`,
|
||||
> and a dedicated bulk-assign endpoint (`POST /api/routes/{id}/stores`) was added in
|
||||
> [11_route_sales_management.md](./11_route_sales_management.md).
|
||||
|
||||
### 3. Role Controller — Missing Authorization
|
||||
|
||||
`RoleController`'s GET endpoints carry only `[Authorize]`, with no `[Authorize(Policy = "...")]`
|
||||
|
||||
@@ -64,16 +64,29 @@ When `FulfillImmediately = false`, no stock movement — order stays Pending for
|
||||
|
||||
**Feature folder:** `Features/Payment/`
|
||||
|
||||
### API Endpoints
|
||||
### Sales API Endpoints
|
||||
|
||||
| Method | Route | Who | Description |
|
||||
|---|---|---|---|
|
||||
| POST | `/api/sales/{id}/payments` | Driver/Agent | Record a payment against a sale |
|
||||
| GET | `/api/sales/{id}/payments` | Any | List all payments for a sale |
|
||||
| GET | `/api/sales` | Any | List sales — supports `?rideId=`, `?page=`, `?pageSize=` query params |
|
||||
| POST | `/api/sales/{saleId:guid}/payments` | Driver/Agent | Record a payment against a sale |
|
||||
| GET | `/api/sales/{saleId:guid}/payments` | Any | List all payments for a sale |
|
||||
|
||||
**`GET /api/sales` filter params:**
|
||||
|
||||
| Param | Type | Description |
|
||||
|---|---|---|
|
||||
| `rideId` | `Guid?` | Filter to sales created on a specific ride |
|
||||
| `page` | `int` | Page number (default 1) |
|
||||
| `pageSize` | `int` | Items per page (default 20) |
|
||||
|
||||
Returns `PagedResponse<SaleResponse>`: `{ page, pageSize, total, items }`.
|
||||
|
||||
Scope rules still apply: non-global users only see sales for stores in their scope.
|
||||
|
||||
### Payment Creation Logic
|
||||
|
||||
On `POST /api/sales/{id}/payments`:
|
||||
On `POST /api/sales/{saleId:guid}/payments`:
|
||||
1. Validate sale exists and is not `Cancelled`.
|
||||
2. Add `Payment` record (`FK_SaleId`, `FK_StoreId` from sale, `Amount`, `Method`, `CollectedAt`, `CollectedBy`).
|
||||
3. Sum all payments for this sale. Recalculate `Sale.PaymentStatus`:
|
||||
|
||||
@@ -48,7 +48,7 @@ adds the automated pre-check (`ReturnWithoutSale`) that runs before a human appr
|
||||
| `logAuditEvent(userId, action, entityType, entityId)` (§18) | Internal — called by every mutating service, not directly exposed |
|
||||
| `checkLicenseCompliance(entityId, licenseType)` (§18) | `GET /api/compliance/{entityType}/{entityId}/license-check` |
|
||||
| `generateComplianceReport(period)` (§18) | `GET /api/compliance/report?period=...` |
|
||||
| `sendRouteDeviationAlert(routeId, salesRepId)` (§15) | Triggered from route check-in/out data (§3 of the function reference; not yet in any numbered step — see [11_route_sales_management.md](./11_route_sales_management.md)) |
|
||||
| `sendRouteDeviationAlert(routeId, salesRepId)` (§15) | Not implemented. The underlying data now exists — `POST /api/routes/{id}/visits/check-in` ([11_route_sales_management.md](./11_route_sales_management.md)) computes and stores `IsDeviationFlagged` on each `RouteVisitLog` row (Haversine distance vs. the store's registered lat/long) — but nothing reads that flag to raise an alert/anomaly flag yet. |
|
||||
| — | `GET /api/audit-log?entityType=...&entityId=...` |
|
||||
| — | `GET /api/anomaly-flags?status=Open` |
|
||||
|
||||
@@ -57,8 +57,9 @@ adds the automated pre-check (`ReturnWithoutSale`) that runs before a human appr
|
||||
## Automated Checks & Flags
|
||||
|
||||
- Returns without a matching prior sale (`ReturnWithoutSale`).
|
||||
- Sales/deliveries outside the geofenced route (`RouteDeviation`) — depends on GPS check-in/out
|
||||
data from [11_route_sales_management.md](./11_route_sales_management.md).
|
||||
- Sales/deliveries outside the geofenced route (`RouteDeviation`) — the GPS check-in/out data this
|
||||
depends on now exists ([11_route_sales_management.md](./11_route_sales_management.md)'s
|
||||
`RouteVisitLog.IsDeviationFlagged`), but no anomaly flag or alert reads it yet.
|
||||
- Agents with consistently high variance rates across closed rides (`HighVarianceRate`) — reads
|
||||
`Variance Record` history from [07_ride_reconciliation.md](./07_ride_reconciliation.md).
|
||||
- Cash collected below invoiced amount (`CashShortfall`) — reads `Payment Record` from
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 10 — Region Management (Beyond CRUD)
|
||||
|
||||
**Status**: Not Started
|
||||
**Status**: Implemented (except `assignAreaToRegion`, blocked on the `Area` entity)
|
||||
**Depends On**: 00 — Existing Gap Fixes
|
||||
|
||||
---
|
||||
@@ -24,48 +24,77 @@ CRUD: targets, budgets, agency mapping, tax rules, hierarchy, and dashboarding.
|
||||
|
||||
### Regional Target / Budget
|
||||
|
||||
`RegionId`, `Period` (e.g. `2026-08`), `TargetValue`, `BudgetAmount`.
|
||||
Implemented as two separate entities, `RegionalTarget` and `RegionalBudget`
|
||||
(`Models/RegionalTarget.cs`, `Models/RegionalBudget.cs`), each with `FK_RegionId`, `Period`
|
||||
(string, `yyyy-MM`), and `TargetValue`/`BudgetAmount` respectively. A unique index on
|
||||
`(FK_RegionId, Period)` means each region has at most one target and one budget row per period;
|
||||
setting the same period again updates it in place rather than inserting a duplicate.
|
||||
|
||||
### Agency-Region Map
|
||||
|
||||
`RegionId`, `AgencyId` — depends on whether "Regional Agency" becomes a distinct entity or stays a
|
||||
`Role` (see Open Questions).
|
||||
Implemented as `RegionAgencyMap` (`Models/RegionAgencyMap.cs`): `FK_RegionId`, `FK_AgencyUserId`,
|
||||
unique on the pair. "Regional Agency" stayed a `Role`, not a distinct entity (see Open Questions,
|
||||
resolved) — `FK_AgencyUserId` points at an existing `User` who holds the `RegionalAgency` role,
|
||||
the same convention already used by `Claim.FK_AgencyUserId` (§18).
|
||||
|
||||
### Regional Tax Rule
|
||||
|
||||
`RegionId`, `RuleConfig` (JSON) — deferred to whenever tax/pricing rule overrides are prioritized.
|
||||
Implemented as `RegionalTaxRule` (`Models/RegionalTaxRule.cs`): `FK_RegionId` (unique — one rule
|
||||
per region), `RuleConfig` (raw JSON string). Nothing in pricing/tax calculation reads this yet;
|
||||
it's stored for a future pricing-rule integration.
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Function reference | Endpoint intent |
|
||||
|---|---|
|
||||
| `assignAreaToRegion(areaId, regionId)` | Blocked — no `Area` entity exists (see [00_existing_gaps.md](./00_existing_gaps.md#9-no-area-entity-between-region-and-route)) |
|
||||
| `setRegionalTarget(regionId, period, targetValue)` | `PUT /api/regions/{id}/targets/{period}` |
|
||||
| `setRegionalBudget(regionId, period, budgetAmount)` | `PUT /api/regions/{id}/budgets/{period}` |
|
||||
| `mapAgencyToRegion(agencyId, regionId)` | `POST /api/regions/{id}/agencies` |
|
||||
| `setRegionalTaxRule(regionId, ruleConfig)` | `PUT /api/regions/{id}/tax-rule` |
|
||||
| `getRegionHierarchy(regionId)` | `GET /api/regions/{id}/hierarchy` |
|
||||
| `getRegionDashboard(regionId, period)` | `GET /api/regions/{id}/dashboard?period=...` |
|
||||
| Function reference | Endpoint | Status |
|
||||
|---|---|---|
|
||||
| `assignAreaToRegion(areaId, regionId)` | — | Blocked — no `Area` entity exists (see [00_existing_gaps.md](./00_existing_gaps.md#9-no-area-entity-between-region-and-route)). Stand-in: `PUT /api/routes/{id}/region` assigns/reassigns an existing route directly to a region (see [11_route_sales_management.md](./11_route_sales_management.md)). |
|
||||
| `setRegionalTarget(regionId, period, targetValue)` | `PUT /api/regions/{id}/targets/{period}` | Implemented |
|
||||
| `setRegionalBudget(regionId, period, budgetAmount)` | `PUT /api/regions/{id}/budgets/{period}` | Implemented |
|
||||
| `mapAgencyToRegion(agencyId, regionId)` | `POST /api/regions/{id}/agencies` | Implemented |
|
||||
| `setRegionalTaxRule(regionId, ruleConfig)` | `PUT /api/regions/{id}/tax-rule` | Implemented |
|
||||
| `getRegionHierarchy(regionId)` | `GET /api/regions/{id}/hierarchy` | Implemented (region → routes → store ids; no `Area` level) |
|
||||
| `getRegionDashboard(regionId, period)` | `GET /api/regions/{id}/dashboard?period=...` | Implemented (real-time aggregation; see Open Questions, resolved) |
|
||||
|
||||
All request/response DTOs live in `Features/Region/RegionDTOs.cs`; routing and access checks are
|
||||
in `RegionController.cs` and `RegionService.cs`.
|
||||
|
||||
---
|
||||
|
||||
## Business Rules
|
||||
|
||||
- Only `RegionalManager` and above (per role level in `Data/Seed/RoleAndPermissionSeed.cs`) can
|
||||
set targets/budgets for their own region; only `RegionalAgency` can set them across regions.
|
||||
set targets/budgets/tax-rule for their own region; only `RegionalAgency` can set them across
|
||||
regions. Implemented via `RegionService.CanManageRegionAsync`: role level ≥ 60 (`RegionalAgency`)
|
||||
is allowed unconditionally, role level ≥ 50 (`RegionalManager`) requires a matching
|
||||
`UserRegionScope` row for that region, anything lower is rejected. The same gate is applied to
|
||||
`mapAgencyToRegion`.
|
||||
- `mapAgencyToRegion` additionally rejects the target user if their role level is below the
|
||||
`RegionalAgency` threshold (60) — you can only map a user who actually holds (or outranks) that
|
||||
role.
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
- Is "Regional Agency" a business entity distinct from the `RegionalAgency` role (e.g. a contracted
|
||||
third party with its own record), or is the role sufficient?
|
||||
- Does `getRegionDashboard` need real-time aggregation, or a scheduled/cached rollup?
|
||||
- ~~Is "Regional Agency" a business entity distinct from the `RegionalAgency` role...?~~ Resolved:
|
||||
kept as a `Role` on `User`; no new agency entity, consistent with `Claim.FK_AgencyUserId`.
|
||||
- ~~Does `getRegionDashboard` need real-time aggregation, or a scheduled/cached rollup?~~ Resolved:
|
||||
real-time aggregation from `Order`/`Store`/`Route` for now; revisit if/when region-wide dashboard
|
||||
queries become a performance concern at scale.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
- Backend: `Models/RegionalTarget.cs`, `Models/RegionalBudget.cs`, `Models/RegionAgencyMap.cs`,
|
||||
`Models/RegionalTaxRule.cs`, `Data/AppDBContext.cs` (DbSets + unique indexes),
|
||||
`Features/Region/{IRegionRepository,RegionRepository,RegionService,RegionController,RegionDTOs}.cs`.
|
||||
- Frontend: `distribution_fe/types/api.ts` (response types), `distribution_fe/lib/api/master.ts`
|
||||
(`regions.setTarget/setBudget/mapAgency/setTaxRule/hierarchy/dashboard`), and a new
|
||||
`RegionManageSheet` dialog (`distribution_fe/app/(dashboard)/network/regions/_components/region-manage-sheet.tsx`)
|
||||
wired into the regions table's row actions.
|
||||
- The EF Core migration `20260831050805_AddRegionManagement` has been generated and applied to the
|
||||
shared database — `RegionalTargets`, `RegionalBudgets`, `RegionAgencyMaps`, and `RegionalTaxRules`
|
||||
all exist.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 11 — Route & Sales Visit Management
|
||||
|
||||
**Status**: Not Started
|
||||
**Status**: Partially Implemented
|
||||
**Depends On**: 00 — Existing Gap Fixes
|
||||
|
||||
---
|
||||
@@ -62,10 +62,41 @@ access grant which may cover multiple users (e.g. a Supervisor overseeing severa
|
||||
## Open Questions
|
||||
|
||||
- Is route sequence optimization (`optimizeRouteSequence`) a manual reorder endpoint, or does it
|
||||
need actual distance/priority-based computation (external mapping API)?
|
||||
need actual distance/priority-based computation (external mapping API)? — **Deferred.** The
|
||||
endpoint is stubbed (`501 Not Implemented`) until this is decided.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
> Fill this section in during planning discussion before writing any code.
|
||||
Implemented: `assignOutletsToRoute`, `assignRouteToSalesRep`/`reassignRoute` (same endpoint),
|
||||
`recordRouteCheckIn`/`recordRouteCheckOut`, and `getStoreVisitHistory` (§4, now reads from
|
||||
`RouteVisitLog`). See [BACKEND_API_REFERENCE.md §6.6](../../sharedDocs/BACKEND_API_REFERENCE.md#66-routes)
|
||||
for full request/response shapes.
|
||||
|
||||
Deliberately deferred, not oversights:
|
||||
- **`optimizeRouteSequence`** — stubbed as `501 Not Implemented`; no distance/priority computation
|
||||
exists (see Open Questions above).
|
||||
- **`getRouteAdherence`** / **`getRoutePerformance`** — not built; the underlying metrics
|
||||
(adherence %, strike rate, missed-visit count) were never defined, so there was nothing concrete
|
||||
to implement against.
|
||||
- **`sendRouteDeviationAlert`** — check-in computes and stores a basic `IsDeviationFlagged` boolean
|
||||
(Haversine distance > 500m from the store's registered `Latitude`/`Longitude`) but does not call
|
||||
any alert/notification pipeline, since [09_fraud_controls.md](./09_fraud_controls.md) itself is
|
||||
not implemented yet.
|
||||
|
||||
Data model differs slightly from the original sketch above: `RouteId`/`OwnerUserId` became a
|
||||
nullable `FK_OwnerUserId` directly on `Route` (no separate ownership table needed for a
|
||||
single-owner field), and `Route Visit Log`'s `CheckInGps` became two decimal columns
|
||||
(`CheckInLatitude`/`CheckInLongitude`) to match the existing `Store.Latitude`/`Longitude` shape
|
||||
and make the distance calculation straightforward.
|
||||
|
||||
Authorization for the new endpoints follows the `RegionService.CanManageRegionAsync` pattern
|
||||
(scope check via `IScopeAccessService`, no dedicated `routes.*` permission code): bulk store
|
||||
assignment and owner assignment require `IScopeAccessService.HasRouteScopeAsync` plus role level
|
||||
≥ 20 (Supervisor+); check-in/check-out require route scope only, no role floor, since any rep with
|
||||
access to the route should be able to log their own visits.
|
||||
|
||||
Frontend: implemented in `distribution_fe` — an admin "Manage" dialog on the Routes page (owner +
|
||||
bulk store assignment), a read-only visit-history dialog on the Stores page, and a new rep-facing
|
||||
`/sales-visits` page for GPS check-in/check-out (see `distribution_fe/app/(dashboard)/sales-visits/`).
|
||||
|
||||
@@ -100,14 +100,14 @@ One migration needed:
|
||||
### New
|
||||
| Method | Route | Permission | Notes |
|
||||
|---|---|---|---|
|
||||
| POST | /api/stores/{id}/kyc-documents | stores.update | Multipart upload, appends a KYC document |
|
||||
| GET | /api/stores/{id}/kyc-documents | stores.view | Lists documents for a store |
|
||||
| POST | /api/stores/{storeId:guid}/kyc-documents | stores.update | Multipart upload, appends a KYC document |
|
||||
| GET | /api/stores/{storeId:guid}/kyc-documents | stores.view | Lists documents for a store |
|
||||
| PUT | /api/stores/{id}/kyc/verify | stores.kyc.verify | Sets KycStatus, body carries `status` (Verified/Rejected) + optional `notes` |
|
||||
| PUT | /api/stores/{id}/credit-limit | stores.credit.update | Requires Supervisor (roleLevel ≥ 20) or above |
|
||||
| PUT | /api/stores/{id}/outstanding-balance | stores.credit.update | Manual adjustment until Finance owns this; same permission as credit-limit |
|
||||
| GET | /api/stores/{id}/outstanding-balance | stores.view | Returns cached value + CreditLimit + available credit |
|
||||
| PUT | /api/stores/{id}/segment | stores.update | Body: `{ "segment": "Gold" }` |
|
||||
| GET | /api/stores/{id}/visit-history | stores.view | Paginated. Empty list until Step 11 wiring lands |
|
||||
| GET | /api/stores/{id}/visit-history | stores.view | Wired to Step 11 — returns a plain array (not paginated) read from `RouteVisitLog` |
|
||||
| GET | /api/stores/{id}/schemes/{schemeId}/eligibility | stores.view | Wired to Step 17 — returns real region/segment/date-range eligibility for the store against that scheme |
|
||||
| GET | /api/stores/{id}/dashboard?period=... | stores.view | Aggregates order count/value for the period from existing Order tables |
|
||||
|
||||
@@ -115,7 +115,7 @@ One migration needed:
|
||||
|
||||
## Request / Response Shapes
|
||||
|
||||
### POST `/api/stores/{id}/kyc-documents` (multipart/form-data)
|
||||
### POST `/api/stores/{storeId:guid}/kyc-documents` (multipart/form-data)
|
||||
Fields: `documentType` (string), `file` (binary).
|
||||
|
||||
Response:
|
||||
@@ -247,7 +247,7 @@ ever belong to a Store and have no independent lifecycle.
|
||||
|
||||
### KYC upload logic (pseudo)
|
||||
```
|
||||
POST /api/stores/{id}/kyc-documents — multipart (documentType, file):
|
||||
POST /api/stores/{storeId:guid}/kyc-documents — multipart (documentType, file):
|
||||
1. Load Store by id, reject if missing/inactive or caller lacks store scope
|
||||
2. Ensure wwwroot/uploads/kyc/{storeId}/ exists
|
||||
3. Save file as {guid}.{ext}, record FileReference = "uploads/kyc/{storeId}/{guid}.{ext}"
|
||||
|
||||
@@ -347,7 +347,7 @@ GET /api/schemes/eligible?storeId=...&orderId=...
|
||||
|
||||
**Apply it:**
|
||||
```
|
||||
POST /api/orders/{orderId}/apply-scheme
|
||||
POST /api/orders/{id}/apply-scheme
|
||||
{ "schemeId": "..." }
|
||||
```
|
||||
Adds an `OrderItem` line (`Soap-500ml`, qty 2, `UnitPrice = 0`) and a `SchemeRedemption` with
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user