raouf-b-dev/ecommerce-store-api
57.4
Adequate · 21 September 2026
43.9k
lines of production code
TypeScript
with JavaScript
4
measurements over time
What this system is
This system is a backend e-commerce API built with NestJS, providing core commerce capabilities including user authentication, shopping cart management, inventory tracking with reservations, and order processing. It supports a full checkout flow that integrates payment intent creation with stock locking, while offering administrative endpoints for role-based access control and operational analytics. The architecture emphasizes reliability through features like idempotency, optimistic concurrency control, and comprehensive observability via Prometheus, OpenTelemetry, and structured logging.
Features
Add Grafana monitoring dashboards and configuration for the E-Commerce API
This change introduces a set of pre-configured Grafana dashboards and provisioning files for the \docker/monitoring/grafana\ directory. It includes an entrypoint script that enforces non-default admin credentials for security, a datasource configuration linking Prometheus, Loki, and Tempo, and four specific dashboard definitions: 'api-overview' (request rate, error rate, latency percentiles), 'business-metrics' (orders, payments, logins), 'checkout-saga' (saga completion/failure rates, compensations, TraceQL integration), and 'infrastructure' (DB connections, Redis status, WebSocket connections, BullMQ depth, Node.js heap). These files provision the visualizations that rely on the underlying Prometheus, Loki, and Tempo configurations added in the same location.
docker · high confidence
Add OpenTelemetry tracing infrastructure
The application now includes OpenTelemetry tracing support, bootstrapped via the --require flag before the NestJS application starts. This configuration initializes the NodeSDK with an OTLP gRPC exporter, automatically instruments HTTP and other node modules (excluding noisy file-system instrumentation), and tags traces with the service name, version, and deployment environment. Health and metrics endpoints are explicitly ignored to reduce noise, and the SDK performs a graceful shutdown to flush pending spans on process termination.
src/infrastructure/tracing · high confidence
Add Postgres-based cart query adapter with integration tests
This change introduces the PostgresCartQueryAdapter, a new secondary adapter that implements the CartQueryService interface to retrieve cart data from a PostgreSQL database. The adapter supports fetching carts by ID or user ID, including item details such as price, currency, and image URL, and ensures items are returned in a stable order. Alongside the implementation, integration tests have been added to verify the adapter's behavior against a real database, including scenarios for single and multi-line carts and non-existent users.
src/modules/carts/secondary-adapters/query · high confidence
Add Postgres-based order query adapter with advanced filtering and sorting
The order module now includes a new PostgresOrderQueryAdapter that implements the OrderQueryService interface, enabling efficient read-side operations via TypeORM. This adapter supports paginated order listing with multiple filter options (status, user identity, date range, and amount bounds), sorting by total price, and detailed order retrieval including line items and product SKUs. Integration tests verify correct behavior for ownership scoping, date-only boundary handling, and error cases.
src/modules/orders/secondary-adapters/query · high confidence
Add category management and demo catalog seeding
Introduces a new CategoriesController with endpoints to create, read, update, delete, activate, and deactivate catalog categories, along with the underlying domain entities, application use cases, and query services. Adds SeedDemoCategoriesUseCase and SeedDemoCatalogUseCase to populate the system with default categories and a set of sample products, including logic to backfill missing category associations for existing demo SKUs. Includes comprehensive unit tests for the new controllers, domain logic, and seeding workflows.
src/modules/products · high confidence
Add notification query mapping logic
Introduces the NotificationQueryMapper to convert raw database query results into structured NotificationListItemDTO objects. This mapper handles type coercion for identifiers and strings, normalizes date formats to ISO strings, and safely manages null or missing optional fields like userId and targetRole, ensuring consistent data shapes for downstream notification list queries.
src/modules/notifications/secondary-adapters/mappers · high confidence
Add order query interfaces and result DTOs for order management
New interfaces and DTOs have been introduced in the order application layer to support querying and presenting order data. This includes the ListOrdersQuery interface for filtering orders by status, user, date, and amount, as well as result types for checkout operations, order details (including subtotal, shipping cost, and items), order list items, and individual order item details. These changes provide the structured data contracts needed for order retrieval and display features.
src/modules/orders/core/application/queries · high confidence
Add process, Redis, and WebSocket health indicators
The health-check system now includes three new indicators to monitor application stability and infrastructure connectivity. The ProcessHealthIndicator tracks Node.js process health by measuring event loop lag and RSS memory usage against defined thresholds. The RedisHealthIndicator verifies Redis availability by pinging the server with a 3-second timeout. The WebSocketHealthIndicator checks the Socket.io server's initialization status and retrieves the count of connected clients, also with a 3-second timeout. These indicators provide more granular visibility into the application's runtime state and external service dependencies.
src/modules/health/indicators · high confidence
Add user query mapping for list and detail views with address support
The identity module now includes a new UserQueryMapper that converts raw database query results into structured DTOs for user lists and user details. This mapping ensures consistent data formatting, including ISO date strings, and supports enriching user detail views with associated address entities. A new interface, RawUserListQueryRow, defines the expected shape of raw query data, and corresponding unit tests verify the correct transformation of user and address data.
src/modules/identity/secondary-adapters/mappers · high confidence
Added DeleteProductUseCase and its unit tests
A new DeleteProductUseCase has been introduced in the products module to handle product deletion. The implementation delegates to the ProductRepository's deleteById method and wraps the outcome in a Result type, returning success or a UseCaseError based on the repository's response. Corresponding unit tests verify both the successful deletion path and the failure path where the product is not deleted.
src/modules/products/core/application/usecases/delete-product · high confidence
Added ORM entities and persistence mappers for role-based authorization
This change introduces the database schema definitions and data-mapping logic for the authorization module's role-based access control. It adds TypeORM entities for Permissions, Roles, and User-Role Assignments, including the many-to-many relationship between roles and permissions. Corresponding mappers are provided to translate between these persistence entities and the core domain models, enabling the storage and retrieval of role definitions, permission codes, and user-to-role assignments.
src/modules/authorization/secondary-adapter/orm · high confidence
Added ORM entities for User and Address with optimistic locking
The ORM layer now includes new TypeORM entity definitions for User and Address. The UserEntity introduces a version column to support optimistic locking for concurrency control, while the AddressEntity defines the schema for user addresses with a many-to-one relationship to the user. These entities establish the database structure for identity data, including fields for user details and address information.
src/modules/identity/secondary-adapters/orm · high confidence
Added ORM entities for credential and session token management
The authentication module now includes persistent storage definitions for user credentials and session tokens via new TypeORM entities. The CredentialEntity maps to the 'credentials' table, storing user IDs, password hashes, and a flag to enforce password changes, while the SessionTokenEntity maps to 'session\_tokens', tracking UUID-based token hashes, expiration times, and revocation status. These schema definitions enable the underlying infrastructure to support secure credential storage and active session management.
src/modules/authentication/secondary-adapters/orm · high confidence
Added PostgreSQL implementation for user-role assignment persistence
The authorization module now includes a concrete Postgres-based repository for managing user-role assignments, implementing the core domain interface with save, findByUserId, and deleteByUserId operations. This adapter handles data mapping between the domain entities and the TypeORM schema, wrapping database interactions in a Result type to manage success and failure states consistently. An accompanying integration test suite verifies that assignments are correctly persisted, that duplicate assignments for the same user are rejected, and that deletions effectively remove the association.
src/modules/authorization/secondary-adapter/repositories/postgres-user-role-assignment-repository · high confidence
Added Redis Search index initialization and query escaping utilities
The application now automatically initializes RediSearch indexes for Orders, Products, Inventory, Cart, Payments, and Users on startup via the new RedisIndexInitializerService, which handles readiness checks and logs creation status or errors. Additionally, new search-utils functions (textEquals, tagEquals) provide safe escaping for Redis Search queries, preventing syntax errors when values contain special characters like quotes, backslashes, or punctuation.
src/infrastructure/redis/search · high confidence
Added ValidateCheckout use case with caller context and address resolution
The ValidateCheckout use case has been introduced to orchestrate checkout validation by verifying the caller's permissions, ensuring the cart is valid and non-empty, confirming the user exists, and resolving the shipping address. It now accepts a caller context to distinguish between customer and system requests, allowing system callers to bypass specific permission checks during saga execution, while customer requests require the 'manage\_own\_cart' permission. The use case integrates with the ShippingAddressResolver to handle address resolution from provided DTOs or user defaults, returning a validated context containing user, cart, and shipping address details.
src/modules/orders/core/application/usecases/validate-checkout · high confidence
Added demo cart seeding capability
A new SeedDemoCartUseCase has been introduced in the carts module to automatically populate a user's cart with predefined demo items (headphones, clothing, home goods) when no active cart exists. This feature allows users to quickly experience the shopping flow with sample products, while ensuring that existing carts with items are left untouched.
src/modules/carts/core/application/seed · high confidence
Added in-process domain event publishing via EventEmitter2
A new EventEmitter2DomainEventPublisher has been introduced in the infrastructure layer to handle domain event delivery using NestJS's EventEmitter2. This adapter implements the standard DomainEventPublisher interface, allowing the application to publish events asynchronously with fire-and-forget semantics. If event processing fails, errors are caught and logged using the shared toError utility, ensuring that listener issues do not crash the calling use case. This change provides a swappable foundation for in-process event handling, with the design intent to allow future migration to external brokers like Kafka or RabbitMQ without affecting domain or use-case code.
src/infrastructure/events · high confidence
Added use case to expire pending orders
A new ExpirePendingOrdersUseCase has been introduced to automatically cancel orders that have remained in the PENDING\_PAYMENT state for longer than a specified duration. The use case queries the order repository for matching orders and invokes the existing CancelOrderUseCase for each, returning a summary of successfully cancelled and failed cancellations. A corresponding test suite validates the core logic, including handling repository errors, partial cancellation failures, and empty result sets.
src/modules/orders/core/application/usecases/expire-pending-orders · high confidence
Analytics query interfaces and period parsing logic
The analytics core module now defines the query contracts and data structures for retrieving overview KPIs, payment time series, top products, and inventory alerts. This includes the \AnalyticsQueryService\ abstract port, specific query and result interfaces (such as \AnalyticsOverviewQuery\ with previous-window support, \PaymentsTimeSeriesQuery\, \TopProductsQuery\, and \InventoryAlertsQuery\), and the \AnalyticsPolicy\ constants for time buckets and attention order statuses. Additionally, a new \AnalyticsPeriodParser\ service handles date conversion and calculates equal-length previous windows for comparative KPIs.
src/modules/analytics/core · high confidence
Authentication module implementation with session management and security features
The authentication module has been implemented with several key components. A RefreshToken decorator has been added to extract refresh tokens from cookies or request bodies, enabling seamless token retrieval in controllers. A UserDeactivatedListener has been introduced to automatically revoke all active sessions when a user account is deactivated, enhancing security by ensuring no lingering access remains. Session token persistence is handled through a mapper that converts between domain entities and database records, supporting full lifecycle management of session tokens. Additionally, a BcryptService has been implemented for secure password hashing and comparison, providing the foundation for robust authentication security.
(repo-wide) · high confidence
Authentication module restructured with new change-password capability and HTTP contract tests
The authentication module has been reorganized into a clean architecture with dedicated use cases for registration, login, token refresh, logout, and a new change-password flow. The change-password feature allows authenticated users to update their credentials, which automatically revokes all existing sessions and issues new tokens. The module now includes an HTTP contract test suite that validates the full authentication lifecycle (register, login, refresh, logout) and verifies that refresh tokens are securely set as HttpOnly, Secure, SameSite=Strict cookies scoped to /v1/authentication. The controller also supports reading refresh tokens from cookies with a JSON body fallback for non-browser clients.
src/modules/authentication · high confidence
Automatic initialization of system permissions and roles on application startup
The application now automatically bootstraps the authorization system on startup. A new PermissionSystemDataInitializer ensures that core system permissions are created or updated in the database before the RoleSystemDataInitializer runs, preventing issues where system roles (like SUPER\_ADMIN) are created with empty permission sets. The RoleSystemDataInitializer then creates or updates system roles and their permission grants, correcting any misconfigurations (such as missing the 'isSystem' flag) and ensuring the authorization catalog is consistent with the defined reference data.
src/modules/authorization/core/application · high confidence
Cached inventory repository with integration and unit tests
The inventory module now uses a \CachedInventoryRepository\ that wraps the existing Postgres repository with a Redis cache layer. This adapter intercepts read operations (\findById\, \findByProductId\, \findByProductIds\) to serve data from cache when available, falling back to the database on misses and populating the cache with a defined TTL. Write operations (\save\) write through to Postgres and invalidate relevant cache entries. Comprehensive unit and integration tests have been added to verify cache hit/miss behavior, error handling for Redis/DB failures, and data consistency between the cache and the database.
src/modules/inventory/secondary-adapters/repositories/cached-inventory-repository · high confidence
Checkout compensation use cases publish domain events
The RefundCheckoutPayment and ReleaseCheckoutStock use cases now publish a 'checkout.saga.compensation' domain event upon successfully processing a refund or releasing inventory. This enables downstream systems to react to compensation steps in the checkout saga, ensuring consistent state management when order processing requires rollback actions.
src/modules/orders/core/application/usecases/refund-checkout-payment, src/modules/orders/core/application/usecases/release-checkout-stock · high confidence
Custom type definitions for Express and Socket.io
Added src/types/express.ts to extend the Express Request interface with user, userPermissions, and correlationId fields, and the Socket.io Socket interface with a user field, enabling type-safe access to authentication and permission data in request handlers and socket connections.
src/types · high confidence
Demo order seeding and payment linking capabilities added
The orders module now includes application use cases to populate the system with sample data and manage their payment associations. The SeedDemoOrdersUseCase creates pre-configured demo orders (such as confirmed electronics or shipped apparel) with specific statuses, skipping creation if orders already exist for the user. Additionally, the LinkDemoOrderPaymentsUseCase allows linking real payment IDs to these demo orders and refreshing their timestamps, supporting the testing and demonstration of the full order lifecycle.
src/modules/orders/core/application/seed · high confidence
IdempotencyInterceptor now enforces request idempotency with Redis-backed locking
The new IdempotencyInterceptor intercepts HTTP requests to prevent duplicate processing by checking for a client-provided idempotency key. If a key is present, the interceptor uses the IdempotencyStore (backed by Redis) to lock the operation; subsequent requests with the same key while the first is in progress receive a 409 Conflict with a Retry-After header, and completed requests return the cached response. If the store is unavailable or fails to persist the result, the request fails with a 503 Service Unavailable. The interceptor supports both standard and legacy x-idempotency-key headers and ensures locks are released on failure.
src/infrastructure/interceptors · high confidence
Identity module exposes user and address management APIs with role-based access control
The identity module now provides a comprehensive set of endpoints for managing user profiles and addresses, secured by the new authorization system. Administrators can list, view, update, delete, activate, and deactivate users, as well as assign roles, while users can view their own profiles via a dedicated 'me' endpoint. Address management (add, update, delete, set default) is also exposed, requiring specific permissions. These capabilities are backed by a new \GetUserByEmailUseCase\ that enforces ownership policies and a \ModuleAuthorizationGateway\ that delegates role assignment to the authorization module.
src/modules/identity · high confidence
Implement WebSocket notification delivery via dedicated gateway
A new WebsocketNotificationGateway has been introduced to handle real-time notification delivery. This component implements the core NotificationGateway interface and utilizes the existing WebsocketConnectionGateway to emit notification payloads to specific user rooms (formatted as user\_{userId}), enabling immediate push-style updates to connected clients.
src/modules/notifications/secondary-adapters/gateways · high confidence
Initial Carts module implementation with Hexagonal architecture
The Carts module is now available, providing a complete set of endpoints for managing shopping carts (create, retrieve, add/update/remove items, clear) and seeding demo data. The implementation follows a Hexagonal architecture, exposing a NestJS controller that delegates to domain use cases, backed by both Postgres and cached repositories, and integrated with Inventory and Product modules via gateways for stock and product data.
src/modules/carts · high confidence
Initial NestJS application bootstrap with modular architecture and security defaults
The application is now bootstrapped as a NestJS service, wiring together core modules (Orders, Products, Carts, Payments, Inventory, Identity, Authentication, Authorization, Notifications, Analytics, Health, and Shutdown) via the AppModule. The bootstrap process in main.ts configures global behaviors including URI-based API versioning, request validation with property whitelisting, sanitization, and centralized exception handling. Security is enforced via Helmet, CORS, cookie parsing, and global guards for authentication, permission checks, and mandatory password changes. Infrastructure features include Redis-backed WebSocket support, graceful shutdown hooks, and Winston logging. Swagger documentation is available in non-production environments, and health checks are exposed via the HealthModule.
src · high confidence
Initial Swagger/OpenAPI configuration and nullable response support
The API documentation infrastructure now includes a dedicated configuration for the Swagger document, setting the title to 'E-Commerce API', version to '1.0', and enabling Bearer token authentication. Additionally, a utility for generating OpenAPI 3.0 nullable response schemas has been added, allowing endpoints to explicitly document responses that may be null when paired with \@ApiExtraModels\.
src/infrastructure/swagger · high confidence
Initial database schema and subsequent structural updates
The application now includes a comprehensive initial database migration establishing core tables for products, orders, payments, users, and inventory, along with supporting tables for categories, carts, and roles. Subsequent migrations add a dedicated categories table with seed data and link it to products, introduce specific indexes on orders, order items, and payments to support analytics queries, and add a currency column to cart items to support multi-currency pricing.
src/migrations · high confidence
Initial project scaffolding and developer environment setup
The repository is initialized with a NestJS application structure, including a multi-stage Dockerfile and docker-compose configurations for local development and production. This change introduces a comprehensive set of configuration files: environment templates (.env.example, .secrets.example), TypeScript build settings (tsconfig.json, nest-cli.json), and linting rules (eslint.config.mjs). It also establishes the project's governance and documentation standards by adding AGENT.md, CLAUDE.md, GEMINI.md, CONTRIBUTING.md, CODE\_OF\_CONDUCT.md, and SECURITY.md. Additionally, a docker-entrypoint.sh script is added to handle database migrations before application startup, and a .gitignore file is configured to exclude sensitive and build artifacts.
(repo-wide) · high confidence
Introduce Cart Ownership Validator for Access Control
A new CartOwnershipValidator service has been added to enforce stricter access control on cart operations. This validator checks the caller's context to ensure that only system users, administrators with 'manage\_carts' permission, or the specific user owning the cart (with 'manage\_own\_cart' permission) can access it. It returns a Result wrapper indicating success or failure, preventing unauthorized access attempts.
src/modules/carts/core/application/services · high confidence
Introduce Cart and CartItem domain entities with currency support and validation
The cart module now includes new domain entities for Cart and CartItem, replacing previous implementations. These entities enforce strict validation rules, such as requiring a valid 3-letter ISO 4217 currency code and rejecting negative prices or zero quantities. The Cart entity manages a single-currency constraint, preventing the mixing of different currencies within one cart, and provides methods for adding, updating, and removing items while automatically calculating subtotals and total amounts. The CartItem entity handles individual line item logic, including quantity adjustments and price updates, ensuring data integrity through domain-driven design principles.
src/modules/carts/core/domain/entities · high confidence
Introduce OrderFactory for creating orders from cart data
A new OrderFactory has been added to the orders domain to handle the creation of Order entities from cart inputs. This factory accepts a structured cart payload (including item details like productName, unitPrice, and currency), along with userId, shipping address, and payment method, and maps these into the internal OrderItemProps and Order entity structure. This centralizes the transformation logic for converting checkout cart data into a finalized order.
src/modules/orders/core/domain/factories · high confidence
Introduce OrderScheduler interface for order lifecycle scheduling
A new abstract OrderScheduler interface has been added to define the contract for scheduling key order lifecycle events. This interface specifies methods for scheduling checkout, post-payment processing, stock release, and the expiration of pending orders, establishing the foundation for the background job infrastructure in the orders module.
src/modules/orders/core/domain/schedulers · high confidence
Introduce caching layer for Order repository operations
The Orders module now uses a CachedOrderRepository that wraps the existing Postgres repository with Redis caching. For list operations, the system checks a cache flag and serves results from Redis when no filters are applied and default pagination is used, falling back to the database on cache misses or errors. Individual order lookups (findById) and mutations (save, deleteById) now read from or write to the cache, ensuring that list caches are invalidated when orders are created or removed. Integration and unit tests verify this behavior, including fallback logic when Redis is unavailable.
src/modules/orders/secondary-adapters/repositories/cached-order-repository · high confidence
Introduce core authorization domain model for roles and permissions
This change establishes the foundational domain layer for the authorization module by introducing the \Permission\, \Role\, and \UserRoleAssignment\ entities, along with the \RolePermissions\ value object. It defines the data structures and business rules for managing access control, including the ability to create and update roles, assign permissions, and enforce system-level constraints (such as preventing the deletion or renaming of system roles). The update also includes reference data for default system roles and permissions, as well as the abstract repository interfaces required to persist these entities.
src/modules/authorization/core/domain · high confidence
Introduce core domain model and application services for the Notifications module
This change establishes the foundational structure for the Notifications module within the application core. It defines the \Notification\ domain entity with a strict lifecycle (Pending, Sent, Delivered, Read, Failed) and a 30-day default expiration. It introduces application-layer services to handle notification delivery via a gateway, persist history, update status, and clean up expired records. Additionally, it provides use cases for retrieving user notifications and marking them as read, supported by query interfaces and DTOs for paginated listing.
src/modules/notifications/core · high confidence
Introduce credential and session token domain models
The authentication module now includes core domain entities for managing user credentials and session tokens. The new Credential entity supports password updates and tracks whether a password change is required, while the SessionToken entity handles token lifecycle management including creation, expiration checks, and revocation. Corresponding repository interfaces have been added to define persistence operations for both entities.
src/modules/authentication/core/domain · high confidence
Introduce notifications module with API endpoints and background processing
The new notifications module exposes REST endpoints for retrieving a user's notifications (with pagination and status filtering) and marking individual notifications as read. It integrates a BullMQ-based job processor to handle notification delivery, history saving, status updates, and cleanup of expired notifications, while using WebSockets to push updates and PostgreSQL to persist notification data.
src/modules/notifications · high confidence
Introduces identity module command/query interfaces and DTOs
The identity module's application layer now defines the core contracts for user and address management. New command interfaces (CreateUser, UpdateUser, AddAddress, UpdateAddress) specify the input shapes for mutating user profiles and addresses, including optional fields like phone, address type, and delivery instructions. Corresponding query interfaces (UserQueryService, ListUsersQuery) and DTOs (UserListItemDTO, UserDetailDTO) establish how users are retrieved, supporting pagination, search, active status filtering, role code filtering, and the inclusion of associated address details. An AuthorizationGateway interface is also introduced to handle role assignment.
src/modules/identity/core/application · high confidence
Introduces structured error handling, domain value objects, and access control policies
The shared-kernel now provides a comprehensive foundation for domain-driven development, including a typed \Result\ monad and a hierarchy of \AppError\ classes (Domain, UseCase, Service, Repository, Infrastructure, Query) with a central \ErrorFactory\ for consistent error creation. New domain value objects for \Money\ (with arithmetic and validation), \Quantity\, \PaymentMethod\, and \AddressType\ are available for use across bounded contexts. The kernel also introduces \CallerContext\ and \OwnedResourceAccessPolicy\ to enforce user-scoped resource access (view/mutate) based on permissions, alongside interfaces for JWT verification, caching, and idempotency to standardize infrastructure interactions.
src/shared-kernel · high confidence
Introduction of CachedCartRepository with Redis caching and updated test coverage
A new CachedCartRepository has been added to the cart module, implementing the CartRepository interface to wrap database operations with Redis caching. This adapter intercepts find and save operations to store and retrieve cart data from Redis using a defined expiration time, while ensuring cache consistency by deleting entries on cart deletion. The implementation includes specific logic for handling user-ID based lookups and versioned updates, delegating directly to the underlying Postgres repository for update operations. Corresponding unit tests have been added to verify the repository's behavior, including scenarios for cache misses, successful saves, and deletions across both the cache and database layers.
src/modules/carts/secondary-adapters/repositories/cached-cart-repository · high confidence
Introduction of Notification ORM entity schema
A new TypeORM entity definition for notifications has been added, establishing the database schema for the \notifications\ table. This schema maps core notification attributes including UUID identifiers, user and role targeting, message content, and status tracking, while also defining database indexes on user ID, status, creation date, and expiration date to support efficient querying.
src/modules/notifications/secondary-adapters/orm · high confidence
Introduction of role-based permission checks via decorator and guard
The authorization module now supports fine-grained access control through a new \RequirePermissions\ decorator and \PermissionsGuard\. Developers can now annotate controllers or methods with \@RequirePermissions('permission\_code')\ to enforce that the requesting user holds at least one of the specified permissions. The guard resolves the user's effective permissions based on their role using \ResolveRolePermissionsService\ and validates them before allowing access. This change is accompanied by new DTOs (\CreateRoleDto\, \UpdateRoleDto\, \RoleResponseDto\, \PermissionResponseDto\) to handle role creation, updates, and API responses, ensuring that roles and their associated permissions are properly managed and exposed via the API.
src/modules/authorization/primary-adapter · high confidence
Inventory module with stock management, reservations, and reconciliation
The new Inventory module exposes endpoints for listing and viewing inventory details, adjusting stock quantities, and checking availability (publicly for shoppers). It introduces stock reservation capabilities, allowing orders to temporarily hold inventory and release it upon cancellation. Additionally, it includes a background job for inventory reconciliation to detect and log discrepancies between database records and active reservations, ensuring data consistency.
src/modules/inventory · high confidence
JWT infrastructure module with port-based abstraction
The application now includes a new JWT infrastructure module that exposes JWKS and JWT verification capabilities through defined ports (JwksPort and JwtVerifierPort). This module registers these services as global providers, allowing other parts of the application to depend on the abstract interfaces rather than concrete implementations, thereby improving testability and separation of concerns.
src/infrastructure/jwt · high confidence
JWT verification now supports cart session tokens
The JWT verification service has been extended to validate cart session tokens in addition to access and refresh tokens. The new \JwtVerifierService\ implements a \verifyCartSessionToken\ method that checks for the \cart\_session\ token type and asserts the presence of required claims such as \cartId\, \sub\, \typ\, \iss\, \iat\, and \exp\. This change is supported by a new \JwksService\ that handles RSA key import and JWKS generation, ensuring the public key is available for verifying these new token signatures.
src/infrastructure/jwt/services · high confidence
New BullMQ-based checkout and order scheduling infrastructure
The system now uses a new BullMQ-based scheduler (BullMqOrderScheduler) to handle order lifecycle events. This adapter implements the OrderScheduler interface to manage checkout flows (validating cart, reserving stock, processing payment), post-payment flows (finalizing checkout, clearing cart, confirming reservation), and stock release operations. It integrates with the CorrelationService for enhanced logging across job chains and implements ApplicationLifecyclePort to ensure graceful shutdown handling.
src/modules/orders/secondary-adapters/schedulers · high confidence
New Cursor IDE agent policy and verification rules
Added three new rule files to the Cursor configuration to define agent behavior: a canonical policy enforcing DDD and Hexagonal architecture boundaries, verification gates requiring type checking and architectural tests before task completion, and skills discovery hints for auto-loading relevant agent capabilities.
.cursor · high confidence
New Identity Domain Model with Optimistic Concurrency Control
The identity module now introduces core domain entities for Users and Addresses, complete with validation logic (e.g., email normalization, required fields) and business methods such as activating/deactivating users, managing default addresses, and updating personal information. A key behavioral change is the introduction of optimistic concurrency control in the UserRepository, which now requires version checking during save operations to prevent race conditions, alongside new repository interfaces for address management.
src/modules/identity/core/domain · high confidence
New JWT signing service with session and cart token support
The authentication module now includes a dedicated JwtSignerService that handles signing access, refresh, and cart session tokens using the jose library. This service introduces a mustChangePassword claim in access tokens, generates unique session IDs for refresh tokens via a new signRefreshTokenWithSession method, and supports guest cart session tokens. The implementation is accompanied by unit tests verifying the service's basic instantiation and dependency injection.
src/modules/authentication/core/application/services · high confidence
New ORM schema definitions for Cart and CartItem entities
This change introduces the TypeORM entity definitions for the cart module, specifically creating \CartEntity\ and \CartItemEntity\ in the ORM secondary adapter. The \CartEntity\ now includes a \version\ column for optimistic locking, a unique \userId\ field, and a one-to-many relationship with cart items. The \CartItemEntity\ defines fields for product details, price, quantity, and a new \currency\ field (defaulting to 'USD'), along with a many-to-one relationship back to the cart. These schemas establish the database structure for cart persistence.
src/modules/carts/secondary-adapters/orm · high confidence
New ORM schema definitions for Inventory and Reservation entities
The inventory module now includes explicit TypeORM schema definitions for the Inventory, Reservation, and ReservationItem entities. The InventoryEntity schema introduces optimistic locking via a version column and specific database indexes on product ID and available quantity to support query performance. The ReservationEntity schema defines the reservation lifecycle with status tracking, expiration handling, and a one-to-many relationship to ReservationItemEntity, which enforces cascade deletion. These schemas establish the data access layer structure for inventory tracking and order reservations.
src/modules/inventory/secondary-adapters/orm · high confidence
New Orders API DTOs for checkout, listing, and order management
The Orders module now exposes a comprehensive set of Data Transfer Objects that define the request and response contracts for order operations. Users can now create orders with explicit items, shipping addresses, and payment methods via CreateOrderDto, and initiate asynchronous checkouts via CheckoutDto which returns a jobId and optional clientSecret. Order listing is enhanced with ListOrdersQueryDto, supporting pagination (page/limit with defaults), filtering by user, status, date ranges, and amount, as well as sorting. Read models include OrderDetailResponseDto (with subtotal, shippingCost, and totalAmount), OrderListItemResponseDto, and OrderResponseDto, while mutation responses (OrderMutationResponseDto) and delivery notes (DeliverOrderDto) support admin workflows. Validation and Swagger documentation are applied across all DTOs, and PaymentMethodType is centralized from the shared-kernel domain.
src/modules/orders/primary-adapters/dto · high confidence
New PostgreSQL analytics query adapter with UTC time-series and KPI mapping
The secondary-adapters layer now includes a PostgresAnalyticsQueryAdapter that executes raw SQL queries against the database to power analytics features. This adapter maps raw database rows into application-specific DTOs via AnalyticsQueryMapper, handling revenue KPIs (gross, net, refunded, AOV), order attention counts, top products, and inventory alerts. A key behavioral change is the use of UTC-based time bucketing for payment time-series data, ensuring consistent zero-filling of missing days/weeks in charts regardless of server timezone. The implementation includes specific SQL filters for revenue statuses (CAPTURED, COMPLETED, etc.) and order statuses, along with a 5-second statement timeout to prevent long-running analytics queries from blocking the system.
src/modules/analytics/secondary-adapters · high confidence
New Prometheus metrics endpoint and middleware for application monitoring
The application now exposes a new \/metrics\ endpoint that returns Prometheus-formatted metrics, protected by an optional API key guard and exempt from rate limiting. A new \MetricsMiddleware\ automatically tracks HTTP request counts and durations for all routes, normalizing paths by replacing UUIDs and integer IDs with \:id\ placeholders to prevent cardinality explosion. The underlying \MetricsService\ registers a comprehensive set of counters, gauges, and histograms, including HTTP metrics, business indicators (orders, checkout sagas, payments, auth, carts), infrastructure status (DB pool, Redis health/cache, throttler degradation, BullMQ queue depth, WebSocket connections), and audit metrics (inventory drift, Redis cache hits/misses/recovery failures).
src/infrastructure/metrics · high confidence
New Redis JSON-based cache service with search and fail-open behavior
The application now uses a new CacheService in the Redis infrastructure layer that stores data as RedisJSON documents. This service provides standard caching operations (get, set, delete) as well as a new search capability that queries Redis FT indexes and returns mapped domain objects. It includes fail-open logic, meaning Redis outages or pipeline errors will not crash the application but instead fall back to the primary data source (PostgreSQL). The implementation also adds metrics tracking for cache hits and misses.
src/infrastructure/redis/cache · high confidence
New Redis-backed Idempotency Service with robust error handling
The infrastructure layer now includes a new \IdempotencyService\ that uses Redis (via the \CachePort\) to manage idempotency keys. This service provides atomic locking via \checkAndLock\ (using SET NX), allows marking operations as \complete\ with stored data, and supports \release\ to delete keys. It is designed to fail closed when the cache is unavailable or when encountering malformed records/unknown statuses, ensuring system stability. The service is exposed via a new \IdempotencyModule\ and registered as a global provider, making it available across the application.
src/infrastructure/idempotency · high confidence
New admin analytics endpoints for operational insights
This change introduces the \AnalyticsModule\ in \src/modules/analytics\, exposing a new \AnalyticsController\ under the \/admin/analytics\ route. Users with appropriate permissions can now access four new endpoints: an operational overview (\/overview\) for KPIs like revenue and order counts, a payments time-series (\/payments/time-series\) for revenue trends, a top products list (\/products/top\), and low-stock inventory alerts (\/inventory/alerts\). The module wires these controllers to specific use cases and a Postgres-based query adapter, with default limits applied to product and inventory queries.
src/modules/analytics · high confidence
New analytics API request and response contracts
This change introduces the primary-adapter Data Transfer Objects (DTOs) that define the input and output schemas for the new analytics endpoints. Users will now be able to query analytics data using period-based filters (with a maximum 90-day range), time-series buckets (day/week), and specific views such as inventory alerts and top products. The response structures expose KPI snapshots (revenue, AOV, order counts), time-series payment buckets, low-stock inventory alerts, and top-selling product details, all standardized with Swagger annotations for API documentation.
src/modules/analytics/primary-adapters · high confidence
New analytics use cases for inventory, overview, payments, and top products
This change introduces four new application-layer use cases within the analytics module: GetInventoryAlertsUseCase, GetAnalyticsOverviewUseCase, GetPaymentsTimeSeriesUseCase, and GetTopProductsUseCase. Each use case acts as an intermediary between the API layer and the underlying AnalyticsQueryService, handling query execution and error propagation using a Result pattern. Specifically, GetAnalyticsOverviewUseCase calculates and passes a previous period window to the query service for comparative analytics. Unit tests have been added for all four use cases to verify successful data retrieval and proper failure handling.
(repo-wide) · high confidence
New authentication ports for identity, authorization, and JWT signing
The authentication module now exposes three new application-layer ports that define the contract for user identity management, role-based authorization, and token generation. The IdentityGateway allows the application to create, find, and delete user records, while the AuthorizationGateway handles assigning roles and retrieving role permissions. Additionally, the JwtSignerPort standardizes the creation of access and refresh tokens, introducing a specific payload structure for access tokens that includes an optional 'mustChangePassword' claim to support password rotation workflows without unnecessary database lookups.
src/modules/authentication/core/application/ports · high confidence
New authorization module with role/permission management and Redis caching
The application now includes a new Authorization module that introduces role-based access control. Administrators can manage roles and permissions via new REST endpoints at /roles and /permissions, which require the 'manage\_roles' permission. The system uses PostgreSQL for persistence and integrates Redis to cache role permissions, improving lookup performance while ensuring cache invalidation on role changes.
src/modules/authorization · high confidence
New authorization use cases for managing roles and permissions
The authorization module now includes application-layer use cases for role and permission management. For permissions, the FindAllPermissionsUseCase retrieves all permissions as primitives. For roles, the module introduces CreateRoleUseCase (which validates code uniqueness before saving), FindAllRolesUseCase, FindRoleByIdUseCase, UpdateRoleUseCase (which prevents updating the name of system roles), and DeleteRoleUseCase (which prevents deletion of system roles). Each use case is accompanied by unit tests verifying success paths, repository error handling, and specific business rule validations.
src/modules/authorization/core/application/usecases/permissions, src/modules/authorization/core/application/usecases/role · high confidence
New category management use cases with role-based visibility
Added application-layer use cases for creating, updating, activating, deactivating, deleting, retrieving, and listing product categories. The create and update operations enforce uniqueness constraints on category names and slugs, returning HTTP 409 Conflict when duplicates are detected. Read operations (get and list) integrate with the CategoryQueryService and apply the CatalogVisibilityPolicy to enforce role-based access: shoppers only see active categories, while operators with the view\_all\_products permission can view inactive ones.
src/modules/products/core/application/usecases/categories · high confidence
New checkout use case with validation, event publishing, and scheduling
The checkout flow now uses a dedicated CheckoutUseCase that first validates the cart and shipping context via ValidateCheckoutUseCase, publishes domain events (cart.checkout.initiated and order.created) upon success, persists the order, and schedules the checkout job. If scheduling fails, the order is cancelled and saved before returning an error. The use case accepts a callerContext for access control and supports optional shipping address details.
src/modules/orders/core/application/usecases/checkout · high confidence
New checkout use cases for cart, payment, and stock reservation
The application now includes dedicated use cases to handle key steps in the checkout flow: clearing the checkout cart, confirming inventory reservations, creating payment intents, and reserving stock. These new components allow the system to manage cart state, secure inventory, and initiate payments as distinct, testable operations during order processing.
(repo-wide) · high confidence
New decorators for public access, optional authentication, and password-change exceptions
Three new decorators have been added to the authentication guard system to provide finer control over access requirements. The \Public\ decorator marks routes as accessible without any authentication. The \OptionalAuth\ decorator allows routes to proceed with or without a valid token, enabling endpoints that can utilize user context if available but do not require it. Additionally, the \AllowDuringPasswordChange\ decorator permits access to specific routes even when a user is in a state requiring a password change, ensuring critical functionality remains available during this mandatory security step.
src/guards/decorators · high confidence
New domain value objects for order pricing, status, and shipping address
The Orders module now includes core domain value objects to handle pricing calculations, status management, and shipping address validation. OrderPricing computes subtotals and totals from line items, enforcing currency consistency across items. OrderStatusVO provides a typed wrapper for order lifecycle states (e.g., pending, confirmed, shipped, cancelled) with transition rules and helper predicates. ShippingAddress validates and normalizes delivery details, including required field checks, postal code format validation, country whitelisting, and phone number formatting. These components form the foundational domain logic for order creation and checkout within the orders module.
src/modules/orders/core/domain/value-objects · high confidence
New health check endpoints for monitoring service availability
A new HealthModule has been added to the application, exposing three endpoints under the /health path to monitor system status. The aggregate check (GET /health) verifies the status of PostgreSQL, Redis, and WebSocket services. A liveness probe (GET /health/liveness) checks process viability (event loop lag and memory) without external dependencies, while a readiness probe (GET /health/readiness) verifies PostgreSQL connectivity to determine if the service can accept traffic. These endpoints are public, exempt from rate limiting, and integrated with Swagger documentation.
src/modules/health · high confidence
New identity API decorators and user/address DTOs
The identity module now exposes structured request decorators and DTOs that shape how users and addresses are managed via the API. The new CurrentUser and CallerCtx decorators allow controllers to cleanly extract the authenticated user and their caller context (including permissions) from the request, while the new DTOs define the input and output contracts for user and address operations. Specifically, ListUsersQueryDto adds support for filtering users by role code, active status, and search terms, and pagination. AssignRoleDto enforces uppercase role codes for role assignment. Address handling is supported via AddAddressDto, UpdateAddressDto, and AddressResponseDto, which define the fields for creating, updating, and returning address details. User management is supported via UpdateUserDto for profile updates and UserListItemResponseDto/UserDetailResponseDto for reading user data, with the detail response including an address count and list of addresses. PaginatedUsersResponseDto structures the paginated list of users.
src/modules/identity/primary-adapters · high confidence
New infrastructure metrics collector for database, Redis, and job queues
A new InfraMetricsCollector has been added to the metrics infrastructure, automatically gathering health and performance data every 60 seconds. It now exposes metrics for the PostgreSQL connection pool (active connections), Redis service status and cache generation, and the depth of the BullMQ notification queue (active, waiting, and delayed jobs). Error handling for queue metric collection has been implemented to prevent collection failures from crashing the process.
src/infrastructure/metrics/collectors · high confidence
New inventory API request and response schemas
The inventory module now exposes a comprehensive set of Data Transfer Objects (DTOs) that define the structure of API requests and responses. For input, users can now adjust stock levels (AdjustStockDto), reserve stock for orders (ReserveStockDto), and perform bulk stock checks (BulkCheckStockBodyDto). Querying inventory is supported via ListInventoryQueryDto and LowStockQueryDto, which include pagination, filtering by SKU or product ID, and sorting options. On the output side, the API returns structured data for inventory listings (InventoryListItemResponseDto, PaginatedInventoryResponseDto), stock details (InventoryStockResponseDto), stock availability checks (CheckStockResponseDto), and reservation statuses (ReservationResponseDto, StockReservationResponseDto). These schemas ensure consistent validation and clear documentation for all inventory-related endpoints.
src/modules/inventory/primary-adapters/dto · high confidence
New inventory availability and retrieval use cases
The inventory module now exposes two new application-layer capabilities: checking stock availability and retrieving inventory details. The CheckStockUseCase allows clients to verify if a specific quantity of a product is in stock, returning a structured result with availability status, available quantity, and requested quantity, while treating missing inventory rows as unavailable (quantity 0) rather than errors. The GetInventoryUseCase provides a way to fetch inventory data for a product, returning null if no inventory record exists, distinguishing between missing data and actual errors. Both use cases are implemented with comprehensive test coverage to ensure correct handling of edge cases like insufficient stock, missing products, and invalid inputs.
src/modules/inventory/core/application/usecases/check-stock · high confidence
New inventory management commands, query interfaces, and demo data seeding use cases
This change introduces the application-layer contracts and logic for inventory operations. It adds \AdjustStockCommand\ and \ReserveStockCommand\ interfaces to define how stock adjustments and reservations are triggered. It also defines the \InventoryQueryService\ abstract port along with \ListInventoryQuery\ and \InventoryListItemDTO\ to support paginated inventory lookups. Additionally, two new use cases are provided for development and testing: \SeedDemoInventoryUseCase\ creates initial inventory records for products, and \SeedDemoInventoryFromOrdersUseCase\ rebuilds inventory state by applying hold/consume effects from order lines.
src/modules/inventory/core/application · high confidence
New inventory management use cases for stock adjustments and reservations
The inventory module now includes new application-layer use cases to handle stock adjustments (adding, subtracting, or setting stock levels), reservation lifecycles (reserving, confirming, and releasing stock), and inventory reconciliation. The AdjustStockUseCase validates quantities and preserves reserved stock during adjustments. The ReserveStockUseCase creates new pending reservations, while ConfirmReservationUseCase and ReleaseStockUseCase manage the transition of reservation statuses with appropriate error handling for expired or non-pending states. Additionally, the ReconcileInventoryUseCase detects reservation drift by comparing database reserved quantities against the sum of active pending reservations, reporting discrepancies for operational visibility.
(repo-wide) · high confidence
New inventory use cases for bulk stock checks and low-stock listing
This change introduces two new application-layer use cases within the inventory module. The BulkCheckStockUseCase allows checking stock availability for multiple products in a single operation, handling duplicate product IDs by querying the repository once and defaulting to a quantity of 1 if not specified. The ListLowStockUseCase retrieves a list of inventory items that fall below a specified threshold, returning their primitive data representations. Both use cases are accompanied by comprehensive unit tests covering success paths, error handling, and edge cases like missing inventory records.
src/modules/inventory/core/application/usecases/bulk-check-stock, src/modules/inventory/core/application/usecases/list-low-stock · high confidence
New inventory use cases for listing items and retrieving order reservations
The inventory module now includes dedicated use cases to support specific inventory operations. Users can retrieve a paginated list of inventory items via the new ListInventoryUseCase, which leverages the InventoryQueryService to return structured results. Additionally, a new GetOrderReservationsUseCase has been added to fetch all reservations associated with a specific order ID by querying the ReservationRepository. These changes introduce the application-layer logic for these capabilities within the inventory module's use case directory.
src/modules/inventory/core/application/usecases/get-order-reservations, src/modules/inventory/core/application/usecases/list-inventory · high confidence
New job infrastructure with configurable retry policies and correlation context support
The \src/infrastructure/jobs\ module now provides a structured foundation for background job processing. It introduces a \BaseJobHandler\ that automatically restores correlation IDs for better traceability and standardizes error handling and logging. A new \JobConfigService\ centralizes job ID generation and applies specific retry policies (exponential, linear, or fixed backoff) to each job type defined in \JobNames\, such as \inventory-reconciliation\ and \expire-pending-orders\. Utility functions in \job-child-values\ and \job-correlation\ support these operations, while \JobsModule\ exposes the configuration service globally.
src/infrastructure/jobs · high confidence
New local development setup workflow with Docker integration
The \scripts/lib\ directory now includes a new setup bootstrap (\setup-bootstrap.js\) that orchestrates the local development environment by checking for Docker, generating environment files, starting PostgreSQL and Redis via Docker Compose, running database migrations, and seeding demo data. This workflow is supported by new utility libraries: \docker.js\ handles Docker preflight checks (detecting missing engine, timeouts, or missing Compose plugin) and manages the \docker compose up\ command for dev infrastructure; \pg.js\ provides PostgreSQL interaction capabilities, preferring Docker exec or ephemeral client containers for database operations; and \cli.js\ offers shared utilities for loading environment variables and parsing CLI arguments.
scripts/lib · high confidence
New logout and logout-all authentication use cases
The authentication module now includes dedicated application use cases for session termination. The new LogoutUseCase revokes a single active session by validating the refresh token, locating the corresponding session token, and marking it as revoked, while remaining idempotent if the session is not found. The new LogoutAllUseCase revokes all active sessions for a user by validating the refresh token and calling the session repository's revoke-all method. Both use cases are implemented as NestJS injectable services, depend on JWT verification and session token repositories, and return a standard Result type to handle success or error states.
src/modules/authentication/core/application/usecases/logout, src/modules/authentication/core/application/usecases/logout-all · high confidence
New operational scripts for environment setup, database management, and code quality
This change introduces a suite of new scripts in the \scripts/\ directory to streamline development, deployment, and maintenance. For environment setup, \generate-envs.js\ now creates \.env\ files from templates with environment-specific defaults (such as \TRUST\_PROXY\ and \IS\_DB\_SYNCHRONIZE\) and generates RSA keys for JWT secrets, while \setup.js\ orchestrates the full local development bootstrap including Docker, migrations, and seeding. Database operations are now supported by \db-backup.js\ and \db-restore.js\ for automated PostgreSQL dumps and restores, and a new \db-restore-drill.js\ script allows safe validation of restore procedures in a disposable database. Deployment is enhanced by \docker-migrate.js\, a self-contained runner for TypeORM migrations in production containers. The seed process (\seed.ts\, \seed-admin.ts\) now supports seeding categories, inventory, carts, orders, and payments, with explicit blocking in production environments. Code quality is improved by \lint-ascii-prose.cjs\ to enforce ASCII punctuation in documentation and comments, and \audit-openapi.js\ validates the OpenAPI spec for consistency. Additionally, \sync-agent-skills.js\ synchronizes AI agent skills across local and CI directories, and \smoke-test.js\ provides post-deployment HTTP probes.
scripts · high confidence
New order query mapping for list and detail views
Added the OrderQueryMapper and its supporting RawOrderListQueryRow interface to transform raw database projections into structured OrderListItemDTO and OrderDetailDTO objects. This enables the application to present order lists and detailed order views with consistent data shapes, including user information, shipping addresses, and item details.
src/modules/orders/secondary-adapters/mappers · high confidence
New payment capture and refund use cases with domain event publishing
The payments module now includes dedicated use cases for capturing authorized payments and processing refunds. The CapturePaymentUseCase locates an authorized payment, transitions its status to captured, and publishes a 'payment.captured' domain event. The ProcessRefundUseCase accepts a command containing the payment ID, refund amount, and reason; it resolves the appropriate payment gateway via the PaymentGatewayResolver, executes the refund transaction, updates the payment record with the refund details, and publishes a 'payment.refunded' domain event. Both use cases rely on the DomainEventPublisher to notify other parts of the system of these state changes.
src/modules/payments/core/application/usecases/process-refund · high confidence
New request sanitization and result-handling interceptors
Added a SanitizeInterceptor that recursively strips HTML and JavaScript from all string values in incoming request bodies, including nested objects and arrays, to prevent XSS issues. Also introduced a ResultInterceptor that automatically maps domain Result objects to HTTP responses, throwing HttpExceptions on failure and unwrapping success values, while logging unhandled internal errors.
src/interceptors · high confidence
New role assignment and lookup use cases in the authorization module
The authorization module now includes application-layer use cases for managing user roles. Users can have a default role assigned automatically if they lack one, or have a specific role assigned or updated by code. Additionally, the system can look up the current role and its associated permissions for a given user. These changes introduce new business logic for role management and the corresponding unit tests to verify the behavior.
src/modules/authorization/core/application/usecases/user-role · high confidence
New smoke testing framework for health and authentication checks
A new smoke testing suite has been added to the \scripts/smoke\ directory, providing automated health and authentication probes for the application. The framework includes an HTTP helper with timeout support, a probe builder that validates liveness, readiness, and full health endpoints, verifies the Prometheus metrics endpoint, and performs a full user registration and login flow to test the authentication API. A fail-fast runner executes these checks sequentially, reporting pass/fail status and exiting immediately on the first failure to ensure rapid detection of service issues.
scripts/smoke · high confidence
New use case for assigning roles to users
The application now includes an AssignUserRole use case that allows administrators to assign a specific role to an existing user. This feature validates that the user exists before attempting the assignment and handles errors gracefully, returning a 404 status if the user is not found or if the role assignment fails due to an invalid role code.
src/modules/identity/core/application/usecases/user/assign-user-role · high confidence
New use case to create orders from a shopping cart
Added the CreateOrderFromCartUseCase, which allows users to convert their current shopping cart into a new order. The use case fetches the cart via the CartGateway, validates that it is not empty, constructs the order domain entity using the OrderFactory (incorporating user ID, shipping address, payment method, and optional notes), and persists it via the OrderRepository. A corresponding test suite verifies successful creation, failure when the cart cannot be fetched, and failure when the cart is empty.
src/modules/orders/core/application/usecases/create-order-from-cart · high confidence
New use case to revoke all sessions for a user
A new RevokeAllForUserUsecase has been added to the authentication module, allowing users to invalidate all active session tokens for a specific user ID. This use case integrates with the SessionTokenRepository to perform the bulk revocation, providing a centralized application-layer capability for session management.
src/modules/authentication/core/application/usecases/revoke-all-for-user · high confidence
New user activation and creation use cases in the Identity module
The Identity module now includes application-layer use cases for activating existing users and creating new ones. The ActivateUserUseCase handles the workflow of finding a user by ID, validating that they are not already active, invoking the domain activation logic, and persisting the change, returning specific errors if the user is not found or already active. The CreateUserUseCase accepts a command containing user details (name, email, phone), constructs a new User entity with an active status, and persists it via the repository, handling potential repository errors. Both use cases are accompanied by unit tests verifying their success and failure paths.
src/modules/identity/core/application/usecases/user/create-user · high confidence
Payments module restructured with hexagonal architecture and Stripe integration
The Payments module has been reorganized to follow hexagonal architecture best practices, introducing a clear separation between domain, application, and infrastructure layers. This change adds core domain entities for Payment and Refund with full lifecycle management (pending, authorized, captured, failed, refunded), application use cases for creating payment intents, processing refunds, and querying payments by order ID, and a new Stripe gateway integration with signature verification for webhooks. The module now supports Stripe as the primary payment method, replacing previous PayPal and COD components, and includes a demo payment seeding capability for development environments.
src/modules/payments · high confidence
PostgreSQL implementation for Role and Permission repositories with incremental permission syncing
This change introduces the PostgreSQL persistence layer for the authorization module, specifically implementing the \PostgresRoleRepository\ and \PostgresPermissionRepository\. For roles, the repository now supports creating, updating, and deleting roles while linking them to permissions. A key behavioral detail is that updating a role's permissions uses an incremental sync strategy (adding or removing specific links) rather than replacing all associations, which preserves existing data integrity. The implementation also enforces uniqueness constraints, rejecting duplicate role or permission codes. Integration tests confirm that these repositories correctly persist data to a real database and handle round-trip operations for permissions and role-permission mappings.
src/modules/authorization/secondary-adapter/repositories/postgres-role-repository · high confidence
PostgreSQL implementation for notification query operations
Users can now retrieve notifications via a new Postgres-based query adapter that supports paginated listing filtered by user ID, target role, and status, as well as fetching individual notifications by ID. This change introduces the \PostgresNotificationQueryAdapter\ which implements the \NotificationQueryService\ interface, mapping database rows to DTOs and handling pagination logic, thereby enabling efficient data retrieval from the PostgreSQL database for the notification module.
src/modules/notifications/secondary-adapters/query · high confidence
PostgreSQL implementations for credential and session token repositories
This change introduces the primary database adapters for the Authentication module, enabling persistent storage of user credentials and session tokens via PostgreSQL. The new \PostgresCredentialRepository\ handles saving, retrieving, updating, and deleting password credentials, including enforcing a one-credential-per-user constraint. The \PostgresSessionTokenRepository\ manages session lifecycle operations, allowing tokens to be saved, looked up by ID, revoked for a specific user (supporting logout-all functionality), and automatically cleaned up when expired. Both repositories are implemented using TypeORM and include integration tests against a real database to verify data persistence and business logic correctness.
src/modules/authentication/secondary-adapters/repositories · high confidence
PostgreSQL notification repository implementation and integration tests
The system now includes a concrete Postgres-based implementation of the notification repository, handling core operations such as saving notifications, retrieving them by ID or user ID (with pagination and unread counts), marking notifications as read, and deleting expired entries. This adapter uses TypeORM for data persistence and integrates with the application's shared error-handling utilities to wrap database operations in Result types. To ensure reliability, comprehensive integration tests have been added that verify these repository methods against a real database, including round-trip persistence, user-scoped filtering, status updates, and expiration cleanup.
src/modules/notifications/secondary-adapters/repositories · high confidence
PostgreSQL reservation repository with concurrency-safe inventory locking
The PostgresReservationRepository now implements reservation logic using a REPEATABLE READ transaction with pessimistic write locks on inventory rows, ensuring that concurrent checkout attempts serialize correctly and prevent overselling. It provides save, release, confirm, findById, findByOrderId, findAllByOrderId, and findPendingExpired methods, all wrapped in Result-based error handling. Integration and unit tests verify correct inventory decrementing, stock validation, and concurrent safety.
src/modules/inventory/secondary-adapters/repositories/postgres-reservation-repository · high confidence
PostgreSQL-based inventory query adapter with cross-context product data joins
The inventory module now uses a new PostgresInventoryQueryAdapter to retrieve inventory data, implementing the InventoryQueryService interface. This adapter performs database queries that join the inventory table with the products table, allowing users to filter and sort inventory items by product SKU, product title, and stock levels (including a low-stock filter). The list operation returns paginated results containing product identifiers, SKUs, titles, and quantity details, while the getByProductId operation fetches a single inventory projection. Integration tests verify that these queries correctly join data and handle cases where product data is missing.
src/modules/inventory/secondary-adapters/query · high confidence
Request correlation IDs and structured HTTP logging
The application now automatically assigns a unique correlation ID to every HTTP request, preserving any existing X-Request-Id header from clients or generating a new UUID if one is absent. This ID is attached to the request context, propagated through all asynchronous code via AsyncLocalStorage, and included in the response headers for easier debugging and support. Additionally, HTTP logging middleware now records structured logs for each request, including method, URL, status code, duration, IP, user agent, and the correlation ID, providing better observability into request lifecycles.
src/infrastructure/logging/middleware · high confidence
Scheduled daily inventory reconciliation audit
The system now automatically schedules a daily inventory reconciliation audit job to run at 4:00 AM. This scheduler integrates with the application lifecycle to ensure the job is only registered during normal operation and is safely skipped if the application is shutting down, preventing errors during restarts.
src/modules/inventory/secondary-adapters/schedulers · high confidence
Ship Order Use Case Implementation
The ShipOrderUseCase has been implemented to handle the logic for transitioning an order to the shipped status. It retrieves the order using a versioned find operation (findByIdForUpdate) to ensure data consistency, validates that the order is in the correct processing state, and persists the change via the order repository. The implementation includes comprehensive unit tests covering success scenarios, various invalid states (pending, confirmed, already shipped, delivered, cancelled), and error handling for repository failures.
src/modules/orders/core/application/usecases/ship-order · high confidence
User deactivation capability with optimistic locking and event publishing
The system now supports deactivating user accounts. When a user is deactivated, the system locates the user record using optimistic locking (findByIdForUpdate), marks the user as inactive, persists the change, and publishes a 'user.deactivated' domain event. If the user is not found or is already deactivated, the operation fails with an appropriate error without modifying the database or publishing events.
src/modules/identity/core/application/usecases/user/deactivate-user · high confidence
User profile update capability added
The system now supports updating user personal information (first name, last name, email, and phone) through a new UpdateUserUseCase. This use case retrieves the user for update, applies the provided changes, and persists them, handling cases where the user is not found or the repository save operation fails.
src/modules/identity/core/application/usecases/user/update-user · high confidence
WebSocket adapter now supports Redis for cross-instance communication with graceful shutdown
The WebSocket infrastructure now uses a Redis-based adapter (via @socket.io/redis-adapter) to enable real-time communication across multiple application instances, replacing the previous in-memory-only approach. The new RedisIoAdapter handles connection resilience by falling back to an in-memory adapter if Redis is unavailable, and implements idempotent graceful shutdown logic to prevent race conditions or errors when closing duplicate Pub/Sub clients during application termination.
src/infrastructure/websocket/adapters · high confidence
WebSocket authentication service with token extraction and verification
The WsAuthService now handles WebSocket connection authentication by extracting JWT tokens from Socket.IO handshake data, prioritizing the \auth.token\ field over URL query parameters or Authorization headers to improve security. It uses the JwtVerifierPort to validate tokens and throws specific errors for missing or invalid tokens, with unit tests verifying the token extraction priority and error handling.
src/infrastructure/websocket/services · high confidence
Architecture
Define domain repository contracts for inventory and reservations
The inventory module now exposes explicit domain contracts for data access via the new \InventoryRepository\ and \ReservationRepository\ interfaces. The \InventoryRepository\ defines methods for retrieving inventory items (including batch traversal and low-stock queries) and saving/deleting with optimistic versioning support. The \ReservationRepository\ specifies operations for managing reservations, including saving, updating, releasing, confirming, and calculating pending reserved quantities by product ID. These abstract classes establish the boundaries for infrastructure implementations.
src/modules/inventory/core/domain/repositories · high confidence
Orders module adopts hexagonal architecture with new secondary adapters
The Orders module has been refactored to follow hexagonal architecture best practices by introducing new secondary adapter gateways in the \src/modules/orders/secondary-adapters/adapters\ directory. These adapters—\ModuleCartGateway\, \ModuleInventoryReservationGateway\, \ModulePaymentGateway\, and \ModuleUserGateway\—now serve as the concrete implementations for cross-module communication, delegating to specific use cases in the Carts, Inventory, Payments, and Identity modules respectively. This change replaces previous direct dependencies with a structured gateway pattern, ensuring that order processing logic interacts with other domains through well-defined ports and adapters.
src/modules/orders/secondary-adapters/adapters · high confidence
Behavioural changes
Address management use cases migrated to Identity module with type support
The address management use cases (Add, Update, Delete, and Set Default) have been moved from the Access module into the Identity module's core application layer. This change introduces support for address types (e.g., HOME, WORK, SHIPPING) during creation and updates, defaulting to SHIPPING when omitted. The use cases now enforce ownership policies via \OwnedResourceAccessPolicy\, allowing admins and system callers to manage any user's addresses while restricting customers to their own. All operations utilize \findByIdForUpdate\ for optimistic concurrency control and return structured \Result\ objects with specific error types (UseCaseError, RepositoryError, DomainError) for better error handling.
src/modules/identity/core/application/usecases/address · high confidence
Automated checkout failure compensation
The system now automatically handles failed checkout jobs by triggering a compensation workflow. When a job in the checkout queue fails, the new CheckoutFailureListener intercepts the event and attempts to reverse the transaction by refunding the payment, cancelling the order, and releasing any reserved stock. This ensures data consistency and prevents orphaned reservations or payments when checkout processes encounter errors.
src/modules/orders/primary-adapters/listeners · high confidence
BullMQ-based notification scheduler with structured results and graceful shutdown
The notification module now uses a new BullMQ-based scheduler (BullMqNotificationScheduler) that schedules notifications as a multi-step job flow (send, update status, save history) and returns structured success/failure results instead of throwing errors. It also schedules a daily cleanup job at 3 AM, integrates correlation logging for traceability, and handles application shutdown gracefully by skipping new schedules and demoting scheduling errors to debug level during shutdown.
src/modules/notifications/secondary-adapters/schedulers · high confidence
Cached user repository with improved error handling and test coverage
The identity module now uses a dedicated CachedUserRepository that wraps the Postgres user repository with Redis caching. This implementation improves reliability by handling cache failures gracefully: if a cache lookup fails or returns null, it falls back to the database without throwing errors, and if a cache write fails after a successful database save, it logs a warning but still returns the success result. The repository now properly escapes special characters in email addresses when searching the Redis index, and includes comprehensive integration and unit tests to verify cache hit/miss behavior, save/delete operations, and error resilience.
src/modules/identity/secondary-adapters/repositories/cached-user-repository · high confidence
Cart and CartItem domain interfaces now include currency support
The core domain interfaces for the cart module have been updated to support multi-currency transactions. The new \ICartItem\ interface includes a \currency\ field alongside existing product details, and the \ICart\ interface now tracks a \currency\ property at the cart level, in addition to the standard items, totals, and timestamps. This allows the system to associate specific currencies with individual line items and the overall cart total.
src/modules/carts/core/domain/interfaces · high confidence
Cart creation now returns presentation data and enforces permission checks
The CreateCartUseCase now returns a CartPresentationDTO containing fields such as id, userId, items, subtotal, shippingCost, totalAmount, and currency, rather than just a void or raw domain entity. It also validates that the caller has the 'manage\_own\_cart' permission and a valid userId, rejecting unauthorized attempts with a 'Not authorized to create a customer cart' error. If a cart already exists for the user, it returns that existing cart instead of creating a new one.
src/modules/carts/core/application/usecases/create-cart · high confidence
Cart item operations now enforce ownership validation and inventory checks
The AddCartItem and UpdateCartItem use cases have been refactored to strictly validate that the user owns the cart before allowing modifications, replacing previous session-token dependencies with a dedicated CartOwnershipValidator. Additionally, both operations now integrate with external product and inventory gateways to verify product existence and ensure sufficient stock availability before persisting changes, while also supporting currency and image data for new items.
src/modules/carts/core/application/usecases/add-cart-item · high confidence
Cart persistence mappers restructured with currency support and stable item ordering
The cart persistence layer now includes dedicated mappers for cart items and carts, introducing a currency field to cart items and ensuring that cart line items are stored and retrieved in a stable, sorted order (by ID). The cart mapper also implements cache serialization logic that converts date objects to timestamps for storage and handles deserialization errors gracefully by returning null, while the item mapper correctly omits unset child IDs during persistence.
src/modules/carts/secondary-adapters/persistence · high confidence
Cart query mapping now exposes subtotal, shipping cost, and stable item ordering
The cart query mapper now transforms raw database rows into a presentation DTO that includes calculated subtotal, shipping cost, and total amount fields, along with currency and image URL data for each line item. To ensure a consistent user experience, line items are sorted by ID in ascending order regardless of the order returned by the database, preventing visual flickering when items are updated. The mapper also handles legacy data by including cart lines where the item ID is 0.
src/modules/carts/secondary-adapters/mappers · high confidence
Cart repository interface updated to use userId and optimistic locking
The cart repository interface has been refactored to replace customer-centric identifiers with userId, aligning with the application's shift to user-based ownership. The interface now enforces optimistic concurrency control by requiring an expected version number for find and save operations, ensuring data integrity during concurrent updates. Additionally, the repository abstract class defines methods for finding carts by ID or user ID, saving carts with version checks, and deleting carts, all returning standardized Result types for error handling.
src/modules/carts/core/domain/repositories · high confidence
Cart use cases now enforce ownership validation and return void
The ClearCart and RemoveCartItem use cases have been refactored to require a CartOwnershipValidator, ensuring that only the cart owner can modify the cart contents. Additionally, these use cases now return void instead of a result object upon success, simplifying the caller's handling of successful operations while still propagating errors via the Result type.
src/modules/carts/core/application/usecases/clear-cart, src/modules/carts/core/application/usecases/remove-cart-item · high confidence
Centralized API versioning and trust proxy parsing utility
The HTTP infrastructure now provides a single source of truth for the default API version (v1) and prefix via the new api-version module, ensuring consistency across NestJS configuration, cookie paths, and E2E tests. Additionally, a new parseTrustProxy utility has been introduced to standardize how proxy settings are interpreted, supporting boolean strings, hop counts, and subnet strings.
src/infrastructure/http · high confidence
Centralized Redis caching configuration and search index schemas
The application now uses a dedicated constants module to manage Redis cache keys, expiration policies, and RediSearch index schemas for core entities. Cache expiration is standardized to 7 days for orders, products, inventory, payments, and users, while cart data is cached for 30 days. Idempotency keys expire after 24 hours with a 2-second retry hint, and role-permission caches expire after 1 hour. Additionally, explicit index schemas are defined for Orders, Products, Inventory, Carts, Payments, and Users, specifying field types (TEXT, NUMERIC, TAG) and sortable attributes to support efficient search and filtering.
src/infrastructure/redis/constants · high confidence
Centralized infrastructure module with logging, metrics, and throttling middleware
The application now uses a new InfrastructureModule that consolidates core services (database, Redis, queue, jobs, idempotency, JWT) and registers global middleware to improve observability and protection. On every request, MetricsMiddleware runs first to capture full request duration, followed by CorrelationIdMiddleware to establish a correlation context, and then HttpLoggingMiddleware to write logs with that context. The module also exports a DomainEventPublisher backed by EventEmitter2 for domain events, and includes AppThrottlerModule for rate limiting.
src/infrastructure · high confidence
Checkout completion now publishes a domain event
The FinalizeCheckout use case now publishes a 'checkout.saga.completed' domain event containing the flow and order IDs when a checkout is finalized. This enables downstream systems to react to the completion of the checkout process, supporting event-driven workflows such as order fulfillment or inventory updates.
src/modules/orders/core/application/usecases/finalize-checkout · high confidence
Enforced branch protection and Jira issue key validation via Git hooks
New Husky hooks now prevent direct commits and pushes to the master and develop branches, requiring developers to use feature branches and Pull Requests instead. Additionally, a commit-msg hook automatically prepends the Jira issue key (extracted from the branch name) to commit messages for non-main branches, ensuring traceability while allowing direct commits on main branches without issue keys.
.husky · high confidence
Enhanced refresh token flow with credential and permission integration
The RefreshTokenUseCase now integrates credential management and authorization data into the token refresh process. When refreshing a token, the system verifies the session, detects token reuse to revoke all user sessions for security, and then retrieves the user's role and credential status. The new access token includes the user's role code, permissions, and a mustChangePassword flag, ensuring that immediate credential changes and permission updates are reflected in subsequent requests.
src/modules/authentication/core/application/usecases/refresh-token · high confidence
GetOrder use case now enforces caller context and resource ownership policies
The GetOrder use case has been refactored to require a CallerContext input, enabling access control based on user roles and permissions. It now utilizes the OwnedResourceAccessPolicy to determine if the caller is authorized to view the order (e.g., admins can view all orders, customers only their own). The use case delegates data retrieval to the OrderQueryService, passing the authorized user ID when applicable, and returns a 404-style error if the order is not found or access is denied.
src/modules/orders/core/application/usecases/get-order · high confidence
Global exception filter now exposes machine-readable error codes and handles optimistic lock conflicts
The new GlobalExceptionFilter standardizes error responses across the application by including a machine-readable \code\ field in JSON payloads for HttpExceptions and AppErrors, allowing clients to programmatically handle specific error conditions. In production environments, sensitive details like stack traces and internal error messages are suppressed to improve security, while development modes retain full diagnostic information. Additionally, the filter now explicitly handles TypeORM's OptimisticLockVersionMismatchError, returning a 409 Conflict status with a user-friendly message prompting the user to reload and retry, ensuring consistent behavior for concurrent modification scenarios.
src/filters · high confidence
Graceful application shutdown with safety timeout
The application now handles process termination signals (SIGTERM, SIGINT) via a new ShutdownService that implements a graceful shutdown lifecycle. When a shutdown signal is received, the service initiates a 15-second safety timeout; if the application does not complete shutdown within this window, the process is forcibly exited to prevent hanging. The service exposes an isShuttingDown status and ensures the safety timeout is cleared if shutdown completes normally.
src/infrastructure/shutdown · high confidence
Introduce Winston-based structured logging with OpenTelemetry correlation
The application now uses a new Winston-based logger service that replaces the previous logging implementation. This change introduces structured JSON logging with automatic correlation IDs and OpenTelemetry trace/span context injection into every log entry. It supports configurable transport modes (file, console, or both) via the LOG\_TRANSPORT environment variable, implements daily rotating file logs for errors, combined output, and HTTP requests, and ensures logs are flushed on application shutdown.
src/infrastructure/logging · high confidence
Introduce gateway adapters for cross-module communication
Added ModuleInventoryGateway and ModuleProductGateway to the cart module's secondary adapters. These new classes implement the CartInventoryGateway and CartProductGateway ports respectively, acting as the bridge between the cart module and the inventory and product modules. The inventory gateway now delegates stock checks to the CheckStockUseCase, while the product gateway retrieves product details (including price, currency, and image URL) via the GetProductUseCase, ensuring the cart module interacts with other domains through defined interfaces rather than direct dependencies.
src/modules/carts/secondary-adapters/adapters · high confidence
Introduce optimistic locking and new stock-release use case in Orders module
The DeliverOrder use case now uses optimistic locking (findByIdForUpdate with version checking) to prevent concurrent modification conflicts when changing an order's status to delivered. A new ReleaseOrderStock use case has been added to handle releasing inventory reservations by scheduling stock-release jobs via the OrderScheduler. These changes are part of a broader refactor to align with hexagonal architecture, standardize error handling, and improve consistency across the Orders module.
src/modules/orders/core/application/usecases/deliver-order · medium confidence
Introduce structured cart presentation DTOs for query results
A new result type file has been added to the cart application queries layer, defining \CartPresentationDTO\ and \CartItemPresentationDTO\ interfaces. These structures standardize the shape of cart data returned by queries, explicitly exposing fields such as \subtotal\, \shippingCost\, and \totalAmount\ alongside item details like \productName\ and \imageUrl\. This change provides a clear, typed contract for cart presentation data, separating the query result structure from internal domain models.
src/modules/carts/core/application/queries · high confidence
Introduces authentication command interfaces and result structures
The authentication module now defines specific command interfaces for user registration, login, and password changes, establishing the input contracts for these core actions. Additionally, the AuthTokensResult structure has been updated to include a mustChangePassword flag and a permissions array, allowing the system to signal password reset requirements and return user permissions alongside access and refresh tokens.
src/modules/authentication/core/application/commands · high confidence
Introduces new application-layer ports for order query, cart, payment, inventory, and user gateways
The orders module now exposes a set of new abstract ports in the application layer to define contracts for downstream services and read operations. This includes an OrderQueryService for retrieving presentation-optimized order lists and details, a CartGateway for validating and managing checkout carts (including caller context support), a PaymentGateway for creating payment intents and processing refunds, an InventoryReservationGateway for reserving and confirming stock, and a UserGateway for fetching checkout-specific user information. These ports replace previous ad-hoc or broader gateway definitions with downstream-specific DTOs and clearer separation between command and query responsibilities.
src/modules/orders/core/application/ports · high confidence
Introduction of versioned Order repository interface
The Order repository interface has been updated to support optimistic concurrency control. The \save\ method now accepts an optional \expectedVersion\ parameter, and a new \findByIdForUpdate\ method has been added to retrieve an order along with its current version number, enabling safe concurrent updates to order data.
src/modules/orders/core/domain/repositories · high confidence
Inventory domain interfaces and value objects introduced
The inventory module now exposes explicit domain contracts and value objects to support stock management and reservations. New interfaces define the structure for inventory records (IInventory), stock check results (CheckStockResult), and reservation data (IReservation, IReservationItem). Value objects introduce a ReservationStatus enum (PENDING, CONFIRMED, RELEASED, EXPIRED) and a StockAdjustmentReason class with typed reasons (e.g., RESTOCK, DAMAGE, RETURN) and factory methods, alongside a StockAdjustmentType enum (ADD, SUBTRACT, SET). These changes standardize how inventory state and adjustments are modeled within the domain.
src/modules/inventory/core/domain/interfaces, src/modules/inventory/core/domain/value-objects · high confidence
Inventory query results now include default fallbacks for missing product details
The inventory query mapper now ensures that list items always contain valid data by applying default values when raw database fields are null or missing. Specifically, if the SKU is absent, it defaults to 'N/A', and if the product title is missing, it defaults to 'Unknown Product'. Additionally, numeric fields like available and reserved quantities are safely converted to numbers, with the total quantity calculated as the sum of available and reserved if not explicitly provided, ensuring consistent data shapes for downstream consumers.
src/modules/inventory/secondary-adapters/mappers · high confidence
JWT authentication now propagates a mustChangePassword flag and enforces password rotation
The AuthGuard now attaches a mustChangePassword boolean to the request user object based on the JWT claim, and a new MustChangePasswordGuard blocks access for users flagged for password rotation. When a user's token includes mustChangePassword=true, the new guard verifies the flag against the credential repository and returns a ForbiddenException with code MUST\_CHANGE\_PASSWORD if the password has not yet been changed, while allowing access once the credential is updated or for routes marked as public or allowed during password change.
src/guards · high confidence
List Payments use case now enforces caller-based access control
The ListPaymentsUseCase has been refactored to accept a CallerContext and enforce access policies before querying. Admins can view all payments, while customers are scoped to their own payments only. The use case now delegates to PaymentQueryService and returns an empty result when access is denied.
src/modules/payments/core/application/usecases/list-payments · high confidence
List orders use case now enforces caller context and access policies
The ListOrdersUsecase has been refactored to accept a CallerContext and apply the OwnedResourceAccessPolicy, ensuring that customers can only view their own orders while admins can view all. The use case now delegates data retrieval to the OrderQueryService and handles errors via the Result pattern, with corresponding unit tests verifying access control logic and error propagation.
src/modules/orders/core/application/usecases/list-orders · high confidence
Login flow now includes password change requirement and user permissions in response
The LoginUserUseCase has been updated to enrich the authentication response with additional context for the client. Upon successful login, the returned token payload and result object now include a \mustChangePassword\ boolean (derived from the user's credential record) and a list of \permissions\ (resolved from the user's assigned role via the AuthorizationGateway). This allows clients to immediately enforce password rotation policies and apply fine-grained UI/feature gating based on the user's specific permissions without making a separate API call.
src/modules/authentication/core/application/usecases/login-user · high confidence
Metrics endpoint secured and business events instrumented
The /metrics endpoint is now protected by a new authentication guard that requires a valid API key (via X-Metrics-API-Key header or Authorization Bearer token) and uses constant-time comparison to prevent timing attacks; if the key is not configured, access is denied with a warning. Additionally, a new listener automatically records key business metrics—including order creation, checkout saga outcomes, payment captures/refunds, authentication success/failure, and checkout initiation—by incrementing counters whenever corresponding application events are emitted.
src/infrastructure/metrics/guards, src/infrastructure/metrics/listeners · high confidence
New authentication DTOs and schema definitions for API contracts
The authentication module now introduces a comprehensive set of Data Transfer Objects (DTOs) that define the input and output contracts for user registration, login, token management, and password changes. These new files establish the structure for the \RegisterDto\ and \RegisterResponseDto\ (including optional phone fields), \LoginDto\, and \ChangePasswordDto\ with validation rules like email format and minimum password length. Token handling is formalized through \AuthTokensResponseDto\ (which now explicitly includes a \permissions\ array and a \mustChangePassword\ flag), \RefreshTokenDto\, and \JwksResponseDto\ for JSON Web Key Set responses. This change standardizes the API schema definitions used by the Swagger documentation and enforces non-nullable properties where appropriate.
src/modules/authentication/primary-adapters/dto · high confidence
New centralized environment configuration and validation system
The application now uses a dedicated configuration module (EnvConfigModule) that provides a globally exported EnvConfigService for accessing settings. This service relies on a new validation layer (validate-env) using envalid to enforce required environment variables and defaults for Redis, PostgreSQL, JWT (using privateKey and TTLs), logging, CORS, rate limiting (throttle), proxy trust, metrics, OpenTelemetry, and payment mocks. Configuration values are resolved via an AppConfigReader that maps keys to an IAppConfig interface, and environment file paths are resolved based on NODE\_ENV (e.g., .env.development).
src/config · high confidence
New persistence mappers for Inventory, Reservation, and ReservationItem
The persistence layer now includes dedicated mapper classes (InventoryMapper, InventoryCacheMapper, ReservationMapper, and ReservationItemMapper) that handle the translation between domain entities and ORM schema objects. These mappers ensure consistent data transformation for inventory stock levels, reservation orders, and their associated line items, with the cache mapper specifically handling date serialization and null-safe deserialization for improved reliability.
src/modules/inventory/secondary-adapters/persistence · high confidence
New persistence mappers for User and Address entities
Added new mapper classes (AddressMapper, UserMapper, UserCacheMapper) in the identity persistence layer to handle bidirectional conversion between domain models and ORM entities. UserMapper now includes a toUpdatePayload method for generating update-specific payloads, and UserCacheMapper implements robust serialization for caching, including null-safe handling for phone numbers and error recovery in fromCache to return null on deserialization failures.
src/modules/identity/secondary-adapters/persistence · high confidence
New ports for cart queries and external service communication
The cart module now exposes new application ports to support data retrieval and cross-module interactions. A CartQueryService port has been added to define contracts for fetching cart details by ID or user ID, returning presentation DTOs. Additionally, gateway interfaces for inventory (CartInventoryGateway) and product data (CartProductGateway) have been introduced, enabling the cart module to check stock availability and retrieve product information (including image URLs) from external services.
src/modules/carts/core/application/ports · high confidence
New secondary adapters for Identity and Authorization modules
The authentication module now includes new secondary adapters (\ModuleIdentityGateway\ and \ModuleAuthorizationGateway\) that implement the core application ports for identity and authorization. These adapters delegate user management operations (create, read, delete, check email) to the Identity module's use cases and role management operations (assign role, assign default role, find role) to the Authorization module's use cases, effectively wiring the authentication layer to the newly separated domain modules.
src/modules/authentication/secondary-adapters/adapters · high confidence
Order cancellation now supports saga compensation and stock release scheduling
The CancelOrderUseCase has been refactored to handle saga-based workflows and background stock management. When the \isSagaCompensation\ flag is passed, the use case now publishes \checkout.saga.compensation\ and \checkout.saga.failed\ domain events to coordinate distributed transactions. Additionally, upon successful cancellation, the system automatically schedules a stock release job via the \OrderScheduler\, ensuring inventory is returned even if the cancellation process is part of a larger saga that might fail later. The use case also now utilizes \findByIdForUpdate\ for optimistic concurrency control and includes improved error logging for scheduling failures.
src/modules/orders/core/application/usecases/cancel-order · high confidence
Order status transition rules and validation logic
The order workflow now enforces a strict state machine for order statuses. Users can no longer move an order to arbitrary states; transitions are limited to defined paths (e.g., PENDING\_PAYMENT to CONFIRMED or CANCELLED). Attempting an invalid transition, such as moving from DELIVERED back to CONFIRMED, will now throw an error. Terminal states (CANCELLED, REFUNDED) are explicitly defined and cannot transition further.
src/modules/orders/core/domain/policies · high confidence
Orders module ORM schemas restructured with versioning and new indexes
The Order and OrderItem database schemas have been updated to include optimistic concurrency control via a version column on the OrderEntity, and several new database indexes (including composite indexes on user\_id/status and status/createdAt) to improve query performance. The OrderItemEntity schema now explicitly indexes the productId field, while the OrderEntity schema centralizes payment method definitions from the shared kernel and enforces specific numeric precision for financial fields.
src/modules/orders/secondary-adapters/orm · high confidence
Orders module refactored to support asynchronous checkout with idempotency and job processing
The Orders module has been restructured to support a new asynchronous checkout workflow. The POST /orders/checkout endpoint now initiates a background job (via BullMQ) rather than processing the order synchronously, returning an orderId and jobId for clients to poll for status. This change introduces idempotency support for the checkout endpoint to prevent duplicate processing, along with new use cases and job steps for validating carts, reserving stock, processing payments, and finalizing orders. The module also integrates with Identity, Carts, Inventory, and Payments modules via gateways, and includes new endpoints and use cases for canceling, confirming, processing, shipping, and delivering orders.
src/modules/orders · high confidence
Payment creation and verification now enforce caller-based access control
The CreatePayment and VerifyPayment use cases now require a caller context to enforce access policies. When creating a payment, the system verifies that the user has permission to access the associated order before proceeding with gateway authorization and persistence. Similarly, verifying a payment now checks that the caller is either an admin or the payment owner, returning a failure if access is denied. This ensures that payment operations are restricted to authorized users based on their role and resource ownership.
src/modules/payments/core/application/usecases/create-payment · high confidence
Payment retrieval now enforces caller-based access control
The GetPayment use case has been updated to require a CallerContext, enabling the system to distinguish between admin and customer users. Admins can view any payment, while customers are restricted to viewing only their own payments, ensuring that payment data is scoped correctly based on the user's role and permissions.
src/modules/payments/core/application/usecases/get-payment · high confidence
PostgreSQL cart repository now supports optimistic locking and improved error handling
The PostgresCartRepository has been refactored to support optimistic concurrency control (OCC) for cart updates. When saving a cart with an expected version, the repository now performs an atomic update that checks the version and increments it, preventing lost updates from concurrent modifications. If the version does not match, a conflict error is returned. The repository also now handles cart item synchronization within transactions, ensuring that items are correctly added, updated, or removed in a single atomic operation. Error handling has been improved to provide specific error messages for not-found and conflict scenarios.
src/modules/carts/secondary-adapters/repositories/postgres-cart-repository · high confidence
PostgreSQL order repository now supports optimistic locking for concurrent updates
The PostgresOrderRepository has been updated to handle concurrent order modifications safely using optimistic locking. When saving an order that has been previously loaded for update, the repository now requires an expected version number; it performs an atomic update that checks the current database version against this expectation. If the versions match, the order and its associated items are saved with an incremented version. If they do not match (indicating a concurrent modification), the operation fails with a 409 Conflict error rather than silently overwriting changes. This change also includes integration and unit tests to verify the correct behavior of both standard saves and versioned updates.
src/modules/identity/secondary-adapters/repositories/postgres-user-repository, src/modules/orders/secondary-adapters/repositories/postgres-order-repository · high confidence
Postgres inventory repository refactored with enhanced query capabilities and optimistic locking
The Postgres inventory repository has been restructured to support advanced inventory operations, including batch queries, low-stock filtering, and optimistic concurrency control. Users can now retrieve inventory in batches or filter by stock levels, while save operations enforce version checks to prevent concurrent modification conflicts. The repository also provides improved error handling with specific HTTP status codes for not-found scenarios and includes comprehensive unit and integration tests to verify these new behaviors.
src/modules/inventory/secondary-adapters/repositories/postgres-inventory-repository · high confidence
ProcessOrder use case now uses optimistic locking for state transitions
The ProcessOrder use case has been refactored to use optimistic locking when updating order status. It now calls findByIdForUpdate to retrieve the order with its current version, performs the state transition via the domain entity's process() method, and then saves the order using the expected version. This ensures that concurrent modifications to the same order are detected and rejected, preventing lost updates. The use case also validates that the order is in a processable state (confirmed) before proceeding, returning a failure if the order is not found, not confirmed, or if the save operation fails due to version mismatch.
src/modules/orders/core/application/usecases/process-order · high confidence
Product activation now requires a valid category
The product activation process now enforces that a product must be assigned to a category before it can be activated. If an attempt is made to activate a product with a null category, the operation fails with a BAD\_REQUEST error and the message 'Cannot activate a product without a category'. This change ensures data integrity by preventing the activation of products that lack essential categorization, while still allowing normal activation for products that already have a category assigned.
src/modules/products/core/application/usecases/activate-product · high confidence
Product creation and update now enforce category validation
The CreateProduct and UpdateProduct use cases now validate that the assigned category exists and is active before saving. Creating a product without a categoryId or with an unknown/invalid category ID returns a BAD\_REQUEST error, and updating a product with a null categoryId is also rejected. This ensures products are always linked to valid, active categories.
src/modules/products/core/application/usecases/create-product, src/modules/products/core/application/usecases/update-product · high confidence
Refactor GetCart use case to use CartQueryService and enforce ownership policies
The GetCart use case has been refactored to retrieve cart data via the new CartQueryService instead of direct repository access, and now enforces cart ownership through the OwnedResourceAccessPolicy. This ensures that customers can only access their own carts, while admins with the 'view\_all\_carts' permission can access any cart. The use case now accepts a CallerContext to determine access scope and returns appropriate errors when access is denied or the cart is not found.
src/modules/carts/core/application/usecases/get-cart · high confidence
Refactor Reserve Stock job to use checkout-specific use case and correlation service
The ReserveStockStep job handler has been updated to depend on the new ReserveStockForCheckoutUseCase instead of its previous implementation, ensuring consistent use of checkout-specific domain logic. Additionally, the handler now integrates the CorrelationService to enhance logging context, and its test suite has been added to verify this new behavior.
src/modules/orders/primary-adapters/jobs/reserve-stock-job · high confidence
Refactor mapper utilities to support optimistic locking and clean child ID persistence
The infrastructure mappers now include new utility types and functions to improve data integrity during persistence. A new \UpdateFromEntity\ type enforces explicit assignment of application-owned columns for atomic optimistic-lock updates, ensuring that versioning and timestamp fields are handled correctly by the repository. Additionally, a \persistedChildId\ utility ensures that unset or legacy child IDs are omitted from cart item persistence, preventing invalid foreign key references. These changes streamline the mapping layer and reduce the risk of data inconsistencies during entity updates.
src/infrastructure/mappers · high confidence
Refactor order persistence mappers to use hexagonal architecture and omit unset child IDs
The order persistence layer has been restructured to follow hexagonal architecture best practices, introducing dedicated mapper classes (OrderItemMapper, OrderMapper, ShippingAddressMapper) that handle translation between domain entities and ORM entities. A key behavioral change is that OrderItemMapper now omits the ID field for child items when the domain ID is null or 0, ensuring that unset child IDs are not persisted. Additionally, the mappers now support update payloads and cache serialization, with OrderCacheMapper handling date conversion for caching purposes.
src/modules/orders/secondary-adapters/persistence · high confidence
Refactored GetUserUseCase to use UserQueryService and enforce access policies
The GetUserUseCase now retrieves user data via the new UserQueryService instead of direct repository access, and enforces access control using the OwnedResourceAccessPolicy. This ensures that customers can only view their own profiles, while admins and system callers retain full access, with unauthorized access attempts returning a 404 Not Found error.
src/modules/identity/core/application/usecases/user/get-user · high confidence
Refactored ListUsersUseCase to use UserQueryService with access control
The ListUsersUseCase has been refactored to depend on UserQueryService for data retrieval instead of direct repository access. It now integrates an OwnedResourceAccessPolicy to resolve list scopes based on the caller's context, returning an empty result if access is not allowed, and passing the authorized user ID to the query service. Tests have been added to verify this behavior using a mock query service.
src/modules/identity/core/application/usecases/user/list-users · high confidence
Refactored authentication seeding use cases with improved error handling and test coverage
The seed scripts for the authentication module have been refactored to improve reliability and maintainability. The \SeedSuperAdminUseCase\ now includes input validation to reject passwords shorter than 6 characters and implements compensation logic to clean up partially created users if credential or role assignment steps fail. The \SeedDemoAuthUsersUseCase\ has been updated to return the \userId\ in its result object for better traceability. Both use cases are now accompanied by comprehensive unit tests that verify creation, idempotency (skipping existing users), and error compensation scenarios.
src/modules/authentication/core/application/seed · high confidence
Refactored database module structure and added numeric type transformer
The database infrastructure has been reorganized into a dedicated DatabaseModule that configures the PostgreSQL connection using environment variables, specifically adjusting logging to only show errors in production. Additionally, a new numeric transformer has been introduced to handle the conversion of string values to numbers during database operations, ensuring null safety and NaN handling.
src/infrastructure/database · high confidence
Refactored notification job handlers to use BaseJobHandler and CorrelationService
The job processing files in the notifications module (cleanup, delivery, history saving, and status updates) have been refactored to extend the new BaseJobHandler infrastructure class and integrate with the CorrelationService for enhanced logging context. This change standardizes how these background jobs are executed, ensuring consistent error handling via the Result type and improved traceability through correlation IDs, while maintaining the existing business logic for each specific job type.
src/modules/notifications/primary-adapters/jobs · high confidence
Refactored order processing into dedicated job handlers with improved type safety and logging
The order processing workflow has been restructured into a series of specialized job handlers (such as CreateOrderStep, ProcessPaymentStep, and ConfirmReservationStep) that extend a common BaseJobHandler. This change introduces CorrelationService integration for enhanced logging context across all steps, enforces stricter type safety through dedicated Result interfaces and validation functions (like isConfirmReservationResult), and standardizes error handling. The refactoring also simplifies the CreateOrderStep by removing direct order creation logic in favor of fetching existing orders, while ensuring consistent metadata handling, such as including cartId in payment process metadata.
src/modules/orders/primary-adapters/jobs · high confidence
Refactored payment completion and failure handling to decouple post-payment actions
The order payment handling logic has been restructured to improve reliability and separation of concerns. When a payment is completed, the system now confirms the order status and then schedules the post-payment flow (such as reservation processing) as a separate, independent job; if this scheduling fails, the order remains confirmed and the error is logged for manual intervention rather than rolling back the payment confirmation. Similarly, when a payment fails, the order is marked as failed and the stock release is scheduled as a separate job, ensuring that the order status update is not blocked by downstream scheduling issues. Both use cases now utilize optimistic locking via \findByIdForUpdate\ and \save\ to ensure data consistency.
src/modules/orders/core/application/usecases/handle-payment-completed, src/modules/orders/core/application/usecases/handle-payment-failed · high confidence
Refactored queue infrastructure to use shared BullMQ connection and improved shutdown handling
The queue infrastructure in src/infrastructure/queue has been reorganized to introduce a dedicated BullMQ connection module (BullMqConnectionModule) that centralizes connection options via a shared token (BULLMQ\_CONNECTION\_OPTIONS), ensuring consistent configuration across QueueModule, FlowProducer, and QueueEvents. New services include FlowProducerService for managing flow-based job production and QueueEventsService for handling queue events (failed, completed) with proper lifecycle management. Both services now implement OnApplicationShutdown to ensure graceful closure of connections and event listeners during application shutdown, replacing previous module-destroy patterns for more reliable resource cleanup.
src/infrastructure/queue · high confidence
Refined cart and cart-item API contracts with explicit totals and validation
The cart primary adapters now use stricter DTOs that enforce non-nullable, positive quantities for adding and updating items, and expose richer response shapes. Cart responses now include subtotal, shipping cost (currently always 0), total amount, and currency, while cart-item responses snapshot price and currency at add time and include subtotal and image URL. These changes improve input validation and provide users with clearer, more complete cart totals and item details in API responses.
src/modules/carts/primary-adapters · high confidence
Refresh token cookie handling now supports API versioning
The RefreshTokenCookieInterceptor has been updated to correctly handle both versioned and unversioned API routes. It now uses a helper to normalize route paths, ensuring that refresh tokens are set on login, refresh, and change-password endpoints, and cleared on logout, regardless of whether the request path includes the API version prefix (e.g., /v1/authentication/...).
src/modules/authentication/primary-adapters/interceptors · high confidence
Resilient rate limiting with user-specific tracking and Redis fallback
The throttling infrastructure now includes a ResilientThrottlerStorage that automatically falls back to in-memory storage if the Redis connection is unavailable or fails, ensuring rate limiting continues to function (albeit with per-instance limits) during outages. A new UserThrottlerGuard enables user-specific rate limiting by tracking requests against user IDs rather than just IP addresses, which prevents shared-client scenarios (like E2E tests) from causing cascading blocks. Additionally, specific throttle constants for authentication endpoints (login, register, password change) have been introduced to enforce stricter limits on sensitive routes.
src/infrastructure/throttler · high confidence
Role-based product visibility enforcement in product queries
The GetProduct and ListProducts use cases now enforce role-based visibility rules: inactive products are hidden from shoppers and unauthenticated users (returning 404 or filtered out), while operators with the VIEW\_ALL\_PRODUCTS permission can still view inactive items. This ensures that product browsing and retrieval respect user roles, preventing exposure of non-active catalog items to general users.
src/modules/products/core/application/usecases/get-product, src/modules/products/core/application/usecases/list-products · high confidence
Shipping address resolution logic moved to application service
The logic for determining a customer's shipping address has been extracted into a new \ShippingAddressResolver\ application service. This service now handles the decision to use an explicitly provided address from the checkout input or fall back to the user's default address stored in their profile, ensuring the domain layer only receives the final resolved address object.
src/modules/orders/core/application/services · high confidence
User query adapter now supports role-based filtering and detailed address retrieval
The PostgresUserQueryAdapter in the identity module now implements the UserQueryService interface, enabling users to filter user lists by role code (e.g., 'CUSTOMER') in addition to existing search, pagination, and active status filters. When retrieving a specific user's details, the adapter now joins with the authorization context to resolve role codes and fetches associated addresses, ordering them by default status and creation date. This change provides a more comprehensive view of user data, including their assigned roles and address history, directly through the query layer.
src/modules/identity/secondary-adapters/query · high confidence
Versioned cache key management and automatic recovery on Redis reconnection
The Redis infrastructure now supports cache generation versioning to handle stale data after Redis outages. Domain-specific cache keys (e.g., product, user, order) are prefixed with a generation number (e.g., \c1:\), while stable keys like idempotency tokens and metadata remain unchanged. A new \RedisCacheRecoveryService\ listens for Redis reconnection events; upon reconnection, it increments the cache generation, drops RediSearch indexes from the previous generation, clears cached flags, and reinitializes indexes. This ensures that stale cache-aside data is invalidated and the system repopulates the cache on demand with fresh data, while metrics track any recovery failures.
src/infrastructure/redis · high confidence
WebSocket connection handling and authentication restructured
The WebSocket infrastructure has been refactored to improve connection management and shutdown behavior. A new \WsAuthGuard\ has been introduced to centralize authentication logic for WebSocket clients, attaching the authenticated user payload to the socket object upon successful validation. The \WebsocketConnectionGateway\ now implements the \BeforeApplicationShutdown\ lifecycle hook, ensuring that all active WebSocket clients are gracefully disconnected when the application shuts down, which resolves previous race conditions and double-close issues. Additionally, the module structure has been updated to import from \AuthenticationModule\ instead of the legacy \Auth\ module, and the gateway now explicitly joins users to private rooms based on their user ID upon connection.
src/infrastructure/websocket · high confidence
Fixes
Fix cart creation response to include presentation fields
The cart presentation mapper now correctly maps domain entities to API response DTOs, ensuring that fields such as subtotal, shipping cost, total amount, and item details are included in the response when creating or retrieving a cart. This resolves an issue where these presentation fields were previously missing or incorrect in the API output.
src/modules/carts/core/application/mappers · high confidence
Inventory stock checks now compare quantities numerically to prevent lexicographical errors
The Inventory entity's stock availability checks (such as \isInStock\) now use proper numeric comparison logic via the \Quantity\ value object instead of string coercion. This fixes a regression where multi-digit stock levels (e.g., 79) were incorrectly evaluated against single-digit requests (e.g., 8) due to lexicographical sorting, ensuring that stock availability is accurately reported for all quantity sizes.
src/modules/inventory/core/domain/entities · high confidence
Test coverage
Added OrderBuilder test helper for consistent order fixture creation; Added Redis testing utilities and mocks; Added mock JWT verifier for testing; Added mock implementation for AnalyticsQueryService; Added mock implementations for Orders module testing; Added mock implementations for cart testing infrastructure; Added mock implementations for inventory testing; Added order test factories for DTOs, domain entities, and ORM models; Added test factories and builders for inventory module testing; Added test factories and builders for the cart module; Added test factories for authentication and authorization DTOs; Added test factories for user and address entities; Added test mocks for identity module components; Added test utilities for health check indicators; Added test utilities for the authorization module; Added testing utilities and mocks for authentication module; Added testing utilities for carts and inventory modules; Added testing utilities for the orders module; Added tests for the Confirm Order use case; New Order and OrderItem domain entities with comprehensive unit tests; New architecture and end-to-end test suites; New centralized testing utilities and mock infrastructure.
Dependencies
Initial release of ecommerce-store-api v0.8.0 with NestJS 11 and full dependency set
This change introduces the initial package manifest and lock file for the ecommerce-store-api project at version 0.8.0, establishing the runtime environment on Node.js 24. It installs a comprehensive suite of dependencies including NestJS 11 (core, common, platform-express, websockets, swagger, typeorm, bullmq, schedule, throttler, and terminus), OpenTelemetry for observability, PostgreSQL (pg) and TypeORM for data persistence, Redis (ioredis, socket.io-redis-adapter) for caching and real-time communication, and security libraries like helmet, jose, and bcrypt. The configuration also includes development tooling such as ESLint, Prettier, Jest, and Docker management scripts, providing the foundational structure for the application's modular monolith architecture.
(dependencies) · high confidence
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
Score
- CAI 52 → 57 (+5.7)
- Rubric changed (rubric-2026.08.19 → rubric-2026.09.15) — scores are not directly comparable.
Lenses
- Code Health 87 → 89 (+1.5)
- Architecture 42 → 56 (+13.4)
- Maturity 73 → 80 (+6.5)
- Readiness 43 → 43 (-0.5)
- Security 67 → 93 (+26.4)
Resolved (81)
- Change coupling: login-user.usecase.ts ↔ refresh-token.usecase.ts (src/modules/authentication/core/application/usecases/login-user/login-user.usecase.ts)
- Change coupling: order-entity.factory.ts ↔ order.factory.ts (src/modules/orders/testing/factories/order-entity.factory.ts)
- Change coupling: redis.constants.ts ↔ redis.schemas.ts (src/infrastructure/redis/constants/redis.constants.ts)
- Change coupling: refresh-token.usecase.ts ↔ register-user.usecase.ts (src/modules/authentication/core/application/usecases/refresh-token/refresh-token.usecase.ts)
- Coverage not included — suite not readable by the collector
- Critical CVE: [GHSA redacted] (package-lock.json)
- Critical CVE: [GHSA redacted] (package-lock.json)
- Dependency hygiene not measured — dependency manifest found but not parsed for hygiene
- Further orphaned files (smaller)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- High CVE: [GHSA redacted] (package-lock.json)
- …and 61 more
New (252)
- Boundary-crossing change coupling: cached-inventory-repository.ts ↔ cached.order-repository.ts (src/modules/inventory/secondary-adapters/repositories/cached-inventory-repository/cached-inventory-repository.ts)
- Boundary-crossing change coupling: cached-inventory-repository.ts ↔ cached.product-repository.ts (src/modules/inventory/secondary-adapters/repositories/cached-inventory-repository/cached-inventory-repository.ts)
- Boundary-crossing change coupling: cached-user.repository.ts ↔ cached-inventory-repository.ts (src/modules/identity/secondary-adapters/repositories/cached-user-repository/cached-user.repository.ts)
- Boundary-crossing change coupling: cached-user.repository.ts ↔ cached.product-repository.ts (src/modules/identity/secondary-adapters/repositories/cached-user-repository/cached-user.repository.ts)
- Boundary-crossing change coupling: cached.cart-repository.ts ↔ cached-inventory-repository.ts (src/modules/carts/secondary-adapters/repositories/cached-cart-repository/cached.cart-repository.ts)
- Boundary-crossing change coupling: cached.cart-repository.ts ↔ cached.product-repository.ts (src/modules/carts/secondary-adapters/repositories/cached-cart-repository/cached.cart-repository.ts)
- CachedOrderRepository.listOrders (cognitive 24) (src/modules/orders/secondary-adapters/repositories/cached-order-repository/cached.order-repository.ts)
- CachedOrderRepository.listOrders (cyclomatic 18) (src/modules/orders/secondary-adapters/repositories/cached-order-repository/cached.order-repository.ts)
- CartQueryMapper.toPresentationDto (cognitive 20) (src/modules/carts/secondary-adapters/mappers/query/cart-query.mapper.ts)
- CartQueryMapper.toPresentationDto (cyclomatic 16) (src/modules/carts/secondary-adapters/mappers/query/cart-query.mapper.ts)
- Change coupling: cached.product-repository.ts ↔ postgres.product-repository.ts (src/modules/products/secondary-adapters/repositories/cached-product-repository/cached.product-repository.ts)
- CheckoutFailureListener.onModuleInit (cognitive 21) (src/modules/orders/primary-adapters/listeners/checkout-failure.listener.ts)
- CheckoutFailureListener.onModuleInit (cyclomatic 16) (src/modules/orders/primary-adapters/listeners/checkout-failure.listener.ts)
- Coverage not measured — JavaScript/TypeScript suite
- CreatePaymentUseCase.execute (cognitive 19) (src/modules/payments/core/application/usecases/create-payment/create-payment.usecase.ts)
- Dependency advisory scan runs only on code events
- Documentation: no contributor guidance (docs/README.md)
- Documentation: no licence statement (docs/security/ADMIN-BOOTSTRAP.md)
- Documentation: no usage examples (docs/README.md)
- Floating npm dependency: @nestjs/mapped-types
- …and 232 more
Changes since last survey
- 300 commits — 282 feature/other, 18 fixes
By area
- src/modules — 114 commits
- (repo) — 52 commits
- (root) — 35 commits
- docs/ROADMAP.md — 13 commits
- docs/development — 10 commits
- docs/architecture — 9 commits
- src/testing — 9 commits
- src/infrastructure — 8 commits
- .agents/PROJECT-CONTEXT.md — 5 commits
- docs/FEATURES.md — 5 commits
- test/e2e — 5 commits
- .github/workflows — 3 commits
- docs/README.md — 3 commits
- src/migrations — 3 commits
- docs/data — 2 commits
- docs/infrastructure — 2 commits
- scripts/lib — 2 commits
- src/app.module.ts — 2 commits
- src/filters — 2 commits
- src/guards — 2 commits
Notable commits
- fix: ES-227: fix(deps): override sanitize-html htmlparser2 for Jest CJS compatibility
- fix: ES-228: fix lint
- fix: ES-238: ci(workflow): harden openapi audit services and fix migration script envs
- fix: Fix type comparison for E2E product creation response status
- fix: Merge pull request #192 from raouf-b-dev/ES-184-fix-global-throttler-applying-strict-limit-everywh
- fix: Merge pull request #193 from raouf-b-dev/ES-186-fix-orders-and-payments-openapi-response-contracts
- fix: Merge pull request #199 from raouf-b-dev/ES-195-fix-orders-list-query-adapter-date-amount-filters
- fix: Merge pull request #218 from raouf-b-dev/ES-227-fix-sanitize-html-jest-compatibility
- fix: Merge pull request #237 from raouf-b-dev/fix/cart-order-child-ids-split
- fix: Merge pull request #240 from raouf-b-dev/fix/inventory-stock-and-cart-line-order
- fix: fix lint
- fix: fix lint problems
- fix: fix(carts): keep cart line items in stable add order after updates
- fix: fix(carts): omit unset child ids on cart item persist
- fix: fix(carts): return presentation fields from create cart
- fix: fix(carts): stop auto-creating carts in cached repository
- fix: fix(inventory): compare stock quantities numerically in isInStock
- fix: fix(orders): omit unset child ids on order item persist
- change: Add ADR-0007 for Admin Analytics Query Composition
- change: Add ADR-0008: Money Snapshot and Currency Handling in Cart Domain
- …and 280 more
Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
raouf-b-dev/ecommerce-store-api was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.
About this page
- The score is its most recent published measurement, taken on 21 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit d3b4d6b3ee10ddb50bf2d885cef56932ed3c5dfc — the exact code this score is about.
- Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
- Measured by watchdog.canine.dev using codehealth-analyzer preprod-b84573e22831.