Skip to content

Admin panel: embedding management, auth guard, list fixes, and more - #2

Merged
qingfa-dev merged 1108 commits into
devfrom
feature/implement-admin-panel
Aug 4, 2026
Merged

qingfa-dev merged 1108 commits into
devfrom
feature/implement-admin-panel

Conversation

@qingfa-dev

Copy link
Copy Markdown
Owner

Summary

Merges the feature/implement-admin-panel branch into dev. This branch consolidates the Admin SPA and backend work built on top of main; it is 1,108 commits ahead of dev.

Highlights

Variant image embedding management (Catalog)

  • ImageEmbedding gains an EmbeddingStatus lifecycle (Pending/Processing/Completed/Failed) with status-transition methods and an EF migration (status stored as text per the codebase enum convention).
  • New IEmbeddingOrchestrator.RunAsync Hangfire job entry point; CreateEmbedding/RegenerateEmbedding now pre-create a Pending row and enqueue the job instead of blocking synchronously; GetEmbedding (GET) and DeleteEmbedding (DELETE) endpoints added; upload auto-embed migrated to the same Pending-row pattern.
  • ImageEmbedding.Vector made nullable so Pending rows persist (pgvector rejects empty vectors).
  • Admin UI: per-image embedding badge (None/Pending/Processing/Completed/Failed) with Generate/Regenerate/Delete in VariantDetail's Images tab, plus a useEmbeddingStatus polling composable.
  • Embedding management scoped to the single Search-type image per variant; image-type selector added; one Default and one Search per variant enforced server-side; confirmation before switching to Search/Default.
  • Storefront vector search aligned to consume Search-type embeddings.

Admin auth guard

  • Re-enabled the auth guard: protected routes require authentication, guest-only pages redirect authenticated users, with safe post-login redirect handling.

Other

  • Server-side pagination fixes across Admin list views (PrimeVue lazy DataTable), filter/clear-button fixes, and Code Commenting Standard annotations across views.

Testing

  • Backend: dotnet build clean (warnings-as-errors), Module.UnitTests 2,620 passing.
  • Admin SPA: vue-tsc --build + pnpm run lint clean, pnpm run test:unit 1,097 passing.
  • Storefront vector-search tests updated for the Search-type alignment.

…paths

Flatten CatalogFeature endpoint constant groups into sibling entity
classes (Admin and Storefront) and relocate nested parent ids from URL
path segments into request bodies for commands and query parameters for
queries, per plan/refactor-catalog-feature-1.md.

- Rewrite CatalogFeature.Admin/Storefront into flat entity-group shape
- Relocate VariantId/ProductId/TaxonId/OptionTypeId parent ids to bodies
  and query strings; rename PermissionContext resource descriptors
- Move OptionValues, ProductOptionTypes, VariantOptionValues feature
  folders and update all endpoints, smoke tests, and unit/integration tests
Rewrite taxonRuleApi.ts against flat api/catalog/taxon-rules base, move
taxonId into create/update bodies, use delWithBody for delete, add
syncRules. Update TaxonRuleFormDialog call sites and taxonRuleApi spec.
… types, classifications, prices, images, embeddings
…mbeddings, dashboard and fix flat option-value URLs
qingfa-dev and others added 27 commits August 4, 2026 06:09
Close the full-and-necessary audit for all feature views by labeling the
last unlabelled await/confirm.require/validation sites (Load, Call,
Trigger, Validate) with Code Commenting Standard v3.0 labels.
…ding

Reword four Task 15 Call labels to keep F8 compliance (one action per
comment) by dropping trailing refresh clauses.
The labels restated the invoked API verbatim (AP-1). Keep the required
Call: label but encode intent the code does not show: email the reset
link only when the account exists; confirm the token before resetting.
Align ToDetail test assertion with the Payment.Currency mapping fix from
commit 6bcac8a. The test previously expected an empty string, now it
verifies the actual Currency property is mapped through.

Co-Authored-By: opencode <noreply@opencode.ai>
…e Hangfire enqueue

Add dedicated NotFoundByVariantImage error code for embedding lookups by
variant image ID. In Create and Regenerate handlers, persist the Pending
embedding row before enqueueing the Hangfire job so the background worker
never encounters a missing row. Use the specific error in Get and Delete
handlers when no embedding exists for the given variant image.

Co-Authored-By: opencode <noreply@opencode.ai>
Align DeleteEmbedding and GetEmbedding tests with the new error code
introduced in commit ba43ef6.

Co-Authored-By: opencode <noreply@opencode.ai>
…ector rejects empty vector)

CreatePending wrote an empty float array into the pgvector column, which
Postgres rejects with '22000: vector must have at least 1 dimension'. A
Pending embedding has no vector yet, so make the column nullable and store
NULL until MarkCompleted writes the real vector. Add migration; null-guard
storefront vector search and orchestrator response mapping.
Only the Search-type image (the AI semantic-search source) should carry an
embedding. Gate the per-card embedding badge/actions and 'Generate All
Missing' to Search-type images, and add an image-type selector to the card
so the admin can designate the search image. Align VectorSearchService to
query Search-type embeddings (was Default), matching the upload auto-embed
trigger, and update the storefront tests accordingly.
When an image is set (or uploaded) as Default or Search, demote the prior
image in the same variant holding that type to Thumbnail. Enforced in the
backend Update and Upload handlers so the invariant holds regardless of
client.
…rects

The auth guard was previously disabled behind a TODO after the route
scaffold review. Re-enable it so protected routes require authentication
and guest-only pages (login, forgot-password, reset-password) redirect
authenticated users to the dashboard.

Introduce the guestOnly route meta flag and a resolvePostLoginRedirect
helper that safely validates the redirect query param before resuming the
original destination, falling back to the dashboard when absent or unsafe.

Add unit tests for the guard's redirect logic and the post-login redirect
resolver, plus the feature plan file.
@qingfa-dev
qingfa-dev merged commit 998b442 into dev Aug 4, 2026
0 of 5 checks passed
@qingfa-dev qingfa-dev mentioned this pull request Oct 3, 2026
3 tasks
qingfa-dev added a commit that referenced this pull request Oct 3, 2026
* refactor(admin): fix downstream callers to use named request types

* feat(admin): align Ordering/Payment/Shipping response types with C# DTOs

Phase 2-6: fix response types, create model types & mappers, wire
services, update views/components for ordering, payment, shipping.

- order.response.type: remove nested collections, use decimal totals
- payment.response.type: status as number, not string
- payment-method/shipping-rate/shipping-method: align with C# spec
- model types with display helpers + mappers for all 5 domains
- services wrapped to map DTOs → model types
- stores use model types; views/components updated for new shapes
- removed sections referencing removed nested collections

* docs(admin): add refactoring plans for interceptors, mappers, naming

* refactor(admin): extract API interceptors, rename types to kebab-case, add service layers

- Refactor api.client.ts into modular interceptors (auth, camelCase, error-wrapper)
- Convert all API repository files from .then() to async/await
- Rename PascalCase type/schema files to kebab-case across all features
- Add proper service layers between repositories and stores
- Remove trivial mapper files (inventory, location, ordering, payment, shipping)
- Add model types, shared utils (currency, enums, transform), and handler specs
- Simplify AdminUserSummary response type (remove roleNames, lastSignInAtUtc, lastIpAddress)
- Clean up UI templates to match updated response types

* docs: add admin gap coverage design spec (5 specs: routes, APIs, UI, stubs, cleanup)

* docs: add admin gap coverage implementation plan (15 tasks)

* feat(admin): add payment routes (payments list/detail, payment methods CRUD)

* feat(admin): add shipping routes (methods, rates CRUD)

* feat(admin): add location and addresses routes

* feat(admin): register payment/shipping/location/addresses routes and menu entries

* chore(admin): delete unused identity.api.ts (duplicate of user.api.ts)

* feat(admin): add catalog assign/revoke API functions (option-types, classifications, variant option-values)

* feat(admin): add variant image API functions (getById, download, embeddings)

* feat(admin): add stock items import API function

* feat(admin): wire user role/permission assign/revoke stubs to real endpoints

* feat(admin): convert AddressList to standalone page with user picker

* feat(admin): add stock movements list page

