Parcourir la source

docs: add comprehensive project documentation

unknown il y a 2 mois
Parent
commit
3feb434afa
6 fichiers modifiés avec 321 ajouts et 0 suppressions
  1. 40 0
      docs/README.md
  2. 65 0
      docs/architecture.md
  3. 55 0
      docs/backend.md
  4. 52 0
      docs/deployment.md
  5. 65 0
      docs/development.md
  6. 44 0
      docs/frontend.md

+ 40 - 0
docs/README.md

@@ -0,0 +1,40 @@
+# Radionica 3D Project Documentation
+
+Welcome to the official documentation for the Radionica 3D platform. This document provides a high-level overview of the project, its goals, and the technology stack.
+
+## Overview
+Radionica 3D is a full-stack web application designed for a 3D printing studio based in Montenegro. It allows users to:
+- Upload 3D models (STL, OBJ, etc.).
+- Receive quotes and track order progress.
+- Interact with administrators via a real-time chat.
+- View a portfolio of previous works.
+- Manage reviews and blog posts.
+
+The platform follows a "Trust-based" business model: Pay on delivery, trust in every layer.
+
+## Technology Stack
+The project is built using modern, robust technologies:
+
+### Frontend
+- **Framework**: [Vue 3](https://vuejs.org/) (Composition API)
+- **Build Tool**: [Vite 6](https://vitejs.dev/)
+- **State Management**: [Pinia](https://pinia.vuejs.org/)
+- **Styling**: [Tailwind CSS](https://tailwindcss.com/)
+- **Routing**: [Vue Router](https://router.vuejs.org/)
+- **Localization**: `vue-i18n` with a custom split/merge system.
+- **Animations**: `@vueuse/motion`
+- **3D Rendering**: [Three.js](https://threejs.org/) for STL previews.
+
+### Backend
+- **Framework**: [FastAPI](https://fastapi.tiangolo.com/) (Python 3.11+)
+- **Database**: SQLite (managed via raw SQL and custom migration scripts).
+- **Authentication**: JWT-based (JSON Web Tokens).
+- **Communication**: WebSockets for real-time order chat.
+- **Background Tasks**: Telegram integration for admin notifications.
+
+## Documentation Navigation
+- [Architecture](./architecture.md): Detailed system design and folder structure.
+- [Frontend Guide](./frontend.md): UI components, state, and localization.
+- [Backend Guide](./backend.md): API routes, database schema, and services.
+- [Development Guide](./development.md): How to run locally, add features, and test.
+- [Deployment Guide](./deployment.md): Production setup and build scripts.

+ 65 - 0
docs/architecture.md

@@ -0,0 +1,65 @@
+# Project Architecture
+
+This document describes the high-level architecture and the directory structure of the Radionica 3D project.
+
+## Directory Structure
+
+```text
+radionica3d/
+├── backend/            # FastAPI application
+│   ├── .venv/          # Python virtual environment (ignored)
+│   ├── migrations/     # Current SQL migrations
+│   ├── routers/        # API endpoint definitions (admin, auth, orders, etc.)
+│   ├── services/       # Core business logic (pricing, email, audit, fiscalization)
+│   ├── tests/          # Python unit and integration tests
+│   ├── uploads/        # Local storage for user files (ignored in production, use persistent volume)
+│   ├── main.py         # Entry point for the FastAPI server
+│   ├── database.db     # SQLite database file
+│   └── requirements.txt # Python dependencies
+├── src/                # Vue 3 Frontend
+│   ├── assets/         # Static images and global styles
+│   ├── components/     # Reusable UI components
+│   ├── lib/            # API client (Axios-based) and utility functions
+│   ├── locales/        # Localization JSONs and master fragments
+│   ├── pages/          # Page components (routed)
+│   ├── router/         # Vue Router configuration
+│   ├── stores/         # Pinia state stores (auth, settings)
+│   └── App.vue         # Root component
+├── public/             # Static assets served by Vite directly
+├── scripts/            # Build and utility scripts (localization, sitemap)
+├── legacy/             # Archived migration scripts and old components (unused)
+├── docs/               # This documentation
+├── nginx.conf          # Production Nginx configuration
+├── docker-compose.yml  # Containerization setup
+└── vite.config.ts      # Vite build configuration
+```
+
+## Core Concepts
+
+### 1. Unified Localization (i18n)
+The project uses a "Source of Truth" approach for translations.
+- **Fragments**: Small JSON files in `src/locales/master_user/` and `src/locales/master_admin/`.
+- **Assembly**: The `scripts/manage_locales.py` script merges these fragments into `translations.user.json` and `translations.admin.json`.
+- **Splitting**: The same script then splits the merged files into individual language files (e.g., `en.json`, `ru.json`) which are imported by `src/i18n.ts`.
+
+### 2. Order Workflow
+1. **User Side**: Uploads a file -> Order created as `pending` -> Chat opens.
+2. **Admin Side**: Receives notification (Telegram) -> Reviews file -> Updates status/price -> Chats with user.
+3. **Execution**: Printing -> Delivery via Mail -> Payment.
+
+### 3. Service-Oriented Backend
+The backend logic is decoupled into services:
+- `AuditService`: Tracks all critical actions (order changes, logins) for security.
+- `FiscalService`: Handles digital signing and QR code generation for invoices (Montenegro EFI).
+- `PricingService`: Logic for calculating print costs based on material and weight.
+- `EmailService`: Sends notifications for order status changes and password resets.
+
+## Data Flow
+```mermaid
+graph LR
+    User((User Browser)) <--> Vite[Vite Dev Server / Nginx]
+    Vite <--> FastAPI[FastAPI Backend]
+    FastAPI <--> SQLite[(SQLite Database)]
+    FastAPI <--> Telegram[Telegram Bot]
+    FastAPI <--> Mail[Email Server]
+```

+ 55 - 0
docs/backend.md

@@ -0,0 +1,55 @@
+# Backend Development Guide
+
+The backend is a FastAPI application providing a RESTful API and WebSocket support for the Radionica 3D platform.
+
+## Key Technologies
+- **FastAPI**: High-performance Python framework.
+- **SQLite**: Local database, chosen for simplicity and zero-latency access on small/medium traffic.
+- **Pydantic**: Data validation and serialization.
+- **JWT**: Token-based authentication.
+- **WebSockets**: Real-time communication for the order chat.
+
+## API Structure (`backend/routers/`)
+- `auth.py`: Login, Registration, Password Reset, and Token management.
+- `orders.py`: Order creation, tracking, and management.
+- `admin.py`: High-privileged endpoints for managing users, reviews, and site settings.
+- `files.py`: Handling uploads and serving protected files (STL models, invoice PDFs).
+- `warehouse.py`: Inventory management for materials and filaments.
+
+## Business Logic (`backend/services/`)
+We avoid putting heavy logic in routers. Use services instead:
+- **`AuditService`**: Logs every state change (e.g., when an admin changes an order price).
+- **`FiscalService`**: Implements the Montenegrin Electronic Fiscalization (EFI). Generates JIKR/IKOF codes and signed XMLs.
+- **`PricingService`**: Calculates the quote based on print time, material usage, and fixed costs.
+
+## Database Management
+The project uses raw SQL for schema definitions (`schema.sql`) and migrations.
+- **Initialization**: `init_db.py` (archived in `legacy/`) was used initially.
+- **Migrations**: New changes are added via SQL files in `backend/migrations/` and executed via `run_migrations.py`.
+
+## Authentication
+We use a custom dependency `get_current_user` in `backend/auth_utils.py` to protect routes.
+Example usage:
+```python
+@router.get("/my-orders")
+async def get_orders(current_user: User = Depends(get_current_user)):
+    return await order_service.get_for_user(current_user.id)
+```
+
+## Running the Backend
+1. Ensure the virtual environment is activated:
+   ```bash
+   # Windows
+   backend\.venv\Scripts\activate
+   ```
+2. Install dependencies: `pip install -r backend/requirements.txt`
+3. Run with Uvicorn:
+   ```bash
+   python -m uvicorn main:app --app-dir backend --port 8000 --reload
+   ```
+
+## Adding a New Feature
+1. **Define Schema**: Add a Pydantic model in `backend/schemas.py`.
+2. **Define Logic**: Create a new service or add a method to an existing one in `backend/services/`.
+3. **Define Endpoint**: Create a route in the appropriate router file.
+4. **Register Router**: Ensure the router is included in `backend/main.py`.

+ 52 - 0
docs/deployment.md

@@ -0,0 +1,52 @@
+# Deployment Guide
+
+This document describes how to deploy the Radionica 3D platform to a production server.
+
+## Production Environment
+The recommended production setup uses:
+- **OS**: Linux (Ubuntu 22.04+).
+- **Reverse Proxy**: Nginx.
+- **Process Manager**: Systemd (for the backend).
+- **SSL**: Let's Encrypt (Certbot).
+
+## Build Process
+
+### 1. Build Frontend
+The frontend must be built as a set of static files.
+```bash
+# In project root
+npm run build
+```
+This command:
+1. Generates translations.
+2. Generates the sitemap.
+3. Compiles the Vue app.
+4. Performs SSG (Prerendering) for SEO-sensitive pages.
+5. Outputs to the `dist/` directory.
+
+### 2. Prepare Backend
+Ensure all production dependencies are installed and the environment variables are set in `.env.production`.
+
+## Deployment Scripts
+- `build_frontend.sh`: Automates the frontend build process on the server. It handles atomic deployments by using symlinks (e.g., swapping a `dist` symlink to a new timestamped folder).
+- `server_update.sh`: Pulls the latest code, builds the frontend, and restarts the backend services.
+
+## Systemd Services
+The backend should run as a persistent service. Example configurations are provided in:
+- `radionica-backend.service`: Runs the FastAPI server via Uvicorn.
+- `radionica-deploy.service`: A listener service for automated deployment triggers (if used).
+
+## Nginx Configuration
+The `nginx.conf` file in the root is the source of truth for the web server configuration. Key features:
+- Redirects HTTP to HTTPS.
+- Serves static assets from `dist/public/`.
+- Proxies API requests (`/api/`) and WebSockets (`/ws/`) to the FastAPI backend.
+- Handles history-mode routing for the SPA by falling back to `index.html`.
+
+## Persistence
+- **Database**: Ensure `backend/database.db` is backed up regularly.
+- **Uploads**: The `backend/uploads/` directory must persist between deployments. Use a Docker volume or a dedicated persistent path.
+
+## Monitoring
+- Check `server_debug.log` (if enabled) for backend issues.
+- Monitor Nginx access/error logs for traffic and routing problems.

+ 65 - 0
docs/development.md

@@ -0,0 +1,65 @@
+# Development Workflow
+
+This guide explains how to set up your local environment and perform common development tasks.
+
+## Local Setup
+
+### 1. Prerequisites
+- Node.js (v18+)
+- Python (v3.11+)
+- Git
+
+### 2. Frontend Setup
+```bash
+npm install
+# Generate initial translations
+backend\.venv\Scripts\python.exe scripts\manage_locales.py split
+# Start dev server
+npm run dev
+```
+
+### 3. Backend Setup
+```bash
+cd backend
+python -m venv .venv
+# Activate venv
+.venv\Scripts\activate
+# Install deps
+pip install -r requirements.txt
+# Run server
+python -m uvicorn main:app --port 8000 --reload
+```
+
+## Common Tasks
+
+### Adding a new Translation Key
+The localization system is the heart of the project's multi-language support.
+1. Add the key to the appropriate file in `src/locales/master_user/` or `master_admin/`.
+2. Provide values for all 4 languages.
+3. Run `backend\.venv\Scripts\python.exe scripts\manage_locales.py split`.
+4. Use the key in your Vue component: `{{ t('category.key') }}`.
+
+### Modifying the Database
+1. Create a new SQL file in `backend/migrations/` (e.g., `004_add_user_preferences.sql`).
+2. Run the migration script:
+   ```bash
+   python backend/run_migrations.py
+   ```
+3. Update Pydantic models in `backend/schemas.py`.
+
+### Testing
+- **Backend Tests**: Located in `backend/tests/`. Run with `pytest`.
+  ```bash
+  pytest backend/tests
+  ```
+- **Frontend Tests**: Located alongside components as `*.test.ts`. Run with `npm run test`.
+
+## Code Style and Standards
+- **Frontend**: Use Composition API with `<script setup>`. Follow Tailwind's utility-first approach but keep complex styles in `index.css` if necessary.
+- **Backend**: Use type hints everywhere. Document complex logic in services. Follow the "Router -> Service -> DB" flow.
+
+## Guidelines for Contributions
+- Always work in a feature branch.
+- Ensure `npm run lint` passes before committing.
+- Do not commit large binary files or secrets (`.env` files).
+- Keep the `legacy/` folder clean; move only truly obsolete scripts there.

+ 44 - 0
docs/frontend.md

@@ -0,0 +1,44 @@
+# Frontend Development Guide
+
+The frontend is a Vue 3 Single Page Application (SPA) built with Vite. It features a modern, responsive design with support for multiple languages and 3D visualization.
+
+## Key Technologies
+- **Vue 3**: Using the `<script setup>` syntax and Composition API.
+- **Tailwind CSS**: Utility-first styling. Note that the project uses a custom color palette defined in `tailwind.config.ts`.
+- **Three.js**: Used in `StlViewer.vue` to render 3D models directly in the browser.
+- **Pinia**: Manages user authentication state (`stores/auth.ts`).
+
+## Pages vs Components
+- **Pages** (`src/pages/`): Components mapped to routes. Each page should represent a full view (e.g., `Index.vue`, `Orders.vue`).
+- **Components** (`src/components/`): Reusable UI elements.
+    - `ui/`: Small, primitive components like buttons or inputs.
+    - `admin/`: Specialized components used only in the Admin Dashboard.
+
+## Localization (i18n)
+To add or modify text:
+1. Locate the relevant fragment in `src/locales/master_user/` (for public site) or `master_admin/` (for admin panel).
+2. Edit the JSON file (ensure all supported languages: `en`, `me`, `ru`, `ua` are present).
+3. Run the generation script:
+   ```bash
+   # On Windows:
+   backend\.venv\Scripts\python.exe scripts\manage_locales.py split
+   ```
+4. The changes will be reflected in the generated `src/locales/*.json` files and picked up by Vite.
+
+## 3D Preview (STL)
+The `StlViewer.vue` component handles the rendering of `.stl` files. It supports:
+- Auto-scaling to fit the view.
+- Color customization based on the selected material.
+- Progress indication during large file loads.
+
+## Routing and Auth Guards
+Defined in `src/router/index.ts`.
+- Paths starting with `/:lang/admin` require `admin` role.
+- Paths starting with `/:lang/orders` require the user to be logged in.
+- The router automatically handles language prefixes (redirecting `/about` to `/en/about` based on local storage or defaults).
+
+## Adding a New Page
+1. Create a new `.vue` file in `src/pages/`.
+2. Add the route to `src/router/index.ts`.
+3. Add translations for the page title in `src/locales/master_user/seo.json`.
+4. Run `manage_locales.py split`.