Metadata-Version: 2.4
Name: atams
Version: 1.1.0
Summary: Advanced Toolkit for Application Management System - Universal toolkit for AURA projects
Author: ATAMS Team
Author-email: ATAMS Team <dev@atamsindonesia.com>
License: MIT
Project-URL: Homepage, https://github.com/atams/atams-toolkit
Project-URL: Documentation, https://atams-toolkit.readthedocs.io
Project-URL: Repository, https://github.com/atams/atams-toolkit
Project-URL: Issues, https://github.com/atams/atams-toolkit/issues
Keywords: fastapi,toolkit,aura,atams,framework,boilerplate
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: FastAPI
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Code Generators
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.104.0
Requires-Dist: sqlalchemy>=2.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pydantic-settings>=2.0.0
Requires-Dist: pycryptodome>=3.19.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: email-validator>=2.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: rich>=13.0.0
Requires-Dist: jinja2>=3.1.0
Requires-Dist: inflect>=7.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: build>=0.10.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: author
Dynamic: license-file
Dynamic: requires-python

# ATAMS - Advanced Toolkit for Application Management System

![Version](https://img.shields.io/badge/version-1.1.0-blue)
![Python](https://img.shields.io/badge/python-3.9+-green)
![License](https://img.shields.io/badge/license-MIT-blue)

Universal toolkit untuk semua **AURA (Atams Universal Runtime Architecture)** projects.

## Features

- 🚀 **Instant CRUD Generation** - Generate full boilerplate in seconds
- 🏗️ **Clean Architecture** - Enforced separation of concerns  
- 🔒 **Security by Default** - Atlas SSO, encryption, RBAC
- 📦 **Reusable Components** - Database, middleware, logging, etc.
- 🎨 **CLI Tool** - Project initialization & code generation
- 🌐 **CORS Protection** - Default to `*.atamsindonesia.com`

## Installation

```bash
pip install atams
```

## Quick Start

### 1. Initialize New Project

```bash
atams init my-app
cd my-app
cp .env.example .env
# Edit .env with your configuration
pip install -r requirements.txt
uvicorn app.main:app --reload
```

### 2. Generate CRUD

```bash
atams generate department
```

Generates:
- ✅ Model (SQLAlchemy)
- ✅ Schema (Pydantic)
- ✅ Repository (data access)
- ✅ Service (business logic)
- ✅ Endpoint (API routes)
- ✅ Auto-registered to `api.py`

### 3. Customize & Run

Edit generated files to add custom logic, then test:

```bash
# Access API docs
http://localhost:8000/docs

# Test endpoints
GET  /api/v1/departments
GET  /api/v1/departments/{id}
POST /api/v1/departments
PUT  /api/v1/departments/{id}
DELETE /api/v1/departments/{id}
```

## Components

### Core Components

1. **Database Layer** - BaseRepository with ORM & Native SQL
2. **Atlas SSO** - Authentication & authorization
3. **Response Encryption** - AES-256 for GET endpoints
4. **Exception Handling** - Standardized error responses
5. **Middleware** - Request ID tracking, rate limiting
6. **Logging** - Structured logging with JSON format
7. **Transaction Management** - Context managers for complex operations
8. **Common Schemas** - Response & pagination schemas

### Configuration

ATAMS provides `AtamsBaseSettings` with sensible defaults:

```python
from atams import AtamsBaseSettings

class Settings(AtamsBaseSettings):
    APP_NAME: str = "MyApp"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = True
    
    # App-specific encryption
    ENCRYPTION_KEY: str = "your-key-32-chars"
    ENCRYPTION_IV: str = "your-iv-16-char"

settings = Settings()
```

**CORS Default:** Hanya `*.atamsindonesia.com` + localhost (development)

Override via `.env`:

```env
CORS_ORIGINS=["https://myapp.atamsindonesia.com"]
```

## CLI Commands

### `atams init <project_name>`

Initialize new AURA project with complete structure.

**Options:**
- `--app-name, -a` - Application name (default: project_name)
- `--version, -v` - Application version (default: 1.0.0)
- `--schema, -s` - Database schema (default: aura)

**Example:**

```bash
atams init my-new-app
```

### `atams generate <resource>`

Generate full CRUD boilerplate for a resource.

**Options:**
- `--schema, -s` - Database schema (default: aura)
- `--skip-api` - Skip auto-registration to api.py

**Example:**

```bash
atams generate department
atams generate user --schema=public
```

### `atams --version`

Show toolkit version.

## Project Structure

```
my-app/
├── app/
│   ├── core/              # Configuration
│   │   └── config.py
│   ├── db/                # Database
│   ├── models/            # SQLAlchemy models
│   ├── schemas/           # Pydantic schemas
│   ├── repositories/      # Data access layer
│   ├── services/          # Business logic layer
│   └── api/               # API endpoints
│       └── v1/
│           ├── api.py
│           └── endpoints/
├── tests/                 # Test files
├── .env.example           # Environment template
├── requirements.txt       # Dependencies
└── README.md
```

## Usage Examples

### Using BaseRepository

BaseRepository menyediakan 20+ methods untuk operasi database yang lengkap:

#### Basic CRUD Operations
| Method | Description |
|--------|-------------|
| `get(db, id)` | Get single record by ID |
| `get_multi(db, skip, limit)` | Get multiple records with pagination |
| `create(db, obj_in)` | Create new record |
| `update(db, db_obj, obj_in)` | Update existing record |
| `delete(db, id)` | Delete record by ID |

#### Advanced Query Methods
| Method | Description |
|--------|-------------|
| `exists(db, id)` | Fast existence check (returns bool) |
| `filter(db, filters, skip, limit, order_by)` | Dynamic filtering with pagination & ordering |
| `first(db, filters, order_by)` | Get first matching record |
| `count_filtered(db, filters)` | Count records with conditions |
| `get_or_create(db, defaults, **filters)` | Get existing or create new (atomic) |
| `update_or_create(db, filters, defaults)` | Update existing or create (upsert) |

#### Bulk Operations (High Performance)
| Method | Description |
|--------|-------------|
| `bulk_create(db, objects)` | Batch insert (100x faster than loop) |
| `bulk_update(db, objects)` | Batch update multiple records |
| `delete_many(db, ids)` | Batch delete by IDs |
| `partial_update(db, id, data)` | Update without fetching first |

#### Soft Delete Pattern
| Method | Description |
|--------|-------------|
| `soft_delete(db, id, deleted_at_field)` | Logical deletion with timestamp |
| `restore(db, id, deleted_at_field)` | Restore soft-deleted record |

#### Native SQL Execution
| Method | Description |
|--------|-------------|
| `execute_raw_sql(db, query, params)` | Execute raw SQL, returns result |
| `execute_raw_sql_dict(db, query, params)` | Execute SQL, returns list of dicts |
| `execute_raw_sql_commit(db, query, params)` | Execute SQL with auto-commit |

**Example Usage:**

```python
from atams import BaseRepository
from app.models.user import User

class UserRepository(BaseRepository[User]):
    def __init__(self):
        super().__init__(User)

    def example_usage(self, db):
        # Basic CRUD
        user = self.get(db, id=1)
        users = self.get_multi(db, skip=0, limit=10)
        new_user = self.create(db, {"name": "John", "email": "john@example.com"})

        # Advanced queries
        if self.exists(db, id=1):
            print("User exists!")

        active_users = self.filter(db,
            filters={"status": "active"},
            skip=0, limit=50,
            order_by="-created_at"  # descending
        )

        first_admin = self.first(db,
            filters={"role": "admin"},
            order_by="created_at"
        )

        total = self.count_filtered(db, {"status": "active"})

        # Get or create pattern
        user, created = self.get_or_create(db,
            defaults={"status": "pending"},
            email="new@example.com"
        )

        # Bulk operations (very fast!)
        users_data = [
            {"name": "User1", "email": "user1@example.com"},
            {"name": "User2", "email": "user2@example.com"},
        ]
        self.bulk_create(db, users_data)

        # Soft delete
        self.soft_delete(db, id=1, deleted_at_field="deleted_at")
        self.restore(db, id=1, deleted_at_field="deleted_at")

        # Native SQL
        query = "SELECT * FROM users WHERE status = :status"
        active_users = self.execute_raw_sql_dict(db, query, {"status": "active"})
```

### Using Atlas SSO

Configure Atlas SSO in `.env`:
```env
ATLAS_SSO_URL=https://api.atlas-microapi.atamsindonesia.com/api/v1
ATLAS_APP_CODE=your_app_code
ATLAS_ENCRYPTION_KEY=your_encryption_key
ATLAS_ENCRYPTION_IV=your_encryption_iv
```

Then use in endpoints:
```python
from atams.sso import require_auth, require_min_role_level

@router.get("/admin", dependencies=[Depends(require_min_role_level(50))])
async def admin_dashboard(current_user: dict = Depends(require_auth)):
    # Only users with role level >= 50 can access
    return {"user": current_user}
```

### Using Response Encryption

```python
from atams.encryption import encrypt_response_data
from atams.schemas import DataResponse

@router.get("/users/{user_id}")
async def get_user(user_id: int):
    user = get_user_from_db(user_id)
    response = DataResponse(
        success=True,
        message="User retrieved",
        data=user
    )
    # Auto-encrypt if ENCRYPTION_ENABLED=true
    return encrypt_response_data(response)
```

## Development

### Setup

```bash
git clone https://github.com/GratiaManullang03/atams.git
cd atams
pip install -e ".[dev]"
```

### Run Tests

```bash
pytest tests/ -v
pytest tests/ --cov=atams --cov-report=html
```

### Build Package

```bash
python -m build
```

## Versioning

ATAMS follows [Semantic Versioning](https://semver.org/):

- **MAJOR** version for incompatible API changes
- **MINOR** version for new functionality (backwards compatible)
- **PATCH** version for bug fixes

Current version: **1.1.0**

## Contributing

Contributions welcome! Please read CONTRIBUTING.md first.

## License

MIT License - see LICENSE file for details.

## Links

- Documentation: [https://atams-toolkit.readthedocs.io](https://atams-toolkit.readthedocs.io/)
- GitHub: [https://github.com/atams/atams-toolkit](https://github.com/atams/atams-toolkit)
- PyPI: [https://pypi.org/project/atams](https://pypi.org/project/atams)
- Issues: [https://github.com/atams/atams-toolkit/issues](https://github.com/atams/atams-toolkit/issues)

## Support

For support, email [support@atamsindonesia.com](mailto:support@atamsindonesia.com) or open an issue on GitHub.
