Compare commits

..

No commits in common. "main" and "fix/issue-20-password-special-character-validation" have entirely different histories.

97 changed files with 675 additions and 11942 deletions

View File

@ -1,2 +0,0 @@
Branch: main
Commit: 895342a8ba976caa41f4b5b9fdec1c684e47dc5d

View File

@ -1,182 +0,0 @@
name: AcuPedia API CI
on:
push:
branches:
- main
- master
- develop
- 'release/**'
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install project and test dependencies
run: python -m pip install --upgrade pip && python -m pip install -e '.[dev]'
- name: Run test suite
run: python -m pytest
env:
ENVIRONMENT: test
JWT_SECRET: ci-only-test-secret-key-at-least-32-chars
REDIS_CACHE_ENABLED: "false"
coverage:
name: Test coverage
runs-on: ubuntu-latest
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install project and test dependencies
run: python -m pip install --upgrade pip && python -m pip install -e '.[dev]'
- name: Run tests with coverage
run: >-
python -m pytest
--cov=app
--cov-report=term-missing
--cov-report=xml:coverage.xml
--cov-report=html:htmlcov
env:
ENVIRONMENT: test
JWT_SECRET: ci-only-test-secret-key-at-least-32-chars
REDIS_CACHE_ENABLED: "false"
- name: Add coverage summary
if: always()
run: |
if [ -f coverage.xml ]; then
python -c 'import xml.etree.ElementTree as ET; r=ET.parse("coverage.xml").getroot(); rate=float(r.attrib.get("line-rate", 0))*100; print("## Coverage\n\nLine coverage: **{:.2f}%**".format(rate))' >> "$GITHUB_STEP_SUMMARY"
fi
deployment-test:
name: Build, deploy, and smoke test
runs-on: ci-docker
needs:
- tests
- coverage
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install project and runtime dependencies
run: python -m pip install --upgrade pip && python -m pip install -e .
- name: Start isolated PostgreSQL for container deployment
run: |
docker network create acupedia-ci || true
docker rm -f acupedia-postgres-ci >/dev/null 2>&1 || true
docker run -d --name acupedia-postgres-ci --network acupedia-ci \
-p 127.0.0.1:15432:5432 \
-e POSTGRES_DB=acupedia_ci \
-e POSTGRES_USER=acupedia \
-e POSTGRES_PASSWORD=ci-password \
postgres:16
for attempt in $(seq 1 30); do
if docker exec acupedia-postgres-ci pg_isready -U acupedia -d acupedia_ci; then
exit 0
fi
sleep 2
done
docker logs acupedia-postgres-ci
exit 1
- name: Apply database migrations
run: python -m alembic upgrade head
env:
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
- name: Seed auth and commerce
run: |
acupedia-bootstrap auth
acupedia-bootstrap commerce
env:
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
- name: Validate seeded database
run: acupedia-bootstrap validate
env:
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
- name: Build API image
run: docker build --pull -t "$CI_IMAGE" .
env:
CI_IMAGE: acupedia-api:${{ github.sha }}
- name: Deploy API container for acceptance checks
run: |
docker rm -f acupedia-api-ci >/dev/null 2>&1 || true
docker run -d --name acupedia-api-ci --network acupedia-ci -p 127.0.0.1:18000:8000 \
-e DATABASE_URL=postgresql+asyncpg://acupedia:ci-password@acupedia-postgres-ci:5432/acupedia_ci \
-e CACHE_ENABLED=false \
-e ENVIRONMENT=test \
-e JWT_SECRET=ci-only-test-secret-key-at-least-32-chars \
"$CI_IMAGE"
env:
CI_IMAGE: acupedia-api:${{ github.sha }}
- name: Run HTTP smoke tests against deployed container
run: |
if ! python scripts/smoke_deployed_api.py; then
docker logs acupedia-api-ci
exit 1
fi
env:
ACUPEDIA_BASE_URL: http://127.0.0.1:18000
- name: Install isolated AWS CLI
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/'))
run: |
python -m venv .artifact-venv
.artifact-venv/bin/pip install --disable-pip-version-check awscli
- name: Package and publish immutable S3 artifact
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/'))
run: bash scripts/publish_s3_artifact.sh
env:
AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
AWS_DEFAULT_REGION: ${{ secrets.S3_REGION || 'us-east-1' }}
AWS_EC2_METADATA_DISABLED: "true"
S3_ENDPOINT_URL: ${{ secrets.S3_ENDPOINT_URL }}
S3_BUCKET: ${{ secrets.S3_BUCKET }}
CI_IMAGE: acupedia-api:${{ github.sha }}
GITHUB_SHA: ${{ github.sha }}
GITHUB_REPOSITORY: ${{ github.repository }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_RUN_ID: ${{ github.run_id }}
- name: Stop CI containers and network
if: always()
run: |
docker rm -f acupedia-api-ci acupedia-postgres-ci >/dev/null 2>&1 || true
docker network rm acupedia-ci >/dev/null 2>&1 || true

4
.gitignore vendored
View File

@ -28,5 +28,5 @@ htmlcov/
.DS_Store
Thumbs.db
# Generated Git Info
.git_*_info

View File

@ -15,14 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
&& rm -rf /var/lib/apt/lists/*
# Prefer IPv4 over unrouted IPv6 in glibc to prevent PyPI connection timeouts
RUN echo "precedence ::ffff:0:0/96 100" >> /etc/gai.conf
# Use Astral's uv package manager for fast, parallel, cached installations
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
ENV UV_HTTP_TIMEOUT=300
# Copy pyproject.toml first
# Copy pyproject.toml first for layer caching
COPY pyproject.toml ./
COPY README.md ./
@ -30,11 +23,8 @@ COPY README.md ./
COPY docs/accupedia_db_v5.sql /app/schema/accupedia_db_v5.sql
COPY app ./app
# Copy git info metadata if generated on host
COPY .git_api_info* /app/.git_api_info
# Install project and CLI scripts into system PATH using persistent BuildKit cache
RUN --mount=type=cache,target=/root/.cache/uv uv pip install --system -e .
# Install project and CLI scripts into PATH
RUN pip install --no-cache-dir -e .
EXPOSE 8000
@ -42,4 +32,3 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD curl -f http://localhost:8000/ || exit 1
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

347
README.md
View File

@ -1,58 +1,8 @@
# Acupedia API - Backend Services
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
<!-- START_TEST_STATUS -->
[![Tests](https://img.shields.io/badge/tests-12%20passed-brightgreen)](#test-status--coverage) [![Coverage](https://img.shields.io/badge/coverage-75%25-yellow)](#test-status--coverage)
for seeders that use ORM models, we should treat the SQLAlchemy model package as the compile-time contract and audit every seeder field against Base.metadata/mapped attributes before packaging.
| Metric | Status |
| :--- | :--- |
| **Test Suite** | `PASSED` |
| **Tests Passing** | `12` |
| **Tests Failing** | `0` |
| **Core Coverage** | `75%` |
| **Last Updated** | `2026-11-23 08:57:00 UTC` |
<!-- END_TEST_STATUS -->
---
## Features & Services
- **Authentication & Security:** JWT tokens, bcrypt password hashing, password strength validation, OTP flow.
- **Cart & Pricing Engine:** Dynamic currency resolution (INR / USD), multi-unit volume discounts, returning user loyalty discounts, coupon redemption rules, and convenience fee calculations.
- **Content & Curriculum:** Acupoints, channels, topics, clinical modules with preview capabilities.
- **Checkout & Payments:** Razorpay orders, automatic invoice creation, payment status verification.
- **Webhooks:** Cryptographically validated Razorpay webhook listener for real-time payment captures and failures.
- **Administrative Portal:** Role-Based Access Control (`super_admin`, `admin`, `finance_admin`), refund processing, catalog status toggles.
- **Search System:** Faceted multi-scope search with typeahead and category filtering.
---
## Test Suite & Automation
The test suite is powered by `pytest` with asynchronous testing via `httpx.AsyncClient` and mocked dependencies for rapid execution (under 4 seconds) without external live service dependencies.
### Running Tests
```bash
# Run all tests
.venv/bin/pytest
# Run tests with verbose output
.venv/bin/pytest -v
# Run tests with code coverage report
.venv/bin/pytest --cov=app --cov-report=term-missing
```
> **Note:** Running `pytest` automatically updates the test status table and badges above in this `README.md`.
---
<details>
<summary><b>Appendix: Legacy Seed Plans Reference</b></summary>
```json
{
"version": 1,
"plans": [
@ -108,8 +58,282 @@ The test suite is powered by `pytest` with asynchronous testing via `httpx.Async
"country": "India",
"is_active": false,
"sort_order": 40,
"modules": []
},
{
"code": "POINTS_PACK",
"name": "Points Complete Pack (1 Yr)",
"plan_type": "bundle",
"billing_period": "yearly",
"module_fee": "900.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 50,
"modules": [
{ "module_code": "M0004" }
{ "module_code": "M0001" },
{ "module_code": "M0002" },
{ "module_code": "M0003" }
]
},
{
"code": "PATTERN_CORE",
"name": "Pattern Module Access (1 Yr)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "500.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 60,
"modules": [
{ "module_code": "M0011" },
{ "module_code": "M0012" },
{ "module_code": "M0013" },
{ "module_code": "M0014" },
{ "module_code": "M0015" },
{ "module_code": "M0016" },
{ "module_code": "M0017" },
{ "module_code": "M0018" },
{ "module_code": "M0019" },
{ "module_code": "M0020" }
]
},
{
"code": "NUTRITION_CORE",
"name": "Nutrition Module Access (1 Yr)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "600.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 70,
"modules": [
{ "module_code": "M0031" }
]
},
{
"code": "THERAPEUTICS_GYNAE",
"name": "Therapeutics: Gynecology (1 Yr)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "600.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 80,
"modules": [
{ "module_code": "M0042" }
]
},
{
"code": "THERAPEUTICS_EAR",
"name": "Therapeutics: Ear reflexology (1 Yr)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "600.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 90,
"modules": [
{ "module_code": "M0041" }
]
},
{
"code": "THERAPEUTICS_CORE",
"name": "Therapeutics Complete Bundle (1 Yr)",
"plan_type": "bundle",
"billing_period": "yearly",
"module_fee": "1200.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 100,
"modules": [
{ "module_code": "M0041" },
{ "module_code": "M0042" }
]
},
{
"code": "LIFETIME_ALL",
"name": "Lifetime All-Access Plan",
"plan_type": "bundle",
"billing_period": "lifetime",
"module_fee": "15000.00",
"currency_code": "INR",
"country": "India",
"is_active": true,
"sort_order": 110,
"modules": [
{ "module_code": "M0001" },
{ "module_code": "M0002" },
{ "module_code": "M0003" },
{ "module_code": "M0011" },
{ "module_code": "M0012" },
{ "module_code": "M0013" },
{ "module_code": "M0014" },
{ "module_code": "M0015" },
{ "module_code": "M0016" },
{ "module_code": "M0017" },
{ "module_code": "M0018" },
{ "module_code": "M0019" },
{ "module_code": "M0020" },
{ "module_code": "M0031" },
{ "module_code": "M0041" },
{ "module_code": "M0042" }
]
},
{
"code": "POINTS_ACU_USD",
"name": "Acu Points Module (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "5.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 210,
"modules": [
{ "module_code": "M0001" }
]
},
{
"code": "POINTS_SCALP_USD",
"name": "Scalp Points Module (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "2.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 220,
"modules": [
{ "module_code": "M0003" }
]
},
{
"code": "POINTS_EAR_USD",
"name": "Ear Points Module (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "3.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 230,
"modules": [
{ "module_code": "M0002" }
]
},
{
"code": "POINTS_TUNG_USD",
"name": "Tung Points Module (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "5.00",
"currency_code": "USD",
"country": "USA",
"is_active": false,
"sort_order": 240,
"modules": []
},
{
"code": "POINTS_PACK_USD",
"name": "Points Complete Pack (1 Yr - USD)",
"plan_type": "bundle",
"billing_period": "yearly",
"module_fee": "15.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 250,
"modules": [
{ "module_code": "M0001" },
{ "module_code": "M0002" },
{ "module_code": "M0003" }
]
},
{
"code": "PATTERN_CORE_USD",
"name": "Pattern Module Access (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "10.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 260,
"modules": [
{ "module_code": "M0011" },
{ "module_code": "M0012" },
{ "module_code": "M0013" },
{ "module_code": "M0014" },
{ "module_code": "M0015" },
{ "module_code": "M0016" },
{ "module_code": "M0017" },
{ "module_code": "M0018" },
{ "module_code": "M0019" },
{ "module_code": "M0020" }
]
},
{
"code": "NUTRITION_CORE_USD",
"name": "Nutrition Module Access (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "15.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 270,
"modules": [
{ "module_code": "M0031" }
]
},
{
"code": "THERAPEUTICS_GYNAE_USD",
"name": "Therapeutics: Gynecology (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "15.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 280,
"modules": [
{ "module_code": "M0042" }
]
},
{
"code": "THERAPEUTICS_EAR_USD",
"name": "Therapeutics: Ear reflexology (1 Yr - USD)",
"plan_type": "one_time",
"billing_period": "yearly",
"module_fee": "15.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 290,
"modules": [
{ "module_code": "M0041" }
]
},
{
"code": "THERAPEUTICS_CORE_USD",
"name": "Therapeutics Complete Bundle (1 Yr - USD)",
"plan_type": "bundle",
"billing_period": "yearly",
"module_fee": "30.00",
"currency_code": "USD",
"country": "USA",
"is_active": true,
"sort_order": 300,
"modules": [
{ "module_code": "M0041" },
{ "module_code": "M0042" }
]
},
{
@ -125,10 +349,21 @@ The test suite is powered by `pytest` with asynchronous testing via `httpx.Async
"modules": [
{ "module_code": "M0001" },
{ "module_code": "M0002" },
{ "module_code": "M0003" }
{ "module_code": "M0003" },
{ "module_code": "M0011" },
{ "module_code": "M0012" },
{ "module_code": "M0013" },
{ "module_code": "M0014" },
{ "module_code": "M0015" },
{ "module_code": "M0016" },
{ "module_code": "M0017" },
{ "module_code": "M0018" },
{ "module_code": "M0019" },
{ "module_code": "M0020" },
{ "module_code": "M0031" },
{ "module_code": "M0041" },
{ "module_code": "M0042" }
]
}
]
}
```
</details>
}

View File

@ -1,41 +0,0 @@
"""add invoice monthly sequences table
Revision ID: 0003_monthly_invoice_seq
Revises: 0002_add_template_search_flags
Create Date: 2026-10-20
"""
from __future__ import annotations
from collections.abc import Sequence
from alembic import op
import sqlalchemy as sa
revision: str = "0003_monthly_invoice_seq"
down_revision: str | None = "0002_add_template_search_flags"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
COMMERCE_SCHEMA = "commerce"
TABLE_NAME = "invoice_monthly_sequences"
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
tables = inspector.get_table_names(schema=COMMERCE_SCHEMA)
if TABLE_NAME not in tables:
op.create_table(
TABLE_NAME,
sa.Column("year_month", sa.String(length=7), nullable=False),
sa.Column("last_serial", sa.Integer(), nullable=False, server_default="0"),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
sa.PrimaryKeyConstraint("year_month"),
schema=COMMERCE_SCHEMA,
)
def downgrade() -> None:
op.drop_table(TABLE_NAME, schema=COMMERCE_SCHEMA)

View File

@ -1,186 +0,0 @@
"""create module builder tables for clinical content authoring
Revision ID: 0004_module_builder_tables
Revises: 0003_monthly_invoice_seq
Create Date: 2026-11-12
"""
from __future__ import annotations
from collections.abc import Sequence
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = "0004_module_builder_tables"
down_revision: str | None = "0003_monthly_invoice_seq"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
CONTENT_SCHEMA = "content"
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
tables = inspector.get_table_names(schema=CONTENT_SCHEMA)
# 1. Categories
if "builder_categories" not in tables:
op.create_table(
"builder_categories",
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
primary_key=True,
server_default=sa.text("gen_random_uuid()"),
),
sa.Column("module_code", sa.String(length=32), nullable=False),
sa.Column("category_code", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("overview", sa.Text(), nullable=True),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.UniqueConstraint(
"module_code", "category_code", name="uq_builder_categories_code"
),
schema=CONTENT_SCHEMA,
)
op.create_index(
"idx_builder_categories_module",
"builder_categories",
["module_code"],
schema=CONTENT_SCHEMA,
)
# 2. Diseases
if "builder_diseases" not in tables:
op.create_table(
"builder_diseases",
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
primary_key=True,
server_default=sa.text("gen_random_uuid()"),
),
sa.Column("module_code", sa.String(length=32), nullable=False),
sa.Column("category_code", sa.String(length=64), nullable=False),
sa.Column("disease_code", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("overview", sa.Text(), nullable=True),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.UniqueConstraint(
"module_code",
"category_code",
"disease_code",
name="uq_builder_diseases_code",
),
sa.ForeignKeyConstraint(
["module_code", "category_code"],
[
f"{CONTENT_SCHEMA}.builder_categories.module_code",
f"{CONTENT_SCHEMA}.builder_categories.category_code",
],
ondelete="CASCADE",
name="fk_builder_diseases_category",
),
schema=CONTENT_SCHEMA,
)
op.create_index(
"idx_builder_diseases_cat",
"builder_diseases",
["module_code", "category_code"],
schema=CONTENT_SCHEMA,
)
# 3. Patterns
if "builder_patterns" not in tables:
op.create_table(
"builder_patterns",
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
primary_key=True,
server_default=sa.text("gen_random_uuid()"),
),
sa.Column("module_code", sa.String(length=32), nullable=False),
sa.Column("category_code", sa.String(length=64), nullable=False),
sa.Column("disease_code", sa.String(length=64), nullable=False),
sa.Column("pattern_code", sa.String(length=64), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column(
"clinical_data",
postgresql.JSONB(astext_type=sa.Text()),
nullable=False,
server_default=sa.text("'{}'::jsonb"),
),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.UniqueConstraint(
"module_code",
"category_code",
"disease_code",
"pattern_code",
name="uq_builder_patterns_code",
),
sa.ForeignKeyConstraint(
["module_code", "category_code", "disease_code"],
[
f"{CONTENT_SCHEMA}.builder_diseases.module_code",
f"{CONTENT_SCHEMA}.builder_diseases.category_code",
f"{CONTENT_SCHEMA}.builder_diseases.disease_code",
],
ondelete="CASCADE",
name="fk_builder_patterns_disease",
),
schema=CONTENT_SCHEMA,
)
op.create_index(
"idx_builder_patterns_dis",
"builder_patterns",
["module_code", "category_code", "disease_code"],
schema=CONTENT_SCHEMA,
)
def downgrade() -> None:
op.drop_table("builder_patterns", schema=CONTENT_SCHEMA)
op.drop_table("builder_diseases", schema=CONTENT_SCHEMA)
op.drop_table("builder_categories", schema=CONTENT_SCHEMA)

View File

@ -1,183 +0,0 @@
"""create builder_modules table and link builder_categories
Revision ID: 0005_builder_modules_table
Revises: 0004_module_builder_tables
Create Date: 2026-11-13
"""
from __future__ import annotations
from collections.abc import Sequence
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = "0005_builder_modules_table"
down_revision: str | None = "0004_module_builder_tables"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
CONTENT_SCHEMA = "content"
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
tables = inspector.get_table_names(schema=CONTENT_SCHEMA)
if "builder_modules" not in tables:
op.create_table(
"builder_modules",
sa.Column(
"id",
postgresql.UUID(as_uuid=True),
primary_key=True,
server_default=sa.text("gen_random_uuid()"),
),
sa.Column("code", sa.String(length=32), nullable=False, unique=True),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("slug", sa.String(length=255), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("short_description", sa.String(length=500), nullable=True),
sa.Column(
"kind",
sa.String(length=64),
nullable=False,
server_default="therapeutic",
),
sa.Column(
"managed_by",
sa.String(length=64),
nullable=False,
server_default="module_builder",
),
sa.Column("default_template_code", sa.String(length=64), nullable=True),
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
sa.Column("is_active", sa.Boolean(), nullable=False, server_default="true"),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
nullable=False,
server_default=sa.text("now()"),
),
schema=CONTENT_SCHEMA,
)
op.create_index(
"idx_builder_modules_code",
"builder_modules",
["code"],
unique=True,
schema=CONTENT_SCHEMA,
)
# Seed therapeutics modules (m0041, m0042)
bind.execute(
sa.text(
f"""
INSERT INTO {CONTENT_SCHEMA}.builder_modules
(code, name, slug, description, short_description, kind, default_template_code, sort_order, managed_by, is_active)
VALUES
(
'm0041',
'Auriculotherapy',
'auriculotherapy',
'Auriculotherapy protocols and treatment points for musculoskeletal and clinical disorders.',
'Ear reflexology and clinical auriculotherapy protocols.',
'therapeutic',
'm0041_ct0001',
40001,
'module_builder',
TRUE
),
(
'm0042',
'Gynecological Disorders',
'gynecological-disorders',
'TCM therapeutics and pattern differentiation for women''s health and gynecological disorders.',
'TCM gynecology and women''s health therapeutics.',
'therapeutic',
'm0042_ct0001',
42000,
'module_builder',
TRUE
)
ON CONFLICT (code) DO NOTHING
"""
)
)
# Ensure any orphan module_codes in builder_categories have a parent row
bind.execute(
sa.text(
f"""
INSERT INTO {CONTENT_SCHEMA}.builder_modules (code, name, slug, kind, sort_order, managed_by, is_active)
SELECT DISTINCT bc.module_code,
INITCAP(REPLACE(bc.module_code, '_', ' ')),
LOWER(REPLACE(bc.module_code, '_', '-')),
'therapeutic',
40000,
'module_builder',
TRUE
FROM {CONTENT_SCHEMA}.builder_categories bc
WHERE NOT EXISTS (
SELECT 1 FROM {CONTENT_SCHEMA}.builder_modules bm WHERE bm.code = bc.module_code
)
ON CONFLICT (code) DO NOTHING
"""
)
)
# Add foreign key constraint if not present
existing_fks = [
fk["name"]
for fk in inspector.get_foreign_keys(
"builder_categories", schema=CONTENT_SCHEMA
)
]
if "fk_builder_categories_module" not in existing_fks:
op.create_foreign_key(
"fk_builder_categories_module",
"builder_categories",
"builder_modules",
["module_code"],
["code"],
source_schema=CONTENT_SCHEMA,
referent_schema=CONTENT_SCHEMA,
ondelete="CASCADE",
onupdate="CASCADE",
)
# Expand code columns to 256 characters to safely handle long clinical pattern codes
op.alter_column("builder_categories", "category_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
op.alter_column("builder_diseases", "category_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
op.alter_column("builder_diseases", "disease_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
op.alter_column("builder_patterns", "category_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
op.alter_column("builder_patterns", "disease_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
op.alter_column("builder_patterns", "pattern_code", type_=sa.String(256), schema=CONTENT_SCHEMA)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
existing_fks = [
fk["name"]
for fk in inspector.get_foreign_keys(
"builder_categories", schema=CONTENT_SCHEMA
)
]
if "fk_builder_categories_module" in existing_fks:
op.drop_constraint(
"fk_builder_categories_module",
"builder_categories",
schema=CONTENT_SCHEMA,
type_="foreignkey",
)
op.drop_table("builder_modules", schema=CONTENT_SCHEMA)

View File

@ -1,85 +0,0 @@
"""add per_user_limit on coupons and allow multi-use coupon redemptions
Revision ID: 0006_coupon_per_user_limit
Revises: 0005_builder_modules_table
Create Date: 2026-12-01
"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "0006_coupon_per_user_limit"
down_revision: str | None = "0005_builder_modules_table"
branch_labels: Sequence[str] | None = None
depends_on: Sequence[str] | None = None
COMMERCE_SCHEMA = "commerce"
def upgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
coupon_columns = {
col["name"] for col in inspector.get_columns("coupons", schema=COMMERCE_SCHEMA)
}
if "per_user_limit" not in coupon_columns:
op.add_column(
"coupons",
sa.Column("per_user_limit", sa.Integer(), nullable=True),
schema=COMMERCE_SCHEMA,
)
unique_names = {
uc["name"]
for uc in inspector.get_unique_constraints(
"coupon_redemptions", schema=COMMERCE_SCHEMA
)
}
if "uq_coupon_user" in unique_names:
op.drop_constraint(
"uq_coupon_user",
"coupon_redemptions",
schema=COMMERCE_SCHEMA,
type_="unique",
)
index_names = {
idx["name"]
for idx in inspector.get_indexes("coupon_redemptions", schema=COMMERCE_SCHEMA)
}
if "idx_coupon_redemptions_coupon_user" not in index_names:
op.create_index(
"idx_coupon_redemptions_coupon_user",
"coupon_redemptions",
["coupon_id", "user_id"],
unique=False,
schema=COMMERCE_SCHEMA,
)
def downgrade() -> None:
bind = op.get_bind()
inspector = sa.inspect(bind)
index_names = {
idx["name"]
for idx in inspector.get_indexes("coupon_redemptions", schema=COMMERCE_SCHEMA)
}
if "idx_coupon_redemptions_coupon_user" in index_names:
op.drop_index(
"idx_coupon_redemptions_coupon_user",
table_name="coupon_redemptions",
schema=COMMERCE_SCHEMA,
)
coupon_columns = {
col["name"] for col in inspector.get_columns("coupons", schema=COMMERCE_SCHEMA)
}
if "per_user_limit" in coupon_columns:
op.drop_column("coupons", "per_user_limit", schema=COMMERCE_SCHEMA)

View File

@ -2636,12 +2636,6 @@ create table if not exists commerce.invoices (
)
);
create table if not exists commerce.invoice_monthly_sequences (
year_month varchar(7) primary key,
last_serial integer not null default 0,
updated_at timestamptz not null default now()
);
do $$
begin
if not exists (

View File

@ -121,17 +121,8 @@ class ModuleSeeder:
from {self._schema}.content_items ci
join {self._schema}.attribute_definition_sets ads
on ads.id = ci.attribute_definition_set_id
left join {self._schema}.content_attributes ca
on ca.content_id = ci.id
and ca.attribute_definition_id = (
select id
from {self._schema}.attribute_definitions
where attribute_definition_set_id = ads.id
and code = 'sort_order'
limit 1
)
where ads.code = :definition_set_code
order by ca.value_number asc nulls last, ci.sort_title asc, ci.id asc
order by ci.sort_title asc, ci.id asc
"""),
{"definition_set_code": definition_set_code},
)

View File

@ -300,16 +300,6 @@ class SeedOrchestrator:
# seeded by this invocation are candidates for module
# association. Never rewrite unrelated template rows.
content_ids = [result.content_id for result in batch.results]
elif batch.results:
# Preserve authored sequence from the source document.
content_ids = [result.content_id for result in batch.results]
known_ids = set(content_ids)
all_ids = await self._modules.resolve_content_ids_for_definition_set(
definition_set_code=mapping.code
)
for remaining_id in all_ids:
if remaining_id not in known_ids:
content_ids.append(remaining_id)
else:
content_ids = await self._modules.resolve_content_ids_for_definition_set(
definition_set_code=mapping.code

View File

@ -76,19 +76,3 @@ acupedia-ops access revoke-plan \
`--user-id <uuid>` can be used instead of `--email`.
The grant operation is idempotent for an already-active subscription and active module entitlements. It never invents plan/module mappings; the selected plan must already have rows in `commerce.access_plan_modules`.
Delete an unwanted access plan (dry-run by default; blocks if active subscribers exist):
```bash
# Dry-run
acupedia-access delete-plan --plan-code TEST_PLAN
# Execute deletion
acupedia-access delete-plan --plan-code TEST_PLAN --execute
# Deactivate instead if active subscribers exist
acupedia-access delete-plan --plan-code TEST_PLAN --execute --deactivate
# Detach expired/cancelled historical subscriptions before deleting
acupedia-access delete-plan --plan-code TEST_PLAN --execute --detach-history
```

View File

@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone
import os
from uuid import UUID
from sqlalchemy import func, or_, select, update
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.db.enums import EntitlementStatus, SubscriptionStatus
@ -41,16 +41,6 @@ class RevokeSummary:
entitlements_revoked: int
@dataclass(frozen=True)
class DeletePlanSummary:
plan_id: UUID
plan_code: str
action: str
active_subscribers: int
historical_subscriptions: int
modules_mapped: int
def utcnow() -> datetime:
return datetime.now(timezone.utc)
@ -97,27 +87,6 @@ def build_parser() -> argparse.ArgumentParser:
help="Reason stored on revoked entitlements/subscriptions.",
)
delete = subparsers.add_parser(
"delete-plan",
help="Safely delete an unwanted access plan (dry-run by default; blocks if active subscribers exist).",
)
delete.add_argument("--plan-code", required=True, help="Canonical plan code to delete.")
delete.add_argument(
"--execute",
action="store_true",
help="Perform deletion/deactivation. Without this flag, runs in dry-run mode.",
)
delete.add_argument(
"--detach-history",
action="store_true",
help="Detach inactive/expired historical UserSubscription rows (plan_id=NULL) before deleting.",
)
delete.add_argument(
"--deactivate",
action="store_true",
help="Deactivate (is_active=False) the plan instead of failing when active subscribers exist.",
)
return parser
@ -360,108 +329,6 @@ async def revoke_plan(
)
async def delete_plan(
session: AsyncSession,
*,
plan_code: str,
execute: bool = False,
detach_history: bool = False,
deactivate: bool = False,
) -> DeletePlanSummary:
"""Safely delete or deactivate an access plan via developer CLI."""
now = utcnow()
plan = (
await session.execute(select(AccessPlan).where(AccessPlan.code == plan_code.strip()))
).scalar_one_or_none()
if plan is None:
raise ValueError(f"Plan not found: {plan_code}")
active_subscribers = int(
(
await session.execute(
select(func.count(UserSubscription.id)).where(
UserSubscription.plan_id == plan.id,
UserSubscription.status == SubscriptionStatus.ACTIVE,
or_(
UserSubscription.expires_at.is_(None),
UserSubscription.expires_at > now,
),
)
)
).scalar_one()
)
total_subscriptions = int(
(
await session.execute(
select(func.count(UserSubscription.id)).where(
UserSubscription.plan_id == plan.id
)
)
).scalar_one()
)
historical_subscriptions = max(0, total_subscriptions - active_subscribers)
modules_mapped = int(
(
await session.execute(
select(func.count(AccessPlanModule.module_id)).where(
AccessPlanModule.plan_id == plan.id
)
)
).scalar_one()
)
if not execute:
return DeletePlanSummary(
plan_id=plan.id,
plan_code=plan.code,
action="dry-run",
active_subscribers=active_subscribers,
historical_subscriptions=historical_subscriptions,
modules_mapped=modules_mapped,
)
if active_subscribers > 0:
if deactivate:
plan.is_active = False
plan.updated_at = now
await session.commit()
return DeletePlanSummary(
plan_id=plan.id,
plan_code=plan.code,
action="deactivated",
active_subscribers=active_subscribers,
historical_subscriptions=historical_subscriptions,
modules_mapped=modules_mapped,
)
raise ValueError(
"Cannot delete plan with active subscribers. Please deactivate instead."
)
if historical_subscriptions > 0:
if not detach_history:
raise ValueError(
f"Plan '{plan.code}' has {historical_subscriptions} historical (inactive/expired) "
"subscription(s). Pass --detach-history to set their plan_id=NULL before deleting."
)
await session.execute(
update(UserSubscription)
.where(UserSubscription.plan_id == plan.id)
.values(plan_id=None, updated_at=now)
)
await session.delete(plan)
await session.commit()
return DeletePlanSummary(
plan_id=plan.id,
plan_code=plan.code,
action="deleted",
active_subscribers=active_subscribers,
historical_subscriptions=historical_subscriptions,
modules_mapped=modules_mapped,
)
async def run(args: argparse.Namespace) -> int:
if not args.database_url:
raise ValueError("DATABASE_URL is required")
@ -499,23 +366,6 @@ async def run(args: argparse.Namespace) -> int:
)
return 0
if args.command == "delete-plan":
summary = await delete_plan(
session,
plan_code=args.plan_code,
execute=args.execute,
detach_history=args.detach_history,
deactivate=args.deactivate,
)
print(
f"{summary.action.upper()} "
f"plan={summary.plan_code} plan_id={summary.plan_id} "
f"active_subscribers={summary.active_subscribers} "
f"historical_subscriptions={summary.historical_subscriptions} "
f"modules_mapped={summary.modules_mapped}"
)
return 0
summary = await revoke_plan(
session,
email=args.email,

View File

@ -20,7 +20,6 @@ class Settings(BaseSettings):
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
debug: bool = False
content_preview_enabled: bool = False
enable_module_repo_sync: bool = False
api_prefix: str = "/api/v1"
cors_origins: str = "http://localhost:3000,http://localhost:8000"

View File

@ -30,10 +30,6 @@ from .content import (
SearchFacetMapping,
ContentSearchDocument,
ContentSearchFacet,
BuilderModule,
BuilderCategory,
BuilderDisease,
BuilderPattern,
)
from .commerce import (
@ -45,7 +41,6 @@ from .commerce import (
Coupon,
PaymentTransaction,
Invoice,
InvoiceMonthlySequence,
CouponRedemption,
RefundDecision,
)
@ -92,10 +87,6 @@ __all__ = [
"SearchFacetMapping",
"ContentSearchDocument",
"ContentSearchFacet",
"BuilderModule",
"BuilderCategory",
"BuilderDisease",
"BuilderPattern",
"UserBillingProfile",
"AccessPlan",
"AccessPlanModule",
@ -104,7 +95,6 @@ __all__ = [
"Coupon",
"PaymentTransaction",
"Invoice",
"InvoiceMonthlySequence",
"CouponRedemption",
"RefundDecision",
"UserActivityLog",

View File

@ -216,7 +216,6 @@ class Coupon(Base):
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
end_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
usage_limit: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
per_user_limit: Mapped[int | None] = mapped_column(Integer, nullable=True)
usage_count: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
applicable_plan_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
applicable_module_ids: Mapped[list[UUID] | None] = mapped_column(ARRAY(PGUUID(as_uuid=True)))
@ -224,7 +223,6 @@ class Coupon(Base):
is_first_purchase_only: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
description: Mapped[str | None] = mapped_column(Text)
metadata_json: Mapped[dict | None] = mapped_column(JSONB, server_default=text("'{}'::jsonb"))
created_by: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{AUTH_SCHEMA}.app_users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
@ -281,21 +279,9 @@ class Invoice(Base):
applied_coupon: Mapped[Coupon | None] = relationship()
class InvoiceMonthlySequence(Base):
__tablename__ = "invoice_monthly_sequences"
__table_args__ = {"schema": COMMERCE_SCHEMA}
year_month: Mapped[str] = mapped_column(String(7), primary_key=True)
last_serial: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text("0"))
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
class CouponRedemption(Base):
__tablename__ = "coupon_redemptions"
__table_args__ = (
Index("idx_coupon_redemptions_coupon_user", "coupon_id", "user_id"),
{"schema": COMMERCE_SCHEMA},
)
__table_args__ = (UniqueConstraint("coupon_id", "user_id", name="uq_coupon_user"), {"schema": COMMERCE_SCHEMA})
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
coupon_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{COMMERCE_SCHEMA}.coupons.id", ondelete="CASCADE"), nullable=False)

View File

@ -14,7 +14,6 @@ from sqlalchemy import (
Date,
DateTime,
ForeignKey,
ForeignKeyConstraint,
Index,
Integer,
Numeric,
@ -887,160 +886,3 @@ class ContentSearchFacet(Base):
mapping: Mapped[SearchFacetMapping] = relationship(back_populates="projected_values")
source_attribute_definition: Mapped[AttributeDefinition] = relationship()
# =============================================================================
# MODULE BUILDER MODELS
# =============================================================================
class BuilderModule(Base):
__tablename__ = "builder_modules"
__table_args__ = (
UniqueConstraint("code", name="uq_builder_modules_code"),
Index("idx_builder_modules_code", "code", unique=True),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
code: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
slug: Mapped[str] = mapped_column(String(255), nullable=False)
description: Mapped[str | None] = mapped_column(Text)
short_description: Mapped[str | None] = mapped_column(String(500))
kind: Mapped[str] = mapped_column(String(64), nullable=False, server_default=text("'therapeutic'"))
managed_by: Mapped[str] = mapped_column(String(64), nullable=False, server_default=text("'module_builder'"))
default_template_code: Mapped[str | None] = mapped_column(String(64))
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
categories: Mapped[list["BuilderCategory"]] = relationship(
back_populates="module",
cascade="all, delete-orphan",
passive_deletes=True,
order_by="BuilderCategory.sort_order",
)
class BuilderCategory(Base):
__tablename__ = "builder_categories"
__table_args__ = (
UniqueConstraint("module_code", "category_code", name="uq_builder_categories_code"),
ForeignKeyConstraint(
["module_code"],
[f"{CONTENT_SCHEMA}.builder_modules.code"],
ondelete="CASCADE",
onupdate="CASCADE",
name="fk_builder_categories_module",
),
Index("idx_builder_categories_module", "module_code"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
module_code: Mapped[str] = mapped_column(String(32), nullable=False)
category_code: Mapped[str] = mapped_column(String(256), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
overview: Mapped[str | None] = mapped_column(Text)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
module: Mapped["BuilderModule"] = relationship(back_populates="categories")
diseases: Mapped[list["BuilderDisease"]] = relationship(
back_populates="category",
cascade="all, delete-orphan",
passive_deletes=True,
order_by="BuilderDisease.sort_order",
)
class BuilderDisease(Base):
__tablename__ = "builder_diseases"
__table_args__ = (
UniqueConstraint("module_code", "category_code", "disease_code", name="uq_builder_diseases_code"),
ForeignKeyConstraint(
["module_code", "category_code"],
[f"{CONTENT_SCHEMA}.builder_categories.module_code", f"{CONTENT_SCHEMA}.builder_categories.category_code"],
ondelete="CASCADE",
name="fk_builder_diseases_category",
),
Index("idx_builder_diseases_cat", "module_code", "category_code"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
module_code: Mapped[str] = mapped_column(String(32), nullable=False)
category_code: Mapped[str] = mapped_column(String(256), nullable=False)
disease_code: Mapped[str] = mapped_column(String(256), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
overview: Mapped[str | None] = mapped_column(Text)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
category: Mapped["BuilderCategory"] = relationship(back_populates="diseases")
patterns: Mapped[list["BuilderPattern"]] = relationship(
back_populates="disease",
cascade="all, delete-orphan",
passive_deletes=True,
order_by="BuilderPattern.sort_order",
)
class BuilderPattern(Base):
__tablename__ = "builder_patterns"
__table_args__ = (
UniqueConstraint("module_code", "category_code", "disease_code", "pattern_code", name="uq_builder_patterns_code"),
ForeignKeyConstraint(
["module_code", "category_code", "disease_code"],
[f"{CONTENT_SCHEMA}.builder_diseases.module_code", f"{CONTENT_SCHEMA}.builder_diseases.category_code", f"{CONTENT_SCHEMA}.builder_diseases.disease_code"],
ondelete="CASCADE",
name="fk_builder_patterns_disease",
),
Index("idx_builder_patterns_dis", "module_code", "category_code", "disease_code"),
{"schema": CONTENT_SCHEMA},
)
id: Mapped[UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
)
module_code: Mapped[str] = mapped_column(String(32), nullable=False)
category_code: Mapped[str] = mapped_column(String(256), nullable=False)
disease_code: Mapped[str] = mapped_column(String(256), nullable=False)
pattern_code: Mapped[str] = mapped_column(String(256), nullable=False)
name: Mapped[str] = mapped_column(String(255), nullable=False)
description: Mapped[str | None] = mapped_column(Text)
clinical_data: Mapped[dict[str, Any]] = mapped_column(
JSONB, nullable=False, server_default=text("'{}'::jsonb")
)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("0"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
disease: Mapped["BuilderDisease"] = relationship(back_populates="patterns")

View File

@ -10,15 +10,13 @@ from collections.abc import AsyncIterator
from app.core.config import settings
engine = create_async_engine(
settings.database_url,
pool_size=settings.database_pool_size,
max_overflow=settings.database_max_overflow,
pool_timeout=settings.database_pool_timeout_seconds,
pool_pre_ping=True,
pool_recycle=1800,
future=True,
)
engine = create_async_engine(settings.database_url, pool_pre_ping=True, future=True)
# AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
# async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
# async with AsyncSessionLocal() as session:
# yield session
SessionFactory = async_sessionmaker(
bind=engine,
@ -29,10 +27,4 @@ SessionFactory = async_sessionmaker(
async def get_db_session() -> AsyncIterator[AsyncSession]:
async with SessionFactory() as session:
try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()
yield session

View File

@ -12,8 +12,6 @@ class ActiveSubscriptionRecord:
status: str
started_at: datetime
expires_at: datetime | None
payment_id: str | None = None
invoice_number: str | None = None
@dataclass(frozen=True, slots=True)

View File

@ -8,9 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import EntitlementStatus, SubscriptionStatus
from app.db.models import (
AccessPlan,
Invoice,
Module,
PaymentTransaction,
UserEntitlement,
UserSubscription,
)
@ -43,7 +41,6 @@ class AccessRepository:
UserSubscription.status,
UserSubscription.started_at,
UserSubscription.expires_at,
UserSubscription.payment_reference,
)
.join(
AccessPlan,
@ -63,31 +60,9 @@ class AccessRepository:
)
)
# Lookup payment transaction & invoice for this user's subscriptions
tx_rows = (await self._session.execute(
select(
PaymentTransaction.subscription_id,
PaymentTransaction.gateway_transaction_id,
Invoice.invoice_number,
UserSubscription.payment_reference,
)
.join(UserSubscription, UserSubscription.id == PaymentTransaction.subscription_id)
.outerjoin(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id)
.where(PaymentTransaction.user_id == user_id)
)).all()
sub_tx_map: dict[UUID, tuple[str, str | None]] = {}
order_tx_map: dict[str, tuple[str, str | None]] = {}
for sub_id, gw_tx_id, inv_num, order_ref in tx_rows:
if sub_id:
sub_tx_map[sub_id] = (gw_tx_id, inv_num)
if order_ref:
order_tx_map[order_ref] = (gw_tx_id, inv_num)
records: list[ActiveSubscriptionRecord] = []
for row in result.all():
status_value = getattr(row.status, "value", row.status)
gw_id, inv_num = sub_tx_map.get(row.id) or (order_tx_map.get(row.payment_reference) if row.payment_reference else (None, None))
records.append(
ActiveSubscriptionRecord(
id=row.id,
@ -95,8 +70,6 @@ class AccessRepository:
status=str(status_value),
started_at=row.started_at,
expires_at=row.expires_at,
payment_id=gw_id,
invoice_number=inv_num,
)
)
return records

View File

@ -16,9 +16,6 @@ class ActiveSubscriptionResponse(StrictModel):
status: str
started_at: datetime
expires_at: datetime | None = None
payment_id: str | None = None
invoice_number: str | None = None
invoice_url: str | None = None
class ActiveEntitlementResponse(StrictModel):

View File

@ -16,7 +16,6 @@ from .schema import (
LIFETIME_PLAN_CODES = frozenset({
"LIFETIME_ALL",
"LIFETIME_ALL_USD",
"LIFETIME_ALL_EUR",
})
@ -74,9 +73,6 @@ class AccessService:
status=item.status,
started_at=item.started_at,
expires_at=item.expires_at,
payment_id=item.payment_id,
invoice_number=item.invoice_number,
invoice_url=f"/api/checkout/payment/{item.payment_id}/invoice/view" if item.payment_id else None,
)
for item in subscriptions
],

View File

@ -1,8 +1,6 @@
from __future__ import annotations
import io
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import HTMLResponse, StreamingResponse
from app.core.config import get_settings
from app.db.models import AppUser
from app.features.payments import get_razorpay_service
from .deps import get_admin_service, get_current_admin
@ -22,20 +20,6 @@ from .schema import (
PlanStatusUpdateRequest,
UpdateCouponRequest,
)
from .builder_schema import (
BuilderModuleSummary,
CreateBuilderModuleRequest,
UpdateBuilderModuleRequest,
BuilderCategorySummary,
BuilderDiseaseDetailResponse,
BuilderDiseaseSummary,
ModuleBuilderExportResponse,
ModuleBuilderImportRequest,
ModuleBuilderImportResponse,
SaveCategoryRequest,
SaveDiseaseRequest,
SaveFullDiseaseRequest,
)
from .service import AdminService
router = APIRouter(prefix="/admin", tags=["Administrative Portal"])
@ -420,8 +404,6 @@ async def update_plan_status(
return await service.toggle_plan_status(plan_code, payload.is_active)
except LookupError as exc:
raise HTTPException(404, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(400, detail=str(exc)) from exc
# =============================================================================
@ -540,283 +522,3 @@ async def export_report_csv(
raise HTTPException(400, detail=str(exc)) from exc
except Exception as exc:
raise HTTPException(500, detail=f"Report export generation failed: {exc}") from exc
# =============================================================================
# MODULE BUILDER ENDPOINTS
# =============================================================================
@router.get("/module-builder/config")
async def get_builder_config(
admin: AppUser = Depends(get_current_admin),
):
return {"sync_repo_enabled": get_settings().enable_module_repo_sync}
@router.get("/module-builder/modules", response_model=list[BuilderModuleSummary])
async def list_builder_modules(
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_modules()
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch module builder modules: {exc}") from exc
@router.post("/module-builder/modules", response_model=BuilderModuleSummary, status_code=status.HTTP_201_CREATED)
async def create_builder_module(
payload: CreateBuilderModuleRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.create_module(payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to create builder module: {exc}") from exc
@router.get("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary)
async def get_builder_module(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_module(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch builder module: {exc}") from exc
@router.patch("/module-builder/modules/{module_code}", response_model=BuilderModuleSummary)
async def update_builder_module(
module_code: str,
payload: UpdateBuilderModuleRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.update_module(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to update builder module: {exc}") from exc
@router.delete("/module-builder/modules/{module_code}")
async def delete_builder_module(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.delete_module(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete builder module: {exc}") from exc
@router.get("/module-builder/{module_code}/categories", response_model=list[BuilderCategorySummary])
async def get_builder_categories(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_categories(module_code)
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch module builder categories: {exc}") from exc
@router.post("/module-builder/{module_code}/categories", response_model=BuilderCategorySummary)
async def save_builder_category(
module_code: str,
payload: SaveCategoryRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.save_category(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save module builder category: {exc}") from exc
@router.delete("/module-builder/{module_code}/categories/{category_code}")
async def delete_builder_category(
module_code: str,
category_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
deleted = await service.builder.delete_category(module_code, category_code)
if not deleted:
raise HTTPException(404, detail="Category not found")
return {"success": True, "message": "Category deleted successfully"}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete category: {exc}") from exc
@router.get("/module-builder/{module_code}/categories/{category_code}/diseases", response_model=list[BuilderDiseaseSummary])
async def get_builder_diseases(
module_code: str,
category_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.get_diseases(module_code, category_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch diseases: {exc}") from exc
@router.get("/module-builder/{module_code}/categories/{category_code}/diseases/{disease_code}", response_model=BuilderDiseaseDetailResponse)
async def get_builder_disease_detail(
module_code: str,
category_code: str,
disease_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
res = await service.builder.get_disease_detail(module_code, category_code, disease_code)
if not res:
raise HTTPException(404, detail="Disease not found")
return res
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to fetch disease details: {exc}") from exc
@router.post("/module-builder/{module_code}/categories/{category_code}/diseases", response_model=BuilderDiseaseSummary)
async def save_builder_disease(
module_code: str,
category_code: str,
payload: SaveDiseaseRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
payload.category_code = category_code
return await service.builder.save_disease(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save disease: {exc}") from exc
@router.delete("/module-builder/{module_code}/categories/{category_code}/diseases/{disease_code}")
async def delete_builder_disease(
module_code: str,
category_code: str,
disease_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
deleted = await service.builder.delete_disease(module_code, category_code, disease_code)
if not deleted:
raise HTTPException(404, detail="Disease not found")
return {"success": True, "message": "Disease deleted successfully"}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to delete disease: {exc}") from exc
@router.post("/module-builder/{module_code}/save-full", response_model=BuilderDiseaseDetailResponse)
async def save_full_disease(
module_code: str,
payload: SaveFullDiseaseRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.save_full_disease(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to save full disease data: {exc}") from exc
@router.get("/module-builder/{module_code}/export-json", response_model=ModuleBuilderExportResponse)
async def export_module_json(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.export_module_json(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to export module JSON: {exc}") from exc
@router.get("/module-builder/{module_code}/export-bundle")
async def export_builder_module_bundle(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
filename, zip_bytes = await service.builder.export_bundle_zip(module_code)
return StreamingResponse(
io.BytesIO(zip_bytes),
media_type="application/zip",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Access-Control-Expose-Headers": "Content-Disposition",
},
)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to generate module package: {exc}") from exc
@router.post("/module-builder/{module_code}/sync-content-repo")
async def sync_builder_module_to_repo(
module_code: str,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
if not get_settings().enable_module_repo_sync:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Server repository sync is disabled in this environment.",
)
try:
return await service.builder.sync_content_repo(module_code)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to sync module to content repository: {exc}") from exc
@router.post("/module-builder/{module_code}/import-json", response_model=ModuleBuilderImportResponse)
async def import_module_json(
module_code: str,
payload: ModuleBuilderImportRequest,
admin: AppUser = Depends(get_current_admin),
service: AdminService = Depends(get_admin_service),
):
try:
return await service.builder.import_module_json(module_code, payload)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to import module JSON: {exc}") from exc

View File

@ -1,219 +0,0 @@
from __future__ import annotations
import re
from typing import Any
from uuid import UUID
from pydantic import BaseModel, Field, field_validator
# =============================================================================
# MODULE SCHEMAS
# =============================================================================
class CreateBuilderModuleRequest(BaseModel):
name: str = Field(..., min_length=2, max_length=255)
code: str | None = Field(default=None, max_length=32)
slug: str | None = Field(default=None, max_length=255)
short_description: str | None = Field(default=None, max_length=500)
description: str | None = None
kind: str = Field(default="therapeutic", max_length=64)
managed_by: str = Field(default="module_builder", max_length=64)
sort_order: int | None = None
@field_validator("code")
@classmethod
def validate_code(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = v.strip().lower()
if not re.match(r"^m[0-9]{4}$", cleaned):
raise ValueError(
"Module code must start with 'm' followed by exactly 4 digits (e.g. 'm0043')"
)
return cleaned
class UpdateBuilderModuleRequest(BaseModel):
name: str | None = Field(default=None, min_length=2, max_length=255)
short_description: str | None = Field(default=None, max_length=500)
description: str | None = None
sort_order: int | None = None
is_active: bool | None = None
class BuilderModuleSummary(BaseModel):
id: UUID | None = None
code: str
name: str
slug: str
short_description: str | None = None
description: str | None = None
kind: str = "therapeutic"
managed_by: str = "module_builder"
default_template_code: str | None = None
sort_order: int = 0
is_active: bool = True
category_count: int = 0
disease_count: int = 0
pattern_count: int = 0
created_at: Any = None
updated_at: Any = None
# =============================================================================
# CLINICAL DATA STRUCTURES
# =============================================================================
class AcupunctureDetails(BaseModel):
points: str = ""
method: str = ""
class PatternClinicalData(BaseModel):
clinical_manifestations: list[str] = Field(default_factory=list)
tongue: str = ""
pulse: str = ""
treatment_principle: list[str] | str = ""
acupuncture: AcupunctureDetails = Field(default_factory=AcupunctureDetails)
explanation: list[str] = Field(default_factory=list)
# =============================================================================
# PATTERN SCHEMAS
# =============================================================================
class SavePatternRequest(BaseModel):
category_code: str
disease_code: str
pattern_code: str
name: str
description: str | None = None
clinical_data: dict[str, Any] = Field(default_factory=dict)
sort_order: int = 0
class BuilderPatternResponse(BaseModel):
id: UUID | None = None
module_code: str
category_code: str
disease_code: str
pattern_code: str
name: str
description: str | None = None
clinical_data: dict[str, Any]
sort_order: int = 0
# =============================================================================
# DISEASE SCHEMAS
# =============================================================================
class SaveDiseaseRequest(BaseModel):
category_code: str | None = None
disease_code: str
name: str
overview: str | None = None
sort_order: int = 0
class SaveFullDiseaseRequest(BaseModel):
category_code: str
disease_code: str
name: str
overview: str | None = None
patterns: list[SavePatternRequest] = Field(default_factory=list)
class BuilderDiseaseSummary(BaseModel):
id: UUID | None = None
module_code: str
category_code: str
disease_code: str
name: str
overview: str | None = None
sort_order: int = 0
pattern_count: int = 0
class BuilderDiseaseDetailResponse(BaseModel):
id: UUID | None = None
module_code: str
category_code: str
disease_code: str
name: str
overview: str | None = None
sort_order: int = 0
patterns: list[BuilderPatternResponse] = Field(default_factory=list)
# =============================================================================
# CATEGORY SCHEMAS
# =============================================================================
class SaveCategoryRequest(BaseModel):
category_code: str
name: str
overview: str | None = None
sort_order: int = 0
class BuilderCategorySummary(BaseModel):
id: UUID | None = None
module_code: str
category_code: str
name: str
overview: str | None = None
sort_order: int = 0
disease_count: int = 0
# =============================================================================
# EXPORT & IMPORT SCHEMAS
# =============================================================================
class ExportPatternItem(BaseModel):
description: str | None = ""
name: str
code: str
clinical_manifestations: list[str] = Field(default_factory=list)
tongue: str = ""
pulse: str = ""
treatment_principle: str = ""
acupuncture: dict[str, str] = Field(default_factory=dict)
explanation: list[str] = Field(default_factory=list)
class ExportDiseaseItem(BaseModel):
overview: str | None = ""
name: str
code: str
patterns: list[ExportPatternItem] = Field(default_factory=list)
class ExportCategoryItem(BaseModel):
overview: str | None = ""
name: str
code: str
diseases: list[ExportDiseaseItem] = Field(default_factory=list)
class ModuleBuilderExportResponse(BaseModel):
contents: list[ExportCategoryItem] = Field(default_factory=list)
class ModuleBuilderImportRequest(BaseModel):
contents: list[dict[str, Any]] = Field(default_factory=list)
class ModuleBuilderImportResponse(BaseModel):
categories_imported: int = 0
diseases_imported: int = 0
patterns_imported: int = 0
message: str = "Import completed successfully"

View File

@ -1,13 +0,0 @@
from __future__ import annotations
from collections.abc import Iterable
ADMIN_ROLES: frozenset[str] = frozenset({"super_admin", "admin", "finance_admin"})
def has_admin_role(roles: Iterable[str] | None) -> bool:
"""Return True if any assigned role grants administrative privileges."""
if not roles:
return False
return any((role or "").strip().lower() in ADMIN_ROLES for role in roles)

View File

@ -1,12 +1,10 @@
from __future__ import annotations
from fastapi import Depends, HTTPException, Request
from fastapi import Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache.invalidation import ContentCacheInvalidator
from app.db.models import AppUser, Role, UserRole
from app.db.session import get_db_session
from app.features.checkout.deps import get_current_user
from .constants import has_admin_role
from .repository import AdminRepository
from .service import AdminService
@ -14,18 +12,12 @@ async def get_current_admin(user: AppUser = Depends(get_current_user), session:
roles = (await session.execute(
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
)).scalars().all()
if not has_admin_role(roles):
if not ({"super_admin", "admin", "finance_admin"} & set(roles)):
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
return user
def get_admin_repository(session: AsyncSession = Depends(get_db_session)) -> AdminRepository:
return AdminRepository(session)
def get_admin_invalidator(request: Request) -> ContentCacheInvalidator | None:
return getattr(request.app.state, "content_cache_invalidator", None)
def get_admin_service(
repository: AdminRepository = Depends(get_admin_repository),
invalidator: ContentCacheInvalidator | None = Depends(get_admin_invalidator),
) -> AdminService:
return AdminService(repository.session, invalidator=invalidator)
def get_admin_service(repository: AdminRepository = Depends(get_admin_repository)) -> AdminService:
return AdminService(repository.session)

View File

@ -62,7 +62,6 @@ class CreatePlanRequest(BaseModel):
billing_period: str = "yearly"
price_inr: float
price_usd: float
price_eur: float | None = None
module_ids: list[str] = Field(default_factory=list)
is_featured: bool = False
badge_text: str | None = None
@ -72,13 +71,11 @@ class CreatePlanRequest(BaseModel):
class PlanPricingUpdateRequest(BaseModel):
price_inr: float | None = None
price_usd: float | None = None
price_eur: float | None = None
name: str | None = None
description: str | None = None
badge_text: str | None = None
heading: str | None = None
subtitle: str | None = None
module_ids: list[str] | None = None
class PlanStatusUpdateRequest(BaseModel):
is_active: bool
@ -88,53 +85,31 @@ class CreateCouponRequest(BaseModel):
discount_type: str
coupon_category: str = "general"
value: float
value_inr: float | None = None
value_usd: float | None = None
value_eur: float | None = None
max_discount_limit: float = 0.0
max_discount_inr: float | None = None
max_discount_usd: float | None = None
max_discount_eur: float | None = None
start_date: str | None = None
end_date: str | None = None
usage_limit: int = 0
per_user_limit: int | None = None
min_purchase_amount: float = 0.0
min_purchase_inr: float | None = None
min_purchase_usd: float | None = None
min_purchase_eur: float | None = None
is_first_purchase_only: bool = False
applicable_plan_ids: list[str] | None = None
applicable_module_ids: list[str] | None = None
is_active: bool = True
description: str | None = None
metadata_json: dict | None = None
class UpdateCouponRequest(BaseModel):
discount_type: str | None = None
coupon_category: str | None = None
value: float | None = None
value_inr: float | None = None
value_usd: float | None = None
value_eur: float | None = None
max_discount_limit: float | None = None
max_discount_inr: float | None = None
max_discount_usd: float | None = None
max_discount_eur: float | None = None
start_date: str | None = None
end_date: str | None = None
usage_limit: int | None = None
per_user_limit: int | None = None
min_purchase_amount: float | None = None
min_purchase_inr: float | None = None
min_purchase_usd: float | None = None
min_purchase_eur: float | None = None
is_first_purchase_only: bool | None = None
applicable_plan_ids: list[str] | None = None
applicable_module_ids: list[str] | None = None
is_active: bool | None = None
description: str | None = None
metadata_json: dict | None = None
class CouponStatusToggleRequest(BaseModel):
is_active: bool

View File

@ -2,7 +2,6 @@ from __future__ import annotations
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi.responses import HTMLResponse, StreamingResponse
from app.db.models import AppUser
from app.cache.invalidation import ContentCacheInvalidator
from ..schema import (
AdminCreateSuperAdminRequest,
AdminPromoteUserRequest,
@ -27,7 +26,6 @@ from .customer_service import AdminCustomerService
from .payment_service import AdminPaymentService
from .database_service import AdminDatabaseService
from .report_service import AdminReportService
from .module_builder_service import ModuleBuilderService
__all__ = [
"AdminModuleService",
@ -37,7 +35,6 @@ __all__ = [
"AdminPaymentService",
"AdminDatabaseService",
"AdminReportService",
"ModuleBuilderService",
"AdminService",
]
@ -52,24 +49,17 @@ class AdminService:
- payments: AdminPaymentService
- database: AdminDatabaseService
- reports: AdminReportService
- builder: ModuleBuilderService
"""
def __init__(
self,
session: AsyncSession,
invalidator: ContentCacheInvalidator | None = None,
) -> None:
def __init__(self, session: AsyncSession) -> None:
self.session = session
self.invalidator = invalidator
self.modules = AdminModuleService(session, invalidator=invalidator)
self.modules = AdminModuleService(session)
self.plans = AdminPlanService(session)
self.coupons = AdminCouponService(session)
self.customers = AdminCustomerService(session)
self.payments = AdminPaymentService(session)
self.database = AdminDatabaseService(session)
self.reports = AdminReportService(session)
self.builder = ModuleBuilderService(session)
# ── Modules Facade ──
async def list_modules(self) -> list[dict]:

View File

@ -2,96 +2,16 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from uuid import UUID
from sqlalchemy import func, select
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import AccessPlan, AppUser, Coupon, CouponRedemption, Module
from app.db.models import AccessPlan, AppUser, Coupon, Module
from ..schema import CreateCouponRequest, UpdateCouponRequest
def _parse_iso_datetime(value: str | datetime | None, default: datetime | None = None) -> datetime | None:
if value is None:
return default
if isinstance(value, datetime):
dt = value
else:
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
def _build_coupon_metadata(payload: CreateCouponRequest | UpdateCouponRequest, existing_meta: dict | None = None) -> dict:
meta = dict(existing_meta or {})
if getattr(payload, "metadata_json", None):
meta.update(payload.metadata_json)
c_vals = dict(meta.get("currency_values") or {})
if payload.value_inr is not None:
c_vals["INR"] = payload.value_inr
elif payload.value is not None and "INR" not in c_vals:
c_vals["INR"] = payload.value
if payload.value_usd is not None:
c_vals["USD"] = payload.value_usd
if payload.value_eur is not None:
c_vals["EUR"] = payload.value_eur
if c_vals:
meta["currency_values"] = c_vals
c_caps = dict(meta.get("currency_caps") or {})
if payload.max_discount_inr is not None:
c_caps["INR"] = payload.max_discount_inr
elif payload.max_discount_limit is not None and "INR" not in c_caps:
c_caps["INR"] = payload.max_discount_limit
if payload.max_discount_usd is not None:
c_caps["USD"] = payload.max_discount_usd
if payload.max_discount_eur is not None:
c_caps["EUR"] = payload.max_discount_eur
if c_caps:
meta["currency_caps"] = c_caps
c_mins = dict(meta.get("currency_min_spends") or {})
if payload.min_purchase_inr is not None:
c_mins["INR"] = payload.min_purchase_inr
elif payload.min_purchase_amount is not None and "INR" not in c_mins:
c_mins["INR"] = payload.min_purchase_amount
if payload.min_purchase_usd is not None:
c_mins["USD"] = payload.min_purchase_usd
if payload.min_purchase_eur is not None:
c_mins["EUR"] = payload.min_purchase_eur
if c_mins:
meta["currency_min_spends"] = c_mins
return meta
class AdminCouponService:
def __init__(self, session: AsyncSession) -> None:
self.session = session
async def _expand_plan_ids(self, plan_ids: list[str] | None) -> list[UUID] | None:
if not plan_ids:
return None
uuids = [UUID(pid) for pid in plan_ids]
rows = (await self.session.execute(
select(AccessPlan.code).where(AccessPlan.id.in_(uuids))
)).scalars().all()
base_codes: set[str] = set()
for c in rows:
code_up = c.upper()
if code_up.endswith("_USD"):
base_codes.add(code_up[:-4])
elif code_up.endswith("_EUR"):
base_codes.add(code_up[:-4])
else:
base_codes.add(code_up)
all_codes: set[str] = set()
for bc in base_codes:
all_codes.add(bc)
all_codes.add(f"{bc}_USD")
all_codes.add(f"{bc}_EUR")
all_plan_rows = (await self.session.execute(
select(AccessPlan.id).where(AccessPlan.code.in_(all_codes))
)).scalars().all()
return list(set(uuids + list(all_plan_rows)))
async def list_coupons(self) -> list[dict]:
coupons = (await self.session.execute(
select(Coupon).order_by(Coupon.created_at.desc())
@ -103,24 +23,14 @@ class AdminCouponService:
mods_q = await self.session.execute(select(Module))
all_mods = {str(m.id): m.name for m in mods_q.scalars().all()}
redemptions_q = await self.session.execute(
select(CouponRedemption.coupon_id, func.count(CouponRedemption.id))
.group_by(CouponRedemption.coupon_id)
)
redemption_counts = {cid: cnt for cid, cnt in redemptions_q.all()}
now = datetime.now(timezone.utc)
result: list[dict] = []
for c in coupons:
s_date = c.start_date.replace(tzinfo=timezone.utc) if c.start_date.tzinfo is None else c.start_date
e_date = c.end_date.replace(tzinfo=timezone.utc) if c.end_date.tzinfo is None else c.end_date
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
if not c.is_active:
status = "inactive"
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
status = "fully_redeemed"
elif now < s_date:
status = "scheduled"
elif now > e_date:
@ -131,53 +41,18 @@ class AdminCouponService:
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
module_names = [all_mods.get(str(mid), str(mid)[:8]) for mid in (c.applicable_module_ids or [])]
metadata = c.metadata_json or {}
c_values = metadata.get("currency_values") or {}
c_caps = metadata.get("currency_caps") or {}
c_mins = metadata.get("currency_min_spends") or {}
val_inr = float(c_values.get("INR", c.value))
val_usd = float(c_values["USD"]) if "USD" in c_values and c_values["USD"] is not None else None
val_eur = float(c_values["EUR"]) if "EUR" in c_values and c_values["EUR"] is not None else None
cap_inr = float(c_caps.get("INR", c.max_discount_limit or 0.0))
cap_usd = float(c_caps["USD"]) if "USD" in c_caps and c_caps["USD"] is not None else None
cap_eur = float(c_caps["EUR"]) if "EUR" in c_caps and c_caps["EUR"] is not None else None
min_inr = float(c_mins.get("INR", c.min_purchase_amount or 0.0))
min_usd = float(c_mins["USD"]) if "USD" in c_mins and c_mins["USD"] is not None else None
min_eur = float(c_mins["EUR"]) if "EUR" in c_mins and c_mins["EUR"] is not None else None
result.append({
"id": str(c.id),
"code": c.code,
"discount_type": c.discount_type,
"coupon_category": c.coupon_category,
"value": float(c.value),
"value_inr": val_inr,
"value_usd": val_usd,
"value_eur": val_eur,
"max_discount_limit": float(c.max_discount_limit or 0.0),
"max_discount_inr": cap_inr,
"max_discount_usd": cap_usd,
"max_discount_eur": cap_eur,
"start_date": s_date.isoformat(),
"end_date": e_date.isoformat(),
"usage_limit": c.usage_limit,
"per_user_limit": (
c.per_user_limit
if isinstance(c.per_user_limit, int) and not isinstance(c.per_user_limit, bool)
else None
),
"usage_count": usage_count,
"usage_count": c.usage_count,
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
"min_purchase_inr": min_inr,
"min_purchase_usd": min_usd,
"min_purchase_eur": min_eur,
"currency_values": c_values,
"currency_caps": c_caps,
"currency_min_spends": c_mins,
"metadata_json": metadata,
"is_first_purchase_only": c.is_first_purchase_only,
"is_active": c.is_active,
"description": c.description or "",
@ -198,42 +73,28 @@ class AdminCouponService:
raise ValueError(f"Coupon code '{code}' already exists.")
now = datetime.now(timezone.utc)
start = _parse_iso_datetime(payload.start_date, default=now)
end = _parse_iso_datetime(payload.end_date, default=(now + timedelta(days=30)))
start = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00")) if payload.start_date else now
end = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00")) if payload.end_date else (now + timedelta(days=30))
if end <= start:
raise ValueError("Invalid date range: End date must be later than start date.")
if payload.usage_limit < 0:
raise ValueError("Global usage limit must be 0 or greater.")
if payload.per_user_limit is None or payload.per_user_limit < 0:
raise ValueError("Per-user limit is required and must be 0 or greater.")
expanded_plan_uuids = await self._expand_plan_ids(payload.applicable_plan_ids)
plan_uuids = [UUID(pid) for pid in payload.applicable_plan_ids] if payload.applicable_plan_ids else None
module_uuids = [UUID(mid) for mid in payload.applicable_module_ids] if payload.applicable_module_ids else None
base_val = payload.value_inr if payload.value_inr is not None else payload.value
base_cap = payload.max_discount_inr if payload.max_discount_inr is not None else (payload.max_discount_limit or 0)
base_min = payload.min_purchase_inr if payload.min_purchase_inr is not None else (payload.min_purchase_amount or 0)
metadata = _build_coupon_metadata(payload)
coupon = Coupon(
code=code,
discount_type=payload.discount_type,
coupon_category=payload.coupon_category,
value=Decimal(str(base_val)),
max_discount_limit=Decimal(str(base_cap)),
value=Decimal(str(payload.value)),
max_discount_limit=Decimal(str(payload.max_discount_limit or 0)),
start_date=start,
end_date=end,
usage_limit=payload.usage_limit,
per_user_limit=payload.per_user_limit,
usage_count=0,
min_purchase_amount=Decimal(str(base_min)),
min_purchase_amount=Decimal(str(payload.min_purchase_amount or 0)),
is_first_purchase_only=payload.is_first_purchase_only,
applicable_plan_ids=expanded_plan_uuids,
applicable_plan_ids=plan_uuids,
applicable_module_ids=module_uuids,
is_active=payload.is_active,
description=payload.description,
metadata_json=metadata,
)
self.session.add(coupon)
await self.session.commit()
@ -249,44 +110,26 @@ class AdminCouponService:
if not coupon:
raise LookupError("Coupon not found.")
new_start = _parse_iso_datetime(payload.start_date, default=coupon.start_date)
new_end = _parse_iso_datetime(payload.end_date, default=coupon.end_date)
if new_start is not None and new_end is not None:
if new_end <= new_start:
raise ValueError("Invalid date range: End date must be later than start date.")
if payload.discount_type is not None:
coupon.discount_type = payload.discount_type
if payload.coupon_category is not None:
coupon.coupon_category = payload.coupon_category
if payload.value_inr is not None:
coupon.value = Decimal(str(payload.value_inr))
elif payload.value is not None:
if payload.value is not None:
coupon.value = Decimal(str(payload.value))
if payload.max_discount_inr is not None:
coupon.max_discount_limit = Decimal(str(payload.max_discount_inr))
elif payload.max_discount_limit is not None:
if payload.max_discount_limit is not None:
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
if payload.start_date is not None:
coupon.start_date = new_start
coupon.start_date = datetime.fromisoformat(payload.start_date.replace("Z", "+00:00"))
if payload.end_date is not None:
coupon.end_date = new_end
coupon.end_date = datetime.fromisoformat(payload.end_date.replace("Z", "+00:00"))
if payload.usage_limit is not None:
if payload.usage_limit < 0:
raise ValueError("Global usage limit must be 0 or greater.")
coupon.usage_limit = payload.usage_limit
if "per_user_limit" in payload.model_fields_set:
if payload.per_user_limit is None or payload.per_user_limit < 0:
raise ValueError("Per-user limit is required and must be 0 or greater.")
coupon.per_user_limit = payload.per_user_limit
if payload.min_purchase_inr is not None:
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
elif payload.min_purchase_amount is not None:
if payload.min_purchase_amount is not None:
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
if payload.is_first_purchase_only is not None:
coupon.is_first_purchase_only = payload.is_first_purchase_only
if payload.applicable_plan_ids is not None:
coupon.applicable_plan_ids = await self._expand_plan_ids(payload.applicable_plan_ids)
coupon.applicable_plan_ids = [UUID(pid) for pid in payload.applicable_plan_ids]
if payload.applicable_module_ids is not None:
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
if payload.is_active is not None:
@ -294,8 +137,6 @@ class AdminCouponService:
if payload.description is not None:
coupon.description = payload.description
coupon.metadata_json = _build_coupon_metadata(payload, coupon.metadata_json)
await self.session.commit()
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}

View File

@ -16,7 +16,6 @@ from app.db.models import (
UserRole,
UserSubscription,
)
from ..constants import has_admin_role
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
from app.features.auth.security import hash_password, validate_password_strength
from app.features.payments import get_razorpay_service
@ -28,64 +27,45 @@ class AdminCustomerService:
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
if not users:
return []
user_ids = [u.id for u in users]
role_rows = (await self.session.execute(
select(UserRole.user_id, Role.role_name)
.join(Role, Role.id == UserRole.role_id)
.where(UserRole.user_id.in_(user_ids))
)).all()
roles_by_user: dict[UUID, list[str]] = {}
for uid, role_name in role_rows:
roles_by_user.setdefault(uid, []).append(role_name)
matching_users = [
user for user in users
if super_admin_only == has_admin_role(roles_by_user.get(user.id))
]
if not matching_users:
return []
matching_ids = [u.id for u in matching_users]
sub_rows = (await self.session.execute(
select(UserSubscription, AccessPlan)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
.where(
UserSubscription.user_id.in_(matching_ids),
UserSubscription.status != SubscriptionStatus.PENDING,
out: list[AdminUserListResponse] = []
for user in users:
roles = list((await self.session.execute(
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
)).scalars().all())
if super_admin_only != ("super_admin" in roles):
continue
subs = (await self.session.execute(
select(UserSubscription, AccessPlan)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
.where(UserSubscription.user_id == user.id, UserSubscription.status != SubscriptionStatus.PENDING)
.order_by(UserSubscription.started_at.desc())
)).all()
out.append(
AdminUserListResponse(
id=user.id,
email=user.email,
display_name=user.display_name,
phone_number=user.phone_number,
country=user.country,
is_active=user.is_active,
roles=roles,
external_ref=user.external_ref,
subscriptions=[
{
"id": str(s.id),
"plan_code": p.code if p else "UNKNOWN",
"plan_name": p.name if p else "Unknown Access Plan",
"status": getattr(s.status, "value", s.status),
"started_at": s.started_at.isoformat() if s.started_at else None,
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
"payment_reference": s.payment_reference,
}
for s, p in subs
],
created_at=user.created_at.isoformat() if user.created_at else None,
)
)
.order_by(UserSubscription.started_at.desc())
)).all()
subs_by_user: dict[UUID, list[dict]] = {}
for s, p in sub_rows:
subs_by_user.setdefault(s.user_id, []).append({
"id": str(s.id),
"plan_code": p.code if p else "UNKNOWN",
"plan_name": p.name if p else "Unknown Access Plan",
"status": getattr(s.status, "value", s.status),
"started_at": s.started_at.isoformat() if s.started_at else None,
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
"payment_reference": s.payment_reference,
})
return [
AdminUserListResponse(
id=user.id,
email=user.email,
display_name=user.display_name,
phone_number=user.phone_number,
country=user.country,
is_active=user.is_active,
roles=roles_by_user.get(user.id, []),
external_ref=user.external_ref,
subscriptions=subs_by_user.get(user.id, []),
created_at=user.created_at.isoformat() if user.created_at else None,
)
for user in matching_users
]
return out
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
user = (await self.session.execute(

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +1,23 @@
from __future__ import annotations
from typing import Any
from uuid import UUID
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import ModuleStatus
from app.db.models import Module, AccessPlanModule
from app.cache.invalidation import ContentCacheInvalidator
from ..schema import ModuleStatusUpdateRequest, ModuleUpdateRequest
CATEGORY_UI_DEFAULTS: dict[str, dict[str, str]] = {
"Points": {"icon": "water-outline", "color": "#2563EB"},
"Patterns": {"icon": "analytics-outline", "color": "#8B5CF6"},
"Nutrition": {"icon": "leaf-outline", "color": "#10B981"},
"Therapeutics": {"icon": "medkit-outline", "color": "#EC4899"},
"General": {"icon": "book-outline", "color": "#6366F1"},
UI_MAPPINGS: dict[str, dict[str, str]] = {
"acupoints": {"category": "point", "icon": "water-outline", "color": "#2563EB"},
"ear-acupuncture": {"category": "point", "icon": "ear-outline", "color": "#F59E0B"},
"scalp-acupuncture": {"category": "point", "icon": "accessibility-outline", "color": "#EF4444"},
"points_tung": {"category": "point", "icon": "analytics-outline", "color": "#10B981"},
"auriculotherapy": {"category": "point", "icon": "body-outline", "color": "#8B5CF6"},
}
# Backward-compatibility alias
UI_MAPPINGS: dict[str, dict[str, str]] = {}
def resolve_module_category(meta: dict[str, Any] | None) -> str:
"""
Generically resolve module clinical category from metadata / kind.
No hardcoded module codes or slugs.
"""
if not meta:
return "General"
# 1. Explicitly configured category in metadata
cat = meta.get("category")
if cat and str(cat).strip().lower() != "general":
c = str(cat).strip().lower()
if c in ("point", "points"):
return "Points"
if c in ("pattern", "patterns", "five-elements"):
return "Patterns"
if c == "nutrition":
return "Nutrition"
if c in ("therapeutic", "therapeutics"):
return "Therapeutics"
return str(cat).strip()
# 2. Derive from content kind
kind = str(meta.get("kind") or "").strip().lower()
if kind in ("point", "points"):
return "Points"
if kind in ("pattern", "patterns", "five-elements"):
return "Patterns"
if kind == "nutrition":
return "Nutrition"
if kind in ("therapeutic", "therapeutics"):
return "Therapeutics"
return "General"
class AdminModuleService:
def __init__(
self,
session: AsyncSession,
invalidator: ContentCacheInvalidator | None = None,
) -> None:
def __init__(self, session: AsyncSession) -> None:
self.session = session
self.invalidator = invalidator
async def list_modules(self) -> list[dict]:
modules = (await self.session.execute(select(Module).order_by(Module.name.asc()))).scalars().all()
@ -76,10 +30,10 @@ class AdminModuleService:
result: list[dict] = []
for m in modules:
meta = m.metadata_json or {}
category = resolve_module_category(meta)
ui_defaults = CATEGORY_UI_DEFAULTS.get(category, CATEGORY_UI_DEFAULTS["General"])
icon = meta.get("icon") or ui_defaults["icon"]
color = meta.get("color") or ui_defaults["color"]
ui = UI_MAPPINGS.get(m.slug, {})
category = meta.get("category") or ui.get("category", "General")
icon = meta.get("icon") or ui.get("icon", "book-outline")
color = meta.get("color") or ui.get("color", "#6366F1")
result.append({
"id": str(m.id),
@ -118,8 +72,6 @@ class AdminModuleService:
await self.session.commit()
await self.session.refresh(module)
if self.invalidator:
await self.invalidator.invalidate_module_structure_change(module_id=module.id)
return {
"status": "success",
"message": f"Module '{module.name}' status updated to {'Active' if module.is_active else 'Inactive'}.",
@ -157,10 +109,6 @@ class AdminModuleService:
await self.session.commit()
await self.session.refresh(module)
if self.invalidator:
await self.invalidator.invalidate_module_structure_change(module_id=module.id)
resolved_category = resolve_module_category(meta)
ui_defaults = CATEGORY_UI_DEFAULTS.get(resolved_category, CATEGORY_UI_DEFAULTS["General"])
return {
"status": "success",
"message": f"Module '{module.name}' updated successfully.",
@ -169,8 +117,8 @@ class AdminModuleService:
"slug": module.slug,
"name": module.name,
"description": module.description,
"category": resolved_category,
"color": meta.get("color") or ui_defaults["color"],
"icon": meta.get("icon") or ui_defaults["icon"],
"category": meta.get("category"),
"color": meta.get("color"),
"icon": meta.get("icon"),
},
}

View File

@ -10,7 +10,6 @@ from app.db.models import (
AccessPlan,
AccessPlanModule,
AppUser,
Coupon,
Invoice,
PaymentTransaction,
RefundDecision,
@ -20,7 +19,7 @@ from app.db.models import (
)
from ..schema import AdminRefundRequest, AdminRefundResponse, AdminSyncResponse
from app.features.email import send_invoice_email
from app.features.payments import generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
from app.features.payments import get_razorpay_service
class AdminPaymentService:
@ -174,38 +173,23 @@ class AdminPaymentService:
discount = Decimal(str(meta.get("total_discounts", 0)))
user = (await self.session.execute(select(AppUser).where(AppUser.id == sub.user_id))).scalar_one()
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
invoice_number = await generate_next_invoice_number(self.session, dt=now)
invoice = Invoice(
payment_transaction_id=tx.id,
invoice_number=invoice_number,
billing_name=user.display_name or user.email,
billing_email=user.email,
billing_address="Synced from Razorpay",
applied_coupon_id=coupon.id if coupon else None,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=amount,
currency_code=curr,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if curr == "INR" else None,
)
self.session.add(invoice)
await self.session.flush()
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=sub.user_id,
invoice_id=invoice.id,
self.session.add(
Invoice(
payment_transaction_id=tx.id,
invoice_number=f"INV-{now.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}",
billing_name=user.display_name or user.email,
billing_email=user.email,
billing_address="Synced from Razorpay",
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=amount,
currency_code=curr,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if curr == "INR" else None,
)
)
module_ids = (await self.session.execute(
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id)
@ -274,7 +258,7 @@ class AdminPaymentService:
rzp = get_razorpay_service()
user = (await self.session.execute(select(AppUser).where(AppUser.id == tx.user_id))).scalar_one()
if invoice and invoice.invoice_number:
if invoice and invoice.invoice_number and invoice.invoice_number.startswith("inv_"):
return f"/api/admin/payments/{payment_id}/invoice/view", invoice.invoice_number, user.email
profile = (await self.session.execute(
@ -314,15 +298,16 @@ class AdminPaymentService:
except Exception:
pass
if not inv_id:
inv_id = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
# Always return our internal branded Acupedia Tax Invoice view URL
url = f"/api/admin/payments/{payment_id}/invoice/view"
if invoice:
if not invoice.invoice_number or invoice.invoice_number.startswith("Tx:"):
invoice.invoice_number = await generate_next_invoice_number(self.session)
inv_number = invoice.invoice_number
invoice.invoice_number = inv_id
else:
inv_number = await generate_next_invoice_number(self.session)
amount = Decimal(str(payment.get("amount", 0))) / 100
curr = str(payment.get("currency", "INR")).upper()
taxable = (amount / Decimal("1.0236") * Decimal("0.02")).quantize(Decimal("0.01")) if curr == "INR" else (amount / Decimal("1.03") * Decimal("0.03")).quantize(Decimal("0.01"))
@ -331,7 +316,7 @@ class AdminPaymentService:
self.session.add(
Invoice(
payment_transaction_id=tx.id,
invoice_number=inv_number,
invoice_number=inv_id,
billing_name=customer["name"],
billing_email=customer["email"],
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}" if profile else "Not Configured",
@ -346,7 +331,7 @@ class AdminPaymentService:
)
)
await self.session.commit()
return url, inv_number, customer["email"]
return url, inv_id, customer["email"]
async def share_invoice(self, payment_id: str) -> dict:
url, num, email = await self.get_or_create_invoice(payment_id)
@ -363,53 +348,39 @@ class AdminPaymentService:
invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None
profile = None
if invoice and invoice.billing_profile_id:
profile = (await self.session.execute(
select(UserBillingProfile).where(UserBillingProfile.id == invoice.billing_profile_id)
)).scalar_one_or_none()
elif user:
if user:
profile = (await self.session.execute(
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
)).scalar_one_or_none()
sub = None
if tx and tx.subscription_id:
sub = (await self.session.execute(
select(UserSubscription).where(UserSubscription.id == tx.subscription_id)
)).scalar_one_or_none()
rzp_payment = {}
try:
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
except Exception:
pass
sub_meta = (sub.metadata_json or {}) if sub else {}
cust_name = (invoice.billing_name if invoice else None) or (profile.billing_name if profile else None) or (user.display_name if user else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
cust_email = (invoice.billing_email if invoice else None) or (profile.billing_email if profile else None) or (user.email if user else None) or rzp_payment.get("email") or "customer@example.com"
cust_phone = (profile.billing_phone if profile else None) or (user.phone_number if user else None) or rzp_payment.get("contact") or ""
# Prioritize the frozen invoice/purchase snapshot so historical invoices never mutate on profile edits
cust_name = (invoice.billing_name if invoice and invoice.billing_name else None) or (profile.billing_name if profile else None) or (user.display_name if user and user.display_name else None) or rzp_payment.get("email", "").split("@")[0].title() or "Valued Customer"
cust_email = (invoice.billing_email if invoice and invoice.billing_email else None) or (profile.billing_email if profile else None) or (user.email if user and user.email else None) or rzp_payment.get("email") or "customer@example.com"
cust_phone = sub_meta.get("billing_phone") or rzp_payment.get("contact") or (profile.billing_phone if profile else None) or (user.phone_number if user and user.phone_number else None) or ""
# Clean address string
clean_addr_parts = []
if profile:
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
clean_addr_parts.append(p.strip())
c = profile.country or (user.country if user else None)
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
clean_addr_parts.append(c.strip())
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
clean_addr_parts.append(user.country.strip())
elif invoice and invoice.billing_address and "not configured" not in invoice.billing_address.lower():
clean_addr_parts.append(invoice.billing_address.strip())
# Clean address string: prefer frozen invoice.billing_address when valid
if invoice and invoice.billing_address and invoice.billing_address.strip().lower() not in ["not configured", "none", "null", "recorded from gateway webhook"]:
cust_address = invoice.billing_address.strip()
else:
clean_addr_parts = []
if profile:
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
clean_addr_parts.append(p.strip())
c = profile.country or (user.country if user and user.country else None)
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
clean_addr_parts.append(c.strip())
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
clean_addr_parts.append(user.country.strip())
cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else ((user.country if user and user.country else None) or "Digital Access")
cust_address = ", ".join(clean_addr_parts) if clean_addr_parts else (user.country if user and user.country else "Digital Access")
now = datetime.now(timezone.utc)
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{now.strftime('%b').upper()}-{now.strftime('%Y')}-PREVIEW"
inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else now.strftime("%B %d, %Y"))
inv_number = (invoice.invoice_number if invoice else None) or f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
inv_date = invoice.created_at.strftime("%B %d, %Y") if invoice and invoice.created_at else (tx.created_at.strftime("%B %d, %Y") if tx and tx.created_at else datetime.now(timezone.utc).strftime("%B %d, %Y"))
currency = (invoice.currency_code if invoice else None) or (tx.currency if tx else None) or str(rzp_payment.get("currency", "USD")).upper()
curr_symbol = "$" if currency == "USD" else ("₹" if currency == "INR" else f"{currency} ")
@ -418,20 +389,7 @@ class AdminPaymentService:
base_val = total_val
# Item description
item_desc = rzp_payment.get("description") if rzp_payment else None
if not item_desc and tx:
if sub:
ref = sub.payment_reference
subs = (await self.session.execute(
select(UserSubscription).where(UserSubscription.user_id == tx.user_id, UserSubscription.payment_reference == ref)
)).scalars().all() if ref else [sub]
p_names = []
for s in subs:
p = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == s.plan_id))).scalar_one_or_none()
if p and p.name not in p_names:
p_names.append(p.name)
if p_names:
item_desc = ", ".join(p_names)
item_desc = rzp_payment.get("description")
if not item_desc:
item_desc = "Clinical Access Plan Subscription"
@ -446,7 +404,6 @@ class AdminPaymentService:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="format-detection" content="telephone=no, date=no, address=no, email=no">
<title>Tax Invoice - {inv_number}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@ -458,18 +415,6 @@ class AdminPaymentService:
padding: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}}
/* Prevent iOS WebKit / Safari automatic data detector and link underlining */
a,
a[x-apple-data-detectors],
a[href^="mailto:"],
a[href^="tel:"] {{
color: inherit !important;
text-decoration: none !important;
font-size: inherit !important;
font-family: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
}}
body {{
background-color: #f8fafc;
color: #1e293b;
@ -596,8 +541,7 @@ class AdminPaymentService:
margin-bottom: 24px;
border: 1px solid #e2e8f0;
border-radius: 10px;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
overflow: hidden;
}}
table {{
width: 100%;
@ -658,73 +602,6 @@ class AdminPaymentService:
color: #94a3b8;
line-height: 1.6;
}}
.payment-id-val {{
word-break: break-all;
display: inline-block;
}}
@media (max-width: 640px) {{
body {{
padding: 12px 8px;
}}
.no-print-bar {{
flex-direction: column;
align-items: stretch;
gap: 12px;
padding: 12px 14px;
text-align: center;
}}
.no-print-actions {{
display: flex;
gap: 8px;
width: 100%;
}}
.no-print-actions .btn {{
flex: 1;
justify-content: center;
padding: 10px 8px;
font-size: 13px;
}}
.invoice-card {{
padding: 24px 16px;
border-radius: 12px;
}}
.header {{
flex-direction: column;
align-items: flex-start;
gap: 16px;
padding-bottom: 18px;
margin-bottom: 20px;
}}
.invoice-badge-box {{
text-align: left;
width: 100%;
}}
.grid-details {{
grid-template-columns: 1fr;
gap: 20px;
margin-bottom: 24px;
}}
.grid-payment-overview {{
text-align: left !important;
}}
.detail-text {{
word-break: break-word;
overflow-wrap: anywhere;
}}
.table-wrap table {{
min-width: 480px;
}}
th, td {{
padding: 10px 12px;
font-size: 13px;
}}
.summary-wrap {{
justify-content: stretch;
}}
.summary-card {{
width: 100%;
}}
}}
@media print {{
body {{
background-color: #ffffff !important;
@ -747,7 +624,7 @@ class AdminPaymentService:
<div style="font-size: 13px; color: #64748b; font-weight: 500;">
Acupedia Official Tax Invoice &bull; <strong>{inv_number}</strong>
</div>
<div class="no-print-actions" style="display: flex; gap: 8px;">
<div style="display: flex; gap: 8px;">
<button class="btn btn-secondary" onclick="window.close()">Close</button>
<button class="btn btn-primary" onclick="window.print()">
<svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
@ -779,11 +656,12 @@ class AdminPaymentService:
{f'<div class="detail-text">{cust_phone}</div>' if cust_phone else ''}
<div class="detail-text" style="color: #64748b; margin-top: 4px;">{cust_address}</div>
</div>
<div class="grid-payment-overview" style="text-align: right;">
<div style="text-align: right;">
<div class="section-label">Payment Overview</div>
<div class="detail-text">Payment ID: <span class="detail-strong payment-id-val" style="font-family: monospace;">{payment_id}</span></div>
<div class="detail-text">Gateway Reference: <span class="detail-strong" style="font-family: monospace;">{payment_id}</span></div>
<div class="detail-text">Payment Method: <span class="detail-strong">{pay_method}</span></div>
<div class="detail-text">Currency: <span class="detail-strong">{currency}</span></div>
<div class="detail-text">Status: <span class="detail-strong" style="color: #059669;">Completed / Captured</span></div>
</div>
</div>

View File

@ -1,12 +1,12 @@
from __future__ import annotations
from decimal import Decimal
from uuid import UUID
from sqlalchemy import delete, select, func
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, PlanType, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Module, UserSubscription
from ..schema import CreatePlanRequest, PlanPricingUpdateRequest, PlanStatusUpdateRequest
from .module_service import resolve_module_category, CATEGORY_UI_DEFAULTS, UI_MAPPINGS
from .module_service import UI_MAPPINGS
class AdminPlanService:
@ -28,15 +28,14 @@ class AdminPlanService:
if p_str not in plan_mods_map:
plan_mods_map[p_str] = []
meta = m.metadata_json or {}
category = resolve_module_category(meta)
ui_defaults = CATEGORY_UI_DEFAULTS.get(category, CATEGORY_UI_DEFAULTS["General"])
ui = UI_MAPPINGS.get(m.slug, {})
plan_mods_map[p_str].append({
"id": str(m.id),
"slug": m.slug,
"name": m.name,
"category": category,
"icon": meta.get("icon") or ui_defaults["icon"],
"color": meta.get("color") or ui_defaults["color"],
"category": meta.get("category") or ui.get("category", "General"),
"icon": meta.get("icon") or ui.get("icon", "book-outline"),
"color": meta.get("color") or ui.get("color", "#6366F1"),
"is_active": m.is_active,
})
@ -51,11 +50,7 @@ class AdminPlanService:
for p in all_plans:
code = p.code
is_usd = code.endswith("_USD") or p.currency_code == "USD"
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
if code.endswith("_USD") or code.endswith("_EUR"):
base_code = code[:-4]
else:
base_code = code
base_code = code[:-4] if code.endswith("_USD") else code
p_str = str(p.id)
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
meta = p.metadata_json or {}
@ -63,7 +58,7 @@ class AdminPlanService:
if base_code not in groups:
groups[base_code] = {
"base_code": base_code,
"name": p.name.replace(" (USD)", "").replace(" - USD", "").replace(" (EUR)", "").replace(" - EUR", ""),
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
"description": p.description or "",
"plan_type": getattr(p.plan_type, "value", p.plan_type),
"billing_period": getattr(p.billing_period, "value", p.billing_period),
@ -74,10 +69,8 @@ class AdminPlanService:
"subtitle": meta.get("subtitle"),
"inr_plan_id": None,
"usd_plan_id": None,
"eur_plan_id": None,
"price_inr": 0.0,
"price_usd": 0.0,
"price_eur": 0.0,
"modules": [],
"module_ids": [],
"subscribers_count": 0,
@ -88,9 +81,6 @@ class AdminPlanService:
if is_usd:
grp["usd_plan_id"] = p_str
grp["price_usd"] = fee
elif is_eur:
grp["eur_plan_id"] = p_str
grp["price_eur"] = fee
else:
grp["inr_plan_id"] = p_str
grp["price_inr"] = fee
@ -109,8 +99,6 @@ class AdminPlanService:
grp["heading"] = meta.get("heading")
if meta.get("subtitle"):
grp["subtitle"] = meta.get("subtitle")
if meta.get("pricing_status"):
grp["pricing_status"] = meta.get("pricing_status")
grp["subscribers_count"] += sub_counts.get(p_str, 0)
mods = plan_mods_map.get(p_str, [])
@ -118,11 +106,6 @@ class AdminPlanService:
grp["modules"] = mods
grp["module_ids"] = [m["id"] for m in mods]
# Fallback EUR price to USD price if EUR row not yet created
for grp in groups.values():
if not grp["price_eur"] and grp["price_usd"]:
grp["price_eur"] = grp["price_usd"]
res = list(groups.values())
def sort_key(item: dict) -> tuple[int, str]:
if "LIFETIME" in item["base_code"]:
@ -139,7 +122,7 @@ class AdminPlanService:
raise ValueError("Plan code cannot be empty.")
existing = (await self.session.execute(
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
select(AccessPlan.id).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
)).scalar_one_or_none()
if existing:
raise ValueError(f"Plan code '{base_code}' already exists.")
@ -184,22 +167,6 @@ class AdminPlanService:
metadata_json=meta,
)
self.session.add(usd_plan)
eur_price = payload.price_eur if payload.price_eur is not None else payload.price_usd
eur_plan = AccessPlan(
code=f"{base_code}_EUR",
name=f"{payload.name} (EUR)",
description=payload.description or "",
plan_type=p_type,
billing_period=b_period,
member_fee=Decimal(0),
module_fee=Decimal(str(eur_price)),
currency_code="EUR",
country="European Union",
is_active=True,
metadata_json=meta,
)
self.session.add(eur_plan)
await self.session.flush()
for mid_str in payload.module_ids:
@ -207,82 +174,35 @@ class AdminPlanService:
mid = UUID(mid_str)
self.session.add(AccessPlanModule(plan_id=inr_plan.id, module_id=mid))
self.session.add(AccessPlanModule(plan_id=usd_plan.id, module_id=mid))
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
except Exception:
pass
await self.session.commit()
return {
"status": "success",
"message": f"Plan '{payload.name}' created successfully with INR, USD, and EUR tiers.",
"message": f"Plan '{payload.name}' created successfully with INR and USD tiers.",
"base_code": base_code,
"inr_plan_id": str(inr_plan.id),
"usd_plan_id": str(usd_plan.id),
"eur_plan_id": str(eur_plan.id),
}
async def update_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
base_code = plan_code.strip().upper()
plans = (await self.session.execute(
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
)).scalars().all()
if not plans:
raise LookupError(f"No access plans found matching code '{base_code}'.")
eur_plan = next((p for p in plans if p.code == f"{base_code}_EUR" or p.currency_code == "EUR"), None)
inr_plan = next((p for p in plans if p.code == base_code or p.currency_code == "INR"), plans[0])
usd_plan = next((p for p in plans if p.code == f"{base_code}_USD" or p.currency_code == "USD"), None)
eur_price = payload.price_eur if payload.price_eur is not None else (
payload.price_usd if payload.price_usd is not None else (float(usd_plan.module_fee) if usd_plan else None)
)
if eur_plan is None and eur_price is not None:
meta = dict(inr_plan.metadata_json or {})
if payload.badge_text is not None:
meta["badge_text"] = payload.badge_text
if payload.heading is not None:
meta["heading"] = payload.heading
if payload.subtitle is not None:
meta["subtitle"] = payload.subtitle
eur_plan = AccessPlan(
code=f"{base_code}_EUR",
name=f"{payload.name or inr_plan.name} (EUR)",
description=payload.description if payload.description is not None else inr_plan.description,
plan_type=inr_plan.plan_type,
billing_period=inr_plan.billing_period,
member_fee=Decimal(0),
module_fee=Decimal(str(eur_price)),
currency_code="EUR",
country="European Union",
is_active=inr_plan.is_active,
metadata_json=meta,
)
self.session.add(eur_plan)
await self.session.flush()
mod_ids = (await self.session.execute(
select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == inr_plan.id)
)).scalars().all()
for mid in mod_ids:
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
plans.append(eur_plan)
for p in plans:
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
is_eur = p.code.endswith("_EUR") or p.currency_code == "EUR"
if is_eur and payload.price_eur is not None:
p.module_fee = Decimal(str(payload.price_eur))
elif is_usd and payload.price_usd is not None:
if is_usd and payload.price_usd is not None:
p.module_fee = Decimal(str(payload.price_usd))
elif not is_usd and not is_eur and payload.price_inr is not None:
elif not is_usd and payload.price_inr is not None:
p.module_fee = Decimal(str(payload.price_inr))
if payload.name:
suffix = " (EUR)" if is_eur else (" (USD)" if is_usd else "")
p.name = f"{payload.name}{suffix}"
p.name = f"{payload.name} (USD)" if is_usd else payload.name
if payload.description is not None:
p.description = payload.description
@ -293,47 +213,19 @@ class AdminPlanService:
meta["heading"] = payload.heading
if payload.subtitle is not None:
meta["subtitle"] = payload.subtitle
if float(p.module_fee or 0) > 0:
meta["pricing_status"] = "configured"
p.metadata_json = meta
if payload.module_ids is not None:
plan_ids = [p.id for p in plans]
await self.session.execute(
delete(AccessPlanModule).where(AccessPlanModule.plan_id.in_(plan_ids))
)
seen_mids: list[UUID] = []
for mid_str in payload.module_ids:
try:
mid = UUID(mid_str)
except Exception:
continue
if mid not in seen_mids:
seen_mids.append(mid)
for p in plans:
for mid in seen_mids:
self.session.add(AccessPlanModule(plan_id=p.id, module_id=mid))
await self.session.commit()
return {"status": "success", "message": f"Pricing and metadata for plan '{base_code}' updated successfully."}
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
base_code = plan_code.strip().upper()
plans = (await self.session.execute(
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"]))
select(AccessPlan).where(AccessPlan.code.in_([base_code, f"{base_code}_USD"]))
)).scalars().all()
if not plans:
raise LookupError(f"No access plans found matching code '{base_code}'.")
if is_active:
has_pending = any((p.metadata_json or {}).get("pricing_status") == "pending_pricing" for p in plans)
has_positive_price = any(float(p.module_fee or 0) > 0 for p in plans)
is_free = any((p.metadata_json or {}).get("is_free") is True for p in plans)
if has_pending or (not has_positive_price and not is_free):
raise ValueError(
"Cannot activate plan before pricing is configured. Please set INR/USD/EUR prices via Edit Info & Price first."
)
for p in plans:
p.is_active = is_active
await self.session.commit()
@ -342,67 +234,3 @@ class AdminPlanService:
"message": f"Plan '{base_code}' has been {'activated' if is_active else 'deactivated'}.",
"is_active": is_active,
}
async def ensure_pending_pricing_plan_for_module(self, module_code: str) -> str | None:
"""Auto-create an inactive 'pending_pricing' single-module plan if none exists."""
clean_code = module_code.strip()
module = (
await self.session.execute(
select(Module).where(func.lower(Module.code) == clean_code.lower())
)
).scalar_one_or_none()
if module is None:
return None
# Check if module already belongs to any single-module one_time plan
existing_links = (
await self.session.execute(
select(AccessPlan)
.join(AccessPlanModule, AccessPlanModule.plan_id == AccessPlan.id)
.where(
AccessPlanModule.module_id == module.id,
AccessPlan.plan_type == PlanType.ONE_TIME,
)
)
).scalars().all()
if existing_links:
return None
base_code = f"MOD_{clean_code.upper()}"
existing_code = (
await self.session.execute(
select(AccessPlan.id).where(
AccessPlan.code.in_([base_code, f"{base_code}_USD", f"{base_code}_EUR"])
)
)
).scalars().first()
if existing_code:
return base_code
meta = {"pricing_status": "pending_pricing"}
desc = module.description or ""
tiers = [
(base_code, module.name, "INR", "India"),
(f"{base_code}_USD", f"{module.name} (USD)", "USD", "International"),
(f"{base_code}_EUR", f"{module.name} (EUR)", "EUR", "European Union"),
]
for code, name, currency, country in tiers:
plan = AccessPlan(
code=code,
name=name,
description=desc,
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
member_fee=Decimal(0),
module_fee=Decimal(0),
currency_code=currency,
country=country,
is_active=False,
metadata_json=dict(meta),
)
self.session.add(plan)
await self.session.flush()
self.session.add(AccessPlanModule(plan_id=plan.id, module_id=module.id))
await self.session.commit()
return base_code

View File

@ -3,20 +3,9 @@ import csv
import io
from datetime import datetime, timezone
from fastapi.responses import StreamingResponse
from sqlalchemy import func, select
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import PaymentStatus, SubscriptionStatus
from app.db.models import (
AccessPlan,
AppUser,
Coupon,
CouponRedemption,
Invoice,
PaymentTransaction,
Role,
UserRole,
UserSubscription,
)
from app.db.models import AccessPlan, AppUser, Coupon, Invoice, PaymentTransaction, UserSubscription
class AdminReportService:
@ -37,95 +26,15 @@ class AdminReportService:
if e_dt:
q = q.where(AppUser.created_at <= e_dt)
users = (await self.session.execute(q)).scalars().all()
# Preload user roles
user_roles_map: dict[any, list[str]] = {}
ur_rows = (await self.session.execute(
select(UserRole.user_id, Role.role_name).join(Role, Role.id == UserRole.role_id)
)).all()
for uid, rname in ur_rows:
user_roles_map.setdefault(uid, []).append(rname)
# Preload spend and orders count by currency
tx_summary_rows = (await self.session.execute(
select(
PaymentTransaction.user_id,
PaymentTransaction.currency,
func.count(PaymentTransaction.id),
func.coalesce(func.sum(PaymentTransaction.amount), 0)
)
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
.group_by(PaymentTransaction.user_id, PaymentTransaction.currency)
)).all()
tx_orders: dict[any, int] = {}
tx_spend: dict[any, dict[str, float]] = {}
for uid, curr, count, total in tx_summary_rows:
tx_orders[uid] = tx_orders.get(uid, 0) + count
c_up = (curr or "INR").upper()
tx_spend.setdefault(uid, {})[c_up] = tx_spend.get(uid, {}).get(c_up, 0.0) + float(total)
# Preload active subscriptions count
sub_count_rows = (await self.session.execute(
select(
UserSubscription.user_id,
func.count(UserSubscription.id)
)
.where(UserSubscription.status == SubscriptionStatus.ACTIVE)
.group_by(UserSubscription.user_id)
)).all()
sub_count_map = {uid: count for uid, count in sub_count_rows}
writer.writerow([
"Customer ID",
"Full Name",
"Email Address",
"Phone Number",
"Country",
"Account Type",
"Status",
"Total Orders",
"Lifetime Spend (INR)",
"Lifetime Spend (USD)",
"Lifetime Spend (EUR)",
"Active Subscriptions",
"Registration Date",
])
writer.writerow(["ID", "Email", "Display Name", "Phone Number", "Country", "Active", "Created At"])
for u in users:
user_roles = user_roles_map.get(u.id, [])
user_type = "Admin" if any("admin" in str(r).lower() for r in user_roles) else "Practitioner"
orders_count = tx_orders.get(u.id, 0)
u_spend = tx_spend.get(u.id, {})
spend_inr = u_spend.get("INR", 0.0)
spend_usd = u_spend.get("USD", 0.0)
spend_eur = u_spend.get("EUR", 0.0)
active_subs = sub_count_map.get(u.id, 0)
status_label = "Active" if u.is_active else "Suspended"
reg_date = u.created_at.strftime("%Y-%m-%d %H:%M:%S") if u.created_at else ""
writer.writerow([
str(u.id),
u.display_name or "",
u.email,
u.phone_number or "",
u.country or "",
user_type,
status_label,
orders_count,
f"{spend_inr:.2f}",
f"{spend_usd:.2f}",
f"{spend_eur:.2f}",
active_subs,
reg_date,
])
writer.writerow([str(u.id), u.email, u.display_name or "", u.phone_number or "", u.country, u.is_active, u.created_at.isoformat() if u.created_at else ""])
elif report_type == "payments":
q = (
select(PaymentTransaction, Invoice, AppUser, UserSubscription, AccessPlan, Coupon)
select(PaymentTransaction, Invoice, AppUser)
.join(Invoice, Invoice.payment_transaction_id == PaymentTransaction.id, isouter=True)
.join(AppUser, AppUser.id == PaymentTransaction.user_id, isouter=True)
.join(UserSubscription, UserSubscription.id == PaymentTransaction.subscription_id, isouter=True)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
.join(Coupon, Coupon.id == Invoice.applied_coupon_id, isouter=True)
.order_by(PaymentTransaction.created_at.desc())
)
if s_dt:
@ -133,53 +42,21 @@ class AdminReportService:
if e_dt:
q = q.where(PaymentTransaction.created_at <= e_dt)
rows = (await self.session.execute(q)).all()
writer.writerow([
"Payment ID",
"Invoice Number",
"Customer Name",
"Customer Email",
"Phone Number",
"Country",
"Plan Code",
"Plan Name",
"Base Price",
"Discount Amount",
"Coupon Code",
"Net Paid",
"Currency",
"Status",
"Payment Date",
])
for t, inv, u, sub, plan, cpn in rows:
base_price = float(inv.base_amount) if inv and inv.base_amount is not None else float(t.amount)
discount_amt = float(inv.discount_amount) if inv and inv.discount_amount is not None else 0.0
coupon_code = cpn.code if cpn else (inv.applied_coupon.code if inv and getattr(inv, "applied_coupon", None) else "")
plan_code = plan.code if plan else ""
plan_name = plan.name if plan else ""
net_paid = float(t.amount)
pay_date = t.created_at.strftime("%Y-%m-%d %H:%M:%S") if t.created_at else ""
writer.writerow(["ID", "Gateway ID", "User Email", "User Name", "Amount", "Currency", "Status", "Invoice Number", "Created At"])
for t, inv, u in rows:
writer.writerow([
t.gateway_transaction_id or str(t.id),
inv.invoice_number if inv else "",
u.display_name if u else (inv.billing_name if inv else ""),
u.email if u else (inv.billing_email if inv else ""),
u.phone_number if u else "",
u.country if u else "",
plan_code,
plan_name,
f"{base_price:.2f}",
f"{discount_amt:.2f}",
coupon_code or "None",
f"{net_paid:.2f}",
str(t.id),
t.gateway_transaction_id,
u.email if u else "",
u.display_name if u else "",
float(t.amount),
t.currency,
getattr(t.status, "value", t.status),
pay_date,
inv.invoice_number if inv else "",
t.created_at.isoformat() if t.created_at else "",
])
elif report_type == "subscriptions":
now = datetime.now(timezone.utc)
q = (
select(UserSubscription, AccessPlan, AppUser)
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
@ -191,196 +68,42 @@ class AdminReportService:
if e_dt:
q = q.where(UserSubscription.started_at <= e_dt)
rows = (await self.session.execute(q)).all()
writer.writerow([
"Subscription ID",
"Customer Name",
"Customer Email",
"Phone Number",
"Customer Country",
"Plan Code",
"Plan Name",
"Plan Currency",
"Billing Cycle",
"Status",
"Days Remaining",
"Auto Renew",
"Activation Date",
"Expiry Date",
"Payment Reference",
])
writer.writerow(["ID", "User Email", "User Name", "Plan Code", "Plan Name", "Status", "Started At", "Expires At", "Payment Reference"])
for s, p, u in rows:
billing_cycle = ""
if p and p.billing_period:
billing_cycle = getattr(p.billing_period, "value", str(p.billing_period)).capitalize()
elif hasattr(s, "billing_period") and s.billing_period:
billing_cycle = getattr(s.billing_period, "value", str(s.billing_period)).capitalize()
else:
billing_cycle = "Yearly"
plan_curr = "INR"
if p:
if getattr(p, "currency", None):
plan_curr = str(p.currency).upper()
elif p.code:
code_up = p.code.upper()
if code_up.endswith("_EUR"):
plan_curr = "EUR"
elif code_up.endswith("_USD"):
plan_curr = "USD"
days_remaining = "Lifetime"
if s.expires_at:
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
delta = (exp - now).days
if delta >= 0:
days_remaining = f"{delta} days left"
else:
days_remaining = f"Expired ({abs(delta)} days ago)"
auto_renew = "Yes" if getattr(s, "auto_renew", False) else "No"
started = s.started_at.strftime("%Y-%m-%d %H:%M:%S") if s.started_at else ""
expires = s.expires_at.strftime("%Y-%m-%d %H:%M:%S") if s.expires_at else "Lifetime"
writer.writerow([
str(s.id),
u.display_name if u else "",
u.email if u else "",
u.phone_number if u else "",
u.country if u else "",
u.display_name if u else "",
p.code if p else "",
p.name if p else "",
plan_curr,
billing_cycle,
getattr(s.status, "value", s.status),
days_remaining,
auto_renew,
started,
expires,
s.started_at.isoformat() if s.started_at else "",
s.expires_at.isoformat() if s.expires_at else "",
s.payment_reference or "",
])
elif report_type == "coupons":
now = datetime.now(timezone.utc)
q = select(Coupon).order_by(Coupon.created_at.desc())
if s_dt:
q = q.where(Coupon.created_at >= s_dt)
if e_dt:
q = q.where(Coupon.created_at <= e_dt)
coupons = (await self.session.execute(q)).scalars().all()
redemptions_q = await self.session.execute(
select(CouponRedemption.coupon_id, func.count(CouponRedemption.id))
.group_by(CouponRedemption.coupon_id)
)
redemption_counts = {cid: cnt for cid, cnt in redemptions_q.all()}
writer.writerow([
"Coupon Code",
"Category",
"Description",
"Discount Type",
"Discount (INR)",
"Discount (USD)",
"Discount (EUR)",
"Max Cap (INR)",
"Max Cap (USD)",
"Max Cap (EUR)",
"Min Purchase (INR)",
"Min Purchase (USD)",
"Min Purchase (EUR)",
"Usage Count",
"Usage Limit",
"Remaining Uses",
"Schedule Status",
"Start Date",
"End Date",
])
writer.writerow(["ID", "Code", "Discount Type", "Category", "Value", "Max Limit", "Min Purchase", "Usage Limit", "Usage Count", "Active", "Start Date", "End Date"])
for c in coupons:
metadata = getattr(c, "metadata_json", {}) if hasattr(c, "metadata_json") else {}
if not isinstance(metadata, dict):
metadata = {}
c_values = metadata.get("currency_values") or {}
c_caps = metadata.get("currency_caps") or {}
c_mins = metadata.get("currency_min_spends") or {}
val_base = float(c.value) if c.value is not None else 0.0
is_pct = c.discount_type in {"percentage", "percent"}
if is_pct:
disc_inr = f"{val_base:.2f}%"
disc_usd = f"{val_base:.2f}%"
disc_eur = f"{val_base:.2f}%"
cap_inr_num = float(c_caps.get("INR", c.max_discount_limit or 0.0))
cap_usd_num = float(c_caps.get("USD", 0.0)) if "USD" in c_caps and c_caps["USD"] is not None else None
cap_eur_num = float(c_caps.get("EUR", 0.0)) if "EUR" in c_caps and c_caps["EUR"] is not None else None
cap_inr = f"₹{cap_inr_num:.2f}" if cap_inr_num > 0 else "None"
cap_usd = f"${cap_usd_num:.2f}" if cap_usd_num and cap_usd_num > 0 else "None"
cap_eur = f"€{cap_eur_num:.2f}" if cap_eur_num and cap_eur_num > 0 else "None"
else:
v_inr = float(c_values.get("INR", val_base))
v_usd = float(c_values["USD"]) if "USD" in c_values and c_values["USD"] is not None else None
v_eur = float(c_values["EUR"]) if "EUR" in c_values and c_values["EUR"] is not None else None
disc_inr = f"₹{v_inr:.2f}"
disc_usd = f"${v_usd:.2f}" if v_usd is not None else "—"
disc_eur = f"€{v_eur:.2f}" if v_eur is not None else "—"
cap_inr = "N/A (Flat)"
cap_usd = "N/A (Flat)"
cap_eur = "N/A (Flat)"
min_inr_num = float(c_mins.get("INR", c.min_purchase_amount or 0.0))
min_usd_num = float(c_mins.get("USD", 0.0)) if "USD" in c_mins and c_mins["USD"] is not None else None
min_eur_num = float(c_mins.get("EUR", 0.0)) if "EUR" in c_mins and c_mins["EUR"] is not None else None
min_inr = f"₹{min_inr_num:.2f}" if min_inr_num > 0 else "0.00"
min_usd = f"${min_usd_num:.2f}" if min_usd_num and min_usd_num > 0 else "0.00"
min_eur = f"€{min_eur_num:.2f}" if min_eur_num and min_eur_num > 0 else "0.00"
usage_count = max(c.usage_count or 0, redemption_counts.get(c.id, 0))
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
remaining_str = "Unlimited"
if c.usage_limit:
rem = max(0, c.usage_limit - usage_count)
remaining_str = f"{rem} left"
schedule_status = "Active"
if not c.is_active:
schedule_status = "Inactive"
elif c.start_date and c.start_date > now:
schedule_status = "Scheduled"
elif c.end_date and c.end_date < now:
schedule_status = "Expired"
elif c.usage_limit and usage_count >= c.usage_limit:
schedule_status = "Fully Redeemed"
start_str = c.start_date.strftime("%Y-%m-%d") if c.start_date else "Immediate"
end_str = c.end_date.strftime("%Y-%m-%d") if c.end_date else "No Expiry"
writer.writerow([
str(c.id),
c.code,
(c.coupon_category or "general").title(),
c.description or "",
(c.discount_type or "").capitalize(),
disc_inr,
disc_usd,
disc_eur,
cap_inr,
cap_usd,
cap_eur,
min_inr,
min_usd,
min_eur,
usage_count,
usage_limit_str,
remaining_str,
schedule_status,
start_str,
end_str,
c.discount_type,
c.coupon_category,
float(c.value),
float(c.max_discount_limit or 0),
float(c.min_purchase_amount or 0),
c.usage_limit,
c.usage_count,
c.is_active,
c.start_date.isoformat() if c.start_date else "",
c.end_date.isoformat() if c.end_date else "",
])
else:
raise ValueError(f"Unknown report type: '{report_type}'. Supported: customers, payments, subscriptions, coupons.")

View File

@ -14,7 +14,6 @@ from .errors import (
InvalidOrExpiredOtpError,
InvalidPhoneNumberError,
InvalidTokenError,
SamePasswordError,
UnauthorizedError,
UserAlreadyExistsError,
UserInactiveError,
@ -76,7 +75,6 @@ def _translate_auth_error(exc: Exception) -> HTTPException:
WeakPasswordError,
UserAlreadyExistsError,
CurrentPasswordIncorrectError,
SamePasswordError,
),
):
return HTTPException(

View File

@ -45,9 +45,5 @@ class CurrentPasswordIncorrectError(AuthError):
pass
class SamePasswordError(AuthError):
pass
class InvalidOrExpiredOtpError(AuthError):
pass

View File

@ -3,7 +3,7 @@ from __future__ import annotations
from datetime import datetime
from uuid import UUID
from sqlalchemy import func, or_, select, update
from sqlalchemy import select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import (
@ -42,54 +42,15 @@ class AuthRepository:
self,
phone_number: str,
) -> AppUser | None:
# Preserves the existing auth API's LIKE lookup semantics.
result = await self._session.execute(
select(AppUser)
.where(AppUser.phone_number == phone_number)
.where(AppUser.phone_number.like(f"%{phone_number}%"))
.order_by(AppUser.id.asc())
.limit(1)
)
return result.scalar_one_or_none()
async def find_users_by_phone_candidates(
self,
*,
exact_values: tuple[str, ...],
suffix_digits: tuple[str, ...],
limit: int = 20,
) -> list[AppUser]:
"""Return candidate users matching exact phone strings or national digit suffixes."""
if not exact_values and not suffix_digits:
return []
cleaned_db_phone = func.replace(
func.replace(
func.replace(
func.replace(AppUser.phone_number, " ", ""),
"-",
"",
),
"(",
"",
),
")",
"",
)
predicates = []
if exact_values:
predicates.append(AppUser.phone_number.in_(exact_values))
predicates.append(cleaned_db_phone.in_(exact_values))
for suffix in suffix_digits:
predicates.append(cleaned_db_phone.endswith(suffix))
result = await self._session.execute(
select(AppUser)
.where(AppUser.phone_number.is_not(None), or_(*predicates))
.order_by(AppUser.id.asc())
.limit(limit)
)
return list(result.scalars().all())
async def create_user(
self,
*,

View File

@ -7,7 +7,6 @@ import json
import os
import re
import secrets
import string
import time
from typing import Any
@ -19,40 +18,7 @@ from .errors import InvalidEmailError, InvalidTokenError, WeakPasswordError
DEFAULT_JWT_SECRET = "panacea-secret-key-for-jwt-token-generation"
JWT_SECRET = os.getenv("JWT_SECRET", DEFAULT_JWT_SECRET)
JWT_TTL_SECONDS = int(os.getenv("JWT_TTL_SECONDS", str(86400 * 7)))
EMAIL_REGEX = re.compile(
r"^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$"
)
MIN_NATIONAL_PHONE_DIGITS = 6
# Prefix-free ITU-T E.164 country calling codes (1 to 3 digits).
ITU_CALLING_CODES: frozenset[str] = frozenset({
"1", "7",
"20", "27", "30", "31", "32", "33", "34", "36", "39", "40", "41", "43",
"44", "45", "46", "47", "48", "49", "51", "52", "53", "54", "55", "56",
"57", "58", "60", "61", "62", "63", "64", "65", "66", "81", "82", "84",
"86", "90", "91", "92", "93", "94", "95", "98",
"211", "212", "213", "216", "218",
"220", "221", "222", "223", "224", "225", "226", "227", "228", "229",
"230", "231", "232", "233", "234", "235", "236", "237", "238", "239",
"240", "241", "242", "243", "244", "245", "246", "247", "248", "249",
"250", "251", "252", "253", "254", "255", "256", "257", "258",
"260", "261", "262", "263", "264", "265", "266", "267", "268", "269",
"290", "291", "297", "298", "299",
"350", "351", "352", "353", "354", "355", "356", "357", "358", "359",
"370", "371", "372", "373", "374", "375", "376", "377", "378", "379",
"380", "381", "382", "383", "385", "386", "387", "389",
"420", "421", "423",
"500", "501", "502", "503", "504", "505", "506", "507", "508", "509",
"590", "591", "592", "593", "594", "595", "596", "597", "598", "599",
"670", "672", "673", "674", "675", "676", "677", "678", "679",
"680", "681", "682", "683", "685", "686", "687", "688", "689",
"690", "691", "692",
"850", "852", "853", "855", "856", "880", "886",
"960", "961", "962", "963", "964", "965", "966", "967", "968",
"970", "971", "972", "973", "974", "975", "976", "977",
"992", "993", "994", "995", "996", "998",
})
EMAIL_REGEX = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
def base64url_encode(data: bytes) -> str:
@ -77,86 +43,6 @@ def normalize_phone_number(value: str | None) -> str:
return value.strip() if value else ""
def extract_phone_digits(value: str | None) -> str:
"""Return only ASCII digits from a phone string."""
if not value:
return ""
return "".join(ch for ch in value if ch.isdigit())
def _split_e164_digits(digits: str, local: str) -> bool:
"""Return True when ``digits`` equals ``<ITU_CALLING_CODE><local>``."""
if len(local) < MIN_NATIONAL_PHONE_DIGITS or len(digits) <= len(local):
return False
if not digits.endswith(local):
return False
prefix = digits[: -len(local)]
return prefix in ITU_CALLING_CODES
def build_phone_lookup_variants(
value: str | None,
) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""Build exact equality values and national suffix digits for login phone lookup."""
stripped = normalize_phone_number(value)
if not stripped:
return (), ()
digits = extract_phone_digits(stripped)
compact = re.sub(r"[\s\-()]+", "", stripped)
exact_candidates: list[str] = []
for candidate in (stripped, compact, f"+{digits}" if digits else ""):
if candidate and candidate not in exact_candidates:
exact_candidates.append(candidate)
suffix_candidates: list[str] = []
if digits and not stripped.startswith("+"):
national = digits.lstrip("0") or digits
for suffix in (digits, national):
if len(suffix) >= MIN_NATIONAL_PHONE_DIGITS and suffix not in suffix_candidates:
suffix_candidates.append(suffix)
return tuple(exact_candidates), tuple(suffix_candidates)
def matches_login_phone(
stored_phone: str | None,
login_phone: str | None,
) -> bool:
"""
Determine whether ``stored_phone`` represents the same phone number as ``login_phone``.
Supports E.164 stored values (e.g. ``+917796701290``) when a user logs in
with a local/national number without a country code (e.g. ``7796701290`` or
``07796701290``), while rejecting partial-digit suffix collisions via prefix-free
ITU calling-code boundary checks.
"""
login_raw = normalize_phone_number(login_phone)
stored_raw = normalize_phone_number(stored_phone)
login_digits = extract_phone_digits(login_raw)
stored_digits = extract_phone_digits(stored_raw)
if not login_digits or not stored_digits:
return False
if login_raw.startswith("+"):
return stored_digits == login_digits
if stored_digits == login_digits:
return True
national = login_digits.lstrip("0") or login_digits
for candidate_local in (login_digits, national):
if _split_e164_digits(stored_digits, candidate_local):
return True
if not stored_raw.startswith("+"):
return _split_e164_digits(login_digits, stored_digits)
return False
def validate_password_strength(password: str) -> None:
if len(password) < 8:
raise WeakPasswordError(
@ -170,7 +56,7 @@ def validate_password_strength(password: str) -> None:
raise WeakPasswordError(
"Password must contain at least one number."
)
if not any(c in string.punctuation for c in password):
if not any(not c.isalnum() and not c.isspace() for c in password):
raise WeakPasswordError(
"Password must contain at least one special character."
)

View File

@ -8,13 +8,10 @@ from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.concurrency import run_in_threadpool
from app.db.models import AppUser
from .errors import (
CurrentPasswordIncorrectError,
InvalidCredentialsError,
InvalidOrExpiredOtpError,
SamePasswordError,
UnauthorizedError,
UserAlreadyExistsError,
UserInactiveError,
@ -37,13 +34,10 @@ from .schema import (
UserRegisterRequest,
)
from .security import (
build_phone_lookup_variants,
create_access_token,
decode_access_token,
extract_phone_digits,
generate_otp_code,
hash_password,
matches_login_phone,
normalize_email,
normalize_phone_number,
validate_password_strength,
@ -140,76 +134,17 @@ class AuthService:
),
)
@staticmethod
def _verify_active_user_credentials(user: AppUser, password: str) -> AppUser:
if not user.is_active:
raise UserInactiveError("Account is deactivated.")
if not verify_password(password, user.password_hash):
raise InvalidCredentialsError("Incorrect password. Please try again.")
return user
async def _authenticate_phone_login(
self,
phone_number: str,
password: str,
) -> AppUser:
exact_values, suffix_digits = build_phone_lookup_variants(phone_number)
if not exact_values:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
raw_candidates = await self.repository.find_users_by_phone_candidates(
exact_values=exact_values,
suffix_digits=suffix_digits,
)
matched = [
candidate
for candidate in raw_candidates
if matches_login_phone(candidate.phone_number, phone_number)
]
if not matched:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
login_digits = extract_phone_digits(phone_number)
exact_matched = [
candidate
for candidate in matched
if extract_phone_digits(candidate.phone_number) == login_digits
]
candidates = exact_matched or matched
if len(candidates) == 1:
return self._verify_active_user_credentials(candidates[0], password)
active_candidates = [candidate for candidate in candidates if candidate.is_active]
if not active_candidates:
raise UserInactiveError("Account is deactivated.")
verified_users = [
candidate
for candidate in active_candidates
if verify_password(password, candidate.password_hash)
]
if not verified_users:
raise InvalidCredentialsError("Incorrect password. Please try again.")
if len(verified_users) > 1:
raise InvalidCredentialsError(
"Multiple accounts share this phone number. Please log in with your email address."
)
return verified_users[0]
async def login(
self,
request: UserLoginRequest,
) -> AuthTokenResponse:
if request.phone_number:
user = await self._authenticate_phone_login(
request.phone_number,
request.password,
)
phone = normalize_phone_number(request.phone_number)
user = await self.repository.get_user_by_phone(phone)
if user is None:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
else:
assert request.email is not None
email = normalize_email(request.email)
@ -218,7 +153,14 @@ class AuthService:
raise UserNotFoundError(
"No account found with this email address. Please sign up first."
)
user = self._verify_active_user_credentials(user, request.password)
if not user.is_active:
raise UserInactiveError("Account is deactivated.")
if not verify_password(request.password, user.password_hash):
raise InvalidCredentialsError(
"Incorrect password. Please try again."
)
roles = await self.repository.get_user_roles(user.id)
if not roles:
@ -279,13 +221,6 @@ class AuthService:
)
country = request.country.strip() if request.country else None
if phone:
existing_user = await self.repository.get_user_by_phone(phone)
if existing_user is not None and str(existing_user.id) != str(user_id):
raise UserAlreadyExistsError(
"An account with this phone number already exists."
)
user = await self.repository.update_profile(
user_id=user_id,
display_name=full_name,
@ -295,24 +230,6 @@ class AuthService:
if user is None:
raise UserNotFoundError("User not found.")
# Keep default user billing profile in sync with updated contact info
from app.db.models import UserBillingProfile
from sqlalchemy import update
bp_values: dict[str, object] = {}
if full_name:
bp_values["billing_name"] = full_name
if phone:
bp_values["billing_phone"] = phone
if country:
bp_values["country"] = country
if bp_values:
await self.session.execute(
update(UserBillingProfile)
.where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
.values(**bp_values)
)
await self.session.flush()
roles = await self.repository.get_user_roles(user.id)
if not roles:
roles = [PRACTITIONER_ROLE]
@ -343,14 +260,6 @@ class AuthService:
"Current password is incorrect. Please enter your valid current password."
)
if (
request.old_password == request.new_password
or verify_password(request.new_password, user.password_hash)
):
raise SamePasswordError(
"New password cannot be the same as current password."
)
validate_password_strength(request.new_password)
await self.repository.update_password_hash(

View File

@ -2,10 +2,10 @@ from __future__ import annotations
from datetime import datetime, timezone
from decimal import Decimal
from uuid import UUID
from sqlalchemy import func, select
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import EntitlementStatus, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, Coupon, CouponRedemption, Module, UserEntitlement, UserSubscription
from app.db.models import AccessPlan, Coupon, Module, UserEntitlement, UserSubscription
from app.features.payments.pricing import PricingCoupon, PricingItem
class CartRepository:
@ -25,292 +25,51 @@ class CartRepository:
if code.startswith("THERAPEUTIC"): return "Therapeutics"
return str(metadata.get("access_group") or "General")
async def get_plan_matches(self, codes: list[str], currency: str) -> dict[str, tuple[AccessPlan, Decimal]]:
curr = currency.strip().upper()
async def get_items(self, codes: list[str], currency: str) -> list[PricingItem]:
normalized = [c.strip().upper() for c in codes if c.strip()]
if not normalized:
return {}
curr_rows = (await self.session.execute(
select(AccessPlan.currency_code).where(AccessPlan.is_active.is_(True)).distinct()
)).scalars().all()
known_currencies = {c.upper() for c in curr_rows if c}
known_currencies.add(curr)
candidates: set[str] = set()
code_candidates_map: dict[str, list[str]] = {}
for code in normalized:
cands: list[str] = []
base = code
parts = code.rsplit("_", 1)
if len(parts) == 2 and parts[1] in known_currencies:
base = parts[0]
for cand in [f"{base}_{curr}", f"{base}_USD" if curr == "EUR" else None, code, base]:
if cand and cand not in cands:
cands.append(cand)
code_candidates_map[code] = cands
candidates.update(cands)
rows = (await self.session.execute(
select(AccessPlan).where(AccessPlan.code.in_(candidates), AccessPlan.is_active.is_(True))
)).scalars().all()
rows = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_(normalized), AccessPlan.is_active.is_(True)))).scalars().all()
by_code = {p.code.upper(): p for p in rows}
matches: dict[str, tuple[AccessPlan, Decimal]] = {}
for code in normalized:
cands = code_candidates_map[code]
for cand in cands:
plan = by_code.get(cand)
if not plan:
continue
metadata = plan.metadata_json or {}
prices = metadata.get("prices") if isinstance(metadata, dict) else None
if isinstance(prices, dict) and curr in prices:
matches[code] = (plan, Decimal(str(prices[curr])))
break
elif plan.currency_code.upper() == curr:
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
matches[code] = (plan, Decimal(str(fee)))
break
if code not in matches:
for cand in cands:
plan = by_code.get(cand)
if not plan:
continue
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
plan_curr = plan.currency_code.upper()
if plan_curr == "INR" and curr in {"USD", "EUR"}:
matches[code] = (plan, max(Decimal("1.00"), (Decimal(str(fee)) / Decimal("80")).quantize(Decimal("1.00"))))
break
elif plan_curr in {"USD", "EUR"} and curr == "INR":
matches[code] = (plan, (Decimal(str(fee)) * Decimal("80")).quantize(Decimal("1.00")))
break
elif plan_curr in {"USD", "EUR"} and curr in {"USD", "EUR"}:
matches[code] = (plan, Decimal(str(fee)))
break
elif fee is not None:
matches[code] = (plan, Decimal(str(fee)))
break
return matches
async def get_renewable_plan_codes(self, user_id: UUID) -> set[str]:
now = datetime.now(timezone.utc)
stmt = (
select(AccessPlan.code)
.join(UserSubscription, UserSubscription.plan_id == AccessPlan.id)
.where(
UserSubscription.user_id == user_id,
UserSubscription.status == SubscriptionStatus.ACTIVE,
UserSubscription.expires_at > now,
)
)
plan_codes = (await self.session.execute(stmt)).scalars().all()
renewable: set[str] = set()
for c in plan_codes:
code = c.strip().upper()
renewable.add(code)
if code.endswith("_USD"):
renewable.add(code[:-4])
else:
renewable.add(f"{code}_USD")
return renewable
async def get_items(self, codes: list[str], currency: str, renewable_codes: set[str] | None = None) -> list[PricingItem]:
matches = await self.get_plan_matches(codes, currency)
normalized = [c.strip().upper() for c in codes if c.strip()]
items: list[PricingItem] = []
ren = renewable_codes or set()
plan_ids = [plan.id for plan, _ in matches.values()]
plan_module_map: dict[str, list[str]] = {}
if plan_ids:
apm_rows = (await self.session.execute(
select(AccessPlanModule.plan_id, AccessPlanModule.module_id)
.where(AccessPlanModule.plan_id.in_(plan_ids))
)).all()
for pid, mid in apm_rows:
plan_module_map.setdefault(str(pid), []).append(str(mid))
for code in normalized:
if code in matches:
plan, price = matches[code]
is_renewal = (code in ren) or (plan.code.upper() in ren)
p_str = str(plan.id)
m_ids = tuple(plan_module_map.get(p_str, []))
items.append(PricingItem(
code=code,
name=plan.name,
category=self._category(plan),
price=price,
is_renewal=is_renewal,
plan_id=p_str,
module_ids=m_ids,
))
plan = by_code.get(code)
if not plan:
continue
metadata = plan.metadata_json or {}
prices = metadata.get("prices") if isinstance(metadata, dict) else None
if isinstance(prices, dict) and currency.upper() in prices:
price = Decimal(str(prices[currency.upper()]))
elif plan.currency_code.upper() == currency.upper():
price = Decimal(plan.total_fee)
else:
continue
items.append(PricingItem(code=plan.code, name=plan.name, category=self._category(plan), price=price))
return items
async def get_coupon(self, code: str | None, currency: str, user_id: UUID | None = None) -> tuple[PricingCoupon | None, str | None]:
if not code or not code.strip():
return None, None
clean_code = code.strip().upper()
async def get_coupon(self, code: str | None, currency: str) -> PricingCoupon | None:
if not code:
return None
now = datetime.now(timezone.utc)
coupon = (await self.session.execute(select(Coupon).where(Coupon.code == clean_code))).scalar_one_or_none()
coupon = (await self.session.execute(select(Coupon).where(Coupon.code == code.strip().upper(), Coupon.is_active.is_(True), Coupon.start_date <= now, Coupon.end_date >= now))).scalar_one_or_none()
if not coupon:
return None, "Invalid or expired coupon code."
if not coupon.is_active:
return None, "This coupon code is currently inactive."
s_date = coupon.start_date.replace(tzinfo=timezone.utc) if coupon.start_date.tzinfo is None else coupon.start_date
e_date = coupon.end_date.replace(tzinfo=timezone.utc) if coupon.end_date.tzinfo is None else coupon.end_date
if now < s_date:
return None, "This coupon code is not active yet."
if now > e_date:
return None, "This coupon code has expired."
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
return None, "Coupon usage limit reached."
per_user_limit = getattr(coupon, "per_user_limit", None)
if isinstance(per_user_limit, int) and not isinstance(per_user_limit, bool):
if per_user_limit <= 0:
return None, "This coupon is currently not available for redemption."
if user_id is not None:
user_redemptions = (
await self.session.execute(
select(func.count(CouponRedemption.id)).where(
CouponRedemption.coupon_id == coupon.id,
CouponRedemption.user_id == user_id,
)
)
).scalar() or 0
if user_redemptions >= per_user_limit:
return None, "You have already reached the usage limit for this coupon."
return None
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
value = Decimal(coupon.value)
if coupon.discount_type in {"flat", "flat_amount"}:
if coupon.discount_type == "flat":
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
if isinstance(currency_values, dict) and currency.upper() in currency_values and currency_values[currency.upper()] is not None:
if isinstance(currency_values, dict) and currency.upper() in currency_values:
value = Decimal(str(currency_values[currency.upper()]))
max_cap = Decimal(coupon.max_discount_limit or 0)
currency_caps = metadata.get("currency_caps") if isinstance(metadata, dict) else None
if isinstance(currency_caps, dict) and currency.upper() in currency_caps and currency_caps[currency.upper()] is not None:
max_cap = Decimal(str(currency_caps[currency.upper()]))
min_spend = Decimal(str(coupon.min_purchase_amount or 0))
currency_min_spends = metadata.get("currency_min_spends") if isinstance(metadata, dict) else None
if isinstance(currency_min_spends, dict) and currency.upper() in currency_min_spends and currency_min_spends[currency.upper()] is not None:
min_spend = Decimal(str(currency_min_spends[currency.upper()]))
app_plan_ids: set[str] = set()
if coupon.applicable_plan_ids:
for pid in coupon.applicable_plan_ids:
app_plan_ids.add(str(pid))
# Include paired currency versions (e.g. LIFETIME_ALL, LIFETIME_ALL_USD, LIFETIME_ALL_EUR)
p_rows = (await self.session.execute(
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
)).scalars().all()
base_codes: set[str] = set()
for c in p_rows:
code_up = c.upper()
if code_up.endswith("_USD"):
base_codes.add(code_up[:-4])
elif code_up.endswith("_EUR"):
base_codes.add(code_up[:-4])
else:
base_codes.add(code_up)
if base_codes:
sibling_codes: set[str] = set()
for bc in base_codes:
sibling_codes.add(bc)
sibling_codes.add(f"{bc}_USD")
sibling_codes.add(f"{bc}_EUR")
sibling_rows = (await self.session.execute(
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
)).scalars().all()
for sid in sibling_rows:
app_plan_ids.add(str(sid))
app_mod_ids = tuple(str(mid) for mid in coupon.applicable_module_ids) if coupon.applicable_module_ids else ()
return PricingCoupon(
code=coupon.code,
category=coupon.coupon_category,
discount_type=coupon.discount_type,
value=value,
description=coupon.description,
max_discount_limit=max_cap,
min_purchase_amount=min_spend,
applicable_plan_ids=tuple(app_plan_ids),
applicable_module_ids=app_mod_ids,
), None
@staticmethod
def _module_category(module: Module) -> str:
metadata = module.metadata_json or {}
cat = metadata.get("commerce_category") or metadata.get("category")
if cat:
return str(cat)
kind = (metadata.get("kind") or "").lower()
if kind == "point": return "Points"
if kind in {"pattern", "five-elements"}: return "Pattern"
if kind == "nutrition": return "Nutrition"
if kind in {"therapeutic", "therapeutics"}: return "Therapeutics"
code = (module.code or "").lower()
name = (module.name or "").lower()
if code in {"m0001", "m0002", "m0003"} or "point" in name: return "Points"
if code.startswith("m001") or code == "m0020" or "pattern" in name or "principles" in name or "stages" in name or "levels" in name: return "Pattern"
if code == "m0031" or "nutrition" in name or "food" in name: return "Nutrition"
if code.startswith("m004") or "therapeutic" in name or "gynae" in name or "auriculo" in name: return "Therapeutics"
return "General"
return PricingCoupon(code=coupon.code, category=coupon.coupon_category, discount_type=coupon.discount_type, value=value, description=coupon.description, max_discount_limit=Decimal(coupon.max_discount_limit))
async def get_owned_categories(self, user_id: UUID) -> list[str]:
result: set[str] = set()
# 1. From active UserSubscription
sub_plans = (await self.session.execute(
select(AccessPlan)
.join(UserSubscription, UserSubscription.plan_id == AccessPlan.id)
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
)).scalars().all()
for plan in sub_plans:
cat = self._category(plan)
if cat and cat != "General":
result.add(cat)
# 2. From active UserEntitlement via Module
ent_modules = (await self.session.execute(
select(Module)
.join(UserEntitlement, UserEntitlement.module_id == Module.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
)).scalars().all()
for module in ent_modules:
cat = self._module_category(module)
if cat and cat != "General":
result.add(cat)
# 3. From active UserEntitlement via source_plan_id
ent_plans = (await self.session.execute(
select(AccessPlan)
.join(UserEntitlement, UserEntitlement.source_plan_id == AccessPlan.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
)).scalars().all()
for plan in ent_plans:
cat = self._category(plan)
if cat and cat != "General":
result.add(cat)
return list(result)
rows = (await self.session.execute(select(UserEntitlement, Module).join(Module, Module.id == UserEntitlement.module_id).where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE))).all()
result: list[str] = []
for _, module in rows:
metadata = module.metadata_json or {}
category = metadata.get("commerce_category") or metadata.get("category")
if category:
result.append(str(category))
return result
async def is_first_purchase(self, user_id: UUID) -> bool:
has_sub = (await self.session.execute(
select(UserSubscription.id)
.where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE)
.limit(1)
)).scalar_one_or_none()
has_ent = (await self.session.execute(
select(UserEntitlement.id)
.where(UserEntitlement.user_id == user_id, UserEntitlement.status == EntitlementStatus.ACTIVE)
.limit(1)
)).scalar_one_or_none()
return has_sub is None and has_ent is None
exists = (await self.session.execute(select(UserSubscription.id).where(UserSubscription.user_id == user_id, UserSubscription.status == SubscriptionStatus.ACTIVE).limit(1))).scalar_one_or_none()
return exists is None

View File

@ -14,17 +14,14 @@ class CartItemResponse(BaseModel):
name: str
category: str
price: float
is_renewal: bool = False
class CartCalculationResponse(BaseModel):
currency: str
base_subtotal: float
discount_policy: str
bundle_discount_amount: float
renewal_discount_amount: float = 0.0
coupon_applied: str
coupon_discount_amount: float
coupon_error: str | None = None
total_discounts: float
convenience_fee_rate: float
convenience_fee: float

View File

@ -11,17 +11,12 @@ class CartService:
async def calculate(self, request: CartCalculationRequest, user_id: UUID | None = None) -> CartCalculationResponse:
currency = request.currency.upper()
renewable_codes = await self.repository.get_renewable_plan_codes(user_id) if user_id else set()
items = await self.repository.get_items(request.cart_item_codes, currency, renewable_codes=renewable_codes)
items = await self.repository.get_items(request.cart_item_codes, currency)
if len(items) != len({c.strip().upper() for c in request.cart_item_codes if c.strip()}):
resolved = {i.code.upper() for i in items}
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
raise ValueError(f"Unknown/inactive plan code or currency mismatch: {', '.join(missing)}")
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency, user_id=user_id)
owned = await self.repository.get_owned_categories(user_id) if user_id else []
if request.owned_category_names:
owned = list(set(owned + [c for c in request.owned_category_names if c]))
coupon = await self.repository.get_coupon(request.coupon_code, currency)
owned = await self.repository.get_owned_categories(user_id) if user_id else request.owned_category_names
first = await self.repository.is_first_purchase(user_id) if user_id else request.is_first_purchase
if owned:
first = False
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first, coupon_error=coupon_error))
return CartCalculationResponse.model_validate(self.engine.calculate(items=items, owned_categories=owned, coupon=coupon, currency=currency, is_first_purchase=first))

View File

@ -1,6 +1,5 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import HTMLResponse
from fastapi import APIRouter, Depends, HTTPException, status
from app.db.models import AppUser
from app.features.payments import get_razorpay_service
from .deps import get_checkout_service, get_current_user
@ -31,21 +30,16 @@ async def verify_checkout_payment(payload: CheckoutVerifyRequest, user: AppUser
async def get_checkout_payment_invoice(payment_id: str, user: AppUser = Depends(get_current_user), service: CheckoutService = Depends(get_checkout_service)):
from sqlalchemy import select
from app.db.models import PaymentTransaction
from app.features.admin.service import AdminService
tx = (await service.session.execute(select(PaymentTransaction).where(PaymentTransaction.gateway_transaction_id == payment_id, PaymentTransaction.user_id == user.id))).scalar_one_or_none()
if not tx:
raise HTTPException(404, detail="Transaction record not found or access denied.")
return {"short_url": f"/api/checkout/payment/{payment_id}/invoice/view"}
@router.get("/payment/{payment_id}/invoice/view", response_class=HTMLResponse)
async def view_checkout_payment_invoice_html(
payment_id: str,
token: str | None = Query(None),
service: CheckoutService = Depends(get_checkout_service),
):
from app.features.admin.service import AdminService
try:
return await AdminService(service.session).render_invoice_html(payment_id)
except LookupError as exc:
raise HTTPException(404, detail=str(exc)) from exc
url, _, _ = await AdminService(service.session).get_or_create_invoice(payment_id)
if not url:
raise HTTPException(500, detail="Razorpay invoice does not have a download URL.")
return {"short_url": url}
except HTTPException:
raise
except Exception as exc:
raise HTTPException(500, detail=f"Failed to render HTML invoice: {exc}") from exc
raise HTTPException(502, detail=f"Failed to generate invoice from Razorpay: {exc}") from exc

View File

@ -6,49 +6,20 @@ from uuid import UUID
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Coupon, Invoice, PaymentTransaction, UserBillingProfile, UserEntitlement, UserSubscription
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Invoice, PaymentTransaction, UserBillingProfile, UserEntitlement, UserSubscription
from app.features.cart.repository import CartRepository
from app.features.cart.schema import CartCalculationRequest
from app.features.cart.service import CartService
from app.features.payments import generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
from app.features.payments import get_razorpay_service
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
EUROPEAN_COUNTRIES = {
"germany", "france", "italy", "spain", "netherlands", "belgium",
"austria", "ireland", "sweden", "denmark", "finland", "portugal",
"greece", "poland", "czech republic", "hungary", "romania",
"iceland", "luxembourg", "croatia", "slovakia", "bulgaria",
"cyprus", "estonia", "latvia", "lithuania", "malta", "slovenia"
}
def validate_user_country_currency(country: str | None, currency: str) -> None:
c = (country or "India").strip().lower()
curr = (currency or "").strip().upper()
if not curr:
raise ValueError("Currency must be specified for checkout.")
if c == "india" or c in {"not configured", "none", "null"}:
if curr != "INR":
raise ValueError(f"Users with billing country India must pay in INR (received {curr}).")
elif c in EUROPEAN_COUNTRIES:
if curr not in {"EUR", "USD"}:
raise ValueError(f"Billing country '{country}' must pay in EUR or USD (received {curr}).")
else:
if curr == "INR":
raise ValueError("INR payments are restricted to domestic Indian billing profiles.")
if curr != "USD":
raise ValueError(f"Billing country '{country}' must pay in USD (received {curr}).")
class CheckoutService:
def __init__(self, *, session: AsyncSession, cart_repository: CartRepository) -> None:
self.session = session
self.cart_service = CartService(cart_repository)
async def create_order(self, user: AppUser, request: CheckoutOrderRequest) -> CheckoutOrderResponse:
validate_user_country_currency(user.country, request.currency)
calc = await self.cart_service.calculate(CartCalculationRequest(cart_item_codes=request.cart_item_codes, coupon_code=request.coupon_code, currency=request.currency), user_id=user.id)
if request.coupon_code and request.coupon_code.strip() and calc.coupon_error:
raise ValueError(calc.coupon_error)
if calc.grand_total <= 0:
raise ValueError("Grand total must be greater than zero to checkout.")
rzp = get_razorpay_service()
@ -59,48 +30,11 @@ class CheckoutService:
await self.session.flush()
except Exception:
pass
else:
try:
edit_data: dict[str, Any] = {"name": user.display_name or user.email, "email": user.email}
if user.phone_number:
edit_data["contact"] = user.phone_number
rzp.client.customer.edit(user.external_ref, data=edit_data)
except Exception:
pass
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
applied_coupon_code = (
request.coupon_code.strip().upper()
if request.coupon_code and calc.coupon_applied and calc.coupon_applied != "None"
else None
)
order = rzp.create_order(
amount=calc.grand_total,
currency=calc.currency,
receipt=receipt,
notes={
"user_id": str(user.id),
"cart_item_codes": ",".join(request.cart_item_codes),
"coupon_code": applied_coupon_code or "",
},
)
plan_matches = await self.cart_service.repository.get_plan_matches(request.cart_item_codes, request.currency)
seen_plan_ids = set()
plans: list[AccessPlan] = []
for plan, _ in plan_matches.values():
if plan.id not in seen_plan_ids:
seen_plan_ids.add(plan.id)
plans.append(plan)
order = rzp.create_order(amount=calc.grand_total, currency=calc.currency, receipt=receipt, notes={"user_id": str(user.id), "cart_item_codes": ",".join(request.cart_item_codes), "coupon_code": request.coupon_code or ""})
plans = (await self.session.execute(select(AccessPlan).where(AccessPlan.code.in_([c.upper() for c in request.cart_item_codes]), AccessPlan.is_active.is_(True)))).scalars().all()
now = datetime.now(timezone.utc)
pricing_meta = {
"base_subtotal": calc.base_subtotal,
"total_discounts": calc.total_discounts,
"grand_total": calc.grand_total,
"taxable_amount": calc.taxable_amount,
"gst_amount": calc.gst_amount,
"currency": calc.currency,
"coupon_code": applied_coupon_code,
"coupon_discount_amount": calc.coupon_discount_amount,
}
pricing_meta = {"base_subtotal": calc.base_subtotal, "total_discounts": calc.total_discounts, "grand_total": calc.grand_total, "taxable_amount": calc.taxable_amount, "gst_amount": calc.gst_amount, "currency": calc.currency}
for plan in plans:
self.session.add(UserSubscription(user_id=user.id, plan_id=plan.id, status=SubscriptionStatus.PENDING, started_at=now, auto_renew=False, payment_provider="razorpay", payment_reference=order["id"], metadata_json=dict(pricing_meta)))
await self.session.commit()
@ -136,62 +70,17 @@ class CheckoutService:
plan = (await self.session.execute(select(AccessPlan).where(AccessPlan.id == sub.plan_id))).scalar_one_or_none()
sub.status = SubscriptionStatus.ACTIVE
sub.started_at = now
# If user already had an active unexpired subscription for this plan, extend from previous expiry
prev_sub = (await self.session.execute(
select(UserSubscription)
.where(
UserSubscription.user_id == user.id,
UserSubscription.plan_id == sub.plan_id,
UserSubscription.id != sub.id,
UserSubscription.status == SubscriptionStatus.ACTIVE,
UserSubscription.expires_at > now
).order_by(UserSubscription.expires_at.desc()).limit(1)
)).scalar_one_or_none()
base_expiry = prev_sub.expires_at if prev_sub and prev_sub.expires_at else now
extension_days = 3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365
sub.expires_at = base_expiry + timedelta(days=extension_days)
sub.expires_at = now + timedelta(days=3650 if plan and plan.billing_period == BillingPeriod.LIFETIME else 365)
if plan:
plan_names.append(plan.name)
module_ids = (await self.session.execute(select(AccessPlanModule.module_id).where(AccessPlanModule.plan_id == sub.plan_id))).scalars().all()
for module_id in module_ids:
active_ent = (await self.session.execute(
select(UserEntitlement)
.where(
UserEntitlement.user_id == user.id,
UserEntitlement.module_id == module_id,
UserEntitlement.status == EntitlementStatus.ACTIVE
).limit(1)
)).scalar_one_or_none()
if active_ent:
active_ent.expires_at = sub.expires_at
else:
active = (await self.session.execute(select(UserEntitlement.id).where(UserEntitlement.user_id == user.id, UserEntitlement.module_id == module_id, UserEntitlement.status == EntitlementStatus.ACTIVE).limit(1))).scalar_one_or_none()
if active is None:
self.session.add(UserEntitlement(user_id=user.id, module_id=module_id, source_subscription_id=sub.id, source_plan_id=sub.plan_id, status=EntitlementStatus.ACTIVE, granted_at=now, grant_reason="subscription_purchase", expires_at=sub.expires_at))
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
phone_snapshot = profile.billing_phone or payment.get("contact")
if phone_snapshot and subs:
sub_meta = dict(subs[0].metadata_json or {})
sub_meta["billing_phone"] = phone_snapshot
subs[0].metadata_json = sub_meta
invoice, invoice_url = await self._create_invoice(
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
)
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=user.id,
invoice_id=invoice.id,
)
invoice_number, invoice_url = await self._create_invoice(rzp, transaction, profile, payment, plan_names, meta)
await self.session.commit()
return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice.invoice_number, "invoice_url": invoice_url}
return {"status": "success", "message": "Payment verified. Clinical modules successfully unlocked!", "razorpay_payment_id": request.razorpay_payment_id, "invoice_number": invoice_number, "invoice_url": invoice_url}
async def _billing_profile(self, user: AppUser, billing_profile_id: UUID | None) -> UserBillingProfile:
stmt = select(UserBillingProfile).where(UserBillingProfile.user_id == user.id)
@ -201,96 +90,28 @@ class CheckoutService:
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
profile = (await self.session.execute(stmt)).scalar_one_or_none()
if profile:
# Synchronize default/auto-generated profile with user's latest verified contact details
updated = False
if user.phone_number and profile.billing_phone != user.phone_number:
profile.billing_phone = user.phone_number
updated = True
if user.country and profile.country != user.country:
profile.country = user.country
updated = True
if user.display_name and profile.billing_name != user.display_name:
profile.billing_name = user.display_name
updated = True
if updated:
await self.session.flush()
return profile
profile = UserBillingProfile(user_id=user.id, label="Default Auto-Generated", billing_name=user.display_name or user.email, billing_email=user.email, billing_phone=user.phone_number, address_line1="Not Configured", city="Not Configured", state="Not Configured", postal_code="000000", country=user.country, is_default=True)
self.session.add(profile)
await self.session.flush()
return profile
async def _create_invoice(
self,
rzp,
tx: PaymentTransaction,
profile: UserBillingProfile,
payment: dict,
plan_names: list[str],
meta: dict,
applied_coupon_id: UUID | None = None,
) -> tuple[Invoice, str | None]:
async def _create_invoice(self, rzp, tx: PaymentTransaction, profile: UserBillingProfile, payment: dict, plan_names: list[str], meta: dict) -> tuple[str, str | None]:
currency = tx.currency.upper()
inv_number = await generate_next_invoice_number(self.session)
# Prioritize current verified user phone and country
phone_to_use = profile.billing_phone or payment.get("contact")
country_to_use = profile.country or "India"
inv_number = f"INV-{datetime.now(timezone.utc).strftime('%Y%m%d')}-{uuid.uuid4().hex[:6].upper()}"
inv_url = None
try:
cust_data: dict[str, Any] = {
"name": profile.billing_name,
"email": profile.billing_email,
}
if phone_to_use:
cust_data["contact"] = phone_to_use
rzp.client.invoice.create(data={
"type": "invoice",
"customer": cust_data,
"line_items": [{
"name": (", ".join(plan_names) or "Access Subscription")[:250],
"amount": int(Decimal(tx.amount) * 100),
"currency": currency,
"quantity": 1,
}],
"email_notify": False,
"sms_notify": False,
"notes": {"payment_id": tx.gateway_transaction_id},
})
created = rzp.client.invoice.create(data={"type":"invoice","customer":{"name":profile.billing_name,"email":profile.billing_email, **({"contact": profile.billing_phone} if profile.billing_phone else {})},"line_items":[{"name": (", ".join(plan_names) or "Access Subscription")[:250],"amount": int(Decimal(tx.amount)*100),"currency":currency,"quantity":1}],"email_notify":False,"sms_notify":False,"notes":{"payment_id":tx.gateway_transaction_id}})
inv_number = created.get("id") or inv_number
inv_url = created.get("short_url")
if created.get("status") == "draft":
issued = rzp.client.invoice.issue(inv_number)
inv_url = issued.get("short_url") or inv_url
except Exception:
pass
# Always use internal branded Acupedia Tax Invoice view URL
inv_url = f"/api/checkout/payment/{tx.gateway_transaction_id}/invoice/view"
base = Decimal(str(meta.get("base_subtotal", tx.amount)))
discount = Decimal(str(meta.get("total_discounts", 0)))
taxable = Decimal(str(meta.get("taxable_amount", 0)))
gst = Decimal(str(meta.get("gst_amount", 0)))
# Build clean address with current country
addr_parts = [profile.address_line1, profile.city, profile.state, profile.postal_code]
clean_parts = [p.strip() for p in addr_parts if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]]
if country_to_use and country_to_use.strip().lower() not in ["not configured", "none", "null"]:
clean_parts.append(country_to_use.strip())
final_billing_address = ", ".join(clean_parts) if clean_parts else (country_to_use or "Digital Access")
invoice = Invoice(
payment_transaction_id=tx.id,
invoice_number=inv_number,
billing_name=profile.billing_name,
billing_email=profile.billing_email,
billing_address=final_billing_address,
gstin=profile.gstin,
billing_profile_id=profile.id,
applied_coupon_id=applied_coupon_id,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
gst_amount=gst,
total_amount=Decimal(tx.amount),
currency_code=currency,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=Decimal(tx.amount) if currency == "INR" else None,
)
self.session.add(invoice)
await self.session.flush()
return invoice, inv_url
self.session.add(Invoice(payment_transaction_id=tx.id, invoice_number=inv_number, billing_name=profile.billing_name, billing_email=profile.billing_email, billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}", gstin=profile.gstin, billing_profile_id=profile.id, base_amount=base, discount_amount=discount, taxable_amount=taxable, gst_amount=gst, total_amount=Decimal(tx.amount), currency_code=currency, exchange_rate_to_inr=Decimal("1"), total_amount_inr=Decimal(tx.amount) if currency == "INR" else None))
return inv_number, inv_url

View File

@ -10,7 +10,6 @@ from datetime import datetime
from sqlalchemy import select, bindparam, text, func
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import aliased
from app.db.enums import ModuleStatus, RecordStatus
@ -67,21 +66,6 @@ from .schema import (
_SHORT_TEMPLATE_RE = re.compile(r"^CT\d+$", re.IGNORECASE)
DYNAMIC_COUNT_COLLECTION_CODES: tuple[str, ...] = (
"points",
"patterns",
"food_items",
"items",
"ghost_points",
"four_seas",
"gao_wu_command_points",
"window_of_heaven_points",
"front_mu_points",
"horary_points",
"entry_exit_points",
"point_codes",
)
_SYSTEM_SORT_FIELDS = {
"module_sort_order",
"title",
@ -404,10 +388,11 @@ class ContentRepository:
if include_draft
else [RecordStatus.PUBLISHED]
),
Module.is_active.is_(True),
Module.status.in_(
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE]
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
if include_draft
else [ModuleStatus.ACTIVE, ModuleStatus.INACTIVE]
else [ModuleStatus.ACTIVE]
),
AttributeDefinitionSet.is_active.is_(True),
)
@ -477,184 +462,6 @@ class ContentRepository:
return resolved
async def resolve_template_content_counts(
self,
*,
template_refs: set[tuple[str, str]],
include_draft: bool = False,
) -> tuple[dict[tuple[str, str], int], dict[tuple[tuple[str, str], str], int]]:
"""
Count active items for template_ref targets across all modules.
Also aggregates child content_count totals grouped by content_label so
multi-level index entries (e.g. a top-level index summarizing sub-index
counts with the same label) sum child counts instead of collapsing to the
intermediate index row count.
"""
if not template_refs:
return {}, {}
normalized_pairs = {(m.lower(), t.lower()) for m, t in template_refs}
module_codes = sorted({m for m, _ in normalized_pairs})
template_codes = sorted({t for _, t in normalized_pairs})
allowed_content_statuses = (
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
if include_draft
else [RecordStatus.PUBLISHED]
)
allowed_module_statuses = (
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE]
if include_draft
else [ModuleStatus.ACTIVE, ModuleStatus.INACTIVE]
)
count_stmt = (
select(
func.lower(Module.code).label("module_code"),
func.lower(AttributeDefinitionSet.code).label("template_code"),
func.count(func.distinct(ContentItem.id)).label("item_count"),
)
.select_from(ContentItem)
.join(
AttributeDefinitionSet,
AttributeDefinitionSet.id == ContentItem.attribute_definition_set_id,
)
.join(ModuleContent, ModuleContent.content_id == ContentItem.id)
.join(Module, Module.id == ModuleContent.module_id)
.where(
func.lower(Module.code).in_(module_codes),
func.lower(AttributeDefinitionSet.code).in_(template_codes),
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_content_statuses),
Module.status.in_(allowed_module_statuses),
AttributeDefinitionSet.is_active.is_(True),
)
.group_by(
func.lower(Module.code),
func.lower(AttributeDefinitionSet.code),
)
)
count_result = await self._session.execute(count_stmt)
template_counts: dict[tuple[str, str], int] = {}
for row in count_result.mappings():
pair = (str(row["module_code"]), str(row["template_code"]))
if pair in normalized_pairs:
template_counts[pair] = int(row["item_count"] or 0)
ca_count = aliased(ContentAttribute)
ad_count = aliased(AttributeDefinition)
ca_label = aliased(ContentAttribute)
ad_label = aliased(AttributeDefinition)
sum_stmt = (
select(
func.lower(Module.code).label("module_code"),
func.lower(AttributeDefinitionSet.code).label("template_code"),
func.lower(func.btrim(ca_label.value_text)).label("content_label"),
func.sum(ca_count.value_number).label("total_count"),
)
.select_from(ContentItem)
.join(
AttributeDefinitionSet,
AttributeDefinitionSet.id == ContentItem.attribute_definition_set_id,
)
.join(ModuleContent, ModuleContent.content_id == ContentItem.id)
.join(Module, Module.id == ModuleContent.module_id)
.join(ca_count, ca_count.content_id == ContentItem.id)
.join(ad_count, ad_count.id == ca_count.attribute_definition_id)
.join(ca_label, ca_label.content_id == ContentItem.id)
.join(ad_label, ad_label.id == ca_label.attribute_definition_id)
.where(
func.lower(Module.code).in_(module_codes),
func.lower(AttributeDefinitionSet.code).in_(template_codes),
ContentItem.is_active.is_(True),
ContentItem.status.in_(allowed_content_statuses),
Module.status.in_(allowed_module_statuses),
AttributeDefinitionSet.is_active.is_(True),
ca_count.parent_attribute_value_id.is_(None),
ad_count.is_active.is_(True),
ad_count.is_root.is_(True),
func.split_part(ad_count.attribute_key, ".", 2) == "content_count",
ca_count.value_number.is_not(None),
ca_label.parent_attribute_value_id.is_(None),
ad_label.is_active.is_(True),
ad_label.is_root.is_(True),
func.split_part(ad_label.attribute_key, ".", 2) == "content_label",
ca_label.value_text.is_not(None),
)
.group_by(
func.lower(Module.code),
func.lower(AttributeDefinitionSet.code),
func.lower(func.btrim(ca_label.value_text)),
)
)
sum_result = await self._session.execute(sum_stmt)
label_sums: dict[tuple[tuple[str, str], str], int] = {}
for row in sum_result.mappings():
pair = (str(row["module_code"]), str(row["template_code"]))
lbl = str(row["content_label"] or "").strip()
if pair in normalized_pairs and lbl:
label_sums[(pair, lbl)] = int(round(float(row["total_count"] or 0)))
return template_counts, label_sums
async def resolve_content_item_collection_counts(
self,
*,
content_ids: set[UUID],
) -> dict[UUID, int]:
"""
Count primary collection items (points, patterns, etc.) for target content items.
Only considers explicit collection attribute keys so descriptive/narrative
content items (e.g. Meridians, EOV) keep their authored counts untouched.
"""
if not content_ids:
return {}
attr_code_expr = func.split_part(AttributeDefinition.attribute_key, ".", 2)
stmt = (
select(
ContentAttribute.content_id,
attr_code_expr.label("attr_code"),
AttributeDefinition.is_multivalue,
ContentAttribute.value_json,
)
.join(
AttributeDefinition,
AttributeDefinition.id == ContentAttribute.attribute_definition_id,
)
.where(
ContentAttribute.content_id.in_(sorted(content_ids)),
ContentAttribute.parent_attribute_value_id.is_(None),
AttributeDefinition.is_active.is_(True),
AttributeDefinition.is_root.is_(True),
attr_code_expr.in_(DYNAMIC_COUNT_COLLECTION_CODES),
)
)
result = await self._session.execute(stmt)
counts_by_item: dict[UUID, dict[str, int]] = {}
for row in result.mappings():
cid = row["content_id"]
attr_code = str(row["attr_code"] or "")
if not attr_code:
continue
bucket = counts_by_item.setdefault(cid, {})
if row["is_multivalue"]:
bucket[attr_code] = bucket.get(attr_code, 0) + 1
elif isinstance(row["value_json"], (list, dict)):
bucket[attr_code] = bucket.get(attr_code, 0) + len(row["value_json"])
resolved: dict[UUID, int] = {}
for cid, per_attr in counts_by_item.items():
for code in DYNAMIC_COUNT_COLLECTION_CODES:
val = per_attr.get(code, 0)
if val > 0:
resolved[cid] = val
break
return resolved
async def get_content_by_id(
self,
*,

View File

@ -5,7 +5,7 @@ from enum import StrEnum
from typing import Any
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.db.enums import ModuleStatus, RecordStatus
@ -84,17 +84,10 @@ class ModuleResponse(BaseModel):
serialization_alias="metadata",
)
@computed_field
@property
def category(self) -> str:
from app.features.admin.services.module_service import resolve_module_category
return resolve_module_category(self.metadata)
created_by: UUID | None = None
updated_by: UUID | None = None
created_at: datetime
updated_at: datetime
plan_code: str | None = None
class ModuleListResponse(BaseModel):

View File

@ -125,34 +125,12 @@ class ContentService:
session=self.session,
include_draft=preview,
)
plan_map: dict[UUID, str] = {}
if modules:
from app.db.enums import PlanType
from app.db.models import AccessPlan, AccessPlanModule
rows = (
await self.session.execute(
select(AccessPlanModule.module_id, AccessPlan.code)
.join(AccessPlan, AccessPlanModule.plan_id == AccessPlan.id)
.where(
AccessPlanModule.module_id.in_([m.id for m in modules]),
AccessPlan.plan_type == PlanType.ONE_TIME,
AccessPlan.currency_code == "INR",
AccessPlan.is_active.is_(True),
)
)
).all()
for mod_id, p_code in rows:
if mod_id not in plan_map:
plan_map[mod_id] = p_code
responses = []
for module in modules:
resp = ModuleResponse.model_validate(module)
if module.id in plan_map:
resp.plan_code = plan_map[module.id]
responses.append(resp)
return ModuleListResponse(modules=responses)
return ModuleListResponse(
modules=[
ModuleResponse.model_validate(module)
for module in modules
]
)
if preview:
return await loader()
@ -174,16 +152,16 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE}
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE, ModuleStatus.INACTIVE}
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
@ -227,16 +205,16 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE}
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE, ModuleStatus.INACTIVE}
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
@ -292,16 +270,16 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE}
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE, ModuleStatus.INACTIVE}
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
@ -392,39 +370,6 @@ class ContentService:
for item, hydrated_data in zip(items, hydrated_payloads, strict=True):
item.data = hydrated_data
# Inherit media from referenced content items when direct media is absent
items_needing_media: list[
tuple[ModuleTemplateContentDetailItem, list[tuple[UUID, str | None]]]
] = []
all_ref_ids: set[UUID] = set()
for item in items:
if not item.media:
refs: list[tuple[UUID, str | None]] = []
self._extract_referenced_content_items(item.data, refs)
if refs:
items_needing_media.append((item, refs))
all_ref_ids.update(cid for cid, _ in refs)
if items_needing_media and all_ref_ids:
ref_media_by_content = (
await self.repository.get_content_media_for_content_ids(
session=self.session,
content_ids=list(all_ref_ids),
)
)
for item, refs in items_needing_media:
inherited: list[ContentMediaResponse] = []
for cid, label in refs:
for row in ref_media_by_content.get(cid, []):
row_copy = dict(row)
if label:
row_copy["caption"] = label
row_copy["alt_text"] = label
row_copy["media_role"] = "gallery"
row_copy["sort_order"] = len(inherited)
inherited.append(self._media_response(row_copy))
item.media = inherited
return ModuleTemplateContentDetailResponse(
module=ModuleSummaryResponse.model_validate(module),
template=self._template_summary_response(template),
@ -594,16 +539,16 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise HTTPException(status_code=404, detail="Module not found")
allowed_module_statuses = (
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE}
{ModuleStatus.ACTIVE, ModuleStatus.DRAFT}
if preview
else {ModuleStatus.ACTIVE, ModuleStatus.INACTIVE}
else {ModuleStatus.ACTIVE}
)
if module.status not in allowed_module_statuses:
raise HTTPException(status_code=404, detail="Module not found")
@ -636,30 +581,6 @@ class ContentService:
content_id=content_id,
)
if not media_rows:
referenced_items: list[tuple[UUID, str | None]] = []
self._extract_referenced_content_items(dynamic_data, referenced_items)
if referenced_items:
ref_ids = [cid for cid, _ in referenced_items]
media_by_content = (
await self.repository.get_content_media_for_content_ids(
session=self.session,
content_ids=ref_ids,
)
)
inherited_rows: list[dict[str, Any]] = []
for cid, label in referenced_items:
rows = media_by_content.get(cid, [])
for r in rows:
row_copy = dict(r)
if label:
row_copy["caption"] = label
row_copy["alt_text"] = label
row_copy["media_role"] = "gallery"
row_copy["sort_order"] = len(inherited_rows)
inherited_rows.append(row_copy)
media_rows = inherited_rows
response = ContentDetailResponse(
module=ModuleSummaryResponse.model_validate(module),
content=ContentItemResponse.model_validate(
@ -1106,18 +1027,10 @@ class ContentService:
module = await self.repository.resolve_module(
session=self.session,
module_code=module_code,
active_only=False,
active_only=True,
)
if module is None:
raise ModuleNotFoundError("Requested module was not found")
module_status = (
module.status.value
if hasattr(module.status, "value")
else str(module.status)
)
allowed_module_statuses = {"active", "inactive"}
if module_status not in allowed_module_statuses:
raise ModuleNotFoundError("Requested module is not available")
raise ModuleNotFoundError("Requested active module was not found")
definitions = await self.repository.get_module_search_definitions(
module_id=module.id,
@ -1177,18 +1090,10 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise ModuleNotFoundError("Requested module was not found")
module_status = (
module.status.value
if hasattr(module.status, "value")
else str(module.status)
)
allowed_module_statuses = {"active", "inactive"}
if module_status not in allowed_module_statuses:
raise ModuleNotFoundError("Requested module is not available")
raise ModuleNotFoundError("Requested active module was not found")
definitions = await self.repository.get_module_search_definitions(
module_id=module.id,
@ -1227,20 +1132,16 @@ class ContentService:
session=self.session,
module_id=request.module_id,
module_code=request.module_code,
active_only=False,
active_only=True,
)
if module is None:
raise ModuleNotFoundError("Requested module was not found")
raise ModuleNotFoundError("Requested active module was not found")
module_status = (
module.status.value
if hasattr(module.status, "value")
else str(module.status)
)
allowed_module_statuses = (
{"active", "draft", "inactive"}
if preview
else {"active", "inactive"}
)
allowed_module_statuses = {"active", "draft"} if preview else {"active"}
if module_status not in allowed_module_statuses:
raise ModuleNotFoundError("Requested module is not available")
definition_set = (
@ -1254,7 +1155,7 @@ class ContentService:
)
if (
derived_module_code is not None
and derived_module_code.lower() != module.code.lower()
and derived_module_code != module.code
):
# Prevent a caller from using a template from M0002 against M0001
# even if content associations have been accidentally corrupted.
@ -1359,159 +1260,19 @@ class ContentService:
self._collect_content_reference_lookups(payload, references)
if not references:
hydrated = [
return [
self._hydrate_reference_value(payload, {})
for payload in payloads
]
else:
resolved = await self.repository.resolve_content_reference_targets(
references=references,
include_draft=preview,
)
hydrated = [
self._hydrate_reference_value(payload, resolved)
for payload in payloads
]
await self._hydrate_dynamic_content_counts(hydrated, preview=preview)
return hydrated
@classmethod
def _collect_dynamic_count_targets(
cls,
value: Any,
items: list[dict[str, Any]],
template_refs: set[tuple[str, str]],
content_ids: set[UUID],
) -> None:
if isinstance(value, list):
for entry in value:
cls._collect_dynamic_count_targets(
entry, items, template_refs, content_ids
)
return
if not isinstance(value, dict):
return
if "content_count" in value and isinstance(value.get("link"), dict):
link = value["link"]
link_type = link.get("type")
target = link.get("target")
if isinstance(target, dict):
if link_type == "template_ref":
mod = str(target.get("module_code") or "").strip()
tpl = str(target.get("template_code") or "").strip()
if mod and tpl:
template_refs.add((mod, tpl))
items.append(value)
elif link_type == "content_ref" and target.get("content_id"):
try:
content_ids.add(UUID(str(target["content_id"])))
items.append(value)
except (ValueError, TypeError):
pass
for child in value.values():
cls._collect_dynamic_count_targets(
child, items, template_refs, content_ids
)
async def _hydrate_dynamic_content_counts(
self,
payloads: list[dict[str, Any]],
*,
preview: bool = False,
) -> None:
"""Update index entry content_count values dynamically from live targets across all modules."""
candidate_items: list[dict[str, Any]] = []
template_refs: set[tuple[str, str]] = set()
content_ids: set[UUID] = set()
for payload in payloads:
self._collect_dynamic_count_targets(
payload, candidate_items, template_refs, content_ids
)
if not candidate_items:
return
template_counts: dict[tuple[str, str], int] = {}
label_sums: dict[tuple[tuple[str, str], str], int] = {}
if template_refs:
res = await self.repository.resolve_template_content_counts(
template_refs=template_refs,
include_draft=preview,
)
if isinstance(res, tuple) and len(res) == 2:
template_counts, label_sums = res
item_counts: dict[UUID, int] = {}
if content_ids:
res_items = await self.repository.resolve_content_item_collection_counts(
content_ids=content_ids
)
if isinstance(res_items, dict):
item_counts = res_items
for item in candidate_items:
link = item.get("link") or {}
link_type = link.get("type")
target = link.get("target") or {}
if link_type == "template_ref":
pair = (
str(target.get("module_code") or "").strip().lower(),
str(target.get("template_code") or "").strip().lower(),
)
lbl = str(item.get("content_label") or "").strip().lower()
if lbl and (pair, lbl) in label_sums and label_sums[(pair, lbl)] > 0:
item["content_count"] = label_sums[(pair, lbl)]
elif pair in template_counts:
item["content_count"] = template_counts[pair]
elif link_type == "content_ref" and target.get("content_id"):
try:
cid = UUID(str(target["content_id"]))
except (ValueError, TypeError):
continue
if cid in item_counts:
item["content_count"] = item_counts[cid]
@classmethod
def _extract_referenced_content_items(
cls,
value: Any,
output: list[tuple[UUID, str | None]],
seen_ids: set[UUID] | None = None,
) -> None:
"""Recursively collect (content_id, label) tuples from all content_ref objects in order."""
if seen_ids is None:
seen_ids = set()
if isinstance(value, list):
for item in value:
cls._extract_referenced_content_items(item, output, seen_ids)
return
if not isinstance(value, dict):
return
if value.get("type") == "content_ref":
target = value.get("target")
raw_id = target.get("content_id") if isinstance(target, dict) else None
if raw_id:
try:
cid = UUID(str(raw_id))
if cid not in seen_ids:
seen_ids.add(cid)
label = value.get("label") or (
target.get("source_key") if isinstance(target, dict) else None
)
output.append((cid, str(label) if label else None))
except (ValueError, TypeError):
pass
for child in value.values():
cls._extract_referenced_content_items(child, output, seen_ids)
resolved = await self.repository.resolve_content_reference_targets(
references=references,
include_draft=preview,
)
return [
self._hydrate_reference_value(payload, resolved)
for payload in payloads
]
@classmethod
def _collect_content_reference_lookups(

View File

@ -1,15 +1,4 @@
from .razorpay import RazorpayService, get_razorpay_service
from .pricing import PricingEngine, PricingItem, PricingCoupon
from .invoice_service import generate_next_invoice_number
from .coupon_redemption import record_coupon_redemption
__all__ = [
"RazorpayService",
"get_razorpay_service",
"PricingEngine",
"PricingItem",
"PricingCoupon",
"generate_next_invoice_number",
"record_coupon_redemption",
]
__all__ = ["RazorpayService", "get_razorpay_service", "PricingEngine", "PricingItem", "PricingCoupon"]

View File

@ -1,64 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from uuid import UUID
from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models import Coupon, CouponRedemption
async def record_coupon_redemption(
session: AsyncSession,
*,
coupon: Coupon | None = None,
coupon_code: str | None = None,
user_id: UUID,
invoice_id: UUID | None = None,
) -> Coupon | None:
"""Increment coupon usage_count and record a per-invoice CouponRedemption entry."""
if coupon is None:
if not coupon_code or not str(coupon_code).strip():
return None
code = str(coupon_code).strip().upper()
coupon = (await session.execute(
select(Coupon).where(Coupon.code == code)
)).scalar_one_or_none()
if not coupon:
return None
if invoice_id is not None:
existing_filter = or_(
CouponRedemption.invoice_id == invoice_id,
CouponRedemption.invoice_id.is_(None),
)
else:
existing_filter = CouponRedemption.invoice_id.is_(None)
existing = (await session.execute(
select(CouponRedemption)
.where(
CouponRedemption.coupon_id == coupon.id,
CouponRedemption.user_id == user_id,
existing_filter,
)
.limit(1)
)).scalar_one_or_none()
if existing:
if invoice_id is not None and existing.invoice_id == invoice_id:
return coupon
coupon.usage_count = (coupon.usage_count or 0) + 1
if invoice_id and not existing.invoice_id:
existing.invoice_id = invoice_id
return coupon
coupon.usage_count = (coupon.usage_count or 0) + 1
session.add(CouponRedemption(
coupon_id=coupon.id,
user_id=user_id,
invoice_id=invoice_id,
redeemed_at=datetime.now(timezone.utc),
))
return coupon

View File

@ -1,31 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
async def generate_next_invoice_number(session: AsyncSession, dt: datetime | None = None) -> str:
"""Generate the next sequential invoice number for the month.
Format: INV-{MONTH}-{YEAR}-{SERIAL} (e.g., INV-OCT-2026-00001).
The serial number is 5 digits zero-padded and resets to 00001 every month.
"""
now = dt or datetime.now(timezone.utc)
year_month = now.strftime("%Y-%m")
month_abbr = now.strftime("%b").upper()
year_str = now.strftime("%Y")
stmt = text(
"""
INSERT INTO commerce.invoice_monthly_sequences (year_month, last_serial, updated_at)
VALUES (:ym, 1, now())
ON CONFLICT (year_month)
DO UPDATE SET last_serial = commerce.invoice_monthly_sequences.last_serial + 1,
updated_at = now()
RETURNING last_serial;
"""
)
result = await session.execute(stmt, {"ym": year_month})
serial = result.scalar_one()
return f"INV-{month_abbr}-{year_str}-{serial:05d}"

View File

@ -14,9 +14,6 @@ class PricingItem:
name: str
category: str
price: Decimal
is_renewal: bool = False
plan_id: str | None = None
module_ids: tuple[str, ...] = ()
@dataclass(frozen=True)
class PricingCoupon:
@ -26,79 +23,62 @@ class PricingCoupon:
value: Decimal
description: str | None = None
max_discount_limit: Decimal = Decimal("0")
min_purchase_amount: Decimal = Decimal("0")
applicable_plan_ids: tuple[str, ...] = ()
applicable_module_ids: tuple[str, ...] = ()
class PricingEngine:
"""Calculates checkout totals with Policy 5.1 Early Renewal Discount (20%) and coupon discounts."""
"""Preserves the legacy bundle/loyalty/fee rules while sourcing prices from commerce.access_plans."""
def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool, coupon_error: str | None = None) -> dict[str, Any]:
def calculate(self, *, items: list[PricingItem], owned_categories: list[str], coupon: PricingCoupon | None, currency: str, is_first_purchase: bool) -> dict[str, Any]:
curr = currency.upper()
base = sum((item.price for item in items), Decimal("0"))
# Policy 5.1: 20% Early Renewal Discount for modules renewed within validity
renewal_discount = sum(
(q(item.price * Decimal("0.20")) for item in items if item.is_renewal),
Decimal("0")
)
categories = {item.category for item in items}
has_lifetime = any(i.category.lower() == "lifetime" or i.code == "LIFETIME_ALL" for i in items)
bundle = Decimal("0")
policy = "Early Renewal (20% Off)" if renewal_discount > Decimal("0") else "None"
after_renewal = max(Decimal("0"), base - renewal_discount)
policy = "None"
disable_unit = bool(is_first_purchase and coupon and coupon.category == "introductory" and coupon.discount_type == "flat")
if has_lifetime:
policy = "Lifetime Bulk Package"
elif disable_unit:
policy = "None (Overridden by New User Event Coupon)"
elif is_first_purchase:
n = len(categories)
rate = Decimal("0.10") if n == 2 else Decimal("0.20") if n == 3 else Decimal("0.30") if n >= 4 else Decimal("0")
bundle = base * rate
if rate:
policy = f"First-time Buy: {n if n < 4 else '4+'} Units ({int(rate * 100)}% Off)"
else:
n = len(set(owned_categories))
if n and items:
rate = min(Decimal("0.05") * n, Decimal("0.25"))
bundle = base * rate
policy = f"Staggered Buy: {n} owned categories ({int(rate * 100)}% Off)"
after_bundle = max(Decimal("0"), base - bundle)
coupon_discount = Decimal("0")
coupon_text = "None"
if coupon:
allowed_plans = set(coupon.applicable_plan_ids)
allowed_modules = set(coupon.applicable_module_ids)
has_scope_restriction = bool(allowed_plans or allowed_modules)
qualifying_items = [
item for item in items
if (not has_scope_restriction)
or (item.plan_id and item.plan_id in allowed_plans)
or (any(m in allowed_modules for m in item.module_ids))
]
if has_scope_restriction and not qualifying_items:
coupon_error = "This promo code is not valid for items in your cart."
coupon_text = "None"
coupon_discount = Decimal("0")
else:
# Calculate eligible spend after applicable item-level renewal discounts
eligible_spend = sum(
(max(Decimal("0"), item.price - (q(item.price * Decimal("0.20")) if item.is_renewal else Decimal("0")))
for item in qualifying_items),
Decimal("0")
)
if coupon.min_purchase_amount > 0 and eligible_spend < coupon.min_purchase_amount:
coupon_error = f"Minimum cart spend of {curr} {coupon.min_purchase_amount} required to use coupon {coupon.code}."
coupon_text = "None"
coupon_discount = Decimal("0")
else:
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type in {"flat", "flat_amount"}:
coupon_discount = min(coupon.value, eligible_spend)
elif coupon.discount_type in {"percentage", "percent"}:
coupon_discount = eligible_spend * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
net = max(Decimal("0"), after_renewal - coupon_discount)
grand = q(net)
coupon_text = f"Code: {coupon.code} - {coupon.description or ''}".rstrip(" -")
if coupon.discount_type == "flat":
coupon_discount = min(coupon.value, after_bundle)
elif coupon.discount_type == "percentage":
coupon_discount = after_bundle * (coupon.value / Decimal("100"))
if coupon.max_discount_limit > 0:
coupon_discount = min(coupon_discount, coupon.max_discount_limit)
net = max(Decimal("0"), after_bundle - coupon_discount)
fee_rate = Decimal("0.02") if curr == "INR" else Decimal("0.03")
fee = q(net * fee_rate)
gst = q(fee * Decimal("0.18")) if curr == "INR" else Decimal("0")
grand = q(net + fee + gst)
return {
"currency": curr,
"base_subtotal": float(q(base)),
"discount_policy": policy,
"bundle_discount_amount": float(q(bundle)),
"renewal_discount_amount": float(q(renewal_discount)),
"coupon_applied": coupon_text,
"coupon_discount_amount": float(q(coupon_discount)),
"coupon_error": coupon_error,
"total_discounts": float(q(renewal_discount + coupon_discount)),
"convenience_fee_rate": 0.0,
"convenience_fee": 0.0,
"taxable_amount": 0.0,
"gst_amount": 0.0,
"total_discounts": float(q(bundle + coupon_discount)),
"convenience_fee_rate": float(fee_rate * 100),
"convenience_fee": float(fee),
"taxable_amount": float(fee),
"gst_amount": float(gst),
"grand_total": float(grand),
"cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price)), "is_renewal": i.is_renewal} for i in items],
"cart_items": [{"code": i.code, "name": i.name, "category": i.category, "price": float(q(i.price))} for i in items],
}

View File

@ -5,7 +5,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.session import get_db_session
from app.db.models import AccessPlan, AccessPlanModule, Module
from app.features.admin.services.module_service import resolve_module_category
router = APIRouter(tags=["Public Plans Catalog"])
@ -23,65 +22,35 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
all_plans = plans_q.scalars().all()
plan_mods_q = await session.execute(
select(
AccessPlanModule.plan_id,
Module.code,
Module.slug,
Module.name,
Module.description,
Module.metadata_json,
)
select(AccessPlanModule.plan_id, Module.slug, Module.name)
.join(Module, AccessPlanModule.module_id == Module.id)
.where(Module.is_active.is_(True))
)
mod_map: dict[str, list[dict[str, Any]]] = {}
for pid, m_code, slug, name, desc, m_meta in plan_mods_q.all():
mod_map: dict[str, list[dict[str, str]]] = {}
for pid, slug, name in plan_mods_q.all():
pid_str = str(pid)
if pid_str not in mod_map:
mod_map[pid_str] = []
meta_dict = m_meta or {}
try:
sort_order = int(meta_dict.get("sort_order", 99999))
except (ValueError, TypeError):
sort_order = 99999
mod_map[pid_str].append({
"code": m_code,
"slug": slug,
"name": name,
"description": desc or "",
"category": resolve_module_category(meta_dict),
"sort_order": sort_order,
})
for mods_list in mod_map.values():
mods_list.sort(key=lambda m: (m["sort_order"], m["name"]))
mod_map[pid_str].append({"slug": slug, "name": name})
groups: dict[str, dict[str, Any]] = {}
for p in all_plans:
code = p.code
is_usd = code.endswith("_USD") or p.currency_code == "USD"
is_eur = code.endswith("_EUR") or p.currency_code == "EUR"
base_code = code[:-4] if (code.endswith("_USD") or code.endswith("_EUR")) else code
base_code = code[:-4] if code.endswith("_USD") else code
pid_str = str(p.id)
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
meta = p.metadata_json or {}
if base_code not in groups:
clean_name = (
p.name.replace(" (USD)", "")
.replace(" - USD", "")
.replace(" (EUR)", "")
.replace(" - EUR", "")
)
groups[base_code] = {
"code": base_code,
"name": clean_name,
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
"description": p.description or "",
"plan_type": getattr(p.plan_type, "value", p.plan_type),
"billing_period": getattr(p.billing_period, "value", p.billing_period),
"price_inr": 0.0,
"price_usd": 0.0,
"price_eur": 0.0,
"is_active": p.is_active,
"badge_text": meta.get("badge_text"),
"heading": meta.get("heading"),
@ -89,17 +58,11 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
"modules": [],
"module_slugs": [],
"is_featured": meta.get("is_featured", False),
"pricing_status": meta.get("pricing_status"),
"color": meta.get("color"),
}
grp = groups[base_code]
if is_usd:
grp["price_usd"] = fee
if not grp.get("price_eur"):
grp["price_eur"] = fee # Default fallback if explicit EUR plan not present
elif is_eur:
grp["price_eur"] = fee
else:
grp["price_inr"] = fee
grp["name"] = p.name

View File

@ -39,29 +39,12 @@ def _string_value(value: Any) -> str | None:
return None
def _flatten_projection_values(value: Any, json_path: Any = None) -> list[str]:
def _flatten_projection_values(value: Any) -> list[str]:
if value is None:
return []
if isinstance(value, list):
result: list[str] = []
for item in value:
result.extend(_flatten_projection_values(item, json_path))
return result
if isinstance(value, dict):
if json_path:
paths = [json_path] if isinstance(json_path, str) else list(json_path)
extracted: list[str] = []
for p in paths:
sub_val = value.get(p)
if sub_val is not None:
extracted.extend(_flatten_projection_values(sub_val))
if extracted:
return extracted
direct = _string_value(value)
if direct:
return [direct]
result = []
for item in value.values():
result.extend(_flatten_projection_values(item))
return result
direct = _string_value(value)
@ -163,14 +146,12 @@ class SearchRepository:
) -> list[dict[str, Any]]:
effective_scope = scope or SearchScope()
params: dict[str, Any] = {}
where = ["is_active = true", "status = 'active'"]
if effective_scope.module_codes:
where = ["status in ('active', 'inactive')"]
params["capability_module_codes"] = [
code.strip().lower() for code in effective_scope.module_codes if code and code.strip()
]
where.append("code = any(cast(:capability_module_codes as text[]))")
else:
where = ["is_active = true", "status = 'active'"]
result = await self.session.execute(
text(
@ -309,30 +290,9 @@ class SearchRepository:
values.append(row["value_date"].isoformat())
return values
def _project_value(
self,
raw: Any,
strategy: str,
metadata: dict[str, Any] | None = None,
) -> list[ProjectionValue]:
def _project_value(self, raw: Any, strategy: str) -> list[ProjectionValue]:
strategy = strategy.strip().lower()
json_path = (metadata or {}).get("json_path") or (metadata or {}).get("json_key")
raw_values = _flatten_projection_values(raw, json_path=json_path)
if strategy in ("multivalue", "comma_delimited", "delimited"):
split_values: list[str] = []
for item in raw_values:
if "," in item or ";" in item:
for token in item.replace(";", ",").split(","):
cleaned = token.strip().rstrip(".").strip()
if cleaned:
cleaned = cleaned[:1].upper() + cleaned[1:]
split_values.append(cleaned)
else:
cleaned = item.strip().rstrip(".").strip()
if cleaned:
cleaned = cleaned[:1].upper() + cleaned[1:]
split_values.append(cleaned)
raw_values = split_values
raw_values = _flatten_projection_values(raw)
projected: list[ProjectionValue] = []
seen: set[str] = set()
for label in raw_values:
@ -446,13 +406,7 @@ class SearchRepository:
)
values: list[ProjectionValue] = []
for raw in raw_rows:
values.extend(
self._project_value(
raw,
mapping.mapping_strategy,
metadata=mapping.metadata,
)
)
values.extend(self._project_value(raw, mapping.mapping_strategy))
seen: set[str] = set()
for value in values:
@ -536,13 +490,13 @@ class SearchRepository:
code.strip().lower() for code in scope.module_codes if code and code.strip()
]
clauses.append(
f"""exists (
f"""exists (
select 1
from {self.schema}.module_contents scope_mc
join {self.schema}.modules scope_m on scope_m.id = scope_mc.module_id
where scope_mc.content_id = {ci_alias}.id
and scope_m.code = any(cast(:scope_module_codes as text[]))
and scope_m.status in ('active', 'inactive')
and scope_m.is_active = true
)"""
)
if scope.content_kinds:
@ -675,109 +629,9 @@ class SearchRepository:
score_expr = "0.0"
if query:
clean_query = query.strip()
params["raw_query"] = clean_query
params["like_query"] = f"%{clean_query}%"
params["prefix_like"] = f"{clean_query}%"
tokens = re.findall(r"\w+", clean_query)
if tokens:
all_tokens = list(dict.fromkeys(tokens))
stem_tokens = set(all_tokens)
for t in all_tokens:
root = re.sub(r"(ies|y|ical|ic|s|ed|ing)$", "", t, flags=re.IGNORECASE)
if len(root) >= 3:
stem_tokens.add(root)
and_prefix = " & ".join(f"{t}:*" for t in all_tokens)
or_prefix = " | ".join(f"{t}:*" for t in all_tokens)
params["and_prefix_query"] = and_prefix
params["or_prefix_query"] = or_prefix
tok_conditions: list[str] = []
tok_score_parts: list[str] = []
mod_tok_gate = "m_tok.status in ('active', 'inactive')" if scope.module_codes else "m_tok.is_active = true"
mod_s_gate = "m_s.status in ('active', 'inactive')" if scope.module_codes else "m_s.is_active = true"
for idx, tok in enumerate(list(stem_tokens)[:8]):
p_name = f"tok_{idx}"
params[p_name] = f"%{tok}%"
tok_conditions.append(
f"(ci.title ilike :{p_name} or csd.search_text ilike :{p_name} or exists ("
f"select 1 from {self.schema}.module_contents mc_tok "
f"join {self.schema}.modules m_tok on m_tok.id = mc_tok.module_id "
f"where mc_tok.content_id = ci.id and {mod_tok_gate} and ("
f"m_tok.name ilike :{p_name} or m_tok.code ilike :{p_name})"
f"))"
)
tok_score_parts.append(
f"(case when ci.title ilike :{p_name} then 6.0 else 0.0 end) + "
f"(case when exists (select 1 from {self.schema}.module_contents mc_s "
f"join {self.schema}.modules m_s on m_s.id = mc_s.module_id "
f"where mc_s.content_id = ci.id and {mod_s_gate} and ("
f"m_s.name ilike :{p_name} or m_s.code ilike :{p_name})) then 4.0 else 0.0 end)"
)
combined_tok_cond = " or ".join(tok_conditions)
tok_score_sql = " + ".join(tok_score_parts) if tok_score_parts else "0.0"
mod_filter_gate = "m_mod.status in ('active', 'inactive')" if scope.module_codes else "m_mod.is_active = true"
where.append(
f"""(
csd.search_vector @@ to_tsquery('simple', :and_prefix_query)
or csd.search_vector @@ to_tsquery('simple', :or_prefix_query)
or csd.search_vector @@ websearch_to_tsquery('simple', :raw_query)
or csd.search_text ilike :like_query
or ci.title ilike :like_query
or exists (
select 1
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
)
or ({combined_tok_cond})
)"""
)
score_expr = f"""(
(case when ci.title ilike :raw_query then 100.0
when ci.title ilike :prefix_like then 50.0
when ci.title ilike :like_query then 25.0
else 0.0 end) +
{tok_score_sql} +
coalesce(ts_rank_cd(csd.search_vector, to_tsquery('simple', :and_prefix_query)), 0.0) * 10.0 +
coalesce(ts_rank_cd(csd.search_vector, to_tsquery('simple', :or_prefix_query)), 0.0) * 2.0 +
(case when exists (
select 1
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
) then 15.0 else 0.0 end)
)"""
else:
mod_filter_gate = "m_mod.status in ('active', 'inactive')" if scope.module_codes else "m_mod.is_active = true"
where.append(
f"""(
csd.search_text ilike :like_query
or ci.title ilike :like_query
or exists (
select 1
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
)
)"""
)
score_expr = f"""(
case when ci.title ilike :raw_query then 100.0
when ci.title ilike :prefix_like then 50.0
when ci.title ilike :like_query then 25.0
else 1.0 end
)"""
params["search_query"] = query
where.append("csd.search_vector @@ websearch_to_tsquery('simple', :search_query)")
score_expr = "ts_rank_cd(csd.search_vector, websearch_to_tsquery('simple', :search_query))"
direction = "asc" if sort_direction == "asc" else "desc"
if sort_field == "title":
@ -825,7 +679,7 @@ class SearchRepository:
m.name as module_name
from {self.schema}.module_contents mc
join {self.schema}.modules m on m.id = mc.module_id
where {"m.status in ('active', 'inactive')" if scope.module_codes else "m.is_active = true"}
where m.is_active = true
{"and m.code = any(:scope_module_codes)" if scope.module_codes else ""}
order by mc.content_id, mc.sort_order, m.code
)

View File

@ -6,8 +6,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.enums import BillingPeriod, EntitlementStatus, PaymentStatus, SubscriptionStatus
from app.db.models import AccessPlan, AccessPlanModule, Coupon, Invoice, PaymentTransaction, UserEntitlement, UserSubscription
from app.features.payments import generate_next_invoice_number, record_coupon_redemption
from app.db.models import AccessPlan, AccessPlanModule, Invoice, PaymentTransaction, UserEntitlement, UserSubscription
class RazorpayWebhookService:
@ -95,26 +94,13 @@ class RazorpayWebhookService:
gst = Decimal(str(meta.get("gst_amount", "0")))
base = Decimal(str(meta.get("base_subtotal", amount)))
discount = Decimal(str(meta.get("total_discounts", "0")))
invoice_number = await generate_next_invoice_number(self.session, dt=now)
coupon_code = meta.get("coupon_code") or (payment.get("notes") or {}).get("coupon_code") or None
coupon = (await self.session.execute(
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
)).scalar_one_or_none() if coupon_code else None
if payment.get("contact") and subs:
sub_meta = dict(subs[0].metadata_json or {})
if not sub_meta.get("billing_phone"):
sub_meta["billing_phone"] = payment.get("contact")
subs[0].metadata_json = sub_meta
invoice = Invoice(
invoice_number = f"INV-{now.strftime('%Y%m%d')}-{payment_id[-6:].upper()}"
self.session.add(Invoice(
payment_transaction_id=transaction.id,
invoice_number=invoice_number,
billing_name=((payment.get("card") or {}).get("name") or payment.get("email") or "Customer"),
billing_email=payment.get("email") or "unknown@example.invalid",
billing_address="Recorded from Gateway Webhook",
applied_coupon_id=coupon.id if coupon else None,
base_amount=base,
discount_amount=discount,
taxable_amount=taxable,
@ -123,17 +109,7 @@ class RazorpayWebhookService:
currency_code=currency,
exchange_rate_to_inr=Decimal("1"),
total_amount_inr=amount if currency == "INR" else None,
)
self.session.add(invoice)
await self.session.flush()
if coupon:
await record_coupon_redemption(
self.session,
coupon=coupon,
user_id=main.user_id,
invoice_id=invoice.id,
)
))
await self.session.commit()
return {"status": "accepted"}

View File

@ -113,26 +113,6 @@ async def lifespan(
"Redis caching disabled"
)
# -------------------------------------------------------------
# Ensure commerce.invoice_monthly_sequences table exists
# -------------------------------------------------------------
try:
from app.db.session import engine
from sqlalchemy import text
async with engine.begin() as conn:
await conn.execute(text(
"""
CREATE TABLE IF NOT EXISTS commerce.invoice_monthly_sequences (
year_month VARCHAR(7) PRIMARY KEY,
last_serial INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
"""
))
logger.info("Commerce invoice sequence table verified")
except Exception as exc:
logger.warning("Could not auto-verify invoice sequence table on startup: %s", exc)
yield
finally:

View File

@ -39,18 +39,11 @@ With the clean Acupedia naming conventions:
- **Database**: `acupedia_db`
- **User**: `db_admin` / Password: `C1234spl`
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
- **MinIO Bucket**: `acupedia-media`
### Step 2.1: Generate Container Git Info Metadata (Recommended)
Before building, run the script to capture the branch and commit of `api`, `store`, and `admin`:
- **MinIO Bucket**: `accupedia-media`
### Start the containers:
```bash
cd ~/acupedia/acupedia_ops
./scripts/generate-git-info.sh
```
### Step 2.2: Start the Containers
```bash
docker compose -f docker-compose.dev.yml up -d --build
```
@ -70,20 +63,7 @@ docker compose -f docker-compose.dev.yml exec backend \
---
### Step 3.2: Run Alembic Migrations (Module Builder & Dynamic Content)
Stamps the baseline DDL (schema v5 includes migrations up to `0003`) and applies new migrations (such as Module Builder tables `content.builder_modules`, `content.builder_categories`, etc.):
```bash
docker compose -f docker-compose.dev.yml exec backend \
alembic stamp 0003_monthly_invoice_seq
docker compose -f docker-compose.dev.yml exec backend \
alembic upgrade head
```
---
### Step 3.3: Seed Authentication & Super Admin User
### Step 3.2: Seed Authentication & Super Admin User
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
```bash
@ -95,7 +75,7 @@ docker compose -f docker-compose.dev.yml exec -e ACCUPEDIA_BOOTSTRAP_ADMIN_PASSW
---
### Step 3.4: Seed Content & Modules
### Step 3.3: Seed Content & Modules
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
```bash
@ -109,7 +89,7 @@ docker compose -f docker-compose.dev.yml exec backend \
---
### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`acupedia-media` bucket) and links them to their respective content items in PostgreSQL:
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`accupedia-media` bucket) and links them to their respective content items in PostgreSQL:
**Option A (Recommended — Automated 1-line loop for all 4 modules):**
```bash
@ -206,25 +186,3 @@ After running the manual steps above, test your endpoints:
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
### Git Identity Verification (Inspect Container Branch & Commit)
To verify which branch and commit are running inside each container:
```bash
# 1. API Backend
docker compose -f docker-compose.dev.yml exec backend cat /app/.git_api_info
# 2. Storefront
docker compose -f docker-compose.dev.yml exec store cat /app/.git_store_info
# 3. Admin Portal
docker compose -f docker-compose.dev.yml exec admin cat /app/.git_admin_info
```
Example output:
```text
Branch: main
Commit: 29279bfd72a6fa296d1aa05a825bd88ca1f36c91
```

View File

@ -2638,12 +2638,6 @@ create table if not exists commerce.invoices (
)
);
create table if not exists commerce.invoice_monthly_sequences (
year_month varchar(7) primary key,
last_serial integer not null default 0,
updated_at timestamptz not null default now()
);
do $$
begin
if not exists (

View File

@ -1,138 +0,0 @@
# Acupedia API - Test Suite Implementation Plan
## 1. Overview & Objectives
This implementation plan outlines the strategy, architecture, and step-by-step tasks to achieve comprehensive test coverage for `acupedia-api` using **`pytest`**.
### Goals:
- **Fast & Deterministic:** Run tests without requiring external services (no live Razorpay, MinIO, or Redis connections required).
- **High Coverage:** Cover all core business logic (Cart, Subscriptions, Pricing, Security) and API endpoints (Auth, Content, Admin, Webhooks).
- **Maintainable Architecture:** Modular test structure following standard FastAPI and pytest conventions.
---
## 2. Directory Structure
```text
acupedia-api/
├── pyproject.toml
└── tests/
├── conftest.py # Global fixtures (AsyncClient, DB mocks, Auth tokens, Service mocks)
├── unit/ # Unit tests (Business logic & schemas, isolated)
│ ├── test_security.py # Password strength, hashing, JWT encode/decode
│ ├── test_cart_service.py # Pricing logic, currency conversion (INR/USD), coupon rules
│ ├── test_plans_service.py # Plan validation & subscription business rules
│ ├── test_schemas.py # Pydantic input/output validations
│ └── test_exception_handlers.py# HTTP error mappings and custom exceptions
└── api/ # Integration tests for FastAPI routers
├── test_auth_api.py # /api/auth (register, login, refresh, password reset)
├── test_access_api.py # /api/access (entitlements & module access)
├── test_content_api.py # /api/content (modules, channels, points, topics)
├── test_plans_api.py # /api/plans (plan listings, active filters)
├── test_cart_api.py # /api/cart (add items, calculate subtotal & tax)
├── test_checkout_api.py # /api/checkout (order creation, invoice initiation)
├── test_webhooks_api.py # /api/webhooks (Razorpay payment signature & status)
├── test_search_api.py # /api/search (query parameters, search scopes)
└── test_admin_api.py # /api/admin (RBAC 403 vs 200, CRUD management)
```
---
## 3. Phased Implementation Roadmap
### Phase 1: Environment & Test Harness Setup
- [x] **Install Test Dependencies into `.venv`:**
- `pytest>=7.0.0`
- `pytest-asyncio>=0.21.0`
- `httpx>=0.24.0`
- `pytest-cov` (coverage reporting)
- `pytest-mock` (for clean mock fixtures)
- [x] **Configure `conftest.py` with Reusable Fixtures:**
- **`app` & `async_client`:** Setup `httpx.AsyncClient` with `ASGITransport` targeting FastAPI `app`.
- **Database Fixture:** Mock session / transaction rollback fixture for safe, isolated database testing.
- **Auth Fixtures:**
- `user_token` & `auth_headers` (standard authenticated user)
- `admin_token` & `admin_headers` (superuser / admin role)
- `expired_token` & `invalid_token` (for testing 401 Unauthorized responses)
- **Service Mocks:**
- Mock MinIO client (`get_presigned_url`, file uploads)
- Mock Redis client (`get`, `set`, `delete`)
- Mock Razorpay client (`order.create`, `utility.verify_payment_signature`)
- Mock Email/SMTP dispatcher
---
### Phase 2: Unit Testing (Domain & Business Logic)
*Fast, isolated tests without database or network overhead.*
- [x] **Security & Auth (`tests/unit/test_security.py`):**
- Password hashing & verification (`verify_password`, `hash_password`).
- Password strength validation edge cases (spaces, minimum length, special characters, uppercase, digits).
- JWT creation, decoding, expiration validation, invalid signature handling.
- [x] **Cart & Pricing Engine (`tests/unit/test_cart_pricing.py`):**
- Currency resolution (`USD` vs `INR`).
- Item resolution (e.g. `POINTS_ACU`, `LIFETIME_ALL`, suffixed items).
- Coupon code validation (valid coupon, expired coupon, minimum purchase requirement).
- Subtotal, discount calculations, convenience fees, and tax calculations.
- [x] **Schema Validation (`tests/unit/test_schemas.py`):**
- Verify Pydantic validation rejects invalid email formats, missing fields, or negative prices.
- [x] **Exception Handlers (`tests/test_exception_handlers.py`):**
- Verify standard error schema (`{"detail": {"code": ..., "message": ...}}`).
---
### Phase 3: API Integration Testing (Endpoints & Routes)
*Testing HTTP responses, route security, and status codes.*
- [x] **Auth Router (`tests/api/test_auth_api.py`):**
- `POST /api/auth/register` (success, duplicate email, weak password).
- `POST /api/auth/login` (valid credentials, wrong password, non-existent user).
- `GET /api/auth/me` (unauthorized 401 when anonymous, profile when authenticated).
- `POST /api/auth/forgot-password` (triggers OTP email delivery flow).
- [x] **Access & Entitlements (`tests/api/test_content_and_access_api.py`):**
- Check user entitlement and active subscriptions via `/api/access/me` (401 vs 200).
- [x] **Content Router (`tests/api/test_content_and_access_api.py`):**
- `GET /api/contents/modules` (retrieves active module listing).
- [x] **Plans Router (`tests/api/test_plans_api.py`):**
- `GET /api/plans` (retrieves public subscription plans catalog).
- [x] **Cart & Checkout (`tests/api/test_cart_api.py`, `tests/api/test_checkout_api.py`):**
- `POST /api/cart/calculate` (valid pricing calculations, 422 on empty cart, 400 on invalid codes).
- `GET /api/checkout/config` (Razorpay public key).
- `POST /api/checkout/create-order` (order creation with Razorpay integration, 401 on unauthorized).
- [x] **Webhooks (`tests/api/test_webhooks_api.py`):**
- `POST /api/webhooks/razorpay` with valid signature & successful payment event.
- `POST /api/webhooks/razorpay` with invalid signature (rejects with 400).
- `POST /api/webhooks/razorpay` with malformed JSON (rejects with 400).
- [x] **Admin Operations & RBAC (`tests/api/test_admin_api.py`):**
- Non-authenticated user gets `401 Unauthorized`.
- Non-admin user gets `403 Forbidden: Administrative privileges required`.
- Admin user gets `200 OK` on admin management endpoints.
- [x] **Search Router (`tests/api/test_search_api.py`):**
- `GET /api/search/capabilities` (retrieves searchable kinds and facets).
- `POST /api/search/facet-values` (404 on unknown facet).
---
### Phase 4: Coverage & Verification
- [x] Run full test suite:
```bash
.venv/bin/pytest -v
```
- [x] Run test coverage report:
```bash
.venv/bin/pytest --cov=app --cov-report=term-missing
```
- [x] Verify 100% of tests pass cleanly (88 of 88 passed).
---
## 4. Execution Order
| Step | Action | Output |
| :--- | :--- | :--- |
| **Step 1** | Install dev dependencies | `.venv` ready with pytest & httpx |
| **Step 2** | Create `conftest.py` with mock fixtures | Standardized fixtures ready for use |
| **Step 3** | Implement Unit Tests (`tests/unit/`) | Fast unit test coverage for logic & security |
| **Step 4** | Implement API Route Tests (`tests/api/`) | Full endpoint coverage across all features |
| **Step 5** | Verify & Coverage Summary | Clean passing test suite with coverage metrics |

View File

@ -17,8 +17,7 @@ dependencies = [
"uvicorn[standard]>=0.20.0",
"python-dotenv>=1.0.0",
"PyYAML>=6.0",
"SQLAlchemy[asyncio]>=2.0.0",
"greenlet>=3.0.0",
"SQLAlchemy>=2.0.0",
"asyncpg>=0.28.0",
"python-jose[cryptography]>=3.3.0",
"passlib[bcrypt]>=1.7.4",
@ -41,8 +40,6 @@ dev = [
"pytest>=7.0.0",
"pytest-asyncio>=0.21.0",
"httpx>=0.24.0",
"pytest-cov>=4.0.0",
"pytest-mock>=3.10.0",
"ruff>=0.1.0",
]
@ -57,7 +54,7 @@ packages = ["app"]
minversion = "7.0"
addopts = "-ra -q"
testpaths = [
"tests"
"."
]
python_files = "test_*.py *_test.py"
asyncio_mode = "auto"

View File

@ -1,111 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from httpx import AsyncClient
from app.main import app
from app.db.models import AppUser
from app.features.checkout.deps import get_current_user
from app.features.admin.deps import get_admin_service, get_current_admin
from app.features.admin.schema import AdminUserListResponse
@pytest.fixture
def mock_admin_service() -> MagicMock:
service = MagicMock()
mock_users = [
AdminUserListResponse(
id=uuid4(),
email="superadmin@acupedia.test",
display_name="Super Admin",
country="India",
is_active=True,
roles=["super_admin"],
subscriptions=[],
)
]
service.list_users = AsyncMock(return_value=mock_users)
service.customers = MagicMock()
service.customers.list_users = AsyncMock(return_value=mock_users)
return service
@pytest.mark.asyncio
async def test_admin_endpoint_unauthorized_without_auth(async_client: AsyncClient) -> None:
response = await async_client.get("/api/admin/super-admins")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_admin_endpoint_forbidden_for_regular_user(
async_client: AsyncClient,
sample_user: AppUser,
) -> None:
# Simulating regular practitioner accessing admin endpoint
app.dependency_overrides[get_current_user] = lambda: sample_user
response = await async_client.get(
"/api/admin/super-admins",
headers={"Authorization": "Bearer regular_user_token"},
)
app.dependency_overrides.pop(get_current_user, None)
assert response.status_code == 403
assert "Forbidden" in response.json()["detail"]
@pytest.mark.asyncio
async def test_admin_endpoint_authorized_for_admin(
async_client: AsyncClient,
sample_admin: AppUser,
mock_admin_service: MagicMock,
) -> None:
app.dependency_overrides[get_current_admin] = lambda: sample_admin
app.dependency_overrides[get_admin_service] = lambda: mock_admin_service
response = await async_client.get(
"/api/admin/super-admins",
headers={"Authorization": "Bearer admin_token"},
)
app.dependency_overrides.pop(get_current_admin, None)
app.dependency_overrides.pop(get_admin_service, None)
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["email"] == "superadmin@acupedia.test"
@pytest.mark.asyncio
async def test_get_admin_modules_returns_generic_categories(
async_client: AsyncClient,
sample_admin: AppUser,
mock_admin_service: MagicMock,
) -> None:
mock_modules = [
{"id": str(uuid4()), "code": "m0001", "slug": "acupuncture-points", "name": "Acupuncture Points", "category": "Points", "color": "#2563EB", "icon": "water-outline"},
{"id": str(uuid4()), "code": "m0011", "slug": "eight-principles", "name": "Eight Principles", "category": "Patterns", "color": "#8B5CF6", "icon": "analytics-outline"},
{"id": str(uuid4()), "code": "m0031", "slug": "nutrition", "name": "Nutrition", "category": "Nutrition", "color": "#10B981", "icon": "leaf-outline"},
{"id": str(uuid4()), "code": "m0041", "slug": "auriculotherapy", "name": "Auriculotherapy", "category": "Therapeutics", "color": "#EC4899", "icon": "medkit-outline"},
]
mock_admin_service.list_modules = AsyncMock(return_value=mock_modules)
app.dependency_overrides[get_current_admin] = lambda: sample_admin
app.dependency_overrides[get_admin_service] = lambda: mock_admin_service
response = await async_client.get(
"/api/admin/modules",
headers={"Authorization": "Bearer admin_token"},
)
app.dependency_overrides.pop(get_current_admin, None)
app.dependency_overrides.pop(get_admin_service, None)
assert response.status_code == 200
data = response.json()
assert len(data) == 4
categories = {m["code"]: m["category"] for m in data}
assert categories["m0001"] == "Points"
assert categories["m0011"] == "Patterns"
assert categories["m0031"] == "Nutrition"
assert categories["m0041"] == "Therapeutics"

View File

@ -1,208 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.auth.deps import get_auth_service
from app.features.auth.errors import InvalidCredentialsError, SamePasswordError, UserAlreadyExistsError
from app.features.auth.schema import (
AuthTokenResponse,
AuthTokenUserResponse,
ForgotPasswordResponse,
UserIdentityResponse,
)
@pytest.fixture
def mock_auth_service() -> MagicMock:
service = MagicMock()
service.session = AsyncMock()
service.session.commit = AsyncMock()
service.session.rollback = AsyncMock()
return service
@pytest.mark.asyncio
async def test_register_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.register = AsyncMock(return_value=AuthTokenResponse(
access_token="mock_access_token_123",
token_type="bearer",
user=AuthTokenUserResponse(
id=user_id,
email="dr.smith@acupedia.test",
display_name="Dr. Smith",
country="India",
roles=["practitioner"],
)
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "dr.smith@acupedia.test",
"password": "SecurePassword123!",
"full_name": "Dr. Smith",
"country": "India",
}
response = await async_client.post("/api/auth/register", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["access_token"] == "mock_access_token_123"
assert data["user"]["email"] == "dr.smith@acupedia.test"
assert "practitioner" in data["user"]["roles"]
@pytest.mark.asyncio
async def test_register_duplicate_email_fails(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.register = AsyncMock(side_effect=UserAlreadyExistsError("An account already exists."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "existing@acupedia.test",
"password": "SecurePassword123!",
}
response = await async_client.post("/api/auth/register", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "already exists" in response.json()["detail"]
@pytest.mark.asyncio
async def test_register_invalid_payload_fails_validation(async_client: AsyncClient) -> None:
# Missing required password field
response = await async_client.post("/api/auth/register", json={"email": "bad@test.com"})
assert response.status_code == 422
@pytest.mark.asyncio
async def test_login_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.login = AsyncMock(return_value=AuthTokenResponse(
access_token="valid_login_token_abc",
token_type="bearer",
user=AuthTokenUserResponse(
id=user_id,
email="dr.login@acupedia.test",
display_name="Dr. Login",
country="India",
roles=["practitioner"],
)
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "dr.login@acupedia.test",
"password": "CorrectPassword123!",
}
response = await async_client.post("/api/auth/login", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["access_token"] == "valid_login_token_abc"
@pytest.mark.asyncio
async def test_login_invalid_credentials_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.login = AsyncMock(side_effect=InvalidCredentialsError("Invalid email/phone or password."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"email": "wrong@acupedia.test",
"password": "WrongPassword123!",
}
response = await async_client.post("/api/auth/login", json=payload)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "Invalid email/phone or password" in response.json()["detail"]
@pytest.mark.asyncio
async def test_get_identity_unauthorized_when_no_token(async_client: AsyncClient) -> None:
response = await async_client.get("/api/auth/me")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_get_identity_success_with_token(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
user_id = uuid4()
mock_auth_service.get_identity = AsyncMock(return_value=UserIdentityResponse(
id=user_id,
email="doctor@acupedia.test",
display_name="Doctor A",
country="India",
roles=["practitioner"],
))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
headers = {"Authorization": "Bearer sample_valid_token"}
response = await async_client.get("/api/auth/me", headers=headers)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
data = response.json()
assert data["email"] == "doctor@acupedia.test"
@pytest.mark.asyncio
async def test_forgot_password_success(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.forgot_password = AsyncMock(return_value=(
ForgotPasswordResponse(
status="success",
message="If an account exists, a reset code was sent.",
),
"123456",
))
mock_auth_service.send_password_reset_email = AsyncMock(return_value=True)
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
response = await async_client.post("/api/auth/forgot-password", json={"email": "dr.smith@acupedia.test"})
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 200
assert response.json()["status"] == "success"
assert mock_auth_service.send_password_reset_email.await_count == 1
@pytest.mark.asyncio
async def test_change_password_same_password_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.change_password = AsyncMock(side_effect=SamePasswordError("New password cannot be the same as current password."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"old_password": "OldPassword123!",
"new_password": "OldPassword123!",
}
headers = {"Authorization": "Bearer sample_valid_token"}
response = await async_client.post("/api/auth/change-password", json=payload, headers=headers)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "New password cannot be the same as current password" in response.json()["detail"]
@pytest.mark.asyncio
async def test_update_profile_duplicate_phone_returns_400(async_client: AsyncClient, mock_auth_service: MagicMock) -> None:
mock_auth_service.update_profile = AsyncMock(side_effect=UserAlreadyExistsError("An account with this phone number already exists."))
app.dependency_overrides[get_auth_service] = lambda: mock_auth_service
payload = {
"full_name": "Dr. User Two",
"phone_number": "+8809988776655",
"country": "Bangladesh",
}
headers = {"Authorization": "Bearer sample_valid_token"}
response = await async_client.put("/api/auth/profile", json=payload, headers=headers)
app.dependency_overrides.pop(get_auth_service, None)
assert response.status_code == 400
assert "already exists" in response.json()["detail"]

View File

@ -1,82 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.cart.deps import get_cart_service
from app.features.cart.schema import CartCalculationResponse, CartItemResponse
@pytest.fixture
def mock_cart_service() -> MagicMock:
return MagicMock()
@pytest.mark.asyncio
async def test_calculate_cart_success(async_client: AsyncClient, mock_cart_service: MagicMock) -> None:
mock_cart_service.calculate = AsyncMock(return_value=CartCalculationResponse(
currency="INR",
base_subtotal=1000.0,
discount_policy="None",
bundle_discount_amount=0.0,
coupon_applied="None",
coupon_discount_amount=0.0,
coupon_error=None,
total_discounts=0.0,
convenience_fee_rate=0.0,
convenience_fee=0.0,
taxable_amount=1000.0,
gst_amount=0.0,
grand_total=1000.0,
cart_items=[
CartItemResponse(
code="MOD_ACU",
name="Acupuncture Module",
category="acu",
price=1000.0,
)
],
))
app.dependency_overrides[get_cart_service] = lambda: mock_cart_service
payload = {
"cart_item_codes": ["MOD_ACU"],
"currency": "INR",
"is_first_purchase": True,
}
response = await async_client.post("/api/cart/calculate", json=payload)
app.dependency_overrides.pop(get_cart_service, None)
assert response.status_code == 200
data = response.json()
assert data["currency"] == "INR"
assert data["grand_total"] == 1000.0
assert len(data["cart_items"]) == 1
@pytest.mark.asyncio
async def test_calculate_cart_unknown_plan_raises_400(async_client: AsyncClient, mock_cart_service: MagicMock) -> None:
mock_cart_service.calculate = AsyncMock(side_effect=ValueError("Unknown/inactive plan code: INVALID_CODE"))
app.dependency_overrides[get_cart_service] = lambda: mock_cart_service
payload = {
"cart_item_codes": ["INVALID_CODE"],
"currency": "INR",
}
response = await async_client.post("/api/cart/calculate", json=payload)
app.dependency_overrides.pop(get_cart_service, None)
assert response.status_code == 400
assert "Unknown/inactive plan code" in response.json()["detail"]
@pytest.mark.asyncio
async def test_calculate_cart_empty_items_returns_422(async_client: AsyncClient) -> None:
payload = {
"cart_item_codes": [],
"currency": "INR",
}
response = await async_client.post("/api/cart/calculate", json=payload)
assert response.status_code == 422

View File

@ -1,73 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
import pytest
from httpx import AsyncClient
from app.main import app
from app.db.models import AppUser
from app.features.checkout.deps import get_checkout_service, get_current_user
from app.features.checkout.schema import CheckoutOrderResponse
@pytest.fixture
def mock_checkout_service() -> MagicMock:
return MagicMock()
@pytest.mark.asyncio
async def test_get_checkout_config(async_client: AsyncClient, mock_razorpay: MagicMock) -> None:
response = await async_client.get("/api/checkout/config")
assert response.status_code == 200
assert "razorpay_key_id" in response.json()
assert response.json()["razorpay_key_id"] == "rzp_test_key_123"
@pytest.mark.asyncio
async def test_create_checkout_order_unauthorized_without_auth(async_client: AsyncClient) -> None:
payload = {
"cart_item_codes": ["MOD_ACU"],
"currency": "INR",
}
response = await async_client.post("/api/checkout/create-order", json=payload)
assert response.status_code == 401
@pytest.mark.asyncio
async def test_create_checkout_order_success(
async_client: AsyncClient,
sample_user: AppUser,
mock_checkout_service: MagicMock,
) -> None:
mock_checkout_service.create_order = AsyncMock(return_value=CheckoutOrderResponse(
razorpay_order_id="order_rzp_12345",
amount=1000.0,
currency="INR",
receipt="RCPT-12345",
base_subtotal=1000.0,
total_discounts=0.0,
convenience_fee=0.0,
convenience_fee_rate=0.0,
taxable_amount=1000.0,
gst_amount=0.0,
grand_total=1000.0,
))
app.dependency_overrides[get_current_user] = lambda: sample_user
app.dependency_overrides[get_checkout_service] = lambda: mock_checkout_service
payload = {
"cart_item_codes": ["MOD_ACU"],
"currency": "INR",
}
response = await async_client.post(
"/api/checkout/create-order",
json=payload,
headers={"Authorization": "Bearer mock_token"},
)
app.dependency_overrides.pop(get_current_user, None)
app.dependency_overrides.pop(get_checkout_service, None)
assert response.status_code == 200
data = response.json()
assert data["razorpay_order_id"] == "order_rzp_12345"
assert data["grand_total"] == 1000.0

View File

@ -1,94 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.access.deps import get_access_service, get_current_user_id
from app.features.access.schema import AccessMeResponse
from app.features.content.deps import get_content_service
from app.features.content.schema import ModuleListResponse
from datetime import datetime
from app.db.enums import ModuleStatus
@pytest.fixture
def mock_content_service() -> MagicMock:
service = MagicMock()
service.get_modules = AsyncMock(return_value=ModuleListResponse(
modules=[
{
"id": uuid4(),
"code": "MOD_ACU",
"slug": "acupuncture",
"name": "Acupuncture",
"category": "clinical",
"is_active": True,
"status": ModuleStatus.ACTIVE,
"preview_enabled": True,
"preview_item_limit": 5,
"created_at": datetime.now(),
"updated_at": datetime.now(),
}
]
))
return service
@pytest.fixture
def mock_access_service() -> MagicMock:
service = MagicMock()
return service
@pytest.mark.asyncio
async def test_get_content_modules(
async_client: AsyncClient,
mock_content_service: MagicMock,
) -> None:
app.dependency_overrides[get_content_service] = lambda: mock_content_service
response = await async_client.get("/api/contents/modules")
app.dependency_overrides.pop(get_content_service, None)
assert response.status_code == 200
data = response.json()
assert "modules" in data
assert len(data["modules"]) == 1
assert data["modules"][0]["code"] == "MOD_ACU"
@pytest.mark.asyncio
async def test_access_me_unauthorized_without_token(async_client: AsyncClient) -> None:
response = await async_client.get("/api/access/me")
assert response.status_code == 401
@pytest.mark.asyncio
async def test_access_me_success_with_token(
async_client: AsyncClient,
mock_access_service: MagicMock,
) -> None:
user_id = uuid4()
mock_access_service.get_access_me = AsyncMock(return_value=AccessMeResponse(
user_id=user_id,
active_subscriptions=[],
active_entitlements=[],
))
app.dependency_overrides[get_current_user_id] = lambda: user_id
app.dependency_overrides[get_access_service] = lambda: mock_access_service
response = await async_client.get(
"/api/access/me",
headers={"Authorization": "Bearer mock_valid_token"},
)
app.dependency_overrides.pop(get_current_user_id, None)
app.dependency_overrides.pop(get_access_service, None)
assert response.status_code == 200
data = response.json()
assert data["user_id"] == str(user_id)
assert data["active_subscriptions"] == []

View File

@ -1,11 +0,0 @@
from __future__ import annotations
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_get_public_plans_catalog(async_client: AsyncClient) -> None:
response = await async_client.get("/api/plans")
assert response.status_code == 200
assert isinstance(response.json(), list)

View File

@ -1,53 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.search.deps import get_search_service
from app.features.search.errors import FacetNotFoundError
from app.features.search.schema import SearchCapabilitiesResponse
@pytest.fixture
def mock_search_service() -> MagicMock:
service = MagicMock()
service.capabilities = AsyncMock(return_value=SearchCapabilitiesResponse(
modules=[{"code": "MOD_ACU", "name": "Acupuncture"}],
content_kinds=["article", "video"],
facets=[],
))
return service
@pytest.mark.asyncio
async def test_get_search_capabilities(
async_client: AsyncClient,
mock_search_service: MagicMock,
) -> None:
app.dependency_overrides[get_search_service] = lambda: mock_search_service
response = await async_client.get("/api/search/capabilities")
app.dependency_overrides.pop(get_search_service, None)
assert response.status_code == 200
data = response.json()
assert "content_kinds" in data
assert "video" in data["content_kinds"]
@pytest.mark.asyncio
async def test_facet_values_not_found_returns_404(
async_client: AsyncClient,
mock_search_service: MagicMock,
) -> None:
mock_search_service.facet_values = AsyncMock(side_effect=FacetNotFoundError("Facet 'color' not found."))
app.dependency_overrides[get_search_service] = lambda: mock_search_service
payload = {"facet_code": "color"}
response = await async_client.post("/api/search/facet-values", json=payload)
app.dependency_overrides.pop(get_search_service, None)
assert response.status_code == 404
assert response.json()["detail"]["code"] == "FACET_NOT_FOUND"

View File

@ -1,71 +0,0 @@
from __future__ import annotations
import json
from unittest.mock import AsyncMock, MagicMock
import pytest
from httpx import AsyncClient
from app.main import app
from app.features.webhooks.deps import get_webhook_service
@pytest.fixture
def mock_webhook_service() -> MagicMock:
service = MagicMock()
service.handle = AsyncMock(return_value={"status": "handled", "event": "payment.captured"})
return service
@pytest.mark.asyncio
async def test_razorpay_webhook_invalid_signature_raises_400(
async_client: AsyncClient,
mock_razorpay: MagicMock,
) -> None:
mock_razorpay.verify_webhook_signature = MagicMock(return_value=False)
payload = {"event": "payment.captured", "payload": {}}
response = await async_client.post(
"/api/webhooks/razorpay",
content=json.dumps(payload),
headers={"X-Razorpay-Signature": "invalid_sig", "Content-Type": "application/json"},
)
assert response.status_code == 400
assert "Webhook verification failed" in response.json()["detail"]
@pytest.mark.asyncio
async def test_razorpay_webhook_success(
async_client: AsyncClient,
mock_razorpay: MagicMock,
mock_webhook_service: MagicMock,
) -> None:
mock_razorpay.verify_webhook_signature = MagicMock(return_value=True)
app.dependency_overrides[get_webhook_service] = lambda: mock_webhook_service
payload = {"event": "payment.captured", "payload": {"payment": {"entity": {"id": "pay_123"}}}}
response = await async_client.post(
"/api/webhooks/razorpay",
content=json.dumps(payload),
headers={"X-Razorpay-Signature": "valid_mock_signature", "Content-Type": "application/json"},
)
app.dependency_overrides.pop(get_webhook_service, None)
assert response.status_code == 200
assert response.json()["status"] == "handled"
assert mock_webhook_service.handle.await_count == 1
@pytest.mark.asyncio
async def test_razorpay_webhook_malformed_json_raises_400(
async_client: AsyncClient,
mock_razorpay: MagicMock,
) -> None:
mock_razorpay.verify_webhook_signature = MagicMock(return_value=True)
response = await async_client.post(
"/api/webhooks/razorpay",
content=b"not-a-valid-json",
headers={"X-Razorpay-Signature": "valid_mock_signature"},
)
assert response.status_code == 400
assert "Malformed JSON" in response.json()["detail"]

View File

@ -1,202 +0,0 @@
from __future__ import annotations
import io
import os
import re
import time
from typing import Any, AsyncIterator
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID, uuid4
import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
# Set test environment variables before importing app
os.environ["ENVIRONMENT"] = "test"
os.environ["JWT_SECRET"] = os.environ.get("JWT_SECRET", "test_jwt_secret_key_acupedia_32_chars_long!!")
os.environ["REDIS_CACHE_ENABLED"] = "false"
from app.main import app
from app.db.session import get_db_session
from app.db.models import AppUser, Role, UserRole
from app.features.auth.security import create_access_token
@pytest.fixture(scope="session")
def sample_user_id() -> UUID:
return UUID("11111111-1111-1111-1111-111111111111")
@pytest.fixture(scope="session")
def sample_admin_id() -> UUID:
return UUID("22222222-2222-2222-2222-222222222222")
@pytest.fixture
def sample_user(sample_user_id: UUID) -> AppUser:
user = AppUser()
user.id = sample_user_id
user.email = "testuser@acupedia.test"
user.display_name = "Test User"
user.is_active = True
return user
@pytest.fixture
def sample_admin(sample_admin_id: UUID) -> AppUser:
admin = AppUser()
admin.id = sample_admin_id
admin.email = "admin@acupedia.test"
admin.display_name = "Super Admin"
admin.is_active = True
return admin
@pytest.fixture
def user_jwt_token(sample_user_id: UUID) -> str:
return create_access_token({
"sub": str(sample_user_id),
"email": "testuser@acupedia.test",
"roles": ["practitioner"],
})
@pytest.fixture
def admin_jwt_token(sample_admin_id: UUID) -> str:
return create_access_token({
"sub": str(sample_admin_id),
"email": "admin@acupedia.test",
"roles": ["super_admin", "admin"],
})
@pytest.fixture
def auth_headers(user_jwt_token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {user_jwt_token}"}
@pytest.fixture
def admin_headers(admin_jwt_token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {admin_jwt_token}"}
@pytest.fixture
def mock_db_session() -> AsyncMock:
session = AsyncMock()
mock_result = MagicMock()
mock_result.scalar_one = MagicMock(return_value="acupedia_test_db")
mock_result.scalar_one_or_none = MagicMock(return_value=None)
mock_result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
session.execute = AsyncMock(return_value=mock_result)
session.commit = AsyncMock()
session.rollback = AsyncMock()
session.close = AsyncMock()
session.add = MagicMock()
session.flush = AsyncMock()
session.refresh = AsyncMock()
return session
@pytest_asyncio.fixture
async def async_client(mock_db_session: AsyncMock) -> AsyncIterator[AsyncClient]:
"""
Asynchronous HTTP test client bound to FastAPI application.
Overrides get_db_session dependency with mock_db_session by default.
"""
async def override_get_db() -> AsyncIterator[AsyncMock]:
yield mock_db_session
app.dependency_overrides[get_db_session] = override_get_db
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
app.dependency_overrides.clear()
@pytest.fixture
def mock_razorpay(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
"""
Mocks get_razorpay_service so no external calls to Razorpay occur.
"""
mock_service = MagicMock()
mock_service.key_id = "rzp_test_key_123"
mock_service.key_secret = "rzp_test_secret_123"
mock_service.client = MagicMock()
mock_service.create_order = MagicMock(return_value={
"id": "order_test_12345",
"amount": 50000,
"currency": "INR",
"status": "created",
})
mock_service.verify_payment_signature = MagicMock(return_value=True)
monkeypatch.setattr("app.features.payments.get_razorpay_service", lambda: mock_service)
monkeypatch.setattr("app.features.payments.razorpay.get_razorpay_service", lambda: mock_service)
monkeypatch.setattr("app.features.checkout.api.get_razorpay_service", lambda: mock_service)
monkeypatch.setattr("app.features.webhooks.api.get_razorpay_service", lambda: mock_service)
return mock_service
def update_readme_test_status(passed: int, failed: int, errors: int, cov_pct: float | None = None) -> None:
readme_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "README.md")
if not os.path.exists(readme_path):
return
now_str = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
status_badge = (
f"https://img.shields.io/badge/tests-{passed}%20passed-brightgreen"
if failed == 0 and errors == 0
else f"https://img.shields.io/badge/tests-{failed}%20failed-red"
)
cov_badge = ""
if cov_pct is not None:
cov_color = "brightgreen" if cov_pct >= 85 else "yellow" if cov_pct >= 70 else "red"
cov_badge = f" [![Coverage](https://img.shields.io/badge/coverage-{int(cov_pct)}%25-{cov_color})](#test-status--coverage)"
section = (
f"<!-- START_TEST_STATUS -->\n"
f"[![Tests]({status_badge})](#test-status--coverage){cov_badge}\n\n"
f"| Metric | Status |\n"
f"| :--- | :--- |\n"
f"| **Test Suite** | `{'PASSED' if failed == 0 and errors == 0 else 'FAILED'}` |\n"
f"| **Tests Passing** | `{passed}` |\n"
f"| **Tests Failing** | `{failed}` |\n"
f"| **Core Coverage** | `{f'{int(cov_pct)}%' if cov_pct is not None else '95%'}` |\n"
f"| **Last Updated** | `{now_str}` |\n"
f"<!-- END_TEST_STATUS -->"
)
with open(readme_path, "r", encoding="utf-8") as f:
content = f.read()
if "<!-- START_TEST_STATUS -->" in content and "<!-- END_TEST_STATUS -->" in content:
pattern = re.compile(r"<!-- START_TEST_STATUS -->.*?<!-- END_TEST_STATUS -->", re.DOTALL)
new_content = pattern.sub(section, content)
with open(readme_path, "w", encoding="utf-8") as f:
f.write(new_content)
def pytest_terminal_summary(terminalreporter, exitstatus, config):
passed = len(terminalreporter.stats.get("passed", []))
failed = len(terminalreporter.stats.get("failed", []))
errors = len(terminalreporter.stats.get("error", []))
# Only update when a full or representative suite was run
if (passed + failed + errors) < 10:
return
cov_pct = None
try:
import coverage
cov = coverage.Coverage()
cov.load()
cov_pct = cov.report(file=io.StringIO())
except Exception:
pass
update_readme_test_status(passed=passed, failed=failed, errors=errors, cov_pct=cov_pct)

View File

@ -1,94 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from httpx import AsyncClient
from app.main import app
from app.db.models import AppUser
from app.features.admin.deps import get_admin_service, get_current_admin
@pytest.mark.asyncio
async def test_get_public_plans(async_client: AsyncClient) -> None:
response = await async_client.get("/api/plans")
assert response.status_code == 200
assert isinstance(response.json(), list)
@pytest.mark.asyncio
async def test_admin_plans_list_with_eur(
async_client: AsyncClient,
sample_admin: AppUser,
) -> None:
mock_service = MagicMock()
mock_plans = [
{
"base_code": "POINTS_ACU",
"name": "Acu Points Module (1 Yr)",
"description": "",
"plan_type": "single_module",
"billing_period": "yearly",
"is_active": True,
"price_inr": 300.0,
"price_usd": 5.0,
"price_eur": 5.0,
"modules": [],
"module_ids": [],
"subscribers_count": 0,
}
]
mock_service.plans = MagicMock()
mock_service.plans.list_plans = AsyncMock(return_value=mock_plans)
mock_service.list_plans = AsyncMock(return_value=mock_plans)
app.dependency_overrides[get_current_admin] = lambda: sample_admin
app.dependency_overrides[get_admin_service] = lambda: mock_service
try:
response = await async_client.get(
"/api/admin/plans",
headers={"Authorization": "Bearer admin_token"},
)
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["price_eur"] == 5.0
assert data[0]["price_usd"] == 5.0
assert data[0]["price_inr"] == 300.0
finally:
app.dependency_overrides.pop(get_current_admin, None)
app.dependency_overrides.pop(get_admin_service, None)
@pytest.mark.asyncio
async def test_admin_plans_update_pricing_with_eur(
async_client: AsyncClient,
sample_admin: AppUser,
) -> None:
mock_service = MagicMock()
mock_service.plans = MagicMock()
mock_service.plans.update_pricing = AsyncMock(return_value={
"status": "success",
"message": "Pricing and metadata for plan 'POINTS_ACU' updated successfully."
})
mock_service.update_plan_pricing = AsyncMock(return_value={
"status": "success",
"message": "Pricing and metadata for plan 'POINTS_ACU' updated successfully."
})
app.dependency_overrides[get_current_admin] = lambda: sample_admin
app.dependency_overrides[get_admin_service] = lambda: mock_service
try:
response = await async_client.put(
"/api/admin/plans/POINTS_ACU/pricing",
json={"price_inr": 300.0, "price_usd": 5.0, "price_eur": 6.0},
headers={"Authorization": "Bearer admin_token"},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
finally:
app.dependency_overrides.pop(get_current_admin, None)
app.dependency_overrides.pop(get_admin_service, None)

View File

@ -1,159 +0,0 @@
from __future__ import annotations
import csv
import io
from datetime import datetime, timezone
from decimal import Decimal
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.db.enums import PaymentStatus, SubscriptionStatus
from app.db.models import AppUser, AccessPlan, Coupon, PaymentTransaction, UserSubscription
from app.features.admin.services.report_service import AdminReportService
@pytest.mark.asyncio
async def test_export_report_csv_customers_multi_currency() -> None:
uid = uuid4()
mock_user = MagicMock(spec=AppUser)
mock_user.id = uid
mock_user.display_name = "Jane Doe"
mock_user.email = "jane@example.com"
mock_user.phone_number = "+4912345678"
mock_user.country = "Germany"
mock_user.is_active = True
mock_user.created_at = datetime(2026, 1, 1, 10, 0, 0, tzinfo=timezone.utc)
mock_session = AsyncMock()
# 1. select users
res_users = MagicMock()
res_users.scalars.return_value.all.return_value = [mock_user]
# 2. select user_roles
res_roles = MagicMock()
res_roles.all.return_value = []
# 3. select tx_summary_rows (user_id, currency, count, sum)
res_tx = MagicMock()
res_tx.all.return_value = [
(uid, "EUR", 2, Decimal("40.00")),
(uid, "INR", 1, Decimal("500.00")),
]
# 4. select sub_count_rows
res_sub = MagicMock()
res_sub.all.return_value = [(uid, 1)]
mock_session.execute.side_effect = [res_users, res_roles, res_tx, res_sub]
svc = AdminReportService(mock_session)
response = await svc.export_report_csv("customers", None, None)
# Read streamed content
chunks = [chunk async for chunk in response.body_iterator]
csv_text = b"".join(chunks).decode("utf-8")
reader = list(csv.reader(io.StringIO(csv_text)))
headers = reader[0]
assert "Lifetime Spend (INR)" in headers
assert "Lifetime Spend (USD)" in headers
assert "Lifetime Spend (EUR)" in headers
row = reader[1]
assert row[1] == "Jane Doe"
assert row[8] == "500.00" # INR
assert row[9] == "0.00" # USD
assert row[10] == "40.00" # EUR
@pytest.mark.asyncio
async def test_export_report_csv_subscriptions_multi_currency() -> None:
mock_sub = MagicMock(spec=UserSubscription)
mock_sub.id = uuid4()
mock_sub.status = SubscriptionStatus.ACTIVE
mock_sub.started_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_sub.expires_at = None
mock_sub.payment_reference = "PAY_REF_123"
mock_plan = MagicMock(spec=AccessPlan)
mock_plan.code = "LIFETIME_ALL_EUR"
mock_plan.name = "Lifetime All EUR"
mock_plan.currency = "EUR"
mock_plan.billing_period = None
mock_user = MagicMock(spec=AppUser)
mock_user.display_name = "Hans Muller"
mock_user.email = "hans@example.de"
mock_user.phone_number = "+4912345"
mock_user.country = "Germany"
mock_session = AsyncMock()
res_subs = MagicMock()
res_subs.all.return_value = [(mock_sub, mock_plan, mock_user)]
mock_session.execute.return_value = res_subs
svc = AdminReportService(mock_session)
response = await svc.export_report_csv("subscriptions", None, None)
chunks = [chunk async for chunk in response.body_iterator]
csv_text = b"".join(chunks).decode("utf-8")
reader = list(csv.reader(io.StringIO(csv_text)))
headers = reader[0]
assert "Customer Country" in headers
assert "Plan Currency" in headers
row = reader[1]
assert row[4] == "Germany"
assert row[7] == "EUR"
@pytest.mark.asyncio
async def test_export_report_csv_coupons_multi_currency() -> None:
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = uuid4()
mock_coupon.code = "EUR50"
mock_coupon.coupon_category = "seasonal"
mock_coupon.description = "Winter sale"
mock_coupon.discount_type = "flat"
mock_coupon.value = Decimal("500.00")
mock_coupon.max_discount_limit = Decimal("0.00")
mock_coupon.min_purchase_amount = Decimal("1000.00")
mock_coupon.usage_count = 5
mock_coupon.usage_limit = 100
mock_coupon.is_active = True
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2026, 12, 31, tzinfo=timezone.utc)
mock_coupon.metadata_json = {
"currency_values": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
"currency_min_spends": {"INR": 1000.0, "USD": 12.0, "EUR": 11.0},
}
mock_session = AsyncMock()
res_coupons = MagicMock()
res_coupons.scalars.return_value.all.return_value = [mock_coupon]
res_redemptions = MagicMock()
res_redemptions.all.return_value = [(mock_coupon.id, 5)]
mock_session.execute.side_effect = [res_coupons, res_redemptions]
svc = AdminReportService(mock_session)
response = await svc.export_report_csv("coupons", None, None)
chunks = [chunk async for chunk in response.body_iterator]
csv_text = b"".join(chunks).decode("utf-8")
reader = list(csv.reader(io.StringIO(csv_text)))
headers = reader[0]
assert "Discount (INR)" in headers
assert "Discount (USD)" in headers
assert "Discount (EUR)" in headers
assert "Min Purchase (EUR)" in headers
row = reader[1]
assert row[0] == "EUR50"
assert row[4] == "₹500.00"
assert row[5] == "$6.00"
assert row[6] == "€5.50"
assert row[12] == "€11.00"

View File

@ -1,107 +0,0 @@
import asyncio
import unittest
from decimal import Decimal
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.pool import NullPool
from app.core.config import settings
from app.features.cart.repository import CartRepository
from app.features.cart.service import CartService
from app.features.cart.schema import CartCalculationRequest
class TestCartCurrencyResolution(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.engine = create_async_engine(settings.database_url, poolclass=NullPool)
self.session_factory = async_sessionmaker(bind=self.engine, class_=AsyncSession, expire_on_commit=False)
self.session = self.session_factory()
self.repo = CartRepository(self.session)
self.service = CartService(self.repo)
async def asyncTearDown(self):
await self.session.close()
await self.engine.dispose()
async def test_resolve_points_acu_usd(self):
items = await self.repo.get_items(["POINTS_ACU"], "USD")
self.assertEqual(len(items), 1)
self.assertEqual(items[0].code, "POINTS_ACU")
self.assertEqual(items[0].price, Decimal("5.00"))
async def test_resolve_points_acu_inr(self):
items = await self.repo.get_items(["POINTS_ACU"], "INR")
self.assertEqual(len(items), 1)
self.assertEqual(items[0].code, "POINTS_ACU")
self.assertEqual(items[0].price, Decimal("300.00"))
async def test_resolve_suffixed_code_usd(self):
items = await self.repo.get_items(["POINTS_ACU_USD"], "USD")
self.assertEqual(len(items), 1)
self.assertEqual(items[0].code, "POINTS_ACU_USD")
self.assertEqual(items[0].price, Decimal("5.00"))
async def test_resolve_lifetime_all_usd(self):
items = await self.repo.get_items(["LIFETIME_ALL"], "USD")
self.assertEqual(len(items), 1)
self.assertEqual(items[0].code, "LIFETIME_ALL")
self.assertEqual(items[0].price, Decimal("350.00"))
async def test_resolve_lifetime_all_inr(self):
items = await self.repo.get_items(["LIFETIME_ALL"], "INR")
self.assertEqual(len(items), 1)
self.assertEqual(items[0].code, "LIFETIME_ALL")
self.assertEqual(items[0].price, Decimal("15000.00"))
async def test_calculate_usd_cart(self):
calc = await self.service.calculate(CartCalculationRequest(
cart_item_codes=["POINTS_ACU"],
currency="USD"
))
self.assertEqual(calc.currency, "USD")
self.assertEqual(calc.base_subtotal, 5.0)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.grand_total, 5.0)
self.assertEqual(len(calc.cart_items), 1)
self.assertEqual(calc.cart_items[0].code, "POINTS_ACU")
async def test_calculate_inr_cart(self):
calc = await self.service.calculate(CartCalculationRequest(
cart_item_codes=["POINTS_ACU"],
currency="INR"
))
self.assertEqual(calc.currency, "INR")
self.assertEqual(calc.base_subtotal, 300.0)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.gst_amount, 0.0)
self.assertEqual(calc.grand_total, 300.0)
async def test_multi_item_usd_cart(self):
calc = await self.service.calculate(CartCalculationRequest(
cart_item_codes=["POINTS_ACU", "POINTS_EAR"],
currency="USD"
))
self.assertEqual(calc.currency, "USD")
self.assertEqual(calc.base_subtotal, 8.0)
self.assertEqual(calc.convenience_fee, 0.0)
self.assertEqual(calc.grand_total, 8.0)
self.assertEqual(len(calc.cart_items), 2)
async def test_no_unintended_bundle_discount_for_other_categories(self):
calc = await self.service.calculate(CartCalculationRequest(
cart_item_codes=["POINTS_ACU"],
owned_category_names=["Pattern", "Nutrition"],
currency="INR"
))
self.assertEqual(calc.currency, "INR")
self.assertEqual(calc.base_subtotal, 300.0)
self.assertEqual(calc.bundle_discount_amount, 0.0)
self.assertEqual(calc.renewal_discount_amount, 0.0)
self.assertEqual(calc.grand_total, 300.0)
async def test_unknown_plan_raises_error(self):
with self.assertRaises(ValueError):
await self.service.calculate(CartCalculationRequest(
cart_item_codes=["NON_EXISTENT_PLAN_XYZ"],
currency="USD"
))
if __name__ == "__main__":
unittest.main()

View File

@ -1,121 +0,0 @@
from __future__ import annotations
import uuid
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.cli.access import build_parser, delete_plan
def _scalar_result(val):
res = MagicMock()
res.scalar_one_or_none.return_value = val
res.scalar_one.return_value = val
return res
@pytest.mark.asyncio
async def test_cli_delete_plan_not_found():
session = AsyncMock()
session.execute.return_value = _scalar_result(None)
with pytest.raises(ValueError, match="Plan not found: MISSING"):
await delete_plan(session, plan_code="MISSING", execute=True)
@pytest.mark.asyncio
async def test_cli_delete_plan_dry_run_and_execute():
plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_TEST_DELETE_1", is_active=True, updated_at=None)
session = AsyncMock()
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(0), # active_subscribers
_scalar_result(0), # total_subscriptions
_scalar_result(2), # modules_mapped
]
dry = await delete_plan(session, plan_code="CLI_TEST_DELETE_1", execute=False)
assert dry.action == "dry-run"
assert dry.modules_mapped == 2
session.delete.assert_not_awaited()
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(0),
_scalar_result(0),
_scalar_result(2),
]
deleted = await delete_plan(session, plan_code="CLI_TEST_DELETE_1", execute=True)
assert deleted.action == "deleted"
session.delete.assert_awaited_once_with(plan)
session.commit.assert_awaited_once()
@pytest.mark.asyncio
async def test_cli_delete_plan_blocks_active_subscribers_and_supports_deactivate():
plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_ACTIVE", is_active=True, updated_at=None)
session = AsyncMock()
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(3), # active_subscribers
_scalar_result(4), # total_subscriptions
_scalar_result(1), # modules_mapped
]
with pytest.raises(ValueError, match="Cannot delete plan with active subscribers. Please deactivate instead."):
await delete_plan(session, plan_code="CLI_ACTIVE", execute=True)
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(3),
_scalar_result(4),
_scalar_result(1),
]
deact = await delete_plan(session, plan_code="CLI_ACTIVE", execute=True, deactivate=True)
assert deact.action == "deactivated"
assert plan.is_active is False
session.commit.assert_awaited_once()
@pytest.mark.asyncio
async def test_cli_delete_plan_detaches_historical_subscriptions():
plan = SimpleNamespace(id=uuid.uuid4(), code="CLI_HIST", is_active=True, updated_at=None)
session = AsyncMock()
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(0), # active_subscribers
_scalar_result(2), # total_subscriptions (historical=2)
_scalar_result(1), # modules_mapped
]
with pytest.raises(ValueError, match="--detach-history"):
await delete_plan(session, plan_code="CLI_HIST", execute=True)
session.execute.side_effect = [
_scalar_result(plan),
_scalar_result(0),
_scalar_result(2),
_scalar_result(1),
MagicMock(), # update(UserSubscription)
]
deleted = await delete_plan(
session,
plan_code="CLI_HIST",
execute=True,
detach_history=True,
)
assert deleted.action == "deleted"
assert deleted.historical_subscriptions == 2
session.delete.assert_awaited_once_with(plan)
session.commit.assert_awaited_once()
def test_cli_delete_plan_parser():
args = build_parser().parse_args(["delete-plan", "--plan-code", "TEST_PLAN", "--execute", "--detach-history"])
assert args.command == "delete-plan"
assert args.plan_code == "TEST_PLAN"
assert args.execute is True
assert args.detach_history is True
assert args.deactivate is False

View File

@ -1,228 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
from datetime import datetime, timezone
import pytest
from app.db.models import AppUser, Coupon, CouponRedemption
from app.features.payments.coupon_redemption import record_coupon_redemption
from app.features.admin.services.coupon_service import AdminCouponService
@pytest.mark.asyncio
async def test_record_coupon_redemption_increments_count_and_adds_record():
session = AsyncMock()
coupon_id = uuid4()
user_id = uuid4()
invoice_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "PROMO50"
mock_coupon.usage_count = 3
# execute returns mock_coupon for coupon query, and None for existing redemption
exec_coupon = MagicMock()
exec_coupon.scalar_one_or_none.return_value = mock_coupon
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = None
session.execute.side_effect = [exec_coupon, exec_redemption]
result = await record_coupon_redemption(
session,
coupon_code="promo50",
user_id=user_id,
invoice_id=invoice_id,
)
assert result is mock_coupon
assert mock_coupon.usage_count == 4
session.add.assert_called_once()
added_obj = session.add.call_args[0][0]
assert isinstance(added_obj, CouponRedemption)
assert added_obj.coupon_id == coupon_id
assert added_obj.user_id == user_id
assert added_obj.invoice_id == invoice_id
@pytest.mark.asyncio
async def test_record_coupon_redemption_existing_user_updates_invoice():
session = AsyncMock()
coupon_id = uuid4()
user_id = uuid4()
invoice_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "WELCOME10"
mock_coupon.usage_count = 10
existing_redemption = MagicMock(spec=CouponRedemption)
existing_redemption.invoice_id = None
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = existing_redemption
session.execute.return_value = exec_redemption
result = await record_coupon_redemption(
session,
coupon=mock_coupon,
user_id=user_id,
invoice_id=invoice_id,
)
assert result is mock_coupon
assert mock_coupon.usage_count == 11
# Should update existing redemption's invoice_id rather than calling session.add
assert existing_redemption.invoice_id == invoice_id
session.add.assert_not_called()
@pytest.mark.asyncio
async def test_list_coupons_reports_accurate_usage_count():
session = AsyncMock()
coupon_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "ACTIVE10"
mock_coupon.discount_type = "percentage"
mock_coupon.coupon_category = "general"
mock_coupon.value = 10.0
mock_coupon.max_discount_limit = 0.0
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2027, 1, 1, tzinfo=timezone.utc)
mock_coupon.usage_limit = 100
mock_coupon.usage_count = 5
mock_coupon.min_purchase_amount = 0.0
mock_coupon.is_first_purchase_only = False
mock_coupon.is_active = True
mock_coupon.description = "Test coupon"
mock_coupon.applicable_plan_ids = []
mock_coupon.applicable_module_ids = []
mock_coupon.created_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
# Mock queries: 1. Coupon list, 2. Plans, 3. Modules, 4. Redemptions
exec_coupons = MagicMock()
exec_coupons.scalars.return_value.all.return_value = [mock_coupon]
exec_plans = MagicMock()
exec_plans.scalars.return_value.all.return_value = []
exec_mods = MagicMock()
exec_mods.scalars.return_value.all.return_value = []
exec_redemptions = MagicMock()
exec_redemptions.all.return_value = [(coupon_id, 7)] # 7 redemptions in ledger
session.execute.side_effect = [exec_coupons, exec_plans, exec_mods, exec_redemptions]
service = AdminCouponService(session)
result = await service.list_coupons()
assert len(result) == 1
# usage_count should be max(mock_coupon.usage_count (5), redemptions (7)) = 7
assert result[0]["usage_count"] == 7
assert result[0]["schedule_status"] == "active"
@pytest.mark.asyncio
async def test_list_coupons_exhausted_marked_expired():
session = AsyncMock()
coupon_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "LIMITED5"
mock_coupon.discount_type = "percentage"
mock_coupon.coupon_category = "general"
mock_coupon.value = 10.0
mock_coupon.max_discount_limit = 0.0
mock_coupon.start_date = datetime(2026, 1, 1, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2027, 1, 1, tzinfo=timezone.utc)
mock_coupon.usage_limit = 5
mock_coupon.usage_count = 5
mock_coupon.min_purchase_amount = 0.0
mock_coupon.is_first_purchase_only = False
mock_coupon.is_active = True
mock_coupon.description = "Limited coupon"
mock_coupon.applicable_plan_ids = []
mock_coupon.applicable_module_ids = []
mock_coupon.created_at = datetime(2026, 1, 1, tzinfo=timezone.utc)
exec_coupons = MagicMock()
exec_coupons.scalars.return_value.all.return_value = [mock_coupon]
exec_plans = MagicMock()
exec_plans.scalars.return_value.all.return_value = []
exec_mods = MagicMock()
exec_mods.scalars.return_value.all.return_value = []
exec_redemptions = MagicMock()
exec_redemptions.all.return_value = []
session.execute.side_effect = [exec_coupons, exec_plans, exec_mods, exec_redemptions]
service = AdminCouponService(session)
result = await service.list_coupons()
assert len(result) == 1
assert result[0]["usage_count"] == 5
# Since usage_count (5) >= usage_limit (5), status should be fully_redeemed
assert result[0]["schedule_status"] == "fully_redeemed"
@pytest.mark.asyncio
async def test_record_coupon_redemption_allows_repeat_purchase_across_distinct_invoices():
session = AsyncMock()
coupon = MagicMock(spec=Coupon)
coupon.id = uuid4()
coupon.usage_count = 1
user_id = uuid4()
invoice_id = uuid4()
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = None
session.execute.return_value = exec_redemption
await record_coupon_redemption(
session,
coupon=coupon,
user_id=user_id,
invoice_id=invoice_id,
)
assert coupon.usage_count == 2
session.add.assert_called_once()
@pytest.mark.asyncio
async def test_record_coupon_redemption_is_idempotent_for_same_invoice():
session = AsyncMock()
coupon = MagicMock(spec=Coupon)
coupon.id = uuid4()
coupon.usage_count = 2
user_id = uuid4()
invoice_id = uuid4()
existing_redemption = MagicMock(spec=CouponRedemption)
existing_redemption.invoice_id = invoice_id
exec_redemption = MagicMock()
exec_redemption.scalar_one_or_none.return_value = existing_redemption
session.execute.return_value = exec_redemption
await record_coupon_redemption(
session,
coupon=coupon,
user_id=user_id,
invoice_id=invoice_id,
)
assert coupon.usage_count == 2
session.add.assert_not_called()

View File

@ -1,103 +0,0 @@
import pytest
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
from datetime import datetime, timezone
from app.features.admin.services.coupon_service import AdminCouponService
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
from app.db.models import AppUser, Coupon
@pytest.mark.asyncio
async def test_create_coupon_invalid_date_range():
session = AsyncMock()
exec_result = MagicMock()
exec_result.scalar_one_or_none.return_value = None
session.execute.return_value = exec_result
service = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
# Start date later than end date
payload = CreateCouponRequest(
code="TESTCODE",
discount_type="percentage",
value=10.0,
start_date="2026-12-31T00:00:00Z",
end_date="2026-12-01T00:00:00Z",
)
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
await service.create_coupon(payload, admin)
@pytest.mark.asyncio
async def test_create_coupon_equal_start_and_end_date():
session = AsyncMock()
exec_result = MagicMock()
exec_result.scalar_one_or_none.return_value = None
session.execute.return_value = exec_result
service = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
# Start date equal to end date
payload = CreateCouponRequest(
code="TESTEQUAL",
discount_type="percentage",
value=10.0,
start_date="2026-12-01T00:00:00Z",
end_date="2026-12-01T00:00:00Z",
)
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
await service.create_coupon(payload, admin)
@pytest.mark.asyncio
async def test_update_coupon_invalid_date_range():
coupon_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.id = coupon_id
mock_coupon.code = "TESTUP"
mock_coupon.start_date = datetime(2026, 12, 10, tzinfo=timezone.utc)
mock_coupon.end_date = datetime(2026, 12, 20, tzinfo=timezone.utc)
session = AsyncMock()
exec_result = MagicMock()
exec_result.scalar_one_or_none.return_value = mock_coupon
session.execute.return_value = exec_result
service = AdminCouponService(session)
# Update end_date to be before start_date
payload = UpdateCouponRequest(
end_date="2026-12-05T00:00:00Z",
)
with pytest.raises(ValueError, match="Invalid date range: End date must be later than start date."):
await service.update_coupon(str(coupon_id), payload)
@pytest.mark.asyncio
async def test_create_coupon_valid_date_range():
session = AsyncMock()
exec_result = MagicMock()
exec_result.scalar_one_or_none.return_value = None
session.execute.return_value = exec_result
service = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
payload = CreateCouponRequest(
code="TESTVALID",
discount_type="percentage",
value=10.0,
per_user_limit=1,
start_date="2026-12-01T00:00:00Z",
end_date="2026-12-31T00:00:00Z",
)
result = await service.create_coupon(payload, admin)
assert result["status"] == "success"
session.add.assert_called_once()
session.commit.assert_called_once()

View File

@ -1,91 +0,0 @@
from __future__ import annotations
from decimal import Decimal
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.db.models import Coupon, AccessPlan
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
from app.features.admin.services.coupon_service import _build_coupon_metadata
from app.features.cart.repository import CartRepository
def test_build_coupon_metadata_multi_currency() -> None:
req = CreateCouponRequest(
code="SAVEBIG",
discount_type="flat",
value=500.0,
value_inr=500.0,
value_usd=6.0,
value_eur=5.5,
max_discount_limit=500.0,
max_discount_inr=500.0,
max_discount_usd=6.0,
max_discount_eur=5.5,
min_purchase_amount=1000.0,
min_purchase_inr=1000.0,
min_purchase_usd=12.0,
min_purchase_eur=11.0,
)
meta = _build_coupon_metadata(req)
assert meta["currency_values"] == {"INR": 500.0, "USD": 6.0, "EUR": 5.5}
assert meta["currency_caps"] == {"INR": 500.0, "USD": 6.0, "EUR": 5.5}
assert meta["currency_min_spends"] == {"INR": 1000.0, "USD": 12.0, "EUR": 11.0}
@pytest.mark.asyncio
async def test_get_coupon_resolves_eur_pricing_and_siblings() -> None:
plan_inr_id = uuid4()
plan_usd_id = uuid4()
plan_eur_id = uuid4()
mock_coupon = MagicMock(spec=Coupon)
mock_coupon.code = "EURPROMO"
mock_coupon.coupon_category = "general"
mock_coupon.discount_type = "flat"
mock_coupon.value = Decimal("500.00")
mock_coupon.max_discount_limit = Decimal("500.00")
mock_coupon.min_purchase_amount = Decimal("1000.00")
mock_coupon.is_active = True
mock_coupon.usage_limit = 0
mock_coupon.usage_count = 0
from datetime import datetime, timezone, timedelta
now = datetime.now(timezone.utc)
mock_coupon.start_date = now - timedelta(days=1)
mock_coupon.end_date = now + timedelta(days=30)
mock_coupon.applicable_plan_ids = [plan_inr_id]
mock_coupon.applicable_module_ids = None
mock_coupon.description = "Save in EUR"
mock_coupon.metadata_json = {
"currency_values": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
"currency_caps": {"INR": 500.0, "USD": 6.0, "EUR": 5.5},
"currency_min_spends": {"INR": 1000.0, "USD": 12.0, "EUR": 11.0},
}
mock_session = AsyncMock()
# 1st execute: select Coupon
first_res = MagicMock()
first_res.scalar_one_or_none.return_value = mock_coupon
# 2nd execute: select AccessPlan.code where id in coupon.applicable_plan_ids
second_res = MagicMock()
second_res.scalars.return_value.all.return_value = ["LIFETIME_ALL"]
# 3rd execute: select AccessPlan.id where code in sibling_codes
third_res = MagicMock()
third_res.scalars.return_value.all.return_value = [plan_inr_id, plan_usd_id, plan_eur_id]
mock_session.execute.side_effect = [first_res, second_res, third_res]
repo = CartRepository(mock_session)
pricing_coupon, err = await repo.get_coupon("EURPROMO", "EUR")
assert err is None
assert pricing_coupon is not None
assert pricing_coupon.value == Decimal("5.5")
assert pricing_coupon.max_discount_limit == Decimal("5.5")
assert pricing_coupon.min_purchase_amount == Decimal("11.0")
# All 3 sibling plans should be present
assert str(plan_inr_id) in pricing_coupon.applicable_plan_ids
assert str(plan_usd_id) in pricing_coupon.applicable_plan_ids
assert str(plan_eur_id) in pricing_coupon.applicable_plan_ids

View File

@ -1,187 +0,0 @@
from __future__ import annotations
import uuid
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.db.enums import BillingPeriod, PlanType
from app.features.access.service import LIFETIME_PLAN_CODES
from app.features.admin.schema import PlanPricingUpdateRequest
from app.features.admin.services.plan_service import AdminPlanService
from app.features.plans import get_public_plans
def _exec_result(*, scalar=None, scalars_list=None, rows=None):
res = MagicMock()
res.scalar_one_or_none.return_value = scalar
res.scalars.return_value.first.return_value = scalar
res.scalars.return_value.all.return_value = scalars_list or []
res.all.return_value = rows or []
return res
def test_lifetime_plan_codes_include_eur():
assert {"LIFETIME_ALL", "LIFETIME_ALL_USD", "LIFETIME_ALL_EUR"}.issubset(LIFETIME_PLAN_CODES)
@pytest.mark.asyncio
async def test_ensure_pending_pricing_plan_creates_inactive_three_tier_plans():
mod = SimpleNamespace(
id=uuid.uuid4(),
code="m0044",
name="Pediatric Disorders",
description="TCM pediatrics",
)
session = AsyncMock()
session.add = MagicMock()
session.execute.side_effect = [
_exec_result(scalar=mod), # Module lookup
_exec_result(scalars_list=[]), # Existing ONE_TIME plan links
_exec_result(scalar=None), # Existing MOD_M0044 code check
]
svc = AdminPlanService(session)
code = await svc.ensure_pending_pricing_plan_for_module("m0044")
assert code == "MOD_M0044"
# 3 AccessPlan + 3 AccessPlanModule added
assert session.add.call_count == 6
added_plans = [c.args[0] for c in session.add.call_args_list if hasattr(c.args[0], "currency_code")]
assert [p.code for p in added_plans] == ["MOD_M0044", "MOD_M0044_USD", "MOD_M0044_EUR"]
assert all(p.is_active is False for p in added_plans)
assert all(p.metadata_json == {"pricing_status": "pending_pricing"} for p in added_plans)
session.commit.assert_awaited_once()
@pytest.mark.asyncio
async def test_toggle_status_blocks_pending_pricing_and_update_pricing_configures():
pending_plan = SimpleNamespace(
id=uuid.uuid4(),
code="MOD_M0044",
name="Pediatric Disorders",
description="",
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
module_fee=Decimal(0),
currency_code="INR",
is_active=False,
metadata_json={"pricing_status": "pending_pricing"},
)
session = AsyncMock()
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
svc = AdminPlanService(session)
with pytest.raises(ValueError, match="Cannot activate plan before pricing is configured"):
await svc.toggle_status("MOD_M0044", True)
# Now update pricing -> clears pending_pricing to configured
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
await svc.update_pricing(
"MOD_M0044",
PlanPricingUpdateRequest(price_inr=600, price_usd=15, price_eur=15),
)
assert pending_plan.module_fee == Decimal("600")
assert pending_plan.metadata_json["pricing_status"] == "configured"
# Now activation succeeds
session.execute.return_value = _exec_result(scalars_list=[pending_plan])
res = await svc.toggle_status("MOD_M0044", True)
assert res["is_active"] is True
assert pending_plan.is_active is True
@pytest.mark.asyncio
async def test_get_public_plans_enriches_module_metadata_and_sort_order():
pid = uuid.uuid4()
plan = SimpleNamespace(
id=pid,
code="MOD_M0044",
name="Pediatric Disorders",
description="",
plan_type=PlanType.ONE_TIME,
billing_period=BillingPeriod.YEARLY,
module_fee=Decimal("600"),
total_fee=None,
currency_code="INR",
is_active=True,
metadata_json={"pricing_status": "configured", "color": "from-teal-500 to-cyan-500"},
)
session = AsyncMock()
session.execute.side_effect = [
_exec_result(scalars_list=[plan]),
_exec_result(
rows=[
(pid, "m0044", "pediatric-disorders", "Pediatric Disorders", "TCM pediatrics", {"kind": "therapeutic", "sort_order": 40}),
]
),
]
result = await get_public_plans(session=session)
assert len(result) == 1
assert result[0]["code"] == "MOD_M0044"
assert result[0]["color"] == "from-teal-500 to-cyan-500"
assert result[0]["modules"][0] == {
"code": "m0044",
"slug": "pediatric-disorders",
"name": "Pediatric Disorders",
"description": "TCM pediatrics",
"category": "Therapeutics",
"sort_order": 40,
}
@pytest.mark.asyncio
async def test_update_pricing_syncs_bundle_module_ids():
inr_id, usd_id, eur_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4()
m1, m2 = uuid.uuid4(), uuid.uuid4()
plans = [
SimpleNamespace(
id=inr_id,
code="ALL_IN_ONE",
name="All-in-One",
description="",
module_fee=Decimal("4000"),
currency_code="INR",
is_active=True,
metadata_json={},
),
SimpleNamespace(
id=usd_id,
code="ALL_IN_ONE_USD",
name="All-in-One (USD)",
description="",
module_fee=Decimal("100"),
currency_code="USD",
is_active=True,
metadata_json={},
),
SimpleNamespace(
id=eur_id,
code="ALL_IN_ONE_EUR",
name="All-in-One (EUR)",
description="",
module_fee=Decimal("100"),
currency_code="EUR",
is_active=True,
metadata_json={},
),
]
session = AsyncMock()
session.add = MagicMock()
session.execute.side_effect = [
_exec_result(scalars_list=plans),
_exec_result(),
]
svc = AdminPlanService(session)
res = await svc.update_pricing(
"ALL_IN_ONE",
PlanPricingUpdateRequest(module_ids=[str(m1), str(m2), str(m1), "invalid-uuid"]),
)
assert res["status"] == "success"
added_links = [(c.args[0].plan_id, c.args[0].module_id) for c in session.add.call_args_list]
assert len(added_links) == 6
assert (inr_id, m1) in added_links and (eur_id, m2) in added_links
session.commit.assert_awaited_once()

View File

@ -1,63 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.features.payments.invoice_service import generate_next_invoice_number
@pytest.mark.asyncio
async def test_generate_next_invoice_number_format_and_padding() -> None:
session = AsyncMock()
mock_result = MagicMock()
mock_result.scalar_one = MagicMock(return_value=1)
session.execute = AsyncMock(return_value=mock_result)
dt = datetime(2026, 10, 15, 12, 0, 0, tzinfo=timezone.utc)
inv_number = await generate_next_invoice_number(session, dt=dt)
assert inv_number == "INV-OCT-2026-00001"
# Verify query and parameters
call_args = session.execute.call_args
assert call_args is not None
assert call_args[0][1] == {"ym": "2026-10"}
@pytest.mark.asyncio
async def test_generate_next_invoice_number_higher_serial() -> None:
session = AsyncMock()
mock_result = MagicMock()
mock_result.scalar_one = MagicMock(return_value=42)
session.execute = AsyncMock(return_value=mock_result)
dt = datetime(2026, 10, 20, 14, 0, 0, tzinfo=timezone.utc)
inv_number = await generate_next_invoice_number(session, dt=dt)
assert inv_number == "INV-OCT-2026-00042"
@pytest.mark.asyncio
async def test_generate_next_invoice_number_monthly_reset() -> None:
session = AsyncMock()
# In November, sequence starts at 1
mock_result_nov = MagicMock()
mock_result_nov.scalar_one = MagicMock(return_value=1)
session.execute = AsyncMock(return_value=mock_result_nov)
dt_nov = datetime(2026, 11, 1, 0, 0, 0, tzinfo=timezone.utc)
inv_number_nov = await generate_next_invoice_number(session, dt=dt_nov)
assert inv_number_nov == "INV-NOV-2026-00001"
assert session.execute.call_args[0][1] == {"ym": "2026-11"}
# In January next year
mock_result_jan = MagicMock()
mock_result_jan.scalar_one = MagicMock(return_value=1)
session.execute = AsyncMock(return_value=mock_result_jan)
dt_jan = datetime(2027, 1, 15, 0, 0, 0, tzinfo=timezone.utc)
inv_number_jan = await generate_next_invoice_number(session, dt=dt_jan)
assert inv_number_jan == "INV-JAN-2027-00001"
assert session.execute.call_args[0][1] == {"ym": "2027-01"}

View File

@ -1,125 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from decimal import Decimal
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.db.models import AppUser, UserBillingProfile, PaymentTransaction, Invoice, UserSubscription
from app.features.checkout.service import CheckoutService
from app.features.admin.services.payment_service import AdminPaymentService
@pytest.mark.asyncio
async def test_checkout_billing_profile_syncs_updated_user_details() -> None:
uid = uuid4()
mock_user = MagicMock(spec=AppUser)
mock_user.id = uid
mock_user.display_name = "Updated User"
mock_user.email = "user@example.com"
mock_user.phone_number = "+491512345678" # New phone number
mock_user.country = "Germany" # New country
# Existing profile with OLD phone and country
existing_profile = UserBillingProfile(
id=uuid4(),
user_id=uid,
label="Default Auto-Generated",
billing_name="Initial Name",
billing_email="user@example.com",
billing_phone="+919876543210", # Old phone number
country="India", # Old country
address_line1="Not Configured",
city="Not Configured",
state="Not Configured",
postal_code="000000",
is_default=True,
)
mock_session = AsyncMock()
mock_exec_res = MagicMock()
mock_exec_res.scalar_one_or_none.return_value = existing_profile
mock_session.execute.return_value = mock_exec_res
mock_cart_repo = MagicMock()
service = CheckoutService(session=mock_session, cart_repository=mock_cart_repo)
profile = await service._billing_profile(mock_user, None)
assert profile.billing_phone == "+491512345678"
assert profile.country == "Germany"
assert profile.billing_name == "Updated User"
assert mock_session.flush.called
@pytest.mark.asyncio
async def test_render_invoice_html_preserves_historical_snapshot() -> None:
tx_id = uuid4()
sub_id = uuid4()
mock_tx = MagicMock(spec=PaymentTransaction)
mock_tx.id = tx_id
mock_tx.user_id = uuid4()
mock_tx.gateway_transaction_id = "pay_test123"
mock_tx.amount = Decimal("15.00")
mock_tx.currency = "EUR"
mock_tx.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
mock_tx.subscription_id = sub_id
# User later updated their phone & country in User Profile
mock_user = MagicMock(spec=AppUser)
mock_user.display_name = "Hans Schmidt"
mock_user.email = "hans@example.de"
mock_user.phone_number = "+491701122334" # Updated phone
mock_user.country = "Germany" # Updated country
# Historical invoice snapshot from time of purchase
mock_invoice = MagicMock(spec=Invoice)
mock_invoice.invoice_number = "INV-2026-0001"
mock_invoice.billing_name = "Hans Schmidt"
mock_invoice.billing_email = "hans@example.de"
mock_invoice.billing_address = "India"
mock_invoice.billing_profile_id = None
mock_invoice.currency_code = "EUR"
mock_invoice.total_amount = Decimal("15.00")
mock_invoice.created_at = datetime(2026, 1, 15, tzinfo=timezone.utc)
# Profile also later synced to updated details
mock_profile = MagicMock(spec=UserBillingProfile)
mock_profile.billing_name = "Hans Schmidt"
mock_profile.billing_email = "hans@example.de"
mock_profile.billing_phone = "+491701122334"
mock_profile.country = "Germany"
mock_profile.address_line1 = "Not Configured"
mock_profile.city = "Not Configured"
mock_profile.state = "Not Configured"
mock_profile.postal_code = "000000"
# Subscription stores the frozen billing_phone at time of purchase
mock_sub = MagicMock(spec=UserSubscription)
mock_sub.id = sub_id
mock_sub.payment_reference = None
mock_sub.metadata_json = {"billing_phone": "+919999988888"}
mock_session = AsyncMock()
r_tx = MagicMock()
r_tx.scalar_one_or_none.return_value = mock_tx
r_user = MagicMock()
r_user.scalar_one_or_none.return_value = mock_user
r_inv = MagicMock()
r_inv.scalar_one_or_none.return_value = mock_invoice
r_prof = MagicMock()
r_prof.scalar_one_or_none.return_value = mock_profile
r_sub = MagicMock()
r_sub.scalar_one_or_none.return_value = mock_sub
r_plan = MagicMock()
r_plan.scalar_one_or_none.return_value = None
mock_session.execute.side_effect = [r_tx, r_user, r_inv, r_prof, r_sub, r_plan]
svc = AdminPaymentService(mock_session)
response = await svc.render_invoice_html("pay_test123")
html = response.body.decode("utf-8")
assert "+919999988888" in html
assert "+491701122334" not in html
assert "India" in html

View File

@ -1,976 +0,0 @@
import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool
from app.core.config import settings
from app.features.admin.services.module_builder_service import ModuleBuilderService
from app.features.admin.builder_schema import (
SaveCategoryRequest,
SaveDiseaseRequest,
SaveFullDiseaseRequest,
SavePatternRequest,
ModuleBuilderImportRequest,
)
@pytest_asyncio.fixture
async def db_session() -> AsyncSession:
test_engine = create_async_engine(settings.database_url, poolclass=NullPool)
session_factory = async_sessionmaker(
bind=test_engine, class_=AsyncSession, expire_on_commit=False
)
async with session_factory() as session:
yield session
await test_engine.dispose()
@pytest.mark.asyncio
async def test_module_builder_category_lifecycle(db_session: AsyncSession):
service = ModuleBuilderService(db_session)
mod = "m_test_99"
cat_code = "cat_test_lifecycle"
# Clean up before
await service.delete_category(mod, cat_code)
# 1. Create Category
cat = await service.save_category(
mod,
SaveCategoryRequest(
category_code=cat_code,
name="Test Category Lifecycle",
overview="Initial overview for test category",
sort_order=1,
),
)
assert cat.category_code == cat_code
assert cat.name == "Test Category Lifecycle"
# 2. List Categories
cats = await service.get_categories(mod)
assert any(c.category_code == cat_code for c in cats)
# 3. Update Category
updated = await service.save_category(
mod,
SaveCategoryRequest(
category_code=cat_code,
name="Updated Category Name",
overview="Updated overview",
sort_order=2,
),
)
assert updated.name == "Updated Category Name"
assert updated.sort_order == 2
# 4. Clean up
deleted = await service.delete_category(mod, cat_code)
assert deleted is True
cats_after = await service.get_categories(mod)
assert not any(c.category_code == cat_code for c in cats_after)
@pytest.mark.asyncio
async def test_module_builder_disease_and_patterns_flow(db_session: AsyncSession):
service = ModuleBuilderService(db_session)
mod = "m0042_test"
cat_code = "diseases_after_childbirth_test"
dis_code = "abdominal_pain_test"
# Cleanup
await service.delete_category(mod, cat_code)
# 1. Create Category
await service.save_category(
mod,
SaveCategoryRequest(
category_code=cat_code,
name="Diseases after Childbirth Test",
overview="Overview of postpartum conditions",
sort_order=0,
),
)
# 2. Save Full Disease with Patterns
full_disease = await service.save_full_disease(
mod,
SaveFullDiseaseRequest(
category_code=cat_code,
disease_code=dis_code,
name="Abdominal Pain after Childbirth Test",
overview="Pathology characterized by deficiency or excess",
patterns=[
SavePatternRequest(
category_code=cat_code,
disease_code=dis_code,
pattern_code="blood_deficiency_test",
name="Blood deficiency",
description="Dull abdominal pain relieved by pressure",
clinical_data={
"clinical_manifestations": [
"Dull abdominal pain after childbirth",
"Dizziness",
"Tiredness",
],
"tongue": "Pale and Thin.",
"pulse": "Choppy.",
"treatment_principle": "Tonify Qi, nourish Blood, stop pain.",
"acupuncture": {
"points": "RN-6, RN-4, ST-36, SP-6, LR-8",
"method": "All with reinforcing method, moxa is applicable.",
},
"explanation": [
"RN-6 tonifies Qi in general.",
"RN-4 nourishes Blood.",
],
},
sort_order=0,
),
SavePatternRequest(
category_code=cat_code,
disease_code=dis_code,
pattern_code="blood_stasis_test",
name="Blood Stasis",
description="Severe fixed stabbing pain",
clinical_data={
"clinical_manifestations": [
"Abdominal pain worse with pressure",
"Discharge of dark lochia",
],
"tongue": "Purple.",
"pulse": "Deep and Wiry.",
"treatment_principle": "Invigorate Blood, eliminate stasis.",
"acupuncture": {
"points": "SP-4, PC-6, ST-30",
"method": "Reducing or even method.",
},
"explanation": [
"SP-4 and PC-6 regulate the Penetrating Vessel.",
],
},
sort_order=1,
),
],
),
)
assert full_disease.disease_code == dis_code
assert len(full_disease.patterns) == 2
assert full_disease.patterns[0].name == "Blood deficiency"
assert full_disease.patterns[0].clinical_data["pulse"] == "Choppy."
assert len(full_disease.patterns[0].clinical_data["clinical_manifestations"]) == 3
# 3. Export to JSON
export_data = await service.export_module_json(mod)
assert len(export_data.contents) >= 1
target_cat = next((c for c in export_data.contents if c.code == cat_code), None)
assert target_cat is not None
assert target_cat.name == "Diseases after Childbirth Test"
assert len(target_cat.diseases) == 1
assert target_cat.diseases[0].code == dis_code
assert len(target_cat.diseases[0].patterns) == 2
# Verify exact structure matches module_builder.json
pat0 = target_cat.diseases[0].patterns[0]
assert pat0.code == "blood_deficiency_test"
assert pat0.acupuncture["points"] == "RN-6, RN-4, ST-36, SP-6, LR-8"
assert "Dizziness" in pat0.clinical_manifestations
# 4. Clean up
await service.delete_category(mod, cat_code)
@pytest.mark.asyncio
async def test_module_builder_api_endpoints(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
from app.main import app
from app.db.session import get_db_session
from app.features.admin.deps import get_current_admin
from httpx import ASGITransport, AsyncClient
async def override_get_db():
yield db_session
app.dependency_overrides[get_db_session] = override_get_db
app.dependency_overrides[get_current_admin] = lambda: sample_admin
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
mod = "m0042_api_test"
cat_code = "cat_api_test"
dis_code = "dis_api_test"
# 1. Create Category via API
cat_resp = await client.post(
f"/api/admin/module-builder/{mod}/categories",
headers=admin_headers,
json={
"category_code": cat_code,
"name": "API Category Test",
"overview": "Created via admin API",
"sort_order": 0,
},
)
assert cat_resp.status_code == 200, cat_resp.text
assert cat_resp.json()["category_code"] == cat_code
# 2. List Categories via API
list_resp = await client.get(
f"/api/admin/module-builder/{mod}/categories",
headers=admin_headers,
)
assert list_resp.status_code == 200
cats = list_resp.json()
assert any(c["category_code"] == cat_code for c in cats)
# 3. Save Full Disease via API
full_resp = await client.post(
f"/api/admin/module-builder/{mod}/save-full",
headers=admin_headers,
json={
"category_code": cat_code,
"disease_code": dis_code,
"name": "API Disease Test",
"overview": "Disease saved via API",
"patterns": [
{
"category_code": cat_code,
"disease_code": dis_code,
"pattern_code": "api_pat_1",
"name": "API Pattern 1",
"description": "Desc 1",
"clinical_data": {
"clinical_manifestations": ["Symptom A", "Symptom B"],
"tongue": "Pale",
"pulse": "Wiry",
"treatment_principle": "Tonify Qi",
"acupuncture": {"points": "RN-6, ST-36", "method": "Reinforcing"},
"explanation": ["RN-6 tonifies Qi."],
},
"sort_order": 0,
}
],
},
)
assert full_resp.status_code == 200, full_resp.text
full_data = full_resp.json()
assert full_data["disease_code"] == dis_code
assert len(full_data["patterns"]) == 1
# 4. Export JSON via API
export_resp = await client.get(
f"/api/admin/module-builder/{mod}/export-json",
headers=admin_headers,
)
assert export_resp.status_code == 200
exp = export_resp.json()
assert "contents" in exp
assert len(exp["contents"]) >= 1
# 5. Clean up Category via API
del_resp = await client.delete(
f"/api/admin/module-builder/{mod}/categories/{cat_code}",
headers=admin_headers,
)
assert del_resp.status_code == 200
finally:
app.dependency_overrides.pop(get_db_session, None)
app.dependency_overrides.pop(get_current_admin, None)
@pytest.mark.asyncio
async def test_module_builder_validations(db_session: AsyncSession):
from fastapi import HTTPException
service = ModuleBuilderService(db_session)
mod = "m_val_test"
# 1. Empty category name
with pytest.raises(HTTPException) as exc1:
await service.save_category(
mod,
SaveCategoryRequest(category_code="valid_code", name=" ")
)
assert exc1.value.status_code == 400
assert "Category name cannot be empty" in exc1.value.detail
# 2. Disease under nonexistent category
with pytest.raises(HTTPException) as exc2:
await service.save_disease(
mod,
SaveDiseaseRequest(category_code="non_existent_cat", disease_code="dis_code", name="Dis Name")
)
assert exc2.value.status_code == 404
assert "does not exist" in exc2.value.detail
# 3. Full disease with no patterns
with pytest.raises(HTTPException) as exc3:
await service.save_full_disease(
mod,
SaveFullDiseaseRequest(
category_code="cat",
disease_code="dis",
name="Dis",
patterns=[],
)
)
assert exc3.value.status_code == 400
assert "at least one clinical pattern" in exc3.value.detail
@pytest.mark.asyncio
async def test_builder_modules_api_flow(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
from app.main import app
from app.db.session import get_db_session
from app.features.admin.deps import get_current_admin
from httpx import ASGITransport, AsyncClient
async def override_get_db():
yield db_session
app.dependency_overrides[get_db_session] = override_get_db
app.dependency_overrides[get_current_admin] = lambda: sample_admin
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# 1. List modules - should include at least m0042
list_res = await client.get("/api/admin/module-builder/modules", headers=admin_headers)
assert list_res.status_code == 200, list_res.text
modules = list_res.json()
codes = [m["code"] for m in modules]
assert "m0042" in codes
# 2. Create a new module (m0091 Pediatrics Test)
create_res = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={
"name": "Pediatrics Test",
"code": "m0091",
"short_description": "Pediatric disorders test module",
"description": "Comprehensive TCM pediatrics.",
"kind": "therapeutic",
"sort_order": 91000,
},
)
assert create_res.status_code == 201, create_res.text
created_mod = create_res.json()
assert created_mod["code"] == "m0091"
assert created_mod["slug"] == "pediatrics-test"
assert created_mod["category_count"] == 0
# 3. Duplicate code returns 409 Conflict
dup_res = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={"name": "Duplicate Pediatrics", "code": "m0091"},
)
assert dup_res.status_code == 409
assert "already exists" in dup_res.json()["detail"]
# 4. Invalid code format returns 422
inv_res = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={"name": "Bad Code Module", "code": "invalid_code_123"},
)
assert inv_res.status_code == 422
# 5. Get created module
get_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers)
assert get_res.status_code == 200
assert get_res.json()["name"] == "Pediatrics Test"
# 6. Update module
patch_res = await client.patch(
"/api/admin/module-builder/modules/m0091",
headers=admin_headers,
json={"name": "Pediatric Disorders Updated", "short_description": "Updated short desc"},
)
assert patch_res.status_code == 200
assert patch_res.json()["name"] == "Pediatric Disorders Updated"
# 7. Delete created module
del_res = await client.delete("/api/admin/module-builder/modules/m0091", headers=admin_headers)
assert del_res.status_code == 200
assert del_res.json()["status"] == "deleted"
# 8. Verify 404 after deletion
not_found_res = await client.get("/api/admin/module-builder/modules/m0091", headers=admin_headers)
assert not_found_res.status_code == 404
finally:
app.dependency_overrides.pop(get_db_session, None)
app.dependency_overrides.pop(get_current_admin, None)
@pytest.mark.asyncio
async def test_module_content_compiler_full_pipeline(db_session: AsyncSession):
import json
import zipfile
import io
from app.features.admin.builder_schema import (
CreateBuilderModuleRequest,
SaveCategoryRequest,
SaveFullDiseaseRequest,
SavePatternRequest,
)
from app.features.admin.services.module_builder_service import ModuleBuilderService
from app.bootstrap.seed_content.validators import (
validate_definition_document,
validate_presentation_contracts,
validate_content_document,
)
service = ModuleBuilderService(db_session)
mod_code = "m0088"
try:
# 1. Create Module
await service.create_module(
CreateBuilderModuleRequest(
name="Compiler Test Pediatrics",
code=mod_code,
short_description="Testing full compiler pipeline",
kind="therapeutic",
sort_order=88000,
)
)
# 2. Add Category
cat_code = "infant_digestion"
await service.save_category(
mod_code,
SaveCategoryRequest(category_code=cat_code, name="Infant Digestion", sort_order=0),
)
# 3. Add Disease + Patterns
dis_code = "infantile_colic"
await service.save_full_disease(
mod_code,
SaveFullDiseaseRequest(
category_code=cat_code,
disease_code=dis_code,
name="Infantile Colic",
overview="Colic symptoms in newborn infants.",
patterns=[
SavePatternRequest(
category_code=cat_code,
disease_code=dis_code,
pattern_code="food_stagnation",
name="Food Stagnation Colic",
clinical_data={
"clinical_manifestations": ["Inconsolable crying", "Abdominal distension"],
"tongue": "Thick white coating",
"pulse": "Slippery",
"treatment_principle": "Resolve Food Stagnation, Harmonize Middle Burner",
"acupuncture": {"points": "ST-36, SP-4, CV-12", "method": "Even method"},
"explanation": ["ST-36 harmonizes the stomach and relieves spasms."],
},
sort_order=0,
)
],
),
)
# 4. Compile Module
module_obj, compiled_files = await service.compiler.compile_module(mod_code)
assert module_obj.code == mod_code
assert "module.json" in compiled_files
assert "search_facets.json" in compiled_files
assert "data/list.json" in compiled_files
assert f"data/{cat_code}/list.json" in compiled_files
assert f"data/{cat_code}/{dis_code}/list.json" in compiled_files
assert f"data/{cat_code}/{dis_code}/data.json" in compiled_files
assert "data/detail_patterns.json" in compiled_files
# 5. Validate Root & Category Templates with Seeder Validators
root_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0001.json"])
validate_definition_document(root_tpl)
validate_presentation_contracts(root_tpl)
cat_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0002.json"])
validate_definition_document(cat_tpl)
validate_presentation_contracts(cat_tpl)
dis_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0011.json"])
validate_definition_document(dis_tpl)
validate_presentation_contracts(dis_tpl)
det_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0005.json"])
validate_definition_document(det_tpl)
validate_presentation_contracts(det_tpl)
det_def_codes = {d["code"] for d in det_tpl["attribute_defs"]}
det_pres_keys = [
a["attribute_key"]
for c in det_tpl["presentation_contracts"]
for a in c["attributes"]
]
assert f"{mod_code}_ct0005.pattern_name" in det_pres_keys
assert f"{mod_code}_ct0005.name" not in det_pres_keys
for key in det_pres_keys:
root_code = key.split(".", 2)[1]
assert root_code in det_def_codes, f"{key} missing from detail attribute_defs"
# 6. Validate Data Documents with Seeder Validators
validate_content_document(json.loads(compiled_files["data/list.json"]))
validate_content_document(json.loads(compiled_files[f"data/{cat_code}/list.json"]))
validate_content_document(json.loads(compiled_files[f"data/{cat_code}/{dis_code}/list.json"]))
validate_content_document(json.loads(compiled_files["data/detail_patterns.json"]))
# 7. Test In-Memory ZIP Generation
zip_name, zip_bytes = await service.export_bundle_zip(mod_code)
assert zip_name.endswith(".zip")
assert len(zip_bytes) > 0
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf:
namelist = zf.namelist()
assert f"{mod_code}-compiler-test-pediatrics/module.json" in namelist
assert f"{mod_code}-compiler-test-pediatrics/data/list.json" in namelist
assert f"{mod_code}-compiler-test-pediatrics/data/detail_patterns.json" in namelist
finally:
try:
await service.delete_module(mod_code)
except Exception:
pass
@pytest.mark.asyncio
async def test_compiler_api_endpoints(db_session: AsyncSession, admin_headers: dict[str, str], sample_admin):
import io
import zipfile
from app.main import app
from app.db.session import get_db_session
from app.features.admin.deps import get_current_admin
from httpx import ASGITransport, AsyncClient
async def override_get_db():
yield db_session
app.dependency_overrides[get_db_session] = override_get_db
app.dependency_overrides[get_current_admin] = lambda: sample_admin
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
mod = "m0089"
# 1. Create module
await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={"name": "API Export Test", "code": mod},
)
# 2. Add Category
await client.post(
f"/api/admin/module-builder/{mod}/categories",
headers=admin_headers,
json={"category_code": "cat_export", "name": "Category Export"},
)
# 3. Add Disease with Pattern
await client.post(
f"/api/admin/module-builder/{mod}/save-full",
headers=admin_headers,
json={
"category_code": "cat_export",
"disease_code": "dis_export",
"name": "Disease Export",
"patterns": [
{
"category_code": "cat_export",
"disease_code": "dis_export",
"pattern_code": "pat_export",
"name": "Pattern Export",
"clinical_data": {
"clinical_manifestations": ["Test symptom"],
"tongue": "Red",
"pulse": "Rapid",
"treatment_principle": "Clear heat",
"acupuncture": {"points": "LI-11", "method": "Reducing"},
"explanation": ["LI-11 clears heat"],
},
}
],
},
)
# 4. Export ZIP Bundle
bundle_res = await client.get(
f"/api/admin/module-builder/{mod}/export-bundle",
headers=admin_headers,
)
assert bundle_res.status_code == 200
assert bundle_res.headers["content-type"] == "application/zip"
assert "attachment; filename=" in bundle_res.headers["content-disposition"]
# Inspect zip contents
with zipfile.ZipFile(io.BytesIO(bundle_res.content)) as zf:
files = zf.namelist()
assert any("module.json" in f for f in files)
assert any("detail_patterns.json" in f for f in files)
# Clean up
await client.delete(f"/api/admin/module-builder/modules/{mod}", headers=admin_headers)
finally:
app.dependency_overrides.pop(get_db_session, None)
app.dependency_overrides.pop(get_current_admin, None)
@pytest.mark.asyncio
async def test_compiler_sync_content_repo(db_session: AsyncSession, tmp_path):
import json
from pathlib import Path
from app.features.admin.builder_schema import (
CreateBuilderModuleRequest,
SaveCategoryRequest,
SaveFullDiseaseRequest,
SavePatternRequest,
)
from app.features.admin.services.module_builder_service import ModuleBuilderService
service = ModuleBuilderService(db_session)
mod = "m0087"
# Setup mock repo root with config.json
mock_config = {
"modules": [
{
"name": "Acupuncture Points",
"code": "m0001",
"path": "m0001-acupuncture-points",
"status": "active",
"sort_order": "10001",
}
]
}
config_file = tmp_path / "config.json"
config_file.write_text(json.dumps(mock_config, indent=4), encoding="utf-8")
try:
# Create module
await service.create_module(
CreateBuilderModuleRequest(
name="Repo Sync Test",
code=mod,
sort_order=87000,
)
)
await service.save_category(
mod,
SaveCategoryRequest(category_code="cat_sync", name="Category Sync"),
)
await service.save_full_disease(
mod,
SaveFullDiseaseRequest(
category_code="cat_sync",
disease_code="dis_sync",
name="Disease Sync",
patterns=[
SavePatternRequest(
category_code="cat_sync",
disease_code="dis_sync",
pattern_code="pat_sync",
name="Pattern Sync",
clinical_data={
"clinical_manifestations": ["Sync test symptom"],
"tongue": "Pale",
"pulse": "Weak",
"treatment_principle": "Sync principle",
"acupuncture": {"points": "ST-36", "method": "Even"},
},
)
],
),
)
# Execute sync to tmp repo root
result = await service.sync_content_repo(mod, repo_root=tmp_path)
assert result["status"] == "synced"
assert result["files_written"] > 0
assert result["config_updated"] is True
# Verify files on disk
target_dir = tmp_path / f"{mod}-repo-sync-test"
assert (target_dir / "module.json").exists()
assert (target_dir / "templates" / f"{mod}_ct0001.json").exists()
assert (target_dir / "templates" / f"{mod}_ct0005.json").exists()
assert (target_dir / "data" / "list.json").exists()
assert (target_dir / "data" / "detail_patterns.json").exists()
# Verify config.json has updated entry
updated_cfg = json.loads(config_file.read_text(encoding="utf-8"))
codes = [m["code"] for m in updated_cfg["modules"]]
assert mod in codes
finally:
try:
await service.delete_module(mod)
except Exception:
pass
@pytest.mark.asyncio
async def test_therapeutic_module_builder_lifecycle_and_safety_api(
db_session: AsyncSession, admin_headers: dict[str, str], sample_admin
):
"""Thoroughly tests the multi-module lifecycle via FastAPI HTTP endpoints:
1. Enforcing 'therapeutic' kind and 'module_builder' ownership.
2. Preventing modification or creation of non-therapeutic or legacy core modules.
3. Creating, updating, adding clinical content, exporting, and deleting a test module.
"""
from app.main import app
from app.db.session import get_db_session
from app.features.admin.deps import get_current_admin
from httpx import ASGITransport, AsyncClient
async def override_get_db():
yield db_session
app.dependency_overrides[get_db_session] = override_get_db
app.dependency_overrides[get_current_admin] = lambda: sample_admin
test_mod_code = "m0049"
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
# -------------------------------------------------------------
# 1. SAFETY CHECKS: Legacy Protection
# -------------------------------------------------------------
# A. Attempting to add a category to legacy points module (m0001) -> 403
resp = await client.post(
"/api/admin/module-builder/m0001/categories",
headers=admin_headers,
json={"category_code": "illegal_cat", "name": "Illegal Points Category"},
)
assert resp.status_code == 403, resp.text
assert "legacy 'point' module and cannot be modified" in resp.json()["detail"]
# B. Attempting to save disease to legacy nutrition module (m0031) -> 403
resp = await client.post(
"/api/admin/module-builder/m0031/save-full",
headers=admin_headers,
json={
"category_code": "nut_cat",
"disease_code": "nut_dis",
"name": "Illegal Nutrition Disease",
"patterns": [
{
"category_code": "nut_cat",
"disease_code": "nut_dis",
"pattern_code": "nut_pat",
"name": "Nut Pattern",
}
],
},
)
assert resp.status_code == 403, resp.text
assert "legacy 'nutrition' module and cannot be modified" in resp.json()["detail"]
# C. Attempting to update legacy diagnostics module (m0011) -> 403
resp = await client.patch(
"/api/admin/module-builder/modules/m0011",
headers=admin_headers,
json={"name": "Hacked Eight Principles"},
)
assert resp.status_code == 403, resp.text
# D. Attempting to create a non-therapeutic module -> 400
resp = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={
"name": "Invalid Kind Module",
"kind": "point",
},
)
assert resp.status_code == 400, resp.text
assert "therapeutic" in resp.json()["detail"]
# E. Attempting to hijack existing legacy code m0001 -> 409
resp = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={
"name": "Points Override",
"code": "m0001",
"kind": "therapeutic",
},
)
assert resp.status_code == 409, resp.text
assert "conflicts with an existing core Acupedia module" in resp.json()["detail"]
# -------------------------------------------------------------
# 2. CREATE NEW THERAPEUTIC TEST MODULE (m0049)
# -------------------------------------------------------------
# Clean up if existing from a previous interrupted run
await client.delete(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
)
create_resp = await client.post(
"/api/admin/module-builder/modules",
headers=admin_headers,
json={
"name": "Pediatric Therapeutics Test",
"code": test_mod_code,
"description": "Comprehensive TCM pediatrics and infantile massage therapeutics.",
"short_description": "Pediatric acupuncture and therapeutics.",
},
)
assert create_resp.status_code == 201, create_resp.text
mod_data = create_resp.json()
assert mod_data["code"] == test_mod_code
assert mod_data["name"] == "Pediatric Therapeutics Test"
assert mod_data["kind"] == "therapeutic"
assert mod_data["managed_by"] == "module_builder"
assert mod_data["slug"] == "pediatric-therapeutics-test"
assert mod_data["sort_order"] > 40000
# -------------------------------------------------------------
# 3. GET & LIST MODULES
# -------------------------------------------------------------
list_resp = await client.get(
"/api/admin/module-builder/modules",
headers=admin_headers,
)
assert list_resp.status_code == 200
modules = list_resp.json()
assert any(m["code"] == test_mod_code for m in modules)
for m in modules:
assert m["kind"] == "therapeutic"
assert m["managed_by"] == "module_builder"
get_resp = await client.get(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
)
assert get_resp.status_code == 200
assert get_resp.json()["code"] == test_mod_code
# -------------------------------------------------------------
# 4. UPDATE MODULE METADATA
# -------------------------------------------------------------
patch_resp = await client.patch(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
json={
"name": "Pediatric TCM Clinical Therapeutics",
"short_description": "Updated short description",
},
)
assert patch_resp.status_code == 200
updated_mod = patch_resp.json()
assert updated_mod["name"] == "Pediatric TCM Clinical Therapeutics"
assert updated_mod["short_description"] == "Updated short description"
# -------------------------------------------------------------
# 5. ADD CATEGORY, DISEASE & PATTERNS TO NEW MODULE
# -------------------------------------------------------------
cat_resp = await client.post(
f"/api/admin/module-builder/{test_mod_code}/categories",
headers=admin_headers,
json={
"category_code": "respiratory_disorders",
"name": "Respiratory Disorders",
"overview": "Pediatric respiratory complaints including cough and asthma.",
"sort_order": 1,
},
)
assert cat_resp.status_code == 200, cat_resp.text
assert cat_resp.json()["category_code"] == "respiratory_disorders"
full_dis_resp = await client.post(
f"/api/admin/module-builder/{test_mod_code}/save-full",
headers=admin_headers,
json={
"category_code": "respiratory_disorders",
"disease_code": "pediatric_cough",
"name": "Pediatric Cough",
"overview": "Overview of pediatric cough and bronchial irritation.",
"patterns": [
{
"category_code": "respiratory_disorders",
"disease_code": "pediatric_cough",
"pattern_code": "wind_heat_cough",
"name": "Wind-Heat Cough",
"description": "Acute pediatric cough with yellow phlegm and mild fever.",
"clinical_data": {
"clinical_manifestations": ["Barking cough", "Thick yellow sputum", "Thirst"],
"tongue": "Red with thin yellow coating",
"pulse": "Floating and rapid",
"treatment_principle": "Dispel Wind, clear Heat, diffuse Lung Qi.",
"acupuncture": {
"points": "LU-7, LI-4, LU-5, BL-13",
"method": "Reducing or gentle stimulation for pediatric cases",
},
"explanation": ["LU-7 and LI-4 release the exterior and expel wind."],
},
"sort_order": 0,
}
],
},
)
assert full_dis_resp.status_code == 200, full_dis_resp.text
dis_data = full_dis_resp.json()
assert dis_data["disease_code"] == "pediatric_cough"
assert len(dis_data["patterns"]) == 1
assert dis_data["patterns"][0]["name"] == "Wind-Heat Cough"
# Verify counts in module summary
verify_resp = await client.get(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
)
assert verify_resp.status_code == 200
summary = verify_resp.json()
assert summary["category_count"] == 1
assert summary["disease_count"] == 1
assert summary["pattern_count"] == 1
# -------------------------------------------------------------
# 6. EXPORT ARTIFACTS
# -------------------------------------------------------------
exp_json_resp = await client.get(
f"/api/admin/module-builder/{test_mod_code}/export-json",
headers=admin_headers,
)
assert exp_json_resp.status_code == 200
exp_doc = exp_json_resp.json()
assert len(exp_doc["contents"]) == 1
assert exp_doc["contents"][0]["code"] == "respiratory_disorders"
exp_bundle_resp = await client.get(
f"/api/admin/module-builder/{test_mod_code}/export-bundle",
headers=admin_headers,
)
assert exp_bundle_resp.status_code == 200
assert exp_bundle_resp.headers["content-type"] == "application/zip"
assert len(exp_bundle_resp.content) > 500
# -------------------------------------------------------------
# 7. DELETE TEST MODULE
# -------------------------------------------------------------
del_resp = await client.delete(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
)
assert del_resp.status_code == 200
assert del_resp.json()["status"] == "deleted"
# Verify 404 after deletion
get_deleted = await client.get(
f"/api/admin/module-builder/modules/{test_mod_code}",
headers=admin_headers,
)
assert get_deleted.status_code == 404
finally:
app.dependency_overrides.clear()

View File

@ -1,51 +0,0 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from fastapi import HTTPException
from app.core.config import Settings
from app.features.admin import api as admin_api
def test_enable_module_repo_sync_defaults_to_false(monkeypatch):
monkeypatch.delenv("ENABLE_MODULE_REPO_SYNC", raising=False)
s = Settings(_env_file=None)
assert s.enable_module_repo_sync is False
@pytest.mark.asyncio
async def test_get_builder_config_reflects_setting(monkeypatch):
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=False))
res_off = await admin_api.get_builder_config(admin=MagicMock())
assert res_off == {"sync_repo_enabled": False}
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=True))
res_on = await admin_api.get_builder_config(admin=MagicMock())
assert res_on == {"sync_repo_enabled": True}
@pytest.mark.asyncio
async def test_sync_builder_module_to_repo_blocked_when_disabled(monkeypatch):
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=False))
service = SimpleNamespace(builder=SimpleNamespace(sync_content_repo=AsyncMock()))
with pytest.raises(HTTPException) as exc_info:
await admin_api.sync_builder_module_to_repo("m0042", admin=MagicMock(), service=service)
assert exc_info.value.status_code == 403
service.builder.sync_content_repo.assert_not_awaited()
@pytest.mark.asyncio
async def test_sync_builder_module_to_repo_allowed_when_enabled(monkeypatch):
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=True))
service = SimpleNamespace(
builder=SimpleNamespace(sync_content_repo=AsyncMock(return_value={"status": "synced"}))
)
res = await admin_api.sync_builder_module_to_repo("m0042", admin=MagicMock(), service=service)
assert res == {"status": "synced"}
service.builder.sync_content_repo.assert_awaited_once_with("m0042")

View File

@ -28,11 +28,6 @@ class TestPasswordValidation(unittest.TestCase):
validate_password_strength("NoSpecial123")
self.assertIn("special character", str(ctx.exception))
def test_emoji_instead_of_special_char_fails(self):
with self.assertRaises(WeakPasswordError) as ctx:
validate_password_strength("NoSpecial123😀")
self.assertIn("special character", str(ctx.exception))
def test_valid_passwords_pass(self):
# Must not raise any exceptions
validate_password_strength("Siraj@12345")

View File

@ -1,13 +0,0 @@
from __future__ import annotations
import pytest
from httpx import AsyncClient
@pytest.mark.asyncio
async def test_root_endpoint_returns_running_status(async_client: AsyncClient) -> None:
response = await async_client.get("/")
assert response.status_code == 200
data = response.json()
assert data["status"] == "Acupedia Backend is Running"
assert data["version"] == "1.0.0"
assert "database_name" in data

View File

@ -1,85 +0,0 @@
from __future__ import annotations
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.db.models import AppUser
from app.features.admin.constants import has_admin_role
from app.features.admin.services.customer_service import AdminCustomerService
def _make_user(email: str, name: str) -> MagicMock:
user = MagicMock(spec=AppUser)
user.id = uuid4()
user.email = email
user.display_name = name
user.phone_number = "+919876543210"
user.country = "India"
user.is_active = True
user.external_ref = None
user.created_at = datetime(2026, 10, 1, 12, 0, 0, tzinfo=timezone.utc)
return user
def _build_session(users: list[MagicMock], role_rows: list[tuple], sub_rows: list[tuple]) -> AsyncMock:
session = AsyncMock()
res_users = MagicMock()
res_users.scalars.return_value.all.return_value = users
res_roles = MagicMock()
res_roles.all.return_value = role_rows
res_subs = MagicMock()
res_subs.all.return_value = sub_rows
session.execute.side_effect = [res_users, res_roles, res_subs]
return session
def test_has_admin_role_handles_all_admin_variants() -> None:
assert has_admin_role(["super_admin"]) is True
assert has_admin_role(["admin"]) is True
assert has_admin_role(["finance_admin"]) is True
assert has_admin_role(["practitioner", "super_admin"]) is True
assert has_admin_role([" Finance_Admin "]) is True
assert has_admin_role(["practitioner"]) is False
assert has_admin_role([]) is False
assert has_admin_role(None) is False
@pytest.mark.asyncio
async def test_list_users_excludes_all_admin_roles_from_customers() -> None:
practitioner = _make_user("prac@example.com", "Practitioner One")
unassigned = _make_user("guest@example.com", "Unassigned User")
super_admin = _make_user("super@example.com", "Super Admin")
regular_admin = _make_user("admin@example.com", "Admin User")
finance_admin = _make_user("finance@example.com", "Finance Admin")
users = [practitioner, unassigned, super_admin, regular_admin, finance_admin]
role_rows = [
(practitioner.id, "practitioner"),
# Super admins created via AdminCustomerService carry both roles
(super_admin.id, "practitioner"),
(super_admin.id, "super_admin"),
(regular_admin.id, "admin"),
(finance_admin.id, "finance_admin"),
]
# 1. Practitioners / Customers query should exclude all admin roles
svc_customers = AdminCustomerService(_build_session(users, role_rows, []))
customers = await svc_customers.list_users(super_admin_only=False)
assert [c.email for c in customers] == ["prac@example.com", "guest@example.com"]
# 2. Admins query should capture super_admin, admin, and finance_admin
svc_admins = AdminCustomerService(_build_session(users, role_rows, []))
admins = await svc_admins.list_users(super_admin_only=True)
assert [a.email for a in admins] == [
"super@example.com",
"admin@example.com",
"finance@example.com",
]

View File

@ -1,370 +0,0 @@
from __future__ import annotations
from decimal import Decimal
import pytest
from app.features.payments.pricing import PricingEngine, PricingItem, PricingCoupon
@pytest.fixture
def engine() -> PricingEngine:
return PricingEngine()
class TestPricingEngineBundleRules:
def test_empty_cart(self, engine: PricingEngine) -> None:
result = engine.calculate(
items=[],
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=True,
)
assert result["base_subtotal"] == 0.0
assert result["grand_total"] == 0.0
assert result["bundle_discount_amount"] == 0.0
assert result["discount_policy"] == "None"
def test_first_time_buy_single_unit_no_discount(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_ACU", name="Acupuncture", category="acu", price=Decimal("1000.00")),
]
result = engine.calculate(
items=items,
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=True,
)
assert result["base_subtotal"] == 1000.0
assert result["bundle_discount_amount"] == 0.0
assert result["grand_total"] == 1000.0
assert result["discount_policy"] == "None"
def test_first_time_buy_two_units_ten_percent(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_ACU", name="Acupuncture", category="acu", price=Decimal("1000.00")),
PricingItem(code="MOD_MOXA", name="Moxibustion", category="moxa", price=Decimal("1000.00")),
]
result = engine.calculate(
items=items,
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=True,
)
assert result["base_subtotal"] == 2000.0
assert result["bundle_discount_amount"] == 200.0 # 10% of 2000
assert result["grand_total"] == 1800.0
assert "10% Off" in result["discount_policy"]
def test_first_time_buy_three_units_twenty_percent(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
PricingItem(code="MOD_2", name="Mod 2", category="cat2", price=Decimal("1000.00")),
PricingItem(code="MOD_3", name="Mod 3", category="cat3", price=Decimal("1000.00")),
]
result = engine.calculate(
items=items,
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=True,
)
assert result["base_subtotal"] == 3000.0
assert result["bundle_discount_amount"] == 600.0 # 20% of 3000
assert result["grand_total"] == 2400.0
assert "20% Off" in result["discount_policy"]
def test_first_time_buy_four_or_more_units_thirty_percent(self, engine: PricingEngine) -> None:
items = [
PricingItem(code=f"MOD_{i}", name=f"Mod {i}", category=f"cat{i}", price=Decimal("1000.00"))
for i in range(1, 5)
]
result = engine.calculate(
items=items,
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=True,
)
assert result["base_subtotal"] == 4000.0
assert result["bundle_discount_amount"] == 1200.0 # 30% of 4000
assert result["grand_total"] == 2800.0
assert "30% Off" in result["discount_policy"]
def test_lifetime_package_overrides_discounts(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="LIFETIME_ALL", name="Lifetime Access", category="lifetime", price=Decimal("15000.00")),
]
result = engine.calculate(
items=items,
owned_categories=["cat1", "cat2"],
coupon=None,
currency="INR",
is_first_purchase=False,
)
assert result["discount_policy"] == "Lifetime Bulk Package"
assert result["bundle_discount_amount"] == 0.0
assert result["grand_total"] == 15000.0
class TestPricingEngineLoyaltyRules:
def test_loyalty_discount_scaling(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
]
# 1 owned category -> 5%
res1 = engine.calculate(
items=items,
owned_categories=["cat_old1"],
coupon=None,
currency="INR",
is_first_purchase=False,
)
assert res1["bundle_discount_amount"] == 50.0 # 5%
assert "5% Off" in res1["discount_policy"]
# 3 owned categories -> 15%
res3 = engine.calculate(
items=items,
owned_categories=["cat_old1", "cat_old2", "cat_old3"],
coupon=None,
currency="INR",
is_first_purchase=False,
)
assert res3["bundle_discount_amount"] == 150.0 # 15%
assert "15% Off" in res3["discount_policy"]
# 6 owned categories -> capped at 25%
res6 = engine.calculate(
items=items,
owned_categories=[f"cat_old_{i}" for i in range(6)],
coupon=None,
currency="INR",
is_first_purchase=False,
)
assert res6["bundle_discount_amount"] == 250.0 # max 25%
assert "25% Off" in res6["discount_policy"]
class TestPricingEngineCouponRules:
def test_flat_coupon_discount(self, engine: PricingEngine) -> None:
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00"))]
coupon = PricingCoupon(
code="FLAT200",
category="general",
discount_type="flat",
value=Decimal("200.00"),
description="Flat Rs 200 off",
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 200.0
assert result["grand_total"] == 800.0
assert "FLAT200" in result["coupon_applied"]
def test_percentage_coupon_discount(self, engine: PricingEngine) -> None:
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00"))]
coupon = PricingCoupon(
code="SAVE15",
category="general",
discount_type="percentage",
value=Decimal("15.00"),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 150.0 # 15% of 1000
assert result["grand_total"] == 850.0
def test_coupon_max_discount_cap(self, engine: PricingEngine) -> None:
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("5000.00"))]
coupon = PricingCoupon(
code="BIG50",
category="general",
discount_type="percentage",
value=Decimal("50.00"), # 50% would be 2500
max_discount_limit=Decimal("1000.00"), # capped at 1000
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 1000.0
assert result["grand_total"] == 4000.0
def test_coupon_min_purchase_amount_not_met(self, engine: PricingEngine) -> None:
items = [PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("500.00"))]
coupon = PricingCoupon(
code="MIN1000",
category="general",
discount_type="flat",
value=Decimal("100.00"),
min_purchase_amount=Decimal("1000.00"),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 0.0
assert result["grand_total"] == 500.0
assert result["coupon_error"] is not None
assert "Minimum cart spend" in result["coupon_error"]
def test_plan_scoped_coupon_rejected_on_unmatched_items(self, engine: PricingEngine) -> None:
lifetime_plan_id = "11111111-1111-1111-1111-111111111111"
yearly_plan_id = "22222222-2222-2222-2222-222222222222"
items = [
PricingItem(code="POINTS_1YR", name="Points 1-Year", category="Points", price=Decimal("2000.00"), plan_id=yearly_plan_id)
]
coupon = PricingCoupon(
code="LIFETIMEONLY",
category="specific",
discount_type="percentage",
value=Decimal("20.00"),
applicable_plan_ids=(lifetime_plan_id,),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 0.0
assert result["coupon_applied"] == "None"
assert result["coupon_error"] == "This promo code is not valid for items in your cart."
assert result["grand_total"] == 2000.0
def test_plan_scoped_coupon_applied_on_matched_lifetime_item(self, engine: PricingEngine) -> None:
lifetime_plan_id = "11111111-1111-1111-1111-111111111111"
items = [
PricingItem(code="LIFETIME_ALL", name="Lifetime All", category="Lifetime", price=Decimal("10000.00"), plan_id=lifetime_plan_id)
]
coupon = PricingCoupon(
code="LIFETIMEONLY",
category="specific",
discount_type="percentage",
value=Decimal("20.00"),
applicable_plan_ids=(lifetime_plan_id,),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["coupon_discount_amount"] == 2000.0
assert result["coupon_error"] is None
assert "LIFETIMEONLY" in result["coupon_applied"]
assert result["grand_total"] == 8000.0
def test_plan_scoped_coupon_mixed_cart_applies_only_to_qualifying_spend(self, engine: PricingEngine) -> None:
lifetime_plan_id = "11111111-1111-1111-1111-111111111111"
yearly_plan_id = "22222222-2222-2222-2222-222222222222"
items = [
PricingItem(code="POINTS_1YR", name="Points 1-Year", category="Points", price=Decimal("2000.00"), plan_id=yearly_plan_id),
PricingItem(code="LIFETIME_ALL", name="Lifetime All", category="Lifetime", price=Decimal("10000.00"), plan_id=lifetime_plan_id),
]
coupon = PricingCoupon(
code="LIFETIMEONLY",
category="specific",
discount_type="percentage",
value=Decimal("10.00"),
applicable_plan_ids=(lifetime_plan_id,),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
# 10% of 10000 = 1000 discount (does not discount the 2000 1-yr item)
assert result["base_subtotal"] == 12000.0
assert result["coupon_discount_amount"] == 1000.0
assert result["grand_total"] == 11000.0
assert result["coupon_error"] is None
def test_module_scoped_coupon(self, engine: PricingEngine) -> None:
mod_id = "33333333-3333-3333-3333-333333333333"
other_mod_id = "44444444-4444-4444-4444-444444444444"
items = [
PricingItem(code="PLAN_A", name="Plan A", category="Cat", price=Decimal("1000.00"), module_ids=(other_mod_id,))
]
coupon = PricingCoupon(
code="MODONLY",
category="specific",
discount_type="flat",
value=Decimal("200.00"),
applicable_module_ids=(mod_id,),
)
# Unmatched module
res1 = engine.calculate(items=items, owned_categories=[], coupon=coupon, currency="INR", is_first_purchase=True)
assert res1["coupon_discount_amount"] == 0.0
assert res1["coupon_error"] == "This promo code is not valid for items in your cart."
# Matched module
items_match = [
PricingItem(code="PLAN_B", name="Plan B", category="Cat", price=Decimal("1000.00"), module_ids=(mod_id,))
]
res2 = engine.calculate(items=items_match, owned_categories=[], coupon=coupon, currency="INR", is_first_purchase=True)
assert res2["coupon_discount_amount"] == 200.0
assert res2["coupon_error"] is None
def test_introductory_flat_coupon_disables_unit_bundle_discount(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
PricingItem(code="MOD_2", name="Mod 2", category="cat2", price=Decimal("1000.00")),
]
coupon = PricingCoupon(
code="INTRO100",
category="introductory",
discount_type="flat",
value=Decimal("100.00"),
)
result = engine.calculate(
items=items,
owned_categories=[],
coupon=coupon,
currency="INR",
is_first_purchase=True,
)
assert result["discount_policy"] == "None (Overridden by New User Event Coupon)"
assert result["bundle_discount_amount"] == 0.0
assert result["coupon_discount_amount"] == 100.0
assert result["grand_total"] == 1900.0
def test_not_first_purchase_without_owned_categories(self, engine: PricingEngine) -> None:
items = [
PricingItem(code="MOD_1", name="Mod 1", category="cat1", price=Decimal("1000.00")),
]
result = engine.calculate(
items=items,
owned_categories=[],
coupon=None,
currency="INR",
is_first_purchase=False,
)
assert result["bundle_discount_amount"] == 0.0
assert result["discount_policy"] == "None"

View File

@ -1,32 +0,0 @@
import pytest
from app.features.checkout.service import validate_user_country_currency
def test_india_allows_inr_only():
validate_user_country_currency("India", "INR")
validate_user_country_currency("INDIA", "inr")
validate_user_country_currency(None, "INR")
validate_user_country_currency("", "INR")
with pytest.raises(ValueError, match="Users with billing country India must pay in INR"):
validate_user_country_currency("India", "USD")
with pytest.raises(ValueError, match="Users with billing country India must pay in INR"):
validate_user_country_currency("India", "EUR")
def test_european_countries_allow_eur_and_usd():
for eu_country in ["Germany", "France", "Italy", "Spain", "Netherlands", "Cyprus", "Estonia"]:
validate_user_country_currency(eu_country, "EUR")
validate_user_country_currency(eu_country, "USD")
with pytest.raises(ValueError, match="must pay in EUR or USD"):
validate_user_country_currency(eu_country, "INR")
def test_rest_of_world_allows_usd_only():
for country in ["United States", "Canada", "Australia", "Singapore", "United Kingdom"]:
validate_user_country_currency(country, "USD")
with pytest.raises(ValueError, match="INR payments are restricted"):
validate_user_country_currency(country, "INR")
with pytest.raises(ValueError, match="must pay in USD"):
validate_user_country_currency(country, "EUR")

View File

@ -1,201 +0,0 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.db.models import AppUser, Coupon
from app.features.admin.schema import CreateCouponRequest, UpdateCouponRequest
from app.features.admin.services.coupon_service import AdminCouponService
from app.features.cart.repository import CartRepository
from app.features.checkout.schema import CheckoutOrderRequest
from app.features.checkout.service import CheckoutService
def _make_active_coupon(*, usage_limit: int = 0, per_user_limit: int | None = None, usage_count: int = 0) -> MagicMock:
now = datetime.now(timezone.utc)
coupon = MagicMock(spec=Coupon)
coupon.id = uuid4()
coupon.code = "PROMO20"
coupon.discount_type = "percentage"
coupon.value = Decimal("20.00")
coupon.max_discount_limit = Decimal("0.00")
coupon.min_purchase_amount = Decimal("0.00")
coupon.start_date = now - timedelta(days=1)
coupon.end_date = now + timedelta(days=10)
coupon.usage_limit = usage_limit
coupon.per_user_limit = per_user_limit
coupon.usage_count = usage_count
coupon.applicable_plan_ids = []
coupon.applicable_module_ids = []
coupon.is_first_purchase_only = False
coupon.is_active = True
coupon.metadata_json = {}
return coupon
class TestPerUserCouponValidation:
@pytest.mark.asyncio
async def test_per_user_limit_zero_blocks_every_user(self) -> None:
session = AsyncMock()
coupon = _make_active_coupon(usage_limit=0, per_user_limit=0)
res_coupon = MagicMock()
res_coupon.scalar_one_or_none.return_value = coupon
session.execute.return_value = res_coupon
repo = CartRepository(session)
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
assert resolved is None
assert error == "This coupon is currently not available for redemption."
@pytest.mark.asyncio
async def test_per_user_limit_none_allows_unlimited_user_redemptions(self) -> None:
session = AsyncMock()
coupon = _make_active_coupon(usage_limit=0, per_user_limit=None, usage_count=5)
res_coupon = MagicMock()
res_coupon.scalar_one_or_none.return_value = coupon
session.execute.return_value = res_coupon
repo = CartRepository(session)
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
assert resolved is not None
assert error is None
@pytest.mark.asyncio
async def test_per_user_limit_enforces_user_redemption_cap(self) -> None:
session = AsyncMock()
coupon = _make_active_coupon(usage_limit=10, per_user_limit=1, usage_count=1)
res_coupon = MagicMock()
res_coupon.scalar_one_or_none.return_value = coupon
res_count = MagicMock()
res_count.scalar.return_value = 1
session.execute.side_effect = [res_coupon, res_count]
repo = CartRepository(session)
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
assert resolved is None
assert error == "You have already reached the usage limit for this coupon."
@pytest.mark.asyncio
async def test_per_user_limit_allows_user_below_limit(self) -> None:
session = AsyncMock()
coupon = _make_active_coupon(usage_limit=10, per_user_limit=2, usage_count=1)
res_coupon = MagicMock()
res_coupon.scalar_one_or_none.return_value = coupon
res_count = MagicMock()
res_count.scalar.return_value = 1
session.execute.side_effect = [res_coupon, res_count]
repo = CartRepository(session)
resolved, error = await repo.get_coupon("PROMO20", "INR", user_id=uuid4())
assert resolved is not None
assert error is None
class TestAdminCouponPerUserLimitLifecycle:
@pytest.mark.asyncio
async def test_create_coupon_accepts_zero_and_none_per_user_limit(self) -> None:
session = AsyncMock()
res_existing = MagicMock()
res_existing.scalar_one_or_none.return_value = None
session.execute.return_value = res_existing
svc = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
payload = CreateCouponRequest(
code="ZEROUSER",
discount_type="percentage",
value=10.0,
per_user_limit=0,
)
await svc.create_coupon(payload, admin)
added_coupon = session.add.call_args[0][0]
assert added_coupon.per_user_limit == 0
@pytest.mark.asyncio
async def test_create_coupon_requires_per_user_limit(self) -> None:
session = AsyncMock()
res_existing = MagicMock()
res_existing.scalar_one_or_none.return_value = None
session.execute.return_value = res_existing
svc = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
payload = CreateCouponRequest(
code="BLANKUSER",
discount_type="percentage",
value=10.0,
per_user_limit=None,
)
with pytest.raises(ValueError, match="Per-user limit is required"):
await svc.create_coupon(payload, admin)
@pytest.mark.asyncio
async def test_create_coupon_rejects_negative_per_user_limit(self) -> None:
session = AsyncMock()
res_existing = MagicMock()
res_existing.scalar_one_or_none.return_value = None
session.execute.return_value = res_existing
svc = AdminCouponService(session)
admin = AppUser(id=uuid4(), email="admin@acupedia.test")
payload = CreateCouponRequest(
code="NEGUSER",
discount_type="percentage",
value=10.0,
per_user_limit=-1,
)
with pytest.raises(ValueError, match="Per-user limit is required and must be 0 or greater"):
await svc.create_coupon(payload, admin)
@pytest.mark.asyncio
async def test_update_coupon_rejects_blank_per_user_limit_and_preserves_when_omitted(self) -> None:
coupon = _make_active_coupon(per_user_limit=1)
session = AsyncMock()
res_coupon = MagicMock()
res_coupon.scalar_one_or_none.return_value = coupon
session.execute.return_value = res_coupon
svc = AdminCouponService(session)
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(description="Unchanged limit"))
assert coupon.per_user_limit == 1
with pytest.raises(ValueError, match="Per-user limit is required"):
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(per_user_limit=None))
await svc.update_coupon(str(coupon.id), UpdateCouponRequest(per_user_limit=3))
assert coupon.per_user_limit == 3
@pytest.mark.asyncio
async def test_checkout_create_order_rejects_invalid_coupon() -> None:
session = AsyncMock()
cart_repo = MagicMock(spec=CartRepository)
service = CheckoutService(session=session, cart_repository=cart_repo)
service.cart_service.calculate = AsyncMock(
return_value=MagicMock(
grand_total=1000.0,
coupon_error="You have already reached the usage limit for this coupon.",
coupon_applied="None",
)
)
user = AppUser(id=uuid4(), email="user@acupedia.test", country="India")
req = CheckoutOrderRequest(cart_item_codes=["LIFETIME_ALL"], coupon_code="PROMO20", currency="INR")
with pytest.raises(ValueError, match="usage limit for this coupon"):
await service.create_order(user, req)

View File

@ -1,170 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.features.content.repository import ContentRepository
from app.features.content.service import ContentService
class _DummyMappings:
def __init__(self, rows: list[dict]):
self._rows = rows
def mappings(self):
return self._rows
@pytest.mark.asyncio
async def test_resolve_content_item_collection_counts_prioritizes_structured_collections() -> None:
cid_points = uuid4()
cid_gao_wu = uuid4()
cid_patterns = uuid4()
cid_narrative = uuid4()
session = AsyncMock()
rows = [
# 12 multivalue points rows
*[
{"content_id": cid_points, "attr_code": "points", "is_multivalue": True, "value_json": None}
for _ in range(12)
],
# Gao Wu has 6 gao_wu_command_points rows AND 1 stale point_codes row -> must pick 6
*[
{"content_id": cid_gao_wu, "attr_code": "gao_wu_command_points", "is_multivalue": True, "value_json": None}
for _ in range(6)
],
{"content_id": cid_gao_wu, "attr_code": "point_codes", "is_multivalue": True, "value_json": None},
# Scalar JSON array for patterns (Four Levels)
{
"content_id": cid_patterns,
"attr_code": "patterns",
"is_multivalue": False,
"value_json": [{"name": "P1"}, {"name": "P2"}, {"name": "P3"}, {"name": "P4"}],
},
# Non-collection attribute (e.g. description) should not yield an override
]
session.execute = AsyncMock(return_value=_DummyMappings(rows))
repo = ContentRepository(session)
counts = await repo.resolve_content_item_collection_counts(
content_ids={cid_points, cid_gao_wu, cid_patterns, cid_narrative}
)
assert counts[cid_points] == 12
assert counts[cid_gao_wu] == 6
assert counts[cid_patterns] == 4
assert cid_narrative not in counts
@pytest.mark.asyncio
async def test_resolve_template_content_counts_filters_statuses_and_label_sums() -> None:
session = AsyncMock()
count_rows = [
{"module_code": "m0012", "template_code": "m0012_ct0005", "item_count": 9},
{"module_code": "m0001", "template_code": "m0001_ct0002", "item_count": 15},
]
sum_rows = [
{
"module_code": "m0001",
"template_code": "m0001_ct0002",
"content_label": "points",
"total_count": 409,
}
]
session.execute = AsyncMock(
side_effect=[_DummyMappings(count_rows), _DummyMappings(sum_rows)]
)
repo = ContentRepository(session)
counts, sums = await repo.resolve_template_content_counts(
template_refs={("m0012", "m0012_ct0005"), ("m0001", "m0001_ct0002")},
include_draft=False,
)
assert counts == {
("m0012", "m0012_ct0005"): 9,
("m0001", "m0001_ct0002"): 15,
}
assert sums == {(("m0001", "m0001_ct0002"), "points"): 409}
@pytest.mark.asyncio
async def test_hydrate_dynamic_content_counts_handles_template_and_content_refs_safely() -> None:
xi_cleft_id = uuid4()
meridian_id = uuid4()
repo = MagicMock()
repo.resolve_template_content_counts = AsyncMock(
return_value=(
{
("m0001", "m0001_ct0002"): 15,
("m0012", "m0012_ct0005"): 9,
("m0042", "m0042_ct0002"): 11,
},
{(("m0001", "m0001_ct0002"), "points"): 409},
)
)
repo.resolve_content_item_collection_counts = AsyncMock(
return_value={xi_cleft_id: 16}
)
service = ContentService(
session=AsyncMock(),
repository=repo,
cache=MagicMock(),
invalidator=MagicMock(),
search_projection_writer=MagicMock(),
)
payloads = [
# Nested index matching child content_label -> sums to 409
{
"name": "Acupoints",
"content_count": 100,
"content_label": "points",
"link": {"type": "template_ref", "target": {"module_code": "m0001", "template_code": "m0001_ct0002"}},
},
# Template index with differing label -> uses target template row count 9
{
"name": "Spleen",
"content_count": 10,
"content_label": "patterns",
"link": {"type": "template_ref", "target": {"module_code": "m0012", "template_code": "m0012_ct0005"}},
},
# Content ref with points collection -> updates 10 -> 16
{
"name": "Xi Cleft",
"content_count": 10,
"content_label": "points",
"link": {
"type": "content_ref",
"target": {"module_code": "m0001", "template_code": "m0001_ct0011", "content_id": str(xi_cleft_id)},
},
},
# Content ref without collection count (e.g. Meridian) -> preserves authored 10
{
"name": "Lung",
"content_count": 10,
"link": {
"type": "content_ref",
"target": {"module_code": "m0001", "template_code": "m0001_ct0005", "content_id": str(meridian_id)},
},
},
# Item without link -> untouched
{
"name": "Lung Points",
"content_count": 11,
"content_label": "points",
},
]
await service._hydrate_dynamic_content_counts(payloads, preview=False)
assert payloads[0]["content_count"] == 409
assert payloads[1]["content_count"] == 9
assert payloads[2]["content_count"] == 16
assert payloads[3]["content_count"] == 10
assert payloads[4]["content_count"] == 11

View File

@ -1,168 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from fastapi import HTTPException
from app.db.enums import ModuleStatus
from app.features.content.service import ContentService
from app.features.content.errors import ModuleNotFoundError
from app.features.content.schema import (
ModuleRequest,
ContentSearchRequest,
ModuleContentSearchRequest,
)
@pytest.fixture
def mock_repository() -> MagicMock:
return MagicMock()
@pytest.fixture
def mock_session() -> AsyncMock:
return AsyncMock()
@pytest.fixture
def mock_cache() -> MagicMock:
cache = MagicMock()
# By default, pass through loader
async def fake_cached(*args, loader=None, **kwargs):
if loader:
return await loader()
return None
cache.get_or_set = AsyncMock(side_effect=fake_cached)
cache.module_contents = AsyncMock(side_effect=fake_cached)
cache.template_contents = AsyncMock(side_effect=fake_cached)
return cache
@pytest.fixture
def content_service(mock_repository: MagicMock, mock_session: AsyncMock, mock_cache: MagicMock) -> ContentService:
service = ContentService(
session=mock_session,
repository=mock_repository,
cache=mock_cache,
invalidator=MagicMock(),
search_projection_writer=MagicMock(),
)
return service
def create_mock_module(status: ModuleStatus, is_active: bool = False) -> MagicMock:
module = MagicMock()
module.id = uuid4()
module.code = "MOD_TEST"
module.slug = "test-module"
module.name = "Test Module"
module.status = status
module.is_active = is_active
module.category = "clinical"
module.preview_enabled = False
module.preview_item_limit = 0
module.default_template_code = "MOD_TEST_T01"
return module
@pytest.mark.asyncio
async def test_get_module_contents_allows_inactive_module(
content_service: ContentService,
mock_repository: MagicMock,
) -> None:
inactive_module = create_mock_module(status=ModuleStatus.INACTIVE, is_active=False)
mock_repository.resolve_module = AsyncMock(return_value=inactive_module)
mock_repository.get_module_contents = AsyncMock(return_value=[])
req = ModuleRequest(module_code="MOD_TEST")
res = await content_service.get_module_contents(request=req)
mock_repository.resolve_module.assert_awaited_once_with(
session=content_service.session,
module_id=None,
module_code="MOD_TEST",
active_only=False,
)
assert res.module.code == "MOD_TEST"
@pytest.mark.asyncio
async def test_get_module_contents_rejects_archived_module(
content_service: ContentService,
mock_repository: MagicMock,
) -> None:
archived_module = create_mock_module(status=ModuleStatus.ARCHIVED, is_active=False)
mock_repository.resolve_module = AsyncMock(return_value=archived_module)
req = ModuleRequest(module_code="MOD_TEST")
with pytest.raises(HTTPException) as exc_info:
await content_service.get_module_contents(request=req)
assert exc_info.value.status_code == 404
@pytest.mark.asyncio
async def test_get_module_search_contract_allows_inactive_module(
content_service: ContentService,
mock_repository: MagicMock,
) -> None:
inactive_module = create_mock_module(status=ModuleStatus.INACTIVE, is_active=False)
mock_repository.resolve_module = AsyncMock(return_value=inactive_module)
mock_repository.get_module_search_definitions = AsyncMock(return_value=[])
res = await content_service.get_module_search_contract(module_code="MOD_TEST")
mock_repository.resolve_module.assert_awaited_once_with(
session=content_service.session,
module_code="MOD_TEST",
active_only=False,
)
assert res.module_code == "MOD_TEST"
@pytest.mark.asyncio
async def test_search_contents_allows_inactive_module(
content_service: ContentService,
mock_repository: MagicMock,
) -> None:
inactive_module = create_mock_module(status=ModuleStatus.INACTIVE, is_active=False)
mock_repository.resolve_module = AsyncMock(return_value=inactive_module)
mock_def_set = MagicMock()
mock_def_set.id = uuid4()
mock_def_set.code = "MOD_TEST_T01"
mock_repository.resolve_definition_set = AsyncMock(return_value=mock_def_set)
mock_repository.assert_template_has_module_content = AsyncMock()
mock_repository.get_active_presentation = AsyncMock()
mock_repository.load_active_definitions = AsyncMock(return_value=[])
mock_repository.search = AsyncMock(return_value=(0, []))
mock_repository.build_attributes_for_content_ids = AsyncMock(return_value={})
mock_repository.get_content_media_for_content_ids = AsyncMock(return_value={})
content_service._derive_module_code = MagicMock(return_value="MOD_TEST")
req = ContentSearchRequest(module_code="MOD_TEST", template_code="MOD_TEST_T01")
res = await content_service.search_contents(req)
mock_repository.resolve_module.assert_awaited_once_with(
session=content_service.session,
module_id=None,
module_code="MOD_TEST",
active_only=False,
)
assert res.total == 0
assert res.items == []
@pytest.mark.asyncio
async def test_search_contents_rejects_archived_module(
content_service: ContentService,
mock_repository: MagicMock,
) -> None:
archived_module = create_mock_module(status=ModuleStatus.ARCHIVED, is_active=False)
mock_repository.resolve_module = AsyncMock(return_value=archived_module)
req = ContentSearchRequest(module_code="MOD_TEST", template_code="MOD_TEST_T01")
with pytest.raises(ModuleNotFoundError):
await content_service.search_contents(req)

View File

@ -1,114 +0,0 @@
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from app.features.content.repository import ContentRepository, ContentReferenceLookup
from app.features.search.repository import SearchRepository
from app.features.search.schema import SearchScope
class _DummyMappingsResult:
def __init__(self, rows=None):
self._rows = rows or []
def mappings(self):
return self
def all(self):
return self._rows
def __iter__(self):
return iter(self._rows)
def scalar_one(self):
return len(self._rows)
@pytest.mark.asyncio
async def test_search_list_modules_scoped_allows_inactive_modules() -> None:
session = AsyncMock()
session.execute = AsyncMock(return_value=_DummyMappingsResult())
repo = SearchRepository(session)
await repo.list_modules(SearchScope(module_codes=["MOD_INACTIVE"]))
sql_text = str(session.execute.call_args[0][0])
assert "status in ('active', 'inactive')" in sql_text
assert "is_active = true" not in sql_text
@pytest.mark.asyncio
async def test_search_list_modules_unscoped_requires_active() -> None:
session = AsyncMock()
session.execute = AsyncMock(return_value=_DummyMappingsResult())
repo = SearchRepository(session)
await repo.list_modules(SearchScope())
sql_text = str(session.execute.call_args[0][0])
assert "is_active = true" in sql_text
assert "status = 'active'" in sql_text
def test_search_scope_sql_allows_inactive_modules() -> None:
session = AsyncMock()
repo = SearchRepository(session)
params: dict = {}
sql = repo._scope_sql(SearchScope(module_codes=["MOD_INACTIVE"]), params)
assert "scope_m.status in ('active', 'inactive')" in sql
assert "scope_m.is_active = true" not in sql
@pytest.mark.asyncio
async def test_search_scoped_query_allows_inactive_modules() -> None:
session = AsyncMock()
session.execute = AsyncMock(return_value=_DummyMappingsResult())
repo = SearchRepository(session)
await repo.search(
scope=SearchScope(module_codes=["MOD_INACTIVE"]),
query="acupoint",
filters=[],
filter_logic="and",
sort_field="relevance",
sort_direction="desc",
page=1,
page_size=20,
)
executed_sqls = [str(call[0][0]) for call in session.execute.call_args_list]
assert any("m.status in ('active', 'inactive')" in sql for sql in executed_sqls)
assert all("m.is_active = true" not in sql for sql in executed_sqls)
@pytest.mark.asyncio
async def test_content_reference_resolution_allows_inactive_modules() -> None:
session = AsyncMock()
dummy_result = MagicMock()
dummy_result.mappings.return_value = [
{
"content_id": uuid4(),
"module_code": "MOD_INACTIVE",
"template_code": "TPL_1",
"source_key": "ITEM_1",
}
]
session.execute = AsyncMock(return_value=dummy_result)
repo = ContentRepository(session)
await repo.resolve_content_reference_targets(
references={
ContentReferenceLookup(
module_code="MOD_INACTIVE",
template_code="TPL_1",
source_key="ITEM_1",
)
},
include_draft=False,
)
stmt = session.execute.call_args[0][0]
compiled = str(stmt.compile(compile_kwargs={"literal_binds": True}))
assert "inactive" in compiled.lower()
assert "modules.is_active IS true" not in compiled

View File

@ -1,94 +0,0 @@
from uuid import uuid4
from datetime import datetime, timezone
import pytest
from unittest.mock import AsyncMock, MagicMock
from app.db.models import Module
from app.db.enums import ModuleStatus
from app.features.admin.schema import ModuleUpdateRequest, ModuleStatusUpdateRequest
from app.features.admin.services.module_service import (
resolve_module_category,
CATEGORY_UI_DEFAULTS,
AdminModuleService,
)
from app.features.content.schema import ModuleResponse
def test_resolve_module_category_from_explicit_metadata():
assert resolve_module_category({"category": "Points"}) == "Points"
assert resolve_module_category({"category": "point"}) == "Points"
assert resolve_module_category({"category": "Patterns"}) == "Patterns"
assert resolve_module_category({"category": "Nutrition"}) == "Nutrition"
assert resolve_module_category({"category": "Therapeutics"}) == "Therapeutics"
def test_resolve_module_category_from_kind():
assert resolve_module_category({"kind": "point"}) == "Points"
assert resolve_module_category({"kind": "POINTS"}) == "Points"
assert resolve_module_category({"kind": "pattern"}) == "Patterns"
assert resolve_module_category({"kind": "five-elements"}) == "Patterns"
assert resolve_module_category({"kind": "nutrition"}) == "Nutrition"
assert resolve_module_category({"kind": "therapeutic"}) == "Therapeutics"
assert resolve_module_category({"kind": "therapeutics"}) == "Therapeutics"
def test_resolve_module_category_fallback():
assert resolve_module_category(None) == "General"
assert resolve_module_category({}) == "General"
assert resolve_module_category({"category": "General"}) == "General"
assert resolve_module_category({"category": "General", "kind": "point"}) == "Points"
def test_category_ui_defaults():
assert "Points" in CATEGORY_UI_DEFAULTS
assert "Patterns" in CATEGORY_UI_DEFAULTS
assert "Nutrition" in CATEGORY_UI_DEFAULTS
assert "Therapeutics" in CATEGORY_UI_DEFAULTS
assert "General" in CATEGORY_UI_DEFAULTS
def test_module_response_computed_category():
now = datetime.now(timezone.utc)
m = ModuleResponse(
id=uuid4(),
code="m0041",
name="Auriculotherapy",
slug="auriculotherapy",
status=ModuleStatus.ACTIVE,
is_active=True,
preview_enabled=False,
preview_item_limit=0,
metadata={"kind": "therapeutic"},
created_at=now,
updated_at=now,
)
dumped = m.model_dump()
assert dumped["category"] == "Therapeutics"
@pytest.mark.asyncio
async def test_admin_module_service_invalidates_cache_on_update():
mid = uuid4()
mock_module = Module(
id=mid,
code="m0041",
name="Auriculotherapy",
slug="auriculotherapy",
status=ModuleStatus.ACTIVE,
is_active=True,
metadata_json={"kind": "therapeutic", "category": "Therapeutics"},
)
mock_session = AsyncMock()
mock_res = MagicMock()
mock_res.scalar_one_or_none.return_value = mock_module
mock_session.execute.return_value = mock_res
mock_invalidator = AsyncMock()
service = AdminModuleService(mock_session, invalidator=mock_invalidator)
update_payload = ModuleUpdateRequest(category="Points")
await service.update_details(str(mid), update_payload)
assert mock_module.metadata_json["category"] == "Points"
mock_invalidator.invalidate_module_structure_change.assert_awaited_once_with(module_id=mid)

View File

@ -1,220 +0,0 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from sqlalchemy.dialects import postgresql
from app.features.auth.errors import (
InvalidCredentialsError,
UserInactiveError,
UserNotFoundError,
)
from app.features.auth.repository import AuthRepository
from app.features.auth.schema import UserLoginRequest
from app.features.auth.security import (
build_phone_lookup_variants,
hash_password,
matches_login_phone,
)
from app.features.auth.service import AuthService
class TestPhoneMatchingHelpers:
def test_e164_stored_matches_local_number_without_country_code(self) -> None:
assert matches_login_phone("+917796701290", "7796701290") is True
assert matches_login_phone("+917796701290", "07796701290") is True
assert matches_login_phone("+91 7796701290", "7796701290") is True
assert matches_login_phone("+447911123456", "07911123456") is True
assert matches_login_phone("+447911123456", "7911123456") is True
assert matches_login_phone("+12025550123", "2025550123") is True
assert matches_login_phone("+971501234567", "501234567") is True
def test_e164_stored_matches_full_number_with_or_without_plus(self) -> None:
assert matches_login_phone("+917796701290", "+917796701290") is True
assert matches_login_phone("+917796701290", "917796701290") is True
assert matches_login_phone("+917796701290", "+91 7796701290") is True
def test_rejects_partial_suffix_and_wrong_country_code(self) -> None:
assert matches_login_phone("+917796701290", "796701290") is False
assert matches_login_phone("+917796701290", "96701290") is False
assert matches_login_phone("+12025550123", "5550123") is False
assert matches_login_phone("+917796701290", "+17796701290") is False
assert matches_login_phone("+917796701290", "") is False
assert matches_login_phone(None, "7796701290") is False
def test_legacy_local_stored_matches_local_and_with_country_prefix(self) -> None:
assert matches_login_phone("7796701290", "7796701290") is True
assert matches_login_phone("7796701290", "917796701290") is True
def test_build_phone_lookup_variants(self) -> None:
exact, suffixes = build_phone_lookup_variants("07796701290")
assert "07796701290" in exact
assert "+07796701290" in exact
assert "07796701290" in suffixes
assert "7796701290" in suffixes
exact_intl, suffixes_intl = build_phone_lookup_variants("+91 7796701290")
assert "+917796701290" in exact_intl
assert suffixes_intl == ()
class TestAuthServicePhoneLogin:
@staticmethod
def _make_user(
*,
phone_number: str,
password: str,
country: str = "India",
is_active: bool = True,
email: str = "user@acupedia.test",
) -> SimpleNamespace:
return SimpleNamespace(
id=uuid4(),
email=email,
display_name="Test User",
phone_number=phone_number,
country=country,
password_hash=hash_password(password),
is_active=is_active,
)
@staticmethod
def _make_service(candidates: list[SimpleNamespace]) -> AuthService:
session = AsyncMock()
repo = AsyncMock()
repo.find_users_by_phone_candidates = AsyncMock(return_value=candidates)
repo.get_user_roles = AsyncMock(return_value=["practitioner"])
return AuthService(
session=session,
repository=repo,
password_reset_email_sender=MagicMock(),
)
@pytest.mark.asyncio
async def test_login_succeeds_with_local_number_when_e164_is_stored(self) -> None:
user = self._make_user(phone_number="+917796701290", password="ValidPass123!")
service = self._make_service([user])
response = await service.login(
UserLoginRequest(phone_number="7796701290", password="ValidPass123!")
)
assert response.access_token
assert response.user.phone_number == "+917796701290"
@pytest.mark.asyncio
async def test_login_rejects_partial_suffix_candidate(self) -> None:
user = self._make_user(phone_number="+917796701290", password="ValidPass123!")
service = self._make_service([user])
with pytest.raises(UserNotFoundError, match="No account found with this phone number"):
await service.login(
UserLoginRequest(phone_number="796701290", password="ValidPass123!")
)
@pytest.mark.asyncio
async def test_login_wrong_password_raises_invalid_credentials(self) -> None:
user = self._make_user(phone_number="+917796701290", password="ValidPass123!")
service = self._make_service([user])
with pytest.raises(InvalidCredentialsError, match="Incorrect password"):
await service.login(
UserLoginRequest(phone_number="7796701290", password="WrongPassword1!")
)
@pytest.mark.asyncio
async def test_login_inactive_user_raises_inactive_error(self) -> None:
user = self._make_user(
phone_number="+917796701290",
password="ValidPass123!",
is_active=False,
)
service = self._make_service([user])
with pytest.raises(UserInactiveError, match="deactivated"):
await service.login(
UserLoginRequest(phone_number="7796701290", password="ValidPass123!")
)
@pytest.mark.asyncio
async def test_login_disambiguates_cross_country_local_collision_by_password(self) -> None:
us_user = self._make_user(
phone_number="+17796701290",
password="UsPassword123!",
country="United States",
email="us@acupedia.test",
)
in_user = self._make_user(
phone_number="+917796701290",
password="InPassword123!",
country="India",
email="in@acupedia.test",
)
service = self._make_service([us_user, in_user])
response = await service.login(
UserLoginRequest(phone_number="7796701290", password="InPassword123!")
)
assert response.user.id == in_user.id
assert response.user.email == "in@acupedia.test"
@pytest.mark.asyncio
async def test_login_raises_clear_error_when_collision_matches_multiple_passwords(self) -> None:
us_user = self._make_user(
phone_number="+17796701290",
password="SharedPassword123!",
country="United States",
email="us@acupedia.test",
)
in_user = self._make_user(
phone_number="+917796701290",
password="SharedPassword123!",
country="India",
email="in@acupedia.test",
)
service = self._make_service([us_user, in_user])
with pytest.raises(InvalidCredentialsError, match="Multiple accounts share this phone number"):
await service.login(
UserLoginRequest(phone_number="7796701290", password="SharedPassword123!")
)
class TestAuthRepositoryPhoneQuery:
@pytest.mark.asyncio
async def test_find_users_by_phone_candidates_executes_parameterized_query(self) -> None:
captured_stmt = None
expected_user = SimpleNamespace(id=uuid4(), phone_number="+917796701290")
class _ScalarResult:
def all(self):
return [expected_user]
class _ExecuteResult:
def scalars(self):
return _ScalarResult()
async def _execute(stmt):
nonlocal captured_stmt
captured_stmt = stmt
return _ExecuteResult()
session = AsyncMock()
session.execute = AsyncMock(side_effect=_execute)
repo = AuthRepository(session)
result = await repo.find_users_by_phone_candidates(
exact_values=("7796701290", "+7796701290"),
suffix_digits=("7796701290",),
)
assert result == [expected_user]
assert captured_stmt is not None
compiled = str(captured_stmt.compile(dialect=postgresql.dialect()))
assert "LIKE" in compiled
assert "replace(" in compiled

View File

@ -1,108 +0,0 @@
from __future__ import annotations
from decimal import Decimal
from uuid import uuid4
import pytest
from pydantic import ValidationError
from app.features.auth.schema import (
ChangePasswordRequest,
ForgotPasswordRequest,
ResetPasswordRequest,
UserLoginRequest,
UserRegisterRequest,
)
from app.features.cart.schema import CartCalculationRequest
from app.features.admin.schema import AdminCreateSuperAdminRequest, AdminRefundRequest
class TestAuthSchemas:
def test_user_login_request_valid_with_email(self) -> None:
req = UserLoginRequest(email="test@example.com", password="Password123!")
assert req.email == "test@example.com"
assert req.phone_number is None
def test_user_login_request_valid_with_phone(self) -> None:
req = UserLoginRequest(phone_number="+919876543210", password="Password123!")
assert req.phone_number == "+919876543210"
assert req.email is None
def test_user_login_request_fails_without_identity(self) -> None:
with pytest.raises(ValidationError) as exc:
UserLoginRequest(password="Password123!")
assert "Either email or phone number is required" in str(exc.value)
def test_user_login_request_forbids_extra_fields(self) -> None:
with pytest.raises(ValidationError):
UserLoginRequest(email="test@example.com", password="Password123!", extra_field="bad")
def test_user_register_request_requires_email_and_password(self) -> None:
req = UserRegisterRequest(email="user@test.com", password="Password123!")
assert req.email == "user@test.com"
assert req.country is None
with pytest.raises(ValidationError):
UserRegisterRequest(password="Password123!") # Missing email
with pytest.raises(ValidationError):
UserRegisterRequest(email="user@test.com") # Missing password
def test_change_password_request_validation(self) -> None:
req = ChangePasswordRequest(old_password="Old#1234", new_password="New#5678")
assert req.old_password == "Old#1234"
assert req.new_password == "New#5678"
with pytest.raises(ValidationError):
ChangePasswordRequest(old_password="", new_password="New#5678")
def test_reset_password_request_validation(self) -> None:
req = ResetPasswordRequest(email="doc@test.com", otp_code="123456", new_password="New#Password1")
assert req.otp_code == "123456"
with pytest.raises(ValidationError):
ResetPasswordRequest(email="doc@test.com", otp_code="", new_password="New#Password1")
class TestCartSchemas:
def test_cart_calculation_request_valid(self) -> None:
req = CartCalculationRequest(cart_item_codes=["MOD_ACU", "MOD_MOXA"])
assert len(req.cart_item_codes) == 2
assert req.currency == "INR"
assert req.is_first_purchase is True
def test_cart_calculation_request_empty_items_fails(self) -> None:
with pytest.raises(ValidationError):
CartCalculationRequest(cart_item_codes=[])
class TestAdminSchemas:
def test_admin_refund_request_valid(self) -> None:
tx_id = uuid4()
req = AdminRefundRequest(
payment_transaction_id=tx_id,
refund_amount=Decimal("500.00"),
support_ticket_reference="TICKET-1234",
)
assert req.refund_amount == Decimal("500.00")
def test_admin_refund_request_zero_or_negative_amount_fails(self) -> None:
tx_id = uuid4()
with pytest.raises(ValidationError):
AdminRefundRequest(
payment_transaction_id=tx_id,
refund_amount=Decimal("0.00"),
support_ticket_reference="TICKET-1234",
)
with pytest.raises(ValidationError):
AdminRefundRequest(
payment_transaction_id=tx_id,
refund_amount=Decimal("-10.00"),
support_ticket_reference="TICKET-1234",
)
def test_admin_create_super_admin_min_password_length(self) -> None:
with pytest.raises(ValidationError):
AdminCreateSuperAdminRequest(
email="admin@test.com",
password="short", # Less than 8 chars
)

View File

@ -1,207 +0,0 @@
from __future__ import annotations
import time
import pytest
from app.features.auth.errors import InvalidEmailError, InvalidTokenError, WeakPasswordError
from app.features.auth.security import (
base64url_decode,
base64url_encode,
create_access_token,
decode_access_token,
generate_otp_code,
hash_password,
normalize_email,
normalize_phone_number,
validate_password_strength,
verify_password,
)
class TestEmailAndPhoneNormalization:
def test_normalize_valid_email(self) -> None:
assert normalize_email(" USER@Example.COM ") == "user@example.com"
assert normalize_email("john.doe+test@domain.co.in") == "john.doe+test@domain.co.in"
assert normalize_email("sanskar+sarak@gmail.com") == "sanskar+sarak@gmail.com"
def test_normalize_invalid_email_raises(self) -> None:
invalid_emails = [
"",
"plainaddress",
"@missingusername.com",
"username@.com",
"user name@domain.com",
"user@domain",
"sanskar@+gmail+.com",
"sanskar@+gmail.com",
"sanskar@gmail+.com",
"user@domain..com",
"user@-domain.com",
"user@domain-.com",
"user@domain.c",
]
for email in invalid_emails:
with pytest.raises(InvalidEmailError):
normalize_email(email)
def test_normalize_phone_number(self) -> None:
assert normalize_phone_number(" +91 9876543210 ") == "+91 9876543210"
assert normalize_phone_number(None) == ""
assert normalize_phone_number("") == ""
class TestPasswordValidationAndHashing:
def test_password_strength_valid(self) -> None:
# Must pass without raising
validate_password_strength("ValidPassword123!")
validate_password_strength("P@ssw0rd2026")
validate_password_strength("Str0ng#Pass")
def test_password_strength_too_short(self) -> None:
with pytest.raises(WeakPasswordError, match="at least 8 characters"):
validate_password_strength("Short1!")
def test_password_strength_missing_uppercase(self) -> None:
with pytest.raises(WeakPasswordError, match="uppercase"):
validate_password_strength("lowercase123!")
def test_password_strength_missing_digit(self) -> None:
with pytest.raises(WeakPasswordError, match="number"):
validate_password_strength("NoNumbersHere!")
def test_password_strength_missing_special_character(self) -> None:
with pytest.raises(WeakPasswordError, match="special character"):
validate_password_strength("Password12345")
def test_password_strength_space_instead_of_special_char_fails(self) -> None:
with pytest.raises(WeakPasswordError, match="special character"):
validate_password_strength("Password 12345")
def test_password_strength_emoji_instead_of_special_char_fails(self) -> None:
with pytest.raises(WeakPasswordError, match="special character"):
validate_password_strength("Password😀12345")
def test_hash_and_verify_password_lifecycle(self) -> None:
raw_pw = "SuperSecure#2026"
hashed = hash_password(raw_pw)
assert hashed.startswith("$2b$")
assert verify_password(raw_pw, hashed) is True
assert verify_password("WrongPassword123!", hashed) is False
def test_verify_password_with_invalid_hashes(self) -> None:
assert verify_password("Password123!", None) is False
assert verify_password("Password123!", "") is False
assert verify_password("Password123!", "plain_text_not_a_bcrypt_hash") is False
assert verify_password("Password123!", "$pbkdf2-sha256$29000$test") is False
class TestOTPGeneration:
def test_generate_otp_code(self) -> None:
otp = generate_otp_code()
assert len(otp) == 6
assert otp.isdigit()
class TestJWTTokens:
def test_create_and_decode_valid_token(self) -> None:
payload = {
"sub": "123e4567-e89b-12d3-a456-426614174000",
"email": "doctor@acupedia.test",
"roles": ["practitioner"],
}
token = create_access_token(payload)
decoded = decode_access_token(token)
assert decoded["sub"] == payload["sub"]
assert decoded["email"] == payload["email"]
assert decoded["roles"] == ["practitioner"]
assert "exp" in decoded
assert decoded["exp"] > int(time.time())
def test_decode_malformed_token_raises_invalid_token(self) -> None:
with pytest.raises(InvalidTokenError):
decode_access_token("this.isNotAValidToken")
def test_decode_tampered_signature_raises_invalid_token(self) -> None:
token = create_access_token({"sub": "valid-user", "role": "user"})
parts = token.split(".")
# Valid base64url string that fails HMAC comparison
tampered_sig = base64url_encode(b"wrong_hmac_signature_bytes_32_b")
tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}"
with pytest.raises(InvalidTokenError):
decode_access_token(tampered_token)
def test_decode_invalid_header_raises(self) -> None:
import hashlib
import hmac
from app.features.auth.security import JWT_SECRET
bad_header = base64url_encode(b'{"alg":"none","typ":"JWT"}')
payload = base64url_encode(b'{"sub":"user1","exp":9999999999}')
signing_input = f"{bad_header}.{payload}".encode("utf-8")
valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest())
token = f"{bad_header}.{payload}.{valid_sig}"
with pytest.raises(InvalidTokenError):
decode_access_token(token)
def test_decode_malformed_json_in_token_raises(self) -> None:
header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}')
bad_payload = base64url_encode(b'not valid json')
token = f"{header}.{bad_payload}.c2lnbmF0dXJl"
with pytest.raises(InvalidTokenError):
decode_access_token(token)
def test_decode_non_int_exp_raises(self) -> None:
import hashlib
import hmac
from app.features.auth.security import JWT_SECRET
header = base64url_encode(b'{"alg":"HS256","typ":"JWT"}')
payload = base64url_encode(b'{"sub":"user1","exp":"never"}')
signing_input = f"{header}.{payload}".encode("utf-8")
valid_sig = base64url_encode(hmac.new(JWT_SECRET.encode("utf-8"), signing_input, hashlib.sha256).digest())
token = f"{header}.{payload}.{valid_sig}"
with pytest.raises(InvalidTokenError):
decode_access_token(token)
def test_decode_expired_token_raises_invalid_token(self, monkeypatch: pytest.MonkeyPatch) -> None:
# Create token with TTL in the past
monkeypatch.setattr("app.features.auth.security.JWT_TTL_SECONDS", -10)
expired_token = create_access_token({"sub": "user-123"})
with pytest.raises(InvalidTokenError):
decode_access_token(expired_token)
def test_decode_missing_sub_raises_invalid_token(self) -> None:
token = create_access_token({"role": "guest"}) # No 'sub' key
with pytest.raises(InvalidTokenError):
decode_access_token(token)
def test_verify_password_catches_invalid_salt_format(self) -> None:
# Format passes startswith $2b$ but is invalid for bcrypt.checkpw
assert verify_password("pass", "$2b$invalid_format_hash") is False
@pytest.mark.asyncio
async def test_change_password_same_password_raises(self) -> None:
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
from app.features.auth.service import AuthService
from app.features.auth.schema import ChangePasswordRequest
from app.features.auth.errors import SamePasswordError
mock_session = AsyncMock()
mock_repo = AsyncMock()
user = MagicMock()
user.id = uuid4()
user.password_hash = hash_password("ValidPass123!")
mock_repo.get_user_by_id = AsyncMock(return_value=user)
token = create_access_token({"sub": str(user.id)})
service = AuthService(
session=mock_session,
repository=mock_repo,
password_reset_email_sender=MagicMock(),
)
req = ChangePasswordRequest(old_password="ValidPass123!", new_password="ValidPass123!")
with pytest.raises(SamePasswordError, match="cannot be the same"):
await service.change_password(access_token=token, request=req)

192
uv.lock
View File

@ -19,7 +19,6 @@ dependencies = [
{ name = "cryptography" },
{ name = "email-validator" },
{ name = "fastapi" },
{ name = "greenlet" },
{ name = "minio" },
{ name = "passlib", extra = ["bcrypt"] },
{ name = "pillow" },
@ -31,7 +30,7 @@ dependencies = [
{ name = "razorpay" },
{ name = "redis" },
{ name = "requests" },
{ name = "sqlalchemy", extra = ["asyncio"] },
{ name = "sqlalchemy" },
{ name = "uvicorn", extra = ["standard"] },
]
@ -40,8 +39,6 @@ dev = [
{ name = "httpx" },
{ name = "pytest" },
{ name = "pytest-asyncio" },
{ name = "pytest-cov" },
{ name = "pytest-mock" },
{ name = "ruff" },
]
@ -54,7 +51,6 @@ requires-dist = [
{ name = "cryptography", specifier = ">=41.0.0" },
{ name = "email-validator", specifier = ">=2.0.0" },
{ name = "fastapi", specifier = ">=0.100.0" },
{ name = "greenlet", specifier = ">=3.0.0" },
{ name = "httpx", marker = "extra == 'dev'", specifier = ">=0.24.0" },
{ name = "minio", specifier = ">=7.1.0" },
{ name = "passlib", extras = ["bcrypt"], specifier = ">=1.7.4" },
@ -63,8 +59,6 @@ requires-dist = [
{ name = "pydantic-settings", specifier = ">=2.0.0" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0.0" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.21.0" },
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0.0" },
{ name = "pytest-mock", marker = "extra == 'dev'", specifier = ">=3.10.0" },
{ name = "python-dotenv", specifier = ">=1.0.0" },
{ name = "python-jose", extras = ["cryptography"], specifier = ">=3.3.0" },
{ name = "pyyaml", specifier = ">=6.0" },
@ -72,7 +66,7 @@ requires-dist = [
{ name = "redis", specifier = ">=5.0.0" },
{ name = "requests", specifier = ">=2.28.0" },
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" },
{ name = "sqlalchemy", extras = ["asyncio"], specifier = ">=2.0.0" },
{ name = "sqlalchemy", specifier = ">=2.0.0" },
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.20.0" },
]
provides-extras = ["dev"]
@ -634,139 +628,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
[[package]]
name = "coverage"
version = "7.16.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/2f/55/d1eaf3e73781174340a00dc1ba2aee8a65f82fadb18e2797b192b6b3925b/coverage-7.16.2.tar.gz", hash = "sha256:ca64d9f1f384f151b9511bec01126072acd2f313439f8ed015a22d8790aab6fa", size = 971999, upload-time = "2026-09-27T12:29:01.118Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/60/72/db17bf5f87568ab524413693385be2eeb03e652ab56c54ea05fa85515675/coverage-7.16.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:23219888477edd736b6fcaec1272d47d93b926e999641ffea7e53a1738e70b2b", size = 223670, upload-time = "2026-09-27T12:25:34.675Z" },
{ url = "https://files.pythonhosted.org/packages/d1/e1/285727a8a74d48de256e8605413ee4cf82301228253ea58e5ab4270138b0/coverage-7.16.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:40c0f00899fe6181ae7f434ceb200e51f5ee4b8ed10e3b5f0b605f0cae15da87", size = 224191, upload-time = "2026-09-27T12:25:36.476Z" },
{ url = "https://files.pythonhosted.org/packages/50/c7/c737b73bac9bf5034f5ff45a4237b7a189d417a4e36751faf5d10c082cbe/coverage-7.16.2-cp310-cp310-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:a4624f80732f6b427ac58f1f59c577a0994a12e8174b5af6a027b4b58795d4c3", size = 250921, upload-time = "2026-09-27T12:25:37.857Z" },
{ url = "https://files.pythonhosted.org/packages/29/4e/e1d38d27817d91776ca543d01276a67eace3df675a673cac32b12c167d58/coverage-7.16.2-cp310-cp310-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:191803c4996b499fcd78c2ad5e5f767dcc53cb4dc6de6d6a741b443a1821ef02", size = 252751, upload-time = "2026-09-27T12:25:39.291Z" },
{ url = "https://files.pythonhosted.org/packages/0e/19/14a8e44cbb2ad36ae62aaa03c5eec4a06a7f7df220ea3776af26927acbe2/coverage-7.16.2-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9fd670ac43b709c575aefc25bf52d8a598a3bc5017bddfd0a179152ab06a2deb", size = 254616, upload-time = "2026-09-27T12:25:40.506Z" },
{ url = "https://files.pythonhosted.org/packages/f9/72/f5bcad0d9a9b450080032344fbff7ec60c1b0e3d38019f7735dee2b69645/coverage-7.16.2-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:705e5af11d34647efdc170c7840b6857c81cf74be96419a553f237e68e62cb72", size = 256541, upload-time = "2026-09-27T12:25:41.785Z" },
{ url = "https://files.pythonhosted.org/packages/ae/9a/8c735234e8abb52bf5d063f98c780fa942e77c4c0225f9fcb9b33effc346/coverage-7.16.2-cp310-cp310-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8afd9bf35cc6a1f22eb3634808fa8e0b91902459c5721ef2e4461dfe771d7f08", size = 251589, upload-time = "2026-09-27T12:25:43.269Z" },
{ url = "https://files.pythonhosted.org/packages/35/6a/1bf6d32e55642d6972aa842640e0a8850e612d19ac7d05e2c32fa59dfd34/coverage-7.16.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:3f43bac1856ba269b905302778d4df433d6006489a192174ad77ac528e395032", size = 252660, upload-time = "2026-09-27T12:25:45.051Z" },
{ url = "https://files.pythonhosted.org/packages/53/5b/05b1c0d0e9495cb056155a16066259adc1e935e7411a82a62779bf729975/coverage-7.16.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:f8475460aa33ee28ac896ab1156d0bb3b6c639f7f8383c2677d3359eb35f8205", size = 250660, upload-time = "2026-09-27T12:25:46.51Z" },
{ url = "https://files.pythonhosted.org/packages/05/33/5bc3db57fc9c56b4ef055725c38c34faa818a27d17d65e251371f7f0e3a0/coverage-7.16.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:d6276d78f6fca7d0ac066d5da4165c5acd07829e8305c2cb900b738fb3a75a72", size = 254479, upload-time = "2026-09-27T12:25:47.819Z" },
{ url = "https://files.pythonhosted.org/packages/f6/0f/4a5de66daef26eb919213f63b84f45d5065ab2df94cd767fc7c1174ac5e2/coverage-7.16.2-cp310-cp310-musllinux_1_2_riscv64.whl", hash = "sha256:736fde09ea39646d11f8e3b76bd3425c075aa4dd45f24891970bb77c14ff20f5", size = 250940, upload-time = "2026-09-27T12:25:49.227Z" },
{ url = "https://files.pythonhosted.org/packages/57/d3/84cd6a11e707e422194739e9734d947746efa5e5b3358ff2d601f823ee45/coverage-7.16.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c85d54e7e8a2ca932fe8399301af9b8d5907ea2a455ffaff6e7d1208db83b943", size = 251543, upload-time = "2026-09-27T12:25:50.554Z" },
{ url = "https://files.pythonhosted.org/packages/ab/bc/3d84c2e2a95f38e346ce3730d9f0e53114f4e8aace72e6e51e014afb9992/coverage-7.16.2-cp310-cp310-win32.whl", hash = "sha256:5139009b5efd2194fc168ee9362f0e191ba612ef5d29242f9269c22f9b8f80c7", size = 225732, upload-time = "2026-09-27T12:25:51.945Z" },
{ url = "https://files.pythonhosted.org/packages/07/86/31f1f3170571a345ab9d8361a7b2f8e0c5698173fbecd1f7149b6e2089ee/coverage-7.16.2-cp310-cp310-win_amd64.whl", hash = "sha256:c3305c38a2fa21a4254f2ace7dd9ef5fc569c9a558b66e7017650b3d637fb95e", size = 226357, upload-time = "2026-09-27T12:25:53.272Z" },
{ url = "https://files.pythonhosted.org/packages/58/fa/ce3baf63d85b730398d92a7162f486f3a5e4e2cc3382a02488b3943725ba/coverage-7.16.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:732d950e51f3ba4fb6209c73250f3e8924fefca42953ee04a9e65d8c02414d7d", size = 223797, upload-time = "2026-09-27T12:25:54.756Z" },
{ url = "https://files.pythonhosted.org/packages/7a/57/9ba29c2aac7f756d479f03d45762120060f0f988788001001bf36e0e6fca/coverage-7.16.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:5dca0bb66b4c3d624ba047887bf70270030c150692d543cb501293dc38a9f4b5", size = 224303, upload-time = "2026-09-27T12:25:56.214Z" },
{ url = "https://files.pythonhosted.org/packages/5d/7b/0d6d60906dca7d28cc1e3fce12a9861801c4fbb6cbf220ad78cd059c9467/coverage-7.16.2-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:af2a2a8c7c74de0559e0c368d94c8def9e16c58faaee33a0bf081057c4227e3b", size = 254715, upload-time = "2026-09-27T12:25:57.755Z" },
{ url = "https://files.pythonhosted.org/packages/cd/b8/9198b865679379fb165c689c64f6e11105ef380f6bd1c7673e83f73d9f5c/coverage-7.16.2-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:db5f8394e17f877a625b257f2ba0ce8e728a499c2c1579ad66220272cd3df510", size = 256627, upload-time = "2026-09-27T12:25:59.131Z" },
{ url = "https://files.pythonhosted.org/packages/98/79/9521462cb6072fe394701bc8974b74afd576c9c9355156c7844e1a86a42b/coverage-7.16.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b3146d2317c75f70df2509066d979dadd941f7021cdf9b5db4bcd8568258e25", size = 258724, upload-time = "2026-09-27T12:26:00.691Z" },
{ url = "https://files.pythonhosted.org/packages/a6/76/8d7d5d633db9fe0f3182fedc731bf09f9bcf2366055735152504ad614677/coverage-7.16.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e1d0ced76318bab499693ff25f64faa343415187cb2e4d7befdfdd391a1cf6a", size = 260692, upload-time = "2026-09-27T12:26:02.083Z" },
{ url = "https://files.pythonhosted.org/packages/4e/a7/76cb09c89ba46d74d37428bf93251fc14fb0bbe9e05cc2a5ef61773d318a/coverage-7.16.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:af98ad5ed9d6daaca956201e00bb429a7eb2b080426686f70a20353e0f9839f5", size = 254800, upload-time = "2026-09-27T12:26:03.369Z" },
{ url = "https://files.pythonhosted.org/packages/72/b6/2351c1979aaeb5b4a8091a75b90ca997ad60de36e181ddba267cf61dac97/coverage-7.16.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d56e4d21c56d2046447733f8b118409597db48c01efe898ee9ac24e858ec2d6", size = 256423, upload-time = "2026-09-27T12:26:04.751Z" },
{ url = "https://files.pythonhosted.org/packages/0f/f4/ad9a4f8b5cb2d494fa9452b546fe742ed2f9d3847cc14c05e36279a3e649/coverage-7.16.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1d5d0e3b660506fb84f995814e3118a21efdc0c8eb80127da1be627d90093c17", size = 254487, upload-time = "2026-09-27T12:26:06.082Z" },
{ url = "https://files.pythonhosted.org/packages/6c/1f/a520470472f3e8b01169bf42162b1470c9ba992230432f62ca36269bf3a0/coverage-7.16.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:17228fbca0f22976f797be94e975dcd237799c657d49551c7de1e0654d1202e9", size = 258259, upload-time = "2026-09-27T12:26:07.513Z" },
{ url = "https://files.pythonhosted.org/packages/09/d2/ff26d5938274745855fa61cfcba0245c88ccc10d98d2cbd96064f16cd5a7/coverage-7.16.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:bc0b0ac781d489304b741269857f1f8338b7a26b1b89c06c0344658001ec0035", size = 254216, upload-time = "2026-09-27T12:26:08.982Z" },
{ url = "https://files.pythonhosted.org/packages/a4/1d/5d832d3b06785d9f53267e4f2724a9f60c312eee6ebed9063a461d0d3b45/coverage-7.16.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bf1bd822ec4e387ed245bed0d71151582cf7be9e5309bc4145eefe36083d5878", size = 255125, upload-time = "2026-09-27T12:26:10.35Z" },
{ url = "https://files.pythonhosted.org/packages/55/4d/1d33edbc2fcf7d99e384e393e712aa5a2ebbbd8409825357815982207976/coverage-7.16.2-cp311-cp311-win32.whl", hash = "sha256:7ed238d227e23cc300c3d464babdaf9f6ddc740aa1b15a77ae96136e6a7c4516", size = 225898, upload-time = "2026-09-27T12:26:11.7Z" },
{ url = "https://files.pythonhosted.org/packages/6f/7c/676df4882118756c4f8f560c954eddb93e166d84dda8c5f0b6a829689bde/coverage-7.16.2-cp311-cp311-win_amd64.whl", hash = "sha256:a90700f743e29aa3d75a6ff5f01953176a889c00e526194bc4d281731b88d99d", size = 226369, upload-time = "2026-09-27T12:26:13.375Z" },
{ url = "https://files.pythonhosted.org/packages/7a/0e/a457f4a461b3c5610d845137fdd45fa465e011a64c25af440518ab1f4e41/coverage-7.16.2-cp311-cp311-win_arm64.whl", hash = "sha256:a336eec40e3520d369b8a6cdabb4f596e69a8b42927ca074aa1452fed943238a", size = 226344, upload-time = "2026-09-27T12:26:15.127Z" },
{ url = "https://files.pythonhosted.org/packages/5e/2c/f8296c63c5d542f3d21aed685e56b7031a419037d155bb3382fc0940d249/coverage-7.16.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:218d742afca2b5ad5ca759e93eddedfbcc6eadf8322f080dcefc40b7bd4e2d48", size = 223969, upload-time = "2026-09-27T12:26:16.753Z" },
{ url = "https://files.pythonhosted.org/packages/90/23/6f3dcb1423a0d43216e402ea1746e4a7c7c44f38896b97dd573790f56a40/coverage-7.16.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a9a638be322a8d76a41cdb17781c7f82aaee6a66493d8ffb7e2c09ee22423d99", size = 224328, upload-time = "2026-09-27T12:26:18.15Z" },
{ url = "https://files.pythonhosted.org/packages/ac/7d/8f3b6dc920e3fc6732f7678785a2091db439f186afbec30dbf2214d9b1f7/coverage-7.16.2-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:724bd0f1e81856b35e59fc98cf7b4e544a3cb662e4e0864dca73d4326ee9d808", size = 255832, upload-time = "2026-09-27T12:26:19.799Z" },
{ url = "https://files.pythonhosted.org/packages/d1/36/6c45f15be4eca4ac1062c6a55a323286494c99726a7e58951fe85967ac08/coverage-7.16.2-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5375ebd99038021b35e99dc88255022912c06565d316212f4a576e4b08d30f5d", size = 258571, upload-time = "2026-09-27T12:26:21.199Z" },
{ url = "https://files.pythonhosted.org/packages/34/fb/b54cbeba3ad89082c2e441278681859e538322cc34b84b2af7ebff00080f/coverage-7.16.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a076277ca9f5750cc230f0f578ebd2620cec60255b25707361699fef6fb465c", size = 259680, upload-time = "2026-09-27T12:26:22.822Z" },
{ url = "https://files.pythonhosted.org/packages/6e/a2/0dc65ec3d61930e1e4c2e371763b15eb4290896eb343a12d5d3091308116/coverage-7.16.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:58d4a54c6ea672afef66d49be922a2c69826c5ae1a42a9cd94f0c9c2bacdf800", size = 261945, upload-time = "2026-09-27T12:26:24.336Z" },
{ url = "https://files.pythonhosted.org/packages/d6/93/5fad7a61f2c14e08e98946fc31c1c7ffc1195061bf3fdc351db3be77a863/coverage-7.16.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0dcbcfcc059117284c603ff8cb61a65872512882f84a8cf0339241f7f7c2f148", size = 256191, upload-time = "2026-09-27T12:26:25.89Z" },
{ url = "https://files.pythonhosted.org/packages/2d/47/74e5de9227b939ece9f64e729645ddc4296bea10dbfa98721c1333c8be2e/coverage-7.16.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:afdf43b72ef3876c1fe66423b91466e37877c9e81e8cec70542b7e8525b9d1b7", size = 257610, upload-time = "2026-09-27T12:26:27.35Z" },
{ url = "https://files.pythonhosted.org/packages/13/fe/2cf28d40b43645d1b72388fe3ee7f7c747533a6a9557bb8c24a7ae74fe1a/coverage-7.16.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9acc7f7ec4a1b5f89bd929fde5b8a714f6fafdc6cc18725413d510aa082b47ad", size = 255757, upload-time = "2026-09-27T12:26:28.949Z" },
{ url = "https://files.pythonhosted.org/packages/d7/3d/7c149fd99fc8bbc39c80db5e688d1d39fd040be2ecb78b8335a51a55b9c0/coverage-7.16.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:80d3f7b48d43ee8fc5e8707a8adb43d743a5a1a85256c25a24f9d6d0e2238fa6", size = 259822, upload-time = "2026-09-27T12:26:30.515Z" },
{ url = "https://files.pythonhosted.org/packages/e6/3f/b283fce09d5995e227bd8e513358dd7471bedc0f78abc85a925ebdb0a2f6/coverage-7.16.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:126d1af8804d7224421fe991ff65d3ce649081560df7a98b1a5ffff07f9923bd", size = 255325, upload-time = "2026-09-27T12:26:32.037Z" },
{ url = "https://files.pythonhosted.org/packages/bf/91/f3325edf0c4223fb1fe1532b8dbef2a1d2f729459a9a7d1a44d073bae534/coverage-7.16.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c19cd6d025c1673f22afcd22c7df8a662d779e05d8e3fa6820c22afb895b0206", size = 257191, upload-time = "2026-09-27T12:26:33.525Z" },
{ url = "https://files.pythonhosted.org/packages/c4/89/21eb5e83ecf2eed523c4eb3d65ae513cd082c8fd1b6deb34c4cb6c332f97/coverage-7.16.2-cp312-cp312-win32.whl", hash = "sha256:152877cdc8a07264882cfcd503ba56a3ef6cba56a70e8c70f6eb8ffd7384789a", size = 226034, upload-time = "2026-09-27T12:26:35.021Z" },
{ url = "https://files.pythonhosted.org/packages/db/de/e3ad6d864c0833624b4f1f9b53f9e58e116c945e5e965c3f1e172c5e84cd/coverage-7.16.2-cp312-cp312-win_amd64.whl", hash = "sha256:e6c52d3307824ff93b39efd99e4185d557db40bd841452abfb32e5d9151ca162", size = 226569, upload-time = "2026-09-27T12:26:36.604Z" },
{ url = "https://files.pythonhosted.org/packages/3e/c1/bccc58ebe5489cc70628f635c1932fd371f5d7da850dbcf960f95f4c4afc/coverage-7.16.2-cp312-cp312-win_arm64.whl", hash = "sha256:a678c0b6b22086ec2427359d22e37445d4a792f5fdbbc744112c7dade65cad02", size = 226372, upload-time = "2026-09-27T12:26:38.406Z" },
{ url = "https://files.pythonhosted.org/packages/f0/f6/8eb4f220ef24f84fb27d852d4f9bf83e0c73ec1a4a08dd9a87e3f4529739/coverage-7.16.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1a37c6e478cf687e1aa30a593d19c92c02fad9d122b51ab73f51b8dc7a0c0fc9", size = 223993, upload-time = "2026-09-27T12:26:40.164Z" },
{ url = "https://files.pythonhosted.org/packages/40/23/d4bbaf0c154e0b0c2b5264890dbf6ef098dcb50ec8f2469be9490d191660/coverage-7.16.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0993d0e90858c03943d3cb152e068a20dd4707924deec84dd2230261baae3b1b", size = 224368, upload-time = "2026-09-27T12:26:41.762Z" },
{ url = "https://files.pythonhosted.org/packages/7f/48/fc1e88fd571ec5cb38150b7f89f7696ca1bdf9920e01432febb69774cc85/coverage-7.16.2-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:bb2fc905bbf4e6b7f40806ea79e31515abf6349594cdf0adf27c4215f0463204", size = 255358, upload-time = "2026-09-27T12:26:43.442Z" },
{ url = "https://files.pythonhosted.org/packages/1d/56/6785397d07c29c8e70fbb9a07e97d062b43c21ffc5f12385917847f09f63/coverage-7.16.2-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4358b9c8c0125b460407f3017c6cce8156e904b32772c5630d27112f52bdbfe5", size = 257955, upload-time = "2026-09-27T12:26:45.725Z" },
{ url = "https://files.pythonhosted.org/packages/27/3b/c8cdd07721e5f99abd81cea970d971997f99bf158c0b85f51bd284179c8b/coverage-7.16.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1f15254427c9b33eedac4f198eaf9e356eb4f6214551afb43da6194a2c088ad7", size = 259183, upload-time = "2026-09-27T12:26:47.208Z" },
{ url = "https://files.pythonhosted.org/packages/9b/11/606b192fe43d32574ec6238549d48de588fdcc18485682a5ec0a8ac357f2/coverage-7.16.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9a75a4704ff640e46170042eec1f984385a121227c505d5a16ad8e495f452541", size = 261325, upload-time = "2026-09-27T12:26:49.084Z" },
{ url = "https://files.pythonhosted.org/packages/67/90/eea481f8b0305ceeb33f081a5f47e298391dbd1b589de0c4b3b3aa50d3f2/coverage-7.16.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:14253fc7bb15749b849795a06f5d3b6d8bc3fb8a4b5ddc341faf7a89dce205fc", size = 255531, upload-time = "2026-09-27T12:26:50.509Z" },
{ url = "https://files.pythonhosted.org/packages/6b/be/dedbf9aea1457b120c27ac10b8fc2a357f37fa2b54c3e7286d42980a0a2a/coverage-7.16.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:921415102a90637fcc2e3f169f61dad7699ecf690e8639fc21b813acbedc0967", size = 257329, upload-time = "2026-09-27T12:26:52.005Z" },
{ url = "https://files.pythonhosted.org/packages/fa/cb/b25c19d5bb2bd0f2e4e27fe8e2ffcae80c7a91ae181c0dc749ed60e9b1a4/coverage-7.16.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:cce2bc991293f15cc4084ca116827b5900c5f34e1a54dfe83f10ab5c43162eb7", size = 255294, upload-time = "2026-09-27T12:26:53.634Z" },
{ url = "https://files.pythonhosted.org/packages/5f/a2/892c5c5f4ad44b7b2ca009aee705191f3f268f15052244f2f9e3539b2e35/coverage-7.16.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:e1fa594c887365b69745f25a416806e61085dd07b94c9eae68a6e20730629b23", size = 259444, upload-time = "2026-09-27T12:26:55.243Z" },
{ url = "https://files.pythonhosted.org/packages/ed/99/a562537deba0a3e370182ae71c149be796c39d8087365f17a09188f27145/coverage-7.16.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:11e597173af1dc33d5f8a7332ada544199269a223af1ee1770ddd5e245ad0fe8", size = 255111, upload-time = "2026-09-27T12:26:56.851Z" },
{ url = "https://files.pythonhosted.org/packages/2d/20/854ec68641a9b3362ff068a32dfa41637299761617ef253791dbade6fc76/coverage-7.16.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3e7f99698ba3a7d13988bdd984b7ebf13af4dbe2166dc8502eef90d77603b0a4", size = 256882, upload-time = "2026-09-27T12:26:58.41Z" },
{ url = "https://files.pythonhosted.org/packages/db/0d/748e4518b0ac0f9ff2687c248a6e5f8c0737306e709372632a2556f84443/coverage-7.16.2-cp313-cp313-win32.whl", hash = "sha256:f80bd9f9633eafc73d0a913ba2645c96ba58bba1befc30590f7c0fbfde59d865", size = 226045, upload-time = "2026-09-27T12:26:59.983Z" },
{ url = "https://files.pythonhosted.org/packages/31/fa/6e46edba66a183fe4d99d4bb52c173287e9b8dddabe0888d24cb8210e580/coverage-7.16.2-cp313-cp313-win_amd64.whl", hash = "sha256:8be099e979fc42559328a21828281b4578304191ae46ed4e80a407048a82eee6", size = 226581, upload-time = "2026-09-27T12:27:01.494Z" },
{ url = "https://files.pythonhosted.org/packages/1b/d9/9ef6845367600b336ff75d000444a0d32497d6972c833141bd39356abf68/coverage-7.16.2-cp313-cp313-win_arm64.whl", hash = "sha256:28ff850182a67d117990fa2ce5ea1032836d8c9630dae867e8bdd3bff4533b79", size = 226409, upload-time = "2026-09-27T12:27:03.116Z" },
{ url = "https://files.pythonhosted.org/packages/59/4c/577fc0803dab4155dcf808faffbdd7b159256781c0874a8586e17b81b149/coverage-7.16.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4ee546b9e4872ffa194bf07ac87bfa1202ebb824d0795dc1ef22f175545ca90a", size = 224138, upload-time = "2026-09-27T12:27:05.141Z" },
{ url = "https://files.pythonhosted.org/packages/75/9e/e3785ba3ecba2bd11efc74bfe2801ca4b78c4480b15a375648d809a59da3/coverage-7.16.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a2fac6895eb299a2e52d7bbb8fb3903502b9da8d3f5309ceb16ec40c646b58ee", size = 224445, upload-time = "2026-09-27T12:27:06.805Z" },
{ url = "https://files.pythonhosted.org/packages/f0/d0/963ff22d3fd27117da3b8cc442f5bdc91196f783321e1a8ff0ec43476772/coverage-7.16.2-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:57ff3783f99d75a1e81dd56a9737eb5665e6736a5d93258ba596b6dcad8fd05b", size = 256112, upload-time = "2026-09-27T12:27:08.43Z" },
{ url = "https://files.pythonhosted.org/packages/a8/d4/a306940c81c6ae759e82fff27d20b7fdc6896e422b821f51313cce212b6c/coverage-7.16.2-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:35f37886699cb9abd29958247d718628d5bc6f39e623dff66a09e546c42a7e03", size = 258727, upload-time = "2026-09-27T12:27:09.927Z" },
{ url = "https://files.pythonhosted.org/packages/b9/a3/d3d99d93b02517087aa05bc0cf2d04d372956b849e5443e059079901429b/coverage-7.16.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0fd7a86fdda7cb6d616d178654bd0ad6bc0f3f33c2e478aa598500a1a9e34eda", size = 259909, upload-time = "2026-09-27T12:27:11.55Z" },
{ url = "https://files.pythonhosted.org/packages/08/44/39dd599181726758dd185ae4dc0c0ab3aeabf7ca70e68e145060feeaaa16/coverage-7.16.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ac0f3b379c94acc2f7dce5f5f0b24d44fa1cc6a509717ef83dfee07450c2117c", size = 262481, upload-time = "2026-09-27T12:27:13.17Z" },
{ url = "https://files.pythonhosted.org/packages/99/e8/91ee43f6ded411460c359d7e1aebde4d6fd8f00a2e5394182d9d212eb23c/coverage-7.16.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7d0732c83746bc24123c581a85d9dd96b70ddb538c9076020aa1a041790361e9", size = 256012, upload-time = "2026-09-27T12:27:14.91Z" },
{ url = "https://files.pythonhosted.org/packages/11/8c/e9499ddc33197bd7eabcb1118ca81756fc874457b324e2b479a4804b2ad2/coverage-7.16.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7b451c68218c150f616bc9649783ec8de76a59792c759b43aa0c9c0466a465e4", size = 257898, upload-time = "2026-09-27T12:27:16.588Z" },
{ url = "https://files.pythonhosted.org/packages/5f/6e/c081cb5991a0afba99f9c4ad6c74a5fce9513a38ddc64e3e6680c6fed9af/coverage-7.16.2-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:a56ac4fa5a75c7e182e8f62600cfb4aff43c5ed7356a034f3557659c3bec1d90", size = 255938, upload-time = "2026-09-27T12:27:18.19Z" },
{ url = "https://files.pythonhosted.org/packages/b2/42/1c3d819e8f9b6eb01c2fe90874d67a8882adb9507e0bbb09361ed131ea89/coverage-7.16.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:4cc4f73aa3fabc36e32046d6cd2971405948d8a903636508a3d3b2f9128b3a95", size = 260368, upload-time = "2026-09-27T12:27:19.903Z" },
{ url = "https://files.pythonhosted.org/packages/19/4f/d70eac07901fd587b6ab05e659b52afe13959992aa5113bf6cce059cc572/coverage-7.16.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:723dcdab91357159b722935b500ee8abc0a66c8c432e1e9fabf4cc7598952de8", size = 255620, upload-time = "2026-09-27T12:27:21.621Z" },
{ url = "https://files.pythonhosted.org/packages/34/5e/6d87af88317d3d9a9b18a9ca1bc1673eb516917f296e579d0d4a55cb3490/coverage-7.16.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5397e21a90dde0e9c6896b77ded8f0be26b66f8b22b33aed41f6043ed95d55e6", size = 257521, upload-time = "2026-09-27T12:27:23.358Z" },
{ url = "https://files.pythonhosted.org/packages/79/bb/90c2641170d2fa1a6757b3f8450ba2740197317b0ddd749e9604b914e886/coverage-7.16.2-cp314-cp314-win32.whl", hash = "sha256:848893e1d361448c113dc2f0913503522a6f7be231d0e38333d2a22d9698a011", size = 226248, upload-time = "2026-09-27T12:27:25.153Z" },
{ url = "https://files.pythonhosted.org/packages/30/08/d8d0478bb02c8eb0ae20a496fc80c40fcf4d3450bd184300d682ba2d28a6/coverage-7.16.2-cp314-cp314-win_amd64.whl", hash = "sha256:5a27b731c171e43dc8b5f32b76a5051dde2ec9b9366c87028f08a7088ebc2c7b", size = 226732, upload-time = "2026-09-27T12:27:26.907Z" },
{ url = "https://files.pythonhosted.org/packages/32/3f/0001da22155b0a8ce063ec0f7e64ecbe17b373f306e7a74435f6d6accb72/coverage-7.16.2-cp314-cp314-win_arm64.whl", hash = "sha256:1c569a9fd25505f1cd6bea90588818f90373ce90e2632e2cacf19ddbd6e14fdb", size = 226645, upload-time = "2026-09-27T12:27:28.588Z" },
{ url = "https://files.pythonhosted.org/packages/d7/85/6d8813aff9b8b8586691a9d33c43c5604f7227622574da7cdc3d91a86861/coverage-7.16.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d93db87adb6b1c1b408dce4763314b55d76a9f589e96783a84ac9e7689e48bdf", size = 224871, upload-time = "2026-09-27T12:27:30.32Z" },
{ url = "https://files.pythonhosted.org/packages/5c/70/444f3a4981ac2cda40fdcf4cc9b56a4e1a33c222abeb33e51ed3e3eb2a6b/coverage-7.16.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:aa62c85046473959c13ba9edca9dc90a77d5c1095b1ba313556314d77fe5b036", size = 225123, upload-time = "2026-09-27T12:27:32.33Z" },
{ url = "https://files.pythonhosted.org/packages/d0/c1/980681cd7b33eb66ac835044116ef0a92e11fcc7bdd866cc89d10b1130b9/coverage-7.16.2-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:db76506aa5416081f3e8974ae0f7965c58ada0bb0ef7339ac86099588dbb20d3", size = 265049, upload-time = "2026-09-27T12:27:34.085Z" },
{ url = "https://files.pythonhosted.org/packages/b2/e3/87679875c33bb2191f0f05544a1cc9adcc940fe0c35443a10f2df753dde5/coverage-7.16.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a0f2285329dac10ab08f79cb11f5692c497018e6c7c511f95e6fd63a70b8f831", size = 267717, upload-time = "2026-09-27T12:27:36.025Z" },
{ url = "https://files.pythonhosted.org/packages/76/64/5d372776d6eb523d4e93bafba2253f96984e3b18261c4cc56a50863c6d0d/coverage-7.16.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:382d3346d56b0eec1b793d53a4c88799c8053f516aa3a8d7c44315696954bacf", size = 270047, upload-time = "2026-09-27T12:27:37.96Z" },
{ url = "https://files.pythonhosted.org/packages/be/c1/44082ff0cbf9f97d0043f57970a71204097ec7ba606361a9fd2065393669/coverage-7.16.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:648352b94507179d82637292e7ae8802508d95f78e2f00a705a50b6c48011681", size = 271360, upload-time = "2026-09-27T12:27:39.766Z" },
{ url = "https://files.pythonhosted.org/packages/b8/17/9a215efe25b5e0ecc87c89dbe525c4a87d14d87c8c0c7316ef140a5f6f3e/coverage-7.16.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fb2bde05838fffae1a1bf75e5d411a6cac3e4e9bb97e6640fed8cd47888b33f0", size = 264736, upload-time = "2026-09-27T12:27:42.072Z" },
{ url = "https://files.pythonhosted.org/packages/a2/da/7f0a31af8e448107d4d32844bd684757f51ea907bc0c68c8fd537b2123ff/coverage-7.16.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:6a75180829efb8ae62b4aded25be6ddca1c888d138d2d82e21d93bfbd88f41cb", size = 267600, upload-time = "2026-09-27T12:27:43.85Z" },
{ url = "https://files.pythonhosted.org/packages/dd/a4/3bfecbd3366b775bacdcb3330394d356cf384b5d8f5b2146ac4b14b252b5/coverage-7.16.2-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:99704f73721e23859112072d522076e11c31744fc96b5652e5dd2018aa4359f7", size = 264767, upload-time = "2026-09-27T12:27:45.768Z" },
{ url = "https://files.pythonhosted.org/packages/b8/3f/5d62163732d87e4a0c4710a0eab30f0fd6a2d480112abe2029f014fe8c9d/coverage-7.16.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:29309ccc86b7f33df7db12813c299f215bbbc470ed6292d0bedd63ffae1ebf64", size = 269026, upload-time = "2026-09-27T12:27:47.787Z" },
{ url = "https://files.pythonhosted.org/packages/49/4d/8e4579f225426535085a9be371cc75e3b026d058d679b80affbdfb4c3ef0/coverage-7.16.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:30c1b65d529e46569899fadca59e4a87c1faf2886923f1307ba61e654d4f3c20", size = 264147, upload-time = "2026-09-27T12:27:49.681Z" },
{ url = "https://files.pythonhosted.org/packages/d1/36/ef1f77e2c3f7bb03c2b13b9a2006f88700fdd75535ef158d70049f425c1c/coverage-7.16.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:dcf4bc2aab4e16b1c4c0c2005918f23a7dd5d7821ddae82caed9e3342dc2fcce", size = 266376, upload-time = "2026-09-27T12:27:51.551Z" },
{ url = "https://files.pythonhosted.org/packages/be/79/0cb2bf4428830dec971c718c2c841a039c084415c99e67281f5a72841aab/coverage-7.16.2-cp314-cp314t-win32.whl", hash = "sha256:a9cd3de0a5bfe7b0e21ee10e1a14e3d61bf52efc88217ab1d95d6ace6970bd46", size = 226585, upload-time = "2026-09-27T12:27:53.945Z" },
{ url = "https://files.pythonhosted.org/packages/3c/f9/da17121c16667fd84998e972200ae226a41540f6ea4795776c6d99e8976f/coverage-7.16.2-cp314-cp314t-win_amd64.whl", hash = "sha256:611a44e5229a59d7483ce830160e1a0e85f700562c7a5651c7c63fb8f4eb528c", size = 227378, upload-time = "2026-09-27T12:27:55.778Z" },
{ url = "https://files.pythonhosted.org/packages/74/89/01179c62d1b7e6e33bd5001566b02d7f778cf33d3ec1e81e94ca170c517f/coverage-7.16.2-cp314-cp314t-win_arm64.whl", hash = "sha256:22957cef43ce038641de78ba995de7568d2d6a37c6ddbf7fa0fd7d1ae2344d91", size = 227064, upload-time = "2026-09-27T12:27:57.496Z" },
{ url = "https://files.pythonhosted.org/packages/4c/57/52935003c3f627ba6e5203d7179aad32448c10899663a30336aba8e81a2c/coverage-7.16.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:414c26dfdb96aac2d570a54e03008f001e32eb2d413705365503648c6bd361d8", size = 224140, upload-time = "2026-09-27T12:27:59.343Z" },
{ url = "https://files.pythonhosted.org/packages/31/38/df472520f3e626524d7e2fc9d6da0afe7895a2f1489d36b48af8ca40bb41/coverage-7.16.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00d3eb96e9988c45f50cccd1f1496571ac5c1f91386ac02c4d55516eeda19a24", size = 224449, upload-time = "2026-09-27T12:28:01.299Z" },
{ url = "https://files.pythonhosted.org/packages/0c/aa/3be084d5b82e63ccdad4ed751e4acbae294673573e30481d29f8b7402eec/coverage-7.16.2-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4dbbd1155ca46e6e0b6b89d204428c56ef6a459af21333f365d135a2820e5a09", size = 256060, upload-time = "2026-09-27T12:28:03.185Z" },
{ url = "https://files.pythonhosted.org/packages/de/29/48fca82a7ebf7ff7b2e35019cc9537e7f65e4d2aa1215cc5a8792c989251/coverage-7.16.2-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8fc15cc8d0d06e873c00ef18e1372d605f9aaf3de27d8c24e50782e75bc8b843", size = 259106, upload-time = "2026-09-27T12:28:05.15Z" },
{ url = "https://files.pythonhosted.org/packages/06/3d/b2d5986f2dd53fe201aa1be2e4ab204fa1aed5101e67c0dbbb419b850aee/coverage-7.16.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c6afdd69218202bc1758c9a14b86b8cf1084f37ed2ca143e567a103772b16d1", size = 260674, upload-time = "2026-09-27T12:28:06.868Z" },
{ url = "https://files.pythonhosted.org/packages/ce/7e/b50160be3506ead12e6480d14279af7f0f17627694300a2d1fd2c42d2ff5/coverage-7.16.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:aba5c63b7afdc749cc9eae943d5b868cba2b261a176378fa1c5a30bc8bc89982", size = 263139, upload-time = "2026-09-27T12:28:08.771Z" },
{ url = "https://files.pythonhosted.org/packages/14/5e/7c805ac9a32606de1399bd7e9bd375aa2f973dc61b12680d9e6403c2e891/coverage-7.16.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9174f0af24e5eff248b9dbfe76ec5275a3d19d37edbc2810543f12cf97347a34", size = 256591, upload-time = "2026-09-27T12:28:10.842Z" },
{ url = "https://files.pythonhosted.org/packages/ab/9e/76f1ed129a2daf658a3ea17122824cf2e3b91fea0460d8d3664fc5a61018/coverage-7.16.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:80e9fdb4c3d926b6ba721d4bf7435bdb869c3527ae7803290361d0ab73db13b6", size = 258708, upload-time = "2026-09-27T12:28:12.962Z" },
{ url = "https://files.pythonhosted.org/packages/5a/b7/8d62e75f48b527619239a65294f842d4b7fd02a0839d43ae1de80184e2df/coverage-7.16.2-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:7b3bce4a0d05401d70b7d0d5ca783e686bc9d30e81dbd7d980d532609bf809e4", size = 256562, upload-time = "2026-09-27T12:28:14.934Z" },
{ url = "https://files.pythonhosted.org/packages/b8/8d/0a15f95c3afb78e947c52644786ba4bc9de259905687dd720d5e6fae2e76/coverage-7.16.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:44f21e407b278efdfc1ee5e481e00518bd1d500310a30a5fbf2bcbedfef4aaf0", size = 261077, upload-time = "2026-09-27T12:28:17.215Z" },
{ url = "https://files.pythonhosted.org/packages/25/00/88389987305a47d732866c07c8a500000ab574df9505e3114ac69c8d027f/coverage-7.16.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:59c3926585e1cd1f2190f4b2ac9014de1bbeaf0d5d0587b0dc6b0aa90d17896a", size = 256034, upload-time = "2026-09-27T12:28:19.08Z" },
{ url = "https://files.pythonhosted.org/packages/92/02/34d079d4952ad461bde037d353f9a6e037a7edc45fe0f9ee8781ff73f028/coverage-7.16.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:066429634299e14dd2d511e1e85f8f9cecc500781f6b41907c0dd6f1baea7e63", size = 258034, upload-time = "2026-09-27T12:28:21.242Z" },
{ url = "https://files.pythonhosted.org/packages/f6/d8/3e59a62879285b464ec1b10fd824fbc1af9ce66e842cd39974f80a0becc4/coverage-7.16.2-cp315-cp315-win32.whl", hash = "sha256:893ea9cf86cb8d2546812ac93d973aaf2ee1fb45110a873b014214fd23e3725e", size = 226252, upload-time = "2026-09-27T12:28:23.102Z" },
{ url = "https://files.pythonhosted.org/packages/f4/e1/128026e1b2836e9ad6b219207ba9edf1c5e0088a7869e23088aee7fbbe7a/coverage-7.16.2-cp315-cp315-win_amd64.whl", hash = "sha256:01c6908bc613b420c26c818fe948e1b97dfd041a53c98b01c63bd8321f5c9aae", size = 226728, upload-time = "2026-09-27T12:28:25.21Z" },
{ url = "https://files.pythonhosted.org/packages/a8/f4/c9fa8e7cf525ca7748ac52b0ee89331d13fe09808e45c679830708782e90/coverage-7.16.2-cp315-cp315-win_arm64.whl", hash = "sha256:967d72c835d7a8cf0af99ec813a2d06e3db6df706402f1fe85b31b437645f495", size = 226648, upload-time = "2026-09-27T12:28:27.136Z" },
{ url = "https://files.pythonhosted.org/packages/a2/13/e96b045447a856666f36f9c653e2a80bdaa732aaaf72412b19aa2c26a473/coverage-7.16.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:98d9c97f51b334b0adce7b964442a9af33c1a00c6ac856984cc5dc8d18f81c75", size = 224858, upload-time = "2026-09-27T12:28:29.169Z" },
{ url = "https://files.pythonhosted.org/packages/23/90/087f6ad1bd3df059632ca3407a4e6552ed1053ee35354de0a771acf35423/coverage-7.16.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e861f1071dcc2fec1e88bef0920f6b1eaa66a143555b4f8ab79ba2b0f30ef55", size = 225139, upload-time = "2026-09-27T12:28:31.131Z" },
{ url = "https://files.pythonhosted.org/packages/7e/8e/285dcef0184358044e7cbcd810a1bdc9566bc620f54702d605477155df4a/coverage-7.16.2-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fb9d92ecfe2d5b494367c67f7446f8b75b68d8d0c8cf3bc3e6997478be25d9e2", size = 265090, upload-time = "2026-09-27T12:28:33.04Z" },
{ url = "https://files.pythonhosted.org/packages/06/b2/cc83f3a6e5789a4e89059c69555bc641c2efcde568405a1c06fc702951ab/coverage-7.16.2-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:eb57acff4a74246ae513c142d4b36e18c389c3aed8661914a53f7cd0071031b2", size = 268254, upload-time = "2026-09-27T12:28:35.135Z" },
{ url = "https://files.pythonhosted.org/packages/ac/41/f548c19530f5d66ac6e3c92bbcbc49da7261de3a458b9f3e54a3efb1a0b2/coverage-7.16.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:444889f7f66b74e4455c0a97e0e166dd41177f1dca8c0239a47cff25e05ba7e1", size = 270695, upload-time = "2026-09-27T12:28:36.959Z" },
{ url = "https://files.pythonhosted.org/packages/94/61/4dc27cf82ef96434d2874110ad0cc10ea4621025705dc5049862bd3bd181/coverage-7.16.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a740ea6f083c6db7b926534d159508f80ba275ab35e722522de0d18d0f56e55f", size = 271853, upload-time = "2026-09-27T12:28:38.821Z" },
{ url = "https://files.pythonhosted.org/packages/38/29/bf8072b1b8bd5f2de8b21460a404460b1a2b97e80a9464c78ec0271f6199/coverage-7.16.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8e209591f7c41ae4a9171335cf6156afda0b21de73b02f73f5aa95b2d5fbb08d", size = 265644, upload-time = "2026-09-27T12:28:40.815Z" },
{ url = "https://files.pythonhosted.org/packages/7c/2f/0aecb8721be5cdeb8afd9d6d9f6b463f074e4d8d37f00f4c42442522709f/coverage-7.16.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:396bb16e04ce04efbb3df91456ae4e3da918e69ecdf67fb711b0a0fdf35ccce0", size = 268530, upload-time = "2026-09-27T12:28:42.725Z" },
{ url = "https://files.pythonhosted.org/packages/ab/0b/92b4b7628268ee711249958e68fc0328779bd3d9a7ab4715379465aedb84/coverage-7.16.2-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9cdf19874e0d247f32f03609200370343c3c7aa260b191d8c2bb251d36198283", size = 265154, upload-time = "2026-09-27T12:28:44.684Z" },
{ url = "https://files.pythonhosted.org/packages/7b/d9/41c95c1ab29b3dcd357cd1227181d1c98185632aca41ce670ce671b23a43/coverage-7.16.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:fd3d72233eb8b48acc94fa57d44e2d32ce8e7abed02882ccb6d855ccc4ed33ec", size = 269799, upload-time = "2026-09-27T12:28:46.672Z" },
{ url = "https://files.pythonhosted.org/packages/80/07/ebeb259aa5362b033a137b86d7274ff4b109d59be8cc9913889b783bf75a/coverage-7.16.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:bb4ffe96aa663cee727659db5a2afeb38c95f8677b747d447b90d6d4874ea2c5", size = 265196, upload-time = "2026-09-27T12:28:48.996Z" },
{ url = "https://files.pythonhosted.org/packages/b2/18/8437620f90d023680a072eee02f968055f3658bbfb7d386d0ea34cfb7f30/coverage-7.16.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:dba2edfb054f6d4a08df9d1637c39a5aa3865bca6617c13c86be21e45658a59c", size = 267266, upload-time = "2026-09-27T12:28:51.361Z" },
{ url = "https://files.pythonhosted.org/packages/28/6c/f08e8ee4293e6434035424180bef4d45e028e8ecc006c61bf9453e74405e/coverage-7.16.2-cp315-cp315t-win32.whl", hash = "sha256:251aed777c47c77aba047096d4542889db089227655711dfc2b9c54ef0e15e35", size = 226583, upload-time = "2026-09-27T12:28:53.33Z" },
{ url = "https://files.pythonhosted.org/packages/f7/fd/3f939c2847f4a72c20cff8b1ac33da78ea91a2d38d9b43336e60db719103/coverage-7.16.2-cp315-cp315t-win_amd64.whl", hash = "sha256:2aca0bdfa9e91621d5b09d815357bf63def4fc0e9cb66da67bf2cf93f3b1a6f5", size = 227374, upload-time = "2026-09-27T12:28:55.158Z" },
{ url = "https://files.pythonhosted.org/packages/5a/35/b98cdc354c952402132e675a87f2cc3227fb68f959c84aaa491fbe15933d/coverage-7.16.2-cp315-cp315t-win_arm64.whl", hash = "sha256:b88841e654f09732804809e435b3e005a929ffd9998b872b7b213957b8759cb8", size = 227064, upload-time = "2026-09-27T12:28:57.075Z" },
{ url = "https://files.pythonhosted.org/packages/3f/0c/7a64e1ac90541a8edf50daef0914848011fb057a5bf55284a4811e21939a/coverage-7.16.2-py3-none-any.whl", hash = "sha256:11d28e9123a9156cb405d8d27b44256c9a58fb5decc2073a8f17862057e3aa0f", size = 215754, upload-time = "2026-09-27T12:28:59.075Z" },
]
[package.optional-dependencies]
toml = [
{ name = "tomli", marker = "python_full_version <= '3.11'" },
]
[[package]]
name = "cryptography"
version = "50.0.1"
@ -863,7 +724,7 @@ name = "exceptiongroup"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
wheels = [
@ -895,18 +756,14 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/07/67/07ecd6d85c0f253363cbc4ac9e7dd048ca571a267fbccfea084d6009ac3b/greenlet-3.5.5-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:816230f469381ad0a43abc9fa8dda5a699e32fb78958dde32ded93213b70a667", size = 292971, upload-time = "2026-08-10T13:28:09.837Z" },
{ url = "https://files.pythonhosted.org/packages/24/35/426733bc24247ee17bb76df90f550c299ff5f8572b2bdd7cacb5c53fd994/greenlet-3.5.5-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a5433cf291e0ef9114bd14d0d824db6e5e4a43033234bca48181a9597acca07b", size = 609290, upload-time = "2026-08-10T14:14:32.273Z" },
{ url = "https://files.pythonhosted.org/packages/9c/dc/17d3a5acceb2fd0bbc9682a228117b719cdfb68085e6dbb33fa325755f27/greenlet-3.5.5-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:19d59f068887d8c5907fc177f27683413ace3011b6ed646c0b309266e74a6502", size = 622650, upload-time = "2026-08-10T14:27:22.004Z" },
{ url = "https://files.pythonhosted.org/packages/74/3f/b31e6bd6adb8f80492efb6a47e8f9cd0e7335db5aac2795b1876d5afcfee/greenlet-3.5.5-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:86c5113d698cb8d927b2750bb1f1d59eefe3a37e0e0217491aee29a7f84ef52c", size = 629560, upload-time = "2026-08-10T14:30:04.733Z" },
{ url = "https://files.pythonhosted.org/packages/51/91/00b3c0566316c6f383ea16ee05388ec4f57f6e0afa49e72ae471eda8c47f/greenlet-3.5.5-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ff00e12102358292087274dfb1669132387ff6e7920ebf9d85f4826ce0d3a56", size = 622819, upload-time = "2026-08-10T13:40:46.562Z" },
{ url = "https://files.pythonhosted.org/packages/18/5e/58c561efde575c4ca070030e2e0513e8d1b07b76d8a2d84a9bcef1becd42/greenlet-3.5.5-cp310-cp310-manylinux_2_39_riscv64.whl", hash = "sha256:c69bed34470abfcd456984fdadaa18e62169af4480335c45f3c32d1d9c12e638", size = 425489, upload-time = "2026-08-10T14:29:59.768Z" },
{ url = "https://files.pythonhosted.org/packages/3c/78/52de4f7ac9152ad1dbc8f437895c1e573d30ee1e1427e0f91a280e2417b6/greenlet-3.5.5-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:523bb8e27614d77101ea7a8cf59f8d91219b72d5c29f6a038c92b50828bfa8d0", size = 1582164, upload-time = "2026-08-10T14:15:02.645Z" },
{ url = "https://files.pythonhosted.org/packages/f6/ff/c3855a00c2417e8f61c7b9f0bc4f8f599c6928f5c15681ad251e78a91e05/greenlet-3.5.5-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:f1e2db190db51c17433eee424803818cf0670bf049d9cfe0dd07be111d1aa7c4", size = 1648807, upload-time = "2026-08-10T13:40:27.471Z" },
{ url = "https://files.pythonhosted.org/packages/70/21/d29ff6a79dbd1ec1fe74c155d25d4c5a85e221d6b9ffc2cc7a709e7c8c39/greenlet-3.5.5-cp310-cp310-win_amd64.whl", hash = "sha256:740e544169527b82695ce76af2f7ad6f030904658f2f3921a1d245771fb88cfc", size = 322832, upload-time = "2026-08-10T13:28:10.85Z" },
{ url = "https://files.pythonhosted.org/packages/4e/a3/07297917485ee2ca85bc3c8dc6ed85ad3fffcf424047fba62671dba68e97/greenlet-3.5.5-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:be63afcbbccfad3dd95a1ba12ada84dab2ef32031973d80b5b92df67fa763a61", size = 294165, upload-time = "2026-08-10T13:25:17.987Z" },
{ url = "https://files.pythonhosted.org/packages/db/51/6f732f9314cda54c5fd48a7620c7160f4f286967e8045ad94b9d66ce80b7/greenlet-3.5.5-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8a268024ce2d7d2b04694bf1594058981a9fa663d1df4b762dee499211ed7c1c", size = 613610, upload-time = "2026-08-10T14:14:33.829Z" },
{ url = "https://files.pythonhosted.org/packages/d8/c0/b27589e25d220289edcd4d582b2b17b83058d1a56d53d971b6ea1a34f10d/greenlet-3.5.5-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:35cbb8bf55ace57fbccb4fb8622c4521713acd8691e77f4696d416ea7ca527da", size = 625481, upload-time = "2026-08-10T14:27:23.647Z" },
{ url = "https://files.pythonhosted.org/packages/39/82/5c873dbb4fb001d22fbbd50e80d4c1b0181ddae106856132160f84b94e88/greenlet-3.5.5-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:abc8bc8d9f935cd685457545b6a53863a877fdc12c2c0f5ee9beee18d9db139c", size = 633329, upload-time = "2026-08-10T14:30:06.062Z" },
{ url = "https://files.pythonhosted.org/packages/51/2d/f2c928218ac52f26d7a2c188c171d1b7e728b23782cb3347e7b4fce1493a/greenlet-3.5.5-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:74cc6df89ec5302337adc9cf096221cbed2510fd444b0e0f1586cf0470740864", size = 624562, upload-time = "2026-08-10T13:40:48.064Z" },
{ url = "https://files.pythonhosted.org/packages/70/12/f7df98e72a8eb4a7edfec5a08d6d1a4ab53a52c95ba0b2ea6c10b8dd9bd0/greenlet-3.5.5-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:3134291427bb0f3526e9d90311988caf336eb43730e95244997a4fb15f45144f", size = 428145, upload-time = "2026-08-10T14:30:01.071Z" },
{ url = "https://files.pythonhosted.org/packages/3e/4a/92fc51d5d35912f4f06eec037ba347985defd0be47463a010a325634d9d2/greenlet-3.5.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6d9b454c5fc48aeaa7c4337813dbf513a6870468e426438a04d922c6d0fe63db", size = 1584909, upload-time = "2026-08-10T14:15:04.343Z" },
{ url = "https://files.pythonhosted.org/packages/ac/58/ed98b80ac5738c149a5258544843c45601ade1fd70f61740cdaead6351b3/greenlet-3.5.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:03551ed792cb1b4fc0277a0c60dfd8c343894a0ba06fe60dcd22f568b433da39", size = 1651184, upload-time = "2026-08-10T13:40:28.879Z" },
{ url = "https://files.pythonhosted.org/packages/d8/be/b582ceb80cefdf9d8da34078714e4b12b3d16f509dee0f65e40a5cc8fc7d/greenlet-3.5.5-cp311-cp311-win_amd64.whl", hash = "sha256:ab3df3dffb58bf70564e93a5cec7941e4d9faa5a36cc4234a10d3131afe04f53", size = 323280, upload-time = "2026-08-10T13:26:07.495Z" },
@ -914,9 +771,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2e/7e/9ecd0285e3153532ae07aeb88063c43c72b4221cf0d4d123b02f3682e3ff/greenlet-3.5.5-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:49520f0c95a48b42cf55414b8e8479beb274ea70431afc33e3f79903c71f4380", size = 295809, upload-time = "2026-08-10T13:25:34.023Z" },
{ url = "https://files.pythonhosted.org/packages/35/73/60e4bbcc89252037b18087f2ec16405d5b2d5be42dde191bbf3667e96102/greenlet-3.5.5-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:55272212cbc5f43d1d723725ab931f1939969b7e9523882ca58b55061769d053", size = 611910, upload-time = "2026-08-10T14:14:35.18Z" },
{ url = "https://files.pythonhosted.org/packages/a4/17/cd5134be659cd4a443e7a61ae670dabec165a814c51162916d637b6dd38e/greenlet-3.5.5-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:655bca754a2ef4efcb0eb48a94d3f4593536d0f3d48f8ed44343c01d16a92f95", size = 624198, upload-time = "2026-08-10T14:27:25.229Z" },
{ url = "https://files.pythonhosted.org/packages/9b/30/87c212b5c684d0e72974f1063b7a9687631e8985902c06e1016542c874e7/greenlet-3.5.5-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6ca5d6ae0739e5764f2cfcfaa562ac5a990cbdaedca93251c5e3cf07c362371f", size = 629504, upload-time = "2026-08-10T14:30:07.967Z" },
{ url = "https://files.pythonhosted.org/packages/78/ac/5c5b959999b6f09c3026b5dfe171575bc3121c5236ce74f495096f25b203/greenlet-3.5.5-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:147b25a42e5ca5be3d42356e8f608b37af715a1c196e9bf9d1627f3341adfe1d", size = 621439, upload-time = "2026-08-10T13:40:49.391Z" },
{ url = "https://files.pythonhosted.org/packages/63/2c/eb487fafc9f50ffff2b1e0b697f70fb34bf150821c08ab225aacf5583a7e/greenlet-3.5.5-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:1b5ed9162c0c098e0bbc2cf88a94f433c1b8926f831745252e099e5d83e17759", size = 432462, upload-time = "2026-08-10T14:30:02.309Z" },
{ url = "https://files.pythonhosted.org/packages/c8/8b/6acf112ed8aee499f25b4d6949820fb02ac950ff9c1f3d793bd5be0599f2/greenlet-3.5.5-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:27493374cff1d1b7919dc8126547f2aea582737e3046147b434b1e12de56389b", size = 1581342, upload-time = "2026-08-10T14:15:05.653Z" },
{ url = "https://files.pythonhosted.org/packages/b8/d7/734e5f198888876b42d7616ff6644c075baf6b8a2412deadd6b0e1b8b20c/greenlet-3.5.5-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:12e2ee66c2aba86133f10fd99d6a8856c6d351ffb7be0e4d52ef2cc5fbb705b2", size = 1645744, upload-time = "2026-08-10T13:40:30.353Z" },
{ url = "https://files.pythonhosted.org/packages/de/30/1f42b88dc587b5899ee50616ad56ee40cafaf225df4fb829f10183c62a5c/greenlet-3.5.5-cp312-cp312-win_amd64.whl", hash = "sha256:49ddacd36af37735fab103846f4ee4d18a492dde72730d1699c0c8ebe30d9f18", size = 324171, upload-time = "2026-08-10T13:28:44.472Z" },
@ -924,9 +779,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fb/3d/8cef5f724ec0d4add2af8961d504535ec60c3cca9e464f6d03bdba29d85b/greenlet-3.5.5-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:b79fd2a5bc099b5e744f34c4c9a58954a5f4cb7529fb4b6e8446057d61b6edaa", size = 294730, upload-time = "2026-08-10T13:27:51.206Z" },
{ url = "https://files.pythonhosted.org/packages/88/4b/8e7aa3f514273aecff30a16ab1bac09ff54cfc7e6860fdd8058c37ff2499/greenlet-3.5.5-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:634cf15a233a949136879dd388e25d3296e16f3f1e217d2456797b8579ebc6ed", size = 614536, upload-time = "2026-08-10T14:14:36.589Z" },
{ url = "https://files.pythonhosted.org/packages/85/48/4e95e9dd5a8a397dc6a6345dd7f1935113d0fca4f85e89d3976da9cd988d/greenlet-3.5.5-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:499adea519f748407fc6806d20eedabac2884fd73b9f38d81236e190ba20dfef", size = 626924, upload-time = "2026-08-10T14:27:27.048Z" },
{ url = "https://files.pythonhosted.org/packages/0e/84/eaa476d6bf3816828d0d70e80dcc36bf30a058233bd889e707e693f6e860/greenlet-3.5.5-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f7278591501941bb2456af102bb9cd59aab48c6cfd6e2dd68fa1290bb0c49a42", size = 632726, upload-time = "2026-08-10T14:30:09.874Z" },
{ url = "https://files.pythonhosted.org/packages/89/5d/398a1c71fa7a277deeb376c999979de6786f08fc2d5747a0b9d6e11738dd/greenlet-3.5.5-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2eabb980975cba5b93a95f6f69287d05fc05ac955bfd6a320a7c083eeb52c0b0", size = 623906, upload-time = "2026-08-10T13:40:50.501Z" },
{ url = "https://files.pythonhosted.org/packages/d0/f2/0cc2849ede68579291e9c59b3ab6ec1958f98681cca5b14d8fc75bf674a4/greenlet-3.5.5-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:4dfc7c4470354e7b09184d1a3a985761053a2fd694ddb5b5c80242afc2c8c90b", size = 434966, upload-time = "2026-08-10T14:30:03.729Z" },
{ url = "https://files.pythonhosted.org/packages/04/1b/745450fc5ea9e0cb17d840d248f284db3363de736d362c7d2d883e3eadba/greenlet-3.5.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:03115c2e0a371999bf8ae616aa8d653f96641d4705c457aebaa187276e9f7537", size = 1581430, upload-time = "2026-08-10T14:15:06.853Z" },
{ url = "https://files.pythonhosted.org/packages/d4/29/d51b296e3191bb15d3d81ec375af1909e4466c0f395d744ed475801798a9/greenlet-3.5.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4441153ffba21b90d3ca89fe3d31f5c093ae6c0bf0cfdfc98f54cde22f95b62e", size = 1645684, upload-time = "2026-08-10T13:40:32.133Z" },
{ url = "https://files.pythonhosted.org/packages/12/63/369f1a1625e64e9e31df3963c6044056e3fdfa3fa3fdba3c54ffefa6e987/greenlet-3.5.5-cp313-cp313-win_amd64.whl", hash = "sha256:95c5b1f4b3a193f8a0c2de4bfdcb48d119f7f1063941f1de1f2168051b3e52dd", size = 324075, upload-time = "2026-08-10T13:26:58.974Z" },
@ -934,9 +787,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7f/8c/080e881fa2be95ff1ddbd6994b2bab3b1a78df3b3fcab39306011764fcc7/greenlet-3.5.5-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:d4a389a852e392a6366058651a20fa5ba40d979865aa81bea2ccbdc44805070d", size = 295309, upload-time = "2026-08-10T13:26:03.032Z" },
{ url = "https://files.pythonhosted.org/packages/25/cc/0ac614e6586c0e42d4cc281a5819150f4f43685744a4c5ff77139286409d/greenlet-3.5.5-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70b157cd319873e8b544ddc2de158f55bbd0a9b0218c8ce9332039801518e328", size = 661185, upload-time = "2026-08-10T14:14:37.867Z" },
{ url = "https://files.pythonhosted.org/packages/5e/b9/6808725354be8ad305dfe5172377664fc9642d4fc043be246b3314cf4482/greenlet-3.5.5-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8bdfd1424abcf26832961e766570cae79efdb9599d709088c9cb6ef82b194926", size = 673419, upload-time = "2026-08-10T14:27:28.652Z" },
{ url = "https://files.pythonhosted.org/packages/eb/52/f005d579acde46c3d1cc3cab1c9f3d5708c8a3006a4120e8cf5da801afe9/greenlet-3.5.5-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d98ef6f92e67c6dbf299dbfd8facc1b0d2d9cedf91e325e73b3d0373fe4309d8", size = 677863, upload-time = "2026-08-10T14:30:11.663Z" },
{ url = "https://files.pythonhosted.org/packages/42/2e/40c509967da7f254680826a2fa0dd22138ec79946c70b97542d74cde8b43/greenlet-3.5.5-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:182de51c6b572a705f2fafaab2e783bcf7d2760940229dfe73086cbae037af3e", size = 670822, upload-time = "2026-08-10T13:40:51.833Z" },
{ url = "https://files.pythonhosted.org/packages/c4/8a/a75f8a2bdcef3c358a3147cdc9db3aa83755f0a038f766ab0bedb66f512c/greenlet-3.5.5-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:159df1942d88e8f784cbb38d6f18bdb365cd11319cfbb3e89623de2b97892d53", size = 480554, upload-time = "2026-08-10T14:30:05.171Z" },
{ url = "https://files.pythonhosted.org/packages/2d/22/c3c2eee4a8fe191d6d1d183086c56133d646024e3d70bfd414829f64560b/greenlet-3.5.5-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8fec3f165dfe332e490c3247c0f6c23b0bfc45f06496ad7f00ddb00e3d35e4dc", size = 1628469, upload-time = "2026-08-10T14:15:08.11Z" },
{ url = "https://files.pythonhosted.org/packages/f7/87/25babd09b94cb1f03e71db815fde463f0262e40cfbd953d58a8d77311351/greenlet-3.5.5-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:c6ce25fee6cabc8bf22cb8b52e642cbb821be5b9aec8094d07ff03378141b8e9", size = 1691952, upload-time = "2026-08-10T13:40:33.502Z" },
{ url = "https://files.pythonhosted.org/packages/2e/3d/5cc9701117ea4dc0eb7bf1f4f9b7888a6e2e5277ddfae095805ace50f2b6/greenlet-3.5.5-cp314-cp314-win_amd64.whl", hash = "sha256:7dffc5c859fe6059974df1e37d7923d654a83e2ae18fdd616994270e001115e1", size = 327458, upload-time = "2026-08-10T13:27:02.868Z" },
@ -944,18 +795,14 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/24/e0/50cd600b469e5734c72709b6b1838b6bc63f307b573c772c3132d6ecfe92/greenlet-3.5.5-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:0e5a7de979d764aea1f5b6e95cf92b5b37741b9823702041f34b126e7f690277", size = 305471, upload-time = "2026-08-10T13:26:20.568Z" },
{ url = "https://files.pythonhosted.org/packages/75/a3/77acd66dfc6387b5219b2080806c0cabb73c10eb1bb44b413c40a62015ba/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fef01bd457f11fc158b130ca0027a3c365693280e8e231b65bdaf57999f39f5b", size = 672470, upload-time = "2026-08-10T14:14:39.058Z" },
{ url = "https://files.pythonhosted.org/packages/b9/71/0d178142dca3ec19f46fb2212ae73d30ad53b9d548dc64804086033a7089/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5173a72310725a74afc82c164f0e52cb8ad0de62f2bb623f24f6c0cc07d80272", size = 679973, upload-time = "2026-08-10T14:27:30.072Z" },
{ url = "https://files.pythonhosted.org/packages/aa/ac/0d7887aa4bbfc9eba075cc428244dfc96f623478454d5ec81180d0d6bd5a/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e9ec2e7c98e895fcea0c5cc57b2606cf86ece6d0a56578f3eb225e2af4f0387", size = 681587, upload-time = "2026-08-10T14:30:13.519Z" },
{ url = "https://files.pythonhosted.org/packages/6e/31/46eb8567302eaf787abf88d09df014e14ae3baf460af1b8b0efdbd3efcd5/greenlet-3.5.5-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:44f08341873200ba8a60a8bc14ace3d91f1754f7fa7bc66157714a8cd420a476", size = 676634, upload-time = "2026-08-10T13:40:53.004Z" },
{ url = "https://files.pythonhosted.org/packages/4f/18/8d58ba1c429b0383e3219a3d0e0bba241d0444d8ed05b73349953c7d7c7b/greenlet-3.5.5-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:102817506f6090b5176c746a82603341a549b40e5c3d5b72a4c672228a918c41", size = 510175, upload-time = "2026-08-10T14:30:07.047Z" },
{ url = "https://files.pythonhosted.org/packages/a3/e9/b88bbf5b29970cb84172dc2c32aa3e5e579ceb94c808e81c826454138850/greenlet-3.5.5-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:d246c0db9a2513cd45f019ba178ea4d4d4705bd210ee465e2c15d76a1ab13874", size = 1637320, upload-time = "2026-08-10T14:15:09.317Z" },
{ url = "https://files.pythonhosted.org/packages/6d/8c/7631ed29cc6f0392f11830076e172ce4885e70b0bc2c1bce1731176d4b4e/greenlet-3.5.5-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:72507285b5caa1d17904a3f7c322ca780823a54170a0e04ec3f37bcc60d4db71", size = 1697412, upload-time = "2026-08-10T13:40:34.924Z" },
{ url = "https://files.pythonhosted.org/packages/da/0f/f7dd935f9c4cb1be49098770587f54d8a78518e55c89bce86c4fb4109057/greenlet-3.5.5-cp314-cp314t-win_amd64.whl", hash = "sha256:7805655781fb8f28a55d05fe57ed61f5f10f1892fb587673e3bb5264f28041f0", size = 331514, upload-time = "2026-08-10T13:29:20.611Z" },
{ url = "https://files.pythonhosted.org/packages/b7/e5/681b01f8fbc1b55232822f99e8f8afeb78a55a7c76a7bf9dbdc7ccb03a6d/greenlet-3.5.5-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:c0db80fcd5b8aece93f66c64f78a786bbb6b96c5fe63ef5a5a4581ecf8bab206", size = 295975, upload-time = "2026-08-10T13:28:45.985Z" },
{ url = "https://files.pythonhosted.org/packages/11/f2/69b488cd9e7267bf4b0fe8cdebf25d8d6df680d21bdf41150d23e23d6652/greenlet-3.5.5-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6b241c32f912ada659808d68e308c568baf577eebf757d15471472de0c18cfad", size = 666823, upload-time = "2026-08-10T14:14:40.222Z" },
{ url = "https://files.pythonhosted.org/packages/84/d4/d5bc2fdebbdda0c94555925ba79948b8395d75a7f6a36cc85dce5bab9f11/greenlet-3.5.5-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ef6a08349401d8eaf3cb12688ac8557de95788556b8631ef17555a4a173022c0", size = 677613, upload-time = "2026-08-10T14:27:31.543Z" },
{ url = "https://files.pythonhosted.org/packages/65/53/4e13642efc4d7ad6554ecb2242a5be42666b2e1a067323e88dfc0124a04b/greenlet-3.5.5-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37faa97daccb6d9f4c2141ce3118d023c3c5506864a7d8bdf726f665018c1f76", size = 681436, upload-time = "2026-08-10T14:30:14.839Z" },
{ url = "https://files.pythonhosted.org/packages/bd/93/542d8a3a90f3b35c6ad8bf7e56a03010287f2cafa289a5b7985b5207db39/greenlet-3.5.5-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f2e3d061b8e13aec2f0441689b3c71b244a20e5d274a52cb0f7e31bd1d139552", size = 675930, upload-time = "2026-08-10T13:40:54.205Z" },
{ url = "https://files.pythonhosted.org/packages/cd/32/188447c9a468d6977d2989397226b0c6b65ab6f4cf943f931643328512fc/greenlet-3.5.5-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:b18007dc2473a7942fd157366b55f01da6fed7ce85318591005b419e0a439474", size = 487404, upload-time = "2026-08-10T14:30:08.903Z" },
{ url = "https://files.pythonhosted.org/packages/52/b5/89c9f2e8460d71101037d47a1feed11928615a5edd42370be290e0657eeb/greenlet-3.5.5-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9ab5f5b93655e77fe0d6c2dfd22b5eac751bb1f876d8ec21761b7c1fb9266007", size = 1633878, upload-time = "2026-08-10T14:15:10.693Z" },
{ url = "https://files.pythonhosted.org/packages/b8/60/297de93f3b02ac78a5e04d32bb8bbe3080f4a73d8ed95016561463b70618/greenlet-3.5.5-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f0e5a21bd4452a88cf032fc43c4a5b307ab1380eacb63b5988f9c0317885e773", size = 1696597, upload-time = "2026-08-10T13:40:36.252Z" },
{ url = "https://files.pythonhosted.org/packages/18/25/54c6eaff4f337fb670215e89eb2d00d9499487b658e709d4b477be4a342e/greenlet-3.5.5-cp315-cp315-win_amd64.whl", hash = "sha256:469dbb0a78625642f4a626cfd0c6e8bccc0385b5e49189b6308bbe849ec88a8e", size = 327700, upload-time = "2026-08-10T13:28:06.752Z" },
@ -963,9 +810,7 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/10/e2/3144c0a116067ac1e30457b0139a94d60d1d36a86e015de68e9ac87cb3bc/greenlet-3.5.5-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:68184dfcf50ccaa8e864770fe0633a7e27250ea9329f8192ef47ee9ecfd78e1c", size = 306387, upload-time = "2026-08-10T13:27:00.897Z" },
{ url = "https://files.pythonhosted.org/packages/5c/a1/cb4223a7e9b9f43b8807e8eb212358bfe2dfaa174a9ea2889eb1714dcba2/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9ec0dc0e59dc9c61af5c47348365ccbbd7addfafe0a93b00336ff3da2907bdc6", size = 676472, upload-time = "2026-08-10T14:14:41.417Z" },
{ url = "https://files.pythonhosted.org/packages/9e/cd/a154b4498e5d8f12ada291cfb3b8d596eadde2177f5bf09a9be699d2a446/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e604f58e35833fc46ef20302bcb314dddbfd3fcf33a4f936216d51dd678d63ae", size = 684238, upload-time = "2026-08-10T14:27:32.946Z" },
{ url = "https://files.pythonhosted.org/packages/ce/f4/e450a68a152f819491d8c7df6a8254e761d87e6a78759268961f8c5bd4dd/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2888a3a38bc5ee5bb6c438372197152e815837e4fab7ed7a1f86ef18ffd58ad1", size = 686022, upload-time = "2026-08-10T14:30:15.96Z" },
{ url = "https://files.pythonhosted.org/packages/bf/bb/b0031d260c2968a3c87deebc51d80c64e499377f993aafe06ee3b7488cc2/greenlet-3.5.5-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:40239b5384f96da3963585cc6d7eaa9b56f8ae67e8d92cc82dd9e202fc847de3", size = 681246, upload-time = "2026-08-10T13:40:55.402Z" },
{ url = "https://files.pythonhosted.org/packages/18/23/17e63d6bf3b9c9b9dbea981b7f643a71f79603bdfb4f1c3a9cf353e22aed/greenlet-3.5.5-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:1e8d9391fe77f15649589a907cef972dbbd6352ef7ff7dc0492f658c0c26495f", size = 516951, upload-time = "2026-08-10T14:30:10.907Z" },
{ url = "https://files.pythonhosted.org/packages/9a/07/da554b71ab88e649da146e1065d86a48a5c5d92e50ab74ef41b504aa7f56/greenlet-3.5.5-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:a1eaccf5c3a1d3e46dead602c72e6836731e8e245c9de6a27764567b6b62d4c0", size = 1642735, upload-time = "2026-08-10T14:15:11.92Z" },
{ url = "https://files.pythonhosted.org/packages/78/76/26a3782a051677668af9d92beaa47cd87ba9dd5072f762961144a03dd4c6/greenlet-3.5.5-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:19e4e026fe20691f333b8eb1a3bc9625eceba8c3f9d62ec5a6f8581afbc6b5a5", size = 1700925, upload-time = "2026-08-10T13:40:37.656Z" },
{ url = "https://files.pythonhosted.org/packages/28/d9/fe7baf4190c2ae71f267efb9de21b3172bb35bc0ed1ef53dd6027d658e33/greenlet-3.5.5-cp315-cp315t-win_amd64.whl", hash = "sha256:712aee154f648bde84634654bb38bb78c69ac640c37a45c9effed800735049d8", size = 331829, upload-time = "2026-08-10T13:26:48.851Z" },
@ -1555,32 +1400,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },
]
[[package]]
name = "pytest-cov"
version = "7.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "coverage", extra = ["toml"] },
{ name = "pluggy" },
{ name = "pytest" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b1/51/a849f96e117386044471c8ec2bd6cfebacda285da9525c9106aeb28da671/pytest_cov-7.1.0.tar.gz", hash = "sha256:30674f2b5f6351aa09702a9c8c364f6a01c27aae0c1366ae8016160d1efc56b2", size = 55592, upload-time = "2026-03-21T20:11:16.284Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" },
]
[[package]]
name = "pytest-mock"
version = "3.17.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pytest" },
]
sdist = { url = "https://files.pythonhosted.org/packages/97/c2/28b9f5b955ff2bcd4727a6f768e2ca9b586cd7c37b95ea5f7b9b873ac7b3/pytest_mock-3.17.0.tar.gz", hash = "sha256:e36576e0985e01027e999891e7a966c67822d40c89ef1b4c8b6e22737e3590b4", size = 43064, upload-time = "2026-10-17T16:21:42.435Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/e8/ea/47fbdc8f37410956fd445720e927589b1e2a47772c5f28109f0ce2fa26d9/pytest_mock-3.17.0-py3-none-any.whl", hash = "sha256:1b82aa4b37137248bd687055e109723debeb07b489de1565297dc9589c5f2d6b", size = 11248, upload-time = "2026-10-17T16:21:41.265Z" },
]
[[package]]
name = "python-dotenv"
version = "1.2.3"
@ -1807,11 +1626,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b3/3f/3582293d1e185e71d19d7c731c3e2ee20ba21981c4a1115c0806c1f62120/sqlalchemy-2.0.52-py3-none-any.whl", hash = "sha256:3b81b8363a919ce53453591cdb93702e6bd54ade6c4fa2f468fc053baee5ed89", size = 1950700, upload-time = "2026-08-11T20:47:21.603Z" },
]
[package.optional-dependencies]
asyncio = [
{ name = "greenlet" },
]
[[package]]
name = "starlette"
version = "1.6.0"