# io8 System Architect Agent - Customized for This Project

## Project-Specific Instructions


# Architecture Document
Generated: 2025-10-15T12:31:51.000000

## System Overview
The system will evolve the existing Angular Clarity Boilerplate into a full-featured e-commerce application. It comprises a decoupled frontend Single-Page Application (SPA) built with Angular and the Clarity Design System, and a robust backend API service. The application supports both customer-facing functionalities (product browsing, cart, checkout, user profiles) and secure administrator functionalities (product, order, user management, audit logging).

## Architecture Pattern
*   **Frontend:** Single-Page Application (SPA) using Angular, adhering to the established modular architecture (Core, Shared, Feature modules) from the boilerplate. This promotes maintainability, reusability, and clear separation of concerns.
*   **Backend:** A **Layered Monolithic Architecture** will be adopted for the backend service. This pattern provides a clear separation of concerns (Presentation, Application, Domain, Infrastructure layers), facilitates structured development, and allows for scalability while keeping deployment manageable initially. It also provides a solid foundation for future transition to microservices if the application's scale demands it.

## Component Design
### Frontend (Angular - Extending Boilerplate)
*   **AppModule:** Root module, orchestrating main application components and routing.
*   **CoreModule:** (Extended) Provides singleton services (e.g., `AuthService`, `ErrorHandlingService`, `NotificationService`), HTTP interceptors for authentication and error handling, and guard services for route protection (e.g., `AuthGuard`, `AdminGuard`).
*   **SharedModule:** (Extended) Declares and exports reusable UI components (e.g., custom form controls, data display components, loading indicators using Clarity components), pipes, and directives, ensuring consistency across feature modules.
*   **AuthModule (Feature Module):** Handles user registration, login, logout, password reset flows. Interacts with backend authentication APIs.
*   **ProductCatalogModule (Feature Module):** Responsible for browsing products, displaying product details, search functionality, and filtering options. Uses Clarity Datagrid for product listings in Admin UI.
*   **CartModule (Feature Module):** Manages shopping cart state, adding/removing items, updating quantities, and displaying cart contents.
*   **CheckoutModule (Feature Module):** Guides users through the checkout process, including shipping information, payment integration, and order confirmation.
*   **UserProfileModule (Feature Module):** Allows users to view and manage their profile information, shipping addresses, and review past orders.
*   **AdminModule (Lazy-loaded Feature Module):** Dedicated module for administrator functionalities, protected by `AdminGuard`.
    *   `AdminDashboardComponent`: Provides an overview of key e-commerce metrics (e.g., recent orders, product inventory alerts) using Clarity cards/widgets.
    *   `ProductManagementComponent`: Offers a comprehensive interface for CRUD operations on products, categories, and inventory. Utilizes Clarity Datagrid for product listings and forms for detailed editing/creation.
    *   `OrderManagementComponent`: Enables administrators to view, filter, search, and update the status of customer orders. Displays order details using Clarity layouts.
    *   `UserManagementComponent`: A basic interface to view and manage registered user accounts and roles.

### Backend (Layered Monolith)
*   **Presentation Layer (API Endpoints):** RESTful API endpoints (e.g., Django Views/ViewSets with Django REST Framework) for handling HTTP requests, input validation, and serialization/deserialization of data. Responsible for routing requests to the appropriate application services.
*   **Application Layer (Services):** Contains application-specific business logic and orchestrates domain operations. Examples include `ProductService` (managing product CRUD), `OrderService` (processing orders, updating status), `UserService` (user authentication, profile management, role assignment), and `AuditService` (logging administrative actions).
*   **Domain Layer (Models & Business Rules):** Defines the core business entities (`User`, `Product`, `Order`, `Category`, `AuditLog`, `OrderItem`, `ShippingAddress`) and encapsulates domain-specific business rules (e.g., order status transitions, inventory checks, user role validations).
*   **Infrastructure Layer (Persistence & External Services):** Handles interactions with external systems. This includes database access via ORM (Object-Relational Mapper), integration with third-party payment gateways, email services, and logging frameworks.

