Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions agent/analysis/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Target Architecture: NailStudio Rebuild

This document outlines the proposed software architecture for the new NailStudio application. The goal is to create a system that is robust, maintainable, testable, and directly reflects the core business domain.

## 1. Guiding Principles

* **Separation of Concerns (SoC):** Each component of the application will have a single, well-defined responsibility. Business logic, data access, and request handling will be explicitly separated.
* **Testability:** The architecture must be designed to be easily testable. Core business logic should be testable in isolation (unit tests) without needing a full application context.
* **Clarity & Maintainability:** The structure should be intuitive for new developers. The "shape" of the code should reflect the shape of the business domain.
* **Domain-Centric:** The core of the application will be the business logic (the Domain), not the web framework (Flask).

## 2. Proposed Structure (High-Level)

The application will be structured in layers, ensuring a clean flow of control and dependencies.

```
/nailstudio_app
├── /web # Flask Application (The "Delivery Mechanism")
│ ├── /blueprints # Groupings of related web routes (e.g., transactions, reports)
│ │ ├── /transactions
│ │ │ ├── routes.py
│ │ │ └── templates/
│ │ └── ...
│ ├── __init__.py # Application Factory (create_app)
│ └── ...
├── /core # Core Business Logic (Domain & Services)
│ ├── /services # Business logic implementation
│ │ ├── salary_service.py
│ │ ├── transaction_service.py
│ │ └── ...
│ ├── /models # SQLAlchemy Domain Models (The "What")
│ │ ├── user.py
│ │ ├── transaction.py
│ │ └── ...
│ └── /repositories # Data Access Layer (Optional but Recommended)
│ ├── user_repository.py
│ └── ...
├── /tests
│ ├── /unit # Tests for services in isolation
│ └── /integration # Tests for blueprints and database interactions
└── config.py
```

## 3. Core Components Explained

### A. The Web Layer (`/web`)

* **Responsibility:** Handles all things related to HTTP. This includes parsing incoming requests, validating form data, and returning HTML templates or JSON responses.
* **Implementation:** This is where the Flask application and its Blueprints live.
* **Key Rule:** This layer is **thin**. It contains **no business logic**. It knows *how to handle a web request*, but not *how to run the business*. It calls the Service Layer to perform actions.

### B. The Service Layer (`/core/services`)

* **Responsibility:** This is the heart of the application. It contains all the core business logic and orchestrates the application's workflows.
* **Implementation:** Plain Python classes or modules.
* **Example (`salary_service.py`):**
* The logic for calculating master salaries, previously in the `Transaction` model, will live here.
* It will have functions like `calculate_master_salary_for_period(master, start_date, end_date)`.
* This service will fetch the necessary data via repositories, perform the calculations according to business rules, and return the result.
* **Key Rule:** This layer is completely independent of the web. It has no knowledge of Flask, HTTP, or templates. It can be tested in isolation.

### C. The Data Layer (`/core/models` & `/core/repositories`)

* **Responsibility:** Manages all interactions with the database.
* **Models (`/core/models`):**
* These will be lean representations of the database tables (the Domain).
* They will contain **no business logic**. Properties like `master_salary` will be removed entirely. They are pure data containers.
* **Repositories (`/core/repositories`):** (Recommended)
* This is an abstraction layer that sits between the services and the models.
* It centralizes all database query logic. For example, instead of a service doing `db.session.query(User).filter_by(...).first()`, it would call `user_repository.get_by_id(user_id)`.
* This makes services cleaner and allows for easier testing (you can "mock" a repository).

## 4. Key Systems Design

### Authorization: Pure RBAC

* **The Plan:** The hybrid authorization system will be completely replaced.
* **Implementation:**
1. The `Role` and `Permission` models will be the **single source of truth**.
2. All hardcoded properties (`is_admin`, `is_owner`) and role string checks (`user.role == 'owner'`) will be **deleted** from the `User` model.
3. Access control will be enforced universally using a `user.has_permission('permission_slug')` check.
4. A decorator (e.g., `@permission_required('create_transaction')`) will be used on web routes to protect endpoints. This makes the required permissions explicit and declarative.

This architecture directly addresses the major flaws in the original project, creating a clear separation of concerns that will result in a more robust, testable, and maintainable application.
70 changes: 70 additions & 0 deletions agent/analysis/DOMAIN_MAP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Domain Map: NailStudio

This document outlines the core business concepts (the domain) of the NailStudio application. It focuses on the "what" of the business, abstracting away the specific implementation details.

## 1. Core Entities & Relationships

```mermaid
graph TD
subgraph "People & Access"
User -- "has one" --> Master
User -- "has one" --> Role
Role -- "has many" --> Permission
end

subgraph "Client Visit (Transaction)"
Transaction -- "performed by" --> Master
Transaction -- "paid via" --> PaymentMethod
Transaction -- "attracted by" --> Source
Transaction -- "includes many" --> Service
Transaction -- "sells many" --> TransactionItem
end

subgraph "Products & Inventory"
TransactionItem -- "is an instance of" --> ShelfItem
end

subgraph "Business Expenses"
Expense -- "belongs to" --> ExpenseCategory
end

subgraph "Financial Records"
Transaction -- "contributes to" --> DailyBalance
Expense -- "contributes to" --> DailyBalance
end

User -- "creates" --> Transaction
User -- "logs" --> Expense
```

