Dev #71
@@ -1,3 +1,4 @@
|
||||
using Distribution.Features.LoadingEvent;
|
||||
using Distribution.Features.Ride;
|
||||
using Distribution.Features.ShopPO;
|
||||
using Distribution.Features.Stock;
|
||||
@@ -10,6 +11,7 @@ public class DeliveryTaskService(
|
||||
IDeliveryTaskRepository repo,
|
||||
IRideRepository rideRepo,
|
||||
IShopPORepository shopPORepo,
|
||||
ILoadingSheetRepository loadingSheetRepo,
|
||||
IStockRepository stockRepo,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
@@ -32,8 +34,52 @@ public class DeliveryTaskService(
|
||||
i.UnitPrice)).ToList(),
|
||||
t.CreatedAt);
|
||||
|
||||
public Task<List<DeliveryTaskResponse>> GenerateAsync(Guid rideId, CancellationToken ct = default) =>
|
||||
throw new NotImplementedException("Delivery task auto-generation is deferred — route-based dispatch not yet implemented.");
|
||||
public async Task<List<DeliveryTaskResponse>> GenerateAsync(Guid rideId, CancellationToken ct = default)
|
||||
{
|
||||
var ride = await rideRepo.GetByIdAsync(rideId)
|
||||
?? throw new KeyNotFoundException("Ride not found");
|
||||
|
||||
var confirmedSheets = await loadingSheetRepo.GetAllAsync(rideId, LoadingSheetStatus.Confirmed, null, null, 1, int.MaxValue);
|
||||
if (confirmedSheets.Count == 0)
|
||||
throw new InvalidOperationException("Ride has no confirmed loading sheet to generate delivery tasks from");
|
||||
|
||||
var shopPOIds = confirmedSheets
|
||||
.SelectMany(s => s.Orders)
|
||||
.Select(o => o.FK_ShopPOId)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
var existingTasks = await repo.GetByRideIdAsync(rideId);
|
||||
var nextSequence = existingTasks.Count > 0 ? existingTasks.Max(t => t.Sequence) + 1 : 1;
|
||||
|
||||
var newTasks = new List<DeliveryTask>();
|
||||
foreach (var shopPOId in shopPOIds)
|
||||
{
|
||||
if (await repo.ExistsForOrderAndRideAsync(shopPOId, rideId)) continue;
|
||||
|
||||
newTasks.Add(new DeliveryTask
|
||||
{
|
||||
FK_RideId = rideId,
|
||||
FK_ShopPOId = shopPOId,
|
||||
Sequence = nextSequence++,
|
||||
Status = DeliveryTaskStatus.Pending
|
||||
});
|
||||
}
|
||||
|
||||
if (newTasks.Count > 0)
|
||||
{
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
foreach (var task in newTasks) await repo.AddAsync(task);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
}
|
||||
|
||||
var saved = await repo.GetByRideIdAsync(rideId);
|
||||
return saved.Select(ToResponse).ToList();
|
||||
}
|
||||
|
||||
public async Task<List<DeliveryTaskResponse>> GetByRideIdAsync(Guid rideId)
|
||||
{
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
|
||||
namespace Distribution.Features.Invoice;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/invoices")]
|
||||
public class InvoiceController(InvoiceService service) : ControllerBase
|
||||
public class InvoiceController(InvoiceService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll(
|
||||
@@ -26,4 +27,30 @@ public class InvoiceController(InvoiceService service) : ControllerBase
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/print")]
|
||||
public async Task<IActionResult> Print(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.PrintAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/finalize")]
|
||||
public async Task<IActionResult> Finalize(Guid id, [FromBody] FinalizeInvoiceRequest? request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.FinalizeAsync(id, request ?? new FinalizeInvoiceRequest(), userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace Distribution.Features.Invoice;
|
||||
|
||||
public record CreateInvoiceRequest(Guid ShopPOId);
|
||||
public record InvoiceItemAdjustment(Guid ShopPOItemId, int AdjustedQuantity, string? Note = null);
|
||||
public record FinalizeInvoiceRequest(List<InvoiceItemAdjustment> Adjustments);
|
||||
public record FinalizeInvoiceRequest(List<InvoiceItemAdjustment>? Adjustments = null);
|
||||
|
||||
public record InvoiceResponse(
|
||||
Guid Id,
|
||||
|
||||
@@ -9,6 +9,7 @@ public class InvoiceRepository(AppDBContext context) : IInvoiceRepository
|
||||
public async Task<Models.Invoice?> GetByIdAsync(Guid id) =>
|
||||
await context.Invoices
|
||||
.Include(i => i.ShopPO).ThenInclude(p => p.Store)
|
||||
.Include(i => i.ShopPO).ThenInclude(p => p.Items.Where(x => x.IsActive))
|
||||
.Include(i => i.Payments.Where(p => p.IsActive))
|
||||
.FirstOrDefaultAsync(i => i.Id == id && i.IsActive);
|
||||
|
||||
|
||||
@@ -30,4 +30,61 @@ public class InvoiceService(
|
||||
var items = await repo.GetAllAsync(agentId, routeId, shopId, status, page, pageSize);
|
||||
return new PagedResponse<InvoiceResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
public async Task<InvoiceResponse> PrintAsync(Guid id, Guid printedBy, CancellationToken ct = default)
|
||||
{
|
||||
var invoice = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Invoice not found");
|
||||
|
||||
if (invoice.Status != InvoiceStatus.Draft)
|
||||
throw new InvalidOperationException($"Cannot print an invoice in {invoice.Status} status");
|
||||
|
||||
invoice.Status = InvoiceStatus.Printed;
|
||||
invoice.PrintedAt = DateTime.Now;
|
||||
invoice.PrintedBy = printedBy;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(invoice); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(invoice);
|
||||
}
|
||||
|
||||
public async Task<InvoiceResponse> FinalizeAsync(Guid id, FinalizeInvoiceRequest request, Guid finalizedBy, CancellationToken ct = default)
|
||||
{
|
||||
var invoice = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Invoice not found");
|
||||
|
||||
if (invoice.Status != InvoiceStatus.Printed)
|
||||
throw new InvalidOperationException($"Cannot finalize an invoice in {invoice.Status} status");
|
||||
|
||||
var adjustments = request.Adjustments ?? [];
|
||||
if (adjustments.Count > 0)
|
||||
{
|
||||
var poItems = invoice.ShopPO.Items.Where(i => i.IsActive).ToList();
|
||||
decimal total = 0;
|
||||
foreach (var item in poItems)
|
||||
{
|
||||
var adjustment = adjustments.FirstOrDefault(a => a.ShopPOItemId == item.Id);
|
||||
var billedQuantity = adjustment is not null ? adjustment.AdjustedQuantity : item.Quantity;
|
||||
|
||||
if (billedQuantity < 0 || billedQuantity > item.Quantity)
|
||||
throw new InvalidOperationException(
|
||||
$"Adjusted quantity for item {item.Id} must be between 0 and {item.Quantity}");
|
||||
|
||||
total += billedQuantity * item.UnitPrice;
|
||||
}
|
||||
invoice.TotalAmount = total;
|
||||
}
|
||||
|
||||
invoice.Status = InvoiceStatus.Finalized;
|
||||
invoice.FinalizedAt = DateTime.Now;
|
||||
invoice.FinalizedBy = finalizedBy;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(invoice); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(invoice);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ public interface ILoadingSheetRepository
|
||||
{
|
||||
Task<LoadingSheet?> GetByIdAsync(Guid id);
|
||||
Task<LoadingSheet?> GetActiveByRideIdAsync(Guid rideId);
|
||||
Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status);
|
||||
Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, Guid? routeId, Guid? regionId, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status, Guid? routeId, Guid? regionId);
|
||||
Task AddAsync(LoadingSheet sheet);
|
||||
void Update(LoadingSheet sheet);
|
||||
void RemoveItems(IEnumerable<LoadingSheetItem> items);
|
||||
Task AddItemsAsync(IEnumerable<LoadingSheetItem> items);
|
||||
Task<List<Guid>> GetShopPOIdsByItemIdsAsync(IEnumerable<Guid> shopPOItemIds);
|
||||
Task ReplaceOrdersAsync(Guid loadingSheetId, List<Guid> shopPOIds);
|
||||
}
|
||||
|
||||
@@ -12,10 +12,12 @@ public class LoadingSheetController(LoadingSheetService service, ICurrentUserSer
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? rideId,
|
||||
[FromQuery] LoadingSheetStatus? status,
|
||||
[FromQuery] Guid? routeId,
|
||||
[FromQuery] Guid? regionId,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(rideId, status, page, pageSize);
|
||||
var result = await service.GetAllAsync(rideId, status, routeId, regionId, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,24 +17,28 @@ public class LoadingSheetRepository(AppDBContext context) : ILoadingSheetReposit
|
||||
await context.LoadingSheets
|
||||
.FirstOrDefaultAsync(s => s.FK_RideId == rideId && s.Status == LoadingSheetStatus.Planned);
|
||||
|
||||
public async Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize) =>
|
||||
public async Task<List<LoadingSheet>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, Guid? routeId, Guid? regionId, int page, int pageSize) =>
|
||||
await context.LoadingSheets
|
||||
.Include(s => s.Items).ThenInclude(i => i.Item)
|
||||
.Include(s => s.Items).ThenInclude(i => i.Warehouse)
|
||||
.Include(s => s.Orders)
|
||||
.Where(s =>
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(status == null || s.Status == status))
|
||||
(status == null || s.Status == status) &&
|
||||
(routeId == null || s.Orders.Any(o => o.ShopPO.Store.FK_RouteId == routeId)) &&
|
||||
(regionId == null || s.Orders.Any(o => o.ShopPO.Store.Route.FK_RegionId == regionId)))
|
||||
.OrderByDescending(s => s.CreatedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status) =>
|
||||
public async Task<int> GetCountAsync(Guid? rideId, LoadingSheetStatus? status, Guid? routeId, Guid? regionId) =>
|
||||
await context.LoadingSheets
|
||||
.CountAsync(s =>
|
||||
(rideId == null || s.FK_RideId == rideId) &&
|
||||
(status == null || s.Status == status));
|
||||
(status == null || s.Status == status) &&
|
||||
(routeId == null || s.Orders.Any(o => o.ShopPO.Store.FK_RouteId == routeId)) &&
|
||||
(regionId == null || s.Orders.Any(o => o.ShopPO.Store.Route.FK_RegionId == regionId)));
|
||||
|
||||
public async Task AddAsync(LoadingSheet sheet) =>
|
||||
await context.LoadingSheets.AddAsync(sheet);
|
||||
@@ -47,4 +51,25 @@ public class LoadingSheetRepository(AppDBContext context) : ILoadingSheetReposit
|
||||
|
||||
public async Task AddItemsAsync(IEnumerable<LoadingSheetItem> items) =>
|
||||
await context.LoadingSheetItems.AddRangeAsync(items);
|
||||
|
||||
public async Task<List<Guid>> GetShopPOIdsByItemIdsAsync(IEnumerable<Guid> shopPOItemIds) =>
|
||||
await context.ShopPOItems
|
||||
.Where(i => shopPOItemIds.Contains(i.Id))
|
||||
.Select(i => i.FK_ShopPOId)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
public async Task ReplaceOrdersAsync(Guid loadingSheetId, List<Guid> shopPOIds)
|
||||
{
|
||||
var current = await context.LoadingSheetOrders
|
||||
.Where(o => o.FK_LoadingSheetId == loadingSheetId)
|
||||
.ToListAsync();
|
||||
context.LoadingSheetOrders.RemoveRange(current);
|
||||
|
||||
await context.LoadingSheetOrders.AddRangeAsync(shopPOIds.Select(shopPOId => new LoadingSheetOrder
|
||||
{
|
||||
FK_LoadingSheetId = loadingSheetId,
|
||||
FK_ShopPOId = shopPOId
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ public class LoadingSheetService(
|
||||
IStockRepository stockRepo,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
public async Task<PagedResponse<LoadingSheetResponse>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, int page, int pageSize)
|
||||
public async Task<PagedResponse<LoadingSheetResponse>> GetAllAsync(Guid? rideId, LoadingSheetStatus? status, Guid? routeId, Guid? regionId, int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync(rideId, status);
|
||||
var items = await repo.GetAllAsync(rideId, status, page, pageSize);
|
||||
var total = await repo.GetCountAsync(rideId, status, routeId, regionId);
|
||||
var items = await repo.GetAllAsync(rideId, status, routeId, regionId, page, pageSize);
|
||||
return new PagedResponse<LoadingSheetResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
@@ -64,6 +64,14 @@ public class LoadingSheetService(
|
||||
if (sheet.Status != LoadingSheetStatus.Planned)
|
||||
throw new InvalidOperationException("Items can only be changed while the sheet is Planned");
|
||||
|
||||
var shopPOItemIds = request.Items
|
||||
.Where(i => i.FK_ShopPOItemId.HasValue)
|
||||
.Select(i => i.FK_ShopPOItemId!.Value)
|
||||
.ToList();
|
||||
var shopPOIds = shopPOItemIds.Count > 0
|
||||
? await repo.GetShopPOIdsByItemIdsAsync(shopPOItemIds)
|
||||
: new List<Guid>();
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
@@ -76,6 +84,7 @@ public class LoadingSheetService(
|
||||
FK_ShopPOItemId = i.FK_ShopPOItemId,
|
||||
QuantityDispatched = i.Quantity
|
||||
}));
|
||||
await repo.ReplaceOrdersAsync(sheet.Id, shopPOIds);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
@@ -13,6 +13,8 @@ public record RideResponse(
|
||||
int Meterend,
|
||||
DateTime? StartedAt,
|
||||
DateTime? ClosedAt,
|
||||
CancelRequestType? CancelTypeCode,
|
||||
string? CancelReason,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CreateRideRequest(
|
||||
|
||||
@@ -109,6 +109,8 @@ public class RideService(
|
||||
throw new InvalidOperationException($"Cannot cancel a ride in {ride.Status} status");
|
||||
|
||||
ride.Status = RideStatus.Cancelled;
|
||||
ride.CancelTypeCode = request.TypeCode;
|
||||
ride.CancelReason = request.Reason;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { rideRepo.Update(ride); await uow.CommitAsync(ct); }
|
||||
@@ -149,5 +151,5 @@ public class RideService(
|
||||
r.FK_VehicleId, r.Vehicle?.NumberPlate ?? string.Empty,
|
||||
r.FK_DriverProfileId, r.DriverProfile?.User?.FullName ?? string.Empty,
|
||||
r.Meterstart, r.Meterend,
|
||||
r.StartedAt, r.ClosedAt, r.CreatedAt);
|
||||
r.StartedAt, r.ClosedAt, r.CancelTypeCode, r.CancelReason, r.CreatedAt);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ namespace Distribution.Features.ShopPO;
|
||||
public interface IShopPORepository
|
||||
{
|
||||
Task<Models.ShopPO?> GetByIdAsync(Guid id);
|
||||
Task<List<Models.ShopPO>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? shopId, bool? confirmed, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? agentId, Guid? routeId, Guid? shopId, bool? confirmed);
|
||||
Task<List<Models.ShopPO>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? regionId, Guid? shopId, bool? confirmed, ShopPOStatus? status, int page, int pageSize);
|
||||
Task<int> GetCountAsync(Guid? agentId, Guid? routeId, Guid? regionId, Guid? shopId, bool? confirmed, ShopPOStatus? status);
|
||||
Task<List<Models.ShopPO>> GetConfirmedWithoutInvoiceAsync(Guid? agentId, Guid? routeId, Guid? shopId);
|
||||
Task<List<Models.ShopPOItem>> GetActiveItemsByShopPOIdAsync(Guid shopPOId);
|
||||
Task<List<Models.ShopPO>> GetByStoreIdAsync(Guid storeId);
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Distribution.Infra.Authorization;
|
||||
using Distribution.Models;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Distribution.Features.ShopPO;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/shop-pos")]
|
||||
public class ShopPOController(ShopPOService service) : ControllerBase
|
||||
public class ShopPOController(ShopPOService service, ICurrentUserService currentUser) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] Guid? agentId,
|
||||
[FromQuery] Guid? routeId,
|
||||
[FromQuery] Guid? regionId,
|
||||
[FromQuery] Guid? shopId,
|
||||
[FromQuery] bool? confirmed,
|
||||
[FromQuery] ShopPOStatus? status,
|
||||
[FromQuery] int page = 1,
|
||||
[FromQuery] int pageSize = 20)
|
||||
{
|
||||
var result = await service.GetAllAsync(agentId, routeId, shopId, confirmed, page, pageSize);
|
||||
var result = await service.GetAllAsync(agentId, routeId, regionId, shopId, confirmed, status, page, pageSize);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
@@ -25,4 +29,66 @@ public class ShopPOController(ShopPOService service) : ControllerBase
|
||||
var result = await service.GetByIdAsync(id);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(CreateShopPORequest request, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.CreateAsync(request, userId, ct);
|
||||
return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPut("{id:guid}/items")]
|
||||
public async Task<IActionResult> UpdateItems(Guid id, UpdateShopPOItemsRequest request, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.UpdateItemsAsync(id, request, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm")]
|
||||
public async Task<IActionResult> Confirm(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ConfirmAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/confirm-and-create-invoice")]
|
||||
public async Task<IActionResult> ConfirmAndCreateInvoice(Guid id, CancellationToken ct)
|
||||
{
|
||||
var userId = currentUser.UserId ?? throw new UnauthorizedAccessException();
|
||||
try
|
||||
{
|
||||
var result = await service.ConfirmAndCreateInvoiceAsync(id, userId, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
|
||||
[HttpPost("{id:guid}/cancel")]
|
||||
public async Task<IActionResult> Cancel(Guid id, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await service.CancelAsync(id, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (KeyNotFoundException) { return NotFound(); }
|
||||
catch (InvalidOperationException ex) { return BadRequest(new { error = ex.Message }); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,27 +13,32 @@ public class ShopPORepository(AppDBContext context) : IShopPORepository
|
||||
.ThenInclude(i => i.Item)
|
||||
.FirstOrDefaultAsync(p => p.Id == id && p.IsActive);
|
||||
|
||||
public async Task<List<Models.ShopPO>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? shopId, bool? confirmed, int page, int pageSize) =>
|
||||
public async Task<List<Models.ShopPO>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? regionId, Guid? shopId, bool? confirmed, ShopPOStatus? status, int page, int pageSize) =>
|
||||
await context.ShopPOs
|
||||
.Include(p => p.Store)
|
||||
.Include(p => p.Store).ThenInclude(s => s.Route)
|
||||
.Include(p => p.Items.Where(i => i.IsActive)).ThenInclude(i => i.Item)
|
||||
.Where(p => p.IsActive
|
||||
&& (agentId == null || p.RaisedById == agentId)
|
||||
&& (routeId == null || p.Store.FK_RouteId == routeId)
|
||||
&& (regionId == null || p.Store.Route.FK_RegionId == regionId)
|
||||
&& (shopId == null || p.FK_StoreId == shopId)
|
||||
&& (confirmed == null || (confirmed == true ? p.ConfirmedAt != null : p.ConfirmedAt == null)))
|
||||
&& (confirmed == null || (confirmed == true ? p.ConfirmedAt != null : p.ConfirmedAt == null))
|
||||
&& (status == null || p.Status == status))
|
||||
.OrderByDescending(p => p.CreatedAt)
|
||||
.Skip((page - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<int> GetCountAsync(Guid? agentId, Guid? routeId, Guid? shopId, bool? confirmed) =>
|
||||
public async Task<int> GetCountAsync(Guid? agentId, Guid? routeId, Guid? regionId, Guid? shopId, bool? confirmed, ShopPOStatus? status) =>
|
||||
await context.ShopPOs
|
||||
.Include(p => p.Store)
|
||||
.Include(p => p.Store).ThenInclude(s => s.Route)
|
||||
.CountAsync(p => p.IsActive
|
||||
&& (agentId == null || p.RaisedById == agentId)
|
||||
&& (routeId == null || p.Store.FK_RouteId == routeId)
|
||||
&& (regionId == null || p.Store.Route.FK_RegionId == regionId)
|
||||
&& (shopId == null || p.FK_StoreId == shopId)
|
||||
&& (confirmed == null || (confirmed == true ? p.ConfirmedAt != null : p.ConfirmedAt == null)));
|
||||
&& (confirmed == null || (confirmed == true ? p.ConfirmedAt != null : p.ConfirmedAt == null))
|
||||
&& (status == null || p.Status == status));
|
||||
|
||||
public async Task<List<Models.ShopPO>> GetConfirmedWithoutInvoiceAsync(Guid? agentId, Guid? routeId, Guid? shopId) =>
|
||||
await context.ShopPOs
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Features.Invoice;
|
||||
using Distribution.Features.PriceList;
|
||||
using Distribution.Features.Stock;
|
||||
using Distribution.Infra.UoW;
|
||||
using Distribution.Models;
|
||||
|
||||
@@ -6,6 +8,8 @@ namespace Distribution.Features.ShopPO;
|
||||
|
||||
public class ShopPOService(
|
||||
IShopPORepository repo,
|
||||
IInvoiceRepository invoiceRepo,
|
||||
PriceListService priceListService,
|
||||
IUnitOfWork uow)
|
||||
{
|
||||
private static ShopPOResponse ToResponse(Models.ShopPO p) =>
|
||||
@@ -17,10 +21,10 @@ public class ShopPOService(
|
||||
i.Quantity, i.QuantityFulfilled, i.UnitPrice, i.IsActive)).ToList(),
|
||||
p.IsActive, p.CreatedAt);
|
||||
|
||||
public async Task<PagedResponse<ShopPOResponse>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? shopId, bool? confirmed, int page, int pageSize)
|
||||
public async Task<PagedResponse<ShopPOResponse>> GetAllAsync(Guid? agentId, Guid? routeId, Guid? regionId, Guid? shopId, bool? confirmed, ShopPOStatus? status, int page, int pageSize)
|
||||
{
|
||||
var total = await repo.GetCountAsync(agentId, routeId, shopId, confirmed);
|
||||
var items = await repo.GetAllAsync(agentId, routeId, shopId, confirmed, page, pageSize);
|
||||
var total = await repo.GetCountAsync(agentId, routeId, regionId, shopId, confirmed, status);
|
||||
var items = await repo.GetAllAsync(agentId, routeId, regionId, shopId, confirmed, status, page, pageSize);
|
||||
return new PagedResponse<ShopPOResponse>(page, pageSize, total, items.Select(ToResponse).ToList());
|
||||
}
|
||||
|
||||
@@ -29,4 +33,174 @@ public class ShopPOService(
|
||||
var po = await repo.GetByIdAsync(id);
|
||||
return po is null ? null : ToResponse(po);
|
||||
}
|
||||
|
||||
public async Task<ShopPOResponse> CreateAsync(CreateShopPORequest request, Guid raisedById, CancellationToken ct = default)
|
||||
{
|
||||
if (request.Items.Count == 0)
|
||||
throw new InvalidOperationException("At least one item is required");
|
||||
|
||||
var items = new List<ShopPOItem>();
|
||||
decimal total = 0;
|
||||
|
||||
foreach (var line in request.Items)
|
||||
{
|
||||
var unitPrice = line.UnitPrice
|
||||
?? (await priceListService.ResolveByStoreAsync(line.ItemId, request.StoreId, DateTime.Now))?.Price
|
||||
?? throw new InvalidOperationException($"No resolvable price for item {line.ItemId}");
|
||||
|
||||
items.Add(new ShopPOItem
|
||||
{
|
||||
FK_ItemId = line.ItemId,
|
||||
Quantity = line.Quantity,
|
||||
QuantityFulfilled = 0,
|
||||
UnitPrice = unitPrice
|
||||
});
|
||||
total += line.Quantity * unitPrice;
|
||||
}
|
||||
|
||||
var po = new Models.ShopPO
|
||||
{
|
||||
FK_StoreId = request.StoreId,
|
||||
RaisedById = raisedById,
|
||||
TotalAmount = total,
|
||||
Status = ShopPOStatus.Pending
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.AddAsync(po);
|
||||
foreach (var item in items) item.FK_ShopPOId = po.Id;
|
||||
await repo.AddItemsAsync(items);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await repo.GetByIdAsync(po.Id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<ShopPOResponse> UpdateItemsAsync(Guid id, UpdateShopPOItemsRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var po = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Shop PO not found");
|
||||
|
||||
if (po.ConfirmedAt is not null)
|
||||
throw new InvalidOperationException("Items can only be changed before the Shop PO is confirmed");
|
||||
|
||||
if (request.Items.Count == 0)
|
||||
throw new InvalidOperationException("At least one item is required");
|
||||
|
||||
var newItems = new List<ShopPOItem>();
|
||||
decimal total = 0;
|
||||
|
||||
foreach (var line in request.Items)
|
||||
{
|
||||
var unitPrice = line.UnitPrice
|
||||
?? (await priceListService.ResolveByStoreAsync(line.ItemId, po.FK_StoreId, DateTime.Now))?.Price
|
||||
?? throw new InvalidOperationException($"No resolvable price for item {line.ItemId}");
|
||||
|
||||
newItems.Add(new ShopPOItem
|
||||
{
|
||||
FK_ShopPOId = id,
|
||||
FK_ItemId = line.ItemId,
|
||||
Quantity = line.Quantity,
|
||||
QuantityFulfilled = 0,
|
||||
UnitPrice = unitPrice
|
||||
});
|
||||
total += line.Quantity * unitPrice;
|
||||
}
|
||||
|
||||
po.TotalAmount = total;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await repo.ReplaceItemsAsync(id, newItems);
|
||||
repo.Update(po);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await repo.GetByIdAsync(id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<ShopPOResponse> ConfirmAsync(Guid id, Guid confirmedBy, CancellationToken ct = default)
|
||||
{
|
||||
var po = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Shop PO not found");
|
||||
|
||||
if (po.ConfirmedAt is not null)
|
||||
throw new InvalidOperationException("Shop PO is already confirmed");
|
||||
|
||||
if (po.Status == ShopPOStatus.Cancelled)
|
||||
throw new InvalidOperationException("Cannot confirm a cancelled Shop PO");
|
||||
|
||||
po.ConfirmedAt = DateTime.Now;
|
||||
po.ConfirmedBy = confirmedBy;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(po); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(po);
|
||||
}
|
||||
|
||||
public async Task<ShopPOResponse> ConfirmAndCreateInvoiceAsync(Guid id, Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var po = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Shop PO not found");
|
||||
|
||||
if (po.ConfirmedAt is not null)
|
||||
throw new InvalidOperationException("Shop PO is already confirmed");
|
||||
|
||||
if (po.Status == ShopPOStatus.Cancelled)
|
||||
throw new InvalidOperationException("Cannot confirm a cancelled Shop PO");
|
||||
|
||||
po.ConfirmedAt = DateTime.Now;
|
||||
po.ConfirmedBy = userId;
|
||||
|
||||
var invoice = new Models.Invoice
|
||||
{
|
||||
FK_ShopPOId = po.Id,
|
||||
Status = InvoiceStatus.Draft,
|
||||
PaymentStatus = PaymentStatus.Pending,
|
||||
CreatedBy = userId,
|
||||
TotalAmount = po.TotalAmount
|
||||
};
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try
|
||||
{
|
||||
await invoiceRepo.AddAsync(invoice);
|
||||
po.InvoiceId = invoice.Id;
|
||||
repo.Update(po);
|
||||
await uow.CommitAsync(ct);
|
||||
}
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
var saved = await repo.GetByIdAsync(id);
|
||||
return ToResponse(saved!);
|
||||
}
|
||||
|
||||
public async Task<ShopPOResponse> CancelAsync(Guid id, CancellationToken ct = default)
|
||||
{
|
||||
var po = await repo.GetByIdAsync(id)
|
||||
?? throw new KeyNotFoundException("Shop PO not found");
|
||||
|
||||
if (po.Status == ShopPOStatus.Cancelled)
|
||||
throw new InvalidOperationException("Shop PO is already cancelled");
|
||||
|
||||
if (po.Status is ShopPOStatus.PartiallyFulfilled or ShopPOStatus.Fulfilled)
|
||||
throw new InvalidOperationException($"Cannot cancel a Shop PO in {po.Status} status");
|
||||
|
||||
po.Status = ShopPOStatus.Cancelled;
|
||||
|
||||
await uow.BeginAsync(ct);
|
||||
try { repo.Update(po); await uow.CommitAsync(ct); }
|
||||
catch { await uow.RollbackAsync(ct); throw; }
|
||||
|
||||
return ToResponse(po);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Distribution.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddRideCancelReason : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "CancelReason",
|
||||
table: "DeliveryRuns",
|
||||
type: "longtext",
|
||||
nullable: true)
|
||||
.Annotation("MySql:CharSet", "utf8mb4");
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "CancelTypeCode",
|
||||
table: "DeliveryRuns",
|
||||
type: "int",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "DeliveryRuns",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("31000000-0000-0000-0000-000000000001"),
|
||||
columns: new[] { "CancelReason", "CancelTypeCode" },
|
||||
values: new object[] { null, null });
|
||||
|
||||
migrationBuilder.UpdateData(
|
||||
table: "DeliveryRuns",
|
||||
keyColumn: "Id",
|
||||
keyValue: new Guid("31000000-0000-0000-0000-000000000002"),
|
||||
columns: new[] { "CancelReason", "CancelTypeCode" },
|
||||
values: new object[] { null, null });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CancelReason",
|
||||
table: "DeliveryRuns");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CancelTypeCode",
|
||||
table: "DeliveryRuns");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,6 +206,12 @@ namespace Distribution.Migrations
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("char(36)");
|
||||
|
||||
b.Property<string>("CancelReason")
|
||||
.HasColumnType("longtext");
|
||||
|
||||
b.Property<int?>("CancelTypeCode")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<DateTime?>("ClosedAt")
|
||||
.HasColumnType("datetime(6)");
|
||||
|
||||
|
||||
@@ -19,5 +19,8 @@ namespace Distribution.Models
|
||||
|
||||
public DateTime? StartedAt { get; set; }
|
||||
public DateTime? ClosedAt { get; set; }
|
||||
|
||||
public CancelRequestType? CancelTypeCode { get; set; }
|
||||
public string? CancelReason { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import {
|
||||
shopPos as shopPosApi,
|
||||
regions as regionsApi,
|
||||
routes as routesApi,
|
||||
warehouses as warehousesApi,
|
||||
loadingSheets as loadingSheetsApi,
|
||||
getApiError,
|
||||
getPaginatedItems,
|
||||
} from '@/lib/api/index'
|
||||
import type { LoadingSheetResponse, ShopPOResponse, RegionResponse, RouteResponse, WarehouseResponse } from '@/types/api'
|
||||
import type { LoadingSheetItemInput } from '@/lib/api/operations'
|
||||
|
||||
const ALL = '__all__'
|
||||
|
||||
interface LoadingSheetItemsDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSuccess: () => void
|
||||
sheet: LoadingSheetResponse | null
|
||||
}
|
||||
|
||||
interface PickedLine {
|
||||
shopPOItemId: string
|
||||
itemId: string
|
||||
itemName: string
|
||||
storeName: string
|
||||
orderedQty: number
|
||||
remainingQty: number
|
||||
checked: boolean
|
||||
quantity: number
|
||||
}
|
||||
|
||||
export function LoadingSheetItemsDialog({ open, onClose, onSuccess, sheet }: LoadingSheetItemsDialogProps) {
|
||||
const [regionsList, setRegionsList] = useState<RegionResponse[]>([])
|
||||
const [routesList, setRoutesList] = useState<RouteResponse[]>([])
|
||||
const [warehousesList, setWarehousesList] = useState<WarehouseResponse[]>([])
|
||||
|
||||
const [regionId, setRegionId] = useState('')
|
||||
const [routeId, setRouteId] = useState('')
|
||||
const [warehouseId, setWarehouseId] = useState('')
|
||||
|
||||
const [pos, setPos] = useState<ShopPOResponse[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [lines, setLines] = useState<Record<string, PickedLine>>({})
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setRegionId('')
|
||||
setRouteId('')
|
||||
setWarehouseId('')
|
||||
setPos([])
|
||||
setLines({})
|
||||
|
||||
Promise.all([
|
||||
regionsApi.list({ pageSize: 200 }),
|
||||
warehousesApi.list({ pageSize: 200 }),
|
||||
])
|
||||
.then(([regionsRes, warehousesRes]) => {
|
||||
setRegionsList(getPaginatedItems(regionsRes))
|
||||
setWarehousesList(getPaginatedItems(warehousesRes))
|
||||
})
|
||||
.catch((err) => toast.add({ title: 'Failed to load reference data', description: getApiError(err), type: 'error' }))
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setRouteId('')
|
||||
routesApi.list({ regionId: regionId || undefined, pageSize: 200 })
|
||||
.then((res) => setRoutesList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load routes', description: getApiError(err), type: 'error' }))
|
||||
}, [open, regionId])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setLoading(true)
|
||||
shopPosApi.list({ regionId: regionId || undefined, routeId: routeId || undefined, confirmed: true, pageSize: 200 })
|
||||
.then((res) => {
|
||||
const items = getPaginatedItems(res).filter((po) => po.status === 'Pending' || po.status === 'PartiallyFulfilled')
|
||||
setPos(items)
|
||||
})
|
||||
.catch((err) => toast.add({ title: 'Failed to load Shop POs', description: getApiError(err), type: 'error' }))
|
||||
.finally(() => setLoading(false))
|
||||
}, [open, regionId, routeId])
|
||||
|
||||
const rows = useMemo<PickedLine[]>(() => {
|
||||
const result: PickedLine[] = []
|
||||
for (const po of pos) {
|
||||
for (const item of po.items) {
|
||||
const remaining = item.quantity - item.quantityFulfilled
|
||||
if (remaining <= 0) continue
|
||||
result.push(
|
||||
lines[item.id] ?? {
|
||||
shopPOItemId: item.id,
|
||||
itemId: item.itemId,
|
||||
itemName: item.itemName,
|
||||
storeName: po.storeName,
|
||||
orderedQty: item.quantity,
|
||||
remainingQty: remaining,
|
||||
checked: false,
|
||||
quantity: remaining,
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}, [pos, lines])
|
||||
|
||||
function toggleLine(line: PickedLine, checked: boolean) {
|
||||
setLines((prev) => ({ ...prev, [line.shopPOItemId]: { ...line, checked } }))
|
||||
}
|
||||
|
||||
function setLineQuantity(line: PickedLine, quantity: number) {
|
||||
setLines((prev) => ({ ...prev, [line.shopPOItemId]: { ...line, quantity } }))
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!sheet) return
|
||||
if (!warehouseId) {
|
||||
toast.add({ title: 'Select a warehouse first', type: 'error' })
|
||||
return
|
||||
}
|
||||
const selected = rows.filter((r) => (lines[r.shopPOItemId]?.checked ?? false))
|
||||
if (selected.length === 0) {
|
||||
toast.add({ title: 'Select at least one item', type: 'error' })
|
||||
return
|
||||
}
|
||||
|
||||
const items: LoadingSheetItemInput[] = selected.map((r) => {
|
||||
const line = lines[r.shopPOItemId]
|
||||
return {
|
||||
fK_ItemId: line.itemId,
|
||||
fK_WarehouseId: warehouseId,
|
||||
quantity: line.quantity,
|
||||
fK_ShopPOItemId: line.shopPOItemId,
|
||||
}
|
||||
})
|
||||
|
||||
setSubmitting(true)
|
||||
try {
|
||||
await loadingSheetsApi.updateItems(sheet.id, items)
|
||||
toast.add({ title: 'Loading sheet items saved', type: 'success' })
|
||||
onSuccess()
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to save items', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!sheet) return null
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(v) => !v && onClose()}>
|
||||
<DialogContent className="overflow-y-auto sm:max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Set Loading Sheet Items</DialogTitle>
|
||||
<DialogDescription>
|
||||
Pick items from confirmed Shop POs to load onto the vehicle for this ride. Narrow the list
|
||||
by region/route first.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-wrap items-end gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-muted-foreground">Region</label>
|
||||
<Select value={regionId || ALL} onValueChange={(v) => setRegionId(!v || v === ALL ? '' : v)}>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue placeholder="All regions" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL}>All regions</SelectItem>
|
||||
{regionsList.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-muted-foreground">Route</label>
|
||||
<Select value={routeId || ALL} onValueChange={(v) => setRouteId(!v || v === ALL ? '' : v)}>
|
||||
<SelectTrigger className="w-48">
|
||||
<SelectValue placeholder="All routes" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL}>All routes</SelectItem>
|
||||
{routesList.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.routeName}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-muted-foreground">Warehouse *</label>
|
||||
<Select value={warehouseId} onValueChange={(v) => setWarehouseId(v ?? '')}>
|
||||
<SelectTrigger className="w-52">
|
||||
<SelectValue placeholder="Select warehouse..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{warehousesList.map((w) => (
|
||||
<SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto rounded-xl border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50">
|
||||
<tr>
|
||||
<th className="w-10 px-3 py-2"></th>
|
||||
<th className="px-3 py-2 text-left font-medium">Store</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Item</th>
|
||||
<th className="w-24 px-3 py-2 text-right font-medium">Ordered</th>
|
||||
<th className="w-32 px-3 py-2 text-right font-medium">Qty to load</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">Loading…</td></tr>
|
||||
) : rows.length === 0 ? (
|
||||
<tr><td colSpan={5} className="text-center text-muted-foreground px-3 py-6">No eligible Shop PO items found for this filter.</td></tr>
|
||||
) : (
|
||||
rows.map((row) => {
|
||||
const line = lines[row.shopPOItemId] ?? row
|
||||
return (
|
||||
<tr key={row.shopPOItemId} className="border-t">
|
||||
<td className="px-3 py-2">
|
||||
<Checkbox
|
||||
checked={line.checked}
|
||||
onCheckedChange={(v) => toggleLine(row, v === true)}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-2">{row.storeName}</td>
|
||||
<td className="px-3 py-2">{row.itemName}</td>
|
||||
<td className="px-3 py-2 text-right text-muted-foreground">{row.remainingQty}</td>
|
||||
<td className="px-3 py-2">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
max={row.remainingQty}
|
||||
value={line.quantity}
|
||||
disabled={!line.checked}
|
||||
onChange={(e) => setLineQuantity(row, Number(e.target.value))}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" disabled={submitting} onClick={handleSubmit}>
|
||||
{submitting ? 'Saving…' : 'Save Items'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
+97
-5
@@ -16,13 +16,14 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { toast } from '@/components/ui/toast'
|
||||
import { loadingSheets as loadingSheetsApi, rides as ridesApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { LoadingSheetResponse, LoadingSheetStatus, RideResponse } from '@/types/api'
|
||||
import { loadingSheets as loadingSheetsApi, rides as ridesApi, regions as regionsApi, routes as routesApi, deliveryTasks as deliveryTasksApi, getApiError, getPaginatedItems } from '@/lib/api/index'
|
||||
import type { LoadingSheetResponse, LoadingSheetStatus, RideResponse, RegionResponse, RouteResponse } from '@/types/api'
|
||||
|
||||
const ALL = '__all__'
|
||||
|
||||
import { LoadingSheetViewSheet } from './loading-sheet-view-sheet'
|
||||
import { LoadingSheetCreateDialog } from './loading-sheet-create-dialog'
|
||||
import { LoadingSheetItemsDialog } from './loading-sheet-items-dialog'
|
||||
|
||||
const fmtDate = (v: string) =>
|
||||
new Date(v).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
|
||||
@@ -43,18 +44,35 @@ export function LoadingSheetsClient() {
|
||||
|
||||
const [createOpen, setCreateOpen] = useState(false)
|
||||
const [viewOpen, setViewOpen] = useState(false)
|
||||
const [itemsOpen, setItemsOpen] = useState(false)
|
||||
const [selectedSheet, setSelectedSheet] = useState<LoadingSheetResponse | null>(null)
|
||||
|
||||
const [ridesList, setRidesList] = useState<RideResponse[]>([])
|
||||
const [rideId, setRideId] = useState('')
|
||||
const [statusFilter, setStatusFilter] = useState<LoadingSheetStatus | ''>('')
|
||||
|
||||
const [regionsList, setRegionsList] = useState<RegionResponse[]>([])
|
||||
const [routesList, setRoutesList] = useState<RouteResponse[]>([])
|
||||
const [regionId, setRegionId] = useState('')
|
||||
const [routeId, setRouteId] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
ridesApi.list({ pageSize: 200 })
|
||||
.then((res) => setRidesList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load rides', description: getApiError(err), type: 'error' }))
|
||||
|
||||
regionsApi.list({ pageSize: 200 })
|
||||
.then((res) => setRegionsList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load regions', description: getApiError(err), type: 'error' }))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
setRouteId('')
|
||||
routesApi.list({ regionId: regionId || undefined, pageSize: 200 })
|
||||
.then((res) => setRoutesList(getPaginatedItems(res)))
|
||||
.catch((err) => toast.add({ title: 'Failed to load routes', description: getApiError(err), type: 'error' }))
|
||||
}, [regionId])
|
||||
|
||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
@@ -63,6 +81,8 @@ export function LoadingSheetsClient() {
|
||||
pageSize: ps,
|
||||
rideId: rideId || undefined,
|
||||
status: statusFilter || undefined,
|
||||
regionId: regionId || undefined,
|
||||
routeId: routeId || undefined,
|
||||
})
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
@@ -71,17 +91,19 @@ export function LoadingSheetsClient() {
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [rideId, statusFilter])
|
||||
}, [rideId, statusFilter, regionId, routeId])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
|
||||
const hasFilters = !!rideId || !!statusFilter
|
||||
const hasFilters = !!rideId || !!statusFilter || !!regionId || !!routeId
|
||||
|
||||
function clearFilters() {
|
||||
setRideId('')
|
||||
setStatusFilter('')
|
||||
setRegionId('')
|
||||
setRouteId('')
|
||||
}
|
||||
|
||||
function handleView(row: LoadingSheetResponse) {
|
||||
@@ -89,6 +111,11 @@ export function LoadingSheetsClient() {
|
||||
setViewOpen(true)
|
||||
}
|
||||
|
||||
function handleSetItems(row: LoadingSheetResponse) {
|
||||
setSelectedSheet(row)
|
||||
setItemsOpen(true)
|
||||
}
|
||||
|
||||
async function handleConfirm(row: LoadingSheetResponse) {
|
||||
try {
|
||||
await loadingSheetsApi.confirm(row.id)
|
||||
@@ -99,6 +126,16 @@ export function LoadingSheetsClient() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGenerateTasks(row: LoadingSheetResponse) {
|
||||
try {
|
||||
const tasks = await deliveryTasksApi.generate(row.fK_RideId)
|
||||
toast.add({ title: `Generated ${tasks.length} delivery task(s)`, type: 'success' })
|
||||
fetchData(page, pageSize)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to generate delivery tasks', description: getApiError(err), type: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
const tableConfig = useMemo<TableConfig<LoadingSheetResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
@@ -165,11 +202,23 @@ export function LoadingSheetsClient() {
|
||||
label: 'View sheet',
|
||||
onClick: handleView,
|
||||
},
|
||||
{
|
||||
action: 'edit',
|
||||
label: 'Set items',
|
||||
onClick: handleSetItems,
|
||||
visible: (target) => target.status === 'Planned',
|
||||
},
|
||||
{
|
||||
action: 'confirm',
|
||||
label: 'Confirm & commit stock',
|
||||
onClick: handleConfirm,
|
||||
visible: (target) => target.status === 'Planned',
|
||||
visible: (target) => target.status === 'Planned' && target.items.length > 0,
|
||||
},
|
||||
{
|
||||
action: 'generate',
|
||||
label: 'Generate delivery tasks',
|
||||
onClick: handleGenerateTasks,
|
||||
visible: (target) => target.status === 'Confirmed',
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -226,6 +275,42 @@ export function LoadingSheetsClient() {
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-muted-foreground">Region</label>
|
||||
<Select
|
||||
value={regionId || ALL}
|
||||
onValueChange={(v) => { setRegionId(!v || v === ALL ? '' : v); setPage(1) }}
|
||||
>
|
||||
<SelectTrigger className="w-44">
|
||||
<SelectValue placeholder="All regions" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL}>All regions</SelectItem>
|
||||
{regionsList.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-muted-foreground">Route</label>
|
||||
<Select
|
||||
value={routeId || ALL}
|
||||
onValueChange={(v) => { setRouteId(!v || v === ALL ? '' : v); setPage(1) }}
|
||||
>
|
||||
<SelectTrigger className="w-44">
|
||||
<SelectValue placeholder="All routes" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ALL}>All routes</SelectItem>
|
||||
{routesList.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>{r.routeName}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{hasFilters && (
|
||||
<Button variant="ghost" size="sm" onClick={() => { clearFilters(); setPage(1) }}>
|
||||
Clear filters
|
||||
@@ -255,6 +340,13 @@ export function LoadingSheetsClient() {
|
||||
onClose={() => setViewOpen(false)}
|
||||
sheet={selectedSheet}
|
||||
/>
|
||||
|
||||
<LoadingSheetItemsDialog
|
||||
open={itemsOpen}
|
||||
onClose={() => setItemsOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
sheet={selectedSheet}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -55,6 +55,12 @@ export function RideViewSheet({ open, onClose, ride }: RideViewSheetProps) {
|
||||
<Row label="Meter End" value={ride.meterend ? `${ride.meterend} km` : '—'} />
|
||||
<Row label="Started At" value={fmtDateTime(ride.startedAt)} />
|
||||
<Row label="Closed At" value={fmtDateTime(ride.closedAt)} />
|
||||
{ride.status === 'Cancelled' && (
|
||||
<>
|
||||
<Row label="Cancel Type" value={ride.cancelTypeCode || '—'} />
|
||||
<Row label="Cancel Reason" value={ride.cancelReason || '—'} />
|
||||
</>
|
||||
)}
|
||||
<Row label="Created At" value={fmtDateTime(ride.createdAt)} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -30,8 +30,6 @@ const RIDE_STATUS_VARIANT: Record<RideStatus, 'default' | 'secondary' | 'destruc
|
||||
export function RidesClient() {
|
||||
const [data, setData] = useState<RideResponse[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [pageSize, setPageSize] = useState(20)
|
||||
|
||||
const [sheetOpen, setSheetOpen] = useState(false)
|
||||
@@ -41,12 +39,11 @@ export function RidesClient() {
|
||||
const [closeOpen, setCloseOpen] = useState(false)
|
||||
const [selectedRide, setSelectedRide] = useState<RideResponse | null>(null)
|
||||
|
||||
const fetchData = useCallback(async (p: number, ps: number) => {
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const res = await ridesApi.list({ page: p, pageSize: ps })
|
||||
const res = await ridesApi.list({ pageSize: 500 })
|
||||
setData(getPaginatedItems(res))
|
||||
setTotal(res.total)
|
||||
} catch (err) {
|
||||
toast.add({ title: 'Failed to load rides', description: getApiError(err), type: 'error' })
|
||||
} finally {
|
||||
@@ -55,8 +52,8 @@ export function RidesClient() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData(page, pageSize)
|
||||
}, [fetchData, page, pageSize])
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
function handleView(row: RideResponse) {
|
||||
setSelectedRide(row)
|
||||
@@ -80,7 +77,6 @@ export function RidesClient() {
|
||||
|
||||
const tableConfig = useMemo<TableConfig<RideResponse>>(() => ({
|
||||
rowKey: 'id',
|
||||
serverSide: true,
|
||||
stickyHeader: true,
|
||||
emptyMessage: 'No rides found.',
|
||||
pagination: { enabled: true, pageSize, pageSizeOptions: [10, 20, 50] },
|
||||
@@ -149,6 +145,7 @@ export function RidesClient() {
|
||||
{
|
||||
action: 'cancel',
|
||||
label: 'Cancel ride',
|
||||
tone: 'destructive',
|
||||
onClick: handleCancel,
|
||||
visible: (target) => target.status === 'Open',
|
||||
},
|
||||
@@ -175,9 +172,8 @@ export function RidesClient() {
|
||||
config={tableConfig}
|
||||
data={data}
|
||||
loading={loading}
|
||||
totalCount={total}
|
||||
totalCount={data.length}
|
||||
onServerSideChange={({ page: p }) => {
|
||||
setPage(p.page)
|
||||
setPageSize(p.pageSize)
|
||||
}}
|
||||
/>
|
||||
@@ -185,7 +181,7 @@ export function RidesClient() {
|
||||
<RideSheet
|
||||
open={sheetOpen}
|
||||
onClose={() => setSheetOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
onSuccess={fetchData}
|
||||
/>
|
||||
|
||||
<RideViewSheet
|
||||
@@ -197,21 +193,21 @@ export function RidesClient() {
|
||||
<RideEditDriverSheet
|
||||
open={editDriverOpen}
|
||||
onClose={() => setEditDriverOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
onSuccess={fetchData}
|
||||
ride={selectedRide}
|
||||
/>
|
||||
|
||||
<RideCancelDialog
|
||||
open={cancelOpen}
|
||||
onClose={() => setCancelOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
onSuccess={fetchData}
|
||||
ride={selectedRide}
|
||||
/>
|
||||
|
||||
<RideCloseDialog
|
||||
open={closeOpen}
|
||||
onClose={() => setCloseOpen(false)}
|
||||
onSuccess={() => fetchData(page, pageSize)}
|
||||
onSuccess={fetchData}
|
||||
ride={selectedRide}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -12,7 +12,8 @@ export type RowActionKind =
|
||||
| 'close'
|
||||
| 'cancel'
|
||||
| 'print'
|
||||
| 'finalize';
|
||||
| 'finalize'
|
||||
| 'generate';
|
||||
|
||||
export interface BadgeConfig {
|
||||
colorMap?: Record<string, string>;
|
||||
|
||||
@@ -23,6 +23,7 @@ const ACTION_ICONS = {
|
||||
deactivate: Cancel01Icon,
|
||||
edit: PencilEdit01Icon,
|
||||
finalize: CheckmarkSquare01Icon,
|
||||
generate: CheckmarkSquare01Icon,
|
||||
print: PrinterIcon,
|
||||
view: EyeIcon,
|
||||
} as const
|
||||
|
||||
@@ -66,6 +66,8 @@ export interface LoadingSheetItemInput {
|
||||
export interface LoadingSheetListParams extends PageParams {
|
||||
rideId?: string
|
||||
status?: LoadingSheetStatus
|
||||
routeId?: string
|
||||
regionId?: string
|
||||
}
|
||||
|
||||
export const loadingSheets = {
|
||||
@@ -93,6 +95,9 @@ export interface DeliveryTaskItemQuantity {
|
||||
}
|
||||
|
||||
export const deliveryTasks = {
|
||||
generate: (rideId: string) =>
|
||||
api.post<DeliveryTaskResponse[]>(`/rides/${rideId}/tasks/generate`).then(r => r.data),
|
||||
|
||||
listByRide: (rideId: string) =>
|
||||
api.get<DeliveryTaskResponse[]>(`/rides/${rideId}/tasks`).then(r => r.data),
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface UpdateShopPOItemsBody {
|
||||
export interface ShopPOListParams extends PageParams {
|
||||
agentId?: string
|
||||
routeId?: string
|
||||
regionId?: string
|
||||
shopId?: string
|
||||
confirmed?: boolean
|
||||
status?: ShopPOStatus
|
||||
|
||||
@@ -561,6 +561,8 @@ export interface RideResponse {
|
||||
meterend: number
|
||||
startedAt: string | null
|
||||
closedAt: string | null
|
||||
cancelTypeCode: CancelRequestType | null
|
||||
cancelReason: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user