## Data Architecture
### Primary Database (PostgreSQL - Relational)
*   **Users Table:** Stores user credentials and profile information.
    *   `id` (PK, UUID), `email` (unique), `password_hash`, `first_name`, `last_name`, `role` (enum: 'customer', 'administrator', default 'customer'), `created_at`, `updated_at`.
*   **Products Table:** Stores product details.
    *   `id` (PK, UUID), `name`, `description`, `price`, `stock_quantity`, `category_id` (FK to Categories), `image_url`, `is_active` (boolean), `created_at`, `updated_at`.
*   **Categories Table:** Stores product categories.
    *   `id` (PK, UUID), `name` (unique), `description`.
*   **Orders Table:** Stores customer order information.
    *   `id` (PK, UUID), `user_id` (FK to Users), `order_date`, `total_amount`, `status` (enum: 'pending', 'processing', 'shipped', 'delivered', 'cancelled'), `shipping_address_id` (FK to ShippingAddresses), `payment_status` (enum: 'pending', 'paid', 'refunded'), `created_at`, `updated_at`.
*   **OrderItems Table:** Stores individual items within an order.
    *   `id` (PK, UUID), `order_id` (FK to Orders), `product_id` (FK to Products), `quantity`, `unit_price` (price at time of order).
*   **ShippingAddresses Table:** Stores shipping addresses for users and orders.
    *   `id` (PK, UUID), `user_id` (FK to Users, nullable), `recipient_name`, `address_line1`, `address_line2` (optional), `city`, `state`, `zip_code`, `country`, `is_default` (boolean).
*   **AuditLogs Table:** Records significant administrative actions (per NFR-006, NFR-007).
    *   `id` (PK, UUID), `user_id` (FK to Users, specifically administrators), `action` (string, e.g., 'PRODUCT_UPDATED', 'ORDER_STATUS_CHANGED'), `entity_type` (string, e.g., 'Product', 'Order', 'User'), `entity_id` (UUID, ID of the affected entity), `old_value` (JSON/Text, optional), `new_value` (JSON/Text, optional), `timestamp`.

### Caching
*   A distributed cache (e.g., Redis) will be used to store frequently accessed, less volatile data such as product lists, category data, and potentially user sessions, reducing database load and improving response times.

### Data Flow
*   The Angular frontend communicates with the backend via RESTful API calls over HTTPS.
*   The backend processes these requests, performs business logic, and interacts with the PostgreSQL database for data persistence and retrieval. Cache is consulted before hitting the database for read operations.
*   Payment processing is offloaded to a third-party gateway, with the backend only storing transaction references and status, not sensitive card details (Assumption 1).

## API Design
All APIs will be RESTful, returning JSON payloads, and accessible via HTTPS.

### Authentication & User Management
*   `POST /api/auth/register`: Register a new customer user.
*   `POST /api/auth/login`: Authenticate user, return JWT token.
*   `POST /api/auth/logout`: Invalidate JWT token (if applicable for server-side token management).
*   `GET /api/users/me`: Retrieve current user's profile (authenticated only).
*   `PUT /api/users/me`: Update current user's profile (authenticated only).

### Product Catalog (Public)
*   `GET /api/products`: Retrieve a list of active products (supports pagination, filtering by category, search by name/description).
*   `GET /api/products/{id}`: Retrieve details of a specific product.
*   `GET /api/categories`: Retrieve a list of product categories.

### Shopping Cart
*   `GET /api/cart`: Retrieve the current user's shopping cart contents (authenticated only).
*   `POST /api/cart`: Add a product to the cart (authenticated only).
*   `PUT /api/cart/{item_id}`: Update quantity of an item in the cart (authenticated only).
*   `DELETE /api/cart/{item_id}`: Remove an item from the cart (authenticated only).

### Order Management (Customer)
*   `POST /api/orders`: Create a new order from the current cart (authenticated only, idempotent per NFR-007).
*   `GET /api/orders`: Retrieve a list of current user's orders (authenticated only).
*   `GET /api/orders/{id}`: Retrieve details of a specific order (authenticated only).
*   `PATCH /api/orders/{id}/cancel`: Request to cancel an order (only if status is 'Pending' or 'Processing' per Business Rule 8).

