Metadata-Version: 2.4
Name: lexigram-admin
Version: 1.0.0a1
Summary: A modern, Python-first admin framework for Lexigram Framework
Author-email: Lexigram Team <team@lexigram.dev>
License: MIT
Project-URL: Homepage, https://github.com/lexigram-dev/lexigram
Project-URL: Documentation, https://github.com/lexigram-dev/lexigram/tree/main/packages/lexigram-admin
Project-URL: Repository, https://github.com/lexigram-dev/lexigram
Project-URL: Issues, https://github.com/lexigram-dev/lexigram/issues
Keywords: admin,dashboard,crud,htmx,starlette,htpy
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: AsyncIO
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: lexigram>=0.1.0
Requires-Dist: lexigram-cache>=0.1.0
Requires-Dist: lexigram-web[templates,web]>=0.1.0
Requires-Dist: lexigram-db[postgres,sqlite]>=0.1.0
Requires-Dist: lexigram-auth[ldap,oauth2,saml]>=0.1.0
Requires-Dist: lexigram-events>=0.1.0
Requires-Dist: lexigram-storage>=0.1.0
Requires-Dist: lexigram-monitor>=0.1.0
Requires-Dist: lexigram-tasks[messaging]>=0.1.0
Requires-Dist: aiofiles>=23.0.0
Requires-Dist: htpy>=0.2.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pysaml2>=7.0.0
Requires-Dist: xmlsec>=1.3.0
Requires-Dist: ldap3>=2.9.0
Provides-Extra: cache
Requires-Dist: lexigram-cache>=0.1.0; extra == "cache"
Provides-Extra: events
Requires-Dist: lexigram-events>=0.1.0; extra == "events"
Provides-Extra: tasks
Requires-Dist: lexigram-tasks>=0.1.0; extra == "tasks"
Provides-Extra: storage
Requires-Dist: lexigram-storage>=0.1.0; extra == "storage"
Provides-Extra: monitor
Requires-Dist: lexigram-monitor>=0.1.0; extra == "monitor"
Provides-Extra: messaging
Requires-Dist: lexigram-messaging>=0.1.0; extra == "messaging"
Provides-Extra: full
Requires-Dist: lexigram-cache>=0.1.0; extra == "full"
Requires-Dist: lexigram-events>=0.1.0; extra == "full"
Requires-Dist: lexigram-tasks>=0.1.0; extra == "full"
Requires-Dist: lexigram-storage>=0.1.0; extra == "full"
Requires-Dist: lexigram-monitor>=0.1.0; extra == "full"
Requires-Dist: lexigram-messaging>=0.1.0; extra == "full"
Provides-Extra: dev
Requires-Dist: lexigram-testing>=0.1.0; extra == "dev"
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Provides-Extra: export
Requires-Dist: openpyxl>=3.0.0; extra == "export"
Requires-Dist: reportlab>=4.0.0; extra == "export"

# Lexigram Admin

Enterprise-grade admin panel framework built on the Lexigram ecosystem.

## Features

- **HTMX-First Architecture**: Server-side rendering with HTMX for interactivity
- **Atomic Design System**: Composable UI components (atoms, molecules, organisms)
- **Full Lexigram Integration**: Leverages cache, events, tasks, storage, messaging
- **Protocol-Based Design**: Type-safe interfaces with `Result[T, E]` error handling
- **Real-time Updates**: SSE and WebSocket support
- **RBAC System**: Fine-grained role-based access control
- **Background Tasks**: Bulk operations, exports, scheduled tasks

## Installation

```bash
# Basic installation
pip install lexigram-admin

# Full installation with all features
pip install lexigram-admin[full]

# Specific features
pip install lexigram-admin[cache,events,tasks,storage,monitor,messaging]
```

## Quick Start

```python
from lexigram.admin import AdminProvider, AdminConfig
from lexigram.admin.resources import Resource

# Configure admin
config = AdminConfig(
    title="My Admin Panel",
    prefix="/admin",
)

# Create provider
admin = AdminProvider(config)

# Register resources
@admin.resource
class UserResource(Resource):
    model = User
    list_display = ["id", "name", "email", "created_at"]
    search_fields = ["name", "email"]
    filters = ["is_active", "role"]
```

## Architecture

### Core Modules

```
lexigram.admin/
├── core/           # Caching, resilience, middleware, locks
├── services/       # Action executor, navigation, notifications, storage
├── realtime/       # SSE and WebSocket handlers
├── monitoring/     # Prometheus metrics, health checks
├── auth/           # Authentication, permissions, guards
├── forms/          # Form builder, validation, async validation
└── ui/             # Atomic design components
```

### Package Integrations