## 2. Key Business Concepts

### A. People & Access Management

* **User:** An individual with access to the system. This is the entity that logs in.
* **Master:** A service provider (a nail technician). A `Master` is a specific type of `User` with a profile that includes salary and commission settings. This is a critical distinction: not all Users are Masters.
* **Role:** A job function that defines a set of default permissions (e.g., "Owner", "Administrator", "Master").
* **Permission:** A granular right to perform a specific action (e.g., `create_transaction`, `view_financial_reports`, `delete_user`). The system is designed to allow permissions to be assigned to roles, and also overridden for individual users.

### B. Core Business Event: The Transaction

* **Transaction:** This is the central and most important concept in the system. It represents a single, complete interaction with a client, which can include both services and product sales.
* It has a total value (`full_amount`), a value for services (`real_amount`), and a value for products (`shelf_amount`).
* It is always associated with one `Master` who performed the primary service.
* It tracks how the client was acquired (`Source`) and how they paid (`PaymentMethod`), both of which have financial implications (commissions, fees).

### C. Financials & Compensation

* **Salary Calculation:** This is a core business process. A Master's salary is derived from Transactions. The calculation logic is complex and depends on the Master's `salary_mode`:
* **Commission-based:** A percentage of the `real_amount` (services) from their transactions.
* **Fixed-rate:** A fixed daily payment (logic for this is likely in reporting, not the model).
* **Sales Commission:** Masters can also earn a separate commission from selling products (`TransactionItem`). This can be a default rate for the master or a custom rate per item.
* **Source Commission:** The `Source` (e.g., an external marketing partner) can receive a commission based on the service value of the transactions they generate.
* **Payment Fee:** The `PaymentMethod` (e.g., a credit card processor) can have an associated fee, calculated as a percentage of the transaction's total value.
* **Expense:** A record of money spent by the business, categorized for reporting.

### D. Services & Products

* **Service:** A nail service offered by the studio (e.g., "Gel Manicure"). These are the primary revenue drivers.
* **Shelf Item:** A physical product available for sale (e.g., "Cuticle Oil").
* **Transaction Item:** A specific instance of a `ShelfItem` being sold in a `Transaction`. It captures the price at the time of sale.
61 changes: 61 additions & 0 deletions agent/analysis/PROJECT_SCAN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Project Scan: NailStudio

## 1. High-Level Overview

* **Project Name:** NailStudio
* **Description:** A comprehensive web application designed to manage the operations of a nail salon. Core functionalities include managing client appointments (transactions), tracking expenses, calculating master salaries, and generating financial reports.
* **Domain:** Service-based small business management, specifically for a nail salon.

## 2. Technology Stack

* **Backend Framework:** Python / Flask
* **Database:** SQLite
* **ORM:** SQLAlchemy
* **Database Migrations:** Flask-Migrate (Alembic)
* **Authentication:** Flask-Login
* **Forms:** Flask-WTF (inferred from `CSRFProtect`)
* **Frontend:** Jinja2 for server-side templating.
* **Testing:** Pytest
* **Containerization:** Docker (`Dockerfile`, `docker-compose.yml`)
* **Deployment Target:** Render.com (as per README)

## 3. Code Structure

The project follows a modular, Blueprint-based structure.

* `run.py`: Entry point for the development server.
* `config.py`: Application configuration, including database URI and secret keys.
* `app/`: The main application package.
* `__init__.py`: Application factory (`create_app`) where the Flask app is initialized, extensions are registered, and blueprints are mounted.
* `models/`: Contains all SQLAlchemy data models, defining the database schema. A central `__init__.py` re-exports all models.
* **Blueprints:** The application is divided into distinct functional areas using Flask Blueprints:
* `auth/`: User authentication (login/logout).
* `main/`: Core application routes (dashboard, etc.).
* `transactions/`: Managing client visits and sales.
* `expenses/`: Tracking business expenses.
* `reports/`: Generating various reports.
* `admin/`: Administrative functions.
* `api/`: A RESTful API.
* `templates/`: Jinja2 HTML templates.
* `static/`: Static assets (CSS, JS, images).
* `migrations/`: Alembic migration scripts.
* `tests/`: Pytest unit and integration tests.
* `scripts/`: Standalone scripts for tasks like data simulation.

## 4. Key Architectural Components

* **Application Factory:** Uses the `create_app` pattern to allow for different configurations.
* **Blueprints:** Organizes the application into reusable and modular components.
* **ORM:** All database interaction is abstracted through SQLAlchemy models.
* **RBAC (Role-Based Access Control):** A hybrid system is in place.
* **Modern:** `Role` and `Permission` models suggest a flexible, database-driven RBAC system.
* **Legacy:** Hardcoded properties on the `User` model (e.g., `is_admin`, `is_owner`) and direct checks on the `user.role` string indicate a previous, less flexible system. This is a key area of architectural debt.
* **Configuration:** A `Config` class is used to manage settings, with the ability to override from environment variables.

