Metadata-Version: 2.4
Name: ecom-foundation-core
Version: 0.1.4
Summary: E-Com Foundation Platform: A modular foundation for building high-performance enterprise microservices, powering systems like the International Regulatory Management System (IRMS).
Project-URL: Homepage, https://github.com/E-com-services-Ltd/platform-core
Project-URL: Documentation, https://github.com/E-com-services-Ltd/platform-core
Project-URL: Repository, https://github.com/E-com-services-Ltd/platform-core
Project-URL: Changelog, https://github.com/E-com-services-Ltd/platform-core/blob/main/CHANGELOG.md
Author-email: e-com services limited <technical@e-comservicesgh.com>
License: Proprietary
License-File: LICENSE
Keywords: enterprise,fastapi,foundation,platform
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.11
Requires-Dist: alembic>=1.13.0
Requires-Dist: celery>=5.3.0
Requires-Dist: email-validator>=2.1.0
Requires-Dist: fastapi>=0.104.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: passlib[bcrypt]>=1.7.4
Requires-Dist: phonenumbers>=8.13.0
Requires-Dist: prometheus-client>=0.19.0
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: pydantic>=2.5.0
Requires-Dist: pyotp>=2.9.0
Requires-Dist: python-jose[cryptography]>=3.3.0
Requires-Dist: python-multipart>=0.0.6
Requires-Dist: redis>=5.0.0
Requires-Dist: sendgrid>=6.11.0
Requires-Dist: sqlalchemy>=2.0.0
Requires-Dist: stripe>=7.0.0
Requires-Dist: structlog>=23.2.0
Requires-Dist: uvicorn[standard]>=0.24.0
Provides-Extra: aws
Requires-Dist: boto3>=1.34.0; extra == 'aws'
Provides-Extra: dev
Requires-Dist: black>=23.11.0; extra == 'dev'
Requires-Dist: faker>=20.0.0; extra == 'dev'
Requires-Dist: mypy>=1.7.0; extra == 'dev'
Requires-Dist: pre-commit>=3.5.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
Requires-Dist: pytest>=7.4.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: mysql
Requires-Dist: aiomysql>=0.2.0; extra == 'mysql'
Requires-Dist: mysqlclient>=2.2.0; extra == 'mysql'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29.0; extra == 'postgres'
Requires-Dist: psycopg2-binary>=2.9.0; extra == 'postgres'
Provides-Extra: sentry
Requires-Dist: sentry-sdk>=1.35.0; extra == 'sentry'
Description-Content-Type: text/markdown

<div align="center">

# ⚡ ecom-foundation-core

**A production-ready enterprise foundation for FastAPI microservices.**
Stop rebuilding boilerplate. Start building your product.