* feat(admin): add stock items CSV import page

* feat(admin): add resume button and line-item CRUD to OrderDetail

- Export OrderLineItem interface from order.api.ts
- Add resume, updateLineItem, removeLineItem, listLineItems to orderService
- Add resumeOrder, updateLineItem, removeLineItem to orderStore
- Add resume button (visible when status is Canceled) to OrderDetail view
- Replace placeholder text with DataTable for line items with inline quantity editing
- Add i18n keys for resume, line-item update/remove messages
- Load line items via listLineItems on mount and after relevant mutations

* chore(admin): add i18n keys for addresses page and commit remaining changes

* fix(admin): address final review findings — i18n for empty states, error handling, file upload label

* docs(spec): admin SPA standardization design — 8-phase refactor across layout, menu, components, modules, forms, dashboards

* docs(plan): admin SPA standardization implementation plan — 23 tasks across 7 phases

* feat(admin): persist layout preferences to localStorage

* fix(admin): remove duplicate FloatingConfigurator, keep topbar gear icon trigger

* fix(admin): wire topbar profile dropdown, remove calendar/messages placeholders

* feat(admin): add sidebar user footer with avatar, name, email, logout

* fix(admin): nest roles/permissions routes under AppLayout, standardize to dot-notation names

* refactor(admin): normalize all route names to dot-notation convention

* feat(admin): create menu config file with permission-gated module groups

* feat(admin): integrate menu config with permission filtering

* fix(admin): restore item.visible !== false checks lost in aba2c7a5

- MenuItem.Layout.vue: add && item.visible !== false to four template v-if directives
- Menu.Layout.vue: groupHasVisibleItems now also rejects items with visible===false
- admin-menu.config.ts: add visible?: boolean to MenuItem interface

* feat(admin): create FormField component with tests

* feat(admin): create DataTableShell component with tests

* fix(admin): add generic type to DataTableShell, remove unused columnCount

* feat(admin): create remaining shared components (DetailField, StatusBadge, EmptyState, ConfirmButton, StatCard, TabbedDetail)

* fix(admin): fix ConfirmButton and StatusBadge tests — proper emit assertion and component integration test

* feat(payment): rewrite PaymentList with DataTableShell and PageShell pattern

- Replace raw DataTable/Column with DataTableShell + PageShell + PageHeader
- Add pagination, sorting, refresh, and search via store params
- Add i18n with fallback for all labels and messages
- Add row-action slot with eye button navigating to detail

* feat(payment): rewrite PaymentDetail with Detail template pattern

- Use PageShell + PageHeader with back button, status badge, action buttons
- Use DetailField in responsive grid for payment information
- Add transactions DataTable and gateway response panel
- Add confirmation dialogs for capture/void/refund actions
- Add error handling with toast notifications

* feat(shipping): rewrite ShippingMethodList with DataTableShell and CRUD actions

- Use PageShell + PageHeader + DataTableShell for consistent layout
- Add pagination, sorting, refresh via store params
- Add create button routing to shipping.methods.create
- Add edit, delete, and toggle-active row actions
- Use ConfirmButton for delete with confirmation dialog

* feat(shipping): rewrite ShippingRateList with DataTableShell and CRUD actions

- Use PageShell + PageHeader + DataTableShell for consistent layoutk
- Add pagination, sorting, refresh via store paramsk
- Add create button routing to shipping.rates.creates
- Add edit and delete row actions with confirm

* feat(admin): Phase 7 polish — gradient topbar border, route transitions, breadcrumb audit

- Add animated gradient ::after border to .layout-topbar (respects prefers-reduced-motion)
- Wrap <router-view /> in <Transition name="layout-main" mode="out-in">
- Add breadcrumbs to ordering.orders.list, inventory.locations.list,
  users.staff/customers grouping routes (remove duplicates from children)

Closes #7.1 #7.2 #7.3

* chore(admin): final adjustments — form model fixes, DataTableShell generic removal, build verification

* fix(admin): address code review findings — StatusBadge on PaymentDetail, handler wiring, sidebar type safety

* fix(admin): address C2-C4 review findings — StaffForm field mapping, CustomerDetail tabs, ShippingRateForm ranges

* fix(admin): fix pre-existing build errors — TreeNode import, type casts, option-value store arg fix

* fix(admin): update option-value store test to match new 2-arg API call

* fix(Profile): rename admin address classes to avoid duplicate endpoint names

Follow the CreateProfile->CreateUserProfile pattern: rename admin
address feature classes to use 'User' prefix for disambiguation.
- CreateAddress -> CreateUserAddress
- UpdateAddress -> UpdateUserAddress
- DeleteAddress -> DeleteUserAddress
- GetAddressById -> GetUserAddressById

Folders kept as action-only (Create/, Update/, Delete/, Get/ById/)
matching the store side convention.

* fix(admin): show all menu groups when permissions are not loaded

* fix(admin): wire real user permissions — add permissions to auth store computed, fix mapper, update menu

* refactor(admin): consolidate refactored Admin SPA into lagacy directory

- Delete app/Admin/ entirely (old structure nuked)
- Merge all refactored code into app/lagacy/Admin/:
  - Extract API client into modular interceptors (auth, camelCase, error-wrapper)
  - Rename all PascalCase files to kebab-case
  - Convert .then() chains to async/await across all API files
  - Migrate ApiResult type to ServerResult (isSuccess, value, errors)
  - Add auth api/mappers, model types, handler spec files
  - Add inventory sub-feature scaffolding (stock-items, stock-locations, stock-movements, stock-transfers, inventory-units)
  - Add location sub-features (countries, states)
  - Add ordering sub-features (orders, fulfillment)
  - Add payment, shipping, reports, profile address sub-features
  - Add users sub-features (roles, permissions with api/service/store)
  - Clean up schemas (permission, role, user, shipping, payment)
  - Remove all JSDoc comments from composables and utils
  - Enable noUncheckedIndexedAccess in tsconfig

* feat(admin): scaffold new Admin SPA with PrimeVue, Pinia, and Vite

* refactor(api): convert records to block-body syntax

Convert ~79 non-Command/Query records from primary-constructor syntax
to explicit block-body `{ get; init; }` property syntax across Shared,
Catalog, Dashboard, Identity, Inventory, Ordering, Payment, Profile,
Shipping modules.

Updates all positional/named-parameter call sites to object initializer
syntax in both production and test code.

Also fixes:
- CORS origins not populating policy.Origins (add WithOrigins call)
- Duplicate permission identifiers in DashboardFeatureMetadata
  (Orders, Catalog, Inventory sections now use unique resource keys)

2424/2424 Shared.UnitTests passing, 2567/2568 Module.UnitTests passing
(1 pre-existing LocationSchema failure)

Closes #refactor-record-primary-constructors-1

* refactor(profile): consolidate handlers under Store, remove ICurrentUser from handlers

- Move all shared models/validators/mappings under Admin/<Entity>/Shared/
- Delete Store/Addresses/Shared/ (redirected to Admin shared)
- Fix 8 broken Store.Profiles.Shared namespace references
- Fix namespace/location mismatch: GetProfile files → Store
- Admin Profile CRUD endpoints delegate to Store handlers
- Admin Address CRUD + GetAll endpoints delegate to Store handlers
- Remove ICurrentUser from all 16 Store handler constructors
- Add Guid UserId to all Command/Query records
- Update Parameters to use QueryingParameters with ToPagedOrAllAsync
- Use AddressConstant.Query fields in ParseAll calls
- Delete 9 Admin handler test files (handlers no longer exist)
- Update all Store test files: remove ICurrentUser mocks, add UserId to commands
- Fix Shipping test pre-existing bugs

* refactor(models): unify request/response models with shared base records across all modules

- Add Shared.Application.Models.Parameters (Activatable, Named, Seo, Sortable) and Responses (Auditable, Response)
- Convert feature-specific Request/Response classes to inherit from shared base records
- Remove duplicate ShippingMethodUpdateParameters/Request and ShippingRateUpdateParameters/Request
- Update mappings, validators, and tests to match new model hierarchy
- Clean up outdated superpowers plans and specs
- Add plan: feature-code-commenting-api-services-1

* docs(api): add structured code comments to services and all 252 CQRS handlers

