quangdangfit/goshop
53.7
Adequate · 8 November 2026
12.4k
lines of production code
Go
with TypeScript
7
measurements over time
What this system is
Features
Add gRPC API for user authentication and profile management
This change introduces a new gRPC service implementation for the User domain, exposing endpoints for login, registration, retrieving the current user profile (GetMe), refreshing access tokens, and changing passwords. The implementation includes the gRPC server registration logic, request/response handlers that bridge the protobuf definitions to the internal service layer, and data converters that map internal user models to the gRPC UserInfo structure while safely excluding sensitive fields like passwords. Comprehensive unit tests are provided for both the handler logic and the server registration to ensure correct behavior and error handling.
internal/user/port/grpc · high confidence
Add gRPC server with authentication and graceful shutdown
The application now exposes a gRPC server that registers user, product, and order service handlers. Authentication is handled via a configurable interceptor that switches between standard auth and OIDC based on the configuration. The server supports graceful shutdown to ensure clean termination.
internal/server/grpc · high confidence
Added repositories for notification preferences and dead-letter storage
The notification system now supports per-user channel preferences and a dead-letter queue for failed notifications. This change introduces repository implementations that persist user notification settings (allowing users to enable or disable specific event channels) and record exhausted notifications to a dead\_letter\_notifications table for later inspection. Tests verify the correct handling of preference lookups, upserts, and dead-letter recording with error propagation.
internal/notification/repository · high confidence
Configurable authentication modes and OIDC integration
The application now supports switching between legacy JWT authentication and OIDC via Authentik through a new \auth\_mode\ configuration option. This change introduces a centralized configuration schema (\pkg/config\) that loads settings from environment variables and YAML files, covering database, Redis, Stripe, SMTP, and the new Authentik OIDC parameters (issuer, client credentials, JWKS URL). A new \pkg/oidc\ package provides an OIDC validator to handle provider discovery, ID token verification, and OAuth2 authorization code flows. The configuration also defines specific gRPC methods to ignore for authentication checks, allowing unauthenticated access to login and registration endpoints.
pkg/config · high confidence
Coupon support and stock reservation lifecycle in order service
The order service now supports applying coupons during checkout, calculating fixed or percentage discounts while enforcing expiration, usage limits, and minimum order amounts. Placing an order atomically reserves stock and creates stock reservations that hold inventory for 15 minutes until payment clears or a sweeper releases them. When an order is marked paid, reservations are committed and a LowStock event is published if available stock falls to or below 5, enabling admin alerts and frontend badges. The sweeper tolerates orphaned reservations and already-released counters, releasing stock and canceling orders without failing. Cancellation releases active reservations and returns stock. An InsufficientStockError is surfaced on checkout so the frontend can reconcile the cart with a 409 response.
internal/order/service · high confidence
HTTP endpoints for managing user notification preferences
Users can now retrieve and update their notification preferences via new HTTP endpoints. The \GET /me/notification-preferences\ endpoint returns the current preference settings for the authenticated user, while the \PUT /me/notification-preferences\ endpoint allows updating specific preferences (such as enabling or disabling email notifications for certain event types). These endpoints are protected by JWT authentication and are wired up in the application's route configuration.
internal/notification/port · high confidence
HTTP server with graceful shutdown and unified route registration
The HTTP server now supports graceful shutdown via a new Shutdown method, allowing the application to stop accepting new requests and wait for in-flight requests to complete. The server registers routes for user, product, order, payment, and notification APIs under /api/v1, and exposes a /health endpoint for health checks. Swagger documentation is available at /swagger/\*any. The server uses Gin as the HTTP framework and integrates with middleware for CORS and rate limiting.
internal/server/http · high confidence
Initial database seed script for development environments
A new seed script (scripts/seed.sql) has been added to populate the database with initial reference data for local development. This includes six product categories (Electronics, Clothing, Home & Kitchen, Sports & Outdoors, Books, Beauty & Health) and 25 sample products, each associated with placeholder images from picsum.photos. The script also inserts two default user accounts (customer and admin) with pre-hashed passwords for immediate testing access.
scripts · high confidence
Initial gRPC API contracts for User, Product, and Order services
This change introduces the foundational gRPC interface definitions for the application's core domains. It adds Protocol Buffer schemas and the corresponding Go code generation configuration (buf.yaml, buf.gen.yaml) for three services: UserService (handling registration, login, profile retrieval, and password changes), ProductService (managing product creation, updates, and listing), and OrderService (supporting order placement, retrieval, and cancellation). This establishes the contract for inter-service communication and client-server interaction for these features.
proto · high confidence
Initial web client setup with Vite, React, and Tailwind CSS
The web directory now contains a complete frontend application scaffolded with Vite and React, utilizing Tailwind CSS for styling and TypeScript for type safety. This setup includes configuration for client-side routing via an Nginx container (with SPA fallback), API proxying to localhost:8888 during development, and a test environment using Vitest with jsdom. The project structure supports features such as cart management, authentication, product browsing, and checkout, as indicated by the included source files and API clients.
web · high confidence
Introduce Redis client abstraction with JSON serialization and mock support
Added a new \pkg/redis\ package that provides a \Redis\ interface wrapping \go-redis/v9\, enabling services to interact with Redis through a standardized contract. The implementation automatically marshals and unmarshals values to/from JSON, handles connection timeouts, and includes specific methods for incrementing keys with expiration (\Incr\), pattern-based deletion (\RemovePattern\), and connection health checks (\IsConnected\). A generated mock (\pkg/redis/mocks/Redis.go\) and comprehensive unit tests using \miniredis\ are included to facilitate testing of dependent components.
pkg/redis · high confidence
Introduce in-process event bus for domain decoupling
Added a lightweight, in-process publish/subscribe event bus (pkg/eventbus) that allows domains to publish typed events asynchronously without blocking the caller. The bus includes a process-wide singleton (Default/SetDefault) for easy integration and defines specific event types such as OrderCreated, OrderPaid, OrderCancelled, and LowStock, enabling decoupled handling of order lifecycle and inventory notifications.
pkg/eventbus · high confidence
Introduces GoShop API server with graceful shutdown and stock reservation sweeper
The application now starts a unified API server that runs both HTTP and gRPC endpoints concurrently. On startup, it initializes a process-wide event bus that logs low-stock warnings and connects to Redis for caching. A background sweeper runs every 60 seconds to release expired stock reservations and cancel associated unpaid orders. The server handles graceful shutdown, waiting up to 30 seconds for active HTTP requests to complete and ensuring the gRPC server stops cleanly before exiting.
cmd · high confidence
Introduces structured error handling and unified authentication middleware for HTTP and gRPC
This change introduces a new \apperror\ package that standardizes application errors with structured codes, HTTP status mappings, and gRPC code mappings, ensuring consistent error responses across both HTTP and gRPC interfaces. It adds middleware components for JWT and OIDC (Authentik) authentication, providing unified user context injection for both HTTP handlers and gRPC interceptors. Additionally, it includes middleware for admin-only access control, CORS handling, and rate limiting with specific exemptions for webhook endpoints to prevent payment confirmation issues.
pkg/middleware · high confidence
JWT token generation and validation added
The application now includes a dedicated package for handling JSON Web Tokens, providing functions to generate access tokens (valid for 5 hours) and refresh tokens (valid for 30 days) using HS256 signing. It also implements token validation that strips the 'Bearer' prefix, verifies signatures against the configured auth secret, checks expiration, and extracts the payload. Comprehensive tests cover valid tokens, Bearer prefix handling, invalid tokens, non-object payloads, wrong secrets, expired tokens, and signing errors.
pkg/jtoken · high confidence
New database wrapper package with GORM integration
A new \pkg/dbs\ package has been added, providing a \Database\ interface and implementation that wraps GORM with PostgreSQL. This component introduces a unified API for database operations including CRUD actions, batch creation, and transaction management. It supports flexible query construction via functional options for filtering, ordering, pagination, and preloading, and enforces a 5-second timeout on all database contexts. Comprehensive unit tests using \sqlmock\ verify the behavior of these database interactions.
pkg/dbs · high confidence
New email notification channel with retry, dead-letter, and per-user preferences
The notification system now supports sending order-related emails via SMTP. Users can configure SMTP credentials to enable this channel, which is layered alongside the existing logger-based notifier. Delivery respects per-user preferences (allowing users to opt out of specific event types), and failed deliveries are automatically retried with exponential backoff; messages that exhaust retries are sent to a dead-letter queue for later inspection. The implementation includes a new \Notifier\ interface, an \EmailSender\ for SMTP transport, a \PreferenceChecker\ for filtering, and a \RetryingNotifier\ wrapper, all wired together via a factory that builds the appropriate chain based on configuration.
pkg/notification · high confidence
New pagination helper for consistent API response structure
A new \pkg/paging\ package has been added to provide a standardized way to handle pagination logic for API responses. The \New\ function calculates total pages, skip offsets, and current page numbers, enforcing a default page size of 20 and capping custom page sizes at this limit. This ensures consistent pagination metadata (current page, total items, total pages, limit, skip) is returned to users across list endpoints.
pkg/paging · high confidence
New utility functions for object copying, code generation, and password hashing
Added three new utility functions to the \pkg/utils\ package: \Copy\ for deep-copying objects via JSON marshaling, \GenerateCode\ for creating alphanumeric codes with date-based prefixes, and \HashAndSalt\ for securely hashing passwords using bcrypt. Comprehensive table-driven unit tests were added for all three functions to verify their behavior across various input scenarios.
pkg/utils · high confidence
Order service now exposes gRPC and HTTP ports with coupon management and stock conflict handling
The order module now provides a complete set of transport ports: a new gRPC interface (handlers, converters, and server registration) alongside the existing HTTP endpoints. The HTTP API now includes coupon management routes (create and lookup) and returns HTTP 409 Conflict when stock is insufficient during order placement. Both ports enforce authentication, validate inputs, and wire up the order service with reservation, coupon, and notification dependencies.
internal/order/port · high confidence
Payment repository with idempotent webhook event tracking
The payment repository now includes a RecordProviderEvent method that tracks provider events (such as Stripe webhooks) to ensure idempotent processing. If a duplicate event is detected via database unique constraint violations, the repository returns a specific ErrEventAlreadyProcessed error, allowing upstream handlers to safely ignore repeated webhook calls. Tests verify this behavior using sqlmock to simulate both successful inserts and duplicate key errors.
internal/payment/repository · high confidence
Product gRPC service implementation and error handling
The product gRPC port now exposes standard CRUD operations (GetProductByID, ListProducts, CreateProduct, UpdateProduct) via a new ProductHandler. This handler maps incoming gRPC requests to the domain service layer and handles response serialization using utils.Copy. Crucially, the implementation now explicitly checks for errors during this copy process (e.g., when handling NaN values in prices), ensuring that internal data conversion failures are propagated as gRPC errors to the client rather than causing panics or silent data corruption. The service is registered via RegisterHandlers, wiring the repository, service, and handler together.
internal/product/port/grpc · high confidence
Product repository now supports atomic stock decrement and admin restock
The product repository in \internal/product/repository\ has been updated to include two new stock-management capabilities: \DecrementStock\ and \AddStock\. \DecrementStock\ performs an atomic database update that only succeeds if sufficient stock is available (checking \stock\_quantity - reserved\_quantity\), returning an error if stock is insufficient, which supports safe order processing. \AddStock\ atomically increases the stock quantity, supporting the admin restock workflow. The repository interface and its generated mocks have been updated to expose these methods, and unit tests have been added to verify the new behavior.
internal/product/repository · high confidence
Stripe payment integration with webhook handling
The payment port now integrates with Stripe, exposing an authenticated endpoint to create PaymentIntents for orders and a public webhook endpoint to process Stripe callbacks. The webhook handler verifies the Stripe-Signature header to ensure request authenticity before processing. Additionally, a public configuration endpoint exposes the Stripe publishable key and the current authentication mode to the frontend.
internal/payment/port · high confidence
Stripe payment integration with webhook verification
The payment package now includes a transport-neutral interface and a concrete Stripe implementation, allowing the system to create PaymentIntents and verify incoming webhook signatures. The Stripe provider handles intent creation with idempotency keys and automatic payment methods, while webhook verification validates HMAC signatures and rejects stale payloads to prevent replay attacks. Additionally, the payment event types have been expanded to include canceled, processing, and requires\_action states alongside the existing succeeded and failed events.
pkg/payment · high confidence
Behavioural changes
Database-backed notification preferences with opt-in defaults
Users can now have their notification preferences stored in the database, allowing the system to check per-user, per-event, and per-channel settings before sending notifications. The new preference service and checker introduce an opt-in default policy: if a user's preferences are missing, the user lookup fails, or the database is unavailable, notifications are delivered by default to avoid silencing critical alerts. This change adds the backend logic for managing these preferences and the adapter to resolve user IDs by email, but does not include the user-facing UI for configuring them.
internal/notification/service · high confidence
Domain model reorganization and payment reliability improvements
The codebase has been restructured into distinct domain layers (order, product, user, payment, notification), introducing new models such as StockReservation for atomic stock decrement, DeadLetterNotification for failed delivery auditing, and per-user notification preferences. Payment handling now uses Stripe PaymentIntents with idempotent intent creation to ensure the client\_secret is always available on repeat calls, and webhook processing is deduplicated via a ProviderEvent table to guarantee exactly-once semantics. Additionally, the Order model now enforces strict status transition gates, and the OrderLine model was fixed to prevent duplicate line items during order saves.
goshop · high confidence
HTTP handlers for products, categories, and reviews now use domain types and explicit error handling
The HTTP layer for the product module has been refactored to use the new \domain\ package for request/response models instead of the previous \dto\ package, and to handle conversion errors from \utils.Copy\ explicitly. Handlers for products, categories, and reviews now return HTTP 500 errors when model-to-domain copying fails (e.g., due to invalid data like NaN prices), rather than silently failing or panicking. This change ensures that users receive proper error responses for malformed internal data during product, category, and review operations.
internal/product/port/http · high confidence
Headless Authentik authentication via flow executor
The application now supports headless authentication with Authentik by implementing a dedicated HTTP client that interacts with the Authentik flow executor API. This allows the application to handle password-based login (ROPG) and user registration programmatically without relying on browser-based SSO redirects, while still supporting OIDC for federated identity lookups. The change introduces a new client package that manages session cookies and flow stages to verify credentials and provision users server-side.
pkg/authentik · high confidence
Introduce atomic stock reservation lifecycle for order fulfillment
The order repository now supports a three-step inventory management process: ReserveStock atomically increments a reserved\_quantity counter if sufficient stock is available, CommitReservation decrements both stock and reserved counters to finalize a sale, and ReleaseReservation returns reserved units to available stock. This replaces the previous simple DecrementStock approach, allowing orders to hold inventory during the payment window and preventing overselling. The repository also includes new implementations for coupon usage tracking, order listing with newest-first default sorting, and comprehensive unit tests for the new reservation state machine.
internal/order/repository · high confidence
Introduce client-side cart with persistent localStorage storage
The shopping cart is now managed entirely on the client side using a new \cartStore\ backed by \localStorage\ (key \goshop:cart:v1\), removing the previous server-side cart persistence. This change introduces a schema-versioned storage format to handle future shape changes, a stable snapshot mechanism via \useSyncExternalStore\ to prevent infinite React render loops, and cross-tab synchronization using the \storage\ event. The cart now stores a snapshot of product details (name, price, images, stock) at the time of addition for offline display, while the server re-validates price and stock at order time. Existing API endpoints and UI components (CartPage, ProductCard, Navbar) have been updated to interact with this new client-side store.
web/src · high confidence
Introduce typed domain models and explicit converters for the product module
The product module now defines explicit domain types for Categories, Products, and Reviews, along with corresponding request and response structures, replacing the previous generic or implicit data handling. To support this, new typed converter functions have been added to map between internal storage models and these domain types, eliminating the previous reliance on a generic \utils.Copy\ utility that performed JSON round-trip conversions. This change ensures type safety and clearer data boundaries within the product domain layer.
internal/product/domain · high confidence
Product service implements domain-driven design with comprehensive unit tests
The product service has been refactored to follow a domain-driven design (DDD) architecture, moving request objects from a DTO package to a dedicated domain package and introducing typed converters. This change introduces new service interfaces and implementations for managing categories, products, and reviews, including specific capabilities such as atomic stock restocking with admin audit logging and automatic recalculation of product ratings when reviews are created, updated, or deleted. To support this new structure, the update includes generated mocks for service interfaces and extensive table-driven unit tests covering success paths, validation failures, database errors, and permission checks.
internal/product/service · high confidence
Replace automatic schema migration with versioned SQL files
The application no longer automatically applies schema changes on startup via AutoMigrate. Instead, the database schema is now managed through explicit, versioned SQL migration files (using golang-migrate), starting with an initial schema that creates 14 tables including users, products, orders, and payments. Users must now run migrations manually (e.g., via \migrate up\) before or during deployment, rather than relying on the application to handle schema updates automatically.
migrations · high confidence
Standardized HTTP response and error handling
The application now uses a unified response structure for all API interactions, wrapping data in a consistent JSON envelope with 'result' and 'error' fields. Error handling has been centralized to automatically map application errors to appropriate HTTP status codes and user-facing messages, while also supporting environment-aware behavior to hide debug details in production.
pkg/response · high confidence
User HTTP handlers and routes restructured for Domain-Driven Design
The HTTP layer for the user module has been rewritten to align with the new DDD architecture. This introduces dedicated handlers for user authentication (login, register, profile, password change), address management (CRUD and default selection), and wishlist operations (add, remove, list). A new telemetry endpoint allows clients to submit cart snapshots for analytics without affecting order construction. The routing configuration now conditionally initializes an Authentik OIDC client when operating in headless OIDC mode, while maintaining local JWT-based session management for protected routes.
internal/user/port/http · high confidence
User domain models and typed converters introduced
The internal user domain now defines explicit structs for User, Address, and WishlistItem, along with request/response types for authentication and wishlist operations. A new typed converter layer replaces the previous generic copying utility, ensuring that internal fields like passwords are safely excluded from API responses and eliminating unreachable error branches.
internal/user/domain · high confidence
User repository layer refactored to Domain-Driven Design with new address and wishlist persistence
The user repository implementation has been restructured to follow Domain-Driven Design principles, introducing dedicated repositories for user addresses and wishlists alongside the existing user repository. The new AddressRepository provides methods to list, retrieve, create, update, delete, and set default addresses for a user, while the WishlistRepository enables adding, removing, and retrieving wishlist items. The UserRepository remains responsible for basic user creation, updates, and lookups by ID or email. All repository interfaces are now backed by generated mocks to support unit testing, and comprehensive table-driven tests have been added for each repository to verify success and error scenarios.
internal/user/repository · high confidence
User service refactored to support headless Authentik OIDC authentication
The user service now supports two authentication modes: the existing local password-based flow and a new headless OIDC mode powered by Authentik. When configured, login and registration operations delegate credential validation and user provisioning to the Authentik client (via PasswordLogin and CreateUser APIs) instead of using local bcrypt checks, while still issuing internal GoShop JWTs. The service layer has been restructured into distinct Address, User, and Wishlist services with corresponding unit tests and generated mocks, and DTO packages have been renamed to domain.
internal/user/service · high confidence
Fixes
Introduce explicit domain models and converters for orders and coupons
The internal order domain now uses explicit DTO structs (Order, Coupon, OrderLine, Product) and dedicated conversion functions (e.g., OrderFromModel, CouponFromModel) instead of relying on a generic utils.Copy. This removes unreachable error branches from JSON-roundtrip conversions and ensures internal columns like deleted\_at are hidden from API responses. Tests verify correct mapping, including nil handling and nested product data.
internal/order/domain · high confidence
Test coverage
2 commits adding/updating tests in internal/product/model; Added generated mock implementations for database interfaces; Added tests for model BeforeCreate hooks; Added unit tests for order model lifecycle and state transitions; Added unit tests for payment service intent creation and webhook handling; Added unit tests for user model lifecycle hooks; Integration test suite restructured with centralized test infrastructure.
Dependencies
Initial dependency manifests for Go backend and React frontend
The project now includes its first dependency manifests: a Go module file (go.mod) and a web package file (web/package.json) with corresponding lockfiles. The Go backend specifies Go 1.26 and includes libraries for the Gin web framework, GORM with a PostgreSQL driver, Redis caching, gRPC, OIDC authentication, and SQL migrations. The React frontend defines dependencies for React 18, React Router, TanStack Query, and form validation, along with development tools like Vite, TypeScript, and Vitest.
(dependencies) · high confidence
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
Score
- CAI 49 → 54 (+4.4)
- Rubric changed (rubric-2026.10.5 → rubric-2026.11.2) — scores are not directly comparable.
Lenses
- Code Health 84 → 84 (+0.0)
- Architecture 78 → 77 (-1.2)
- Maturity 44 → 69 (+25.0)
- Readiness 42 → 42 (+0.8)
- Security 71 → 68 (-3.2)
- Domain Modelling 82 → 82 (+0.0)
- Event-Driven 78 → 78 (+0.0)
- Accessibility 53 → 53 (-0.5)
- Performance 100 → 100 (+0.0)
Resolved (6)
- Cross-context type Order (order → payment) (internal/payment/service/service.go)
- High CVE: [GHSA redacted] (web/package-lock.json)
- High CVE: [GHSA redacted] (web/package-lock.json)
- High CVE: [GHSA redacted] (web/package-lock.json)
- High CVE: [GHSA redacted] (web/package-lock.json)
- High CVE: [GHSA redacted] (web/package-lock.json)
New (7)
- High CVE: [GHSA redacted] (web/package-lock.json)
- High interface indirection
- Medium CVE: GO-2026-6865 (go.mod)
- Outdated: github.com/testcontainers/testcontainers-go
- Outdated: github.com/testcontainers/testcontainers-go/modules/postgres
- Outdated: google.golang.org/grpc
- Scattered collaborators
Changes since last survey
- 8 commits — 8 feature/other, 0 fixes
By area
- (repo) — 6 commits
- (root) — 1 commit
- web/package-lock.json — 1 commit
Notable commits
- change: Merge pull request #101 from quangdangfit/dependabot/npm_and_yarn/web/axios-1.20.0
- change: Merge pull request #102 from quangdangfit/dependabot/npm_and_yarn/web/source-map-js-1.2.2
- change: Merge pull request #104 from quangdangfit/dependabot/npm_and_yarn/web/vite-8.3.4
- change: Merge pull request #105 from quangdangfit/dependabot/npm_and_yarn/web/follow-redirects-1.16.1
- change: Merge pull request #106 from quangdangfit/dependabot/npm_and_yarn/web/zod-4.6.6
- change: Merge pull request #108 from quangdangfit/dependabot/go_modules/github.com/go-jose/go-jose/v4-4.1.6
- change: chore(deps): bump github.com/go-jose/go-jose/v4 from 4.1.4 to 4.1.6
- change: chore(deps): bump zod from 3.25.76 to 4.6.6 in /web
Architecture
- Unchanged — 0 containers · 1 contexts · 0 edges
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
quangdangfit/goshop 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 8 November 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit e0e20a50dda237337abb1ad8d0934df0ab42e0d1 — the exact code this score is about.
- Scored under rubric-2026.11.2 — the same rubric and the same method as every other entry in this index.
- Measured by Canine Code Analyzer (cca.canine.dev) using cca measure-2026.11.3+preprod-45ab2cab63de.