### Admin Interfaces (Protected by Admin Role)
*   **Product Management:**
    *   `GET /api/admin/products`: List all products (supports pagination, filtering, search).
    *   `POST /api/admin/products`: Create a new product.
    *   `GET /api/admin/products/{id}`: Retrieve product details.
    *   `PUT /api/admin/products/{id}`: Update product details.
    *   `DELETE /api/admin/products/{id}`: Delete a product.
*   **Order Management:**
    *   `GET /api/admin/orders`: List all orders (supports pagination, filtering by status, search by customer/order ID).
    *   `GET /api/admin/orders/{id}`: Retrieve detailed order information.
    *   `PATCH /api/admin/orders/{id}/status`: Update order status (e.g., to 'processing', 'shipped', 'delivered', 'cancelled').
*   **User Management:**
    *   `GET /api/admin/users`: List all users.
    *   `GET /api/admin/users/{id}`: Retrieve user details.
    *   `PATCH /api/admin/users/{id}/role`: Update user roles (e.g., promote to admin).
*   **Audit Logging:**
    *   `GET /api/admin/auditlogs`: Retrieve audit trail of administrative actions.

### API Characteristics
*   **Versioning:** Implicitly `/api/v1` for initial development.
*   **Validation:** Robust input validation for all POST/PUT/PATCH requests (per NFR-007).
*   **Error Handling:** Consistent JSON error responses with appropriate HTTP status codes.
*   **Pagination, Filtering, Sorting:** Supported on all list endpoints (e.g., `/api/products`, `/api/admin/orders`) (per Interface Requirements 4).

## Security Architecture
*   **Authentication:** JWT (JSON Web Tokens) will be used for stateless authentication. Upon successful login, the backend issues a JWT, which the frontend stores (e.g., in `localStorage` or `sessionStorage`) and includes in the `Authorization: Bearer <token>` header for all subsequent API requests.
*   **Authorization (RBAC):** Role-Based Access Control will be implemented.
    *   Backend middleware/decorators will verify user roles ('customer', 'administrator') for accessing specific API endpoints. Admin-specific endpoints (`/api/admin/*`) will be strictly protected to ensure only authenticated users with the 'administrator' role can access them (Business Rules - Admin & Operations).
    *   Frontend route guards will prevent unauthorized navigation to admin sections.
*   **Data Protection:**
    *   All communication between frontend and backend will be secured using HTTPS (SSL/TLS).
    *   User passwords will be stored as securely hashed values (e.g., using bcrypt) in the database.
    *   Input validation on both frontend and backend to prevent common vulnerabilities like XSS, SQL injection, and buffer overflows.
*   **Auditability & Logging:** Per NFR-006 and NFR-007, all critical administrative actions (product CRUD, order status changes, user role updates) will be logged to the `AuditLogs` table, including timestamp, administrator ID, and details of the change. System errors and security-sensitive events (failed logins) will also be logged.
*   **Payment Security:** Integration with a PCI DSS compliant third-party payment gateway (e.g., Stripe, PayPal) to offload sensitive credit card information handling and minimize the application's PCI scope (Assumption 1).

## Scalability Considerations
*   **Frontend Scaling:** Angular application bundles will be optimized for production (tree-shaking, minification, AOT compilation). Can be served via CDN for global performance.
*   **Backend Horizontal Scaling:** The backend services will be designed to be stateless, allowing multiple instances to run concurrently behind a load balancer. This enables horizontal scaling to handle increased traffic.
*   **Database Scaling:** Initially, a single PostgreSQL instance. For increased read loads, read replicas can be added. For extreme scale, database sharding or specialized services may be considered.
*   **Caching Layer:** Redis will act as a distributed cache to reduce the load on the database for frequently accessed data (e.g., product catalog, popular items).
*   **Load Balancing:** An Application Load Balancer (ALB) will distribute incoming requests across multiple backend service instances, enhancing availability and performance.
*   **Asynchronous Processing:** For non-critical, time-consuming tasks (e.g., sending order confirmation emails, processing inventory updates), message queues (e.g., RabbitMQ, AWS SQS) can be introduced to decouple services and improve API responsiveness.
*   **Containerization:** Docker will containerize both frontend and backend applications, ensuring consistent environments from development to production and facilitating orchestration with tools like Kubernetes for auto-scaling and high availability.