Apply Code Commenting Standard v3.0 (CommentingRules.xml) across:
- 46 service files (Inventory, Catalog, Ordering, Payment, Shared)
- 252 CQRS handler files (all modules: Identity, Catalog, Profile,
  Inventory, Ordering, Payment, Location, Shipping, Dashboard)

Adds class-level XML doc (/// <summary>) to 79 previously un-documented
handler classes and structured inline labels (CAT-1 to CAT-9) to 65
handler bodies previously missing them. Upgrades 4 /// <inheritdoc />
references to explicit summaries.

Build: 0 warnings, 0 errors. Tests: 2509 passed, 1 skipped.

* fix(payment): check domain Result in webhook background job handlers

Capture Result from Complete(), Fail(), and Refund() domain method calls.
Log warning and skip SaveChangesAsync when Result.IsFailure.
Prevents silently writing corrupt state after rejected domain transitions.

* fix(payment): make PaymentMethodId nullable to support EF Core SetNull

Change PaymentCapture.PaymentMethodId from Guid to Guid? to fix
EF Core SetNull delete behavior on a non-nullable FK column. Update
mappers and tests to use GetValueOrDefault() for Guid? to Guid assignment.

* fix(payment): add transaction scope and fail-fast unregistered gateways in VoidOrderPayments

* fix(payment): pass GatewayOptions to CancelAsync instead of inline construction (GW-005)

* fix(payment): override GetPaymentStatusAsync in BogusGateway, fix misleading idempotency comment

* test(payment): add VoidOrderPaymentsTransactionTests for transaction rollback

Add VoidOrderPaymentsTransactionTests to test transaction rollback behavior:
- Test gateway-not-registered triggers RollbackAsync
- Test void-failure triggers RollbackAsync

Uses mocked IApplicationDbContext to avoid in-memory DB transaction limitation.
Fix nullable reference warning in BogusGatewayTests (CS8604).

Task 8 of 9

* test(payment): add tests for webhook Result checking and BogusGateway status override

* fix(payment): pass target state instead of currentState twice in state transition validator

* fix(payment): delete dead HandleAsync with hardcoded signature literal from StripeWebhookDispatcher

* fix(payment): delete legacy StripeWebhookHandler — replaced by StripeWebhookDispatcher

* chore(payment): delete 4 legacy duplicate files — GatewayConstants, Gateway, StripeSetting, IWebhookHandler

* test(payment): retag StripeGatewayAuthorizeTests as Integration (makes real HTTP calls to Stripe)

* docs(payment): fix README.yaml — nullable PaymentMethodId, remove phantom properties, correct webhook route

* fix(inventory): restore CountOnHand when releasing cart reservation

BUG-002: ReleaseCartReservation handler set State=Released but never
incremented CountOnHand. Released quantity was permanently lost from
available inventory. Now loads the stock item and restores the quantity.
Switched to StockReservationMethod.Release() domain method for state
validation.

* fix(inventory): add missing SaveChangesAsync to ReleaseCartReservationsAsync

BUG-001: The method mutated reservation states and stock items but never
called SaveChangesAsync — all changes were silently discarded. Added
SaveChangesAsync after the loop. Also added wasActive guard to prevent
double-restore on repeated calls (BUG-004 cart path).

* fix(inventory): prevent double-restore on repeated release/expire

BUG-004: ReleaseReservationsAsync and both expire methods unconditionally
added quantity to CountOnHand. Repeated calls double-restored stock.
Added wasActive guard — only restore if transitioning from Reserved.

* test(inventory): add expire idempotency tests for BUG-004

* fix(inventory): use available stock for decrement guard

BUG-003: DecrementStockAsync checked raw CountOnHand against quantity
but ignored active reservations. If 10 on-hand with 3 reserved, a
decrement of 8 was allowed (only 7 available). Now computes available =
CountOnHand - activeReserved before the guard.

* fix(inventory): guard against null ExpiresAtUtc in GetReservationsForCartAsync
BUG-005: ExpiresAtUtc!.Value threw NRE when reservation had null expiry.
Added ExpiresAtUtc != null to EF query filter.

* fix(inventory): add serializable transaction to ReserveAsync
RISK-001: ReserveAsync had no transaction isolation. Concurrent reserve
calls could oversell between the stock-item read and reservation insert.
Now wrapped in IsolationLevel.Serializable tx matching ReserveCartStock.

* fix(inventory): use domain method AdjustCountOnHand in BulkAdjust
RISK-003: BulkAdjustStockItems directly mutated CountOnHand += delta
without validating result >= 0. Negative adjustments could push stock
below zero. Now delegates to StockItemMethod.AdjustCountOnHand.

* fix(inventory): restrict backorder fulfillment to Reason='backorder'

RISK-004: FulfillBackordersInternalAsync matched ANY active Reserved
reservation, including pending order reservations. Added Reason filter
to only fulfill reservations explicitly marked as backorders.

* fix(inventory): remove duplicate ReservationExpiryService BackgroundService

RISK-005: Both ReservationExpiryService (BackgroundService, 60s sweep)
and ReservationExpiryJob (Hangfire recurring) called
ExpireReservationsAndRestoreStockAsync. Removed the BackgroundService;
Hangfire job remains as the single expiry mechanism.

* fix(inventory): pass ApplicationStopping token to Hangfire expiry job

RISK-007: ReservationExpiryJobScheduler registered the Hangfire job with
CancellationToken.None, preventing graceful cancellation on shutdown.
Now injects IHostApplicationLifetime and passes ApplicationStopping.

Also removes orphaned ReservationExpiryServiceTests.cs (class deleted in 4242dad9).

* fix(inventory): add reservation-aware overload to AvailabilityValidator

RISK-006: IsAvailable summed raw CountOnHand ignoring active reservations.
Added IsAvailableWithReservations overload that subtracts reserved quantity.
Original method preserved with doc warning.

* fix(inventory): add RowVersion optimistic concurrency to StockTransfer

RISK-008: StockTransfer lacked a concurrency token. Two admins could
simultaneously transfer/receive the same draft. Added uint RowVersion
with .IsRowVersion() matching StockItem pattern.

* fix(inventory): use available (on-hand minus reserved) for IsLowStock check

IsLowStock was comparing raw CountOnHand against LowStockThreshold,
ignoring active reservations. When an item had 8 on-hand with 4 reserved
(available=4) and threshold=5, it was incorrectly not flagged as low.
Now uses the computed available quantity.

Added test: GetStockSummaryAsync_ShouldFlagLowStock_WhenAvailableBelowThreshold.

* perf(inventory): add indexes on StockReservation VariantId and ExpiresAtUtc

Queries filter by VariantId (stock summary grouping) and ExpiresAtUtc
(expired reservation cleanup). Adding covering indexes avoids full
table scans on the StockReservations table.

* fix(inventory): add composite indexes on StockReservation for release queries

* chore(inventory): nits cleanup — add cart-to-order OrderId note
NIT-001 satisfied by Task 1 (domain method Release() usage).
NIT-002 (shared helper extraction) deferred — not blocking.
NIT-003 satisfied by Tasks 2+3 (harmonized release patterns).
NIT-004 (N+1 in GetAvailability) deferred — zero-available snapshots are rare.
NIT-005: Added comment documenting that cart reservations need OrderId
patched during cart-to-order flow.

* feat(inventory): add DB migration for concurrency tokens and indexes

* fix(inventory): use domain Release() method in cart release service

* fix(inventory): add RowVersion to StockReservation, use domain Release() consistently

* fix(inventory): clean migration — remove catalog/payment drift, add RowVersion to stock_reservations

* chore(migrations): squash to single InitialCreate migration

* fix(inventory): address remaining review findings — domain Expire(), serializable tx, skip InMemory concurrency tests

* feat(inventory): add CheckStockAvailability MediatR query

* test(inventory): add unit tests for CheckStockAvailability query

* refactor(ordering): replace AvailabilityValidator with CheckStockAvailability query in UpdateCartItemQuantity

* test(ordering): update UpdateCartItemQuantity tests for ISender-based stock check

* refactor(ordering): remove AvailabilityValidator pre-check from AddToCart — rely on ReserveCartStock

* fix(demo-seed): repair size extraction and harden image pipeline

- 02_extract_products.py: fix extract_sizes_from_json to read
  opt['name']=='Size' / opt['value'] instead of non-existent
  opt['sizeOption'] key. Use Path() for cross-platform storage_path.
- 03_process_images.py: track file_name in dedup map, warn on
  conflicts if storage_path maps to different source files.
- run_all.py: guard shutil.copytree against missing output/images
  with explicit exists() check and error message.
- Product.Seeder.cs: fileSize 1 -> 0 (sizes unknown during seeding).
- plan: mark feature-demo-seeders-v5-1 as Completed.

* test(ordering): update AddToCart reservation tests for AvailabilityValidator removal

* refactor(inventory): delete AvailabilityValidator — replaced by MediatR queries

* chore: final validation — all tests pass, 0 warnings

* fix(ordering): prevent double-counting shipping in RecalculateTotals

Exclude SourceType=Shipping adjustments from AdjustmentTotal since
ShipmentTotal already captures them. Total = ItemTotal + ShipmentTotal
+ AdjustmentTotal no longer counts shipping twice.

* fix(ordering): reject Approve() on non-Placed orders

Guard order.Status != Placed before approving. Draft orders can no longer
be approved. Updated existing AlreadyApproved test to use Placed order.

* fix(ordering): reject Empty() on Expired orders

* fix(ordering): use NotDraftForShippingMethod error in SetShippingMethod

Previously returned NotDraftForShipAddress which was semantically wrong.

* refactor(ordering): remove LineItem.FinalAmount() dead abstraction

Method was a pure accessor returning Total unchanged. No non-test callers.

* refactor(inventory): remove TotalAvailable from CheckStockAvailability.Response

Field was always set to 0 — dead data. Query is lightweight UX pre-validation.

* fix(ordering): remove dead IsFailure check and Inventory domain import

CheckStockAvailability handler never returns failures. Replaced cross-module
StockItemResult.Errors.InsufficientStock with OrderResult.Errors.CartQuantityInvalid.

* test(ordering): remove dead StockItem/StockLocation setup from UpdateCartItemQuantity tests

Handler uses CheckStockAvailability via ISender, not direct stock queries.

* fix(ordering): filter inactive locations in AddToCart, replace null-forgiving op

Guard reservation against inactive StockLocations by including them in the
query filter. Replace currentUser.UserId! with ?? string.Empty for safety.

* refactor(ordering): simplify CancelOrder wasPlaced check

Both Place() and Finalize() always set CompletedAtUtc when transitioning
to Placed. The HasValue check was a redundant defensive guard.

* refactor(ordering): remove redundant catch/rollback/rethrow in CreateOrderFromCart

EF Core transaction auto-rollback on DisposeAsync when not committed.
Explicit RollbackAsync before throw was redundant.

* fix(ordering): add pagination to CartExpiryJob, use domain Delete() method

Process expired carts in batches of 500 to prevent OOM. Use
cart.Delete(Default.CreatedBy) instead of direct mutation to preserve
DeletedBy in audit trail.

* feat(payment): add Disputed state to PaymentRecordState enum

* feat(payment): add Dispute() domain method with AlreadyDisputed guard

* feat(payment): make GetPaymentStatusAsync abstract on Gateway — prevents silent default

* feat(payment): add TransientGatewayError and PaymentMethodRequired error factories for Stripe

* feat(payment): handle requires_action (3DS) and requires_payment_method in PurchaseAsync

* fix(payment): distinguish transient StripeException (5xx/api_error) from terminal declines

* fix(payment): wrap amount-to-cents conversion in checked{} to fail on overflow

* feat(payment): pass StatementDescriptorSuffix and ShippingAddress to Stripe PaymentIntent

* refactor(payment): reuse Stripe SDK service instances as fields instead of new per call

* fix(payment): add Hangfire [AutomaticRetry(3)] to webhook job — prevents dropped webhooks on transient DB errors

* feat(payment): add partial index ix_payment_captures_response_code for webhook lookups

* fix(payment): catch StripeException not Exception in ParseEvent — prevents swallowing fatal errors

* fix(payment): guard RefundAsync and CaptureAsync against Disputed state

* feat(payment): fail startup if Stripe enabled but SecretKey or WebhookSecret is empty

* feat(payment): transition payment to Disputed state on charge.dispute.created webhook

* test(payment): add tests for Dispute domain method, dispute webhook, and StripeSettingValidation

* feat(payment): add all 7 PaymentIntent statuses + 3 new webhook event constants

* feat(payment): add SuccessUrl and CancelUrl to GatewayOptions for 3DS return flow

* feat(payment): propagate PaymentStatus from gateway response through entity to response DTO

* feat(payment): register 3 new webhook event types in StripeWebhookDispatcher

* refactor(payment): remove Stripe API polling from ConfirmPayment — rely on webhook

* feat(payment): add StatementDescriptorSuffix to PaymentMethod, use instead of hardcoded empty

* feat(payment): handle requires_action, processing, and canceled webhook events

* test(payment): fix ConfirmPayment tests, add webhook canceled + PaymentStatus mapping tests

* fix(payment): make ReturnUrl conditional and use IntentStatus constant for paymentStatus

* fix(payment): add 6 missing transitions to IsValidTransition — Fail and Dispute paths

* fix(payment): make Capture() domain method set State=Completed and ModifiedAtUtc

* fix(payment): remove redundant catch{rollback} from VoidOrderPayments — await using auto-rolls back

* feat(payment): add optional PaymentMethodId to CreatePaymentIntent

* fix(payment): replace 4 direct State= mutations with domain methods (Capture/Complete/Pend/Void)

* refactor(payment): consolidate 7 duplicate error codes to PaymentCaptureResult.Failure

* fix(payment): BogusGateway returns unknown not succeeded for unrecognized auth codes

* refactor(payment): consolidate CentsMultiplier to GatewayConstants.Amounts

* fix(payment): RefundAsync delegates to domain Refund() — single source of truth for RefundedAmount

* refactor(payment): consolidate CentsMultiplier to GatewayConstants.Amounts

* refactor(payment): remove dead CaptureEventCreated field — never read in any handler

* fix(payment): add amount overflow guard before checked{} casts in StripeGateway

* test(payment): add tests for IsValidTransition gaps, Capture() mutation, BogusGateway unknown, PaymentMethodId

* docs: apply code commenting standard v3.0 across all handlers, services, and stores

Add structured inline labels (CAT-1 through CAT-10), XML doc-comments,
TSDoc, and invariant/boundary annotations per CommentingRules.xml.

Phase 1: Add <summary> and // Map: labels to ~250 .Endpoint.cs files
Phase 2: Add XML doc-comments to 18 service interfaces
Phase 3: Add // Invariant: annotations to domain aggregate roots
Phase 4: Add // Contract: and inline labels to ~50 partial-coverage handlers
Phase 5: Add TSDoc to TypeScript stores and API client
Phase 6: Add <summary> and // Const: to 19 loggers/constants/result files

Verification: dotnet build (0 warnings), unit tests (4962 passed),
TypeScript lint (pass).

* docs: add ordering/payment/stripe design specs and legacy shop app

* docs: add ordering/payment/stripe remediation plans

* docs(spec): single-default currency/locale consolidation design

* docs(plan): single-default currency/locale consolidation — 5 tasks

* chore(security): remove dead store_currency permission — no admin endpoint or UI

* refactor(catalog): delegate Variant.AllowedCurrencies to SystemCurrency.Supported

* feat(shared): add DefaultLanguage config via appsettings, ISystemInfo, and constant fallback

* feat(payment): add Currency property to PaymentCapture with migration and storefront mapping

* fix(ordering): change line_items.currency from text to varchar(3) with USD default

* fix(migration): add catch-up migration for pending PaymentStatus, StatementDescriptorSuffix, and CaptureEventCreated removal

* docs: api review remediation design spec

* docs: api review remediation implementation plan — 23 tasks across 6 clusters

* fix: remove production gate on health check endpoints

* docs: fix HSTS claim in SecurityHeadersMiddleware, add header emission test

* fix: apply RequireRateLimiting to auth, register, forgot-password, payment endpoints

* docs: add CORS origins configuration guidance to appsettings.json

* test: add Base64Url round-trip and encoding regression tests

* fix: use ToBase64Url in ResendEmailVerification to match ConfirmEmail decoder

* fix: use ToBase64Url in ChangeEmail.BuildConfirmPath to match ConfirmEmail decoder

* fix: add UserId NotEmpty validation to ConfirmEmail validator

* fix: add terminal-state guards to Stripe webhook handlers for idempotency

* fix: defer payment capture persistence until after gateway call succeeds

* docs: explain CancellationToken.None in StripeWebhook Hangfire enqueue

* fix: use domain Pick() for stock deduction, add retry on concurrency conflict

* fix: use RepeatableRead instead of Serializable for cart stock reservations

* fix: add validator, constants, and result errors for ReserveCartStock

* fix: guard against Reserve() failure instead of accessing .Value unsafely

* fix: add file extension validation for variant image uploads

* fix: sanitize filename with Path.GetFileName before constructing storage key

* fix: log warning when Stripe webhook event parse fails

* docs: add missing OpenAPI Produces annotations for conflict, validation, and no-content responses

* fix: require authorization on checkout endpoint instead of returning domain error

* fix: await profile creation and notification before returning NoContent in ConfirmEmail

Move SendWelcomeNotificationAsync and CreateUserProfileAsync to fire
after the log block, wrapped in Task.WhenAll, so they run before the
response is returned. CreateUserProfileAsync now fires for both email
change and first-time verification cases.

Update test to reflect that profile creation always fires.

* fix: rename StockReservationExpiryDaysInMinutes, remove dead outer catch

* docs: workflow integration tests design spec — 4 cross-module workflows replacing smoke tests

* docs: workflow integration tests implementation plan — 6 tasks, 4 cross-module workflows

* test: drop smoke tests, add WorkflowTestBase for cross-module workflow tests

* test: add GuestRegistrationWorkflowTests — register, verify, login, access profile

- Create GuestRegistrationWorkflowTests with cross-module workflow test
- Fix migration: ResponseCode filter uses case-sensitive PostgreSQL identifier
- Fix rate limiting: always register named policies even when disabled

* test: add BrowseCatalogToCheckoutWorkflowTests — browse, cart, register, address, checkout

* feat(payment): add Stripe CLI container to Aspire orchestration

Add Stripe webhook forwarding as an orchestrated Aspire resource:
- Add Stripe CLI container (docker.io/stripe/stripe-cli) with dynamic
  forward URL via ReferenceExpression
- Configure StripeApiKey and StripeWebhookSecret as Aspire parameters
- Pass Stripe secrets to API via GatewayProviders__stripe__* env vars
- Enable Stripe gateway in Development config with test credentials
- Relax StripeSettingValidation: WebhookSecret no longer required
  at startup (only needed at runtime for webhook signature validation)
- Stripe CLI container waits for API before starting (.WaitFor(api))

* refactor(aspire): extract Stripe magic strings into constants

Move all Stripe-related magic strings from AppHost.cs into
ReSys.ServiceDefaults.Constants:
- Constants/Stripe.cs — Parameters, EnvironmentVariables, Cli args,
  WebhookRoute, WebhookEvents
- Constants/Images.cs — Stripe.Cli image reference
- Constants/Services.cs — StripeCli service name

* fix(seeders): per-record idempotency for catalog seeders, gate seeders on migration success

- CatalogTaxonSeeder: add per-record ID check to skip existing taxons
- CatalogDemoSeeder: add per-record ID checks for Products, Variants,
  VariantImages; composite-key checks for OptionAssignments,
  Classifications, ProductOptionTypes
- CatalogEmbeddingSeeder: add FK guard (skip embeddings referencing
  non-existent VariantImages) and per-record (VariantImageId, ModelName)
  dedup
- DatabaseInitializer: gate seeders on migration success (skip seeding
  if RunMigrations returns false)
- PaymentRecordConfiguration: remove ResponseCode index

* revert: remove extraneous commits from cancelled subagent

* test: extract GetAccessToken to IdentityTestHelper, add cart associate/shipping-rate API calls, guest cart flow

* test: add AdminCreateCustomerBuy and ForgotPasswordReset workflow tests

* fix: create profile before address in workflow tests, fix field names (stateProvince, zipCode)

* fix: create UserProfile via DB scope before address creation in workflow tests

* fix: create shipping method fallback when 'standard' not seeded

* fix: merge DB scopes, set shipping method directly on cart, add fallback creation

* fix: pass userId to UserProfileMethod.Create in AdminCreateCustomerBuyWorkflowTests

* docs: add 4-layer architecture restructure design spec

* docs: add 4-layer architecture restructure implementation plan

* fix: barrel population ordering in 4-layer plan

* chore: scaffold common/, shared/utils/, shared/types/ directories with barrels

* feat: add result.type.ts to shared/types/ (pre-migration copy)

* refactor: move shared/models/ → shared/types/

* refactor: move shared/mapper/ → shared/utils/

* refactor: delete duplicated barrels, rewrite shared/index.ts

* refactor: move api + token.service to common/, merge error.type

* refactor: move query-string.builder → shared/utils/

* refactor: views/→pages/, stores/→store/, inline auth.service+mapper

* chore: final verification — fix index.html entry, tests+type-check+build pass

* docs: add shared component library design spec (27 components, P0/P1/P2)

* docs: add P0 shared component library implementation plan (16 tasks)

* feat: scaffold shared component category directories and barrels

* feat: add DetailField component with tests

* feat: add FormField component with tests

* feat: add EmptyState component with tests

* feat: add ConfirmButton component with tests

* feat: add PageContainer component with tests

* feat: add PageHeader component with tests

* feat: add Section component with tests

* feat: add SearchInput component with tests

* feat: add DetailGroup component with tests

* feat: add DescriptionList component with tests

* feat: add CopyButton component with tests

* feat: add SkeletonLoader component with tests

* feat: add LoadingOverlay component with tests

* feat: add DeleteDialog component with tests

* docs: add shared/common unit test implementation plan (6 test files, ~80 cases)

* test: add pagination.model unit tests

* test: add result.type unit tests

* test: add filtering.model unit tests

* test: add query-string.builder unit tests

* test: add refresh.handler unit tests

* test: add error.interceptor unit tests

* test: add shared/utils and common/api unit tests, fix type errors

* chore(cleanup): remove 92 stale plan/spec/harness files

* chore(security): move DB connection and Stripe secrets to dotnet user-secrets

- Remove hardcoded DB password from appsettings.Development.json
- Add ConnectionStrings:DefaultConnection to setup-dev-secrets.sh
- Add optional Stripe secret key support via env vars
- Replace hardcoded password in .env.template with placeholder
- Update dev secrets setup comment to reflect all managed secrets

* Admin panel: embedding management, auth guard, list fixes, and more (#2)

* fix(catalog): fetch variants immediately when productId present

* refactor(catalog): drop unused get import from variant list services

* docs(catalog): reconcile plan with standalone variant routes

* fix(catalog): address final review minors for variant list alignment

* refactor(catalog): flatten feature routes and move parent ids out of paths

Flatten CatalogFeature endpoint constant groups into sibling entity
classes (Admin and Storefront) and relocate nested parent ids from URL
path segments into request bodies for commands and query parameters for
queries, per plan/refactor-catalog-feature-1.md.

- Rewrite CatalogFeature.Admin/Storefront into flat entity-group shape
- Relocate VariantId/ProductId/TaxonId/OptionTypeId parent ids to bodies
  and query strings; rename PermissionContext resource descriptors
- Move OptionValues, ProductOptionTypes, VariantOptionValues feature
  folders and update all endpoints, smoke tests, and unit/integration tests

* feat(admin): add delWithBody helper for delete-with-body endpoints

* refactor(catalog): flatten taxon service routes and reconcile taxon tree

* refactor(catalog): flatten taxon rule service routes

Rewrite taxonRuleApi.ts against flat api/catalog/taxon-rules base, move
taxonId into create/update bodies, use delWithBody for delete, add
syncRules. Update TaxonRuleFormDialog call sites and taxonRuleApi spec.

* refactor(catalog): flatten product option type service routes

* refactor(catalog): flatten product classification service routes

* refactor(catalog): flatten variant option value routes and add sync

* refactor(catalog): flatten variant price routes and add sync

* refactor(catalog): flatten variant image routes and add blob download

* fix(catalog): use PATCH for product activate and discontinue

* refactor(catalog): add dedicated type and validation files for option types, classifications, prices, images, embeddings

* feat(catalog): add image embedding API service

* feat(catalog): add taxonomy restore and catalog dashboard services

* feat(catalog): add catalog feature composables wrapping usePagedQuery

* test(catalog): add service specs for option types, classifications, embeddings, dashboard and fix flat option-value URLs

* feat(identity): add role and user form validations

* feat(identity): add role, user, and permission types

* feat(identity): add role API service

* feat(identity): add user API service

* feat(identity): add permission API and role/user stores

* feat(identity): add role and user list/detail composables

* test(identity): add role, user, and permission specs

* feat(inventory): add stock item, location, and transfer form validations

* feat(inventory): add stock item, location, movement, reservation, and transfer types

* feat(inventory): add stock item API service

* feat(inventory): add stock location API service

* feat(inventory): add stock movement API service

* feat(inventory): add stock reservation API service

* feat(inventory): add stock transfer API service

* feat(inventory): add inventory dashboard API and stock stores

* feat(inventory): add stock list composables

* test(inventory): add stock service, validation, type, and store specs

* feat(ordering): add order and ordering dashboard types

* feat(ordering): add order form validations

* feat(ordering): add order API service

* feat(ordering): add ordering dashboard API and order store

* feat(ordering): add order list and detail composables

* test(ordering): add order service, validation, type, and store specs

* feat(payment): add payment method and payment types

* feat(payment): add payment method form validations

* feat(payment): add payment method API service

* feat(payment): add payment API and payment method store

* feat(payment): add payment and payment method composables

* test(payment): add payment and payment method specs

* feat(profile): add profile and address form validations

* feat(profile): add profile and address types

* feat(profile): add profile API service

* feat(profile): add address API and profile/address stores

* feat(profile): add profile and address composables

* test(profile): add profile and address specs

* feat(shipping): add shipping method and shipping rate form validations

* feat(shipping): add shipping method and shipping rate types

* feat(shipping): add shipping method and shipping rate API services

* feat(shipping): add shipping method and shipping rate stores

* feat(shipping): add shipping method and shipping rate composables

* test(shipping): add shipping method and shipping rate specs

* feat(location): add country and state by-iso lookups

* feat(dashboard): add dashboard types

* feat(dashboard): add dashboard API and store

* feat(dashboard): add useDashboard composable

* test(dashboard): add dashboard api, type, and store specs

* fix(admin): normalize query consts and filter DSL to camelCase to match client-side validation

* fix(identity): route role name lookup through search fields to match backend filter whitelist

* chore(admin): fix lint errors in shared and auth code to pass quality gate

* chore(admin): replace vi.fn<any>() with typed mocks to pass eslint

* fix(catalog): use flat option-values route in OptionTypeDetail

* docs(plan): mark feature-admin-data-layer-1 complete with task completion dates

* fix(inventory): normalize stock movement and reservation query consts to camelCase

* docs(spec): design remaining 27 admin views across 7 modules

* docs(plan): 8 implementation plans for remaining 27 admin views + cleanup

* feat(dashboard): replace placeholder with stat cards grid

* feat(identity): implement users list view with search, delete, export

* feat(identity): implement user detail view with profile and roles tabs

* feat(identity): implement roles list view with search, delete, export

* feat(identity): implement role detail view with profile and permissions tabs

* feat(identity): implement permissions list view (read-only)

* feat(inventory): implement stock items list view

* feat(inventory): implement stock item detail view

* fix(inventory): ensure current variant always present in stock item dropdown

* feat(inventory): implement stock locations list view

* feat(inventory): implement stock location detail view

* feat(inventory): implement stock reservations list view (read-only)

* feat(inventory): implement stock transfers list view

* feat(inventory): implement stock transfer detail view

* feat(inventory): implement stock movements list view (read-only)

* feat(ordering): implement orders list view with status filter

* feat(ordering): implement order detail view with overview, items, and payments tabs

* feat(payment): implement payments list view (read-only)

* feat(payment): implement payment methods list view

* feat(payment): implement payment method detail view

* feat(profile): implement profiles list view

* feat(profile): implement profile detail view with addresses tab

* fix(payment): harden Stripe webhook endpoint, fix PII leak, add concurrency control

Security fixes:
- Add 64KB request body size limit + webhook rate limiter (DoS prevention)
- Strip encrypted gateway Settings from storefront PaymentMethod response
- Replace raw Stripe payload in error logs with safe metadata (PII leak)

Correctness fixes:
- Add Stripe event ID deduplication via ProcessedStripeEventIds jsonb column
- Add RowVersion optimistic concurrency on PaymentCapture entity
- Add retry-on-concurrency-conflict to admin RefundPayment handler
- Fix StockReservationExpiryMinutes comment (code is 30 min, not 30 days)
- Log ignored webhook event types (requires_action, processing)

Tests:
- Add Inventory integration tests (stock transfer lifecycle, reservation expiry)
- Add Inventory schema to ApiFixture AllSchemas for proper test isolation

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(profile): navigate to profile detail by userId to match detail view contract

* feat(profile): implement addresses list view

* fix(profile): gate addresses list on the baked userId to prevent empty-userId fetches

* feat(profile): implement address detail view

* fix(profile): thread owner userId into address edit links

* feat(shipping): implement shipping methods list view

* feat(shipping): implement shipping method detail view

* feat(shipping): implement shipping rates list view

* feat(shipping): implement shipping rate detail view

* chore(admin): remove unused feature directories (reports, users, error/pages)

* docs(concerns): record admin cross-feature import deviation and pagination follow-up

* refactor(catalog): reorganize variant image get endpoints into Get tree

Move GetById and ListByVariant under a Get/ hierarchy. Rename
ListVariantImages to GetVariantImagePagedOrAll, introduce a Response
record, and drop the default position sort to align with the paged
querying conventions used across the catalog module.

* docs: add CLAUDE.md agent guidance for repo commands

* feat(catalog): update option value endpoints and adjust tags for consistency

* feat(catalog): add fashion attributes to admin product model

Extend the product domain, parameters, and mapping with fashion-specific
fields (style code, season, material, care, fit, department, gender target)
and reorganize shared product models into regions for maintainability.

Also:
- include classifications and their taxons in the paged product query
- surface ClassificationsCount on list items
- drop variant pricing/dimension passthrough from the update request,
  deriving the master variant SKU and inventory flag from the entity
- remove the permission requirement from variant image download
- add a dev proxy from the Admin SPA to the API
- trim unused role parameter fields and expose role id/system flag

* feat(catalog): rework product factory signature and wire fashion fields

Reorder ProductMethod.Create to derive the slug from the product name
(overridable via slug:), add region-based parameter organization, and
thread fashion attributes (style code, season, material, care, fit,
department, gender target) through the domain factory, admin mappings,
and demo seeder.

Also:
- seed product FitNotes and parse status from demo JSON
- restore the default position sort in GetVariantImagePagedOrAll
- migrate product tests to named factory arguments, fixing the slug
  duplicate, ordering, and rule-evaluator regressions from the reorder

* docs(spec): add admin catalog views corrections design

* docs(plan): add admin catalog views corrections implementation plan

* fix(catalog): return full option-value and image sets to admin

* fix(catalog): full-set paging via empty params and aligned variant services

* feat(catalog): add product status actions and server paging to list

* feat(catalog): wire option types list to server-side paging

* fix(catalog): repair product classification and option type tabs

* docs(plan): record review-driven corrections for getPaged and PickList binding

* feat(catalog): add lazy searchable product options composable

* fix(catalog): reset loading on rejection and guard stale responses

* feat(catalog): refactor variants list with product selector

* fix(catalog): final-review fixes for variants list and product detail

- VariantsList: consolidate product change to one fetch (productId watch
  drives reset+fetch; route watcher only syncs from route; drop redundant
  setSearch/setPage/refresh); clear stale searchTerm on product change;
  gate DataTable behind v-else so error and table are exclusive.
- ProductDetail: gate 'no option types/classifications' empty states on
  the loaded flags so failed loads don't show misleading messages.

* docs(spec): storefront MVP - remove USE_MOCK and enable real API

Co-Authored-By: Claude <noreply@anthropic.com>

* docs(plan): storefront MVP - 8 tasks to remove USE_MOCK and hide dropped features

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(storefront): align API repos with backend routes

Apply prior code-review fixes before the USE_MOCK removal plan:
- Fix double-unwrap bug in response interceptor
- Align category, product, similar-products, shipping-rate, search routes
- Add missing cart endpoints (create, delete, checkout details, associate,
  validate, shipping-rate select) and fix clearCart to POST /cart/empty
- Add order cancel endpoint
- Wire recommendations, search, and notifications stores to services
- Remove dead code (legacy interceptors, api service, stale router)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): flip catalog services to real API (P1)

Remove USE_MOCK from product, category, and search services.
All three now use only their ApiRepository.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: correct admin catalog upload, variant option values, paging binding, and filters

- client: clear Content-Type for FormData bodies so axios sends multipart
  instead of serializing to JSON (fixes 415 on variant-image/stock-item upload)
- variantApi.getVariants: omit empty productId query param so backend
  Guid? binding no longer fails (stock transfer/item variant selection)
- migrations: add processed_stripe_event_ids jsonb + xmin rowversion to
  payment_captures (were missing from InitialCreate)
- variant detail: replace checkbox wall with product-scoped MultiSelect
  per option type for assigning option values
- lists: add related-select filters (products dept/season/status, option
  types filterable, stock items location, transfers source/destination,
  orders checkout state)

* fix: user roles, enum strings, UTC dates, antiforgery, variant option rule, select lists, taxon tree

- user roles: only filter isAssigned roles into assignedRoleNames (all
  roles were previously checked)
- api: register global JsonStringEnumConverter so enums serialize as
  names (product status etc.) instead of numbers
- dates: add formatDateTimeUtc/toUtcIso/fromUtcToDateInput shared utils;
  apply local-time display across list/detail views; product
  availableOn/discontinueOn now round-trip UTC
- antiforgery: dev env overrides CookieSecurePolicy to SameAsRequest so
  uploads over http no longer throw SecurePolicy=Always
- variant option values: enforce exactly one value per option type in
  Assign/Sync (backend) + single-select swap in the MultiSelect UI
- select lists: fetchActive stores request full set without paging/sort
- taxon detail: parent picker now a TreeSelect with nested hierarchy
- build: fix pre-existing DateTimeOffset conversion errors in identity
  auth + test mocks that blocked compilation

* refactor(catalog): remove taxon tree feature from admin frontend

- delete taxonTreeStore, useTaxonTree composable, and their specs
- remove TaxonApi.getTree and TaxonTreeItem type
- TaxonsList: drop tree view mode (TreeTable + toggle); table only
- TaxonomyDetail: drop taxon TreeTable; keep form + add-taxon button
- TaxonDetail: parent picker back to flat Select from the taxon list
  endpoint

* refactor(catalog): rename Paged query slices to PagedOrAll

Rename the GetTaxonomiesPaged and GetOptionValuesPaged feature slices to
GetTaxonomiesPagedOrAll and GetOptionValuesPagedOrAll, moving them from
the Get/Paged directory into Get/PagedOrAll.

The slice captures both a paged and full list retrieval (ToPagedOrAllAsync),
so the Paged name was misleading. Only naming and namespaces change; logic,
routes, permissions, and response contracts are unchanged.

- Move feature files to Get/{Taxonomies|OptionTypes/Values}/Get/PagedOrAll/
- Rename Query/Handler/Parameters/Endpoint types and namespaces
- Update GetTaxonomiesPagedUseCase tests to reference the new slice

* refactor(security): use DateTimeOffset for token and audit timestamps

Replace DateTime with DateTimeOffset across auth token models, the token
blacklist service, token theft detector, refresh token service, user
security audit loggers, and the module dashboard responses (catalog,
dashboard, inventory, ordering).

DateTimeOffset preserves a stable UTC instant and avoids the ambiguity of
naive DateTime in serialized API boundaries. Domain entities already store
timestamps as DateTimeOffset, so response models and loggers now align with
persistence types instead of projecting to DateTime.

- TokenBlacklistService: BlacklistTokenAsync takes DateTimeOffset expiry
- RefreshTokenService: compute sliding max-age as DateTimeOffset
- UserLoggers / TokenTheftDetector: audit timestamps as DateTimeOffset
- Dashboard response models: CreatedAtUtc / Timestamp as DateTimeOffset
- Update unit tests accordingly and correct a stale test DisplayName

* docs(spec): remove forced Pinia stores from admin frontend design

* docs(plan): remove forced Pinia stores from admin frontend implementation plan

* feat(admin): add shared useActiveList composable for fetch-once option lists

* feat(admin): add fetch-active composables for countries, stock locations, taxonomies, users

* feat(catalog): extend useTaxonList with taxonomy scope and add useTaxonDetail composable

* chore(admin): remove dead Pinia stores and empty store barrels

* refactor(admin): rewrite dashboard page on useDashboard and useActiveUsers composables

* refactor(catalog): rewrite taxons list on useTaxonList and useActiveTaxonomies composables

* refactor(catalog): rewrite taxon detail on useTaxonDetail and useActiveTaxonomies composables

* refactor(location): rewrite states views on useActiveCountries composable

* refactor(inventory): rewrite stock item views on useActiveStockLocations composable

* refactor(inventory): rewrite stock transfer views on useActiveStockLocations composable

* chore(admin): remove replaced Pinia stores, keep authStore as the single store

* docs(plan): record approved barrel-prune and vue-tsc --build amendments

* fix(catalog): reset taxon list page when taxonomy scope changes

* docs(plan): correct new composable and spec counts

* rename(store): store -> storefront

* feat(mvp): flip identity services to real API (P2)

Remove USE_MOCK from auth and user services.

Co-Authored-By: Claude <noreply@anthropic.com>

* rename

* feat(mvp): flip cart/order services and align cart API contract

Flip USE_MOCK in cart and order services. Realign add-to-cart to send
{variantId, quantity}, selectShippingRate to send {shippingMethodId},
and cart response types/mapping to the backend CartDetailResponse shape
(itemTotal, itemCount, checkoutState, items with variantId/variantName/sku).

Co-Authored-By: Claude <noreply@anthropic.com>

* test(ordering): update cart unit tests to the variantId add-to-cart contract

cart.service.test.ts now mocks the cart API repo and exercises the new
addToCart(variantId, quantity) signature; cart.repository.test.ts passes
numeric quantities to the mock addItem and asserts the mapped result.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(ordering): enrich storefront cart items with product name and image

CartItem response now carries ProductName and ProductImageUrl, enriched
from the product entity in GetCart and AddToCart. Enables the storefront
cart page to render product thumbnails and display names.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): flip payment and shipping services, align payment-intent body