[![PyPI version](https://badge.fury.io/py/ecom-foundation-core.svg)](https://badge.fury.io/py/ecom-foundation-core)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: Proprietary](https://img.shields.io/badge/License-Proprietary-red.svg)](./LICENSE)
[![Built by E-com Services Ltd](https://img.shields.io/badge/Built%20by-E--com%20Services%20Ltd-0A66C2.svg)](https://github.com/E-com-services-Ltd)

</div>

---

## 📖 What is this?

`ecom_foundation_core` is a **modular, async-first Python package** that gives you a fully working enterprise backend foundation from Day 1. It handles all the "undifferentiated heavy lifting" that every serious application needs — Authentication, Role-Based Access Control, Billing, Audit Logging, Notifications, and Background Workflows — so your engineering team can focus on building the features that actually differentiate your product.

**Powering real products** including the Ordvel Marketplace and the International Regulatory Management System (IRMS).

---

## ✨ Feature Overview

| Module               | What it gives you                                                                                |
| -------------------- | ------------------------------------------------------------------------------------------------ |
| 🔑 **Auth**          | JWT login & signup, 2FA (Email/SMS/TOTP), password reset, email verification, session management |
| 🛡️ **RBAC**          | Role assignment, fine-grained permission checks, multi-scope enforcement                         |
| 📜 **Audit**         | Automatic immutable logs on every INSERT, UPDATE & DELETE in your database                       |
| 💳 **Billing**       | Payment provider abstraction (Stripe, Paystack, or your own) with transaction history            |
| 🔔 **Notifications** | Email notification service with template support                                                 |
| ⚙️ **Workflows**     | Celery worker integration for async background tasks                                             |
| 🔧 **Common**        | Shared database engine, Redis client, rate limiting, security headers, and monitoring            |

---

## 🚀 Quick Start

### 1. Install

```bash
pip install ecom-foundation-core

# With PostgreSQL support (recommended)
pip install "ecom-foundation-core[postgres]"
```

### 2. Configure your environment

Create a `.env` file (or set these environment variables directly):

```env
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/mydb
SECRET_KEY=your-super-secret-key-at-least-32-chars
REDIS_URL=redis://localhost:6379/0
SECURITY_HEADERS_ENABLED=False  # Set to True in production
```

### 3. Bootstrap your FastAPI application

This is all the code you need to have a fully working, secure API with Auth, RBAC, Billing, and Audit:

```python
from fastapi import FastAPI
from sqlalchemy.ext.asyncio import create_async_engine
from ecom_foundation_core.bootstrap import create_app, AppConfig

# 1. Configure which modules to enable
config = AppConfig(
    title="My Service",
    version="1.0.0",
    enable_auth=True,        # Mounts /auth endpoints
    enable_rbac=True,        # Mounts /rbac endpoints
    enable_audit=True,       # Enables automatic audit logging
    enable_billing=True,     # Mounts /billing endpoints
    enable_notifications=True,
)

# 2. Connect your database
engine = create_async_engine("postgresql+asyncpg://user:password@localhost/mydb")

# 3. Bootstrap — done!
app = create_app(config=config, db_engine=engine)
```

Your app now has full Swagger docs at `http://localhost:8000/docs` with all modules pre-wired.

---

## 📡 Available Endpoints

Once bootstrapped, the following endpoint groups are available automatically:

### 🔑 Auth (`/auth`)

| Method | Route                          | Description                    |
| ------ | ------------------------------ | ------------------------------ |
| `POST` | `/auth/register`               | Register a new user            |
| `POST` | `/auth/login`                  | Login and receive JWT tokens   |
| `GET`  | `/auth/me`                     | Get current authenticated user |
| `POST` | `/auth/refresh`                | Refresh an access token        |
| `POST` | `/auth/logout`                 | Revoke the current session     |
| `POST` | `/auth/password-reset/request` | Request a password reset email |
| `POST` | `/auth/password-reset/confirm` | Reset password using token     |
| `POST` | `/auth/verify-email`           | Verify email address           |

### 🛡️ RBAC (`/rbac`)

| Method   | Route                                   | Description               |
| -------- | --------------------------------------- | ------------------------- |
| `GET`    | `/rbac/roles`                           | List all available roles  |
| `POST`   | `/rbac/roles`                           | Create a new role         |
| `POST`   | `/rbac/users/{user_id}/roles`           | Assign a role to a user   |
| `DELETE` | `/rbac/users/{user_id}/roles/{role_id}` | Remove a role from a user |

### 📜 Audit (`/audit`)

| Method | Route                     | Description                             |
| ------ | ------------------------- | --------------------------------------- |
| `GET`  | `/audit/logs`             | List all audit log entries              |
| `GET`  | `/audit/logs/{entity_id}` | Get audit history for a specific entity |

---

## 🧬 Extending the Foundation

The foundation is designed to be built upon. Adding your own models is straightforward:

### Adding a Custom Model with Automatic Audit Logging

```python
from sqlalchemy import Column, String, Integer
from ecom_foundation_core.modules.common.database import Base
from ecom_foundation_core.modules.audit.mixins import AuditableMixin

class Product(Base, AuditableMixin):
    """Your model — audit logging is automatic."""
    __tablename__ = "products"

    id = Column(String(36), primary_key=True)
    name = Column(String(255), nullable=False)
    price = Column(Integer, default=0)
```

Any `INSERT`, `UPDATE`, or `DELETE` on this model will **automatically** be captured and stored in the audit log — zero extra code required.

### Using Dependency Injection

```python
from fastapi import Depends, APIRouter
from sqlalchemy.ext.asyncio import AsyncSession
from ecom_foundation_core.modules.common.database import get_async_session
from ecom_foundation_core.modules.rbac.dependencies import require_permission

router = APIRouter()

@router.get("/admin/reports")
async def admin_reports(
    db: AsyncSession = Depends(get_async_session),
    _: None = Depends(require_permission("reports:read")),
):
    # Only users with the 'reports:read' permission can reach this
    ...
```

### Adding a Custom Payment Provider

```python
from typing import Any
from ecom_foundation_core.modules.billing.providers import PaymentProvider

class MyCustomProvider(PaymentProvider):
    async def initialize_transaction(
        self, amount: int, currency: str, user_email: str, **kwargs: Any
    ) -> dict[str, Any]:
        # Call your payment gateway here
        return {"checkout_url": "...", "reference": "..."}

    async def verify_transaction(self, reference: str) -> bool:
        # Verify with your payment gateway
        return True
```

---

## 🐳 Running the Full Example with Docker

The repository includes a complete, runnable test application that demonstrates every feature:

```bash
git clone https://github.com/E-com-services-Ltd/platform-core.git
cd platform-core/examples/core_test_app

# Start PostgreSQL + the test API
docker-compose up --build
```

Then open `http://localhost:8000/docs` to explore all endpoints interactively.

**Default seed credentials:**

- Email: `admin@example.com`
- Password: `admin123`

---

## ⚙️ Configuration Reference

All settings can be set via environment variables or a `.env` file.

| Variable                      | Default                    | Description                                  |
| ----------------------------- | -------------------------- | -------------------------------------------- |
| `DATABASE_URL`                | _Required_                 | Full async database connection string        |
| `SECRET_KEY`                  | _Required_                 | JWT signing secret (min. 32 characters)      |
| `REDIS_URL`                   | `redis://localhost:6379/0` | Redis connection for rate limiting & caching |
| `ACCESS_TOKEN_EXPIRE_MINUTES` | `30`                       | JWT access token lifetime                    |
| `REFRESH_TOKEN_EXPIRE_DAYS`   | `7`                        | JWT refresh token lifetime                   |
| `SECURITY_HEADERS_ENABLED`    | `True`                     | Enable HSTS, CSP, and XSS-protection headers |
| `ALLOWED_ORIGINS`             | `["*"]`                    | CORS allowed origins list                    |
| `SENDGRID_API_KEY`            | `None`                     | SendGrid key for email notifications         |
| `CELERY_BROKER_URL`           | `redis://localhost:6379/0` | Celery message broker                        |

---

## 🧪 Running Tests

```bash
# Run the full test suite inside Docker
docker compose -f docker-compose.test.yml up --build
```

---

## 🗺️ Roadmap

Here is what we are building next:

- [ ] 🤖 **AI Assistant** — A built-in natural language assistant to query audit logs, generate reports, and manage users.
- [ ] 📊 **Analytics Module** — Pre-built dashboards for user activity and billing insights.
- [ ] 🌍 **Multi-tenancy** — First-class support for isolated tenant workspaces.
- [ ] 🔌 **Webhook System** — Built-in outbound webhook delivery for external integrations.
- [ ] 📦 **CLI Tool** — `ecom-core init my-service` to scaffold a new project in seconds.

---

## 📄 License

© E-com Services Limited. All rights reserved.
This software is proprietary. Redistribution or use without explicit written permission is strictly prohibited.

---

<div align="center">
Built with ❤️ by <a href="https://github.com/E-com-services-Ltd">E-com Services Ltd</a>
</div>
