# Lariv Backend

Lariv Backend is a modern, modular web application built on **Django 6.0** and **Python 3.13**. It operates on an **ASGI** foundation to support real-time features via WebSockets alongside standard HTTP requests.

The project differentiates itself from traditional Django applications by avoiding Django templates and heavy frontend frameworks (like React or Vue). Instead, it relies on a **custom Python-based UI Component Framework**. This framework allows developers to write the entire user interface directly in Python, rendering dynamic HTML supercharged with **HTMX**, **Alpine.js**, and **Tailwind CSS**.

## Key Features

- **Fullstack Python:** Write your UI, business logic, and database operations without context-switching between Python and JavaScript. The custom generic components (`Form`, `Table`, `Modal`, `Button`, etc.) automatically handle rendering.
- **Highly Modular Plugin Architecture:** Business domains and features are isolated into distinct "plugins" (e.g., within the `plugins/` directory). This allows for horizontal scaling of features and keeps the core system clean and decoupled.
- **Next-Generation Tech Stack:** Powered by Django 6.0, ASGI (Daphne), HTMX, and Alpine.js. The application feels incredibly fast and responsive, behaving like a Single Page Application (SPA) while retaining the simplicity of server-rendered HTML.
- **Built-in Real-time Capabilities:** Out-of-the-box infrastructure for real-time messaging using WebSockets (`django-channels`) and Redis.
- **AI Delegations:** Complex generative workflows (like automated letter drafting, proposal generation, and AI-assisted content editing) are delegated to internal microservices, keeping the core Python application lightweight and free of heavy AI SDK dependencies like LangChain.
- **Surgical Monkey Patching:** The defining philosophy of the project. It leverages Python's dynamic nature to surgically monkey patch core behavior across models, views, and third-party apps, enabling deep customization without touching upstream code.

## Architecture & Core Modules

- **`/plugins`**: Domain-specific business logic apps (e.g., authentication, course management, specialized workflows). Each plugin is a highly autonomous Django app.
- **`/components`**: The core, reusable Python UI component library used to construct the frontend interfaces.
- **`/lariv`**: Core project settings, URL routing, and foundational Django configurations.
- **`/services`**: Internal microservices, sidecars, or specific backend services used by the plugins (e.g. Go services) to process asynchronous or complex workloads.
- **`/users`**: Core user authentication, role management, and profiling.

## Tech Stack

- **Core:** Python 3.13, Django 6.0, ASGI (Daphne)
- **Database / Cache:** SQLite (local development), PostgreSQL/PostGIS (production target), Redis (Caching, Channels)
- **Frontend / UI:** Custom Python Components, HTMX, Alpine.js, Tailwind CSS
- **AI / LLM:** Delegated to internal microservices (e.g., Go services)

## Getting Started

### Prerequisites
- Python 3.13+
- [uv](https://github.com/astral-sh/uv) package manager

### Creating a New Project

To scaffold a brand new Lariv project quickly, run the initialization script:

```bash
. <(curl -SL https://lariv.in/init_project.sh)
```

### Installation from Source

1. **Clone the repository:**
   ```bash
   git clone <repository-url>
   cd lariv-backend
   ```

2. **Install dependencies:**
   The project uses `uv` for lightning-fast dependency management.
   ```bash
   uv sync
   ```

3. **Set up environment variables:**
   Create a `.env` file in the project root directory and add necessary variables (see `lariv/settings.py` for required keys):
   ```env
   DEBUG=True
   DJANGO_ALLOWED_HOSTS=localhost,127.0.0.1
   # ... add other required DB, Email, and API configurations
   ```

4. **Run Database Migrations:**
   ```bash
   uv run python manage.py migrate
   ```

5. **Start the Development Server:**
   The project uses Tailwind CSS, so you might need to run the Tailwind watcher along with the Django server.
   ```bash
   uv run python manage.py tailwind dev
   ```
   *Note: For full ASGI support (WebSockets), run via daphne or an ASGI runner if not using `runserver`.*


## Examples

### Surgical Monkey Patching
The project embraces monkey patching to extend functionality across independent plugins without altering their source code. For example, the `p_invoicing` plugin dynamically adds fields to the `Order` model defined in the core `p_orders` plugin:

```python
# plugins/p_invoicing/models.py
from django.db import models
from p_orders.models import Order

# Surgically patching the external model to support generated invoices
Order.add_to_class("generated_invoice_text", models.TextField(null=True, blank=True))
Order.add_to_class("invoice_generation_id", models.IntegerField(null=True, blank=True))
Order.add_to_class("billing_notes", models.TextField(null=True, blank=True))
```

### Python-Based UI Components
Instead of HTML templates, the UI is constructed entirely through Python classes registered in the central `UIRegistry`. This enables rich, HTMX-powered interfaces built entirely in Python:

```python
# plugins/p_two_factor/ui.py
from django.urls import reverse_lazy
from lariv.registry import UIRegistry
from components import Form, PhoneInput, SubmitInput, Column, TitleField
from components.base import Component

@UIRegistry.register("two_factor.PhoneMfaRequestForm")
class PhoneMfaRequestForm(Component):
    def build(self):
        return Column(
            uid="phone-mfa-container",
            classes="w-80",
            children=[
                TitleField(static_value="Login via SMS"),
                Form(
                    uid="phone-mfa-form",
                    url=reverse_lazy("two_factor:login_sms"),
                    target="body",
                    method="post",
                    swap="outerHTML",
                    children=[
                        PhoneInput(key="identifier", label="Phone Number", required=True),
                        SubmitInput(label="Send Code", classes="w-full"),
                    ],
                ),
            ],
        )
```


## License

See the [LICENSE](LICENSE) file for details.