Flip USE_MOCK in payment-intent, payment-method, shipping-method,
shipping-rate. Payment-intent create now sends {amount, currency,
orderId, paymentMethodId} matching the backend contract.

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: demo seeder refactor design — domain-driven single-responsibility pipeline

* feat(mvp): align address, shipping-method, payment-method contracts to backend

Update schemas, response types, and mappings to the real backend shapes:
addresses (address1/zipCode/countryName/stateProvince), shipping methods
(name/calculatorType, no price), payment methods (providerKey, no enum type).

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): flip remaining 7 services to real API (P5)

All 18 services now use real API repositories. Zero USE_MOCK remaining.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): wire home page handlers to cart store and router

Replace console.log placeholders with real cartStore.addItem(),
router navigation for category/product clicks, and wishlist redirect.

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: demo seeder refactor implementation plan

* docs: fix Task 4 smoke-test embedding copy in seeder plan

* feat(mvp): rewrite CBIR view with real API pipeline and 4-state model

Remove hardcoded Unsplash mock data. Wire searchByImage() from
recommendationsService. Implement Empty->Upload->Loading->Results state
machine. Add similarity score badges, query image sidebar.
Hide You May Also Like (backend returns 501).

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(seed): add domain core modules for demo seed ETL

* fix(storefront): map PagedResult from CBIR search-by-image into Product[]