# Technology Stack Document
Generated: 2025-10-15T12:31:51.000000

## Frontend Technologies
-   **Framework:** Angular (latest stable version, currently v16+), building upon the existing boilerplate.
-   **Styling:** Clarity Design System (integrated as per boilerplate), SCSS for project-specific custom styles and overrides.
-   **State Management:** Angular Services with RxJS for reactive data flow and local state management. NgRx (or similar) is considered a potential future enhancement for complex global state requirements.
-   **HTTP Client:** Angular's `HttpClient` module, enhanced with `HttpInterceptor` for global error handling and authentication token injection.
-   **Form Handling:** Angular Reactive Forms.
-   **Testing:** Karma (test runner), Jasmine (testing framework), Protractor/Cypress (for end-to-end testing).

## Backend Technologies
-   **Language:** Python (latest stable version, e.g., 3.10+). Chosen for its readability, vast ecosystem, and suitability for rapid API development and robust administrative features.
-   **Framework:** Django (latest stable version) for the core web framework, integrated with Django REST Framework (DRF) for building powerful and flexible RESTful APIs. Django's built-in ORM and Admin interface greatly accelerate development, especially for admin features.
-   **API:** RESTful JSON API.
-   **Authentication:** Django REST Framework's JWT (JSON Web Tokens) integration (e.g., `djangorestframework-simplejwt`).
-   **Task Queue (Optional, Future):** Celery with Redis/RabbitMQ as a broker for asynchronous tasks like email notifications or background processing.
-   **Testing:** Pytest with `pytest-django` and `pytest-mock` for unit and integration testing.

## Database Technologies
-   **Primary Database:** PostgreSQL (latest stable version). Selected for its robustness, reliability, ACID compliance, extensive features, and strong support for relational data structures essential for e-commerce (products, orders, users, etc.).
-   **Caching:** Redis (latest stable version). Utilized as a high-performance in-memory data store for caching frequently accessed data (e.g., product catalog, categories) and potentially for session management.

## Infrastructure
-   **Deployment:**
    -   **Containerization:** Docker for containerizing both the Angular frontend (serving static files) and the Django backend applications, ensuring consistent environments.
    -   **Orchestration (Future Consideration):** Kubernetes for managing, scaling, and deploying containerized applications in production for high availability and complex scaling needs.
    -   **Local Environment:** Docker Compose for defining and running multi-container Docker applications locally.
-   **Hosting:** AWS (Amazon Web Services).
    -   **Compute:** Amazon EC2 instances for hosting Docker containers (backend API).
    -   **Database:** Amazon RDS (Relational Database Service) for managed PostgreSQL.
    -   **Static Assets/Media:** Amazon S3 for storing frontend build artifacts, product images, and other static content, potentially fronted by Amazon CloudFront (CDN).
    -   **Load Balancing:** Amazon ALB (Application Load Balancer) to distribute traffic across backend instances.
    -   **Email Service:** Amazon SES (Simple Email Service) for transactional emails (e.g., order confirmations, admin notifications).
-   **CI/CD:** GitHub Actions or GitLab CI/CD pipelines for automated testing, building Docker images, and deploying to AWS environments.

## Development Tools
-   **Version Control:** Git (e.g., hosted on GitHub, GitLab, Bitbucket).
-   **Integrated Development Environment (IDE):** Visual Studio Code, PyCharm (for Python/Django), WebStorm (for Angular/Frontend).
-   **API Testing:** Postman or Insomnia for testing RESTful API endpoints.
-   **Code Quality & Formatting:**
    -   **Frontend:** ESLint, Prettier.
    -   **Backend:** Black (code formatter), Flake8 (linter).
-   **Documentation:** OpenAPI/Swagger for backend API documentation.

## Base Agent Prompt Reference

This agent is based on the standard io8architect agent with project-specific customizations above.
Refer to the base io8architect agent prompt for general principles and workflow instructions.
