diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 4778aec5c..c6984a10d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -10,9 +10,8 @@ - [ ] Relevant frontend `pnpm run lint && pnpm run test:unit` passes (Admin / Store / both) - [ ] Python `uv run ruff check . && uv run pytest` passes (if touching `service/Embedding/`) - [ ] `bash scripts/check-feature-conventions.sh` passes (C# changes) -- [ ] `bash scripts/check-cross-module-refs.sh` passes (C# changes — no new cross-module using statements) - [ ] New features follow vertical-slice layout (Handler + Request + Response + Endpoint + Validator) -- [ ] Cross-module work uses `ISender`, not direct namespace reference +- [ ] Cross-module behavior uses `ISender` or direct service/navigation calls as fits the feature slice - [ ] Domain operations return `Result` / `Result`, not exceptions - [ ] `.harness/domains.yml` LOC counts are up-to-date for affected modules - [ ] `AGENTS.md` is updated if conventions or structure changed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70f6bd092..1beaa4ae0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,8 @@ jobs: - run: dotnet build - name: Check feature conventions run: bash scripts/check-feature-conventions.sh - - name: Check cross-module references - run: bash scripts/check-cross-module-refs.sh + - name: Check route conventions + run: bash scripts/check-route-conventions.sh - run: dotnet test service/Api/tests/Shared.UnitTests - run: dotnet test service/Api/tests/Module.UnitTests diff --git a/.gitignore b/.gitignore index 6425a4ee9..51951a653 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ # dotenv files .env +.env.local +.env.*.local # User-specific files *.rsuser @@ -22,7 +24,9 @@ mono_crash.* # Build results [Dd]ebug/ [Dd]ebugPublic/ -[Rr]elease/ +# NARROWED: only match build-output Release dirs — NOT source feature dirs (e.g. StockReservations/Release/) +**/[Bb]in/[Rr]elease/ +**/[Oo]bj/[Rr]elease/ [Rr]eleases/ x64/ x86/ diff --git a/.opencode/plans/2026-08-07-cross-module-contract-relocation.md b/.opencode/plans/2026-08-07-cross-module-contract-relocation.md new file mode 100644 index 000000000..5c7790e92 --- /dev/null +++ b/.opencode/plans/2026-08-07-cross-module-contract-relocation.md @@ -0,0 +1,1017 @@ +# Cross-Module Contract Relocation — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Move 15 cross-module MediatR contracts from `Shared/Application/Contracts/` into module feature folders, remove `Contracts/` folder layer, delete 2 dead Catalog queries. + +**Architecture:** Each cross-module service becomes a feature folder following the `CreateOptionType` pattern (static partial class with Command/Query + Handler + Request/Response). Handlers already exist in module folders — we move the Command/Query/Response records alongside them and delete the Shared originals. + +**Tech Stack:** .NET 10, C#, MediatR, FluentValidation, Carter, EF Core + PostgreSQL + +## Global Constraints + +- All 9 modules share one `Module.csproj` assembly — no project references change +- `TreatWarningsAsErrors=true` — any warning fails build +- Domain error factories in `Module.{X}/Domain/{Entity}/{Entity}.Result.cs` — use existing errors, add new ones only if needed +- `Result` / `Result` patterns for all return types — no inline error strings +- Tests use xUnit + FluentAssertions + Moq + EF Core InMemory + +--- + +## File Structure + +### Files to CREATE (new) + +| Module | Path | Content | +|---|---|---| +| Inventory | `Features/Storefront/ReserveCartStock/ReserveCartStock.Command.cs` | `ReserveCartStockCommand` + `ReserveLineItem` records | +| Inventory | `Features/Storefront/ReserveCartStock/ReserveCartStock.Response.cs` | `ReserveCartStockResponse` record | +| Inventory | `Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.Command.cs` | `ConsumeCartStockReservationsCommand` record | +| Inventory | `Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.Command.cs` | `ReleaseCartStockReservationsCommand` record | +| Inventory | `Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Query.cs` | `CheckVariantAvailabilityQuery` record | +| Inventory | `Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Response.cs` | `CheckVariantAvailabilityResponse` record | +| Ordering | `Features/Storefront/GetCartForCheckout/GetCartForCheckout.Query.cs` | `GetCartForCheckoutQuery` record | +| Ordering | `Features/Storefront/GetCartForCheckout/GetCartForCheckout.Response.cs` | `GetCartForCheckoutResponse` + `CartLineItem` records | +| Ordering | `Features/Storefront/AdvanceCheckoutState/AdvanceCheckoutState.Command.cs` | `AdvanceCheckoutStateCommand` record | +| Ordering | `Features/Storefront/GetCartForShipping/GetCartForShipping.Query.cs` | `GetCartForShippingQuery` record | +| Ordering | `Features/Storefront/GetCartForShipping/GetCartForShipping.Response.cs` | `CartForShippingResponse` record | +| Payment | `Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Query.cs` | `GetPaymentForCheckoutQuery` record | +| Payment | `Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Response.cs` | `PaymentForCheckoutResponse` record | +| Payment | `Features/Storefront/MarkPaymentPaid/MarkPaymentPaid.Command.cs` | `MarkPaymentPaidCommand` record | +| Profile | `Features/Storefront/Profiles/Create/CreateProfile.Command.cs` | `CreateUserProfileCommand` + `CreateUserProfileResult` records | + +### Files to MOVE (handler + delete old location) + +| FROM | TO | +|---|---| +| `Inventory/.../Contracts/ReserveCartStock/ReserveCartStock.cs` | `Inventory/.../ReserveCartStock/ReserveCartStock.cs` | +| `Inventory/.../Contracts/ConsumeCartStockReservations/ConsumeCartStockReservations.cs` | `Inventory/.../ConsumeCartStockReservations/ConsumeCartStockReservations.cs` | +| `Inventory/.../Contracts/ReleaseCartStockReservations/ReleaseCartStockReservations.cs` | `Inventory/.../ReleaseCartStockReservations/ReleaseCartStockReservations.cs` | +| `Inventory/.../Contracts/CheckVariantAvailability/CheckVariantAvailability.cs` | `Inventory/.../CheckVariantAvailability/CheckVariantAvailability.cs` | +| `Ordering/.../Contracts/GetCartForCheckout/GetCartForCheckout.cs` | `Ordering/.../GetCartForCheckout/GetCartForCheckout.cs` | +| `Ordering/.../Contracts/AdvanceCheckoutState/AdvanceCheckoutState.cs` | `Ordering/.../AdvanceCheckoutState/AdvanceCheckoutState.cs` | +| `Ordering/.../Contracts/GetCartForShipping/GetCartForShipping.cs` | `Ordering/.../GetCartForShipping/GetCartForShipping.cs` | +| `Payment/.../Contracts/GetPaymentForCheckout/GetPaymentForCheckout.cs` | `Payment/.../GetPaymentForCheckout/GetPaymentForCheckout.cs` | +| `Payment/.../Contracts/MarkPaymentPaid/MarkPaymentPaid.cs` | `Payment/.../MarkPaymentPaid/MarkPaymentPaid.cs` | +| `Shared/.../Contracts/Inventory/IStockQuantityService.cs` | `Inventory/Services/Abstractions/IStockQuantityService.cs` | + +### Files to UPDATE (consumer using statements) + +| Module | File | +|---|---| +| Ordering | `Cart/Checkout/CreateOrderFromCart.cs` | +| Ordering | `Cart/AddItem/AddToCart.cs` | +| Ordering | `Cart/UpdateItemQuantity/UpdateCartItemQuantity.cs` | +| Ordering | `GetCartForShipping/GetCartForShipping.cs` | +| Payment | `Payment/CreateIntent/CreatePaymentIntent.cs` | +| Profile | `Addresses/Validators/Address.Validator.cs` | +| Identity | `Emails/Confirm/ConfirmEmail.cs` | +| Identity | `Auth/Login/External/Authenticate/ExternalAuthenticate.cs` | +| Inventory | 4 handler files (self-cleanup) | +| Ordering | 3 handler files (self-cleanup) | +| Payment | 2 handler files (self-cleanup) | +| Profile | 1 handler file (self-cleanup) | +| Location | 2 handler files (self-cleanup) | + +### Files to DELETE + +| File | Reason | +|---|---| +| `Shared/.../Contracts/Inventory/ConsumeCartStockReservationsCommand.cs` | Moved to Inventory module | +| `Shared/.../Contracts/Inventory/ReserveCartStockCommand.cs` | Moved to Inventory module | +| `Shared/.../Contracts/Inventory/ReleaseCartStockReservationsCommand.cs` | Moved to Inventory module | +| `Shared/.../Contracts/Inventory/CheckVariantAvailabilityQuery.cs` | Moved to Inventory module | +| `Shared/.../Contracts/Inventory/IStockQuantityService.cs` | Moved to Inventory module | +| `Shared/.../Contracts/Ordering/GetCartForCheckoutQuery.cs` | Moved to Ordering module | +| `Shared/.../Contracts/Ordering/AdvanceCheckoutStateCommand.cs` | Moved to Ordering module | +| `Shared/.../Contracts/Ordering/GetCartForShippingQuery.cs` | Moved to Ordering module | +| `Shared/.../Contracts/Payment/GetPaymentForCheckoutQuery.cs` | Moved to Payment module | +| `Shared/.../Contracts/Payment/MarkPaymentPaidCommand.cs` | Moved to Payment module | +| `Shared/.../Contracts/Profile/CreateUserProfileCommand.cs` | Moved to Profile module | +| `Shared/.../Contracts/Location/CountryExistsByIsoQuery.cs` | Moved into handler file | +| `Shared/.../Contracts/Location/StateExistsByIsoQuery.cs` | Moved into handler file | +| `Shared/.../Contracts/Catalog/GetVariantDiscontinuedStatusesQuery.cs` | Dead code — no handler | +| `Shared/.../Contracts/Catalog/GetVariantWeightsQuery.cs` | Dead code — no handler | +| `Shared/.../Contracts/Inventory/` (directory) | Empty after moves | +| `Shared/.../Contracts/Ordering/` (directory) | Empty after moves | +| `Shared/.../Contracts/Payment/` (directory) | Empty after moves | +| `Shared/.../Contracts/Profile/` (directory) | Empty after moves | +| `Shared/.../Contracts/Location/` (directory) | Empty after moves | +| `Shared/.../Contracts/Catalog/` (directory) | Empty after moves | + +--- + +## Task 1: Inventory — ReserveCartStock + +**Files:** +- Create: `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.Command.cs` +- Create: `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.Response.cs` +- Move: `Module/Inventory/Features/Storefront/Contracts/ReserveCartStock/ReserveCartStock.cs` → `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.cs` +- Delete: `Shared/Application/Contracts/Inventory/ReserveCartStockCommand.cs` + +- [ ] **Step 1: Create command file** + +Create `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.Command.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.Contracts.ReserveCartStock; + +public sealed record ReserveCartStockCommand : ICommand +{ + public Guid CartId { get; init; } + public IReadOnlyList LineItems { get; init; } = []; + public int TtlMinutes { get; init; } = 30; +} + +public sealed record ReserveLineItem +{ + public Guid VariantId { get; init; } + public int Quantity { get; init; } +} +``` + +Wait — namespace should NOT include `Contracts`. Fix: + +```csharp +namespace Module.Inventory.Features.Storefront.ReserveCartStock; + +public sealed record ReserveCartStockCommand : ICommand +{ + public Guid CartId { get; init; } + public IReadOnlyList LineItems { get; init; } = []; + public int TtlMinutes { get; init; } = 30; +} + +public sealed record ReserveLineItem +{ + public Guid VariantId { get; init; } + public int Quantity { get; init; } +} +``` + +- [ ] **Step 2: Create response file** + +Create `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.Response.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.ReserveCartStock; + +public sealed record ReserveCartStockResponse +{ + public IReadOnlyList ReservationIds { get; init; } = []; +} +``` + +- [ ] **Step 3: Move handler file** + +Move `Module/Inventory/Features/Storefront/Contracts/ReserveCartStock/ReserveCartStock.cs` to `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.cs`. + +Update namespace from `Module.Inventory.Features.Storefront.Contracts.ReserveCartStock` to `Module.Inventory.Features.Storefront.ReserveCartStock`. + +Remove `using Shared.Application.Contracts.Inventory;` — the types are now in the same namespace. + +- [ ] **Step 4: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Inventory/ReserveCartStockCommand.cs`. + +- [ ] **Step 5: Build verification** + +Run: `dotnet build service/Api/src/Api` +Expected: PASS (consumers still reference old namespace — will fail, fix in Task 10) + +- [ ] **Step 6: Commit** + +```bash +git add -A +git commit -m "refactor(inventory): move ReserveCartStock from Shared to feature folder" +``` + +--- + +## Task 2: Inventory — ConsumeCartStockReservations + +**Files:** +- Create: `Module/Inventory/Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.Command.cs` +- Move: `Module/Inventory/Features/Storefront/Contracts/ConsumeCartStockReservations/ConsumeCartStockReservations.cs` → `Module/Inventory/Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.cs` +- Delete: `Shared/Application/Contracts/Inventory/ConsumeCartStockReservationsCommand.cs` + +- [x] **Step 1: Create command file** + +Create `Module/Inventory/Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.Command.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.ConsumeCartStockReservations; + +public sealed record ConsumeCartStockReservationsCommand : ICommand +{ + public Guid CartId { get; init; } +} +``` + +- [x] **Step 2: Move handler file** + +Move `Module/Inventory/Features/Storefront/Contracts/ConsumeCartStockReservations/ConsumeCartStockReservations.cs` to `Module/Inventory/Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.cs`. + +Update namespace to `Module.Inventory.Features.Storefront.ConsumeCartStockReservations`. + +Remove `using Shared.Application.Contracts.Inventory;`. + +- [x] **Step 3: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Inventory/ConsumeCartStockReservationsCommand.cs`. + +- [x] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(inventory): move ConsumeCartStockReservations from Shared to feature folder" +``` + +--- + +## Task 3: Inventory — ReleaseCartStockReservations + +**Files:** +- Create: `Module/Inventory/Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.Command.cs` +- Move: `Module/Inventory/Features/Storefront/Contracts/ReleaseCartStockReservations/ReleaseCartStockReservations.cs` → `Module/Inventory/Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.cs` +- Delete: `Shared/Application/Contracts/Inventory/ReleaseCartStockReservationsCommand.cs` + +- [ ] **Step 1: Create command file** + +Create `Module/Inventory/Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.Command.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.ReleaseCartStockReservations; + +public sealed record ReleaseCartStockReservationsCommand : ICommand +{ + public Guid CartId { get; init; } +} +``` + +- [ ] **Step 2: Move handler file** + +Move `Module/Inventory/Features/Storefront/Contracts/ReleaseCartStockReservations/ReleaseCartStockReservations.cs` to `Module/Inventory/Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.cs`. + +Update namespace to `Module.Inventory.Features.Storefront.ReleaseCartStockReservations`. + +Remove `using Shared.Application.Contracts.Inventory;`. + +- [ ] **Step 3: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Inventory/ReleaseCartStockReservationsCommand.cs`. + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(inventory): move ReleaseCartStockReservations from Shared to feature folder" +``` + +--- + +## Task 4: Inventory — CheckVariantAvailability + +**Files:** +- Create: `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Query.cs` +- Create: `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Response.cs` +- Move: `Module/Inventory/Features/Storefront/Contracts/CheckVariantAvailability/CheckVariantAvailability.cs` → `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.cs` +- Delete: `Shared/Application/Contracts/Inventory/CheckVariantAvailabilityQuery.cs` + +- [ ] **Step 1: Create query file** + +Create `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Query.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.CheckVariantAvailability; + +public sealed record CheckVariantAvailabilityQuery(Guid VariantId, int Quantity) + : IQuery; +``` + +- [ ] **Step 2: Create response file** + +Create `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.Response.cs`: + +```csharp +namespace Module.Inventory.Features.Storefront.CheckVariantAvailability; + +public sealed record CheckVariantAvailabilityResponse +{ + public Guid VariantId { get; init; } + public bool IsAvailable { get; init; } +} +``` + +- [ ] **Step 3: Move handler file** + +Move `Module/Inventory/Features/Storefront/Contracts/CheckVariantAvailability/CheckVariantAvailability.cs` to `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.cs`. + +Update namespace to `Module.Inventory.Features.Storefront.CheckVariantAvailability`. + +Remove `using Shared.Application.Contracts.Inventory;`. + +- [ ] **Step 4: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Inventory/CheckVariantAvailabilityQuery.cs`. + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "refactor(inventory): move CheckVariantAvailability from Shared to feature folder" +``` + +--- + +## Task 5: Inventory — IStockQuantityService + Delete Contracts + +**Files:** +- Move: `Shared/Application/Contracts/Inventory/IStockQuantityService.cs` → `Module/Inventory/Services/Abstractions/IStockQuantityService.cs` +- Delete: `Module/Inventory/Features/Storefront/Contracts/` (entire directory) + +- [ ] **Step 1: Move interface** + +Move `Shared/Application/Contracts/Inventory/IStockQuantityService.cs` to `Module/Inventory/Services/Abstractions/IStockQuantityService.cs`. + +Update namespace from `Shared.Application.Contracts.Inventory` to `Module.Inventory.Services.Abstractions`. + +- [ ] **Step 2: Delete Contracts/ directory** + +```bash +rm -rf service/Api/src/Module/Inventory/Features/Storefront/Contracts/ +``` + +- [ ] **Step 3: Build verification** + +Run: `dotnet build service/Api/src/Module` +Expected: PASS (consumers still reference old namespace — will fail at Api level, fix in Task 10) + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(inventory): move IStockQuantityService to Services/Abstractions, delete Contracts/" +``` + +--- + +## Task 6: Ordering — GetCartForCheckout + +**Files:** +- Create: `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.Query.cs` +- Create: `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.Response.cs` +- Move: `Module/Ordering/Features/Storefront/Contracts/GetCartForCheckout/GetCartForCheckout.cs` → `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.cs` +- Delete: `Shared/Application/Contracts/Ordering/GetCartForCheckoutQuery.cs` + +- [ ] **Step 1: Create query file** + +Create `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.Query.cs`: + +```csharp +namespace Module.Ordering.Features.Storefront.GetCartForCheckout; + +public sealed record GetCartForCheckoutQuery : IQuery +{ + public Guid CartId { get; init; } +} +``` + +- [ ] **Step 2: Create response file** + +Create `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.Response.cs`: + +```csharp +namespace Module.Ordering.Features.Storefront.GetCartForCheckout; + +public sealed record GetCartForCheckoutResponse +{ + public string State { get; init; } = default!; + public IReadOnlyList LineItems { get; init; } = []; + public decimal Total { get; init; } + public string? Email { get; init; } +} + +public sealed record CartLineItem +{ + public Guid VariantId { get; init; } + public int Quantity { get; init; } +} +``` + +- [ ] **Step 3: Move handler file** + +Move `Module/Ordering/Features/Storefront/Contracts/GetCartForCheckout/GetCartForCheckout.cs` to `Module/Ordering/Features/Storefront/GetCartForCheckout/GetCartForCheckout.cs`. + +Update namespace to `Module.Ordering.Features.Storefront.GetCartForCheckout`. + +Remove `using Shared.Application.Contracts.Ordering;`. + +- [ ] **Step 4: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Ordering/GetCartForCheckoutQuery.cs`. + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "refactor(ordering): move GetCartForCheckout from Shared to feature folder" +``` + +--- + +## Task 7: Ordering — AdvanceCheckoutState + +**Files:** +- Create: `Module/Ordering/Features/Storefront/AdvanceCheckoutState/AdvanceCheckoutState.Command.cs` +- Move: `Module/Ordering/Features/Storefront/Contracts/AdvanceCheckoutState/AdvanceCheckoutState.cs` → `Module/Ordering/Features/Storefront/AdvanceCheckoutState/AdvanceCheckoutState.cs` +- Delete: `Shared/Application/Contracts/Ordering/AdvanceCheckoutStateCommand.cs` + +- [ ] **Step 1: Create command file** + +Create `Module/Ordering/Features/Storefront/AdvanceCheckoutState/AdvanceCheckoutState.Command.cs`: + +```csharp +namespace Module.Ordering.Features.Storefront.AdvanceCheckoutState; + +public sealed record AdvanceCheckoutStateCommand : ICommand +{ + public Guid CartId { get; init; } + public string TargetState { get; init; } = default!; +} +``` + +- [ ] **Step 2: Move handler file** + +Move `Module/Ordering/Features/Storefront/Contracts/AdvanceCheckoutState/AdvanceCheckoutState.cs` to `Module/Ordering/Features/Storefront/AdvanceCheckoutState/AdvanceCheckoutState.cs`. + +Update namespace to `Module.Ordering.Features.Storefront.AdvanceCheckoutState`. + +Remove `using Shared.Application.Contracts.Ordering;`. + +- [ ] **Step 3: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Ordering/AdvanceCheckoutStateCommand.cs`. + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(ordering): move AdvanceCheckoutState from Shared to feature folder" +``` + +--- + +## Task 8: Ordering — GetCartForShipping + Delete Contracts + +**Files:** +- Create: `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.Query.cs` +- Create: `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.Response.cs` +- Move: `Module/Ordering/Features/Storefront/Contracts/GetCartForShipping/GetCartForShipping.cs` → `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.cs` +- Delete: `Shared/Application/Contracts/Ordering/GetCartForShippingQuery.cs` +- Delete: `Module/Ordering/Features/Storefront/Contracts/` (entire directory) + +- [ ] **Step 1: Create query file** + +Create `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.Query.cs`: + +```csharp +namespace Module.Ordering.Features.Storefront.GetCartForShipping; + +public sealed record GetCartForShippingQuery(Guid CartId) : IQuery; +``` + +- [ ] **Step 2: Create response file** + +Create `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.Response.cs`: + +```csharp +namespace Module.Ordering.Features.Storefront.GetCartForShipping; + +public sealed record CartForShippingResponse +{ + public decimal TotalWeight { get; init; } + public decimal TotalValue { get; init; } + public Guid? ShipAddressId { get; init; } + public string Currency { get; init; } = default!; +} +``` + +- [ ] **Step 3: Move handler file and rewrite weight calculation** + +Move `Module/Ordering/Features/Storefront/Contracts/GetCartForShipping/GetCartForShipping.cs` to `Module/Ordering/Features/Storefront/GetCartForShipping/GetCartForShipping.cs`. + +Update namespace to `Module.Ordering.Features.Storefront.GetCartForShipping`. + +Remove `using Shared.Application.Contracts.Ordering;` and `using Shared.Application.Contracts.Catalog;`. + +Replace the MediatR weights query (lines 25-28) with direct DB query: + +```csharp +var variantWeights = await dbContext.Set() + .Where(v => variantIds.Contains(v.Id)) + .Select(v => new { v.Id, v.Weight }) + .ToListAsync(cancellationToken); +var weightMap = variantWeights.ToDictionary(v => v.Id, v => v.Weight ?? 0m); +``` + +- [ ] **Step 4: Delete old Shared contract and Contracts/ directory** + +Delete `Shared/Application/Contracts/Ordering/GetCartForShippingQuery.cs`. + +```bash +rm -rf service/Api/src/Module/Ordering/Features/Storefront/Contracts/ +``` + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "refactor(ordering): move GetCartForShipping, rewrite weight calc, delete Contracts/" +``` + +--- + +## Task 9: Payment — GetPaymentForCheckout + +**Files:** +- Create: `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Query.cs` +- Create: `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Response.cs` +- Move: `Module/Payment/Features/Storefront/Contracts/GetPaymentForCheckout/GetPaymentForCheckout.cs` → `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.cs` +- Delete: `Shared/Application/Contracts/Payment/GetPaymentForCheckoutQuery.cs` + +- [ ] **Step 1: Create query file** + +Create `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Query.cs`: + +```csharp +namespace Module.Payment.Features.Storefront.GetPaymentForCheckout; + +public sealed record GetPaymentForCheckoutQuery : IQuery +{ + public string PaymentIntentId { get; init; } = default!; + public Guid OrderId { get; init; } +} +``` + +- [ ] **Step 2: Create response file** + +Create `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.Response.cs`: + +```csharp +namespace Module.Payment.Features.Storefront.GetPaymentForCheckout; + +public sealed record PaymentForCheckoutResponse +{ + public decimal Amount { get; init; } + public bool IsCompleted { get; init; } +} +``` + +- [ ] **Step 3: Move handler file** + +Move `Module/Payment/Features/Storefront/Contracts/GetPaymentForCheckout/GetPaymentForCheckout.cs` to `Module/Payment/Features/Storefront/GetPaymentForCheckout/GetPaymentForCheckout.cs`. + +Update namespace to `Module.Payment.Features.Storefront.GetPaymentForCheckout`. + +Remove `using Shared.Application.Contracts.Payment;`. + +- [ ] **Step 4: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Payment/GetPaymentForCheckoutQuery.cs`. + +- [ ] **Step 5: Commit** + +```bash +git add -A +git commit -m "refactor(payment): move GetPaymentForCheckout from Shared to feature folder" +``` + +--- + +## Task 10: Payment — MarkPaymentPaid + Delete Contracts + +**Files:** +- Create: `Module/Payment/Features/Storefront/MarkPaymentPaid/MarkPaymentPaid.Command.cs` +- Move: `Module/Payment/Features/Storefront/Contracts/MarkPaymentPaid/MarkPaymentPaid.cs` → `Module/Payment/Features/Storefront/MarkPaymentPaid/MarkPaymentPaid.cs` +- Delete: `Shared/Application/Contracts/Payment/MarkPaymentPaidCommand.cs` +- Delete: `Module/Payment/Features/Storefront/Contracts/` (entire directory) + +- [ ] **Step 1: Create command file** + +Create `Module/Payment/Features/Storefront/MarkPaymentPaid/MarkPaymentPaid.Command.cs`: + +```csharp +namespace Module.Payment.Features.Storefront.MarkPaymentPaid; + +public sealed record MarkPaymentPaidCommand : ICommand +{ + public Guid OrderId { get; init; } + public string PaymentIntentId { get; init; } = default!; +} +``` + +- [ ] **Step 2: Move handler file** + +Move `Module/Payment/Features/Storefront/Contracts/MarkPaymentPaid/MarkPaymentPaid.cs` to `Module/Payment/Features/Storefront/MarkPaymentPaid/MarkPaymentPaid.cs`. + +Update namespace to `Module.Payment.Features.Storefront.MarkPaymentPaid`. + +Remove `using Shared.Application.Contracts.Payment;`. + +- [ ] **Step 3: Delete old Shared contract and Contracts/ directory** + +Delete `Shared/Application/Contracts/Payment/MarkPaymentPaidCommand.cs`. + +```bash +rm -rf service/Api/src/Module/Payment/Features/Storefront/Contracts/ +``` + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(payment): move MarkPaymentPaid, delete Contracts/" +``` + +--- + +## Task 11: Catalog — Delete Dead Queries + +**Files:** +- Delete: `Shared/Application/Contracts/Catalog/GetVariantDiscontinuedStatusesQuery.cs` +- Delete: `Shared/Application/Contracts/Catalog/GetVariantWeightsQuery.cs` +- Delete: `Shared/Application/Contracts/Catalog/` (directory) +- Update: `Module/Ordering/.../Cart/Checkout/CreateOrderFromCart.cs` + +- [ ] **Step 1: Delete query contracts** + +```bash +rm service/Api/src/Shared/Application/Contracts/Catalog/GetVariantDiscontinuedStatusesQuery.cs +rm service/Api/src/Shared/Application/Contracts/Catalog/GetVariantWeightsQuery.cs +rmdir service/Api/src/Shared/Application/Contracts/Catalog/ +``` + +- [ ] **Step 2: Remove discontinued check from CreateOrderFromCart** + +In `Module/Ordering/Features/Storefront/Cart/Checkout/CreateOrderFromCart.cs`: + +Remove `using Shared.Application.Contracts.Catalog;` + +Remove the entire block (lines ~66-78): +```csharp +// Validate: Reject orders containing discontinued variants via ISender. +var variantIds = cart.LineItems.Select(li => li.VariantId).ToList(); +var discResult = await sender.Send(new GetVariantDiscontinuedStatusesQuery { VariantIds = variantIds }, cancellationToken); +if (discResult.IsFailure) + return discResult.Errors; + +var discontinuedVariantIds = discResult.Value! + .Where(kvp => kvp.Value) + .Select(kvp => kvp.Key) + .ToHashSet(); + +if (!cart.EnsureLineItemVariantsAreNotDiscontinued(discontinuedVariantIds)) + return OrderResult.Errors.VariantDiscontinued; +``` + +- [ ] **Step 3: Commit** + +```bash +git add -A +git commit -m "refactor(catalog): delete dead GetVariantDiscontinuedStatusesQuery and GetVariantWeightsQuery" +``` + +--- + +## Task 12: Profile — Move Command into CreateProfile + +**Files:** +- Create: `Module/Profile/Features/Storefront/Profiles/Create/CreateProfile.Command.cs` +- Update: `Module/Profile/Features/Storefront/Profiles/Create/CreateProfile.cs` +- Delete: `Shared/Application/Contracts/Profile/CreateUserProfileCommand.cs` + +- [ ] **Step 1: Create command file** + +Create `Module/Profile/Features/Storefront/Profiles/Create/CreateProfile.Command.cs`: + +```csharp +namespace Module.Profile.Features.Storefront.Profiles.Create; + +public sealed record CreateUserProfileCommand : ICommand +{ + public Guid UserId { get; init; } + public string FirstName { get; init; } = default!; + public string? LastName { get; init; } + public string Email { get; init; } = default!; +} + +public sealed record CreateUserProfileResult +{ + public Guid ProfileId { get; init; } +} +``` + +- [ ] **Step 2: Update CreateProfile.cs** + +In `Module/Profile/Features/Storefront/Profiles/Create/CreateProfile.cs`: + +Remove `using Shared.Application.Contracts.Profile;` + +- [ ] **Step 3: Delete old Shared contract** + +Delete `Shared/Application/Contracts/Profile/CreateUserProfileCommand.cs`. + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(profile): move CreateUserProfileCommand into CreateProfile feature" +``` + +--- + +## Task 13: Location — Move Queries into Handler Files + +**Files:** +- Update: `Module/Location/Features/Shared/Queries/CountryExistsByIsoHandler.cs` +- Update: `Module/Location/Features/Shared/Queries/StateExistsByIsoHandler.cs` +- Delete: `Shared/Application/Contracts/Location/CountryExistsByIsoQuery.cs` +- Delete: `Shared/Application/Contracts/Location/StateExistsByIsoQuery.cs` +- Delete: `Shared/Application/Contracts/Location/` (directory) + +- [ ] **Step 1: Add query record to CountryExistsByIsoHandler** + +In `Module/Location/Features/Shared/Queries/CountryExistsByIsoHandler.cs`: + +Add before the handler class: + +```csharp +public sealed record CountryExistsByIsoQuery(string IsoCode) : IQuery; +``` + +Remove `using Shared.Application.Contracts.Location;`. + +- [ ] **Step 2: Add query record to StateExistsByIsoHandler** + +In `Module/Location/Features/Shared/Queries/StateExistsByIsoHandler.cs`: + +Add before the handler class: + +```csharp +public sealed record StateExistsByIsoQuery(string CountryCode, string StateCode) : IQuery; +``` + +Remove `using Shared.Application.Contracts.Location;`. + +- [ ] **Step 3: Delete old Shared contracts and directory** + +```bash +rm service/Api/src/Shared/Application/Contracts/Location/CountryExistsByIsoQuery.cs +rm service/Api/src/Shared/Application/Contracts/Location/StateExistsByIsoQuery.cs +rmdir service/Api/src/Shared/Application/Contracts/Location/ +``` + +- [ ] **Step 4: Commit** + +```bash +git add -A +git commit -m "refactor(location): move query records into handler files, delete Contracts/" +``` + +--- + +## Task 14: Update All Consumer Using Statements + +This task updates every file that references the old `Shared.Application.Contracts.*` namespaces. Execute in order by module. + +- [ ] **Step 1: Update Inventory consumers (self-cleanup)** + +Update these 4 handler files — remove `using Shared.Application.Contracts.Inventory;`: +- `Module/Inventory/Features/Storefront/ConsumeCartStockReservations/ConsumeCartStockReservations.cs` +- `Module/Inventory/Features/Storefront/ReserveCartStock/ReserveCartStock.cs` +- `Module/Inventory/Features/Storefront/ReleaseCartStockReservations/ReleaseCartStockReservations.cs` +- `Module/Inventory/Features/Storefront/CheckVariantAvailability/CheckVariantAvailability.cs` + +- [ ] **Step 2: Update Ordering consumers** + +`Module/Ordering/.../Cart/Checkout/CreateOrderFromCart.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Catalog; +using Shared.Application.Contracts.Inventory; +using Shared.Application.Contracts.Payment; + +// Add: +using Module.Inventory.Features.Storefront.ConsumeCartStockReservations; +using Module.Payment.Features.Storefront.GetPaymentForCheckout; +using Module.Payment.Features.Storefront.MarkPaymentPaid; +``` + +`Module/Ordering/.../Cart/AddItem/AddToCart.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Inventory; + +// Add: +using Module.Inventory.Features.Storefront.ReserveCartStock; +``` + +`Module/Ordering/.../Cart/UpdateItemQuantity/UpdateCartItemQuantity.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Inventory; + +// Add: +using Module.Inventory.Features.Storefront.CheckVariantAvailability; +``` + +`Module/Ordering/.../GetCartForShipping/GetCartForShipping.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Catalog; +using Shared.Application.Contracts.Ordering; + +// (no new usings needed — Query/Response are in same namespace) +``` + +- [ ] **Step 3: Update Payment consumer** + +`Module/Payment/.../Payment/CreateIntent/CreatePaymentIntent.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Ordering; +using Shared.Application.Contracts.Inventory; + +// Add: +using Module.Inventory.Features.Storefront.ReserveCartStock; +using Module.Inventory.Features.Storefront.ReleaseCartStockReservations; +using Module.Ordering.Features.Storefront.GetCartForCheckout; +using Module.Ordering.Features.Storefront.AdvanceCheckoutState; +``` + +- [ ] **Step 4: Update Profile consumer** + +`Module/Profile/.../Addresses/Validators/Address.Validator.cs`: +```csharp +// Remove: +// (uses Shared.Application.Contracts.Location indirectly via sender.Send) + +// Add: +using Module.Location.Features.Shared.Queries; +``` + +- [ ] **Step 5: Update Identity consumers** + +`Module/Identity/.../Emails/Confirm/ConfirmEmail.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Profile; + +// Add: +using Module.Profile.Features.Storefront.Profiles.Create; +``` + +`Module/Identity/.../Auth/Login/External/Authenticate/ExternalAuthenticate.cs`: +```csharp +// Remove: +using Shared.Application.Contracts.Profile; + +// Add: +using Module.Profile.Features.Storefront.Profiles.Create; +``` + +- [ ] **Step 6: Build verification** + +Run: `dotnet build service/Api/src/Api` +Expected: PASS with 0 warnings + +- [ ] **Step 7: Commit** + +```bash +git add -A +git commit -m "refactor: update all consumer using statements for relocated contracts" +``` + +--- + +## Task 15: Update Test Files + +- [ ] **Step 1: Update CreateOrderFromCartTransactionTests.cs** + +Remove `using Shared.Application.Contracts.Catalog;` and `using Shared.Application.Contracts.Inventory;` and `using Shared.Application.Contracts.Payment;`. + +Add: +```csharp +using Module.Inventory.Features.Storefront.ConsumeCartStockReservations; +using Module.Payment.Features.Storefront.GetPaymentForCheckout; +using Module.Payment.Features.Storefront.MarkPaymentPaid; +``` + +Remove the `GetVariantDiscontinuedStatusesQuery` mock setup (line ~57). + +- [ ] **Step 2: Update CreateOrderFromCartTests.cs** + +Same using changes as Step 1. + +Remove `GetVariantDiscontinuedStatusesQuery` mock setups (lines ~62, ~243). + +- [ ] **Step 3: Update CreateOrderFromCartStockTests.cs** + +Same using changes as Step 1. + +Remove `GetVariantDiscontinuedStatusesQuery` mock setup (line ~54). + +- [ ] **Step 4: Update AddToCart test files** + +`AddToCartTests.cs`, `AddToCartDefaultsTests.cs`, `AddToCart.Reservation.Tests.cs`: + +Replace `using Shared.Application.Contracts.Inventory;` with `using Module.Inventory.Features.Storefront.ReserveCartStock;`. + +- [ ] **Step 5: Update UpdateCartItemQuantity.Tests.cs** + +Replace `using Shared.Application.Contracts.Inventory;` with `using Module.Inventory.Features.Storefront.CheckVariantAvailability;`. + +- [ ] **Step 6: Update CreatePaymentIntentTests.cs** + +Replace: +```csharp +using Shared.Application.Contracts.Ordering; +using Shared.Application.Contracts.Inventory; +``` +With: +```csharp +using Module.Ordering.Features.Storefront.GetCartForCheckout; +using Module.Ordering.Features.Storefront.AdvanceCheckoutState; +using Module.Inventory.Features.Storefront.ReserveCartStock; +using Module.Inventory.Features.Storefront.ReleaseCartStockReservations; +``` + +- [ ] **Step 7: Update remaining test files** + +`UpdateOrderStatusTests.cs`: Replace `using Shared.Application.Contracts.Inventory;` with `using Module.Inventory.Services.Abstractions;` + +`EventHandlerInvocationTests.cs`: Same as above. + +`CheckVariantAvailability.Tests.cs`: Replace with `using Module.Inventory.Features.Storefront.CheckVariantAvailability;` + +`CalculateShippingHandlerTests.cs`: Replace `using Shared.Application.Contracts.{Catalog,Ordering};` with `using Module.Ordering.Features.Storefront.GetCartForShipping;` + +`ExistsByIsoQueryTests.cs`: Replace with `using Module.Location.Features.Shared.Queries;` + +`ConfirmEmail.Tests.cs`, `ExternalAuthenticate.Tests.cs`, `ExternalAuthenticateProfileCreationTests.cs`: Replace `using Shared.Application.Contracts.Profile;` with `using Module.Profile.Features.Storefront.Profiles.Create;` + +- [ ] **Step 8: Build and test** + +Run: `dotnet build service/Api/src/Api` +Run: `dotnet test service/Api/tests/Module.UnitTests` +Expected: All PASS + +- [ ] **Step 9: Commit** + +```bash +git add -A +git commit -m "refactor: update test using statements for relocated contracts" +``` + +--- + +## Task 16: Final Cleanup and Verification + +- [ ] **Step 1: Delete remaining Shared Contracts directories** + +```bash +rmdir service/Api/src/Shared/Application/Contracts/Inventory/ 2>/dev/null || true +rmdir service/Api/src/Shared/Application/Contracts/Ordering/ 2>/dev/null || true +rmdir service/Api/src/Shared/Application/Contracts/Payment/ 2>/dev/null || true +rmdir service/Api/src/Shared/Application/Contracts/Profile/ 2>/dev/null || true +rmdir service/Api/src/Shared/Application/Contracts/Location/ 2>/dev/null || true +rmdir service/Api/src/Shared/Application/Contracts/Catalog/ 2>/dev/null || true +``` + +- [ ] **Step 2: Update cross-module baseline** + +In `scripts/check-cross-module-refs.sh`, update `EXPECTED_BASELINE` to reflect the new count (run the script first to see the actual count). + +- [ ] **Step 3: Full build verification** + +Run: `dotnet build service/Api/src/Api` +Expected: 0 warnings, 0 errors + +- [ ] **Step 4: Full test verification** + +Run: `dotnet test service/Api/tests/Module.UnitTests` +Run: `dotnet test service/Api/tests/Shared.UnitTests` +Expected: All PASS + +- [ ] **Step 5: Cross-module check** + +Run: `bash scripts/check-cross-module-refs.sh` +Expected: Baseline updated, no new violations + +- [ ] **Step 6: Commit** + +```bash +git add -A +git commit -m "chore: cleanup empty Shared/Contracts directories, update cross-module baseline" +``` diff --git a/AGENTS.md b/AGENTS.md index 89d602068..ff2245f43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,10 +8,13 @@ domain boundaries, principles, quality baselines. ## Non-Negotiable Rules 1. **Result objects, not exceptions** — all domain operations return `Result` or `Result`. Exceptions only for unrecoverable infrastructure failures. -2. **Modules must not reference each other** — all 9 business modules (Catalog, Identity, Inventory, Location, Ordering, Payment, Profile, Shipping, Dashboard) live in one `Module` assembly and must not cross-reference. Communication via MediatR `ISender` only. Existing violations (39 `using Module.X.Domain...` references) being removed. +2. **Modules share one assembly and may reference each other; behavior may use MediatR `ISender` or direct calls** — all 9 business modules (Catalog, Identity, Inventory, Location, Ordering, Payment, Profile, Shipping, Dashboard) live in one `Module` assembly. Cross-module `using` statements, EF Core FK relationships, navigations, and direct service calls are all permitted (no whitelist, no drift check — removed 2026-08-16). For behavior, prefer MediatR `ISender` when dispatching work to another module so it flows through the pipeline (validation, logging, transaction); call services or navigate relationships directly when that fits the feature slice. + - **TODO (replace the ISender convention):** the `ISender`-for-behavior convention is retained for now but is itself under review. Proposal options to replace it (see `brainstorming` skill): (a) keep `ISender` as-is, (b) direct cross-module service calls where the type is already referenced, (c) a module gateway/facade layer, (d) splitting modules into separate assemblies with explicit ProjectReferences. Run `/brainstorming` before choosing. + - **Replacement candidates (audited 2026-08-16):** navigations fit where `Order` is the hub — `GetPaymentForCheckout`/`GetCartForCheckout`/`GetCartForShipping` → load `Order` + `LineItems`/`PaymentCaptures` via `.Include`/direct nav; `MarkPaymentPaid` → `payment.Complete()` on the nav-loaded capture; `RecordOrderPaymentState` → `order.MarkPayment{Completed|Failed|Processing}`; `AdvanceCheckoutState`/`RegressCheckoutState` → `order.AdvanceCheckoutState()`/`Regress*`. Direct service calls fit where a foreign aggregate is created: `CreateShipment` (→ Shipping service), `CreateUserProfile` (→ Customer profile service). Keep `ISender` (pipeline/retry/transaction value): `VoidOrderPayments`, `CompleteCheckoutForPayment`. 3. **Vertical slice feature files** — every C# feature action is `static partial class` split across files in `Features/{Admin|Storefront}/{Feature}/{Action}/`, each with Handler, Request, Response, Endpoint, Validator. Subdirectory always `Storefront` (not `Store`). Read-only queries may omit Request/Validator files. 4. **Warnings-as-errors** — `TreatWarningsAsErrors=true` globally. Any warning fails build. 5. **Forward-only dependency** — `Shared` depends on nothing within `service/`. `Module` depends only on `Shared`. `Api` composes both. +6. **NO git stash / worktree / revert / restore / checkout -- without human permission** — never run `git stash`, `git checkout -- `, `git restore`, `git revert`, `git reset --hard`, or any command that moves/rewrites/loses working-tree changes, unless the human explicitly asked for it and you got an explicit "yes" to run that specific command. If your tooling or hooks auto-stash or reset the working tree, STOP and report it immediately — do not silently continue. Recover lost changes only after the human confirms. Uncommitted work is precious and irreplaceable. ## Repository Map @@ -25,12 +28,11 @@ domain boundaries, principles, quality baselines. - `docs/codebase/CONVENTIONS.md` — coding conventions - `docs/codebase/TESTING.md` — testing strategy - `docs/codebase/PROCESS.md` — doc-gardening, GC, feedback encoding, escalation boundaries -- `docs/failures/` — failure memory: cross-module isolation violations, known incidents +- `docs/failures/` — failure memory: known incidents - `plan/` — implementation plans (currently consolidating README docs across modules) - `guide/code-commenting/CommentingRules.xml` — comment convention rules - `Directory.Packages.props` — central NuGet package versions - `scripts/check-feature-conventions.sh` — feature file AC-001/002/003/005 drift checks -- `scripts/check-cross-module-refs.sh` — cross-module namespace reference drift check ## Tech Stack @@ -54,7 +56,6 @@ cd app/Store && pnpm run lint && pnpm run test:unit # Store SPA verification cd service/Embedding && uv run ruff check . && uv run pytest # Python verification cd benchmarks && uv run ruff check src/ && uv run pytest --ignore=src/tests/integration/ # Benchmark verification bash scripts/check-feature-conventions.sh # Feature file completeness check -bash scripts/check-cross-module-refs.sh # Cross-module reference drift check ``` ## Code Organization @@ -74,7 +75,7 @@ bash scripts/check-cross-module-refs.sh # Cross-module reference d - Dev JWT secret for non-Development environments rejected by `JwtSettingsValidator` (commit `770b6a06`); dev secrets in `dotnet user-secrets` (id `resys.shop.api`), bootstrapped via `service/Api/scripts/setup-dev-secrets.sh` - `app/ReSys.Admin/` legacy admin SPA (npm, older deps) — use `app/Admin/` (pnpm) instead -- `ValidateVerticalSliceIsolation` build target Condition="true" but emits `` (not ``), so cross-module references don't fail build — see `docs/codebase/CONCERNS.md` for 39 known violations +- `ValidateVerticalSliceIsolation` build target emits `` for module ProjectReferences; cross-module references are permitted, so this only guards against future module-split ProjectReference cycles - CI/CD partial — `.github/workflows/ci.yml` runs build, unit tests, lint on PR/push for .NET, both Vue SPAs, Embedding service, Benchmarks. Integration tests (Testcontainers) and deployment not yet automated - `service/Embedding/Dockerfile` exists for Python sidecar; no Dockerfiles for .NET API or Vue SPAs (Aspire manages containers for local dev) - `Embedding/build/lib/` contains stale build artifacts — should be gitignored diff --git a/CLAUDE.md b/CLAUDE.md index abe1fc833..8e380fbea 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ cd app/Admin && pnpm install && pnpm run dev # Dev server (po cd app/Admin && pnpm run lint # Oxlint + ESLint cd app/Admin && pnpm run test:unit # Vitest unit tests -# Store SPA (Vue 3 + Nuxt UI) +# Store SPA (Vue 3 + PrimeVue 5) cd app/Store && pnpm install && pnpm run dev # Dev server (port 5174) cd app/Store && pnpm run lint && pnpm run test:unit @@ -35,7 +35,6 @@ dotnet run --project infra/Aspire/src/ReSys.AppHost # Drift checks bash scripts/check-feature-conventions.sh # Feature file completeness (AC-001 through AC-005) -bash scripts/check-cross-module-refs.sh # Cross-module namespace reference count (baseline: 32) ``` ## Architecture @@ -48,7 +47,7 @@ HTTP Request → Carter endpoint → FluentValidation → MediatR pipeline (Logg → Command/Query Handler → Domain logic + EF Core / external services → Mapster-mapped DTO response ``` -**Assembly dependency chain** (forward-only): `Api` → `Module` + `Shared` + `Migrations`; `Module` → `Shared`; `Shared` → `ServiceDefaults`. Modules must not reference each other — cross-module communication use MediatR `ISender.Send(new OtherModule.Command(...))` only. ~32 known violations tracked by `scripts/check-cross-module-refs.sh` (decreasing over time). +**Assembly dependency chain** (forward-only): `Api` → `Module` + `Shared` + `Migrations`; `Module` → `Shared`; `Shared` → `ServiceDefaults`. Modules share one `Module` assembly and may reference each other's types; for behavior, cross-module work flows through MediatR `ISender.Send(new OtherModule.Command(...))` so it passes the pipeline. **Every feature** is `static partial class` split across files in one directory under `Features/{Admin|Storefront}/{Domain}/{Action}/`: - `{Action}.cs` — handler (`ICommandHandler` or `IQueryHandler`) @@ -75,7 +74,7 @@ HTTP Request → Carter endpoint → FluentValidation → MediatR pipeline (Logg ### TypeScript (Vue SPAs) - **Admin:** PrimeVue + Sakai theme + Tailwind CSS 4. Path alias `@/` → `./src/`. Form validation with Vee-Validate + Zod. Auto-imports via `unplugin-auto-import`. -- **Store:** Nuxt UI + Tailwind CSS 4. Same path alias pattern. +- **Store:** PrimeVue 5 + Aura theme + Tailwind CSS 4. Same path alias pattern. - **Linting:** Dual linter — Oxlint + ESLint. Formatting via Oxfmt (no Prettier). `noUncheckedIndexedAccess: true` in both SPAs. - **Tests:** Vitest + jsdom, tests co-located in `src/**/__tests__/`. @@ -99,7 +98,7 @@ Follow `guide/code-commenting/CommentingRules.xml`. Use `TODO`, `FIXME`, `HACK`, - **`TreatWarningsAsErrors=true`** — any compiler warning fails the build. Includes unused variables and nullable reference warnings. Always run `dotnet build` before committing C# changes. - **InMemory DB ≠ real PostgreSQL** — InMemory doesn't support pgvector, transaction isolation levels, or sequences. Tests passing with InMemory may fail against real PostgreSQL. Add integration tests for DB-specific features. - **Feature subdirectory naming:** Use `Storefront`, not `Store`, for new features. Identity, Location, and Profile still use `Store` — don't replicate in new code. -- **Cross-module references:** When adding features, communicate across modules via `ISender`, never with direct `using Module.X.Domain...` references. Run `bash scripts/check-cross-module-refs.sh` after changes that touch multiple modules. +- **Cross-module references:** Cross-module type references, direct service calls, and navigation/relationship access are all permitted (modules share one assembly). Use MediatR `ISender` when a command/query should flow through the pipeline (validation, logging, transaction); otherwise call the service or navigate the relationship directly. - **Dashboard module:** Exists but NOT registered in `Program.cs`. Don't add new Dashboard features without registering it first. - **Dev secrets:** Live in `dotnet user-secrets` (id: `resys.shop.api`), bootstrapped via `service/Api/scripts/setup-dev-secrets.sh`. Dev JWT secret rejected for non-Development environments. - **Legacy code:** `app/legacy/` directories exist but deprecated and gitignored. Use `app/Admin/` (pnpm) for all admin UI work. diff --git a/Directory.Build.targets b/Directory.Build.targets index c88313433..91cba5d3a 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -38,10 +38,10 @@ Condition="'@(ForbiddenRef)' != ''" /> - + diff --git a/Directory.Packages.props b/Directory.Packages.props index 77d4a8c17..b02f5e897 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -81,7 +81,7 @@ - + diff --git a/README.md b/README.md index f9a10461f..7ddecc7be 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ The API uses the standard .NET configuration pipeline (`appsettings.json` + envi │ └── Embedding/ # Python FastAPI ML sidecar (Fashion-CLIP) ├── app/ │ ├── Admin/ # Vue 3 admin SPA (PrimeVue + Tailwind CSS) -│ └── Store/ # Vue 3 storefront SPA (Nuxt UI + Tailwind CSS) +│ └── Store/ # Vue 3 storefront SPA (PrimeVue 5 + Tailwind CSS) ├── infra/Aspire/ # .NET Aspire orchestration (AppHost + ServiceDefaults) ├── ApiTests/ # HTTP test files (.http) ├── docs/codebase/ # Architecture, stack, conventions, concerns @@ -148,7 +148,7 @@ The API uses the standard .NET configuration pipeline (`appsettings.json` + envi | **Payments** | Stripe.net (planned), BogusGateway (dev) | | **Observability** | OpenTelemetry (traces, metrics, logs), health checks | | **Admin SPA** | Vue 3, PrimeVue 4, Pinia, Tailwind CSS 4, Vite 8 | -| **Store SPA** | Vue 3, Nuxt UI 4, Pinia, Tailwind CSS 4, Vite 8 | +| **Store SPA** | Vue 3, PrimeVue 5 (Aura), Pinia, Tailwind CSS 4, Vite 8 | | **ML sidecar** | Python 3.14, FastAPI, PyTorch, open-clip-torch | | **Orchestration** | .NET Aspire 13.4 | | **Testing** | xUnit v3, Testcontainers, Respawn, Vitest, pytest | diff --git a/ReSys.Shop.slnx b/ReSys.Shop.slnx index a569e40b2..28a802814 100644 --- a/ReSys.Shop.slnx +++ b/ReSys.Shop.slnx @@ -14,7 +14,6 @@ - diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..3d5984967 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,30 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 0.x | :white_check_mark: (pre-release) | + +## Reporting a Vulnerability + +ReSys.Shop is currently in pre-release development. If you discover a security vulnerability, please report it via email to the maintainers rather than opening a public issue. + +**Disclosure process:** +1. Email the details to the project maintainers +2. Include a description of the vulnerability, steps to reproduce, and affected versions +3. Allow reasonable time for the issue to be addressed before public disclosure +4. The maintainers will acknowledge receipt within 5 business days and provide an estimated timeline + +## Security Update Process + +Security patches are released as part of the regular release cycle. Critical vulnerabilities may warrant an out-of-cycle patch. + +## Known Security Considerations + +- JWT secrets for non-Development environments must be provisioned via user-secrets or environment variables. The `appsettings.Development.json` file contains development-only keys. +- CORS allows credentials in the Development environment only. Ensure production CORS is locked down to the deployed origin. +- File upload malware scanning is disabled by default (`MalwareScanner.Enabled = false`). Enable ClamAV integration in production environments. +- Anti-forgery protection is enabled (`AntiForgery.IsEnabled = true` with `X-CSRF-TOKEN` header). Ensure it remains enabled in production. +- Rate limiting is configured for auth endpoints only. Consider adding policies for cart operations and API search endpoints before production deployment. +- The `.env.template` files contain `REPLACE_ME_*` placeholders — never commit real secrets to this repository. diff --git a/_thesis/chapters/part2/chapter2/01-system-overview.typ b/_thesis/chapters/part2/chapter2/01-system-overview.typ index e9f55a94e..fe1f14d1d 100644 --- a/_thesis/chapters/part2/chapter2/01-system-overview.typ +++ b/_thesis/chapters/part2/chapter2/01-system-overview.typ @@ -172,8 +172,8 @@ The API uses *Carter* modules for clean endpoint registration: [ProductsModule (Admin)], [ - `/api/catalog/products` \ - `/api/catalog/products/{id}/images` + `/api/admin/catalog/products` \ + `/api/admin/catalog/products/{id}/images` ], [CRUD \ CRUD], ), diff --git a/_thesis/chapters/part2/chapter2/06-api-design.typ b/_thesis/chapters/part2/chapter2/06-api-design.typ index 41251ea53..0509c3994 100644 --- a/_thesis/chapters/part2/chapter2/06-api-design.typ +++ b/_thesis/chapters/part2/chapter2/06-api-design.typ @@ -56,7 +56,7 @@ public class ProductsModule : ICarterModule async ([FromBody] CreateProduct.Request request, ISender sender) => { var result = await sender.Send(new CreateProduct.Command(request)); - return result.ToApiCreatedResponse(x => $"/api/catalog/products/{x.Id}"); + return result.ToApiCreatedResponse(x => $"/api/admin/catalog/products/{x.Id}"); }) .RequireAccessPermission(FeaturePermissions.Admin.Catalog.Product.Create); diff --git a/_thesis/diagrams/sequences/sources/admin/sq-0012-inventory.puml b/_thesis/diagrams/sequences/sources/admin/sq-0012-inventory.puml index 47d99b198..f8db7c241 100644 --- a/_thesis/diagrams/sequences/sources/admin/sq-0012-inventory.puml +++ b/_thesis/diagrams/sequences/sources/admin/sq-0012-inventory.puml @@ -12,7 +12,7 @@ database "PostgreSQL" as DB <> ' ─── View Stock ────────────────────────────────────────────── Admin -> Portal: View Inventory (SKU-123) activate Portal - Portal -> API: GET /api/inventory/SKU-123 + Portal -> API: GET /api/admin/inventory/SKU-123 activate API API -> DB: Query StockItems + InventoryUnits activate DB @@ -31,7 +31,7 @@ deactivate Portal ' ─── Adjust Stock ──────────────────────────────────────────── Admin -> Portal: Adjust Stock (+10) activate Portal - Portal -> API: POST /api/inventory/adjust + Portal -> API: POST /api/admin/inventory/adjust activate API API -> DB: Get StockItem diff --git a/_thesis/diagrams/sequences/sources/system/sq-0020-payment-integration.puml b/_thesis/diagrams/sequences/sources/system/sq-0020-payment-integration.puml index bf99292fd..d079d2653 100644 --- a/_thesis/diagrams/sequences/sources/system/sq-0020-payment-integration.puml +++ b/_thesis/diagrams/sequences/sources/system/sq-0020-payment-integration.puml @@ -14,7 +14,7 @@ queue "Message Bus" as Bus <> ' ─── Step 1: Intent Creation ───────────────────────────────── User -> Frontend: Click "Pay Now" activate Frontend - Frontend -> API: POST /api/payments/intent\n{orderId, amount} + Frontend -> API: POST /api/admin/payments/intent\n{orderId, amount} activate API API -> Stripe: PaymentIntent.Create(Amount, Currency)\nMetadata: OrderId activate Stripe diff --git a/app/Admin/src/features/auth/services/__tests__/authApi.spec.ts b/app/Admin/src/features/auth/services/__tests__/authApi.spec.ts index dd1d40515..7e09cd090 100644 --- a/app/Admin/src/features/auth/services/__tests__/authApi.spec.ts +++ b/app/Admin/src/features/auth/services/__tests__/authApi.spec.ts @@ -29,7 +29,7 @@ describe('login', () => { const result = await login({ credential: 'admin', password: 'pass' }) - expect(mockPost).toHaveBeenCalledWith('api/store/identity/auth/login/password', { + expect(mockPost).toHaveBeenCalledWith('/api/storefront/identity/auth/login/password', { credential: 'admin', password: 'pass', }) @@ -64,7 +64,7 @@ describe('logout', () => { }) await logout({ revokeAll: true }) - expect(mockPost).toHaveBeenCalledWith('api/store/identity/auth/logout', { revokeAll: true }) + expect(mockPost).toHaveBeenCalledWith('/api/storefront/identity/auth/logout', { revokeAll: true }) }) it('calls POST logout with empty body when no args', async () => { @@ -78,7 +78,7 @@ describe('logout', () => { }) await logout() - expect(mockPost).toHaveBeenCalledWith('api/store/identity/auth/logout', undefined) + expect(mockPost).toHaveBeenCalledWith('/api/storefront/identity/auth/logout', undefined) }) }) @@ -94,7 +94,7 @@ describe('getSession', () => { }) const result = await getSession() - expect(mockGet).toHaveBeenCalledWith('api/store/identity/auth/sessions') + expect(mockGet).toHaveBeenCalledWith('/api/storefront/identity/auth/sessions') expect(result.isSuccess).toBe(true) expect(result.value.roles).toEqual(['Admin']) }) @@ -105,7 +105,7 @@ describe('forgotPassword', () => { mockPost.mockResolvedValue(undefined) await forgotPassword({ email: 'user@example.com' }) - expect(mockPost).toHaveBeenCalledWith('api/store/identity/passwords/forgot', { + expect(mockPost).toHaveBeenCalledWith('/api/storefront/identity/passwords/forgot', { email: 'user@example.com', }) }) @@ -129,7 +129,7 @@ describe('resetPassword', () => { newPassword: 'newpass123', }) - expect(mockPost).toHaveBeenCalledWith('api/store/identity/passwords/reset', { + expect(mockPost).toHaveBeenCalledWith('/api/storefront/identity/passwords/reset', { email: 'u@e.com', userId: 'uid', token: 'tok', diff --git a/app/Admin/src/features/auth/services/authApi.ts b/app/Admin/src/features/auth/services/authApi.ts index 3b0bc8532..2a275a1f1 100644 --- a/app/Admin/src/features/auth/services/authApi.ts +++ b/app/Admin/src/features/auth/services/authApi.ts @@ -9,8 +9,8 @@ import type { SessionInfo, } from '../types/auth' -const AUTH_BASE = 'api/store/identity/auth' -const PASSWORD_BASE = 'api/store/identity/passwords' +const AUTH_BASE = '/api/storefront/identity/auth' +const PASSWORD_BASE = '/api/storefront/identity/passwords' export function login(request: LoginRequest): Promise> { return post>(`${AUTH_BASE}/login/password`, request) diff --git a/app/Admin/src/features/catalog/__tests__/composables/useProductOptions.spec.ts b/app/Admin/src/features/catalog/__tests__/composables/useProductOptions.spec.ts index 3be362489..f92f7f9b0 100644 --- a/app/Admin/src/features/catalog/__tests__/composables/useProductOptions.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/composables/useProductOptions.spec.ts @@ -28,7 +28,7 @@ describe('useProductOptions', () => { const { options, loadInitial } = useProductOptions() await loadInitial() expect(mockGetProducts).toHaveBeenCalledWith( - expect.objectContaining({ search: '', page: 1, pageSize: 25, sortBy: 'name' }), + expect.objectContaining({ search: '', pageNumber: 1, pageSize: 25, sort: ['name:asc'] }), ) expect(options.value).toHaveLength(1) }) @@ -41,7 +41,7 @@ describe('useProductOptions', () => { vi.advanceTimersByTime(300) await vi.advanceTimersByTimeAsync(0) expect(mockGetProducts).toHaveBeenCalledWith( - expect.objectContaining({ search: 'shirt', page: 1, pageSize: 25 }), + expect.objectContaining({ search: 'shirt', pageNumber: 1, pageSize: 25 }), ) expect(options.value).toHaveLength(1) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/catalogDashboardApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/catalogDashboardApi.spec.ts index 0fd50dbb8..aed59ae3f 100644 --- a/app/Admin/src/features/catalog/__tests__/services/catalogDashboardApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/catalogDashboardApi.spec.ts @@ -33,6 +33,6 @@ describe('CatalogDashboardApi.getCatalogDashboard', () => { metadata: null, }) await CatalogDashboardApi.getCatalogDashboard() - expect(mockGet).toHaveBeenCalledWith('api/catalog/dashboard') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/dashboard') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/imageEmbeddingApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/imageEmbeddingApi.spec.ts index 679f4158f..6329b3005 100644 --- a/app/Admin/src/features/catalog/__tests__/services/imageEmbeddingApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/imageEmbeddingApi.spec.ts @@ -42,7 +42,7 @@ describe('ImageEmbeddingApi.create', () => { const req = { variantImageId: 'img-1', modelName: 'openclip-vit-b-32' } mockPost.mockResolvedValue(embeddingResult) await ImageEmbeddingApi.create(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/variant-image-embeddings', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/variant-image-embeddings', req) }) }) @@ -51,7 +51,7 @@ describe('ImageEmbeddingApi.regenerate', () => { const req = { variantImageId: 'img-1', modelName: 'openclip-vit-b-32', modelVersion: 'v1' } mockPut.mockResolvedValue(embeddingResult) await ImageEmbeddingApi.regenerate(req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/variant-image-embeddings/regenerate', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/variant-image-embeddings/regenerate', req) }) }) @@ -60,7 +60,7 @@ describe('ImageEmbeddingApi.get', () => { const result = { value: embeddingResult.value, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null } mockGet.mockResolvedValue(result) await ImageEmbeddingApi.get('img-1') - expect(mockGet).toHaveBeenCalledWith('api/catalog/variant-image-embeddings/img-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/variant-image-embeddings/img-1') }) }) @@ -68,6 +68,6 @@ describe('ImageEmbeddingApi.deleteEmbedding', () => { it('calls DELETE with variantImageId path', async () => { mockDel.mockResolvedValue({ isSuccess: true, statusCode: 200, message: 'Deleted', errors: [], metadata: null }) await ImageEmbeddingApi.deleteEmbedding('img-1') - expect(mockDel).toHaveBeenCalledWith('api/catalog/variant-image-embeddings/img-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/variant-image-embeddings/img-1') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/optionTypeApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/optionTypeApi.spec.ts index b2649e54a..1f398a10e 100644 --- a/app/Admin/src/features/catalog/__tests__/services/optionTypeApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/optionTypeApi.spec.ts @@ -40,11 +40,11 @@ describe('OptionTypeApi.getOptionTypes', () => { metadata: null, }) - await OptionTypeApi.getOptionTypes({ filterable: true, page: 1, pageSize: 10 }) + await OptionTypeApi.getOptionTypes({ filter: 'filterable=true', pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/option-types', - { filter: 'filterable=true', search: null, sort: null, pageNumber: 1, pageSize: 10 }, + '/api/admin/catalog/option-types', + { filter: 'filterable=true', pageNumber: 1, pageSize: 10 }, expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) @@ -55,7 +55,7 @@ describe('OptionTypeApi.getOptionType', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'Size' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionTypeApi.getOptionType('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/catalog/option-types/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/option-types/abc-123') }) }) @@ -65,7 +65,7 @@ describe('OptionTypeApi.createOptionType', () => { mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await OptionTypeApi.createOptionType(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/option-types', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/option-types', req) }) }) @@ -75,7 +75,7 @@ describe('OptionTypeApi.updateOptionType', () => { mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionTypeApi.updateOptionType('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/option-types/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/option-types/abc-123', req) }) }) @@ -84,6 +84,6 @@ describe('OptionTypeApi.deleteOptionType', () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Size' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionTypeApi.deleteOptionType('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/catalog/option-types/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/option-types/abc-123') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/optionValueApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/optionValueApi.spec.ts index d05a4aba3..35528f24d 100644 --- a/app/Admin/src/features/catalog/__tests__/services/optionValueApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/optionValueApi.spec.ts @@ -40,10 +40,10 @@ describe('OptionValueApi.getOptionValues', () => { metadata: null, }) - await OptionValueApi.getOptionValues({ optionTypeId: 'abc-123' }) + await OptionValueApi.getOptionValues({ filter: 'optionTypeId=abc-123' }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/option-values', + '/api/admin/catalog/option-values', expect.objectContaining({ filter: 'optionTypeId=abc-123' }), expect.any(Object), ) @@ -55,7 +55,7 @@ describe('OptionValueApi.getOptionValue', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'Medium' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionValueApi.getOptionValue('xyz-456') - expect(mockGet).toHaveBeenCalledWith('api/catalog/option-values/xyz-456') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/option-values/xyz-456') }) }) @@ -65,7 +65,7 @@ describe('OptionValueApi.createOptionValue', () => { mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await OptionValueApi.createOptionValue(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/option-values', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/option-values', req) }) }) @@ -75,7 +75,7 @@ describe('OptionValueApi.updateOptionValue', () => { mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionValueApi.updateOptionValue('xyz-456', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/option-values/xyz-456', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/option-values/xyz-456', req) }) }) @@ -84,6 +84,6 @@ describe('OptionValueApi.deleteOptionValue', () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Medium' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OptionValueApi.deleteOptionValue('xyz-456') - expect(mockDel).toHaveBeenCalledWith('api/catalog/option-values/xyz-456') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/option-values/xyz-456') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/productApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/productApi.spec.ts index 7977fc77e..bc0a1e1c5 100644 --- a/app/Admin/src/features/catalog/__tests__/services/productApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/productApi.spec.ts @@ -35,11 +35,11 @@ describe('ProductApi.getProducts', () => { isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null, }) - await ProductApi.getProducts({ status: 'Active', page: 1, pageSize: 10 }) + await ProductApi.getProducts({ filter: 'status=Active', pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/products', - { filter: 'status=Active', search: null, sort: null, pageNumber: 1, pageSize: 10 }, + '/api/admin/catalog/products', + { filter: 'status=Active', pageNumber: 1, pageSize: 10 }, expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) @@ -49,7 +49,7 @@ describe('ProductApi.getProduct', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'Shirt' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductApi.getProduct('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/catalog/products/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/products/abc-123') }) }) @@ -58,7 +58,7 @@ describe('ProductApi.createProduct', () => { const req = { name: 'Shirt', slug: 'shirt', description: null, metaTitle: null, metaDescription: null, metaKeywords: null, availableOn: null, discontinueOn: null, trackInventory: true, styleCode: null, seasonName: null, materialComposition: null, careInstructions: null, fitNotes: null, department: null, genderTarget: null } mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await ProductApi.createProduct(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/products', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/products', req) }) }) @@ -67,7 +67,7 @@ describe('ProductApi.updateProduct', () => { const req = { name: 'Shirt', slug: 'shirt', description: null, metaTitle: null, metaDescription: null, metaKeywords: null, availableOn: null, discontinueOn: null, trackInventory: false, styleCode: null, seasonName: null, materialComposition: null, careInstructions: null, fitNotes: null, department: null, genderTarget: null } mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductApi.updateProduct('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/products/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/products/abc-123', req) }) }) @@ -75,7 +75,7 @@ describe('ProductApi.deleteProduct', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Shirt' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductApi.deleteProduct('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/catalog/products/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/products/abc-123') }) }) @@ -83,7 +83,7 @@ describe('ProductApi.activateProduct', () => { it('calls PATCH with activate URL', async () => { mockPatch.mockResolvedValue({ value: { id: '1', name: 'Shirt' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductApi.activateProduct('abc-123') - expect(mockPatch).toHaveBeenCalledWith('api/catalog/products/abc-123/activate') + expect(mockPatch).toHaveBeenCalledWith('/api/admin/catalog/products/abc-123/activate') }) }) @@ -91,6 +91,6 @@ describe('ProductApi.discontinueProduct', () => { it('calls PATCH with discontinue URL', async () => { mockPatch.mockResolvedValue({ value: { id: '1', name: 'Shirt' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductApi.discontinueProduct('abc-123') - expect(mockPatch).toHaveBeenCalledWith('api/catalog/products/abc-123/discontinue') + expect(mockPatch).toHaveBeenCalledWith('/api/admin/catalog/products/abc-123/discontinue') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/productClassificationApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/productClassificationApi.spec.ts index e4cde42a2..c286a741b 100644 --- a/app/Admin/src/features/catalog/__tests__/services/productClassificationApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/productClassificationApi.spec.ts @@ -39,7 +39,7 @@ describe('ProductClassificationApi.getClassifications', () => { await ProductClassificationApi.getClassifications('abc-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/product-classifications?productId=abc-123', + '/api/admin/catalog/product-classifications?productId=abc-123', {}, ) }) @@ -50,7 +50,7 @@ describe('ProductClassificationApi.syncClassifications', () => { const req = { productId: 'prod-1', items: [{ taxonId: 'tx-1', position: 0 }] } mockPut.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductClassificationApi.syncClassifications(req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/product-classifications/sync', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/product-classifications/sync', req) }) }) @@ -59,7 +59,7 @@ describe('ProductClassificationApi.assignClassifications', () => { const req = { productId: 'prod-1', items: [{ taxonId: 'tx-1', position: 0 }] } mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductClassificationApi.assignClassifications(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/product-classifications/assign', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/product-classifications/assign', req) }) }) @@ -68,6 +68,6 @@ describe('ProductClassificationApi.revokeClassifications', () => { const req = { productId: 'prod-1', items: [{ taxonId: 'tx-1', position: 0 }] } mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductClassificationApi.revokeClassifications(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/product-classifications/revoke', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/product-classifications/revoke', req) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/productOptionTypeApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/productOptionTypeApi.spec.ts index c943d5c20..18a799019 100644 --- a/app/Admin/src/features/catalog/__tests__/services/productOptionTypeApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/productOptionTypeApi.spec.ts @@ -39,7 +39,7 @@ describe('ProductOptionTypeApi.getOptionTypes', () => { await ProductOptionTypeApi.getOptionTypes('abc-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/product-option-types?productId=abc-123', + '/api/admin/catalog/product-option-types?productId=abc-123', {}, ) }) @@ -50,7 +50,7 @@ describe('ProductOptionTypeApi.syncOptionTypes', () => { const req = { productId: 'prod-1', items: [{ optionTypeId: 'ot-1', position: 0 }] } mockPut.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductOptionTypeApi.syncOptionTypes(req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/product-option-types/sync', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/product-option-types/sync', req) }) }) @@ -59,7 +59,7 @@ describe('ProductOptionTypeApi.assignOptionTypes', () => { const req = { productId: 'prod-1', items: [{ optionTypeId: 'ot-1', position: 0 }] } mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductOptionTypeApi.assignOptionTypes(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/product-option-types/assign', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/product-option-types/assign', req) }) }) @@ -68,6 +68,6 @@ describe('ProductOptionTypeApi.revokeOptionTypes', () => { const req = { productId: 'prod-1', items: [{ optionTypeId: 'ot-1', position: 0 }] } mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await ProductOptionTypeApi.revokeOptionTypes(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/product-option-types/revoke', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/product-option-types/revoke', req) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/taxonApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/taxonApi.spec.ts index 07a8b688f..f51971324 100644 --- a/app/Admin/src/features/catalog/__tests__/services/taxonApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/taxonApi.spec.ts @@ -36,10 +36,10 @@ describe('TaxonApi.getTaxons', () => { isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null, }) - await TaxonApi.getTaxons({ taxonomyId: 'abc-123' }) + await TaxonApi.getTaxons({ filter: 'taxonomyId=abc-123' }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxons', + '/api/admin/catalog/taxons', expect.objectContaining({ filter: 'taxonomyId=abc-123' }), expect.any(Object), ) @@ -50,7 +50,7 @@ describe('TaxonApi.getTaxon', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'Shoes' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonApi.getTaxon('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/catalog/taxons/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/taxons/abc-123') }) }) @@ -61,9 +61,9 @@ describe('TaxonApi.getList', () => { page: 1, pageSize: 20, totalCount: 0, totalPages: 0, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null, }) - await TaxonApi.getList('abc-123', { page: 1, pageSize: 10 }) + await TaxonApi.getList('abc-123', { pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxons/list?taxonomyId=abc-123', + '/api/admin/catalog/taxons/list?taxonomyId=abc-123', expect.objectContaining({ pageNumber: 1, pageSize: 10 }), expect.any(Object), ) @@ -80,7 +80,7 @@ describe('TaxonApi.createTaxon', () => { } mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await TaxonApi.createTaxon(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/taxons', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/taxons', req) }) }) @@ -94,7 +94,7 @@ describe('TaxonApi.updateTaxon', () => { } mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonApi.updateTaxon('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/taxons/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/taxons/abc-123', req) }) }) @@ -102,7 +102,7 @@ describe('TaxonApi.deleteTaxon', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Shoes' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonApi.deleteTaxon('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/catalog/taxons/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/taxons/abc-123') }) }) @@ -110,7 +110,7 @@ describe('TaxonApi.restoreTaxon', () => { it('calls PATCH with restore URL and no body', async () => { mockPatch.mockResolvedValue({ value: { id: '1', name: 'Shoes' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonApi.restoreTaxon('abc-123') - expect(mockPatch).toHaveBeenCalledWith('api/catalog/taxons/abc-123/restore') + expect(mockPatch).toHaveBeenCalledWith('/api/admin/catalog/taxons/abc-123/restore') }) }) @@ -124,6 +124,6 @@ describe('TaxonApi.repositionTaxon', () => { } mockPost.mockResolvedValue({ value: { id: '1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonApi.repositionTaxon('abc-123', req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/taxons/abc-123/reposition', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/taxons/abc-123/reposition', req) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/taxonRuleApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/taxonRuleApi.spec.ts index 675f6f668..749323956 100644 --- a/app/Admin/src/features/catalog/__tests__/services/taxonRuleApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/taxonRuleApi.spec.ts @@ -38,8 +38,8 @@ describe('TaxonRuleApi.getRules', () => { await TaxonRuleApi.getRules('taxon-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxon-rules?taxonId=taxon-123', - expect.objectContaining({ filter: 'taxonId=taxon-123' }), + '/api/admin/catalog/taxon-rules?taxonId=taxon-123', + {}, ) }) }) @@ -49,7 +49,7 @@ describe('TaxonRuleApi.createRule', () => { const req = { taxonId: 'taxon-123', type: 'product_name', matchPolicy: 'contains', value: 'Nike' } mockPost.mockResolvedValue({ value: { id: '1', taxonId: 'taxon-123', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await TaxonRuleApi.createRule(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/taxon-rules', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/taxon-rules', req) }) }) @@ -58,7 +58,7 @@ describe('TaxonRuleApi.updateRule', () => { const req = { taxonId: 'taxon-123', type: 'product_name', matchPolicy: 'is_equal_to', value: 'Adidas' } mockPut.mockResolvedValue({ value: { id: 'rule-456', taxonId: 'taxon-123', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonRuleApi.updateRule('rule-456', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/taxon-rules/rule-456', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/taxon-rules/rule-456', req) }) }) @@ -66,7 +66,7 @@ describe('TaxonRuleApi.deleteRule', () => { it('calls DELETE with correct URL and body', async () => { mockDelWithBody.mockResolvedValue({ value: { id: 'rule-456', taxonId: 'taxon-123' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonRuleApi.deleteRule('taxon-123', 'rule-456') - expect(mockDelWithBody).toHaveBeenCalledWith('api/catalog/taxon-rules/rule-456', { taxonId: 'taxon-123', ruleId: 'rule-456' }) + expect(mockDelWithBody).toHaveBeenCalledWith('/api/admin/catalog/taxon-rules/rule-456', { taxonId: 'taxon-123', ruleId: 'rule-456' }) }) }) @@ -78,6 +78,6 @@ describe('TaxonRuleApi.syncRules', () => { ] mockPost.mockResolvedValue({ value: { id: 'rule-456', taxonId: 'taxon-123' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonRuleApi.syncRules({ taxonId: 'taxon-123', rules }) - expect(mockPost).toHaveBeenCalledWith('api/catalog/taxon-rules/sync', { taxonId: 'taxon-123', rules }) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/taxon-rules/sync', { taxonId: 'taxon-123', rules }) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/taxonomyApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/taxonomyApi.spec.ts index 01360fbe4..a958d8d50 100644 --- a/app/Admin/src/features/catalog/__tests__/services/taxonomyApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/taxonomyApi.spec.ts @@ -35,11 +35,11 @@ describe('TaxonomyApi.getTaxonomies', () => { isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null, }) - await TaxonomyApi.getTaxonomies({ name: 'Categories', page: 1, pageSize: 10 }) + await TaxonomyApi.getTaxonomies({ filter: 'name*=Categories', pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxonomies', - { filter: 'name*=Categories', search: null, sort: null, pageNumber: 1, pageSize: 10 }, + '/api/admin/catalog/taxonomies', + { filter: 'name*=Categories', pageNumber: 1, pageSize: 10 }, expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) @@ -49,7 +49,7 @@ describe('TaxonomyApi.getTaxonomy', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'Categories' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonomyApi.getTaxonomy('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/catalog/taxonomies/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/taxonomies/abc-123') }) }) @@ -58,7 +58,7 @@ describe('TaxonomyApi.createTaxonomy', () => { const req = { name: 'Categories', presentation: 'Categories', position: 1 } mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await TaxonomyApi.createTaxonomy(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/taxonomies', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/taxonomies', req) }) }) @@ -67,7 +67,7 @@ describe('TaxonomyApi.updateTaxonomy', () => { const req = { name: 'Categories', presentation: 'Categories', position: 2 } mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonomyApi.updateTaxonomy('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/taxonomies/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/taxonomies/abc-123', req) }) }) @@ -75,7 +75,7 @@ describe('TaxonomyApi.deleteTaxonomy', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Categories' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonomyApi.deleteTaxonomy('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/catalog/taxonomies/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/taxonomies/abc-123') }) }) @@ -83,6 +83,6 @@ describe('TaxonomyApi.restoreTaxonomy', () => { it('calls PATCH restore with correct URL and no body', async () => { mockPatch.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await TaxonomyApi.restoreTaxonomy('abc-123') - expect(mockPatch).toHaveBeenCalledWith('api/catalog/taxonomies/abc-123/restore') + expect(mockPatch).toHaveBeenCalledWith('/api/admin/catalog/taxonomies/abc-123/restore') }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/variantApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/variantApi.spec.ts index 412d2f1ee..424830bee 100644 --- a/app/Admin/src/features/catalog/__tests__/services/variantApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/variantApi.spec.ts @@ -34,10 +34,10 @@ describe('VariantApi.getVariants', () => { isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null, }) - await VariantApi.getVariants('prod-1', { search: 'M', page: 2, pageSize: 25 }) + await VariantApi.getVariants('prod-1', { search: 'M', pageNumber: 2, pageSize: 25 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/variants?productId=prod-1', + '/api/admin/catalog/variants?productId=prod-1', expect.objectContaining({ search: 'M', pageNumber: 2, pageSize: 25 }), expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) @@ -52,7 +52,7 @@ describe('VariantApi.getVariants', () => { await VariantApi.getVariants('', { pageSize: 100 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/variants', + '/api/admin/catalog/variants', expect.objectContaining({ pageSize: 100 }), expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) @@ -63,7 +63,7 @@ describe('VariantApi.getVariant', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: '1', sku: 'M' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.getVariant('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/catalog/variants/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/variants/abc-123') }) }) @@ -72,7 +72,7 @@ describe('VariantApi.createVariant', () => { const req: VariantRequest = { sku: 'SHIRT-M', position: 0, trackInventory: true, isMaster: false, productId: 'prod-1', optionValueIds: [] } mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await VariantApi.createVariant(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/variants', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/variants', req) }) }) @@ -81,7 +81,7 @@ describe('VariantApi.updateVariant', () => { const req: VariantRequest = { sku: 'SHIRT-M', position: 1, trackInventory: true, isMaster: false, productId: 'prod-1' } mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.updateVariant('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/catalog/variants/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/catalog/variants/abc-123', req) }) }) @@ -89,7 +89,7 @@ describe('VariantApi.deleteVariant', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.deleteVariant('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/catalog/variants/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/variants/abc-123') }) }) @@ -101,7 +101,7 @@ describe('VariantApi.getOptionValues', () => { }) await VariantApi.getOptionValues('abc-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/variant-option-values?variantId=abc-123', + '/api/admin/catalog/variant-option-values?variantId=abc-123', {}, ) }) @@ -112,7 +112,7 @@ describe('VariantApi.assignOptionValues', () => { mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.assignOptionValues('abc-123', ['ov-1', 'ov-2']) expect(mockPost).toHaveBeenCalledWith( - 'api/catalog/variant-option-values/assign', + '/api/admin/catalog/variant-option-values/assign', { variantId: 'abc-123', optionValueIds: ['ov-1', 'ov-2'] }, ) }) @@ -123,7 +123,7 @@ describe('VariantApi.revokeOptionValues', () => { mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.revokeOptionValues('abc-123', ['ov-1', 'ov-2']) expect(mockPost).toHaveBeenCalledWith( - 'api/catalog/variant-option-values/revoke', + '/api/admin/catalog/variant-option-values/revoke', { variantId: 'abc-123', optionValueIds: ['ov-1', 'ov-2'] }, ) }) @@ -134,7 +134,7 @@ describe('VariantApi.syncOptionValues', () => { mockPut.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantApi.syncOptionValues('abc-123', ['ov-1', 'ov-2']) expect(mockPut).toHaveBeenCalledWith( - 'api/catalog/variant-option-values/sync', + '/api/admin/catalog/variant-option-values/sync', { variantId: 'abc-123', optionValueIds: ['ov-1', 'ov-2'] }, ) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/variantImageApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/variantImageApi.spec.ts index a294fe92d..b3ce2ed62 100644 --- a/app/Admin/src/features/catalog/__tests__/services/variantImageApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/variantImageApi.spec.ts @@ -35,7 +35,7 @@ describe('VariantImageApi.listImages', () => { }) await VariantImageApi.listImages('abc-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/variant-images?variantId=abc-123', + '/api/admin/catalog/variant-images?variantId=abc-123', {}, ) }) @@ -45,7 +45,7 @@ describe('VariantImageApi.getImage', () => { it('calls GET with image URL', async () => { mockGet.mockResolvedValue({ value: { id: 'img-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantImageApi.getImage('img-1') - expect(mockGet).toHaveBeenCalledWith('api/catalog/variant-images/img-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/catalog/variant-images/img-1') }) }) @@ -54,7 +54,7 @@ describe('VariantImageApi.uploadImage', () => { const file = new File(['x'], 'a.png', { type: 'image/png' }) mockPost.mockResolvedValue({ value: { id: '1' }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await VariantImageApi.uploadImage({ variantId: 'abc-123', file }) - expect(mockPost).toHaveBeenCalledWith('api/catalog/variant-images', expect.any(FormData)) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/variant-images', expect.any(FormData)) }) }) @@ -63,7 +63,7 @@ describe('VariantImageApi.updateImage', () => { mockPut.mockResolvedValue({ value: { id: 'img-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantImageApi.updateImage('img-1', { alt: 'updated', position: 2, type: 'gallery' }) expect(mockPut).toHaveBeenCalledWith( - 'api/catalog/variant-images/img-1', + '/api/admin/catalog/variant-images/img-1', { alt: 'updated', position: 2, type: 'gallery' }, ) }) @@ -73,7 +73,7 @@ describe('VariantImageApi.deleteImage', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: { message: 'ok' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantImageApi.deleteImage('img-1') - expect(mockDel).toHaveBeenCalledWith('api/catalog/variant-images/img-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/catalog/variant-images/img-1') }) }) @@ -82,7 +82,7 @@ describe('VariantImageApi.downloadImage', () => { const blob = new Blob(['data'], { type: 'application/octet-stream' }) mockGetBlob.mockResolvedValue(blob) const result = await VariantImageApi.downloadImage('img-1') - expect(mockGetBlob).toHaveBeenCalledWith('api/catalog/variant-images/img-1/download') + expect(mockGetBlob).toHaveBeenCalledWith('/api/admin/catalog/variant-images/img-1/download') expect(result).toBe(blob) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/services/variantPriceApi.spec.ts b/app/Admin/src/features/catalog/__tests__/services/variantPriceApi.spec.ts index 90eb4d452..953cdaf76 100644 --- a/app/Admin/src/features/catalog/__tests__/services/variantPriceApi.spec.ts +++ b/app/Admin/src/features/catalog/__tests__/services/variantPriceApi.spec.ts @@ -29,8 +29,8 @@ describe('VariantPriceApi.listPrices', () => { }) await VariantPriceApi.listPrices('abc-123') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/variant-prices?variantId=abc-123', - expect.objectContaining({ pageNumber: 1, pageSize: 100 }), + '/api/admin/catalog/variant-prices?variantId=abc-123', + {}, ) }) }) @@ -40,7 +40,7 @@ describe('VariantPriceApi.setPrice', () => { const req = { variantId: 'abc-123', amount: 10, currency: 'USD' } mockPost.mockResolvedValue({ value: { variantId: 'abc-123' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantPriceApi.setPrice(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/variant-prices', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/variant-prices', req) }) }) @@ -48,7 +48,7 @@ describe('VariantPriceApi.removePrice', () => { it('calls DELETE with body', async () => { mockDelWithBody.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantPriceApi.removePrice('abc-123', 'price-1') - expect(mockDelWithBody).toHaveBeenCalledWith('api/catalog/variant-prices/price-1', { variantId: 'abc-123', priceId: 'price-1' }) + expect(mockDelWithBody).toHaveBeenCalledWith('/api/admin/catalog/variant-prices/price-1', { variantId: 'abc-123', priceId: 'price-1' }) }) }) @@ -57,6 +57,6 @@ describe('VariantPriceApi.syncPrices', () => { const req = { variantId: 'abc-123', prices: [{ amount: 10, currency: 'USD' }] } mockPost.mockResolvedValue({ isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await VariantPriceApi.syncPrices(req) - expect(mockPost).toHaveBeenCalledWith('api/catalog/variant-prices/sync', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/catalog/variant-prices/sync', req) }) }) diff --git a/app/Admin/src/features/catalog/__tests__/utils/variantListUrl.spec.ts b/app/Admin/src/features/catalog/__tests__/utils/variantListUrl.spec.ts deleted file mode 100644 index 3dd8583fd..000000000 --- a/app/Admin/src/features/catalog/__tests__/utils/variantListUrl.spec.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { variantsListUrl } from '../../utils/variantListUrl' - -describe('variantsListUrl', () => { - it('includes productId when present', () => { - expect(variantsListUrl('abc')).toBe('api/catalog/variants?productId=abc') - }) - it('omits productId when absent', () => { - expect(variantsListUrl(null)).toBe('api/catalog/variants') - expect(variantsListUrl(undefined)).toBe('api/catalog/variants') - }) -}) diff --git a/app/Admin/src/features/catalog/composables/__tests__/useTaxonList.spec.ts b/app/Admin/src/features/catalog/composables/__tests__/useTaxonList.spec.ts index 97b7b4ac7..585f61654 100644 --- a/app/Admin/src/features/catalog/composables/__tests__/useTaxonList.spec.ts +++ b/app/Admin/src/features/catalog/composables/__tests__/useTaxonList.spec.ts @@ -3,10 +3,16 @@ import { ref } from 'vue' import { useTaxonList } from '../useTaxonList' import type { PagedResult } from '@/shared/types/result' -const { mockGetPaged } = vi.hoisted(() => ({ mockGetPaged: vi.fn<(...args: unknown[]) => unknown>() })) +const { mockGetList, mockGetTaxons } = vi.hoisted(() => ({ + mockGetList: vi.fn<(...args: unknown[]) => unknown>(), + mockGetTaxons: vi.fn<(...args: unknown[]) => unknown>(), +})) -vi.mock('@/shared/api', () => ({ - getPaged: mockGetPaged, +vi.mock('../../services/taxonApi', () => ({ + TaxonApi: { + getList: mockGetList, + getTaxons: mockGetTaxons, + }, })) function okResult(overrides: Partial> = {}): PagedResult<{ id: string; name: string }> { @@ -30,63 +36,49 @@ beforeEach(() => { }) describe('useTaxonList', () => { - it('fetches the taxonomy-scoped URL when a taxonomyId ref is set', async () => { - mockGetPaged.mockResolvedValue(okResult()) + it('fetches the taxonomy-scoped list when a taxonomyId ref is set', async () => { + mockGetList.mockResolvedValue(okResult()) const taxonomyId = ref('tax1') const { fetch } = useTaxonList(taxonomyId, { immediate: false }) await fetch() - expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxons/list?taxonomyId=tax1', - expect.objectContaining({ pageNumber: 1 }), - expect.any(Object), - ) + expect(mockGetList).toHaveBeenCalledWith('tax1', expect.objectContaining({ pageNumber: 1 })) }) - it('fetches the unscoped URL when taxonomyId ref is null', async () => { - mockGetPaged.mockResolvedValue(okResult()) + it('fetches the unscoped list when taxonomyId ref is null', async () => { + mockGetTaxons.mockResolvedValue(okResult()) const taxonomyId = ref(null) const { fetch } = useTaxonList(taxonomyId, { immediate: false }) await fetch() - expect(mockGetPaged).toHaveBeenCalledWith( - 'api/catalog/taxons', - expect.objectContaining({ pageNumber: 1 }), - expect.any(Object), - ) + expect(mockGetTaxons).toHaveBeenCalledWith(expect.objectContaining({ pageNumber: 1 })) }) - it('switches to the scoped URL when taxonomyId ref changes to a new value', async () => { - mockGetPaged.mockResolvedValue(okResult()) + it('switches to the scoped list when taxonomyId ref changes to a new value', async () => { + mockGetTaxons.mockResolvedValue(okResult()) const taxonomyId = ref(null) const { fetch } = useTaxonList(taxonomyId, { immediate: false }) await fetch() taxonomyId.value = 'tax2' + mockGetList.mockResolvedValue(okResult()) await fetch() - expect(mockGetPaged).toHaveBeenLastCalledWith( - 'api/catalog/taxons/list?taxonomyId=tax2', - expect.objectContaining({ pageNumber: 1 }), - expect.any(Object), - ) + expect(mockGetList).toHaveBeenLastCalledWith('tax2', expect.objectContaining({ pageNumber: 1 })) }) - it('switches back to the unscoped URL when taxonomyId ref is cleared', async () => { - mockGetPaged.mockResolvedValue(okResult()) + it('switches back to the unscoped list when taxonomyId ref is cleared', async () => { + mockGetList.mockResolvedValue(okResult()) const taxonomyId = ref('tax1') const { fetch } = useTaxonList(taxonomyId, { immediate: false }) await fetch() taxonomyId.value = null + mockGetTaxons.mockResolvedValue(okResult()) await fetch() - expect(mockGetPaged).toHaveBeenLastCalledWith( - 'api/catalog/taxons', - expect.objectContaining({ pageNumber: 1 }), - expect.any(Object), - ) + expect(mockGetTaxons).toHaveBeenLastCalledWith(expect.objectContaining({ pageNumber: 1 })) }) }) diff --git a/app/Admin/src/features/catalog/composables/useOptionTypeList.ts b/app/Admin/src/features/catalog/composables/useOptionTypeList.ts index 796e6531a..8d20fa77d 100644 --- a/app/Admin/src/features/catalog/composables/useOptionTypeList.ts +++ b/app/Admin/src/features/catalog/composables/useOptionTypeList.ts @@ -1,13 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { OPTION_TYPE_FILTER_FIELDS, OPTION_TYPE_SORT_FIELDS } from '../types/optionType' + +import { OptionTypeApi } from '../services/optionTypeApi' import type { OptionTypeListItem } from '../types/optionType' export function useOptionTypeList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${CATALOG}/option-types`, { - allowedFilterFields: OPTION_TYPE_FILTER_FIELDS, - allowedSortFields: OPTION_TYPE_SORT_FIELDS, + return usePagedQuery((params) => OptionTypeApi.getOptionTypes(params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useOptionValueList.ts b/app/Admin/src/features/catalog/composables/useOptionValueList.ts index 4e71b0420..a178205be 100644 --- a/app/Admin/src/features/catalog/composables/useOptionValueList.ts +++ b/app/Admin/src/features/catalog/composables/useOptionValueList.ts @@ -1,13 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { OPTION_VALUE_FILTER_FIELDS, OPTION_VALUE_SORT_FIELDS } from '../types/optionValue' + +import { OptionValueApi } from '../services/optionValueApi' import type { OptionValueListItem } from '../types/optionValue' export function useOptionValueList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${CATALOG}/option-values`, { - allowedFilterFields: OPTION_VALUE_FILTER_FIELDS, - allowedSortFields: OPTION_VALUE_SORT_FIELDS, + return usePagedQuery((params) => OptionValueApi.getOptionValues(params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useProductList.ts b/app/Admin/src/features/catalog/composables/useProductList.ts index f3730f467..711136e2d 100644 --- a/app/Admin/src/features/catalog/composables/useProductList.ts +++ b/app/Admin/src/features/catalog/composables/useProductList.ts @@ -1,13 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { PRODUCT_FILTER_FIELDS, PRODUCT_SORT_FIELDS } from '../types/product' + +import { ProductApi } from '../services/productApi' import type { ProductListItem } from '../types/product' export function useProductList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${CATALOG}/products`, { - allowedFilterFields: PRODUCT_FILTER_FIELDS, - allowedSortFields: PRODUCT_SORT_FIELDS, + return usePagedQuery((params) => ProductApi.getProducts(params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useProductOptions.ts b/app/Admin/src/features/catalog/composables/useProductOptions.ts index 6fbf29055..fbcfa1888 100644 --- a/app/Admin/src/features/catalog/composables/useProductOptions.ts +++ b/app/Admin/src/features/catalog/composables/useProductOptions.ts @@ -19,9 +19,9 @@ export function useProductOptions() { try { const result = await ProductApi.getProducts({ search: term, - page: 1, + pageNumber: 1, pageSize: PAGE_SIZE, - sortBy: 'name', + sort: ['name:asc'], }) if (seq !== requestSeq) return if (result.isSuccess) { diff --git a/app/Admin/src/features/catalog/composables/useTaxonList.ts b/app/Admin/src/features/catalog/composables/useTaxonList.ts index b98032ccf..fc4a54f89 100644 --- a/app/Admin/src/features/catalog/composables/useTaxonList.ts +++ b/app/Admin/src/features/catalog/composables/useTaxonList.ts @@ -1,17 +1,15 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' + import type { Ref } from 'vue' -import { TAXON_FILTER_FIELDS, TAXON_SORT_FIELDS } from '../types/taxon' +import { TaxonApi } from '../services/taxonApi' import type { TaxonListItem } from '../types/taxon' export function useTaxonList(taxonomyId?: Ref, options?: UsePagedQueryOptions) { return usePagedQuery( - // Transform: Scope the taxon endpoint to the selected taxonomy when set - () => (taxonomyId?.value ? `${CATALOG}/taxons/list?taxonomyId=${taxonomyId.value}` : `${CATALOG}/taxons`), + (params) => + taxonomyId?.value ? TaxonApi.getList(taxonomyId.value, params) : TaxonApi.getTaxons(params), { - allowedFilterFields: TAXON_FILTER_FIELDS, - allowedSortFields: TAXON_SORT_FIELDS, defaultSort: ['position'], ...options, }, diff --git a/app/Admin/src/features/catalog/composables/useTaxonRuleList.ts b/app/Admin/src/features/catalog/composables/useTaxonRuleList.ts index 5eb20a4ae..914962c25 100644 --- a/app/Admin/src/features/catalog/composables/useTaxonRuleList.ts +++ b/app/Admin/src/features/catalog/composables/useTaxonRuleList.ts @@ -1,10 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' + +import { TaxonRuleApi } from '../services/taxonRuleApi' import type { TaxonRuleListItem } from '../types/taxonRule' export function useTaxonRuleList(taxonId: string, options?: UsePagedQueryOptions) { - return usePagedQuery(() => `${CATALOG}/taxon-rules?taxonId=${taxonId}`, { + return usePagedQuery((params) => TaxonRuleApi.getRules(taxonId, params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useVariantImageList.ts b/app/Admin/src/features/catalog/composables/useVariantImageList.ts index 034611058..7d0057901 100644 --- a/app/Admin/src/features/catalog/composables/useVariantImageList.ts +++ b/app/Admin/src/features/catalog/composables/useVariantImageList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { VARIANT_IMAGE_FILTER_FIELDS, VARIANT_IMAGE_SORT_FIELDS, VARIANT_IMAGE_SEARCH_FIELDS } from '../types/variantImage' + +import { VariantImageApi } from '../services/variantImageApi' import type { VariantImage } from '../types/variantImage' export function useVariantImageList(variantId: string, options?: UsePagedQueryOptions) { - return usePagedQuery(() => `${CATALOG}/variant-images?variantId=${variantId}`, { - allowedFilterFields: VARIANT_IMAGE_FILTER_FIELDS, - allowedSortFields: VARIANT_IMAGE_SORT_FIELDS, - allowedSearchFields: VARIANT_IMAGE_SEARCH_FIELDS, + return usePagedQuery((params) => VariantImageApi.listImages(variantId, params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useVariantList.ts b/app/Admin/src/features/catalog/composables/useVariantList.ts index eaa6f90f5..b499f47cd 100644 --- a/app/Admin/src/features/catalog/composables/useVariantList.ts +++ b/app/Admin/src/features/catalog/composables/useVariantList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { VARIANT_FILTER_FIELDS, VARIANT_SORT_FIELDS, VARIANT_SEARCH_FIELDS } from '../types/variant' + +import { VariantApi } from '../services/variantApi' import type { VariantListItem } from '../types/variant' export function useVariantList(productId: string, options?: UsePagedQueryOptions) { - return usePagedQuery(() => `${CATALOG}/variants?productId=${productId}`, { - allowedFilterFields: VARIANT_FILTER_FIELDS, - allowedSortFields: VARIANT_SORT_FIELDS, - allowedSearchFields: VARIANT_SEARCH_FIELDS, + return usePagedQuery((params) => VariantApi.getVariants(productId, params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/composables/useVariantPriceList.ts b/app/Admin/src/features/catalog/composables/useVariantPriceList.ts index b3d37c846..21e682377 100644 --- a/app/Admin/src/features/catalog/composables/useVariantPriceList.ts +++ b/app/Admin/src/features/catalog/composables/useVariantPriceList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { CATALOG } from '@/shared/constants/api' -import { VARIANT_PRICE_FILTER_FIELDS, VARIANT_PRICE_SORT_FIELDS, VARIANT_PRICE_SEARCH_FIELDS } from '../types/variantPrice' + +import { VariantPriceApi } from '../services/variantPriceApi' import type { Price } from '../types/variantPrice' export function useVariantPriceList(variantId: string, options?: UsePagedQueryOptions) { - return usePagedQuery(() => `${CATALOG}/variant-prices?variantId=${variantId}`, { - allowedFilterFields: VARIANT_PRICE_FILTER_FIELDS, - allowedSortFields: VARIANT_PRICE_SORT_FIELDS, - allowedSearchFields: VARIANT_PRICE_SEARCH_FIELDS, + return usePagedQuery((params) => VariantPriceApi.listPrices(variantId, params), { ...options, }) } diff --git a/app/Admin/src/features/catalog/services/catalogDashboardApi.ts b/app/Admin/src/features/catalog/services/catalogDashboardApi.ts index 3d4730f2f..2fb2e2fdb 100644 --- a/app/Admin/src/features/catalog/services/catalogDashboardApi.ts +++ b/app/Admin/src/features/catalog/services/catalogDashboardApi.ts @@ -1,12 +1,10 @@ import { get } from '@/shared/api/client' -import { CATALOG } from '@/shared/constants/api' + import type { Result } from '@/shared/types' import type { CatalogDashboard } from '../types/catalogDashboard' export class CatalogDashboardApi { - private static readonly BASE = `${CATALOG}/dashboard` - static getCatalogDashboard(): Promise> { - return get>(CatalogDashboardApi.BASE) + return get>('/api/admin/catalog/dashboard') } } diff --git a/app/Admin/src/features/catalog/services/imageEmbeddingApi.ts b/app/Admin/src/features/catalog/services/imageEmbeddingApi.ts index a4207dd3b..7d6c591e2 100644 --- a/app/Admin/src/features/catalog/services/imageEmbeddingApi.ts +++ b/app/Admin/src/features/catalog/services/imageEmbeddingApi.ts @@ -1,5 +1,5 @@ import { get, post, put, del } from '@/shared/api/client' -import { CATALOG } from '@/shared/constants/api' + import type { Result } from '@/shared/types' import type { CreateEmbeddingRequest, @@ -8,21 +8,19 @@ import type { } from '../types/imageEmbedding' export class ImageEmbeddingApi { - private static readonly BASE = `${CATALOG}/variant-image-embeddings` - static create(request: CreateEmbeddingRequest): Promise> { - return post>(ImageEmbeddingApi.BASE, request) + return post>('/api/admin/catalog/variant-image-embeddings', request) } static regenerate(request: RegenerateEmbeddingRequest): Promise> { - return put>(`${ImageEmbeddingApi.BASE}/regenerate`, request) + return put>('/api/admin/catalog/variant-image-embeddings/regenerate', request) } static get(variantImageId: string): Promise> { - return get>(`${ImageEmbeddingApi.BASE}/${variantImageId}`) + return get>(`/api/admin/catalog/variant-image-embeddings/${variantImageId}`) } - static deleteEmbedding(variantImageId: string): Promise> { - return del>(`${ImageEmbeddingApi.BASE}/${variantImageId}`) + static deleteEmbedding(variantImageId: string): Promise> { + return del>(`/api/admin/catalog/variant-image-embeddings/${variantImageId}`) } } diff --git a/app/Admin/src/features/catalog/services/optionTypeApi.ts b/app/Admin/src/features/catalog/services/optionTypeApi.ts index e2ef3b817..a5ae94bf9 100644 --- a/app/Admin/src/features/catalog/services/optionTypeApi.ts +++ b/app/Admin/src/features/catalog/services/optionTypeApi.ts @@ -1,42 +1,39 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { OptionTypeRequest, OptionTypeListItem, OptionTypeDetail, - OptionTypeQuery, } from '../types/optionType' import { - toOptionTypeQueryParams, OPTION_TYPE_FILTER_FIELDS, OPTION_TYPE_SORT_FIELDS, } from '../types/optionType' export class OptionTypeApi { - private static readonly BASE = `${CATALOG}/option-types` - - static getOptionTypes(query: OptionTypeQuery): Promise> { - return getPaged(OptionTypeApi.BASE, toOptionTypeQueryParams(query), { + static getOptionTypes(params: QueryingParameters): Promise> { + return getPaged('/api/admin/catalog/option-types', params, { allowedFilterFields: OPTION_TYPE_FILTER_FIELDS, allowedSortFields: OPTION_TYPE_SORT_FIELDS, + allowedSearchFields: ['name', 'presentation'], }) } static getOptionType(id: string): Promise> { - return get>(`${OptionTypeApi.BASE}/${id}`) + return get>(`/api/admin/catalog/option-types/${id}`) } static createOptionType(request: OptionTypeRequest): Promise> { - return post>(OptionTypeApi.BASE, request) + return post>('/api/admin/catalog/option-types', request) } static updateOptionType(id: string, request: OptionTypeRequest): Promise> { - return put>(`${OptionTypeApi.BASE}/${id}`, request) + return put>(`/api/admin/catalog/option-types/${id}`, request) } static deleteOptionType(id: string): Promise> { - return del>(`${OptionTypeApi.BASE}/${id}`) + return del>(`/api/admin/catalog/option-types/${id}`) } } diff --git a/app/Admin/src/features/catalog/services/optionValueApi.ts b/app/Admin/src/features/catalog/services/optionValueApi.ts index bd0450b5a..3aef9d2bf 100644 --- a/app/Admin/src/features/catalog/services/optionValueApi.ts +++ b/app/Admin/src/features/catalog/services/optionValueApi.ts @@ -1,42 +1,39 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { OptionValueRequest, OptionValueListItem, OptionValueDetail, - OptionValueQuery, } from '../types/optionValue' import { - toOptionValueQueryParams, OPTION_VALUE_FILTER_FIELDS, OPTION_VALUE_SORT_FIELDS, } from '../types/optionValue' export class OptionValueApi { - private static readonly BASE = `${CATALOG}/option-values` - - static getOptionValues(query: OptionValueQuery): Promise> { - return getPaged(OptionValueApi.BASE, toOptionValueQueryParams(query), { + static getOptionValues(params: QueryingParameters): Promise> { + return getPaged('/api/admin/catalog/option-values', params, { allowedFilterFields: OPTION_VALUE_FILTER_FIELDS, allowedSortFields: OPTION_VALUE_SORT_FIELDS, + allowedSearchFields: ['name', 'presentation'], }) } static getOptionValue(id: string): Promise> { - return get>(`${OptionValueApi.BASE}/${id}`) + return get>(`/api/admin/catalog/option-values/${id}`) } static createOptionValue(request: OptionValueRequest): Promise> { - return post>(OptionValueApi.BASE, request) + return post>('/api/admin/catalog/option-values', request) } static updateOptionValue(id: string, request: OptionValueRequest): Promise> { - return put>(`${OptionValueApi.BASE}/${id}`, request) + return put>(`/api/admin/catalog/option-values/${id}`, request) } static deleteOptionValue(id: string): Promise> { - return del>(`${OptionValueApi.BASE}/${id}`) + return del>(`/api/admin/catalog/option-values/${id}`) } } diff --git a/app/Admin/src/features/catalog/services/productApi.ts b/app/Admin/src/features/catalog/services/productApi.ts index 39616e9f4..ac5f2838f 100644 --- a/app/Admin/src/features/catalog/services/productApi.ts +++ b/app/Admin/src/features/catalog/services/productApi.ts @@ -1,50 +1,47 @@ import { post, get, put, del, patch } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { ProductRequest, ProductListItem, ProductDetail, - ProductQuery, } from '../types/product' import { - toProductQueryParams, PRODUCT_FILTER_FIELDS, PRODUCT_SORT_FIELDS, } from '../types/product' export class ProductApi { - private static readonly BASE = `${CATALOG}/products` - - static getProducts(query: ProductQuery): Promise> { - return getPaged(ProductApi.BASE, toProductQueryParams(query), { + static getProducts(params: QueryingParameters): Promise> { + return getPaged('/api/admin/catalog/products', params, { allowedFilterFields: PRODUCT_FILTER_FIELDS, allowedSortFields: PRODUCT_SORT_FIELDS, + allowedSearchFields: ['name', 'slug'], }) } static getProduct(id: string): Promise> { - return get>(`${ProductApi.BASE}/${id}`) + return get>(`/api/admin/catalog/products/${id}`) } static createProduct(request: ProductRequest): Promise> { - return post>(ProductApi.BASE, request) + return post>('/api/admin/catalog/products', request) } static updateProduct(id: string, request: ProductRequest): Promise> { - return put>(`${ProductApi.BASE}/${id}`, request) + return put>(`/api/admin/catalog/products/${id}`, request) } static deleteProduct(id: string): Promise> { - return del>(`${ProductApi.BASE}/${id}`) + return del>(`/api/admin/catalog/products/${id}`) } static activateProduct(id: string): Promise> { - return patch>(`${ProductApi.BASE}/${id}/activate`) + return patch>(`/api/admin/catalog/products/${id}/activate`) } static discontinueProduct(id: string): Promise> { - return patch>(`${ProductApi.BASE}/${id}/discontinue`) + return patch>(`/api/admin/catalog/products/${id}/discontinue`) } } diff --git a/app/Admin/src/features/catalog/services/productClassificationApi.ts b/app/Admin/src/features/catalog/services/productClassificationApi.ts index b6826b3b8..42fff31ae 100644 --- a/app/Admin/src/features/catalog/services/productClassificationApi.ts +++ b/app/Admin/src/features/catalog/services/productClassificationApi.ts @@ -1,25 +1,23 @@ import { getPaged } from '@/shared/api' import { post, put } from '@/shared/api/client' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { ClassificationAssignment, ProductClassificationAssignmentRequest } from '../types/productClassification' export class ProductClassificationApi { - private static readonly BASE = `${CATALOG}/product-classifications` - - static getClassifications(productId: string): Promise> { - return getPaged(`${ProductClassificationApi.BASE}?productId=${productId}`, {}) + static getClassifications(productId: string, params: QueryingParameters = {}): Promise> { + return getPaged(`/api/admin/catalog/product-classifications?productId=${productId}`, params) } static syncClassifications(request: ProductClassificationAssignmentRequest): Promise> { - return put>(`${ProductClassificationApi.BASE}/sync`, request) + return put>('/api/admin/catalog/product-classifications/sync', request) } static assignClassifications(request: ProductClassificationAssignmentRequest): Promise> { - return post>(`${ProductClassificationApi.BASE}/assign`, request) + return post>('/api/admin/catalog/product-classifications/assign', request) } static revokeClassifications(request: ProductClassificationAssignmentRequest): Promise> { - return post>(`${ProductClassificationApi.BASE}/revoke`, request) + return post>('/api/admin/catalog/product-classifications/revoke', request) } } diff --git a/app/Admin/src/features/catalog/services/productOptionTypeApi.ts b/app/Admin/src/features/catalog/services/productOptionTypeApi.ts index 6cdb0d4e3..55118e27c 100644 --- a/app/Admin/src/features/catalog/services/productOptionTypeApi.ts +++ b/app/Admin/src/features/catalog/services/productOptionTypeApi.ts @@ -1,25 +1,23 @@ import { getPaged } from '@/shared/api' import { post, put } from '@/shared/api/client' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { OptionTypeAssignment, ProductOptionTypeAssignmentRequest } from '../types/productOptionType' export class ProductOptionTypeApi { - private static readonly BASE = `${CATALOG}/product-option-types` - - static getOptionTypes(productId: string): Promise> { - return getPaged(`${ProductOptionTypeApi.BASE}?productId=${productId}`, {}) + static getOptionTypes(productId: string, params: QueryingParameters = {}): Promise> { + return getPaged(`/api/admin/catalog/product-option-types?productId=${productId}`, params) } static syncOptionTypes(request: ProductOptionTypeAssignmentRequest): Promise> { - return put>(`${ProductOptionTypeApi.BASE}/sync`, request) + return put>('/api/admin/catalog/product-option-types/sync', request) } static assignOptionTypes(request: ProductOptionTypeAssignmentRequest): Promise> { - return post>(`${ProductOptionTypeApi.BASE}/assign`, request) + return post>('/api/admin/catalog/product-option-types/assign', request) } static revokeOptionTypes(request: ProductOptionTypeAssignmentRequest): Promise> { - return post>(`${ProductOptionTypeApi.BASE}/revoke`, request) + return post>('/api/admin/catalog/product-option-types/revoke', request) } } diff --git a/app/Admin/src/features/catalog/services/taxonApi.ts b/app/Admin/src/features/catalog/services/taxonApi.ts index 86cf82add..817668a32 100644 --- a/app/Admin/src/features/catalog/services/taxonApi.ts +++ b/app/Admin/src/features/catalog/services/taxonApi.ts @@ -1,57 +1,55 @@ import { post, get, put, patch, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { TaxonRequest, TaxonListItem, TaxonDetail, - TaxonQuery, } from '../types/taxon' import { - toTaxonQueryParams, TAXON_FILTER_FIELDS, TAXON_SORT_FIELDS, } from '../types/taxon' export class TaxonApi { - private static readonly BASE = `${CATALOG}/taxons` - - static getTaxons(query: TaxonQuery): Promise> { - return getPaged(TaxonApi.BASE, toTaxonQueryParams(query), { + static getTaxons(params: QueryingParameters): Promise> { + return getPaged('/api/admin/catalog/taxons', params, { allowedFilterFields: TAXON_FILTER_FIELDS, allowedSortFields: TAXON_SORT_FIELDS, + allowedSearchFields: ['name', 'slug'], }) } static getTaxon(id: string): Promise> { - return get>(`${TaxonApi.BASE}/${id}`) + return get>(`/api/admin/catalog/taxons/${id}`) } - static getList(taxonomyId: string, query: TaxonQuery): Promise> { - return getPaged(`${TaxonApi.BASE}/list?taxonomyId=${taxonomyId}`, toTaxonQueryParams(query), { + static getList(taxonomyId: string, params: QueryingParameters): Promise> { + return getPaged(`/api/admin/catalog/taxons/list?taxonomyId=${taxonomyId}`, params, { allowedFilterFields: TAXON_FILTER_FIELDS, allowedSortFields: TAXON_SORT_FIELDS, + allowedSearchFields: ['name', 'slug'], }) } static createTaxon(request: TaxonRequest): Promise> { - return post>(TaxonApi.BASE, request) + return post>('/api/admin/catalog/taxons', request) } static updateTaxon(id: string, request: TaxonRequest): Promise> { - return put>(`${TaxonApi.BASE}/${id}`, request) + return put>(`/api/admin/catalog/taxons/${id}`, request) } static deleteTaxon(id: string): Promise> { - return del>(`${TaxonApi.BASE}/${id}`) + return del>(`/api/admin/catalog/taxons/${id}`) } static restoreTaxon(id: string): Promise> { - return patch>(`${TaxonApi.BASE}/${id}/restore`) + return patch>(`/api/admin/catalog/taxons/${id}/restore`) } - static repositionTaxon(id: string, request: TaxonRequest): Promise> { - return post>(`${TaxonApi.BASE}/${id}/reposition`, request) + static repositionTaxon(id: string, request: TaxonRequest): Promise> { + return post>(`/api/admin/catalog/taxons/${id}/reposition`, request) } } diff --git a/app/Admin/src/features/catalog/services/taxonRuleApi.ts b/app/Admin/src/features/catalog/services/taxonRuleApi.ts index f4177b22b..0b4b3d35f 100644 --- a/app/Admin/src/features/catalog/services/taxonRuleApi.ts +++ b/app/Admin/src/features/catalog/services/taxonRuleApi.ts @@ -1,36 +1,31 @@ import { post, put, delWithBody } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { TaxonRuleRequest, TaxonRuleListItem, TaxonRuleDetail, } from '../types/taxonRule' -import { - toTaxonRuleQueryParams, -} from '../types/taxonRule' export class TaxonRuleApi { - private static readonly BASE = `${CATALOG}/taxon-rules` - - static getRules(taxonId: string): Promise> { - return getPaged(`${TaxonRuleApi.BASE}?taxonId=${taxonId}`, toTaxonRuleQueryParams({ taxonId })) + static getRules(taxonId: string, params: QueryingParameters = {}): Promise> { + return getPaged(`/api/admin/catalog/taxon-rules?taxonId=${taxonId}`, params) } static createRule(request: TaxonRuleRequest & { taxonId: string }): Promise> { - return post>(TaxonRuleApi.BASE, request) + return post>('/api/admin/catalog/taxon-rules', request) } static updateRule(ruleId: string, request: TaxonRuleRequest & { taxonId: string }): Promise> { - return put>(`${TaxonRuleApi.BASE}/${ruleId}`, request) + return put>(`/api/admin/catalog/taxon-rules/${ruleId}`, request) } static deleteRule(taxonId: string, ruleId: string): Promise> { - return delWithBody>(`${TaxonRuleApi.BASE}/${ruleId}`, { taxonId, ruleId }) + return delWithBody>(`/api/admin/catalog/taxon-rules/${ruleId}`, { taxonId, ruleId }) } static syncRules(request: { taxonId: string; rules: Array }): Promise> { - return post>(`${TaxonRuleApi.BASE}/sync`, request) + return post>('/api/admin/catalog/taxon-rules/sync', request) } } diff --git a/app/Admin/src/features/catalog/services/taxonomyApi.ts b/app/Admin/src/features/catalog/services/taxonomyApi.ts index 1ffbe6e68..e33031e3a 100644 --- a/app/Admin/src/features/catalog/services/taxonomyApi.ts +++ b/app/Admin/src/features/catalog/services/taxonomyApi.ts @@ -1,46 +1,43 @@ import { post, get, put, patch, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { TaxonomyRequest, TaxonomyListItem, TaxonomyDetail, - TaxonomyQuery, } from '../types/taxonomy' import { - toTaxonomyQueryParams, TAXONOMY_FILTER_FIELDS, TAXONOMY_SORT_FIELDS, } from '../types/taxonomy' export class TaxonomyApi { - private static readonly BASE = `${CATALOG}/taxonomies` - - static getTaxonomies(query: TaxonomyQuery): Promise> { - return getPaged(TaxonomyApi.BASE, toTaxonomyQueryParams(query), { + static getTaxonomies(params: QueryingParameters): Promise> { + return getPaged('/api/admin/catalog/taxonomies', params, { allowedFilterFields: TAXONOMY_FILTER_FIELDS, allowedSortFields: TAXONOMY_SORT_FIELDS, + allowedSearchFields: ['name', 'presentation'], }) } static getTaxonomy(id: string): Promise> { - return get>(`${TaxonomyApi.BASE}/${id}`) + return get>(`/api/admin/catalog/taxonomies/${id}`) } static createTaxonomy(request: TaxonomyRequest): Promise> { - return post>(TaxonomyApi.BASE, request) + return post>('/api/admin/catalog/taxonomies', request) } static updateTaxonomy(id: string, request: TaxonomyRequest): Promise> { - return put>(`${TaxonomyApi.BASE}/${id}`, request) + return put>(`/api/admin/catalog/taxonomies/${id}`, request) } static deleteTaxonomy(id: string): Promise> { - return del>(`${TaxonomyApi.BASE}/${id}`) + return del>(`/api/admin/catalog/taxonomies/${id}`) } static restoreTaxonomy(id: string): Promise> { - return patch>(`${TaxonomyApi.BASE}/${id}/restore`) + return patch>(`/api/admin/catalog/taxonomies/${id}/restore`) } } diff --git a/app/Admin/src/features/catalog/services/variantApi.ts b/app/Admin/src/features/catalog/services/variantApi.ts index a301b5fb0..761c276a7 100644 --- a/app/Admin/src/features/catalog/services/variantApi.ts +++ b/app/Admin/src/features/catalog/services/variantApi.ts @@ -1,32 +1,28 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { VariantRequest, VariantListItem, VariantDetail, - VariantQuery, OptionValueAssignment, } from '../types/variant' import { - toVariantQueryParams, VARIANT_FILTER_FIELDS, VARIANT_SORT_FIELDS, VARIANT_SEARCH_FIELDS, } from '../types/variant' -const BASE = `${CATALOG}/variants` - export class VariantApi { static getVariants( productId: string, - query: VariantQuery, + params: QueryingParameters, ): Promise> { - const url = productId ? `${BASE}?productId=${productId}` : BASE + const url = productId ? `/api/admin/catalog/variants?productId=${productId}` : '/api/admin/catalog/variants' return getPaged( url, - toVariantQueryParams(query), + params, { allowedFilterFields: VARIANT_FILTER_FIELDS, allowedSortFields: VARIANT_SORT_FIELDS, @@ -36,14 +32,14 @@ export class VariantApi { } static getVariant(id: string): Promise> { - return get>(`${BASE}/${id}`) + return get>(`/api/admin/catalog/variants/${id}`) } static createVariant( request: VariantRequest, ): Promise> { return post>( - BASE, + '/api/admin/catalog/variants', request, ) } @@ -52,18 +48,18 @@ export class VariantApi { id: string, request: VariantRequest, ): Promise> { - return put>(`${BASE}/${id}`, request) + return put>(`/api/admin/catalog/variants/${id}`, request) } static deleteVariant(id: string): Promise> { - return del>(`${BASE}/${id}`) + return del>(`/api/admin/catalog/variants/${id}`) } static getOptionValues( variantId: string, ): Promise> { return getPaged( - `${CATALOG}/variant-option-values?variantId=${variantId}`, + `/api/admin/catalog/variant-option-values?variantId=${variantId}`, {}, ) } @@ -73,7 +69,7 @@ export class VariantApi { optionValueIds: string[], ): Promise> { return post>( - `${CATALOG}/variant-option-values/assign`, + '/api/admin/catalog/variant-option-values/assign', { variantId, optionValueIds }, ) } @@ -83,7 +79,7 @@ export class VariantApi { optionValueIds: string[], ): Promise> { return post>( - `${CATALOG}/variant-option-values/revoke`, + '/api/admin/catalog/variant-option-values/revoke', { variantId, optionValueIds }, ) } @@ -93,7 +89,7 @@ export class VariantApi { optionValueIds: string[], ): Promise> { return put>( - `${CATALOG}/variant-option-values/sync`, + '/api/admin/catalog/variant-option-values/sync', { variantId, optionValueIds }, ) } diff --git a/app/Admin/src/features/catalog/services/variantImageApi.ts b/app/Admin/src/features/catalog/services/variantImageApi.ts index 279ec5b05..dca9e2a61 100644 --- a/app/Admin/src/features/catalog/services/variantImageApi.ts +++ b/app/Admin/src/features/catalog/services/variantImageApi.ts @@ -1,18 +1,16 @@ import { get, post, put, del, getBlob } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' -import type { VariantImage, VariantImageUpdateRequest, VariantImageUploadRequest } from '../types/variantImage' -const BASE = `${CATALOG}/variant-images` +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' +import type { VariantImage, VariantImageUpdateRequest, VariantImageUploadRequest } from '../types/variantImage' export class VariantImageApi { - static listImages(variantId: string): Promise> { - return getPaged(`${BASE}?variantId=${variantId}`, {}) + static listImages(variantId: string, params: QueryingParameters = {}): Promise> { + return getPaged(`/api/admin/catalog/variant-images?variantId=${variantId}`, params) } static getImage(id: string): Promise> { - return get>(`${BASE}/${id}`) + return get>(`/api/admin/catalog/variant-images/${id}`) } static uploadImage(request: VariantImageUploadRequest): Promise> { @@ -22,21 +20,21 @@ export class VariantImageApi { if (request.alt !== undefined) formData.append('alt', request.alt) if (request.position !== undefined) formData.append('position', String(request.position)) if (request.type !== undefined) formData.append('type', request.type) - return post>(BASE, formData) + return post>('/api/admin/catalog/variant-images', formData) } static updateImage( id: string, request: VariantImageUpdateRequest, ): Promise> { - return put>(`${BASE}/${id}`, request) + return put>(`/api/admin/catalog/variant-images/${id}`, request) } static deleteImage(id: string): Promise> { - return del>(`${BASE}/${id}`) + return del>(`/api/admin/catalog/variant-images/${id}`) } static downloadImage(id: string): Promise { - return getBlob(`${BASE}/${id}/download`) + return getBlob(`/api/admin/catalog/variant-images/${id}/download`) } } diff --git a/app/Admin/src/features/catalog/services/variantPriceApi.ts b/app/Admin/src/features/catalog/services/variantPriceApi.ts index 7ed6516a5..4c5812f93 100644 --- a/app/Admin/src/features/catalog/services/variantPriceApi.ts +++ b/app/Admin/src/features/catalog/services/variantPriceApi.ts @@ -1,36 +1,31 @@ import { post, delWithBody } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { CATALOG } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' -import type { Price, PriceRequest } from '../types/variantPrice' -const BASE = `${CATALOG}/variant-prices` +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' +import type { Price, PriceRequest } from '../types/variantPrice' export class VariantPriceApi { - static listPrices(variantId: string): Promise> { - return getPaged(`${BASE}?variantId=${variantId}`, { - pageNumber: 1, - pageSize: 100, - }) + static listPrices(variantId: string, params: QueryingParameters = {}): Promise> { + return getPaged(`/api/admin/catalog/variant-prices?variantId=${variantId}`, params) } static setPrice( request: PriceRequest & { variantId: string }, ): Promise> { - return post>(BASE, request) + return post>('/api/admin/catalog/variant-prices', request) } static removePrice( variantId: string, priceId: string, ): Promise> { - return delWithBody>(`${BASE}/${priceId}`, { variantId, priceId }) + return delWithBody>(`/api/admin/catalog/variant-prices/${priceId}`, { variantId, priceId }) } static syncPrices(request: { variantId: string prices: PriceRequest[] }): Promise> { - return post>(`${BASE}/sync`, request) + return post>('/api/admin/catalog/variant-prices/sync', request) } } diff --git a/app/Admin/src/features/catalog/utils/variantListUrl.ts b/app/Admin/src/features/catalog/utils/variantListUrl.ts deleted file mode 100644 index a321e632f..000000000 --- a/app/Admin/src/features/catalog/utils/variantListUrl.ts +++ /dev/null @@ -1,5 +0,0 @@ -export function variantsListUrl(productId: string | null | undefined): string { - return productId - ? `api/catalog/variants?productId=${productId}` - : 'api/catalog/variants' -} diff --git a/app/Admin/src/features/catalog/views/OptionTypeDetail.vue b/app/Admin/src/features/catalog/views/OptionTypeDetail.vue index 16f893348..c5de2eb4f 100644 --- a/app/Admin/src/features/catalog/views/OptionTypeDetail.vue +++ b/app/Admin/src/features/catalog/views/OptionTypeDetail.vue @@ -23,7 +23,6 @@ import { OptionValueApi } from '../services/optionValueApi' import { optionTypeSchema, optionTypeName, optionTypePresentation, optionTypePosition } from '../validations/optionType' import type { OptionTypeForm } from '../validations/optionType' import type { OptionValueListItem } from '../types/optionValue' -import { OPTION_VALUE_FILTER_FIELDS, OPTION_VALUE_SORT_FIELDS } from '../types/optionValue' import OptionValueFormDialog from '../components/OptionValueFormDialog.vue' const route = useRoute() @@ -65,10 +64,7 @@ const { setSearch: setValueSearch, setFilter: setValueFilter, refresh: refreshValues, -} = usePagedQuery('api/catalog/option-values', { - allowedFilterFields: OPTION_VALUE_FILTER_FIELDS, - allowedSortFields: OPTION_VALUE_SORT_FIELDS, - allowedSearchFields: valueSearchFields, +} = usePagedQuery((params) => OptionValueApi.getOptionValues(params), { defaultSearchFields: valueSearchFields, defaultSearchMode: 'any', defaultSort: ['position', 'name'], diff --git a/app/Admin/src/features/catalog/views/OptionTypesList.vue b/app/Admin/src/features/catalog/views/OptionTypesList.vue index 1e0b902d4..8b10dead7 100644 --- a/app/Admin/src/features/catalog/views/OptionTypesList.vue +++ b/app/Admin/src/features/catalog/views/OptionTypesList.vue @@ -13,7 +13,6 @@ import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' import { OptionTypeApi } from '../services/optionTypeApi' import type { OptionTypeListItem } from '../types/optionType' -import { OPTION_TYPE_FILTER_FIELDS, OPTION_TYPE_SORT_FIELDS } from '../types/optionType' import { tableFirst } from '../utils/tablePaging' const router = useRouter() @@ -38,10 +37,7 @@ const { setSort, setFilter, refresh, -} = usePagedQuery('api/catalog/option-types', { - allowedFilterFields: OPTION_TYPE_FILTER_FIELDS, - allowedSortFields: OPTION_TYPE_SORT_FIELDS, - allowedSearchFields, +} = usePagedQuery((params) => OptionTypeApi.getOptionTypes(params), { defaultSearchFields: allowedSearchFields, defaultSearchMode: 'any', defaultSort: ['name'], diff --git a/app/Admin/src/features/catalog/views/ProductsList.vue b/app/Admin/src/features/catalog/views/ProductsList.vue index 96bed4dd1..1724a51b2 100644 --- a/app/Admin/src/features/catalog/views/ProductsList.vue +++ b/app/Admin/src/features/catalog/views/ProductsList.vue @@ -14,7 +14,6 @@ import { useNotify } from '@/shared/composables/useNotify' import { formatDateTimeUtc } from '@/shared/utils/date' import { ProductApi } from '../services/productApi' import type { ProductListItem } from '../types/product' -import { PRODUCT_FILTER_FIELDS, PRODUCT_SORT_FIELDS } from '../types/product' import { statusAction } from '../utils/productStatus' const router = useRouter() @@ -39,10 +38,7 @@ const { setSort, setFilter, refresh, -} = usePagedQuery('api/catalog/products', { - allowedFilterFields: PRODUCT_FILTER_FIELDS, - allowedSortFields: PRODUCT_SORT_FIELDS, - allowedSearchFields, +} = usePagedQuery((params) => ProductApi.getProducts(params), { defaultSearchFields: allowedSearchFields, defaultSearchMode: 'any', defaultSort: ['name'], diff --git a/app/Admin/src/features/catalog/views/TaxonomiesList.vue b/app/Admin/src/features/catalog/views/TaxonomiesList.vue index fb74aea5c..a1d2605d2 100644 --- a/app/Admin/src/features/catalog/views/TaxonomiesList.vue +++ b/app/Admin/src/features/catalog/views/TaxonomiesList.vue @@ -10,7 +10,6 @@ import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' import { TaxonomyApi } from '../services/taxonomyApi' import type { TaxonomyListItem } from '../types/taxonomy' -import { TAXONOMY_FILTER_FIELDS, TAXONOMY_SORT_FIELDS } from '../types/taxonomy' const router = useRouter() const confirm = useConfirm() @@ -32,10 +31,7 @@ const { setPageSize, setSort, refresh, -} = usePagedQuery('api/catalog/taxonomies', { - allowedFilterFields: TAXONOMY_FILTER_FIELDS, - allowedSortFields: TAXONOMY_SORT_FIELDS, - allowedSearchFields, +} = usePagedQuery((params) => TaxonomyApi.getTaxonomies(params), { defaultSearchFields: allowedSearchFields, defaultSearchMode: 'any', defaultSort: ['name'], diff --git a/app/Admin/src/features/catalog/views/VariantsList.vue b/app/Admin/src/features/catalog/views/VariantsList.vue index 52e51aa5a..b7633de54 100644 --- a/app/Admin/src/features/catalog/views/VariantsList.vue +++ b/app/Admin/src/features/catalog/views/VariantsList.vue @@ -12,14 +12,9 @@ import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { useNotify } from '@/shared/composables/useNotify' import { useProductOptions } from '../composables/useProductOptions' -import { variantsListUrl } from '../utils/variantListUrl' import { VariantApi } from '../services/variantApi' import type { VariantListItem } from '../types/variant' -import { - VARIANT_FILTER_FIELDS, - VARIANT_SORT_FIELDS, - VARIANT_SEARCH_FIELDS, -} from '../types/variant' +import { VARIANT_SEARCH_FIELDS } from '../types/variant' const route = useRoute() const router = useRouter() @@ -87,11 +82,8 @@ const { setSort, refresh, } = usePagedQuery( - () => variantsListUrl(productId.value), + (params) => VariantApi.getVariants(productId.value ?? '', params), { - allowedFilterFields: VARIANT_FILTER_FIELDS, - allowedSortFields: VARIANT_SORT_FIELDS, - allowedSearchFields: VARIANT_SEARCH_FIELDS, defaultSearchFields: VARIANT_SEARCH_FIELDS, defaultSearchMode: 'any', defaultSort: ['position'], diff --git a/app/Admin/src/features/dashboard/__tests__/services/dashboardApi.spec.ts b/app/Admin/src/features/dashboard/__tests__/services/dashboardApi.spec.ts index 44f7a38f7..b6c8d5216 100644 --- a/app/Admin/src/features/dashboard/__tests__/services/dashboardApi.spec.ts +++ b/app/Admin/src/features/dashboard/__tests__/services/dashboardApi.spec.ts @@ -54,7 +54,7 @@ describe('DashboardApi.getDashboard', () => { await DashboardApi.getDashboard() - expect(mockGet).toHaveBeenCalledWith('api/dashboard') + expect(mockGet).toHaveBeenCalledWith('/api/admin/dashboard') }) it('resolves the dashboard summary result', async () => { diff --git a/app/Admin/src/features/dashboard/services/dashboardApi.ts b/app/Admin/src/features/dashboard/services/dashboardApi.ts index f52cf1012..6e1525e45 100644 --- a/app/Admin/src/features/dashboard/services/dashboardApi.ts +++ b/app/Admin/src/features/dashboard/services/dashboardApi.ts @@ -1,12 +1,10 @@ import { get } from '@/shared/api/client' -import { DASHBOARD } from '@/shared/constants/api' + import type { Result } from '@/shared/types' import type { DashboardSummary } from '../types/dashboard' export class DashboardApi { - private static readonly BASE = DASHBOARD - static getDashboard(): Promise> { - return get>(DashboardApi.BASE) + return get>('/api/admin/dashboard') } } diff --git a/app/Admin/src/features/identity/__tests__/services/permissionApi.spec.ts b/app/Admin/src/features/identity/__tests__/services/permissionApi.spec.ts index 499ba34f4..13a10e510 100644 --- a/app/Admin/src/features/identity/__tests__/services/permissionApi.spec.ts +++ b/app/Admin/src/features/identity/__tests__/services/permissionApi.spec.ts @@ -32,8 +32,8 @@ describe('PermissionApi.getPermissions', () => { await PermissionApi.getPermissions() expect(mockGetPaged).toHaveBeenCalledWith( - 'api/identity/permissions', + '/api/admin/identity/permissions', { pageNumber: 1, pageSize: 100 }, ) }) -}) +}) \ No newline at end of file diff --git a/app/Admin/src/features/identity/__tests__/services/roleApi.spec.ts b/app/Admin/src/features/identity/__tests__/services/roleApi.spec.ts index eb724378a..6b1460ce3 100644 --- a/app/Admin/src/features/identity/__tests__/services/roleApi.spec.ts +++ b/app/Admin/src/features/identity/__tests__/services/roleApi.spec.ts @@ -44,16 +44,12 @@ describe('RoleApi.getRoles', () => { metadata: null, }) - await RoleApi.getRoles({ name: 'Admin', page: 1, pageSize: 10 }) + await RoleApi.getRoles({ search: 'Admin', searchFields: ['name'], pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/identity/roles', - { filter: null, search: 'Admin', searchFields: ['name'], sort: null, pageNumber: 1, pageSize: 10 }, - expect.objectContaining({ - allowedFilterFields: ['isSystem', 'createdAtUtc', 'modifiedAtUtc'], - allowedSortFields: ['name', 'isSystem', 'createdAtUtc', 'modifiedAtUtc'], - allowedSearchFields: ['name', 'description'], - }), + '/api/admin/identity/roles', + { search: 'Admin', searchFields: ['name'], pageNumber: 1, pageSize: 10 }, + expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) }) @@ -62,7 +58,7 @@ describe('RoleApi.getRole', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'r-1', name: 'Admin', isSystem: true }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.getRole('r-1') - expect(mockGet).toHaveBeenCalledWith('api/identity/roles/r-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/identity/roles/r-1') }) }) @@ -71,7 +67,7 @@ describe('RoleApi.createRole', () => { const req = { name: 'Admin', description: 'Administrator role', presentation: 'Admin' } mockPost.mockResolvedValue({ value: { id: 'r-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await RoleApi.createRole(req) - expect(mockPost).toHaveBeenCalledWith('api/identity/roles', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/identity/roles', req) }) }) @@ -80,7 +76,7 @@ describe('RoleApi.updateRole', () => { const req = { name: 'Admin', description: 'Administrator role', presentation: 'Admin' } mockPut.mockResolvedValue({ value: { id: 'r-1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.updateRole('r-1', req) - expect(mockPut).toHaveBeenCalledWith('api/identity/roles/r-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/identity/roles/r-1', req) }) }) @@ -88,7 +84,7 @@ describe('RoleApi.deleteRole', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await RoleApi.deleteRole('r-1') - expect(mockDel).toHaveBeenCalledWith('api/identity/roles/r-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/identity/roles/r-1') }) }) @@ -96,7 +92,7 @@ describe('RoleApi.assignPermissions', () => { it('calls PUT with assign URL and permissions body', async () => { mockPut.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.assignPermissions('r-1', ['a.b.c.view']) - expect(mockPut).toHaveBeenCalledWith('api/identity/roles/r-1/permissions/assign', { permissions: ['a.b.c.view'] }) + expect(mockPut).toHaveBeenCalledWith('/api/admin/identity/roles/r-1/permissions/assign', { permissions: ['a.b.c.view'] }) }) }) @@ -104,7 +100,7 @@ describe('RoleApi.getPermissions', () => { it('calls GET with permissions URL', async () => { mockGet.mockResolvedValue({ value: { categories: [] }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.getPermissions('r-1') - expect(mockGet).toHaveBeenCalledWith('api/identity/roles/r-1/permissions') + expect(mockGet).toHaveBeenCalledWith('/api/admin/identity/roles/r-1/permissions') }) }) @@ -112,7 +108,7 @@ describe('RoleApi.revokePermissions', () => { it('calls delWithBody with revoke URL and permissions body', async () => { mockDelWithBody.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.revokePermissions('r-1', ['a.b.c.view']) - expect(mockDelWithBody).toHaveBeenCalledWith('api/identity/roles/r-1/permissions/revoke', { permissions: ['a.b.c.view'] }) + expect(mockDelWithBody).toHaveBeenCalledWith('/api/admin/identity/roles/r-1/permissions/revoke', { permissions: ['a.b.c.view'] }) expect(mockDel).not.toHaveBeenCalled() }) }) @@ -121,6 +117,6 @@ describe('RoleApi.syncPermissions', () => { it('calls PATCH with sync URL and permissions body', async () => { mockPatch.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await RoleApi.syncPermissions('r-1', ['a.b.c.view']) - expect(mockPatch).toHaveBeenCalledWith('api/identity/roles/r-1/permissions/sync', { permissions: ['a.b.c.view'] }) + expect(mockPatch).toHaveBeenCalledWith('/api/admin/identity/roles/r-1/permissions/sync', { permissions: ['a.b.c.view'] }) }) -}) +}) \ No newline at end of file diff --git a/app/Admin/src/features/identity/__tests__/services/userApi.spec.ts b/app/Admin/src/features/identity/__tests__/services/userApi.spec.ts index c564a8185..52194776b 100644 --- a/app/Admin/src/features/identity/__tests__/services/userApi.spec.ts +++ b/app/Admin/src/features/identity/__tests__/services/userApi.spec.ts @@ -44,16 +44,12 @@ describe('UserApi.getUsers', () => { metadata: null, }) - await UserApi.getUsers({ isActive: true, page: 1, pageSize: 10 }) + await UserApi.getUsers({ filter: 'isActive=true', pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/identity/users', - { filter: 'isActive=true', search: null, sort: null, pageNumber: 1, pageSize: 10 }, - expect.objectContaining({ - allowedFilterFields: ['isActive', 'emailConfirmed', 'phoneNumberConfirmed', 'createdAtUtc', 'modifiedAtUtc'], - allowedSortFields: ['userName', 'email', 'createdAtUtc', 'modifiedAtUtc', 'lastLoginAtUtc'], - allowedSearchFields: ['userName', 'email', 'firstName', 'lastName'], - }), + '/api/admin/identity/users', + { filter: 'isActive=true', pageNumber: 1, pageSize: 10 }, + expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) }) @@ -62,7 +58,7 @@ describe('UserApi.getUser', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'u-1', email: 'a@b.com', userName: 'admin' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.getUser('u-1') - expect(mockGet).toHaveBeenCalledWith('api/identity/users/u-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/identity/users/u-1') }) }) @@ -79,7 +75,7 @@ describe('UserApi.createUser', () => { } mockPost.mockResolvedValue({ value: { id: 'u-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await UserApi.createUser(req) - expect(mockPost).toHaveBeenCalledWith('api/identity/users', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/identity/users', req) }) }) @@ -96,7 +92,7 @@ describe('UserApi.updateUser', () => { } mockPut.mockResolvedValue({ value: { id: 'u-1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.updateUser('u-1', req) - expect(mockPut).toHaveBeenCalledWith('api/identity/users/u-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/identity/users/u-1', req) }) }) @@ -104,7 +100,7 @@ describe('UserApi.deleteUser', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await UserApi.deleteUser('u-1') - expect(mockDel).toHaveBeenCalledWith('api/identity/users/u-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/identity/users/u-1') }) }) @@ -112,7 +108,7 @@ describe('UserApi.toggleStatus', () => { it('calls PATCH with status URL and no body', async () => { mockPatch.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.toggleStatus('u-1') - expect(mockPatch).toHaveBeenCalledWith('api/identity/users/u-1/status') + expect(mockPatch).toHaveBeenCalledWith('/api/admin/identity/users/u-1/status') }) }) @@ -132,7 +128,7 @@ describe('UserApi.getRoles', () => { }) await UserApi.getRoles('u-1') expect(mockGetPaged).toHaveBeenCalledWith( - 'api/identity/users/u-1/roles', + '/api/admin/identity/users/u-1/roles', { pageNumber: 1, pageSize: 100 }, ) }) @@ -142,7 +138,7 @@ describe('UserApi.assignRoles', () => { it('calls POST with assign URL and roles body', async () => { mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.assignRoles('u-1', ['Admin']) - expect(mockPost).toHaveBeenCalledWith('api/identity/users/u-1/roles/assign', { roles: ['Admin'] }) + expect(mockPost).toHaveBeenCalledWith('/api/admin/identity/users/u-1/roles/assign', { roles: ['Admin'] }) }) }) @@ -150,7 +146,7 @@ describe('UserApi.revokeRoles', () => { it('calls POST with revoke URL and roles body', async () => { mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.revokeRoles('u-1', ['Admin']) - expect(mockPost).toHaveBeenCalledWith('api/identity/users/u-1/roles/revoke', { roles: ['Admin'] }) + expect(mockPost).toHaveBeenCalledWith('/api/admin/identity/users/u-1/roles/revoke', { roles: ['Admin'] }) }) }) @@ -158,7 +154,7 @@ describe('UserApi.syncRoles', () => { it('calls PATCH with sync URL and roles body', async () => { mockPatch.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.syncRoles('u-1', ['Admin']) - expect(mockPatch).toHaveBeenCalledWith('api/identity/users/u-1/roles/sync', { roles: ['Admin'] }) + expect(mockPatch).toHaveBeenCalledWith('/api/admin/identity/users/u-1/roles/sync', { roles: ['Admin'] }) }) }) @@ -166,7 +162,7 @@ describe('UserApi.getPermissions', () => { it('calls GET with permissions URL', async () => { mockGet.mockResolvedValue({ value: { categories: [] }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.getPermissions('u-1') - expect(mockGet).toHaveBeenCalledWith('api/identity/users/u-1/permissions') + expect(mockGet).toHaveBeenCalledWith('/api/admin/identity/users/u-1/permissions') }) }) @@ -174,7 +170,7 @@ describe('UserApi.assignPermissions', () => { it('calls POST with assign URL and permissions body', async () => { mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.assignPermissions('u-1', ['a.b.c.view']) - expect(mockPost).toHaveBeenCalledWith('api/identity/users/u-1/permissions/assign', { permissions: ['a.b.c.view'] }) + expect(mockPost).toHaveBeenCalledWith('/api/admin/identity/users/u-1/permissions/assign', { permissions: ['a.b.c.view'] }) }) }) @@ -182,7 +178,7 @@ describe('UserApi.revokePermissions', () => { it('calls delWithBody with revoke URL and permissions body', async () => { mockDelWithBody.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.revokePermissions('u-1', ['a.b.c.view']) - expect(mockDelWithBody).toHaveBeenCalledWith('api/identity/users/u-1/permissions/revoke', { permissions: ['a.b.c.view'] }) + expect(mockDelWithBody).toHaveBeenCalledWith('/api/admin/identity/users/u-1/permissions/revoke', { permissions: ['a.b.c.view'] }) expect(mockDel).not.toHaveBeenCalled() }) }) @@ -191,6 +187,6 @@ describe('UserApi.syncPermissions', () => { it('calls PUT with sync URL and permissions body', async () => { mockPut.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await UserApi.syncPermissions('u-1', ['a.b.c.view']) - expect(mockPut).toHaveBeenCalledWith('api/identity/users/u-1/permissions/sync', { permissions: ['a.b.c.view'] }) + expect(mockPut).toHaveBeenCalledWith('/api/admin/identity/users/u-1/permissions/sync', { permissions: ['a.b.c.view'] }) }) -}) +}) \ No newline at end of file diff --git a/app/Admin/src/features/identity/composables/useRoleList.ts b/app/Admin/src/features/identity/composables/useRoleList.ts index 39c4d7ea1..736342c66 100644 --- a/app/Admin/src/features/identity/composables/useRoleList.ts +++ b/app/Admin/src/features/identity/composables/useRoleList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { IDENTITY } from '@/shared/constants/api' -import { ROLE_FILTER_FIELDS, ROLE_SORT_FIELDS, ROLE_SEARCH_FIELDS } from '../types/role' + +import { RoleApi } from '../services/roleApi' import type { RoleListItem } from '../types/role' export function useRoleList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${IDENTITY}/roles`, { - allowedFilterFields: ROLE_FILTER_FIELDS, - allowedSortFields: ROLE_SORT_FIELDS, - allowedSearchFields: ROLE_SEARCH_FIELDS, + return usePagedQuery((params) => RoleApi.getRoles(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/identity/composables/useUserList.ts b/app/Admin/src/features/identity/composables/useUserList.ts index 510ad8ecc..05be2efb9 100644 --- a/app/Admin/src/features/identity/composables/useUserList.ts +++ b/app/Admin/src/features/identity/composables/useUserList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { IDENTITY } from '@/shared/constants/api' -import { USER_FILTER_FIELDS, USER_SORT_FIELDS, USER_SEARCH_FIELDS } from '../types/user' + +import { UserApi } from '../services/userApi' import type { UserListItem } from '../types/user' export function useUserList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${IDENTITY}/users`, { - allowedFilterFields: USER_FILTER_FIELDS, - allowedSortFields: USER_SORT_FIELDS, - allowedSearchFields: USER_SEARCH_FIELDS, + return usePagedQuery((params) => UserApi.getUsers(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/identity/services/permissionApi.ts b/app/Admin/src/features/identity/services/permissionApi.ts index d4cb3f330..739586967 100644 --- a/app/Admin/src/features/identity/services/permissionApi.ts +++ b/app/Admin/src/features/identity/services/permissionApi.ts @@ -1,12 +1,10 @@ import { getPaged } from '@/shared/api' -import { IDENTITY } from '@/shared/constants/api' + import type { PagedResult } from '@/shared/types' import type { PermissionMetadata } from '../types/permission' export class PermissionApi { - private static readonly BASE = `${IDENTITY}/permissions` - static getPermissions(): Promise> { - return getPaged(PermissionApi.BASE, { pageNumber: 1, pageSize: 100 }) + return getPaged('/api/admin/identity/permissions', { pageNumber: 1, pageSize: 100 }) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/identity/services/roleApi.ts b/app/Admin/src/features/identity/services/roleApi.ts index 21c039fbc..22e168627 100644 --- a/app/Admin/src/features/identity/services/roleApi.ts +++ b/app/Admin/src/features/identity/services/roleApi.ts @@ -1,15 +1,13 @@ import { post, get, put, patch, del, delWithBody } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { IDENTITY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { RoleRequest, RoleListItem, RoleDetail, - RoleQuery, } from '../types/role' import { - toRoleQueryParams, ROLE_FILTER_FIELDS, ROLE_SORT_FIELDS, ROLE_SEARCH_FIELDS, @@ -17,10 +15,8 @@ import { import type { PermissionGroupResponse } from '../types/permission' export class RoleApi { - private static readonly BASE = `${IDENTITY}/roles` - - static getRoles(query: RoleQuery): Promise> { - return getPaged(RoleApi.BASE, toRoleQueryParams(query), { + static getRoles(params: QueryingParameters): Promise> { + return getPaged('/api/admin/identity/roles', params, { allowedFilterFields: ROLE_FILTER_FIELDS, allowedSortFields: ROLE_SORT_FIELDS, allowedSearchFields: ROLE_SEARCH_FIELDS, @@ -28,34 +24,34 @@ export class RoleApi { } static getRole(id: string): Promise> { - return get>(`${RoleApi.BASE}/${id}`) + return get>(`/api/admin/identity/roles/${id}`) } static createRole(request: RoleRequest): Promise> { - return post>(RoleApi.BASE, request) + return post>('/api/admin/identity/roles', request) } static updateRole(id: string, request: RoleRequest): Promise> { - return put>(`${RoleApi.BASE}/${id}`, request) + return put>(`/api/admin/identity/roles/${id}`, request) } static deleteRole(id: string): Promise> { - return del>(`${RoleApi.BASE}/${id}`) + return del>(`/api/admin/identity/roles/${id}`) } static assignPermissions(id: string, permissions: string[]): Promise> { - return put>(`${RoleApi.BASE}/${id}/permissions/assign`, { permissions }) + return put>(`/api/admin/identity/roles/${id}/permissions/assign`, { permissions }) } static getPermissions(id: string): Promise> { - return get>(`${RoleApi.BASE}/${id}/permissions`) + return get>(`/api/admin/identity/roles/${id}/permissions`) } static revokePermissions(id: string, permissions: string[]): Promise> { - return delWithBody>(`${RoleApi.BASE}/${id}/permissions/revoke`, { permissions }) + return delWithBody>(`/api/admin/identity/roles/${id}/permissions/revoke`, { permissions }) } static syncPermissions(id: string, permissions: string[]): Promise> { - return patch>(`${RoleApi.BASE}/${id}/permissions/sync`, { permissions }) + return patch>(`/api/admin/identity/roles/${id}/permissions/sync`, { permissions }) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/identity/services/userApi.ts b/app/Admin/src/features/identity/services/userApi.ts index fcd090194..c1291bf98 100644 --- a/app/Admin/src/features/identity/services/userApi.ts +++ b/app/Admin/src/features/identity/services/userApi.ts @@ -1,15 +1,13 @@ import { post, get, put, patch, del, delWithBody } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { IDENTITY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { UserRequest, UserListItem, UserDetail, - UserQuery, } from '../types/user' import { - toUserQueryParams, USER_FILTER_FIELDS, USER_SORT_FIELDS, USER_SEARCH_FIELDS, @@ -22,10 +20,8 @@ export interface UserRoleAssignment extends RoleListItem { } export class UserApi { - private static readonly BASE = `${IDENTITY}/users` - - static getUsers(query: UserQuery): Promise> { - return getPaged(UserApi.BASE, toUserQueryParams(query), { + static getUsers(params: QueryingParameters): Promise> { + return getPaged('/api/admin/identity/users', params, { allowedFilterFields: USER_FILTER_FIELDS, allowedSortFields: USER_SORT_FIELDS, allowedSearchFields: USER_SEARCH_FIELDS, @@ -33,57 +29,57 @@ export class UserApi { } static getUser(id: string): Promise> { - return get>(`${UserApi.BASE}/${id}`) + return get>(`/api/admin/identity/users/${id}`) } static createUser(request: UserRequest): Promise> { - return post>(UserApi.BASE, request) + return post>('/api/admin/identity/users', request) } static updateUser(id: string, request: UserRequest): Promise> { - return put>(`${UserApi.BASE}/${id}`, request) + return put>(`/api/admin/identity/users/${id}`, request) } static deleteUser(id: string): Promise> { - return del>(`${UserApi.BASE}/${id}`) + return del>(`/api/admin/identity/users/${id}`) } static toggleStatus(id: string): Promise> { - return patch>(`${UserApi.BASE}/${id}/status`) + return patch>(`/api/admin/identity/users/${id}/status`) } static getRoles(id: string): Promise> { return getPaged( - `${UserApi.BASE}/${id}/roles`, + `/api/admin/identity/users/${id}/roles`, { pageNumber: 1, pageSize: 100 }, ) } static assignRoles(id: string, roleNames: string[]): Promise> { - return post>(`${UserApi.BASE}/${id}/roles/assign`, { roles: roleNames }) + return post>(`/api/admin/identity/users/${id}/roles/assign`, { roles: roleNames }) } static revokeRoles(id: string, roleNames: string[]): Promise> { - return post>(`${UserApi.BASE}/${id}/roles/revoke`, { roles: roleNames }) + return post>(`/api/admin/identity/users/${id}/roles/revoke`, { roles: roleNames }) } static syncRoles(id: string, roleNames: string[]): Promise> { - return patch>(`${UserApi.BASE}/${id}/roles/sync`, { roles: roleNames }) + return patch>(`/api/admin/identity/users/${id}/roles/sync`, { roles: roleNames }) } static getPermissions(id: string): Promise> { - return get>(`${UserApi.BASE}/${id}/permissions`) + return get>(`/api/admin/identity/users/${id}/permissions`) } static assignPermissions(id: string, permissions: string[]): Promise> { - return post>(`${UserApi.BASE}/${id}/permissions/assign`, { permissions }) + return post>(`/api/admin/identity/users/${id}/permissions/assign`, { permissions }) } static revokePermissions(id: string, permissions: string[]): Promise> { - return delWithBody>(`${UserApi.BASE}/${id}/permissions/revoke`, { permissions }) + return delWithBody>(`/api/admin/identity/users/${id}/permissions/revoke`, { permissions }) } static syncPermissions(id: string, permissions: string[]): Promise> { - return put>(`${UserApi.BASE}/${id}/permissions/sync`, { permissions }) + return put>(`/api/admin/identity/users/${id}/permissions/sync`, { permissions }) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/identity/views/PermissionsList.vue b/app/Admin/src/features/identity/views/PermissionsList.vue index bc07f89ee..b6608178c 100644 --- a/app/Admin/src/features/identity/views/PermissionsList.vue +++ b/app/Admin/src/features/identity/views/PermissionsList.vue @@ -8,14 +8,15 @@ import IconField from 'primevue/iconfield' import InputIcon from 'primevue/inputicon' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { usePagedQuery } from '@/shared/composables/usePagedQuery' -import { IDENTITY } from '@/shared/constants/api' + import type { PermissionMetadata } from '../types/permission' const { dt, exportCSV } = useDataTableExport() const search = ref('') +const selectedItems = ref([]) const { items, loading, setSearch, refresh } = usePagedQuery( - `${IDENTITY}/permissions`, + `/api/admin/identity/permissions`, { defaultPageSize: 100, allowedSearchFields: ['name', 'category', 'description'], @@ -59,11 +60,13 @@ function clearSearch() { ref="dt" :value="items" :loading="loading" + v-model:selection="selectedItems" scrollable paginator :rows="50" data-key="name" > + diff --git a/app/Admin/src/features/identity/views/RolesList.vue b/app/Admin/src/features/identity/views/RolesList.vue index 8148ec6f2..01322893a 100644 --- a/app/Admin/src/features/identity/views/RolesList.vue +++ b/app/Admin/src/features/identity/views/RolesList.vue @@ -11,7 +11,7 @@ import InputIcon from 'primevue/inputicon' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' -import { IDENTITY } from '@/shared/constants/api' + import { RoleApi } from '../services/roleApi' import type { RoleListItem } from '../types/role' import { ROLE_FILTER_FIELDS, ROLE_SORT_FIELDS, ROLE_SEARCH_FIELDS } from '../types/role' @@ -24,7 +24,7 @@ const search = ref('') const selectedItems = ref([]) const { items, loading, setSearch, refresh } = usePagedQuery( - `${IDENTITY}/roles`, + `/api/admin/identity/roles`, { allowedFilterFields: ROLE_FILTER_FIELDS, allowedSortFields: ROLE_SORT_FIELDS, diff --git a/app/Admin/src/features/identity/views/UsersList.vue b/app/Admin/src/features/identity/views/UsersList.vue index 7836270b1..b910b40cc 100644 --- a/app/Admin/src/features/identity/views/UsersList.vue +++ b/app/Admin/src/features/identity/views/UsersList.vue @@ -12,7 +12,7 @@ import InputIcon from 'primevue/inputicon' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' -import { IDENTITY } from '@/shared/constants/api' + import { UserApi } from '../services/userApi' import type { UserListItem } from '../types/user' import { USER_FILTER_FIELDS, USER_SORT_FIELDS, USER_SEARCH_FIELDS } from '../types/user' @@ -25,7 +25,7 @@ const search = ref('') const selectedItems = ref([]) const { items, loading, setSearch, refresh } = usePagedQuery( - `${IDENTITY}/users`, + `/api/admin/identity/users`, { allowedFilterFields: USER_FILTER_FIELDS, allowedSortFields: USER_SORT_FIELDS, diff --git a/app/Admin/src/features/inventory/__tests__/services/inventoryDashboardApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/inventoryDashboardApi.spec.ts index 3a680a4f5..e1057800b 100644 --- a/app/Admin/src/features/inventory/__tests__/services/inventoryDashboardApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/inventoryDashboardApi.spec.ts @@ -18,6 +18,6 @@ describe('InventoryDashboardApi.getInventoryDashboard', () => { it('calls GET with dashboard URL', async () => { mockGet.mockResolvedValue({ value: { totalStockItems: 0 }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await InventoryDashboardApi.getInventoryDashboard() - expect(mockGet).toHaveBeenCalledWith('api/inventory/dashboard') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/dashboard') }) }) diff --git a/app/Admin/src/features/inventory/__tests__/services/stockItemApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/stockItemApi.spec.ts index 74e7c7171..36f904d62 100644 --- a/app/Admin/src/features/inventory/__tests__/services/stockItemApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/stockItemApi.spec.ts @@ -41,17 +41,15 @@ describe('StockItemApi.getStockItems', () => { }) await StockItemApi.getStockItems({ - stockLocationId: 'l-1', - variantId: 'v-1', - backorderable: true, - sortBy: 'countOnHand', - sortDirection: 'desc', - page: 1, + filter: 'stockLocationId=l-1,variantId=v-1,backorderable=true', + search: null, + sort: ['-countOnHand'], + pageNumber: 1, pageSize: 10, }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-items', + '/api/admin/inventory/stock-items', { filter: 'stockLocationId=l-1,variantId=v-1,backorderable=true', search: null, @@ -72,7 +70,7 @@ describe('StockItemApi.getStockItem', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 's-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockItemApi.getStockItem('s-1') - expect(mockGet).toHaveBeenCalledWith('api/inventory/stock-items/s-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/stock-items/s-1') }) }) @@ -81,7 +79,7 @@ describe('StockItemApi.createStockItem', () => { const req = { stockLocationId: 'l-1', variantId: 'v-1', countOnHand: 10, backorderable: true } mockPost.mockResolvedValue({ value: { id: 's-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await StockItemApi.createStockItem(req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-items', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-items', req) }) }) @@ -90,7 +88,7 @@ describe('StockItemApi.updateStockItem', () => { const req = { stockLocationId: 'l-1', variantId: 'v-1', countOnHand: 15, backorderable: false } mockPut.mockResolvedValue({ value: { id: 's-1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockItemApi.updateStockItem('s-1', req) - expect(mockPut).toHaveBeenCalledWith('api/inventory/stock-items/s-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/inventory/stock-items/s-1', req) }) }) @@ -98,7 +96,7 @@ describe('StockItemApi.deleteStockItem', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await StockItemApi.deleteStockItem('s-1') - expect(mockDel).toHaveBeenCalledWith('api/inventory/stock-items/s-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/inventory/stock-items/s-1') }) }) @@ -114,7 +112,7 @@ describe('StockItemApi.bulkAdjustStockItems', () => { } mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockItemApi.bulkAdjustStockItems(req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-items/bulk-adjust', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-items/bulk-adjust', req) }) }) @@ -123,7 +121,7 @@ describe('StockItemApi.restockStockItem', () => { const req = { quantity: 10, reference: 'po-1', reason: 'received' } mockPost.mockResolvedValue({ value: { stockItemId: 's-1', newCountOnHand: 10 }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockItemApi.restockStockItem('s-1', req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-items/s-1/restock', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-items/s-1/restock', req) }) }) @@ -145,7 +143,7 @@ describe('StockItemApi.getLowStockItems', () => { await StockItemApi.getLowStockItems({ locationId: 'l-1', threshold: 5, page: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-items/low-stock?locationId=l-1&threshold=5', + '/api/admin/inventory/stock-items/low-stock?locationId=l-1&threshold=5', { pageNumber: 1, pageSize: 10 }, ) }) @@ -169,7 +167,7 @@ describe('StockItemApi.getStockSummary', () => { await StockItemApi.getStockSummary({ page: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-items/summary', + '/api/admin/inventory/stock-items/summary', { pageNumber: 1, pageSize: 10 }, ) }) @@ -179,6 +177,6 @@ describe('StockItemApi.importStockItems', () => { it('calls POST with import URL and FormData body', async () => { mockPost.mockResolvedValue({ value: { created: 1, updated: 0, failed: 0, errors: [] }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockItemApi.importStockItems(new File(['csv'], 'stock.csv', { type: 'text/csv' })) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-items/import', expect.any(FormData)) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-items/import', expect.any(FormData)) }) }) diff --git a/app/Admin/src/features/inventory/__tests__/services/stockLocationApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/stockLocationApi.spec.ts index 0b64520af..329051961 100644 --- a/app/Admin/src/features/inventory/__tests__/services/stockLocationApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/stockLocationApi.spec.ts @@ -41,16 +41,15 @@ describe('StockLocationApi.getStockLocations', () => { }) await StockLocationApi.getStockLocations({ - active: true, + filter: 'active=true', search: 'main', - sortBy: 'name', - sortDirection: 'asc', - page: 1, + sort: ['name'], + pageNumber: 1, pageSize: 10, }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-locations', + '/api/admin/inventory/stock-locations', { filter: 'active=true', search: 'main', @@ -71,7 +70,7 @@ describe('StockLocationApi.getStockLocation', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'l-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockLocationApi.getStockLocation('l-1') - expect(mockGet).toHaveBeenCalledWith('api/inventory/stock-locations/l-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/stock-locations/l-1') }) }) @@ -80,7 +79,7 @@ describe('StockLocationApi.createStockLocation', () => { const req = { name: 'Main', active: true, default: false, backorderableDefault: true, propagateAllVariants: true, position: 0 } mockPost.mockResolvedValue({ value: { id: 'l-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await StockLocationApi.createStockLocation(req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-locations', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-locations', req) }) }) @@ -89,7 +88,7 @@ describe('StockLocationApi.updateStockLocation', () => { const req = { name: 'Main Store', active: true, default: false, backorderableDefault: true, propagateAllVariants: true, position: 1 } mockPut.mockResolvedValue({ value: { id: 'l-1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockLocationApi.updateStockLocation('l-1', req) - expect(mockPut).toHaveBeenCalledWith('api/inventory/stock-locations/l-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/inventory/stock-locations/l-1', req) }) }) @@ -97,7 +96,7 @@ describe('StockLocationApi.deleteStockLocation', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await StockLocationApi.deleteStockLocation('l-1') - expect(mockDel).toHaveBeenCalledWith('api/inventory/stock-locations/l-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/inventory/stock-locations/l-1') }) }) @@ -105,6 +104,6 @@ describe('StockLocationApi.setDefaultStockLocation', () => { it('calls PUT with default URL and no body', async () => { mockPut.mockResolvedValue({ value: { id: 'l-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockLocationApi.setDefaultStockLocation('l-1') - expect(mockPut).toHaveBeenCalledWith('api/inventory/stock-locations/l-1/default') + expect(mockPut).toHaveBeenCalledWith('/api/admin/inventory/stock-locations/l-1/default') }) }) diff --git a/app/Admin/src/features/inventory/__tests__/services/stockMovementApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/stockMovementApi.spec.ts index fc9136f3c..d93b57165 100644 --- a/app/Admin/src/features/inventory/__tests__/services/stockMovementApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/stockMovementApi.spec.ts @@ -44,7 +44,7 @@ describe('StockMovementApi.getStockMovements', () => { }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-movements?fromUtc=2026-01-01T08%3A30%3A00Z&toUtc=2026-01-31&variantId=v-1&stockLocationId=l-1', + '/api/admin/inventory/stock-movements?fromUtc=2026-01-01T08%3A30%3A00Z&toUtc=2026-01-31&variantId=v-1&stockLocationId=l-1', expect.objectContaining({ pageNumber: 1, pageSize: 10 }), expect.objectContaining({ allowedFilterFields: ['stockItemId', 'originatorType'], @@ -71,7 +71,7 @@ describe('StockMovementApi.getStockMovements', () => { await StockMovementApi.getStockMovements({ page: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-movements', + '/api/admin/inventory/stock-movements', expect.objectContaining({ pageNumber: 1, pageSize: 10 }), expect.any(Object), ) @@ -116,6 +116,6 @@ describe('StockMovementApi.getStockMovement', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'm-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockMovementApi.getStockMovement('m-1') - expect(mockGet).toHaveBeenCalledWith('api/inventory/stock-movements/m-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/stock-movements/m-1') }) }) diff --git a/app/Admin/src/features/inventory/__tests__/services/stockReservationApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/stockReservationApi.spec.ts index 6cbc685d0..feba5ec1c 100644 --- a/app/Admin/src/features/inventory/__tests__/services/stockReservationApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/stockReservationApi.spec.ts @@ -37,15 +37,15 @@ describe('StockReservationApi.getStockReservations', () => { }) await StockReservationApi.getStockReservations({ - state: 'Reserved', - sortBy: 'createdAtUtc', - sortDirection: 'desc', - page: 1, + filter: 'state=Reserved', + search: null, + sort: ['-createdAtUtc'], + pageNumber: 1, pageSize: 10, }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-reservations', + '/api/admin/inventory/stock-reservations', { filter: 'state=Reserved', search: null, @@ -66,7 +66,7 @@ describe('StockReservationApi.getStockReservation', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'r-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockReservationApi.getStockReservation('r-1') - expect(mockGet).toHaveBeenCalledWith('api/inventory/stock-reservations/r-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/stock-reservations/r-1') }) }) @@ -74,6 +74,6 @@ describe('StockReservationApi.cancelStockReservation', () => { it('calls POST with cancel URL and no body', async () => { mockPost.mockResolvedValue({ value: { id: 'r-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockReservationApi.cancelStockReservation('r-1') - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-reservations/r-1/cancel') + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-reservations/r-1/cancel') }) }) diff --git a/app/Admin/src/features/inventory/__tests__/services/stockTransferApi.spec.ts b/app/Admin/src/features/inventory/__tests__/services/stockTransferApi.spec.ts index ecb8d8dec..57139ce83 100644 --- a/app/Admin/src/features/inventory/__tests__/services/stockTransferApi.spec.ts +++ b/app/Admin/src/features/inventory/__tests__/services/stockTransferApi.spec.ts @@ -37,17 +37,15 @@ describe('StockTransferApi.getStockTransfers', () => { }) await StockTransferApi.getStockTransfers({ - state: 'InTransit', - sourceLocationId: 'l-1', - destinationLocationId: 'l-2', - sortBy: 'createdAtUtc', - sortDirection: 'desc', - page: 1, + filter: 'state=InTransit,sourceLocationId=l-1,destinationLocationId=l-2', + search: null, + sort: ['-createdAtUtc'], + pageNumber: 1, pageSize: 10, }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/inventory/stock-transfers', + '/api/admin/inventory/stock-transfers', { filter: 'state=InTransit,sourceLocationId=l-1,destinationLocationId=l-2', search: null, @@ -68,7 +66,7 @@ describe('StockTransferApi.getStockTransfer', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 't-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockTransferApi.getStockTransfer('t-1') - expect(mockGet).toHaveBeenCalledWith('api/inventory/stock-transfers/t-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/inventory/stock-transfers/t-1') }) }) @@ -77,7 +75,7 @@ describe('StockTransferApi.createStockTransfer', () => { const req = { reference: 'TR-1', sourceLocationId: 'l-1', destinationLocationId: 'l-2', items: [{ variantId: 'v-1', quantity: 5 }] } mockPost.mockResolvedValue({ value: { id: 't-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await StockTransferApi.createStockTransfer(req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-transfers', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-transfers', req) }) }) @@ -85,7 +83,7 @@ describe('StockTransferApi.transferStockTransfer', () => { it('calls POST with transfer URL and no body', async () => { mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockTransferApi.transferStockTransfer('t-1') - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-transfers/t-1/transfer') + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-transfers/t-1/transfer') }) }) @@ -94,7 +92,7 @@ describe('StockTransferApi.receiveStockTransfer', () => { const req = { items: [{ variantId: 'v-1', quantity: 5 }] } mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockTransferApi.receiveStockTransfer('t-1', req) - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-transfers/t-1/receive', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-transfers/t-1/receive', req) }) }) @@ -102,6 +100,6 @@ describe('StockTransferApi.cancelStockTransfer', () => { it('calls POST with cancel URL and no body', async () => { mockPost.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StockTransferApi.cancelStockTransfer('t-1') - expect(mockPost).toHaveBeenCalledWith('api/inventory/stock-transfers/t-1/cancel') + expect(mockPost).toHaveBeenCalledWith('/api/admin/inventory/stock-transfers/t-1/cancel') }) }) diff --git a/app/Admin/src/features/inventory/composables/__tests__/useActiveStockLocations.spec.ts b/app/Admin/src/features/inventory/composables/__tests__/useActiveStockLocations.spec.ts index 672e891a9..eb57b6f8d 100644 --- a/app/Admin/src/features/inventory/composables/__tests__/useActiveStockLocations.spec.ts +++ b/app/Admin/src/features/inventory/composables/__tests__/useActiveStockLocations.spec.ts @@ -25,7 +25,7 @@ describe('useActiveStockLocations', () => { await load() - expect(mockGetStockLocations).toHaveBeenCalledWith({ pageSize: 100, sortBy: 'name', sortDirection: 'asc' }) + expect(mockGetStockLocations).toHaveBeenCalledWith({ sort: ['name'], pageSize: 100 }) expect(items.value).toHaveLength(1) }) }) diff --git a/app/Admin/src/features/inventory/composables/useActiveStockLocations.ts b/app/Admin/src/features/inventory/composables/useActiveStockLocations.ts index 0114c3306..4edda56e8 100644 --- a/app/Admin/src/features/inventory/composables/useActiveStockLocations.ts +++ b/app/Admin/src/features/inventory/composables/useActiveStockLocations.ts @@ -5,6 +5,6 @@ import { StockLocationApi } from '../services/stockLocationApi' export function useActiveStockLocations() { // Call: Inventory service — active stock locations for filter and form Selects return useActiveList(() => - StockLocationApi.getStockLocations({ pageSize: 100, sortBy: 'name', sortDirection: 'asc' }), + StockLocationApi.getStockLocations({ sort: ['name'], pageSize: 100 }), ) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/composables/useStockItemList.ts b/app/Admin/src/features/inventory/composables/useStockItemList.ts index d165b3043..166d71a48 100644 --- a/app/Admin/src/features/inventory/composables/useStockItemList.ts +++ b/app/Admin/src/features/inventory/composables/useStockItemList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { INVENTORY } from '@/shared/constants/api' -import { STOCK_ITEM_FILTER_FIELDS, STOCK_ITEM_SORT_FIELDS, STOCK_ITEM_SEARCH_FIELDS } from '../types/stockItem' + +import { StockItemApi } from '../services/stockItemApi' import type { StockItemListItem } from '../types/stockItem' export function useStockItemList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${INVENTORY}/stock-items`, { - allowedFilterFields: STOCK_ITEM_FILTER_FIELDS, - allowedSortFields: STOCK_ITEM_SORT_FIELDS, - allowedSearchFields: STOCK_ITEM_SEARCH_FIELDS, + return usePagedQuery((params) => StockItemApi.getStockItems(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/composables/useStockLocationList.ts b/app/Admin/src/features/inventory/composables/useStockLocationList.ts index 4bb2fe527..e8be3f4ef 100644 --- a/app/Admin/src/features/inventory/composables/useStockLocationList.ts +++ b/app/Admin/src/features/inventory/composables/useStockLocationList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { INVENTORY } from '@/shared/constants/api' -import { STOCK_LOCATION_FILTER_FIELDS, STOCK_LOCATION_SORT_FIELDS, STOCK_LOCATION_SEARCH_FIELDS } from '../types/stockLocation' + +import { StockLocationApi } from '../services/stockLocationApi' import type { StockLocationListItem } from '../types/stockLocation' export function useStockLocationList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${INVENTORY}/stock-locations`, { - allowedFilterFields: STOCK_LOCATION_FILTER_FIELDS, - allowedSortFields: STOCK_LOCATION_SORT_FIELDS, - allowedSearchFields: STOCK_LOCATION_SEARCH_FIELDS, + return usePagedQuery((params) => StockLocationApi.getStockLocations(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/composables/useStockMovementList.ts b/app/Admin/src/features/inventory/composables/useStockMovementList.ts index 919e054df..892470404 100644 --- a/app/Admin/src/features/inventory/composables/useStockMovementList.ts +++ b/app/Admin/src/features/inventory/composables/useStockMovementList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { INVENTORY } from '@/shared/constants/api' -import { STOCK_MOVEMENT_FILTER_FIELDS, STOCK_MOVEMENT_SORT_FIELDS, STOCK_MOVEMENT_SEARCH_FIELDS } from '../types/stockMovement' -import type { StockMovementListItem } from '../types/stockMovement' + +import { StockMovementApi } from '../services/stockMovementApi' +import type { StockMovementListItem, StockMovementQuery } from '../types/stockMovement' export function useStockMovementList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${INVENTORY}/stock-movements`, { - allowedFilterFields: STOCK_MOVEMENT_FILTER_FIELDS, - allowedSortFields: STOCK_MOVEMENT_SORT_FIELDS, - allowedSearchFields: STOCK_MOVEMENT_SEARCH_FIELDS, + return usePagedQuery((params) => StockMovementApi.getStockMovements(params as StockMovementQuery), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/composables/useStockReservationList.ts b/app/Admin/src/features/inventory/composables/useStockReservationList.ts index 766f3d492..28d5311a6 100644 --- a/app/Admin/src/features/inventory/composables/useStockReservationList.ts +++ b/app/Admin/src/features/inventory/composables/useStockReservationList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { INVENTORY } from '@/shared/constants/api' -import { STOCK_RESERVATION_FILTER_FIELDS, STOCK_RESERVATION_SORT_FIELDS, STOCK_RESERVATION_SEARCH_FIELDS } from '../types/stockReservation' + +import { StockReservationApi } from '../services/stockReservationApi' import type { StockReservationListItem } from '../types/stockReservation' export function useStockReservationList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${INVENTORY}/stock-reservations`, { - allowedFilterFields: STOCK_RESERVATION_FILTER_FIELDS, - allowedSortFields: STOCK_RESERVATION_SORT_FIELDS, - allowedSearchFields: STOCK_RESERVATION_SEARCH_FIELDS, + return usePagedQuery((params) => StockReservationApi.getStockReservations(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/composables/useStockTransferList.ts b/app/Admin/src/features/inventory/composables/useStockTransferList.ts index 73bb50a5c..a949f6ac9 100644 --- a/app/Admin/src/features/inventory/composables/useStockTransferList.ts +++ b/app/Admin/src/features/inventory/composables/useStockTransferList.ts @@ -1,14 +1,11 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { INVENTORY } from '@/shared/constants/api' -import { STOCK_TRANSFER_FILTER_FIELDS, STOCK_TRANSFER_SORT_FIELDS, STOCK_TRANSFER_SEARCH_FIELDS } from '../types/stockTransfer' + +import { StockTransferApi } from '../services/stockTransferApi' import type { StockTransferListItem } from '../types/stockTransfer' export function useStockTransferList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${INVENTORY}/stock-transfers`, { - allowedFilterFields: STOCK_TRANSFER_FILTER_FIELDS, - allowedSortFields: STOCK_TRANSFER_SORT_FIELDS, - allowedSearchFields: STOCK_TRANSFER_SEARCH_FIELDS, + return usePagedQuery((params) => StockTransferApi.getStockTransfers(params), { ...options, }) -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/services/inventoryDashboardApi.ts b/app/Admin/src/features/inventory/services/inventoryDashboardApi.ts index d9682a43b..af196e17e 100644 --- a/app/Admin/src/features/inventory/services/inventoryDashboardApi.ts +++ b/app/Admin/src/features/inventory/services/inventoryDashboardApi.ts @@ -1,12 +1,10 @@ import { get } from '@/shared/api/client' -import { INVENTORY } from '@/shared/constants/api' + import type { Result } from '@/shared/types' import type { InventoryDashboard } from '../types/inventoryDashboard' export class InventoryDashboardApi { - private static readonly BASE = `${INVENTORY}/dashboard` - static getInventoryDashboard(): Promise> { - return get>(InventoryDashboardApi.BASE) + return get>('/api/admin/inventory/dashboard') } } diff --git a/app/Admin/src/features/inventory/services/stockItemApi.ts b/app/Admin/src/features/inventory/services/stockItemApi.ts index 12894e341..9d9474a1e 100644 --- a/app/Admin/src/features/inventory/services/stockItemApi.ts +++ b/app/Admin/src/features/inventory/services/stockItemApi.ts @@ -1,12 +1,11 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { INVENTORY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { StockItemRequest, StockItemListItem, StockItemDetail, - StockItemQuery, BulkAdjustStockItemsRequest, RestockRequest, RestockResultResponse, @@ -16,17 +15,14 @@ import type { ImportStockItemsResponse, } from '../types/stockItem' import { - toStockItemQueryParams, STOCK_ITEM_FILTER_FIELDS, STOCK_ITEM_SORT_FIELDS, STOCK_ITEM_SEARCH_FIELDS, } from '../types/stockItem' export class StockItemApi { - private static readonly BASE = `${INVENTORY}/stock-items` - - static getStockItems(query: StockItemQuery): Promise> { - return getPaged(StockItemApi.BASE, toStockItemQueryParams(query), { + static getStockItems(params: QueryingParameters): Promise> { + return getPaged('/api/admin/inventory/stock-items', params, { allowedFilterFields: STOCK_ITEM_FILTER_FIELDS, allowedSortFields: STOCK_ITEM_SORT_FIELDS, allowedSearchFields: STOCK_ITEM_SEARCH_FIELDS, @@ -34,34 +30,34 @@ export class StockItemApi { } static getStockItem(id: string): Promise> { - return get>(`${StockItemApi.BASE}/${id}`) + return get>(`/api/admin/inventory/stock-items/${id}`) } static createStockItem(request: StockItemRequest): Promise> { - return post>(StockItemApi.BASE, request) + return post>('/api/admin/inventory/stock-items', request) } static updateStockItem(id: string, request: StockItemRequest): Promise> { - return put>(`${StockItemApi.BASE}/${id}`, request) + return put>(`/api/admin/inventory/stock-items/${id}`, request) } static deleteStockItem(id: string): Promise> { - return del>(`${StockItemApi.BASE}/${id}`) + return del>(`/api/admin/inventory/stock-items/${id}`) } static bulkAdjustStockItems(request: BulkAdjustStockItemsRequest): Promise> { - return post>(`${StockItemApi.BASE}/bulk-adjust`, request) + return post>('/api/admin/inventory/stock-items/bulk-adjust', request) } static restockStockItem(id: string, request: RestockRequest): Promise> { - return post>(`${StockItemApi.BASE}/${id}/restock`, request) + return post>(`/api/admin/inventory/stock-items/${id}/restock`, request) } static getLowStockItems(params: LowStockQuery): Promise> { const parts: string[] = [] if (params.locationId !== undefined) parts.push(`locationId=${params.locationId}`) if (params.threshold !== undefined) parts.push(`threshold=${params.threshold}`) - const url = `${StockItemApi.BASE}/low-stock${parts.length ? `?${parts.join('&')}` : ''}` + const url = `/api/admin/inventory/stock-items/low-stock${parts.length ? `?${parts.join('&')}` : ''}` return getPaged(url, { pageNumber: params.page ?? null, pageSize: params.pageSize ?? null, @@ -69,7 +65,7 @@ export class StockItemApi { } static getStockSummary(query: { page?: number; pageSize?: number }): Promise> { - return getPaged(`${StockItemApi.BASE}/summary`, { + return getPaged('/api/admin/inventory/stock-items/summary', { pageNumber: query.page ?? null, pageSize: query.pageSize ?? null, }) @@ -78,6 +74,6 @@ export class StockItemApi { static importStockItems(file: File): Promise> { const formData = new FormData() formData.append('file', file) - return post>(`${StockItemApi.BASE}/import`, formData) + return post>('/api/admin/inventory/stock-items/import', formData) } } diff --git a/app/Admin/src/features/inventory/services/stockLocationApi.ts b/app/Admin/src/features/inventory/services/stockLocationApi.ts index af22da635..1b73fea04 100644 --- a/app/Admin/src/features/inventory/services/stockLocationApi.ts +++ b/app/Admin/src/features/inventory/services/stockLocationApi.ts @@ -1,25 +1,21 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { INVENTORY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { StockLocationRequest, StockLocationListItem, StockLocationDetail, - StockLocationQuery, } from '../types/stockLocation' import { - toStockLocationQueryParams, STOCK_LOCATION_FILTER_FIELDS, STOCK_LOCATION_SORT_FIELDS, STOCK_LOCATION_SEARCH_FIELDS, } from '../types/stockLocation' export class StockLocationApi { - private static readonly BASE = `${INVENTORY}/stock-locations` - - static getStockLocations(query: StockLocationQuery): Promise> { - return getPaged(StockLocationApi.BASE, toStockLocationQueryParams(query), { + static getStockLocations(params: QueryingParameters): Promise> { + return getPaged('/api/admin/inventory/stock-locations', params, { allowedFilterFields: STOCK_LOCATION_FILTER_FIELDS, allowedSortFields: STOCK_LOCATION_SORT_FIELDS, allowedSearchFields: STOCK_LOCATION_SEARCH_FIELDS, @@ -27,22 +23,22 @@ export class StockLocationApi { } static getStockLocation(id: string): Promise> { - return get>(`${StockLocationApi.BASE}/${id}`) + return get>(`/api/admin/inventory/stock-locations/${id}`) } static createStockLocation(request: StockLocationRequest): Promise> { - return post>(StockLocationApi.BASE, request) + return post>('/api/admin/inventory/stock-locations', request) } static updateStockLocation(id: string, request: StockLocationRequest): Promise> { - return put>(`${StockLocationApi.BASE}/${id}`, request) + return put>(`/api/admin/inventory/stock-locations/${id}`, request) } static deleteStockLocation(id: string): Promise> { - return del>(`${StockLocationApi.BASE}/${id}`) + return del>(`/api/admin/inventory/stock-locations/${id}`) } static setDefaultStockLocation(id: string): Promise> { - return put>(`${StockLocationApi.BASE}/${id}/default`) + return put>(`/api/admin/inventory/stock-locations/${id}/default`) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/services/stockMovementApi.ts b/app/Admin/src/features/inventory/services/stockMovementApi.ts index 67bc1d9e8..aa04e3b48 100644 --- a/app/Admin/src/features/inventory/services/stockMovementApi.ts +++ b/app/Admin/src/features/inventory/services/stockMovementApi.ts @@ -1,6 +1,6 @@ import { get } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { INVENTORY } from '@/shared/constants/api' + import type { Result, PagedResult } from '@/shared/types' import type { StockMovementQuery, @@ -15,15 +15,13 @@ import { } from '../types/stockMovement' export class StockMovementApi { - private static readonly BASE = `${INVENTORY}/stock-movements` - static getStockMovements(query: StockMovementQuery): Promise> { const parts: string[] = [] if (query.fromUtc !== undefined) parts.push(`fromUtc=${encodeURIComponent(query.fromUtc)}`) if (query.toUtc !== undefined) parts.push(`toUtc=${encodeURIComponent(query.toUtc)}`) if (query.variantId !== undefined) parts.push(`variantId=${query.variantId}`) if (query.stockLocationId !== undefined) parts.push(`stockLocationId=${query.stockLocationId}`) - const url = `${StockMovementApi.BASE}${parts.length ? `?${parts.join('&')}` : ''}` + const url = `/api/admin/inventory/stock-movements${parts.length ? `?${parts.join('&')}` : ''}` const { fromUtc: _fromUtc, toUtc: _toUtc, variantId: _variantId, stockLocationId: _stockLocationId, ...rest } = query return getPaged(url, toStockMovementQueryParams(rest as StockMovementQuery), { @@ -34,6 +32,6 @@ export class StockMovementApi { } static getStockMovement(id: string): Promise> { - return get>(`${StockMovementApi.BASE}/${id}`) + return get>(`/api/admin/inventory/stock-movements/${id}`) } } diff --git a/app/Admin/src/features/inventory/services/stockReservationApi.ts b/app/Admin/src/features/inventory/services/stockReservationApi.ts index 7f001fea9..e2db99730 100644 --- a/app/Admin/src/features/inventory/services/stockReservationApi.ts +++ b/app/Admin/src/features/inventory/services/stockReservationApi.ts @@ -1,20 +1,17 @@ import { getPaged } from '@/shared/api' import { get, post } from '@/shared/api/client' -import { INVENTORY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' -import type { StockReservationQuery, StockReservationListItem, StockReservationDetail } from '../types/stockReservation' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' +import type { StockReservationListItem, StockReservationDetail } from '../types/stockReservation' import { - toStockReservationQueryParams, STOCK_RESERVATION_FILTER_FIELDS, STOCK_RESERVATION_SORT_FIELDS, STOCK_RESERVATION_SEARCH_FIELDS, } from '../types/stockReservation' export class StockReservationApi { - private static readonly BASE = `${INVENTORY}/stock-reservations` - - static getStockReservations(query: StockReservationQuery): Promise> { - return getPaged(StockReservationApi.BASE, toStockReservationQueryParams(query), { + static getStockReservations(params: QueryingParameters): Promise> { + return getPaged('/api/admin/inventory/stock-reservations', params, { allowedFilterFields: STOCK_RESERVATION_FILTER_FIELDS, allowedSortFields: STOCK_RESERVATION_SORT_FIELDS, allowedSearchFields: STOCK_RESERVATION_SEARCH_FIELDS, @@ -22,10 +19,10 @@ export class StockReservationApi { } static getStockReservation(id: string): Promise> { - return get>(`${StockReservationApi.BASE}/${id}`) + return get>(`/api/admin/inventory/stock-reservations/${id}`) } static cancelStockReservation(id: string): Promise> { - return post>(`${StockReservationApi.BASE}/${id}/cancel`) + return post>(`/api/admin/inventory/stock-reservations/${id}/cancel`) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/services/stockTransferApi.ts b/app/Admin/src/features/inventory/services/stockTransferApi.ts index ec76a8d6e..852c6aec1 100644 --- a/app/Admin/src/features/inventory/services/stockTransferApi.ts +++ b/app/Admin/src/features/inventory/services/stockTransferApi.ts @@ -1,26 +1,22 @@ import { getPaged } from '@/shared/api' import { get, post } from '@/shared/api/client' -import { INVENTORY } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { - StockTransferQuery, StockTransferListItem, StockTransferDetail, StockTransferRequest, StockTransferReceiveRequest, } from '../types/stockTransfer' import { - toStockTransferQueryParams, STOCK_TRANSFER_FILTER_FIELDS, STOCK_TRANSFER_SORT_FIELDS, STOCK_TRANSFER_SEARCH_FIELDS, } from '../types/stockTransfer' export class StockTransferApi { - private static readonly BASE = `${INVENTORY}/stock-transfers` - - static getStockTransfers(query: StockTransferQuery): Promise> { - return getPaged(StockTransferApi.BASE, toStockTransferQueryParams(query), { + static getStockTransfers(params: QueryingParameters): Promise> { + return getPaged('/api/admin/inventory/stock-transfers', params, { allowedFilterFields: STOCK_TRANSFER_FILTER_FIELDS, allowedSortFields: STOCK_TRANSFER_SORT_FIELDS, allowedSearchFields: STOCK_TRANSFER_SEARCH_FIELDS, @@ -28,22 +24,22 @@ export class StockTransferApi { } static getStockTransfer(id: string): Promise> { - return get>(`${StockTransferApi.BASE}/${id}`) + return get>(`/api/admin/inventory/stock-transfers/${id}`) } static createStockTransfer(request: StockTransferRequest): Promise> { - return post>(StockTransferApi.BASE, request) + return post>('/api/admin/inventory/stock-transfers', request) } static transferStockTransfer(id: string): Promise> { - return post>(`${StockTransferApi.BASE}/${id}/transfer`) + return post>(`/api/admin/inventory/stock-transfers/${id}/transfer`) } static receiveStockTransfer(id: string, request: StockTransferReceiveRequest): Promise> { - return post>(`${StockTransferApi.BASE}/${id}/receive`, request) + return post>(`/api/admin/inventory/stock-transfers/${id}/receive`, request) } static cancelStockTransfer(id: string): Promise> { - return post>(`${StockTransferApi.BASE}/${id}/cancel`) + return post>(`/api/admin/inventory/stock-transfers/${id}/cancel`) } -} +} \ No newline at end of file diff --git a/app/Admin/src/features/inventory/types/stockItem.ts b/app/Admin/src/features/inventory/types/stockItem.ts index adffd3eef..e1a950550 100644 --- a/app/Admin/src/features/inventory/types/stockItem.ts +++ b/app/Admin/src/features/inventory/types/stockItem.ts @@ -86,7 +86,7 @@ export interface RestockResultResponse { previousCountOnHand: number newCountOnHand: number backordersFulfilled: number - partiallyFulfilled: boolean + partiallyFulfilled: number remainingQuantity: number movementId: string | null } @@ -125,5 +125,5 @@ export interface LowStockQuery { export interface LowStockItem extends StockItemListItem { locationName: string threshold: number - status: 'low' | 'out_of_stock' + status: 'Low' | 'OutOfStock' } diff --git a/app/Admin/src/features/inventory/types/stockTransfer.ts b/app/Admin/src/features/inventory/types/stockTransfer.ts index 914f02135..876a2736c 100644 --- a/app/Admin/src/features/inventory/types/stockTransfer.ts +++ b/app/Admin/src/features/inventory/types/stockTransfer.ts @@ -20,7 +20,7 @@ export interface StockTransferListItem { reference?: string sourceLocationId: string destinationLocationId: string - state: StockTransferState + state?: StockTransferState totalItems: number createdAtUtc: string } @@ -31,10 +31,11 @@ export interface StockTransferDetail { reference?: string sourceLocationId: string destinationLocationId: string - state: StockTransferState + state?: StockTransferState createdAtUtc: string modifiedAtUtc?: string items: { + id: string variantId: string quantity: number receivedQuantity: number diff --git a/app/Admin/src/features/inventory/views/StockItemsList.vue b/app/Admin/src/features/inventory/views/StockItemsList.vue index 4086862ed..fba1ab7e0 100644 --- a/app/Admin/src/features/inventory/views/StockItemsList.vue +++ b/app/Admin/src/features/inventory/views/StockItemsList.vue @@ -12,7 +12,7 @@ import InputIcon from 'primevue/inputicon' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' -import { INVENTORY } from '@/shared/constants/api' + import { StockItemApi } from '../services/stockItemApi' import { useActiveStockLocations } from '../composables/useActiveStockLocations' import type { StockItemListItem } from '../types/stockItem' @@ -31,7 +31,7 @@ const selectedItems = ref([]) loadActiveStockLocations() const { items, loading, setSearch, setFilter, refresh } = usePagedQuery( - `${INVENTORY}/stock-items`, + `/api/admin/inventory/stock-items`, { allowedFilterFields: STOCK_ITEM_FILTER_FIELDS, allowedSortFields: STOCK_ITEM_SORT_FIELDS, diff --git a/app/Admin/src/features/inventory/views/StockMovementsList.vue b/app/Admin/src/features/inventory/views/StockMovementsList.vue index 330781f74..cd7a524fe 100644 --- a/app/Admin/src/features/inventory/views/StockMovementsList.vue +++ b/app/Admin/src/features/inventory/views/StockMovementsList.vue @@ -13,6 +13,7 @@ import type { StockMovementListItem } from '../types/stockMovement' const { dt, exportCSV } = useDataTableExport() const search = ref('') +const selectedItems = ref([]) const { items, loading, setSearch, refresh } = useStockMovementList({ defaultSearchFields: ['reason'], @@ -90,12 +91,14 @@ function originatorLabel(item: StockMovementListItem): string { ref="dt" :value="items" :loading="loading" + v-model:selection="selectedItems" scrollable paginator :rows="20" :rows-per-page-options="[10, 20, 50]" data-key="id" > + diff --git a/app/Admin/src/features/inventory/views/StockReservationsList.vue b/app/Admin/src/features/inventory/views/StockReservationsList.vue index cfa16632b..36eeb07eb 100644 --- a/app/Admin/src/features/inventory/views/StockReservationsList.vue +++ b/app/Admin/src/features/inventory/views/StockReservationsList.vue @@ -12,10 +12,12 @@ import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { formatDateTimeUtc } from '@/shared/utils/date' import { useStockReservationList } from '../composables/useStockReservationList' import type { ReservationState } from '../types/stockReservation' +import type { StockReservationListItem } from '../types/stockReservation' const { dt, exportCSV } = useDataTableExport() const search = ref('') const selectedState = ref(null) +const selectedItems = ref([]) const { items, loading, setFilter, refresh } = useStockReservationList() @@ -88,12 +90,14 @@ function stateSeverity(state: ReservationState): string { ref="dt" :value="items" :loading="loading" + v-model:selection="selectedItems" scrollable paginator :rows="20" :rows-per-page-options="[10, 20, 50]" data-key="id" > + diff --git a/app/Admin/src/features/inventory/views/StockTransferDetail.vue b/app/Admin/src/features/inventory/views/StockTransferDetail.vue index d15b6de30..9be230778 100644 --- a/app/Admin/src/features/inventory/views/StockTransferDetail.vue +++ b/app/Admin/src/features/inventory/views/StockTransferDetail.vue @@ -163,8 +163,8 @@ const STATE_SEVERITY: Record = { Canceled: 'danger', } -function stateSeverity(state: StockTransferState): string { - return STATE_SEVERITY[state] +function stateSeverity(state: StockTransferState | undefined): string { + return state ? STATE_SEVERITY[state] : 'secondary' } function locationName(locationId: string): string { @@ -373,7 +373,7 @@ watch(
Items
- + diff --git a/app/Admin/src/features/inventory/views/StockTransfersList.vue b/app/Admin/src/features/inventory/views/StockTransfersList.vue index b1338b99c..6615d53f7 100644 --- a/app/Admin/src/features/inventory/views/StockTransfersList.vue +++ b/app/Admin/src/features/inventory/views/StockTransfersList.vue @@ -14,6 +14,7 @@ import { formatDateTimeUtc } from '@/shared/utils/date' import { useStockTransferList } from '../composables/useStockTransferList' import { useActiveStockLocations } from '../composables/useActiveStockLocations' import type { StockTransferState } from '../types/stockTransfer' +import type { StockTransferListItem } from '../types/stockTransfer' const router = useRouter() const { dt, exportCSV } = useDataTableExport() @@ -22,6 +23,7 @@ const search = ref('') const selectedState = ref(null) const selectedSourceLocation = ref(null) const selectedDestinationLocation = ref(null) +const selectedItems = ref([]) const { items, loading, setFilter, refresh } = useStockTransferList() @@ -66,8 +68,8 @@ function onDestinationLocationChange(value: string | null) { applyFilters() } -function stateSeverity(state: StockTransferState): string { - return STATE_SEVERITY[state] +function stateSeverity(state: StockTransferState | undefined): string { + return state ? STATE_SEVERITY[state] : 'secondary' } function navigateToNew() { @@ -148,12 +150,14 @@ function navigateToEdit(id: string) { ref="dt" :value="items" :loading="loading" + v-model:selection="selectedItems" scrollable paginator :rows="20" :rows-per-page-options="[10, 20, 50]" data-key="id" > + diff --git a/app/Admin/src/features/location/composables/__tests__/useActiveCountries.spec.ts b/app/Admin/src/features/location/composables/__tests__/useActiveCountries.spec.ts deleted file mode 100644 index f14311442..000000000 --- a/app/Admin/src/features/location/composables/__tests__/useActiveCountries.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { useActiveCountries } from '../useActiveCountries' -import { CountryApi } from '../../services/countryApi' -import type { PagedResult } from '@/shared/types/result' -import type { CountryListItem } from '../../types/country' - -vi.mock('../../services/countryApi', () => ({ - CountryApi: { getCountries: vi.fn<() => Promise>>() }, -})) - -const mockGetCountries = vi.mocked(CountryApi.getCountries) - -function okResult(items: CountryListItem[] = [{ id: 'us', name: 'United States', isoCode: 'US', callingCode: '+1', statesRequired: true, isActive: true }]): PagedResult { - return { isSuccess: true, statusCode: 200, items, page: 1, pageSize: 20, totalCount: items.length, totalPages: 1, errors: [], message: null, metadata: null } -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('useActiveCountries', () => { - it('loads active countries via the CountryApi', async () => { - mockGetCountries.mockResolvedValue(okResult()) - const { items, load } = useActiveCountries() - - await load() - - expect(mockGetCountries).toHaveBeenCalledWith({ isActive: true }) - expect(items.value).toHaveLength(1) - expect(items.value[0]!.name).toBe('United States') - }) -}) diff --git a/app/Admin/src/features/location/composables/index.ts b/app/Admin/src/features/location/composables/index.ts deleted file mode 100644 index 8e8d1c50e..000000000 --- a/app/Admin/src/features/location/composables/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { useActiveCountries } from './useActiveCountries' diff --git a/app/Admin/src/features/location/composables/useActiveCountries.ts b/app/Admin/src/features/location/composables/useActiveCountries.ts deleted file mode 100644 index 47ec4a231..000000000 --- a/app/Admin/src/features/location/composables/useActiveCountries.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { useActiveList } from '@/shared/composables' -import type { CountryListItem } from '../types/country' -import { CountryApi } from '../services/countryApi' - -export function useActiveCountries() { - // Call: Location service — active countries for form Select options - return useActiveList(() => CountryApi.getCountries({ isActive: true })) -} diff --git a/app/Admin/src/features/location/index.ts b/app/Admin/src/features/location/index.ts index 198f04f5c..875ea1634 100644 --- a/app/Admin/src/features/location/index.ts +++ b/app/Admin/src/features/location/index.ts @@ -1,7 +1,6 @@ // Feature: location // Barrel re-exports export * from './components' -export * from './composables' export * from './routes' export * from './validations' export * from './services' diff --git a/app/Admin/src/features/location/services/__tests__/countryApi.spec.ts b/app/Admin/src/features/location/services/__tests__/countryApi.spec.ts index 5cf9cd38f..b84a1188b 100644 --- a/app/Admin/src/features/location/services/__tests__/countryApi.spec.ts +++ b/app/Admin/src/features/location/services/__tests__/countryApi.spec.ts @@ -40,11 +40,11 @@ describe('CountryApi.getCountries', () => { metadata: null, }) - await CountryApi.getCountries({ isActive: true, page: 1, pageSize: 10 }) + await CountryApi.getCountries({ filter: 'isActive=true', pageNumber: 1, pageSize: 10 }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/locations/countries', - { filter: 'isActive=true', search: null, sort: null, pageNumber: 1, pageSize: 10 }, + '/api/admin/location/countries', + { filter: 'isActive=true', pageNumber: 1, pageSize: 10 }, expect.objectContaining({ allowedFilterFields: expect.any(Array) }), ) }) @@ -55,7 +55,7 @@ describe('CountryApi.getCountry', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'US' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await CountryApi.getCountry('abc-123') - expect(mockGet).toHaveBeenCalledWith('api/locations/countries/abc-123') + expect(mockGet).toHaveBeenCalledWith('/api/admin/location/countries/abc-123') }) }) @@ -64,7 +64,7 @@ describe('CountryApi.getCountryByIso', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'United States', isoCode: 'US' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await CountryApi.getCountryByIso('US') - expect(mockGet).toHaveBeenCalledWith('api/locations/countries/by-iso/US') + expect(mockGet).toHaveBeenCalledWith('/api/admin/location/countries/by-iso/US') }) }) @@ -74,7 +74,7 @@ describe('CountryApi.createCountry', () => { mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await CountryApi.createCountry(req) - expect(mockPost).toHaveBeenCalledWith('api/locations/countries', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/location/countries', req) }) }) @@ -84,7 +84,7 @@ describe('CountryApi.updateCountry', () => { mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await CountryApi.updateCountry('abc-123', req) - expect(mockPut).toHaveBeenCalledWith('api/locations/countries/abc-123', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/location/countries/abc-123', req) }) }) @@ -93,6 +93,6 @@ describe('CountryApi.deleteCountry', () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Canada' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await CountryApi.deleteCountry('abc-123') - expect(mockDel).toHaveBeenCalledWith('api/locations/countries/abc-123') + expect(mockDel).toHaveBeenCalledWith('/api/admin/location/countries/abc-123') }) }) diff --git a/app/Admin/src/features/location/services/__tests__/stateApi.spec.ts b/app/Admin/src/features/location/services/__tests__/stateApi.spec.ts index ad70086f0..0612e31a6 100644 --- a/app/Admin/src/features/location/services/__tests__/stateApi.spec.ts +++ b/app/Admin/src/features/location/services/__tests__/stateApi.spec.ts @@ -40,10 +40,10 @@ describe('StateApi.getStates', () => { metadata: null, }) - await StateApi.getStates({ countryId: 'abc-123' }) + await StateApi.getStates({ filter: 'countryId=abc-123' }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/locations/states', + '/api/admin/location/states', expect.objectContaining({ filter: 'countryId=abc-123' }), expect.any(Object), ) @@ -55,7 +55,7 @@ describe('StateApi.getState', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'California' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StateApi.getState('xyz-456') - expect(mockGet).toHaveBeenCalledWith('api/locations/states/xyz-456') + expect(mockGet).toHaveBeenCalledWith('/api/admin/location/states/xyz-456') }) }) @@ -64,7 +64,7 @@ describe('StateApi.getStateByIso', () => { mockGet.mockResolvedValue({ value: { id: '1', name: 'New York', abbreviation: 'NY' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StateApi.getStateByIso('NY') - expect(mockGet).toHaveBeenCalledWith('api/locations/states/by-iso/NY') + expect(mockGet).toHaveBeenCalledWith('/api/admin/location/states/by-iso/NY') }) }) @@ -74,7 +74,7 @@ describe('StateApi.createState', () => { mockPost.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await StateApi.createState(req) - expect(mockPost).toHaveBeenCalledWith('api/locations/states', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/location/states', req) }) }) @@ -84,7 +84,7 @@ describe('StateApi.updateState', () => { mockPut.mockResolvedValue({ value: { id: '1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StateApi.updateState('xyz-456', req) - expect(mockPut).toHaveBeenCalledWith('api/locations/states/xyz-456', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/location/states/xyz-456', req) }) }) @@ -93,6 +93,6 @@ describe('StateApi.deleteState', () => { mockDel.mockResolvedValue({ value: { id: '1', name: 'Texas' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await StateApi.deleteState('xyz-456') - expect(mockDel).toHaveBeenCalledWith('api/locations/states/xyz-456') + expect(mockDel).toHaveBeenCalledWith('/api/admin/location/states/xyz-456') }) }) diff --git a/app/Admin/src/features/location/services/countryApi.ts b/app/Admin/src/features/location/services/countryApi.ts index be48812da..0ae637fbf 100644 --- a/app/Admin/src/features/location/services/countryApi.ts +++ b/app/Admin/src/features/location/services/countryApi.ts @@ -1,46 +1,43 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { LOCATION } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { CountryRequest, CountryListItem, CountryDetail, - CountryQuery, } from '../types/country' import { - toCountryQueryParams, COUNTRY_FILTER_FIELDS, COUNTRY_SORT_FIELDS, } from '../types/country' export class CountryApi { - private static readonly BASE = `${LOCATION}/countries` - - static getCountries(query: CountryQuery): Promise> { - return getPaged(CountryApi.BASE, toCountryQueryParams(query), { + static getCountries(params: QueryingParameters): Promise> { + return getPaged('/api/admin/location/countries', params, { allowedFilterFields: COUNTRY_FILTER_FIELDS, allowedSortFields: COUNTRY_SORT_FIELDS, + allowedSearchFields: COUNTRY_FILTER_FIELDS, }) } static getCountry(id: string): Promise> { - return get>(`${CountryApi.BASE}/${id}`) + return get>(`/api/admin/location/countries/${id}`) } static getCountryByIso(isoCode: string): Promise> { - return get>(`${CountryApi.BASE}/by-iso/${isoCode}`) + return get>(`/api/admin/location/countries/by-iso/${isoCode}`) } static createCountry(request: CountryRequest): Promise> { - return post>(CountryApi.BASE, request) + return post>('/api/admin/location/countries', request) } static updateCountry(id: string, request: CountryRequest): Promise> { - return put>(`${CountryApi.BASE}/${id}`, request) + return put>(`/api/admin/location/countries/${id}`, request) } static deleteCountry(id: string): Promise> { - return del>(`${CountryApi.BASE}/${id}`) + return del>(`/api/admin/location/countries/${id}`) } } diff --git a/app/Admin/src/features/location/services/stateApi.ts b/app/Admin/src/features/location/services/stateApi.ts index c6618cf60..28e295782 100644 --- a/app/Admin/src/features/location/services/stateApi.ts +++ b/app/Admin/src/features/location/services/stateApi.ts @@ -1,46 +1,43 @@ import { post, get, put, del } from '@/shared/api/client' import { getPaged } from '@/shared/api' -import { LOCATION } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { StateRequest, StateListItem, StateDetail, - StateQuery, } from '../types/state' import { - toStateQueryParams, STATE_FILTER_FIELDS, STATE_SORT_FIELDS, } from '../types/state' export class StateApi { - private static readonly BASE = `${LOCATION}/states` - - static getStates(query: StateQuery): Promise> { - return getPaged(StateApi.BASE, toStateQueryParams(query), { + static getStates(params: QueryingParameters): Promise> { + return getPaged('/api/admin/location/states', params, { allowedFilterFields: STATE_FILTER_FIELDS, allowedSortFields: STATE_SORT_FIELDS, + allowedSearchFields: STATE_FILTER_FIELDS, }) } static getState(id: string): Promise> { - return get>(`${StateApi.BASE}/${id}`) + return get>(`/api/admin/location/states/${id}`) } static getStateByIso(isoCode: string): Promise> { - return get>(`${StateApi.BASE}/by-iso/${isoCode}`) + return get>(`/api/admin/location/states/by-iso/${isoCode}`) } static createState(request: StateRequest): Promise> { - return post>(StateApi.BASE, request) + return post>('/api/admin/location/states', request) } static updateState(id: string, request: StateRequest): Promise> { - return put>(`${StateApi.BASE}/${id}`, request) + return put>(`/api/admin/location/states/${id}`, request) } static deleteState(id: string): Promise> { - return del>(`${StateApi.BASE}/${id}`) + return del>(`/api/admin/location/states/${id}`) } } diff --git a/app/Admin/src/features/location/views/CountriesList.vue b/app/Admin/src/features/location/views/CountriesList.vue index 1d016b529..3adecadd1 100644 --- a/app/Admin/src/features/location/views/CountriesList.vue +++ b/app/Admin/src/features/location/views/CountriesList.vue @@ -11,7 +11,7 @@ import { usePagedQuery } from '@/shared/composables/usePagedQuery' import { useNotify } from '@/shared/composables/useNotify' import { CountryApi } from '../services/countryApi' import type { CountryListItem } from '../types/country' -import { COUNTRY_FILTER_FIELDS, COUNTRY_SORT_FIELDS } from '../types/country' +import { COUNTRY_FILTER_FIELDS } from '../types/country' const router = useRouter() const confirm = useConfirm() @@ -32,10 +32,7 @@ const { setPageSize, setSort, refresh, -} = usePagedQuery('api/locations/countries', { - allowedFilterFields: COUNTRY_FILTER_FIELDS, - allowedSortFields: COUNTRY_SORT_FIELDS, - allowedSearchFields: COUNTRY_FILTER_FIELDS, +} = usePagedQuery((params) => CountryApi.getCountries(params), { defaultSearchFields: COUNTRY_FILTER_FIELDS, defaultSearchMode: 'any', defaultSort: ['name'], diff --git a/app/Admin/src/features/location/views/StateDetail.vue b/app/Admin/src/features/location/views/StateDetail.vue index 23de779e8..4861ee49a 100644 --- a/app/Admin/src/features/location/views/StateDetail.vue +++ b/app/Admin/src/features/location/views/StateDetail.vue @@ -8,8 +8,11 @@ import { zodResolver } from '@primevue/forms/resolvers/zod' import type { FormSubmitEvent } from '@primevue/forms' import { useNotify } from '@/shared/composables/useNotify' import { useApiErrorHandler } from '@/shared/composables/useApiErrorHandler' +import { useActiveList } from '@/shared/composables' import { StateApi } from '../services/stateApi' -import { useActiveCountries } from '../composables/useActiveCountries' +import { CountryApi } from '../services/countryApi' +import type { CountryListItem } from '../types/country' +import { toCountryQueryParams } from '../types/country' import { stateSchema, stateName, stateAbbreviation, stateCountryId } from '../validations/state' import type { StateForm } from '../validations/state' @@ -17,7 +20,7 @@ const route = useRoute() const router = useRouter() const notify = useNotify() const { handleResult } = useApiErrorHandler() -const { items: activeCountries, load: loadActiveCountries } = useActiveCountries() +const { items: activeCountries, load: loadActiveCountries } = useActiveList(() => CountryApi.getCountries(toCountryQueryParams({ isActive: true }))) const isEdit = computed(() => !!route.params.id && route.params.id !== 'new') const pageTitle = computed(() => (isEdit.value ? 'Edit State' : 'New State')) diff --git a/app/Admin/src/features/location/views/StatesList.vue b/app/Admin/src/features/location/views/StatesList.vue index 97523e6d6..66f7e164a 100644 --- a/app/Admin/src/features/location/views/StatesList.vue +++ b/app/Admin/src/features/location/views/StatesList.vue @@ -10,16 +10,19 @@ import Tag from 'primevue/tag' import { useDataTableExport } from '@/shared/composables/useDataTableExport' import { usePagedQuery } from '@/shared/composables/usePagedQuery' +import { useActiveList } from '@/shared/composables' import { useNotify } from '@/shared/composables/useNotify' import { StateApi } from '../services/stateApi' -import { useActiveCountries } from '../composables/useActiveCountries' +import { CountryApi } from '../services/countryApi' import type { StateListItem } from '../types/state' +import type { CountryListItem } from '../types/country' +import { toCountryQueryParams } from '../types/country' import { STATE_FILTER_FIELDS, STATE_SORT_FIELDS } from '../types/state' const router = useRouter() const confirm = useConfirm() const notify = useNotify() -const { items: activeCountries, load: loadActiveCountries } = useActiveCountries() +const { items: activeCountries, load: loadActiveCountries } = useActiveList(() => CountryApi.getCountries(toCountryQueryParams({ isActive: true }))) const { dt, exportCSV } = useDataTableExport() const selectedCountryId = ref(null) @@ -39,7 +42,7 @@ const { setFilter, refresh, } = - usePagedQuery('api/locations/states', { + usePagedQuery((params) => StateApi.getStates(params), { allowedFilterFields: STATE_FILTER_FIELDS, allowedSortFields: STATE_SORT_FIELDS, allowedSearchFields: STATE_FILTER_FIELDS, diff --git a/app/Admin/src/features/ordering/__tests__/services/orderApi.spec.ts b/app/Admin/src/features/ordering/__tests__/services/orderApi.spec.ts index 1bb472fc1..87aa53e97 100644 --- a/app/Admin/src/features/ordering/__tests__/services/orderApi.spec.ts +++ b/app/Admin/src/features/ordering/__tests__/services/orderApi.spec.ts @@ -41,26 +41,22 @@ describe('OrderApi.getOrders', () => { }) await OrderApi.getOrders({ - status: 'Placed', - currency: 'USD', - sortBy: 'createdAtUtc', - sortDirection: 'desc', - page: 1, + filter: 'status=Placed,currency=USD', + sort: ['-createdAtUtc'], + pageNumber: 1, pageSize: 10, }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/ordering/orders', + '/api/admin/ordering/orders', { filter: 'status=Placed,currency=USD', - search: null, - searchFields: ['number', 'email'], sort: ['-createdAtUtc'], pageNumber: 1, pageSize: 10, }, expect.objectContaining({ - allowedFilterFields: ['status', 'checkoutState', 'currency', 'userId', 'storeId', 'isDeleted'], + allowedFilterFields: ['status', 'checkoutState', 'currency', 'userId', 'isDeleted'], allowedSortFields: ['number', 'total', 'completedAtUtc', 'createdAtUtc', 'status'], allowedSearchFields: ['number', 'email'], }), @@ -72,25 +68,26 @@ describe('OrderApi.getOrder', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.getOrder('o-1') - expect(mockGet).toHaveBeenCalledWith('api/ordering/orders/o-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1') }) }) describe('OrderApi.createOrder', () => { - it('calls POST with request body including storeId', async () => { - const req = { storeId: 's-1', currency: 'USD', email: 'a@b.com' } + it('calls POST with request body', async () => { + const req = { currency: 'USD', email: 'a@b.com' } mockPost.mockResolvedValue({ value: { id: 'o-1', ...req }, isSuccess: true, statusCode: 201, message: null, errors: [], metadata: null }) await OrderApi.createOrder(req) - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders', req) }) }) + describe('OrderApi.updateOrder', () => { it('calls PUT with request body', async () => { const req = { currency: 'USD', specialInstructions: 'leave at door' } mockPut.mockResolvedValue({ value: { id: 'o-1', ...req }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateOrder('o-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1', req) }) }) @@ -98,7 +95,7 @@ describe('OrderApi.deleteOrder', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await OrderApi.deleteOrder('o-1') - expect(mockDel).toHaveBeenCalledWith('api/ordering/orders/o-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1') }) }) @@ -117,18 +114,11 @@ describe('OrderApi.getLineItems', () => { metadata: null, }) - await OrderApi.getLineItems('o-1', { sortBy: 'total', sortDirection: 'desc' }) + await OrderApi.getLineItems('o-1', { sort: ['-total'] }) expect(mockGetPaged).toHaveBeenCalledWith( - 'api/ordering/orders/o-1/line-items', - { - filter: null, - search: null, - searchFields: ['number', 'email'], - sort: ['-total'], - pageNumber: null, - pageSize: null, - }, + '/api/admin/ordering/orders/o-1/line-items', + { sort: ['-total'] }, expect.objectContaining({ allowedFilterFields: ['OrderId', 'VariantId'], allowedSortFields: ['Quantity', 'Price', 'Total', 'CreatedAtUtc'], @@ -142,7 +132,7 @@ describe('OrderApi.getLineItem', () => { it('calls GET with correct URL', async () => { mockGet.mockResolvedValue({ value: { id: 'li-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.getLineItem('o-1', 'li-1') - expect(mockGet).toHaveBeenCalledWith('api/ordering/orders/o-1/line-items/li-1') + expect(mockGet).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/line-items/li-1') }) }) @@ -151,7 +141,7 @@ describe('OrderApi.addLineItem', () => { const req = { variantId: 'v-1', quantity: 2, price: 19.99 } mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.addLineItem('o-1', req) - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/line-items', req) + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/line-items', req) }) }) @@ -160,7 +150,7 @@ describe('OrderApi.updateLineItem', () => { const req = { quantity: 3 } mockPut.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateLineItem('o-1', 'li-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1/line-items/li-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/line-items/li-1', req) }) }) @@ -168,7 +158,7 @@ describe('OrderApi.removeLineItem', () => { it('calls DELETE with correct URL', async () => { mockDel.mockResolvedValue({ value: null, isSuccess: true, statusCode: 204, message: null, errors: [], metadata: null }) await OrderApi.removeLineItem('o-1', 'li-1') - expect(mockDel).toHaveBeenCalledWith('api/ordering/orders/o-1/line-items/li-1') + expect(mockDel).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/line-items/li-1') }) }) @@ -176,13 +166,13 @@ describe('OrderApi.cancelOrder', () => { it('calls POST with cancel URL and reason body', async () => { mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.cancelOrder('o-1', { reason: 'x' }) - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/cancel', { reason: 'x' }) + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/cancel', { reason: 'x' }) }) it('calls POST with empty body when no reason given', async () => { mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.cancelOrder('o-1') - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/cancel', {}) + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/cancel', {}) }) }) @@ -190,7 +180,7 @@ describe('OrderApi.completeOrder', () => { it('calls POST with complete URL', async () => { mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.completeOrder('o-1') - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/complete') + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/complete') }) }) @@ -198,7 +188,7 @@ describe('OrderApi.approveOrder', () => { it('calls POST with approve URL', async () => { mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.approveOrder('o-1') - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/approve') + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/approve') }) }) @@ -206,7 +196,7 @@ describe('OrderApi.resumeOrder', () => { it('calls POST with resume URL', async () => { mockPost.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.resumeOrder('o-1') - expect(mockPost).toHaveBeenCalledWith('api/ordering/orders/o-1/resume') + expect(mockPost).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/resume') }) }) @@ -215,7 +205,7 @@ describe('OrderApi.updateShipAddress', () => { const req = { addressId: 'a-1' } mockPut.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateShipAddress('o-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1/ship-address', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/ship-address', req) }) }) @@ -224,7 +214,7 @@ describe('OrderApi.updateBillAddress', () => { const req = { addressId: 'a-2' } mockPut.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateBillAddress('o-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1/bill-address', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/bill-address', req) }) }) @@ -233,7 +223,7 @@ describe('OrderApi.updateShippingMethod', () => { const req = { shippingMethodId: 'sm-1' } mockPut.mockResolvedValue({ value: { id: 'o-1' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateShippingMethod('o-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1/shipping-method', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/shipping-method', req) }) }) @@ -242,6 +232,22 @@ describe('OrderApi.updateStatus', () => { const req = { status: 'Placed' } mockPut.mockResolvedValue({ value: null, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderApi.updateStatus('o-1', req) - expect(mockPut).toHaveBeenCalledWith('api/ordering/orders/o-1/status', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/ordering/orders/o-1/status', req) + }) +}) + +describe('OrderApi.updateShipmentStatus', () => { + it('calls PUT with shipment status URL and request body', async () => { + const req = { status: 'Shipped', trackingNumber: 'TRK-123' } + mockPut.mockResolvedValue({ value: { id: 's-1', status: 'Shipped' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) + await OrderApi.updateShipmentStatus('s-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/shipping/shipments/s-1/status', req) + }) + + it('calls PUT with status only when tracking number is omitted', async () => { + const req = { status: 'Ready' } + mockPut.mockResolvedValue({ value: { id: 's-1', status: 'Ready' }, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) + await OrderApi.updateShipmentStatus('s-1', req) + expect(mockPut).toHaveBeenCalledWith('/api/admin/shipping/shipments/s-1/status', req) }) }) diff --git a/app/Admin/src/features/ordering/__tests__/services/orderingDashboardApi.spec.ts b/app/Admin/src/features/ordering/__tests__/services/orderingDashboardApi.spec.ts index 7afc09f2b..5188adcbb 100644 --- a/app/Admin/src/features/ordering/__tests__/services/orderingDashboardApi.spec.ts +++ b/app/Admin/src/features/ordering/__tests__/services/orderingDashboardApi.spec.ts @@ -18,6 +18,6 @@ describe('OrderingDashboardApi.getOrderingDashboard', () => { it('calls GET with dashboard URL', async () => { mockGet.mockResolvedValue({ value: {}, isSuccess: true, statusCode: 200, message: null, errors: [], metadata: null }) await OrderingDashboardApi.getOrderingDashboard() - expect(mockGet).toHaveBeenCalledWith('api/ordering/dashboard') + expect(mockGet).toHaveBeenCalledWith('/api/admin/ordering/dashboard') }) }) diff --git a/app/Admin/src/features/ordering/__tests__/types/order.spec.ts b/app/Admin/src/features/ordering/__tests__/types/order.spec.ts index e9e0d9857..42fcccace 100644 --- a/app/Admin/src/features/ordering/__tests__/types/order.spec.ts +++ b/app/Admin/src/features/ordering/__tests__/types/order.spec.ts @@ -22,8 +22,8 @@ describe('toOrderQueryParams', () => { }) it('builds filter DSL for checkoutState', () => { - const result = toOrderQueryParams({ checkoutState: 'Payment' }) - expect(result.filter).toBe('checkoutState=Payment') + const result = toOrderQueryParams({ checkoutState: 'PickPaymentMethod' }) + expect(result.filter).toBe('checkoutState=PickPaymentMethod') }) it('builds filter DSL for currency', () => { @@ -61,7 +61,6 @@ describe('ORDER_FILTER_FIELDS', () => { 'checkoutState', 'currency', 'userId', - 'storeId', 'isDeleted', ]) }) diff --git a/app/Admin/src/features/ordering/__tests__/views/OrderDetail.spec.ts b/app/Admin/src/features/ordering/__tests__/views/OrderDetail.spec.ts new file mode 100644 index 000000000..5e60b2e26 --- /dev/null +++ b/app/Admin/src/features/ordering/__tests__/views/OrderDetail.spec.ts @@ -0,0 +1,371 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { mount, flushPromises } from '@vue/test-utils' +import { createRouter, createMemoryHistory } from 'vue-router' +import type { DOMWrapper } from '@vue/test-utils' +import PrimeVue from 'primevue/config' +import OrderDetail from '../../views/OrderDetail.vue' +import { OrderApi } from '../../services/orderApi' +import type { OrderDetail as OrderDetailType } from '../../types/order' + +if (!window.matchMedia) { + window.matchMedia = (query: string) => ({ + matches: false, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }) +} + +if (!window.ResizeObserver) { + window.ResizeObserver = class { + observe() {} + unobserve() {} + disconnect() {} + } as unknown as typeof ResizeObserver +} + +const { confirmRequire, toastAdd } = vi.hoisted(() => ({ + confirmRequire: vi.fn<(...args: unknown[]) => unknown>(), + toastAdd: vi.fn<(...args: unknown[]) => unknown>(), +})) + +vi.mock('primevue/usetoast', () => ({ + useToast: () => ({ add: toastAdd }), +})) + +vi.mock('primevue/useconfirm', () => ({ + useConfirm: () => ({ require: confirmRequire }), +})) + +vi.mock('../../services/orderApi', () => ({ + OrderApi: { + getOrder: vi.fn<(...args: unknown[]) => unknown>(), + getLineItems: vi.fn<(...args: unknown[]) => unknown>(), + updateOrder: vi.fn<(...args: unknown[]) => unknown>(), + approveOrder: vi.fn<(...args: unknown[]) => unknown>(), + cancelOrder: vi.fn<(...args: unknown[]) => unknown>(), + completeOrder: vi.fn<(...args: unknown[]) => unknown>(), + resumeOrder: vi.fn<(...args: unknown[]) => unknown>(), + updateShipmentStatus: vi.fn<(...args: unknown[]) => unknown>(), + }, +})) + +const orderApiMock = OrderApi as unknown as { + getOrder: ReturnType + getLineItems: ReturnType + updateOrder: ReturnType + approveOrder: ReturnType + cancelOrder: ReturnType + completeOrder: ReturnType + resumeOrder: ReturnType + updateShipmentStatus: ReturnType +} + +function makeOrder(): OrderDetailType { + return { + id: 'o-1', + number: '1001', + status: 'Placed', + checkoutState: 'Placed', + currency: 'USD', + itemTotal: 200, + adjustmentTotal: 0, + shipmentTotal: 10, + adjustments: [], + total: 210, + paymentTotal: 0, + outstandingBalance: 210, + itemCount: 2, + createdAtUtc: '2026-01-01T00:00:00Z', + lineItems: [], + payments: [], + shipments: [ + { + id: 's-ready', + orderId: 'o-1', + shippingMethodId: 'sm-1', + shippingMethodName: 'Standard', + trackingNumber: '', + status: 'Ready', + shippedAtUtc: null, + deliveredAtUtc: null, + estimatedDeliveryAtUtc: null, + createdAtUtc: '2026-01-01T00:00:00Z', + }, + { + id: 's-shipped', + orderId: 'o-1', + shippingMethodId: 'sm-2', + shippingMethodName: 'Express', + trackingNumber: 'TRK-9', + status: 'Shipped', + shippedAtUtc: '2026-01-02T00:00:00Z', + deliveredAtUtc: null, + estimatedDeliveryAtUtc: null, + createdAtUtc: '2026-01-01T00:00:00Z', + }, + ], + timeline: [], + } +} + +function shipmentRows(wrapper: ReturnType) { + const tables = wrapper.findAll('table') + const table = tables[0] + return table.findAll('tbody tr') +} + +function rowButtons(row: DOMWrapper) { + return row.findAll('button').map(b => b.text().trim()) +} + +function rowForShippingMethod(wrapper: ReturnType, shippingMethod: string) { + const row = shipmentRows(wrapper).find(r => r.text().includes(shippingMethod)) + expect(row).toBeTruthy() + return row! +} + +async function mountWith(order: OrderDetailType) { + orderApiMock.getOrder.mockResolvedValue({ + isSuccess: true, + statusCode: 200, + message: null, + errors: [], + metadata: null, + value: order, + }) + const router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: '/ordering/orders/:id', component: OrderDetail }], + }) + router.push('/ordering/orders/o-1') + await router.isReady() + const wrapper = mount(OrderDetail, { global: { plugins: [PrimeVue, router] } }) + await flushPromises() + return wrapper +} + +describe('OrderDetail shipment quick actions', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('enables quick actions per shipment status', async () => { + const wrapper = await mountWith(makeOrder()) + + const readyRow = rowForShippingMethod(wrapper, 'Standard') + expect(rowButtons(readyRow)).toEqual(['Save', 'Mark Shipped', 'Mark Delivered']) + + const shippedRow = rowForShippingMethod(wrapper, 'Express') + expect(rowButtons(shippedRow)).toEqual(['Save', 'Mark Shipped', 'Mark Delivered']) + + expect(readyRow.findAll('button')[1].attributes('disabled')).toBeUndefined() + expect(readyRow.findAll('button')[2].attributes('disabled')).toBeDefined() + expect(shippedRow.findAll('button')[1].attributes('disabled')).toBeDefined() + expect(shippedRow.findAll('button')[2].attributes('disabled')).toBeUndefined() + }) + + it('disables Mark Shipped for Backorder and Pending shipments', async () => { + const order = makeOrder() + order.shipments = [ + { + id: 's-backorder', + orderId: 'o-1', + shippingMethodId: 'sm-3', + shippingMethodName: 'Backorder Ship', + trackingNumber: '', + status: 'Backorder', + shippedAtUtc: null, + deliveredAtUtc: null, + estimatedDeliveryAtUtc: null, + createdAtUtc: '2026-01-01T00:00:00Z', + }, + { + id: 's-pending', + orderId: 'o-1', + shippingMethodId: 'sm-4', + shippingMethodName: 'Pending Ship', + trackingNumber: '', + status: 'Pending', + shippedAtUtc: null, + deliveredAtUtc: null, + estimatedDeliveryAtUtc: null, + createdAtUtc: '2026-01-01T00:00:00Z', + }, + ] + const wrapper = await mountWith(order) + + const backorderRow = rowForShippingMethod(wrapper, 'Backorder Ship') + const pendingRow = rowForShippingMethod(wrapper, 'Pending Ship') + + expect(backorderRow.findAll('button')[1].attributes('disabled')).toBeDefined() + expect(pendingRow.findAll('button')[1].attributes('disabled')).toBeDefined() + }) + + it('marks a Ready shipment as Shipped with the tracking number', async () => { + const wrapper = await mountWith(makeOrder()) + orderApiMock.updateShipmentStatus.mockResolvedValue({ + isSuccess: true, + statusCode: 200, + message: null, + errors: [], + metadata: null, + value: { id: 's-ready', status: 'Shipped' }, + }) + + const readyRow = rowForShippingMethod(wrapper, 'Standard') + await readyRow.find('input').setValue('TRK-123') + await readyRow.findAll('button')[1].trigger('click') + await flushPromises() + + expect(orderApiMock.updateShipmentStatus).toHaveBeenCalledWith('s-ready', { + status: 'Shipped', + trackingNumber: 'TRK-123', + }) + expect(toastAdd).toHaveBeenCalledWith(expect.objectContaining({ severity: 'success' })) + expect(orderApiMock.getOrder).toHaveBeenCalledTimes(2) + }) + + it('blocks Mark Shipped when the tracking number is empty', async () => { + const wrapper = await mountWith(makeOrder()) + const readyRow = rowForShippingMethod(wrapper, 'Standard') + await readyRow.findAll('button')[1].trigger('click') + await flushPromises() + + expect(orderApiMock.updateShipmentStatus).not.toHaveBeenCalled() + expect(toastAdd).toHaveBeenCalledWith(expect.objectContaining({ severity: 'error' })) + }) + + it('marks a Shipped shipment as Delivered without a tracking number', async () => { + const wrapper = await mountWith(makeOrder()) + orderApiMock.updateShipmentStatus.mockResolvedValue({ + isSuccess: true, + statusCode: 200, + message: null, + errors: [], + metadata: null, + value: { id: 's-shipped', status: 'Delivered' }, + }) + + const shippedRow = rowForShippingMethod(wrapper, 'Express') + await shippedRow.findAll('button')[2].trigger('click') + await flushPromises() + + expect(orderApiMock.updateShipmentStatus).toHaveBeenCalledWith('s-shipped', { + status: 'Delivered', + }) + expect(toastAdd).toHaveBeenCalledWith(expect.objectContaining({ severity: 'success' })) + }) + + it('shows the current status in the status dropdown alongside its reachable targets', async () => { + const wrapper = await mountWith(makeOrder()) + + // Ready shipment: the dropdown must display the current status (Ready) plus its targets (Shipped, Canceled). + const readyRow = rowForShippingMethod(wrapper, 'Standard') + const readySelect = readyRow.find('.p-select') + expect(readySelect.exists()).toBe(true) + expect(readySelect.text()).toContain('Ready') + + // Shipped shipment: the dropdown must display the current status (Shipped), not just its target (Delivered). + const shippedRow = rowForShippingMethod(wrapper, 'Express') + const shippedSelect = shippedRow.find('.p-select') + expect(shippedSelect.exists()).toBe(true) + expect(shippedSelect.text()).toContain('Shipped') + }) + + it('shows Payment State and Checkout State severity tags in the overview', async () => { + const order: OrderDetailType = { + ...makeOrder(), + paymentState: 'Paid', + checkoutState: 'Placed', + } + const wrapper = await mountWith(order) + + const body = wrapper.text() + expect(body).toContain('Payment State') + expect(body).toContain('Paid') + expect(body).toContain('Checkout State') + expect(body).toContain('Placed') + + // Paid payment state maps to success severity. + const paidTag = wrapper.findAll('.p-tag').find(t => t.text().trim() === 'Paid') + expect(paidTag?.classes()).toContain('p-tag-success') + }) + + it('edits and saves special instructions via updateOrder', async () => { + const order = makeOrder() + order.specialInstructions = 'leave at door' + const wrapper = await mountWith(order) + orderApiMock.updateOrder.mockResolvedValue({ + isSuccess: true, + statusCode: 200, + message: null, + errors: [], + metadata: null, + value: { ...order, specialInstructions: 'ring the bell' }, + }) + + const textarea = wrapper.find('textarea') + expect((textarea.element as HTMLTextAreaElement).value).toBe('leave at door') + await textarea.setValue('ring the bell') + await wrapper.findAll('button').find(b => b.text().trim() === 'Save')!.trigger('click') + await flushPromises() + + expect(orderApiMock.updateOrder).toHaveBeenCalledWith('o-1', { + currency: 'USD', + specialInstructions: 'ring the bell', + }) + expect(toastAdd).toHaveBeenCalledWith(expect.objectContaining({ severity: 'success' })) + expect(orderApiMock.getOrder).toHaveBeenCalledTimes(2) + }) + + it('saves a tracking-number-only edit on a Shipped shipment without changing the status', async () => { + const wrapper = await mountWith(makeOrder()) + orderApiMock.updateShipmentStatus.mockResolvedValue({ + isSuccess: true, + statusCode: 200, + message: null, + errors: [], + metadata: null, + value: { id: 's-shipped', status: 'Shipped' }, + }) + + const shippedRow = rowForShippingMethod(wrapper, 'Express') + const trackingInput = shippedRow.find('input') + await trackingInput.setValue('TRK-NEW') + await shippedRow.findAll('button')[0].trigger('click') + await flushPromises() + + expect(orderApiMock.updateShipmentStatus).toHaveBeenCalledWith('s-shipped', { + status: 'Shipped', + trackingNumber: 'TRK-NEW', + }) + expect(toastAdd).toHaveBeenCalledWith(expect.objectContaining({ severity: 'success' })) + }) + + it('disables the tracking input for a Pending shipment', async () => { + const order = makeOrder() + order.shipments = [ + { + id: 's-pending', + orderId: 'o-1', + shippingMethodId: 'sm-4', + shippingMethodName: 'Pending Ship', + trackingNumber: null, + status: 'Pending', + shippedAtUtc: null, + deliveredAtUtc: null, + estimatedDeliveryAtUtc: null, + createdAtUtc: '2026-01-01T00:00:00Z', + }, + ] + const wrapper = await mountWith(order) + const pendingRow = rowForShippingMethod(wrapper, 'Pending Ship') + const trackingInput = pendingRow.find('input').element as HTMLInputElement + expect(trackingInput.disabled).toBe(true) + }) +}) \ No newline at end of file diff --git a/app/Admin/src/features/ordering/composables/useOrderList.ts b/app/Admin/src/features/ordering/composables/useOrderList.ts index e808b62dc..214f81d60 100644 --- a/app/Admin/src/features/ordering/composables/useOrderList.ts +++ b/app/Admin/src/features/ordering/composables/useOrderList.ts @@ -1,14 +1,9 @@ import { usePagedQuery } from '@/shared/composables' import type { UsePagedQueryOptions } from '@/shared/composables' -import { ORDERING } from '@/shared/constants/api' -import { ORDER_FILTER_FIELDS, ORDER_SORT_FIELDS, ORDER_SEARCH_FIELDS } from '../types/order' + import type { OrderListItem } from '../types/order' +import { OrderApi } from '../services/orderApi' export function useOrderList(options?: UsePagedQueryOptions) { - return usePagedQuery(`${ORDERING}/orders`, { - allowedFilterFields: ORDER_FILTER_FIELDS, - allowedSortFields: ORDER_SORT_FIELDS, - allowedSearchFields: ORDER_SEARCH_FIELDS, - ...options, - }) + return usePagedQuery((params) => OrderApi.getOrders(params), { ...options }) } diff --git a/app/Admin/src/features/ordering/services/orderApi.ts b/app/Admin/src/features/ordering/services/orderApi.ts index abe9b96a1..753c45e6d 100644 --- a/app/Admin/src/features/ordering/services/orderApi.ts +++ b/app/Admin/src/features/ordering/services/orderApi.ts @@ -1,10 +1,9 @@ import { getPaged } from '@/shared/api' import { get, post, put, del } from '@/shared/api/client' -import { ORDERING } from '@/shared/constants/api' -import type { Result, PagedResult } from '@/shared/types' + +import type { Result, PagedResult, QueryingParameters } from '@/shared/types' import type { OrderRequest, - OrderQuery, OrderListItem, OrderDetail, LineItem, @@ -14,19 +13,18 @@ import type { UpdateOrderAddressRequest, UpdateOrderShippingMethodRequest, UpdateOrderStatusRequest, + Shipment, + ShipmentStatus, } from '../types/order' import { ORDER_FILTER_FIELDS, ORDER_SORT_FIELDS, ORDER_SEARCH_FIELDS, - toOrderQueryParams, } from '../types/order' export class OrderApi { - private static readonly BASE = `${ORDERING}/orders` - - static getOrders(query: OrderQuery): Promise> { - return getPaged(OrderApi.BASE, toOrderQueryParams(query), { + static getOrders(params: QueryingParameters): Promise> { + return getPaged('/api/admin/ordering/orders', params, { allowedFilterFields: ORDER_FILTER_FIELDS, allowedSortFields: ORDER_SORT_FIELDS, allowedSearchFields: ORDER_SEARCH_FIELDS, @@ -34,23 +32,23 @@ export class OrderApi { } static getOrder(id: string): Promise> { - return get>(`${OrderApi.BASE}/${id}`) + return get>(`/api/admin/ordering/orders/${id}`) } - static createOrder(request: OrderRequest & { storeId: string }): Promise> { - return post>(OrderApi.BASE, request) + static createOrder(request: OrderRequest ): Promise> { + return post>('/api/admin/ordering/orders', request) } static updateOrder(id: string, request: OrderRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}`, request) + return put>(`/api/admin/ordering/orders/${id}`, request) } static deleteOrder(id: string): Promise> { - return del>(`${OrderApi.BASE}/${id}`) + return del>(`/api/admin/ordering/orders/${id}`) } - static getLineItems(id: string, query: OrderQuery): Promise> { - return getPaged(`${OrderApi.BASE}/${id}/line-items`, toOrderQueryParams(query), { + static getLineItems(id: string, params: QueryingParameters): Promise> { + return getPaged(`/api/admin/ordering/orders/${id}/line-items`, params, { allowedFilterFields: ['OrderId', 'VariantId'], allowedSortFields: ['Quantity', 'Price', 'Total', 'CreatedAtUtc'], allowedSearchFields: [], @@ -58,50 +56,54 @@ export class OrderApi { } static getLineItem(id: string, lineItemId: string): Promise> { - return get>(`${OrderApi.BASE}/${id}/line-items/${lineItemId}`) + return get>(`/api/admin/ordering/orders/${id}/line-items/${lineItemId}`) } static addLineItem(id: string, request: AddLineItemRequest): Promise> { - return post>(`${OrderApi.BASE}/${id}/line-items`, request) + return post>(`/api/admin/ordering/orders/${id}/line-items`, request) } static updateLineItem(id: string, lineItemId: string, request: UpdateLineItemRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}/line-items/${lineItemId}`, request) + return put>(`/api/admin/ordering/orders/${id}/line-items/${lineItemId}`, request) } static removeLineItem(id: string, lineItemId: string): Promise> { - return del>(`${OrderApi.BASE}/${id}/line-items/${lineItemId}`) + return del>(`/api/admin/ordering/orders/${id}/line-items/${lineItemId}`) } static cancelOrder(id: string, request?: CancelOrderRequest): Promise> { - return post>(`${OrderApi.BASE}/${id}/cancel`, request ?? {}) + return post>(`/api/admin/ordering/orders/${id}/cancel`, request ?? {}) } static completeOrder(id: string): Promise> { - return post>(`${OrderApi.BASE}/${id}/complete`) + return post>(`/api/admin/ordering/orders/${id}/complete`) } static approveOrder(id: string): Promise> { - return post>(`${OrderApi.BASE}/${id}/approve`) + return post>(`/api/admin/ordering/orders/${id}/approve`) } static resumeOrder(id: string): Promise> { - return post>(`${OrderApi.BASE}/${id}/resume`) + return post>(`/api/admin/ordering/orders/${id}/resume`) } static updateShipAddress(id: string, request: UpdateOrderAddressRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}/ship-address`, request) + return put>(`/api/admin/ordering/orders/${id}/ship-address`, request) } static updateBillAddress(id: string, request: UpdateOrderAddressRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}/bill-address`, request) + return put>(`/api/admin/ordering/orders/${id}/bill-address`, request) } static updateShippingMethod(id: string, request: UpdateOrderShippingMethodRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}/shipping-method`, request) + return put>(`/api/admin/ordering/orders/${id}/shipping-method`, request) } static updateStatus(id: string, request: UpdateOrderStatusRequest): Promise> { - return put>(`${OrderApi.BASE}/${id}/status`, request) + return put>(`/api/admin/ordering/orders/${id}/status`, request) + } + + static updateShipmentStatus(id: string, body: { status: ShipmentStatus; trackingNumber?: string }): Promise> { + return put>(`/api/admin/shipping/shipments/${id}/status`, body) } } diff --git a/app/Admin/src/features/ordering/services/orderingDashboardApi.ts b/app/Admin/src/features/ordering/services/orderingDashboardApi.ts index ac0d9a02f..114775474 100644 --- a/app/Admin/src/features/ordering/services/orderingDashboardApi.ts +++ b/app/Admin/src/features/ordering/services/orderingDashboardApi.ts @@ -1,12 +1,10 @@ import { get } from '@/shared/api/client' -import { ORDERING } from '@/shared/constants/api' + import type { Result } from '@/shared/types' import type { OrderingDashboard } from '../types/orderingDashboard' export class OrderingDashboardApi { - private static readonly BASE = `${ORDERING}/dashboard` - static getOrderingDashboard(): Promise> { - return get>(OrderingDashboardApi.BASE) + return get>('/api/admin/ordering/dashboard') } } diff --git a/app/Admin/src/features/ordering/types/index.ts b/app/Admin/src/features/ordering/types/index.ts index 1dc729989..8b43d0648 100644 --- a/app/Admin/src/features/ordering/types/index.ts +++ b/app/Admin/src/features/ordering/types/index.ts @@ -1,6 +1,7 @@ export type { OrderStatus, CheckoutState, + OrderPaymentState, OrderRequest, OrderListItem, OrderDetail, diff --git a/app/Admin/src/features/ordering/types/order.ts b/app/Admin/src/features/ordering/types/order.ts index 6907cf303..9b186d5b8 100644 --- a/app/Admin/src/features/ordering/types/order.ts +++ b/app/Admin/src/features/ordering/types/order.ts @@ -1,8 +1,11 @@ import type { QueryingParameters } from '@/shared/types/querying' +import type { PaymentRecordState } from '@/features/payment/types/payment' -export type OrderStatus = 'Draft' | 'Placed' | 'Canceled' | 'Expired' +export type OrderStatus = 'Draft' | 'Placed' | 'Canceled' | 'Completed' | 'Expired' -export type CheckoutState = 'Address' | 'Delivery' | 'Payment' | 'Confirm' | 'Complete' +export type CheckoutState = 'Address' | 'PickDeliveryMethod' | 'PickPaymentMethod' | 'Confirm' | 'Placed' + +export type OrderPaymentState = 'Completed' | 'Failed' | 'Void' | 'BalanceDue' | 'CreditOwed' | 'Paid' | 'Pending' | 'Checkout' | 'Invalid' export interface OrderRequest { currency: string @@ -19,8 +22,8 @@ export interface OrderListItem extends OrderRequest { status: OrderStatus total: number paymentTotal: number - paymentState?: string - shipmentState?: string + paymentState?: OrderPaymentState + fulfillmentState?: OrderFulfillmentState createdAtUtc: string completedAtUtc?: string } @@ -33,13 +36,33 @@ export interface OrderDetail extends OrderRequest { itemTotal: number adjustmentTotal: number shipmentTotal: number + shippingAdjustment?: { + id: string + label: string + amount: number + shippingMethodId?: string + } | null + // Backend: OrderDetailResponse.ShippingCalculation (Order.Model.cs); captured when shipping was applied. + shippingCalculation?: { + totalWeight: number + shippingRateId?: string | null + cost: number + isFreeShipping: boolean + } | null + // Backend: OrderDetailResponse.Adjustments (Order.Model.cs); persisted adjustment rows. + adjustments: { + id: string + label: string + amount: number + sourceType: string + shippingMethodId?: string | null + }[] total: number paymentTotal: number outstandingBalance: number - paymentState?: string - shipmentState?: string + paymentState?: OrderPaymentState + fulfillmentState?: OrderFulfillmentState userId?: string - storeId?: string itemCount: number approvedById?: string approvedAtUtc?: string @@ -47,11 +70,24 @@ export interface OrderDetail extends OrderRequest { canceledAtUtc?: string createdAtUtc: string modifiedAtUtc?: string + paymentProcessingAtUtc?: string + paymentCompletedAtUtc?: string + paymentFailedAtUtc?: string + shipmentShippedAtUtc?: string + shipmentDeliveredAtUtc?: string + lineItems: LineItem[] + payments: PaymentCaptureSummary[] + shipments: ShipmentSummary[] + timeline: OrderTimelineEvent[] } export interface LineItem { id: string - variantId: string + orderId: string + variantId: string | null + productId?: string | null + productName?: string | null + productImageUrl?: string | null quantity: number price: number total: number @@ -64,7 +100,6 @@ export interface OrderQuery { status?: OrderStatus checkoutState?: CheckoutState currency?: string - storeId?: string search?: string sortBy?: 'number' | 'total' | 'completedAtUtc' | 'createdAtUtc' | 'status' sortDirection?: 'asc' | 'desc' @@ -77,7 +112,6 @@ export const ORDER_FILTER_FIELDS = [ 'checkoutState', 'currency', 'userId', - 'storeId', 'isDeleted', ] @@ -97,9 +131,6 @@ export function toOrderQueryParams(query: OrderQuery): QueryingParameters { if (query.currency !== undefined && query.currency !== '') { filters.push(`currency=${query.currency}`) } - if (query.storeId !== undefined && query.storeId !== '') { - filters.push(`storeId=${query.storeId}`) - } let sort: string[] | null = null if (query.sortBy) { @@ -142,3 +173,52 @@ export interface UpdateOrderAddressRequest { export interface UpdateOrderShippingMethodRequest { shippingMethodId: string } + +export type OrderFulfillmentState = 'None' | 'Pending' | 'Partial' | 'Shipped' | 'Delivered' | 'Canceled' + +export type ShipmentStatus = 'Pending' | 'Ready' | 'Shipped' | 'Delivered' | 'Backorder' | 'Canceled' + +export interface Shipment { + id: string + orderId: string + shippingMethodId: string + trackingNumber: string | null + status: ShipmentStatus + shippedAtUtc: string | null + deliveredAtUtc: string | null + estimatedDeliveryAtUtc: string | null + createdAtUtc: string +} + +export interface PaymentCaptureSummary { + id: string + number: string + amount: number + currency: string + state: PaymentRecordState + paymentStatus: string | null + providerKey: string + paymentMethodId: string | null + createdAtUtc: string + completedAtUtc: string | null + failedAtUtc: string | null +} + +export interface ShipmentSummary { + id: string + orderId: string + shippingMethodId: string + shippingMethodName: string | null + trackingNumber: string + status: ShipmentStatus + shippedAtUtc: string | null + deliveredAtUtc: string | null + estimatedDeliveryAtUtc: string | null + createdAtUtc: string +} + +export interface OrderTimelineEvent { + type: string + label: string + occurredAtUtc: string | null +} diff --git a/app/Admin/src/features/ordering/types/orderingDashboard.ts b/app/Admin/src/features/ordering/types/orderingDashboard.ts index 99adfa813..7969096f9 100644 --- a/app/Admin/src/features/ordering/types/orderingDashboard.ts +++ b/app/Admin/src/features/ordering/types/orderingDashboard.ts @@ -1,8 +1,10 @@ +import type { OrderStatus } from './order' + export interface RecentOrderData { id: string number: string total: number - status: string + status: OrderStatus createdAtUtc: string } diff --git a/app/Admin/src/features/ordering/views/OrderDetail.vue b/app/Admin/src/features/ordering/views/OrderDetail.vue index ac2d360cd..da137ce82 100644 --- a/app/Admin/src/features/ordering/views/OrderDetail.vue +++ b/app/Admin/src/features/ordering/views/OrderDetail.vue @@ -10,6 +10,8 @@ import TabPanels from 'primevue/tabpanels' import TabPanel from 'primevue/tabpanel' import Button from 'primevue/button' import Tag from 'primevue/tag' +import Select from 'primevue/select' +import InputText from 'primevue/inputtext' import DataTable from 'primevue/datatable' import Column from 'primevue/column' import { useNotify } from '@/shared/composables/useNotify' @@ -18,10 +20,12 @@ import { formatCurrency } from '@/shared/utils/currency' import { formatDate } from '@/shared/utils/date' import { useOrderDetail } from '../composables/useOrderDetail' import { OrderApi } from '../services/orderApi' -import { PaymentApi } from '@/features/payment/services/paymentApi' +import { PaymentApi } from '../../payment/services/paymentApi' +import { PAYMENT_STATE_SEVERITY } from '../../payment/types/payment' +import type { PaymentRecordState } from '../../payment/types/payment' +import Timeline from 'primevue/timeline' import type { Result } from '@/shared/types' -import type { OrderDetail, OrderStatus, LineItem } from '../types/order' -import type { PaymentListItem } from '@/features/payment/types/payment' +import type { OrderDetail, OrderStatus, OrderPaymentState, CheckoutState, LineItem, OrderFulfillmentState, ShipmentSummary, ShipmentStatus, PaymentCaptureSummary } from '../types/order' const route = useRoute() const router = useRouter() @@ -38,14 +42,18 @@ const items = ref([]) const itemsLoading = ref(false) const itemsLoaded = ref(false) -const payments = ref([]) -const paymentsLoading = ref(false) -const paymentsLoaded = ref(false) +// Shipments: Derive the editable shipment rows from the order detail payload. +const shipments = computed(() => order.value?.shipments ?? []) +// Payments: Derive the payment rows from the order detail payload. +const payments = computed(() => order.value?.payments ?? []) +// Timeline: Derive the status event list from the order detail payload. +const timeline = computed(() => order.value?.timeline ?? []) const STATUS_SEVERITY: Record = { Draft: 'warn', Placed: 'success', Canceled: 'danger', + Completed: 'success', Expired: 'secondary', } @@ -53,6 +61,227 @@ function statusSeverity(status: OrderStatus | undefined): string { return status ? STATUS_SEVERITY[status] : 'secondary' } +const savingShipmentId = ref(null) +const draftStatus = ref>({}) +const trackingInputs = ref>({}) +const paymentActionId = ref(null) +const specialInstructions = ref('') +const savingInstructions = ref(false) + +// Seed: Mirror the order's notes into the editable overview field. +watch(order, (o) => { + specialInstructions.value = o?.specialInstructions ?? '' +}, { immediate: true }) + +// Save: Persist order notes through the admin update endpoint, then refresh. +async function saveSpecialInstructions(): Promise { + savingInstructions.value = true + const result = await OrderApi.updateOrder(orderId.value, { + currency: order.value?.currency ?? 'USD', + specialInstructions: specialInstructions.value, + }) + savingInstructions.value = false + if (result.isSuccess) { + notify.success('Order', 'Special instructions updated.') + await fetchOrder(orderId.value) + } else { + handleResult(result) + } +} + +// Transition: Return the shipment statuses reachable from the row's current status, mirroring ShipmentMethod guards. +function allowedShipmentTargets(status: ShipmentStatus): ShipmentStatus[] { + switch (status) { + case 'Pending': + return ['Ready', 'Backorder', 'Canceled'] + case 'Ready': + return ['Shipped', 'Canceled'] + case 'Backorder': + return ['Ready', 'Canceled'] + case 'Shipped': + return ['Delivered'] + default: + return [] // Delivered and Canceled are terminal states. + } +} + +// Display: The status dropdown shows the current status plus the transitions reachable from it, +// so the Select can render the current value (it is never one of its own targets). +function shipmentStatusOptions(status: ShipmentStatus): ShipmentStatus[] { + return [status, ...allowedShipmentTargets(status)] +} + +// Guard: Save when the status changed to a reachable target OR the tracking number was edited. +function canSaveShipment(shipment: ShipmentSummary): boolean { + const current = shipment.status + const target = draftStatus.value[shipment.id] ?? current + const statusChanged = target !== current && allowedShipmentTargets(current).includes(target) + const trackingChanged = (trackingInputs.value[shipment.id] ?? '') !== (shipment.trackingNumber ?? '') + return statusChanged || trackingChanged +} + +// Guard: Tracking numbers are editable only once the shipment leaves Pending (Ready, Backorder, Shipped, Delivered). +function canEditTracking(shipment: ShipmentSummary): boolean { + return shipment.status !== 'Pending' && shipment.status !== 'Canceled' +} + +const FULFILLMENT_SEVERITY: Record = { + None: 'secondary', + Pending: 'secondary', + Partial: 'warn', + Shipped: 'info', + Delivered: 'success', + Canceled: 'danger', +} + +function fulfillmentSeverity(state: OrderFulfillmentState | null | undefined): string { + return state ? FULFILLMENT_SEVERITY[state] : 'secondary' +} + +// Severity: Map the order-level derived payment state to a PrimeVue Tag severity. +const ORDER_PAYMENT_SEVERITY: Record = { + Paid: 'success', + Completed: 'success', + Pending: 'warn', + Checkout: 'warn', + BalanceDue: 'warn', + CreditOwed: 'warn', + Failed: 'danger', + Void: 'secondary', + Invalid: 'danger', +} + +function orderPaymentSeverity(state: OrderPaymentState | null | undefined): string { + return state ? ORDER_PAYMENT_SEVERITY[state] : 'secondary' +} + +// Severity: Map the checkout wizard step to a PrimeVue Tag severity. +const CHECKOUT_SEVERITY: Record = { + Address: 'info', + PickDeliveryMethod: 'info', + PickPaymentMethod: 'info', + Confirm: 'info', + Placed: 'success', +} + +function checkoutSeverity(state: CheckoutState | undefined): string { + return state ? CHECKOUT_SEVERITY[state] : 'secondary' +} + +function initShipmentDrafts(shipmentList: ShipmentSummary[]) { + // Seed: Track per-row status and tracking edits for the save flow. + draftStatus.value = Object.fromEntries(shipmentList.map(s => [s.id, s.status])) + trackingInputs.value = Object.fromEntries(shipmentList.map(s => [s.id, s.trackingNumber ?? ''])) +} + +// Seed: Rebuild the per-row status/tracking drafts whenever the payload shipments change. +watch(shipments, (list) => initShipmentDrafts(list), { immediate: true }) + +async function saveShipmentStatus(shipment: ShipmentSummary) { + const target = draftStatus.value[shipment.id] ?? shipment.status + const tracking = trackingInputs.value[shipment.id] ?? '' + // Guard: Transitioning to Shipped requires a tracking number. + if (target === 'Shipped' && target !== shipment.status && !tracking.trim()) { + notify.error('Shipment', 'A tracking number is required to mark the shipment as Shipped.') + return + } + // Guard: Tracking edits are allowed only beyond Pending (Ready, Backorder, Shipped, Delivered). + if (tracking !== (shipment.trackingNumber ?? '') && !canEditTracking(shipment)) { + notify.error('Shipment', 'Tracking number can only be set once the shipment leaves Pending.') + return + } + await persistShipmentStatus(shipment, target, tracking) +} + +// Save: Persist a shipment status transition and refresh the order on success. +async function persistShipmentStatus(shipment: ShipmentSummary, status: ShipmentStatus, trackingNumber?: string) { + savingShipmentId.value = shipment.id + const result = await OrderApi.updateShipmentStatus(shipment.id, { status, trackingNumber }) + savingShipmentId.value = null + if (result.isSuccess) { + notify.success('Shipment', `Shipment status updated to "${status}".`) + // Refresh: Re-fetch the order so shipments and timeline reflect the new status. + await fetchOrder(orderId.value) + } else { + handleResult(result) + } +} + +// Gate: Mark Shipped is reachable only from Ready. +function canMarkShipped(shipment: ShipmentSummary): boolean { + return allowedShipmentTargets(shipment.status).includes('Shipped') +} + +// Gate: Mark Delivered is reachable only from Shipped. +function canMarkDelivered(shipment: ShipmentSummary): boolean { + return allowedShipmentTargets(shipment.status).includes('Delivered') +} + +async function markShipmentShipped(shipment: ShipmentSummary) { + // Guard: A tracking number is required to mark a shipment as Shipped. + if (!trackingInputs.value[shipment.id]?.trim()) { + notify.error('Shipment', 'A tracking number is required to mark the shipment as Shipped.') + return + } + await persistShipmentStatus(shipment, 'Shipped', trackingInputs.value[shipment.id]) +} + +async function markShipmentDelivered(shipment: ShipmentSummary) { + await persistShipmentStatus(shipment, 'Delivered') +} + +// Gate: Capture applies only to payments awaiting settlement. +function canCapturePayment(state: PaymentRecordState): boolean { + return state === 'Pending' || state === 'Processing' +} + +// Gate: Refund applies only to completed payments. +function canRefundPayment(state: PaymentRecordState): boolean { + return state === 'Completed' +} + +// Gate: Void applies only to payments that have not completed. +function canVoidPayment(state: PaymentRecordState): boolean { + return state === 'Pending' || state === 'Processing' +} + +// Trigger: Confirm before running a payment action on the row, then reload the order. +function confirmPaymentAction(payment: PaymentCaptureSummary, label: string, message: string, run: () => Promise>) { + confirm.require({ + message, + header: `Confirm ${label}`, + icon: 'pi pi-exclamation-triangle', + rejectLabel: 'Cancel', + acceptLabel: label, + accept: async () => { + paymentActionId.value = payment.id + const result = await run() + paymentActionId.value = null + if (result.isSuccess) { + notify.success('Payment', `Payment ${label.toLowerCase()}d.`) + await fetchOrder(orderId.value) + } else { + handleResult(result) + } + }, + }) +} + +function capturePayment(payment: PaymentCaptureSummary) { + confirmPaymentAction(payment, 'Capture', 'Capture this payment?', () => PaymentApi.capturePayment(payment.id)) +} + +function refundPayment(payment: PaymentCaptureSummary) { + const amount = formatCurrency(payment.amount, payment.currency) + confirmPaymentAction(payment, 'Refund', `Refund ${amount} for this payment?`, () => + PaymentApi.refundPayment(payment.id, { amount: payment.amount }), + ) +} + +function voidPayment(payment: PaymentCaptureSummary) { + confirmPaymentAction(payment, 'Void', 'Void this payment?', () => PaymentApi.voidPayment(payment.id)) +} + function currency(value: OrderDetail | null): string { return value?.currency ?? 'USD' } @@ -163,23 +392,8 @@ async function loadItems() { } } -async function loadPayments() { - if (paymentsLoaded.value || paymentsLoading.value) return - paymentsLoading.value = true - // Load: Fetch payments lazily when the payments tab opens. - const result = await PaymentApi.getPayments({ orderId: orderId.value, pageSize: 100 }) - paymentsLoading.value = false - if (result.isSuccess) { - payments.value = result.items - paymentsLoaded.value = true - } else { - handleResult(result) - } -} - watch(activeTab, (tab) => { if (tab === '1') loadItems() - else if (tab === '2') loadPayments() }) watch( @@ -187,15 +401,15 @@ watch( (id) => { if (id) { itemsLoaded.value = false - paymentsLoaded.value = false items.value = [] - payments.value = [] loadOrder() } }, ) -onMounted(loadOrder) +onMounted(() => { + loadOrder() +})