* refactor(seed): split taxonomy extractor into per-entity scripts

* docs: fix taxon slug allocation order in seeder plan to match old output

* feat(mvp): rewrite checkout with 5-step pipeline and real API data

Replace inline uuidv4 mock data with orderStore.fetchCheckoutData().
Implement 5-step progress indicator (Address→Delivery→Payment→Confirm
→Complete). Load real addresses, shipping methods, payment methods.
Wire place order via orderStore.checkout(). Hide save-payment checkbox.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(seed): allocate master-category taxon slug before sub-category slugs

* refactor(seed): split product extractor into per-entity scripts with variant cap

* feat(mvp): add forgot password two-step flow view

New ForgotPasswordView with email entry and token-based reset steps.
Backend: POST /api/store/identity/passwords/forgot + /reset.
Route: /forgot-password (guest). Wire login forgot-password link.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): add session management view

Route: /account/sessions. Shows active sessions with device info,
IP address, last activity. Current session badge. Logout button.

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(seed): renumber dataset outputs and add invariant verification

* feat(mvp): add wishlists feature with full CRUD and view

New types, API repo, service, Pinia store, WishlistsView.
Backend: /api/store/profiles/wishlists (full CRUD exists).
Route: /account/wishlists. Create/delete wishlists, expand to see items,
remove items. Empty, loading, and error states.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): add notification preferences view