## 5. Initial Observations & Potential Issues

* **Architectural Mix:** The co-existence of a modern RBAC system and legacy role checks points to an incomplete or ongoing refactoring effort. This is a primary source of complexity and potential bugs.
* **Database:** Using SQLite is simple for development but has limitations for production use, as noted in the README regarding Render.com's ephemeral storage.
* **Monolith:** The application is a single monolithic service. While organized with Blueprints, all components are tightly coupled within the same Flask application context.
* **Testing:** The presence of a `tests/` directory is positive, but the actual test coverage is unknown and needs investigation.
* **Business Logic in Models:** The `Transaction.master_salary` property contains significant and complex business logic. While convenient, this can make the model harder to test and maintain.
61 changes: 61 additions & 0 deletions agent/analysis/TRUTH_TABLE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Truth Table: NailStudio

This document analyzes the major concepts extracted from the original project, classifies them according to their business value, and makes a final decision on how to handle them in the rebuild.

---

### 1. User Authentication

* **Concept Name:** User Login & Session Management
* **Where:** `app/auth/`, `app/models/user.py` (password hashing, UserMixin)
* **Why it exists:** To secure the application and ensure that only authorized individuals can access the system.
* **Classification:** `CORE DOMAIN TRUTH`
* **Decision:** **KEEP**. The existing implementation using Flask-Login and standard password hashing is a correct and standard approach. It should be reimplemented cleanly in the new architecture.

---

### 2. Authorization & Permissions

* **Concept Name:** Role-Based Access Control (RBAC)
* **Where:** `app/models/user.py` (Role, Permission models; `is_admin`, `is_owner` properties; `has_permission` method), `README.md` role descriptions.
* **Why it exists:** To enforce business rules about who can perform which actions and see what data. For example, a 'Master' can only see their own salary, while an 'Owner' can see everything.
* **Classification:** `DOMAIN TRUTH, BADLY IMPLEMENTED`
* **Decision:** **REWRITE**.
* **The Truth:** The *need* for different roles with distinct, granular permissions is a core business requirement. The roles listed in the README (Owner, Admin, Master, etc.) are valid domain concepts.
* **The Flaw:** The current implementation is a dangerous hybrid. It mixes a flexible, database-driven RBAC system (`Role`/`Permission` models) with hardcoded, string-based checks in the code (e.g., `if user.role == 'owner'`). This creates two sources of truth and makes the system brittle and difficult to manage.
* **The Plan:** The rebuilt system will use a single, unified, database-driven RBAC system. All hardcoded checks (`is_admin`, `role_slug == 'owner'`) will be removed and replaced with explicit permission checks (e.g., `user.has_permission('view_all_financials')`). The legacy roles will be migrated into the new `Role` table as pre-defined, configurable entities.

---

### 3. Master Salary Calculation

* **Concept Name:** Calculating Master Compensation
* **Where:** `app/models/transaction.py` (in the `master_salary` property), `app/reports/` (inferred handling of fixed-rate salaries).
* **Why it exists:** This is a critical business function to determine payroll. It dictates how much a master earns from their work, including commissions on services and product sales, and accounts for different payment structures (percentage vs. fixed).
* **Classification:** `DOMAIN TRUTH, BADLY IMPLEMENTED` & `ARCHITECTURAL ERROR`
* **Decision:** **REWRITE**.
* **The Truth:** The *rules* for calculating salary (percentage of services, percentage of product sales, different rates per master/item, fixed daily rates) are **absolute core domain truth**.
* **The Flaw:** Placing this complex and critical business logic inside a model property (`@property`) is a major architectural mistake. It violates the Single Responsibility Principle, couples the data model tightly to a business process, and makes the logic nearly impossible to unit test in isolation. The fact that part of the logic (fixed salary) lives elsewhere confirms the design is flawed.
* **The Plan:** The salary calculation logic will be extracted entirely from the model and placed into a dedicated, testable "Salary Service" or "Calculation Module". This module will take transactions, masters, and a date range as input and return the calculated compensation. This decouples the "what" (the transaction data) from the "how" (the calculation process).

---

### 4. Transaction & Visit Management

* **Concept Name:** Recording a Client Visit/Sale
* **Where:** `app/models/transaction.py` (Transaction, TransactionItem models), `app/transactions/` blueprint.
* **Why it exists:** To be the system's primary record of a revenue-generating event. It captures all necessary details for financial reporting, salary calculation, and business analysis.
* **Classification:** `CORE DOMAIN TRUTH`
* **Decision:** **KEEP**. The data model for a `Transaction` is fundamentally sound. It correctly links together the master, services, products sold, payment method, and client source. This structure should be preserved in the new system.

---

### 5. Expense Tracking

* **Concept Name:** Recording Business Expenses
* **Where:** `app/models/finance.py` (Expense model), `app/expenses/` blueprint.
* **Why it exists:** To track operational costs, enabling accurate profit and loss reporting.
* **Classification:** `CORE DOMAIN TRUTH`
* **Decision:** **KEEP**. This is a standard and non-negotiable feature for any business management application. The model is simple and effective.

---