| Package | Features |
|---------|----------|
| `lexigram.cache` | `@cache`, `@remember`, `@invalidate_cache` |
| `lexigram.db` | `@transaction`, `Entity` base classes |
| `lexigram.auth` | `PasswordHasher`, `@RequireAuth`, `@RequireRole` |
| `lexigram.events` | Commands, domain events, event bus |
| `lexigram.tasks` | `@task`, `@scheduled`, bulk operations |
| `lexigram.storage` | `BlobStore`, presigned URLs |
| `lexigram.messaging` | Email notifications, templates |
| `lexigram.monitor` | Prometheus metrics, health checks |
| `lexigram.web` | SSE handlers, WebSocket handlers |

## Core Components

### Caching

```python
from lexigram.admin.core import cache, remember, invalidate_cache

@cache(ttl=300)
async def get_dashboard_stats():
    return await compute_stats()

@remember("permissions:{user_id}", ttl=600)
async def get_user_permissions(user_id: int):
    return await fetch_permissions(user_id)

@invalidate_cache("permissions:{user_id}")
async def update_permissions(user_id: int, perms: list):
    await save_permissions(user_id, perms)
```

### Distributed Locks

```python
from lexigram.admin.core import distributed_lock, ResourceLock

@distributed_lock("bulk-export")
async def export_all_data():
    # Only one instance can run at a time
    ...

async with ResourceLock("users", user_id) as lock:
    await update_user(user_id, data)
```

### Real-time Updates

```python
from lexigram.admin.realtime import AdminEventHub, AdminEventsHandler

# Publish events
hub = AdminEventHub()
await hub.publish("resource.created", {"resource": "users", "id": 123})

# SSE Handler
class MyEventsHandler(AdminEventsHandler):
    async def stream(self, request):
        async for event in self.hub.subscribe(["users"]):
            yield event
```

### WebSocket Support

```python
from lexigram.admin.realtime import AdminWebSocketHandler, ResourceChangeNotifier

class AdminWS(AdminWebSocketHandler):
    async def on_message(self, websocket, message):
        await self.broadcast(message)

# Notify clients of changes
notifier = ResourceChangeNotifier()
await notifier.notify_created("users", user.id, user.to_dict())
```

### Notifications

```python
from lexigram.admin.services import AdminNotificationService, NotificationRecipient

service = AdminNotificationService(messaging_service, config)

# User invite
await service.notify_user_invited(
    user_email="new@example.com",
    user_name="New User",
    invite_url="https://admin.example.com/invite/abc123",
)

# Bulk operation complete
await service.notify_bulk_completed(
    operation_name="User Export",
    resource="users",
    total_items=1000,
    successful=998,
    failed=2,
    duration="2m 34s",
    recipients=admin_list,
)
```

### Storage

```python
from lexigram.admin.services import AdminStorageService, AdminUploadOptions

storage = AdminStorageService(blob_store, config)

# Upload with validation
result = await storage.upload(
    data=file_bytes,
    filename="avatar.jpg",
    options=AdminUploadOptions(
        resource_type="users",
        resource_id=123,
        max_size=5 * 1024 * 1024,
        allowed_types=["image/jpeg", "image/png"],
    ),
)

# Get presigned URL
download_url = await storage.get_download_url(result.file_info.path)
```

### Metrics

```python
from lexigram.admin.monitoring import AdminMetrics, AdminPrometheusMiddleware

metrics = AdminMetrics()

# Track requests automatically
middleware = AdminPrometheusMiddleware(metrics)

# Track custom actions
metrics.track_action("users", "export", success=True, duration=2.5)
metrics.track_bulk_operation("users", "delete", success=True, duration=30.0)
```

## Forms

```python
from lexigram.admin.forms import FormBuilder, AsyncFormValidator

# Build form
form = (
    FormBuilder("user")
    .text("name", required=True)
    .email("email", required=True)
    .select("role", choices=["admin", "user", "guest"])
    .build()
)

# Async validation
validator = AsyncFormValidator()
validator.add_field_validator("email", UniqueValidator(user_repo, "email"))
errors = await validator.validate(form_data)
```

## UI Components

```python
from lexigram.admin.ui import Button, DataTable, Card, Modal

# Atoms
button = Button("Save", variant="primary", hx_post="/save")

# Organisms
table = DataTable(
    columns=[...],
    data=users,
    sortable=True,
    selectable=True,
)
```

## Configuration

```python
from lexigram.admin import AdminConfig

config = AdminConfig(
    title="My Admin",
    prefix="/admin",
    features=AdminFeaturesConfig(
        dark_mode=True,
        export_formats=["csv", "xlsx", "pdf"],
        bulk_operations=True,
        audit_logging=True,
    ),
)
```

## Development

```bash
# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/ -v

# Type checking
mypy src/lexigram/admin --strict

# Linting
ruff check src/
```

## License

MIT License - see LICENSE file for details.