Toggle grid for per-category email/SMS preferences.
Backend: GET/PUT /api/store/profiles/notification-preferences.
Route: /account/notifications.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(mvp): hide dropped features from UI

Hide with v-if='false': Google OAuth, reviews, search suggestions,
avatar upload, newsletter form. Fix dead footer links with '#'.
All code preserved — only visibility toggled.

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(mvp): wire cart badge to cartStore and remove counter boilerplate

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor(catalog): split demo seeders into single-entity classes

* refactor(inventory): point seeders at numbered demo datasets

* fix(mvp): resolve demo blockers — ResponseCode, ConfirmationService, AccountNav, cart refresh

C1: Backend StorePaymentDetailResponse + mapping now expose ResponseCode.
    Frontend PaymentIntent type + mapping + CheckoutView use responseCode.
C2: ConfirmationService registered in main.ts (Wishlists delete dialog).
M1: AccountNav now links Wishlists, Notifications, Sessions, Profile.
M2: Cart refreshed after shipping-rate select — Confirm step totals accurate.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(seed): restore embedding-completeness check in verify gate

* feat(admin): migrate catalog DataTables to server-side lazy pagination and sorting

Switch all catalog list views (OptionTypes, Products, Taxonomies, Taxons,
Variants) from client-side filter-display="menu" to server-side lazy mode.
Adds onPage, onRows, onSort handlers wired to usePagedQuery. Clears search
and filter state on filter reset. VariantsList gains variantType filter,
multi-select, and CSV export.

Co-Authored-By: opencode <noreply@opencode.ai>

* feat(admin): migrate inventory/location DataTables to server-side lazy pagination and sorting

Switch CountriesList, StatesList, and StockItemsList from client-side
filter-display="menu" to server-side lazy mode. Adds onPage, onRows, onSort
handlers and computed first offset for server-driven pagination. Clears filter
state on reset for CountriesList, StatesList, and StockItemsList.

Co-Authored-By: opencode <noreply@opencode.ai>

* feat(storefront): add payment intent and transaction mock repositories with tests

Add IPaymentIntentRepository interface, PaymentIntentApiRepository,
MockPaymentIntentRepository with unit tests, and mock payment data.
Add MockTransactionRepository with unit tests for getByOrderId and getById.
Enables isolated storefront development without backend API.

Co-Authored-By: opencode <noreply@opencode.ai>

* fix(storefront): stub TransactionService with empty result for MVP

Drop mock repository dependency in TransactionService and return empty array.
No storefront API for payment transactions exists yet, so the service
returns a successful empty result to avoid runtime errors.

Co-Authored-By: opencode <noreply@opencode.ai>

* fix(api): prefix master variant SKU with MASTER- in demo seeder

Prepend MASTER- to SKU for master variants to distinguish them from style
variants in the catalog demo data. Ensures unique SKUs across master and
style variants during seeding.

Co-Authored-By: opencode <noreply@opencode.ai>

* fix(mvp): wire address creation in checkout, restore deleted mock files

CheckoutView Step 1 now creates addresses via the real
POST /api/store/profiles/addresses endpoint. Removed the
'MVP: dropped' marker — the backend endpoint exists and
was always available. Form fields aligned to the locations
Address schema.

Restored 30 mock repository/data files that were deleted
during earlier commits — these are referenced by existing
unit tests and barrels.

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(storefront): remove unused mock files, clean barrel exports

Deleted 11 mock data/repo files that no production code or test imports.
Cleaned mock exports from 9 repository barrel files.
Wire address creation in CheckoutView via real API endpoint.
Restore 6 mock data files needed by tests from git history.

Build passes, tests unchanged from baseline.

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(storefront): delete remaining unused mock files

Removed mock repos and data files not imported by any test or production code.

Co-Authored-By: Claude <noreply@anthropic.com>

* docs(admin): provision code commenting standard in app/Admin/AGENTS.md

* docs(admin): add template section commenting standard to README

Append the Template Section Commenting Standard section (REQ-005) with the
Section comment format and canonical List-view (PAT-002) / Detail-view
(PAT-003) section orders.

* docs(admin): add View Code-Commenting Rules section

* docs(admin): annotate auth views with code commenting standard

* docs(admin): annotate catalog views with code commenting standard

* docs(admin): fix F8 label in taxons list filter comment

* docs(admin): annotate dashboard view sections

* docs(admin): annotate identity views with code-commenting sections

* docs(admin): annotate inventory views with code-commenting sections

* docs(admin): annotate location views with code-commenting sections

* docs(admin): polish location view comments after review

* docs(admin): annotate ordering views with code-commenting sections

* docs(admin): annotate payment views with code-commenting sections

* docs: tighten wording in AGENTS.md and CLAUDE.md

Condense agent guide and Claude instructions by removing filler words,
contractions, and redundant phrases. No content changes — purely editorial
to improve scan-ability for LLM consumers.

Co-Authored-By: opencode <noreply@opencode.ai>

* docs(admin): fix F8 label in payment method detail load comment

* refactor(api): add idempotent SaveChangesWithIdempotencyAsync to AbstractDataSeeder

Add SaveChangesWithIdempotencyAsync method that catches Postgres unique
constraint (23505) and foreign key (23503) violations, clearing the change
tracker and returning Result.Failure with a typed error. Migrate all 18
seeders across Catalog, Inventory, Location, Ordering, Payment, Profile,
and Shipping modules from raw SaveChangesAsync to the new idempotent method.

Co-Authored-By: opencode <noreply@opencode.ai>

* refactor(api): per-taxonomy slug dedup and conditional slug generation

TaxonSeeder now tracks used slugs per taxonomy instead of globally, so the
same slug can exist across different taxonomies. TaxonMethod.Create and
Update skip slugging when an explicit slug is provided. Add unique index on
(TaxonomyId, Slug) in TaxonConfiguration. Remove global unique slug index
from SluggableConfiguration. VariantSeeder deduplicates SKUs in-memory and
prefixes master variants with MASTER-.

Co-Authored-By: opencode <noreply@opencode.ai>

* refactor(api): simplify DeleteUser and UpdateUser command contracts

Remove DeleteUser.Request record — Command now takes Guid Id directly via
primary constructor. Add [FromRoute] attribute to endpoint parameter. Remove
redundant Id property from UpdateUser.Request since it is already provided
via route.

Co-Authored-By: opencode <noreply@opencode.ai>

* fix(api): map actual Currency in Payment model and handle deleted VariantImage

Use payment.Currency instead of string.Empty in PaymentModelMapping for
both list and detail projections. In EmbeddingOrchestrator, verify the
VariantImage still exists before persisting and catch foreign-key violations
(23503) on SaveChanges to return a typed error. Add warning log event for
the deleted-image race condition.

Co-Authored-By: opencode <noreply@opencode.ai>

* fix: fallback to USD for empty currency in formatCurre…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant