Compare commits
No commits in common. "main" and "fix/plan-scoped-coupon-validation" have entirely different histories.
main
...
fix/plan-s
|
|
@ -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
|
|
||||||
12
README.md
12
README.md
|
|
@ -3,15 +3,15 @@
|
||||||
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
FastAPI Backend Platform for Acupedia Learning Content, Subscriptions, Pricing, and Payments.
|
||||||
|
|
||||||
<!-- START_TEST_STATUS -->
|
<!-- START_TEST_STATUS -->
|
||||||
[](#test-status--coverage) [](#test-status--coverage)
|
[](#test-status--coverage) [](#test-status--coverage)
|
||||||
|
|
||||||
| Metric | Status |
|
| Metric | Status |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| **Test Suite** | `PASSED` |
|
| **Test Suite** | `FAILED` |
|
||||||
| **Tests Passing** | `12` |
|
| **Tests Passing** | `92` |
|
||||||
| **Tests Failing** | `0` |
|
| **Tests Failing** | `6` |
|
||||||
| **Core Coverage** | `75%` |
|
| **Core Coverage** | `73%` |
|
||||||
| **Last Updated** | `2026-11-23 08:57:00 UTC` |
|
| **Last Updated** | `2026-10-22 06:02:56 UTC` |
|
||||||
<!-- END_TEST_STATUS -->
|
<!-- END_TEST_STATUS -->
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
@ -76,19 +76,3 @@ acupedia-ops access revoke-plan \
|
||||||
`--user-id <uuid>` can be used instead of `--email`.
|
`--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`.
|
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
|
|
||||||
```
|
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone
|
||||||
import os
|
import os
|
||||||
from uuid import UUID
|
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 sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
|
||||||
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
||||||
|
|
@ -41,16 +41,6 @@ class RevokeSummary:
|
||||||
entitlements_revoked: int
|
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:
|
def utcnow() -> datetime:
|
||||||
return datetime.now(timezone.utc)
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
@ -97,27 +87,6 @@ def build_parser() -> argparse.ArgumentParser:
|
||||||
help="Reason stored on revoked entitlements/subscriptions.",
|
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
|
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:
|
async def run(args: argparse.Namespace) -> int:
|
||||||
if not args.database_url:
|
if not args.database_url:
|
||||||
raise ValueError("DATABASE_URL is required")
|
raise ValueError("DATABASE_URL is required")
|
||||||
|
|
@ -499,23 +366,6 @@ async def run(args: argparse.Namespace) -> int:
|
||||||
)
|
)
|
||||||
return 0
|
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(
|
summary = await revoke_plan(
|
||||||
session,
|
session,
|
||||||
email=args.email,
|
email=args.email,
|
||||||
|
|
|
||||||
|
|
@ -20,7 +20,6 @@ class Settings(BaseSettings):
|
||||||
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
|
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
|
||||||
debug: bool = False
|
debug: bool = False
|
||||||
content_preview_enabled: bool = False
|
content_preview_enabled: bool = False
|
||||||
enable_module_repo_sync: bool = False
|
|
||||||
api_prefix: str = "/api/v1"
|
api_prefix: str = "/api/v1"
|
||||||
cors_origins: str = "http://localhost:3000,http://localhost:8000"
|
cors_origins: str = "http://localhost:3000,http://localhost:8000"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,10 +30,6 @@ from .content import (
|
||||||
SearchFacetMapping,
|
SearchFacetMapping,
|
||||||
ContentSearchDocument,
|
ContentSearchDocument,
|
||||||
ContentSearchFacet,
|
ContentSearchFacet,
|
||||||
BuilderModule,
|
|
||||||
BuilderCategory,
|
|
||||||
BuilderDisease,
|
|
||||||
BuilderPattern,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
from .commerce import (
|
from .commerce import (
|
||||||
|
|
@ -92,10 +88,6 @@ __all__ = [
|
||||||
"SearchFacetMapping",
|
"SearchFacetMapping",
|
||||||
"ContentSearchDocument",
|
"ContentSearchDocument",
|
||||||
"ContentSearchFacet",
|
"ContentSearchFacet",
|
||||||
"BuilderModule",
|
|
||||||
"BuilderCategory",
|
|
||||||
"BuilderDisease",
|
|
||||||
"BuilderPattern",
|
|
||||||
"UserBillingProfile",
|
"UserBillingProfile",
|
||||||
"AccessPlan",
|
"AccessPlan",
|
||||||
"AccessPlanModule",
|
"AccessPlanModule",
|
||||||
|
|
|
||||||
|
|
@ -216,7 +216,6 @@ class Coupon(Base):
|
||||||
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
start_date: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
end_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"))
|
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"))
|
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_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)))
|
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_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"))
|
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||||
description: Mapped[str | None] = mapped_column(Text)
|
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_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()"))
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
||||||
|
|
||||||
|
|
@ -292,10 +290,7 @@ class InvoiceMonthlySequence(Base):
|
||||||
|
|
||||||
class CouponRedemption(Base):
|
class CouponRedemption(Base):
|
||||||
__tablename__ = "coupon_redemptions"
|
__tablename__ = "coupon_redemptions"
|
||||||
__table_args__ = (
|
__table_args__ = (UniqueConstraint("coupon_id", "user_id", name="uq_coupon_user"), {"schema": COMMERCE_SCHEMA})
|
||||||
Index("idx_coupon_redemptions_coupon_user", "coupon_id", "user_id"),
|
|
||||||
{"schema": COMMERCE_SCHEMA},
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
|
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)
|
coupon_id: Mapped[UUID] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{COMMERCE_SCHEMA}.coupons.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,6 @@ from sqlalchemy import (
|
||||||
Date,
|
Date,
|
||||||
DateTime,
|
DateTime,
|
||||||
ForeignKey,
|
ForeignKey,
|
||||||
ForeignKeyConstraint,
|
|
||||||
Index,
|
Index,
|
||||||
Integer,
|
Integer,
|
||||||
Numeric,
|
Numeric,
|
||||||
|
|
@ -887,160 +886,3 @@ class ContentSearchFacet(Base):
|
||||||
mapping: Mapped[SearchFacetMapping] = relationship(back_populates="projected_values")
|
mapping: Mapped[SearchFacetMapping] = relationship(back_populates="projected_values")
|
||||||
source_attribute_definition: Mapped[AttributeDefinition] = relationship()
|
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")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,15 +10,13 @@ from collections.abc import AsyncIterator
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
engine = create_async_engine(
|
engine = create_async_engine(settings.database_url, pool_pre_ping=True, future=True)
|
||||||
settings.database_url,
|
# AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
|
||||||
pool_size=settings.database_pool_size,
|
|
||||||
max_overflow=settings.database_max_overflow,
|
# async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
|
||||||
pool_timeout=settings.database_pool_timeout_seconds,
|
# async with AsyncSessionLocal() as session:
|
||||||
pool_pre_ping=True,
|
# yield session
|
||||||
pool_recycle=1800,
|
|
||||||
future=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
SessionFactory = async_sessionmaker(
|
SessionFactory = async_sessionmaker(
|
||||||
bind=engine,
|
bind=engine,
|
||||||
|
|
@ -29,10 +27,4 @@ SessionFactory = async_sessionmaker(
|
||||||
|
|
||||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||||
async with SessionFactory() as session:
|
async with SessionFactory() as session:
|
||||||
try:
|
|
||||||
yield session
|
yield session
|
||||||
except Exception:
|
|
||||||
await session.rollback()
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
await session.close()
|
|
||||||
|
|
@ -16,7 +16,6 @@ from .schema import (
|
||||||
LIFETIME_PLAN_CODES = frozenset({
|
LIFETIME_PLAN_CODES = frozenset({
|
||||||
"LIFETIME_ALL",
|
"LIFETIME_ALL",
|
||||||
"LIFETIME_ALL_USD",
|
"LIFETIME_ALL_USD",
|
||||||
"LIFETIME_ALL_EUR",
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
import io
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||||
from app.core.config import get_settings
|
|
||||||
from app.db.models import AppUser
|
from app.db.models import AppUser
|
||||||
from app.features.payments import get_razorpay_service
|
from app.features.payments import get_razorpay_service
|
||||||
from .deps import get_admin_service, get_current_admin
|
from .deps import get_admin_service, get_current_admin
|
||||||
|
|
@ -22,20 +20,6 @@ from .schema import (
|
||||||
PlanStatusUpdateRequest,
|
PlanStatusUpdateRequest,
|
||||||
UpdateCouponRequest,
|
UpdateCouponRequest,
|
||||||
)
|
)
|
||||||
from .builder_schema import (
|
|
||||||
BuilderModuleSummary,
|
|
||||||
CreateBuilderModuleRequest,
|
|
||||||
UpdateBuilderModuleRequest,
|
|
||||||
BuilderCategorySummary,
|
|
||||||
BuilderDiseaseDetailResponse,
|
|
||||||
BuilderDiseaseSummary,
|
|
||||||
ModuleBuilderExportResponse,
|
|
||||||
ModuleBuilderImportRequest,
|
|
||||||
ModuleBuilderImportResponse,
|
|
||||||
SaveCategoryRequest,
|
|
||||||
SaveDiseaseRequest,
|
|
||||||
SaveFullDiseaseRequest,
|
|
||||||
)
|
|
||||||
from .service import AdminService
|
from .service import AdminService
|
||||||
|
|
||||||
router = APIRouter(prefix="/admin", tags=["Administrative Portal"])
|
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)
|
return await service.toggle_plan_status(plan_code, payload.is_active)
|
||||||
except LookupError as exc:
|
except LookupError as exc:
|
||||||
raise HTTPException(404, detail=str(exc)) from 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
|
raise HTTPException(400, detail=str(exc)) from exc
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise HTTPException(500, detail=f"Report export generation failed: {exc}") from 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
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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"
|
|
||||||
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
||||||
|
|
@ -1,12 +1,10 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from fastapi import Depends, HTTPException, Request
|
from fastapi import Depends, HTTPException
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.cache.invalidation import ContentCacheInvalidator
|
|
||||||
from app.db.models import AppUser, Role, UserRole
|
from app.db.models import AppUser, Role, UserRole
|
||||||
from app.db.session import get_db_session
|
from app.db.session import get_db_session
|
||||||
from app.features.checkout.deps import get_current_user
|
from app.features.checkout.deps import get_current_user
|
||||||
from .constants import has_admin_role
|
|
||||||
from .repository import AdminRepository
|
from .repository import AdminRepository
|
||||||
from .service import AdminService
|
from .service import AdminService
|
||||||
|
|
||||||
|
|
@ -14,18 +12,12 @@ async def get_current_admin(user: AppUser = Depends(get_current_user), session:
|
||||||
roles = (await session.execute(
|
roles = (await session.execute(
|
||||||
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
||||||
)).scalars().all()
|
)).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.")
|
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def get_admin_repository(session: AsyncSession = Depends(get_db_session)) -> AdminRepository:
|
def get_admin_repository(session: AsyncSession = Depends(get_db_session)) -> AdminRepository:
|
||||||
return AdminRepository(session)
|
return AdminRepository(session)
|
||||||
|
|
||||||
def get_admin_invalidator(request: Request) -> ContentCacheInvalidator | None:
|
def get_admin_service(repository: AdminRepository = Depends(get_admin_repository)) -> AdminService:
|
||||||
return getattr(request.app.state, "content_cache_invalidator", None)
|
return AdminService(repository.session)
|
||||||
|
|
||||||
def get_admin_service(
|
|
||||||
repository: AdminRepository = Depends(get_admin_repository),
|
|
||||||
invalidator: ContentCacheInvalidator | None = Depends(get_admin_invalidator),
|
|
||||||
) -> AdminService:
|
|
||||||
return AdminService(repository.session, invalidator=invalidator)
|
|
||||||
|
|
|
||||||
|
|
@ -62,7 +62,6 @@ class CreatePlanRequest(BaseModel):
|
||||||
billing_period: str = "yearly"
|
billing_period: str = "yearly"
|
||||||
price_inr: float
|
price_inr: float
|
||||||
price_usd: float
|
price_usd: float
|
||||||
price_eur: float | None = None
|
|
||||||
module_ids: list[str] = Field(default_factory=list)
|
module_ids: list[str] = Field(default_factory=list)
|
||||||
is_featured: bool = False
|
is_featured: bool = False
|
||||||
badge_text: str | None = None
|
badge_text: str | None = None
|
||||||
|
|
@ -72,13 +71,11 @@ class CreatePlanRequest(BaseModel):
|
||||||
class PlanPricingUpdateRequest(BaseModel):
|
class PlanPricingUpdateRequest(BaseModel):
|
||||||
price_inr: float | None = None
|
price_inr: float | None = None
|
||||||
price_usd: float | None = None
|
price_usd: float | None = None
|
||||||
price_eur: float | None = None
|
|
||||||
name: str | None = None
|
name: str | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
badge_text: str | None = None
|
badge_text: str | None = None
|
||||||
heading: str | None = None
|
heading: str | None = None
|
||||||
subtitle: str | None = None
|
subtitle: str | None = None
|
||||||
module_ids: list[str] | None = None
|
|
||||||
|
|
||||||
class PlanStatusUpdateRequest(BaseModel):
|
class PlanStatusUpdateRequest(BaseModel):
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
|
@ -88,53 +85,31 @@ class CreateCouponRequest(BaseModel):
|
||||||
discount_type: str
|
discount_type: str
|
||||||
coupon_category: str = "general"
|
coupon_category: str = "general"
|
||||||
value: float
|
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_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
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int = 0
|
usage_limit: int = 0
|
||||||
per_user_limit: int | None = None
|
|
||||||
min_purchase_amount: float = 0.0
|
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
|
is_first_purchase_only: bool = False
|
||||||
applicable_plan_ids: list[str] | None = None
|
applicable_plan_ids: list[str] | None = None
|
||||||
applicable_module_ids: list[str] | None = None
|
applicable_module_ids: list[str] | None = None
|
||||||
is_active: bool = True
|
is_active: bool = True
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
metadata_json: dict | None = None
|
|
||||||
|
|
||||||
class UpdateCouponRequest(BaseModel):
|
class UpdateCouponRequest(BaseModel):
|
||||||
discount_type: str | None = None
|
discount_type: str | None = None
|
||||||
coupon_category: str | None = None
|
coupon_category: str | None = None
|
||||||
value: float | 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_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
|
start_date: str | None = None
|
||||||
end_date: str | None = None
|
end_date: str | None = None
|
||||||
usage_limit: int | None = None
|
usage_limit: int | None = None
|
||||||
per_user_limit: int | None = None
|
|
||||||
min_purchase_amount: float | 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
|
is_first_purchase_only: bool | None = None
|
||||||
applicable_plan_ids: list[str] | None = None
|
applicable_plan_ids: list[str] | None = None
|
||||||
applicable_module_ids: list[str] | None = None
|
applicable_module_ids: list[str] | None = None
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
metadata_json: dict | None = None
|
|
||||||
|
|
||||||
class CouponStatusToggleRequest(BaseModel):
|
class CouponStatusToggleRequest(BaseModel):
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ from __future__ import annotations
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||||
from app.db.models import AppUser
|
from app.db.models import AppUser
|
||||||
from app.cache.invalidation import ContentCacheInvalidator
|
|
||||||
from ..schema import (
|
from ..schema import (
|
||||||
AdminCreateSuperAdminRequest,
|
AdminCreateSuperAdminRequest,
|
||||||
AdminPromoteUserRequest,
|
AdminPromoteUserRequest,
|
||||||
|
|
@ -27,7 +26,6 @@ from .customer_service import AdminCustomerService
|
||||||
from .payment_service import AdminPaymentService
|
from .payment_service import AdminPaymentService
|
||||||
from .database_service import AdminDatabaseService
|
from .database_service import AdminDatabaseService
|
||||||
from .report_service import AdminReportService
|
from .report_service import AdminReportService
|
||||||
from .module_builder_service import ModuleBuilderService
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"AdminModuleService",
|
"AdminModuleService",
|
||||||
|
|
@ -37,7 +35,6 @@ __all__ = [
|
||||||
"AdminPaymentService",
|
"AdminPaymentService",
|
||||||
"AdminDatabaseService",
|
"AdminDatabaseService",
|
||||||
"AdminReportService",
|
"AdminReportService",
|
||||||
"ModuleBuilderService",
|
|
||||||
"AdminService",
|
"AdminService",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -52,24 +49,17 @@ class AdminService:
|
||||||
- payments: AdminPaymentService
|
- payments: AdminPaymentService
|
||||||
- database: AdminDatabaseService
|
- database: AdminDatabaseService
|
||||||
- reports: AdminReportService
|
- reports: AdminReportService
|
||||||
- builder: ModuleBuilderService
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self,
|
|
||||||
session: AsyncSession,
|
|
||||||
invalidator: ContentCacheInvalidator | None = None,
|
|
||||||
) -> None:
|
|
||||||
self.session = session
|
self.session = session
|
||||||
self.invalidator = invalidator
|
self.modules = AdminModuleService(session)
|
||||||
self.modules = AdminModuleService(session, invalidator=invalidator)
|
|
||||||
self.plans = AdminPlanService(session)
|
self.plans = AdminPlanService(session)
|
||||||
self.coupons = AdminCouponService(session)
|
self.coupons = AdminCouponService(session)
|
||||||
self.customers = AdminCustomerService(session)
|
self.customers = AdminCustomerService(session)
|
||||||
self.payments = AdminPaymentService(session)
|
self.payments = AdminPaymentService(session)
|
||||||
self.database = AdminDatabaseService(session)
|
self.database = AdminDatabaseService(session)
|
||||||
self.reports = AdminReportService(session)
|
self.reports = AdminReportService(session)
|
||||||
self.builder = ModuleBuilderService(session)
|
|
||||||
|
|
||||||
# ── Modules Facade ──
|
# ── Modules Facade ──
|
||||||
async def list_modules(self) -> list[dict]:
|
async def list_modules(self) -> list[dict]:
|
||||||
|
|
|
||||||
|
|
@ -18,80 +18,10 @@ def _parse_iso_datetime(value: str | datetime | None, default: datetime | None =
|
||||||
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
|
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:
|
class AdminCouponService:
|
||||||
def __init__(self, session: AsyncSession) -> None:
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self.session = session
|
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]:
|
async def list_coupons(self) -> list[dict]:
|
||||||
coupons = (await self.session.execute(
|
coupons = (await self.session.execute(
|
||||||
select(Coupon).order_by(Coupon.created_at.desc())
|
select(Coupon).order_by(Coupon.created_at.desc())
|
||||||
|
|
@ -120,7 +50,7 @@ class AdminCouponService:
|
||||||
if not c.is_active:
|
if not c.is_active:
|
||||||
status = "inactive"
|
status = "inactive"
|
||||||
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
|
elif c.usage_limit > 0 and usage_count >= c.usage_limit:
|
||||||
status = "fully_redeemed"
|
status = "expired"
|
||||||
elif now < s_date:
|
elif now < s_date:
|
||||||
status = "scheduled"
|
status = "scheduled"
|
||||||
elif now > e_date:
|
elif now > e_date:
|
||||||
|
|
@ -131,53 +61,18 @@ class AdminCouponService:
|
||||||
plan_names = [all_plans.get(str(pid), str(pid)[:8]) for pid in (c.applicable_plan_ids or [])]
|
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 [])]
|
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({
|
result.append({
|
||||||
"id": str(c.id),
|
"id": str(c.id),
|
||||||
"code": c.code,
|
"code": c.code,
|
||||||
"discount_type": c.discount_type,
|
"discount_type": c.discount_type,
|
||||||
"coupon_category": c.coupon_category,
|
"coupon_category": c.coupon_category,
|
||||||
"value": float(c.value),
|
"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_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(),
|
"start_date": s_date.isoformat(),
|
||||||
"end_date": e_date.isoformat(),
|
"end_date": e_date.isoformat(),
|
||||||
"usage_limit": c.usage_limit,
|
"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": usage_count,
|
||||||
"min_purchase_amount": float(c.min_purchase_amount or 0.0),
|
"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_first_purchase_only": c.is_first_purchase_only,
|
||||||
"is_active": c.is_active,
|
"is_active": c.is_active,
|
||||||
"description": c.description or "",
|
"description": c.description or "",
|
||||||
|
|
@ -203,37 +98,26 @@ class AdminCouponService:
|
||||||
|
|
||||||
if end <= start:
|
if end <= start:
|
||||||
raise ValueError("Invalid date range: End date must be later than start date.")
|
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
|
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(
|
coupon = Coupon(
|
||||||
code=code,
|
code=code,
|
||||||
discount_type=payload.discount_type,
|
discount_type=payload.discount_type,
|
||||||
coupon_category=payload.coupon_category,
|
coupon_category=payload.coupon_category,
|
||||||
value=Decimal(str(base_val)),
|
value=Decimal(str(payload.value)),
|
||||||
max_discount_limit=Decimal(str(base_cap)),
|
max_discount_limit=Decimal(str(payload.max_discount_limit or 0)),
|
||||||
start_date=start,
|
start_date=start,
|
||||||
end_date=end,
|
end_date=end,
|
||||||
usage_limit=payload.usage_limit,
|
usage_limit=payload.usage_limit,
|
||||||
per_user_limit=payload.per_user_limit,
|
|
||||||
usage_count=0,
|
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,
|
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,
|
applicable_module_ids=module_uuids,
|
||||||
is_active=payload.is_active,
|
is_active=payload.is_active,
|
||||||
description=payload.description,
|
description=payload.description,
|
||||||
metadata_json=metadata,
|
|
||||||
)
|
)
|
||||||
self.session.add(coupon)
|
self.session.add(coupon)
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
|
|
@ -259,34 +143,22 @@ class AdminCouponService:
|
||||||
coupon.discount_type = payload.discount_type
|
coupon.discount_type = payload.discount_type
|
||||||
if payload.coupon_category is not None:
|
if payload.coupon_category is not None:
|
||||||
coupon.coupon_category = payload.coupon_category
|
coupon.coupon_category = payload.coupon_category
|
||||||
if payload.value_inr is not None:
|
if payload.value is not None:
|
||||||
coupon.value = Decimal(str(payload.value_inr))
|
|
||||||
elif payload.value is not None:
|
|
||||||
coupon.value = Decimal(str(payload.value))
|
coupon.value = Decimal(str(payload.value))
|
||||||
if payload.max_discount_inr is not None:
|
if payload.max_discount_limit is not None:
|
||||||
coupon.max_discount_limit = Decimal(str(payload.max_discount_inr))
|
|
||||||
elif payload.max_discount_limit is not None:
|
|
||||||
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
coupon.max_discount_limit = Decimal(str(payload.max_discount_limit))
|
||||||
if payload.start_date is not None:
|
if payload.start_date is not None:
|
||||||
coupon.start_date = new_start
|
coupon.start_date = new_start
|
||||||
if payload.end_date is not None:
|
if payload.end_date is not None:
|
||||||
coupon.end_date = new_end
|
coupon.end_date = new_end
|
||||||
if payload.usage_limit is not None:
|
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
|
coupon.usage_limit = payload.usage_limit
|
||||||
if "per_user_limit" in payload.model_fields_set:
|
if payload.min_purchase_amount is not None:
|
||||||
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:
|
|
||||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_amount))
|
||||||
if payload.is_first_purchase_only is not None:
|
if payload.is_first_purchase_only is not None:
|
||||||
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
coupon.is_first_purchase_only = payload.is_first_purchase_only
|
||||||
if payload.applicable_plan_ids is not None:
|
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:
|
if payload.applicable_module_ids is not None:
|
||||||
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
coupon.applicable_module_ids = [UUID(mid) for mid in payload.applicable_module_ids]
|
||||||
if payload.is_active is not None:
|
if payload.is_active is not None:
|
||||||
|
|
@ -294,8 +166,6 @@ class AdminCouponService:
|
||||||
if payload.description is not None:
|
if payload.description is not None:
|
||||||
coupon.description = payload.description
|
coupon.description = payload.description
|
||||||
|
|
||||||
coupon.metadata_json = _build_coupon_metadata(payload, coupon.metadata_json)
|
|
||||||
|
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
return {"status": "success", "message": f"Coupon '{coupon.code}' updated successfully."}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ from app.db.models import (
|
||||||
UserRole,
|
UserRole,
|
||||||
UserSubscription,
|
UserSubscription,
|
||||||
)
|
)
|
||||||
from ..constants import has_admin_role
|
|
||||||
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
|
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
|
||||||
from app.features.auth.security import hash_password, validate_password_strength
|
from app.features.auth.security import hash_password, validate_password_strength
|
||||||
from app.features.payments import get_razorpay_service
|
from app.features.payments import get_razorpay_service
|
||||||
|
|
@ -28,50 +27,20 @@ class AdminCustomerService:
|
||||||
|
|
||||||
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
||||||
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
|
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
|
||||||
if not users:
|
out: list[AdminUserListResponse] = []
|
||||||
return []
|
for user in users:
|
||||||
|
roles = list((await self.session.execute(
|
||||||
user_ids = [u.id for u in users]
|
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
||||||
|
)).scalars().all())
|
||||||
role_rows = (await self.session.execute(
|
if super_admin_only != ("super_admin" in roles):
|
||||||
select(UserRole.user_id, Role.role_name)
|
continue
|
||||||
.join(Role, Role.id == UserRole.role_id)
|
subs = (await self.session.execute(
|
||||||
.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)
|
select(UserSubscription, AccessPlan)
|
||||||
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
||||||
.where(
|
.where(UserSubscription.user_id == user.id, UserSubscription.status != SubscriptionStatus.PENDING)
|
||||||
UserSubscription.user_id.in_(matching_ids),
|
|
||||||
UserSubscription.status != SubscriptionStatus.PENDING,
|
|
||||||
)
|
|
||||||
.order_by(UserSubscription.started_at.desc())
|
.order_by(UserSubscription.started_at.desc())
|
||||||
)).all()
|
)).all()
|
||||||
subs_by_user: dict[UUID, list[dict]] = {}
|
out.append(
|
||||||
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(
|
AdminUserListResponse(
|
||||||
id=user.id,
|
id=user.id,
|
||||||
email=user.email,
|
email=user.email,
|
||||||
|
|
@ -79,13 +48,24 @@ class AdminCustomerService:
|
||||||
phone_number=user.phone_number,
|
phone_number=user.phone_number,
|
||||||
country=user.country,
|
country=user.country,
|
||||||
is_active=user.is_active,
|
is_active=user.is_active,
|
||||||
roles=roles_by_user.get(user.id, []),
|
roles=roles,
|
||||||
external_ref=user.external_ref,
|
external_ref=user.external_ref,
|
||||||
subscriptions=subs_by_user.get(user.id, []),
|
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,
|
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:
|
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
|
||||||
user = (await self.session.execute(
|
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
|
|
@ -1,69 +1,23 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from typing import Any
|
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import select, func
|
from sqlalchemy import select, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.enums import ModuleStatus
|
from app.db.enums import ModuleStatus
|
||||||
from app.db.models import Module, AccessPlanModule
|
from app.db.models import Module, AccessPlanModule
|
||||||
from app.cache.invalidation import ContentCacheInvalidator
|
|
||||||
from ..schema import ModuleStatusUpdateRequest, ModuleUpdateRequest
|
from ..schema import ModuleStatusUpdateRequest, ModuleUpdateRequest
|
||||||
|
|
||||||
CATEGORY_UI_DEFAULTS: dict[str, dict[str, str]] = {
|
UI_MAPPINGS: dict[str, dict[str, str]] = {
|
||||||
"Points": {"icon": "water-outline", "color": "#2563EB"},
|
"acupoints": {"category": "point", "icon": "water-outline", "color": "#2563EB"},
|
||||||
"Patterns": {"icon": "analytics-outline", "color": "#8B5CF6"},
|
"ear-acupuncture": {"category": "point", "icon": "ear-outline", "color": "#F59E0B"},
|
||||||
"Nutrition": {"icon": "leaf-outline", "color": "#10B981"},
|
"scalp-acupuncture": {"category": "point", "icon": "accessibility-outline", "color": "#EF4444"},
|
||||||
"Therapeutics": {"icon": "medkit-outline", "color": "#EC4899"},
|
"points_tung": {"category": "point", "icon": "analytics-outline", "color": "#10B981"},
|
||||||
"General": {"icon": "book-outline", "color": "#6366F1"},
|
"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:
|
class AdminModuleService:
|
||||||
def __init__(
|
def __init__(self, session: AsyncSession) -> None:
|
||||||
self,
|
|
||||||
session: AsyncSession,
|
|
||||||
invalidator: ContentCacheInvalidator | None = None,
|
|
||||||
) -> None:
|
|
||||||
self.session = session
|
self.session = session
|
||||||
self.invalidator = invalidator
|
|
||||||
|
|
||||||
async def list_modules(self) -> list[dict]:
|
async def list_modules(self) -> list[dict]:
|
||||||
modules = (await self.session.execute(select(Module).order_by(Module.name.asc()))).scalars().all()
|
modules = (await self.session.execute(select(Module).order_by(Module.name.asc()))).scalars().all()
|
||||||
|
|
@ -76,10 +30,10 @@ class AdminModuleService:
|
||||||
result: list[dict] = []
|
result: list[dict] = []
|
||||||
for m in modules:
|
for m in modules:
|
||||||
meta = m.metadata_json or {}
|
meta = m.metadata_json or {}
|
||||||
category = resolve_module_category(meta)
|
ui = UI_MAPPINGS.get(m.slug, {})
|
||||||
ui_defaults = CATEGORY_UI_DEFAULTS.get(category, CATEGORY_UI_DEFAULTS["General"])
|
category = meta.get("category") or ui.get("category", "General")
|
||||||
icon = meta.get("icon") or ui_defaults["icon"]
|
icon = meta.get("icon") or ui.get("icon", "book-outline")
|
||||||
color = meta.get("color") or ui_defaults["color"]
|
color = meta.get("color") or ui.get("color", "#6366F1")
|
||||||
|
|
||||||
result.append({
|
result.append({
|
||||||
"id": str(m.id),
|
"id": str(m.id),
|
||||||
|
|
@ -118,8 +72,6 @@ class AdminModuleService:
|
||||||
|
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
await self.session.refresh(module)
|
await self.session.refresh(module)
|
||||||
if self.invalidator:
|
|
||||||
await self.invalidator.invalidate_module_structure_change(module_id=module.id)
|
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"Module '{module.name}' status updated to {'Active' if module.is_active else 'Inactive'}.",
|
"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.commit()
|
||||||
await self.session.refresh(module)
|
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 {
|
return {
|
||||||
"status": "success",
|
"status": "success",
|
||||||
"message": f"Module '{module.name}' updated successfully.",
|
"message": f"Module '{module.name}' updated successfully.",
|
||||||
|
|
@ -169,8 +117,8 @@ class AdminModuleService:
|
||||||
"slug": module.slug,
|
"slug": module.slug,
|
||||||
"name": module.name,
|
"name": module.name,
|
||||||
"description": module.description,
|
"description": module.description,
|
||||||
"category": resolved_category,
|
"category": meta.get("category"),
|
||||||
"color": meta.get("color") or ui_defaults["color"],
|
"color": meta.get("color"),
|
||||||
"icon": meta.get("icon") or ui_defaults["icon"],
|
"icon": meta.get("icon"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -363,49 +363,36 @@ class AdminPaymentService:
|
||||||
invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None
|
invoice = (await self.session.execute(select(Invoice).where(Invoice.payment_transaction_id == tx.id))).scalar_one_or_none() if tx else None
|
||||||
|
|
||||||
profile = None
|
profile = None
|
||||||
if invoice and invoice.billing_profile_id:
|
if user:
|
||||||
profile = (await self.session.execute(
|
|
||||||
select(UserBillingProfile).where(UserBillingProfile.id == invoice.billing_profile_id)
|
|
||||||
)).scalar_one_or_none()
|
|
||||||
elif user:
|
|
||||||
profile = (await self.session.execute(
|
profile = (await self.session.execute(
|
||||||
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
select(UserBillingProfile).where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
|
||||||
)).scalar_one_or_none()
|
)).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 = {}
|
rzp_payment = {}
|
||||||
try:
|
try:
|
||||||
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
|
rzp_payment = get_razorpay_service().fetch_payment(payment_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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
|
# Clean address string
|
||||||
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: 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 = []
|
clean_addr_parts = []
|
||||||
if profile:
|
if profile:
|
||||||
for p in [profile.address_line1, profile.city, profile.state, profile.postal_code]:
|
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"]:
|
if p and p.strip() and p.strip().lower() not in ["not configured", "000000", "none", "null"]:
|
||||||
clean_addr_parts.append(p.strip())
|
clean_addr_parts.append(p.strip())
|
||||||
c = profile.country or (user.country if user and user.country else None)
|
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"]:
|
if c and c.strip() and c.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
clean_addr_parts.append(c.strip())
|
clean_addr_parts.append(c.strip())
|
||||||
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
elif user and user.country and user.country.strip().lower() not in ["not configured", "none", "null"]:
|
||||||
clean_addr_parts.append(user.country.strip())
|
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")
|
elif invoice and invoice.billing_address and "not configured" not in invoice.billing_address.lower():
|
||||||
|
clean_addr_parts.append(invoice.billing_address.strip())
|
||||||
|
|
||||||
|
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)
|
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_number = (invoice.invoice_number if invoice else None) or f"INV-{now.strftime('%b').upper()}-{now.strftime('%Y')}-PREVIEW"
|
||||||
|
|
@ -420,6 +407,8 @@ class AdminPaymentService:
|
||||||
# Item description
|
# Item description
|
||||||
item_desc = rzp_payment.get("description") if rzp_payment else None
|
item_desc = rzp_payment.get("description") if rzp_payment else None
|
||||||
if not item_desc and tx:
|
if not item_desc and tx:
|
||||||
|
if tx.subscription_id:
|
||||||
|
sub = (await self.session.execute(select(UserSubscription).where(UserSubscription.id == tx.subscription_id))).scalar_one_or_none()
|
||||||
if sub:
|
if sub:
|
||||||
ref = sub.payment_reference
|
ref = sub.payment_reference
|
||||||
subs = (await self.session.execute(
|
subs = (await self.session.execute(
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,12 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import delete, select, func
|
from sqlalchemy import select, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.enums import BillingPeriod, PlanType, SubscriptionStatus
|
from app.db.enums import BillingPeriod, PlanType, SubscriptionStatus
|
||||||
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Module, UserSubscription
|
from app.db.models import AccessPlan, AccessPlanModule, AppUser, Module, UserSubscription
|
||||||
from ..schema import CreatePlanRequest, PlanPricingUpdateRequest, PlanStatusUpdateRequest
|
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:
|
class AdminPlanService:
|
||||||
|
|
@ -28,15 +28,14 @@ class AdminPlanService:
|
||||||
if p_str not in plan_mods_map:
|
if p_str not in plan_mods_map:
|
||||||
plan_mods_map[p_str] = []
|
plan_mods_map[p_str] = []
|
||||||
meta = m.metadata_json or {}
|
meta = m.metadata_json or {}
|
||||||
category = resolve_module_category(meta)
|
ui = UI_MAPPINGS.get(m.slug, {})
|
||||||
ui_defaults = CATEGORY_UI_DEFAULTS.get(category, CATEGORY_UI_DEFAULTS["General"])
|
|
||||||
plan_mods_map[p_str].append({
|
plan_mods_map[p_str].append({
|
||||||
"id": str(m.id),
|
"id": str(m.id),
|
||||||
"slug": m.slug,
|
"slug": m.slug,
|
||||||
"name": m.name,
|
"name": m.name,
|
||||||
"category": category,
|
"category": meta.get("category") or ui.get("category", "General"),
|
||||||
"icon": meta.get("icon") or ui_defaults["icon"],
|
"icon": meta.get("icon") or ui.get("icon", "book-outline"),
|
||||||
"color": meta.get("color") or ui_defaults["color"],
|
"color": meta.get("color") or ui.get("color", "#6366F1"),
|
||||||
"is_active": m.is_active,
|
"is_active": m.is_active,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -51,11 +50,7 @@ class AdminPlanService:
|
||||||
for p in all_plans:
|
for p in all_plans:
|
||||||
code = p.code
|
code = p.code
|
||||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
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") else code
|
||||||
if code.endswith("_USD") or code.endswith("_EUR"):
|
|
||||||
base_code = code[:-4]
|
|
||||||
else:
|
|
||||||
base_code = code
|
|
||||||
p_str = str(p.id)
|
p_str = str(p.id)
|
||||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||||
meta = p.metadata_json or {}
|
meta = p.metadata_json or {}
|
||||||
|
|
@ -63,7 +58,7 @@ class AdminPlanService:
|
||||||
if base_code not in groups:
|
if base_code not in groups:
|
||||||
groups[base_code] = {
|
groups[base_code] = {
|
||||||
"base_code": 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 "",
|
"description": p.description or "",
|
||||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||||
|
|
@ -74,10 +69,8 @@ class AdminPlanService:
|
||||||
"subtitle": meta.get("subtitle"),
|
"subtitle": meta.get("subtitle"),
|
||||||
"inr_plan_id": None,
|
"inr_plan_id": None,
|
||||||
"usd_plan_id": None,
|
"usd_plan_id": None,
|
||||||
"eur_plan_id": None,
|
|
||||||
"price_inr": 0.0,
|
"price_inr": 0.0,
|
||||||
"price_usd": 0.0,
|
"price_usd": 0.0,
|
||||||
"price_eur": 0.0,
|
|
||||||
"modules": [],
|
"modules": [],
|
||||||
"module_ids": [],
|
"module_ids": [],
|
||||||
"subscribers_count": 0,
|
"subscribers_count": 0,
|
||||||
|
|
@ -88,9 +81,6 @@ class AdminPlanService:
|
||||||
if is_usd:
|
if is_usd:
|
||||||
grp["usd_plan_id"] = p_str
|
grp["usd_plan_id"] = p_str
|
||||||
grp["price_usd"] = fee
|
grp["price_usd"] = fee
|
||||||
elif is_eur:
|
|
||||||
grp["eur_plan_id"] = p_str
|
|
||||||
grp["price_eur"] = fee
|
|
||||||
else:
|
else:
|
||||||
grp["inr_plan_id"] = p_str
|
grp["inr_plan_id"] = p_str
|
||||||
grp["price_inr"] = fee
|
grp["price_inr"] = fee
|
||||||
|
|
@ -109,8 +99,6 @@ class AdminPlanService:
|
||||||
grp["heading"] = meta.get("heading")
|
grp["heading"] = meta.get("heading")
|
||||||
if meta.get("subtitle"):
|
if meta.get("subtitle"):
|
||||||
grp["subtitle"] = 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)
|
grp["subscribers_count"] += sub_counts.get(p_str, 0)
|
||||||
mods = plan_mods_map.get(p_str, [])
|
mods = plan_mods_map.get(p_str, [])
|
||||||
|
|
@ -118,11 +106,6 @@ class AdminPlanService:
|
||||||
grp["modules"] = mods
|
grp["modules"] = mods
|
||||||
grp["module_ids"] = [m["id"] for m in 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())
|
res = list(groups.values())
|
||||||
def sort_key(item: dict) -> tuple[int, str]:
|
def sort_key(item: dict) -> tuple[int, str]:
|
||||||
if "LIFETIME" in item["base_code"]:
|
if "LIFETIME" in item["base_code"]:
|
||||||
|
|
@ -139,7 +122,7 @@ class AdminPlanService:
|
||||||
raise ValueError("Plan code cannot be empty.")
|
raise ValueError("Plan code cannot be empty.")
|
||||||
|
|
||||||
existing = (await self.session.execute(
|
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()
|
)).scalar_one_or_none()
|
||||||
if existing:
|
if existing:
|
||||||
raise ValueError(f"Plan code '{base_code}' already exists.")
|
raise ValueError(f"Plan code '{base_code}' already exists.")
|
||||||
|
|
@ -184,22 +167,6 @@ class AdminPlanService:
|
||||||
metadata_json=meta,
|
metadata_json=meta,
|
||||||
)
|
)
|
||||||
self.session.add(usd_plan)
|
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()
|
await self.session.flush()
|
||||||
|
|
||||||
for mid_str in payload.module_ids:
|
for mid_str in payload.module_ids:
|
||||||
|
|
@ -207,82 +174,35 @@ class AdminPlanService:
|
||||||
mid = UUID(mid_str)
|
mid = UUID(mid_str)
|
||||||
self.session.add(AccessPlanModule(plan_id=inr_plan.id, module_id=mid))
|
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=usd_plan.id, module_id=mid))
|
||||||
self.session.add(AccessPlanModule(plan_id=eur_plan.id, module_id=mid))
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
return {
|
return {
|
||||||
"status": "success",
|
"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,
|
"base_code": base_code,
|
||||||
"inr_plan_id": str(inr_plan.id),
|
"inr_plan_id": str(inr_plan.id),
|
||||||
"usd_plan_id": str(usd_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:
|
async def update_pricing(self, plan_code: str, payload: PlanPricingUpdateRequest) -> dict:
|
||||||
base_code = plan_code.strip().upper()
|
base_code = plan_code.strip().upper()
|
||||||
plans = (await self.session.execute(
|
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()
|
)).scalars().all()
|
||||||
if not plans:
|
if not plans:
|
||||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
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:
|
for p in plans:
|
||||||
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
is_usd = p.code.endswith("_USD") or p.currency_code == "USD"
|
||||||
is_eur = p.code.endswith("_EUR") or p.currency_code == "EUR"
|
if is_usd and payload.price_usd is not None:
|
||||||
|
|
||||||
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:
|
|
||||||
p.module_fee = Decimal(str(payload.price_usd))
|
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))
|
p.module_fee = Decimal(str(payload.price_inr))
|
||||||
|
|
||||||
if payload.name:
|
if payload.name:
|
||||||
suffix = " (EUR)" if is_eur else (" (USD)" if is_usd else "")
|
p.name = f"{payload.name} (USD)" if is_usd else payload.name
|
||||||
p.name = f"{payload.name}{suffix}"
|
|
||||||
if payload.description is not None:
|
if payload.description is not None:
|
||||||
p.description = payload.description
|
p.description = payload.description
|
||||||
|
|
||||||
|
|
@ -293,47 +213,19 @@ class AdminPlanService:
|
||||||
meta["heading"] = payload.heading
|
meta["heading"] = payload.heading
|
||||||
if payload.subtitle is not None:
|
if payload.subtitle is not None:
|
||||||
meta["subtitle"] = payload.subtitle
|
meta["subtitle"] = payload.subtitle
|
||||||
if float(p.module_fee or 0) > 0:
|
|
||||||
meta["pricing_status"] = "configured"
|
|
||||||
p.metadata_json = meta
|
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()
|
await self.session.commit()
|
||||||
return {"status": "success", "message": f"Pricing and metadata for plan '{base_code}' updated successfully."}
|
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:
|
async def toggle_status(self, plan_code: str, is_active: bool) -> dict:
|
||||||
base_code = plan_code.strip().upper()
|
base_code = plan_code.strip().upper()
|
||||||
plans = (await self.session.execute(
|
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()
|
)).scalars().all()
|
||||||
if not plans:
|
if not plans:
|
||||||
raise LookupError(f"No access plans found matching code '{base_code}'.")
|
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:
|
for p in plans:
|
||||||
p.is_active = is_active
|
p.is_active = is_active
|
||||||
await self.session.commit()
|
await self.session.commit()
|
||||||
|
|
@ -342,67 +234,3 @@ class AdminPlanService:
|
||||||
"message": f"Plan '{base_code}' has been {'activated' if is_active else 'deactivated'}.",
|
"message": f"Plan '{base_code}' has been {'activated' if is_active else 'deactivated'}.",
|
||||||
"is_active": is_active,
|
"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
|
|
||||||
|
|
|
||||||
|
|
@ -46,23 +46,17 @@ class AdminReportService:
|
||||||
for uid, rname in ur_rows:
|
for uid, rname in ur_rows:
|
||||||
user_roles_map.setdefault(uid, []).append(rname)
|
user_roles_map.setdefault(uid, []).append(rname)
|
||||||
|
|
||||||
# Preload spend and orders count by currency
|
# Preload spend and orders count
|
||||||
tx_summary_rows = (await self.session.execute(
|
tx_summary_rows = (await self.session.execute(
|
||||||
select(
|
select(
|
||||||
PaymentTransaction.user_id,
|
PaymentTransaction.user_id,
|
||||||
PaymentTransaction.currency,
|
|
||||||
func.count(PaymentTransaction.id),
|
func.count(PaymentTransaction.id),
|
||||||
func.coalesce(func.sum(PaymentTransaction.amount), 0)
|
func.coalesce(func.sum(PaymentTransaction.amount), 0)
|
||||||
)
|
)
|
||||||
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
|
.where(PaymentTransaction.status == PaymentStatus.SUCCESS)
|
||||||
.group_by(PaymentTransaction.user_id, PaymentTransaction.currency)
|
.group_by(PaymentTransaction.user_id)
|
||||||
)).all()
|
)).all()
|
||||||
tx_orders: dict[any, int] = {}
|
tx_summary = {uid: (count, float(total)) for uid, count, total in tx_summary_rows}
|
||||||
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
|
# Preload active subscriptions count
|
||||||
sub_count_rows = (await self.session.execute(
|
sub_count_rows = (await self.session.execute(
|
||||||
|
|
@ -84,20 +78,14 @@ class AdminReportService:
|
||||||
"Account Type",
|
"Account Type",
|
||||||
"Status",
|
"Status",
|
||||||
"Total Orders",
|
"Total Orders",
|
||||||
"Lifetime Spend (INR)",
|
"Lifetime Spend",
|
||||||
"Lifetime Spend (USD)",
|
|
||||||
"Lifetime Spend (EUR)",
|
|
||||||
"Active Subscriptions",
|
"Active Subscriptions",
|
||||||
"Registration Date",
|
"Registration Date",
|
||||||
])
|
])
|
||||||
for u in users:
|
for u in users:
|
||||||
user_roles = user_roles_map.get(u.id, [])
|
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"
|
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)
|
orders_count, total_spend = tx_summary.get(u.id, (0, 0.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)
|
active_subs = sub_count_map.get(u.id, 0)
|
||||||
status_label = "Active" if u.is_active else "Suspended"
|
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 ""
|
reg_date = u.created_at.strftime("%Y-%m-%d %H:%M:%S") if u.created_at else ""
|
||||||
|
|
@ -111,9 +99,7 @@ class AdminReportService:
|
||||||
user_type,
|
user_type,
|
||||||
status_label,
|
status_label,
|
||||||
orders_count,
|
orders_count,
|
||||||
f"{spend_inr:.2f}",
|
f"{total_spend:.2f}",
|
||||||
f"{spend_usd:.2f}",
|
|
||||||
f"{spend_eur:.2f}",
|
|
||||||
active_subs,
|
active_subs,
|
||||||
reg_date,
|
reg_date,
|
||||||
])
|
])
|
||||||
|
|
@ -197,10 +183,8 @@ class AdminReportService:
|
||||||
"Customer Name",
|
"Customer Name",
|
||||||
"Customer Email",
|
"Customer Email",
|
||||||
"Phone Number",
|
"Phone Number",
|
||||||
"Customer Country",
|
|
||||||
"Plan Code",
|
"Plan Code",
|
||||||
"Plan Name",
|
"Plan Name",
|
||||||
"Plan Currency",
|
|
||||||
"Billing Cycle",
|
"Billing Cycle",
|
||||||
"Status",
|
"Status",
|
||||||
"Days Remaining",
|
"Days Remaining",
|
||||||
|
|
@ -218,17 +202,6 @@ class AdminReportService:
|
||||||
else:
|
else:
|
||||||
billing_cycle = "Yearly"
|
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"
|
days_remaining = "Lifetime"
|
||||||
if s.expires_at:
|
if s.expires_at:
|
||||||
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
|
exp = s.expires_at.replace(tzinfo=timezone.utc) if s.expires_at.tzinfo is None else s.expires_at
|
||||||
|
|
@ -247,10 +220,8 @@ class AdminReportService:
|
||||||
u.display_name if u else "",
|
u.display_name if u else "",
|
||||||
u.email if u else "",
|
u.email if u else "",
|
||||||
u.phone_number if u else "",
|
u.phone_number if u else "",
|
||||||
u.country if u else "",
|
|
||||||
p.code if p else "",
|
p.code if p else "",
|
||||||
p.name if p else "",
|
p.name if p else "",
|
||||||
plan_curr,
|
|
||||||
billing_cycle,
|
billing_cycle,
|
||||||
getattr(s.status, "value", s.status),
|
getattr(s.status, "value", s.status),
|
||||||
days_remaining,
|
days_remaining,
|
||||||
|
|
@ -279,16 +250,10 @@ class AdminReportService:
|
||||||
"Coupon Code",
|
"Coupon Code",
|
||||||
"Category",
|
"Category",
|
||||||
"Description",
|
"Description",
|
||||||
|
"Discount Value",
|
||||||
"Discount Type",
|
"Discount Type",
|
||||||
"Discount (INR)",
|
"Max Cap",
|
||||||
"Discount (USD)",
|
"Min Purchase",
|
||||||
"Discount (EUR)",
|
|
||||||
"Max Cap (INR)",
|
|
||||||
"Max Cap (USD)",
|
|
||||||
"Max Cap (EUR)",
|
|
||||||
"Min Purchase (INR)",
|
|
||||||
"Min Purchase (USD)",
|
|
||||||
"Min Purchase (EUR)",
|
|
||||||
"Usage Count",
|
"Usage Count",
|
||||||
"Usage Limit",
|
"Usage Limit",
|
||||||
"Remaining Uses",
|
"Remaining Uses",
|
||||||
|
|
@ -297,49 +262,10 @@ class AdminReportService:
|
||||||
"End Date",
|
"End Date",
|
||||||
])
|
])
|
||||||
for c in coupons:
|
for c in coupons:
|
||||||
metadata = getattr(c, "metadata_json", {}) if hasattr(c, "metadata_json") else {}
|
val = float(c.value) if c.value is not None else 0.0
|
||||||
if not isinstance(metadata, dict):
|
disc_val = f"{val:.2f}%" if c.discount_type == "percentage" else f"{val:.2f}"
|
||||||
metadata = {}
|
max_cap = f"{float(c.max_discount_limit):.2f}" if c.max_discount_limit else "None"
|
||||||
c_values = metadata.get("currency_values") or {}
|
min_spend = f"{float(c.min_purchase_amount):.2f}" if c.min_purchase_amount else "0.00"
|
||||||
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_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"
|
usage_limit_str = str(c.usage_limit) if c.usage_limit else "Unlimited"
|
||||||
|
|
||||||
|
|
@ -356,7 +282,7 @@ class AdminReportService:
|
||||||
elif c.end_date and c.end_date < now:
|
elif c.end_date and c.end_date < now:
|
||||||
schedule_status = "Expired"
|
schedule_status = "Expired"
|
||||||
elif c.usage_limit and usage_count >= c.usage_limit:
|
elif c.usage_limit and usage_count >= c.usage_limit:
|
||||||
schedule_status = "Fully Redeemed"
|
schedule_status = "Exhausted"
|
||||||
|
|
||||||
start_str = c.start_date.strftime("%Y-%m-%d") if c.start_date else "Immediate"
|
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"
|
end_str = c.end_date.strftime("%Y-%m-%d") if c.end_date else "No Expiry"
|
||||||
|
|
@ -365,16 +291,10 @@ class AdminReportService:
|
||||||
c.code,
|
c.code,
|
||||||
(c.coupon_category or "general").title(),
|
(c.coupon_category or "general").title(),
|
||||||
c.description or "",
|
c.description or "",
|
||||||
|
disc_val,
|
||||||
(c.discount_type or "").capitalize(),
|
(c.discount_type or "").capitalize(),
|
||||||
disc_inr,
|
max_cap,
|
||||||
disc_usd,
|
min_spend,
|
||||||
disc_eur,
|
|
||||||
cap_inr,
|
|
||||||
cap_usd,
|
|
||||||
cap_eur,
|
|
||||||
min_inr,
|
|
||||||
min_usd,
|
|
||||||
min_eur,
|
|
||||||
usage_count,
|
usage_count,
|
||||||
usage_limit_str,
|
usage_limit_str,
|
||||||
remaining_str,
|
remaining_str,
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from sqlalchemy import func, or_, select, update
|
from sqlalchemy import select, update
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.db.models import (
|
from app.db.models import (
|
||||||
|
|
@ -42,54 +42,15 @@ class AuthRepository:
|
||||||
self,
|
self,
|
||||||
phone_number: str,
|
phone_number: str,
|
||||||
) -> AppUser | None:
|
) -> AppUser | None:
|
||||||
|
# Preserves the existing auth API's LIKE lookup semantics.
|
||||||
result = await self._session.execute(
|
result = await self._session.execute(
|
||||||
select(AppUser)
|
select(AppUser)
|
||||||
.where(AppUser.phone_number == phone_number)
|
.where(AppUser.phone_number.like(f"%{phone_number}%"))
|
||||||
.order_by(AppUser.id.asc())
|
.order_by(AppUser.id.asc())
|
||||||
.limit(1)
|
.limit(1)
|
||||||
)
|
)
|
||||||
return result.scalar_one_or_none()
|
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(
|
async def create_user(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|
|
||||||
|
|
@ -19,40 +19,7 @@ from .errors import InvalidEmailError, InvalidTokenError, WeakPasswordError
|
||||||
DEFAULT_JWT_SECRET = "panacea-secret-key-for-jwt-token-generation"
|
DEFAULT_JWT_SECRET = "panacea-secret-key-for-jwt-token-generation"
|
||||||
JWT_SECRET = os.getenv("JWT_SECRET", DEFAULT_JWT_SECRET)
|
JWT_SECRET = os.getenv("JWT_SECRET", DEFAULT_JWT_SECRET)
|
||||||
JWT_TTL_SECONDS = int(os.getenv("JWT_TTL_SECONDS", str(86400 * 7)))
|
JWT_TTL_SECONDS = int(os.getenv("JWT_TTL_SECONDS", str(86400 * 7)))
|
||||||
EMAIL_REGEX = re.compile(
|
EMAIL_REGEX = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
|
||||||
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",
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
def base64url_encode(data: bytes) -> str:
|
def base64url_encode(data: bytes) -> str:
|
||||||
|
|
@ -77,86 +44,6 @@ def normalize_phone_number(value: str | None) -> str:
|
||||||
return value.strip() if value else ""
|
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:
|
def validate_password_strength(password: str) -> None:
|
||||||
if len(password) < 8:
|
if len(password) < 8:
|
||||||
raise WeakPasswordError(
|
raise WeakPasswordError(
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,6 @@ from uuid import UUID
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
from app.db.models import AppUser
|
|
||||||
|
|
||||||
from .errors import (
|
from .errors import (
|
||||||
CurrentPasswordIncorrectError,
|
CurrentPasswordIncorrectError,
|
||||||
InvalidCredentialsError,
|
InvalidCredentialsError,
|
||||||
|
|
@ -37,13 +35,10 @@ from .schema import (
|
||||||
UserRegisterRequest,
|
UserRegisterRequest,
|
||||||
)
|
)
|
||||||
from .security import (
|
from .security import (
|
||||||
build_phone_lookup_variants,
|
|
||||||
create_access_token,
|
create_access_token,
|
||||||
decode_access_token,
|
decode_access_token,
|
||||||
extract_phone_digits,
|
|
||||||
generate_otp_code,
|
generate_otp_code,
|
||||||
hash_password,
|
hash_password,
|
||||||
matches_login_phone,
|
|
||||||
normalize_email,
|
normalize_email,
|
||||||
normalize_phone_number,
|
normalize_phone_number,
|
||||||
validate_password_strength,
|
validate_password_strength,
|
||||||
|
|
@ -140,75 +135,16 @@ 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(
|
async def login(
|
||||||
self,
|
self,
|
||||||
request: UserLoginRequest,
|
request: UserLoginRequest,
|
||||||
) -> AuthTokenResponse:
|
) -> AuthTokenResponse:
|
||||||
if request.phone_number:
|
if request.phone_number:
|
||||||
user = await self._authenticate_phone_login(
|
phone = normalize_phone_number(request.phone_number)
|
||||||
request.phone_number,
|
user = await self.repository.get_user_by_phone(phone)
|
||||||
request.password,
|
if user is None:
|
||||||
|
raise UserNotFoundError(
|
||||||
|
"No account found with this phone number. Please sign up first."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
assert request.email is not None
|
assert request.email is not None
|
||||||
|
|
@ -218,7 +154,14 @@ class AuthService:
|
||||||
raise UserNotFoundError(
|
raise UserNotFoundError(
|
||||||
"No account found with this email address. Please sign up first."
|
"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)
|
roles = await self.repository.get_user_roles(user.id)
|
||||||
if not roles:
|
if not roles:
|
||||||
|
|
@ -279,13 +222,6 @@ class AuthService:
|
||||||
)
|
)
|
||||||
country = request.country.strip() if request.country else None
|
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 = await self.repository.update_profile(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
display_name=full_name,
|
display_name=full_name,
|
||||||
|
|
@ -295,24 +231,6 @@ class AuthService:
|
||||||
if user is None:
|
if user is None:
|
||||||
raise UserNotFoundError("User not found.")
|
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)
|
roles = await self.repository.get_user_roles(user.id)
|
||||||
if not roles:
|
if not roles:
|
||||||
roles = [PRACTITIONER_ROLE]
|
roles = [PRACTITIONER_ROLE]
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,10 @@ from __future__ import annotations
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import func, select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.enums import EntitlementStatus, SubscriptionStatus
|
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, AccessPlanModule, Coupon, Module, UserEntitlement, UserSubscription
|
||||||
from app.features.payments.pricing import PricingCoupon, PricingItem
|
from app.features.payments.pricing import PricingCoupon, PricingItem
|
||||||
|
|
||||||
class CartRepository:
|
class CartRepository:
|
||||||
|
|
@ -46,8 +46,8 @@ class CartRepository:
|
||||||
if len(parts) == 2 and parts[1] in known_currencies:
|
if len(parts) == 2 and parts[1] in known_currencies:
|
||||||
base = parts[0]
|
base = parts[0]
|
||||||
|
|
||||||
for cand in [f"{base}_{curr}", f"{base}_USD" if curr == "EUR" else None, code, base]:
|
for cand in [f"{base}_{curr}", code, base]:
|
||||||
if cand and cand not in cands:
|
if cand not in cands:
|
||||||
cands.append(cand)
|
cands.append(cand)
|
||||||
code_candidates_map[code] = cands
|
code_candidates_map[code] = cands
|
||||||
candidates.update(cands)
|
candidates.update(cands)
|
||||||
|
|
@ -81,15 +81,12 @@ class CartRepository:
|
||||||
continue
|
continue
|
||||||
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
|
fee = plan.total_fee if plan.total_fee is not None else plan.module_fee
|
||||||
plan_curr = plan.currency_code.upper()
|
plan_curr = plan.currency_code.upper()
|
||||||
if plan_curr == "INR" and curr in {"USD", "EUR"}:
|
if plan_curr == "INR" and curr == "USD":
|
||||||
matches[code] = (plan, max(Decimal("1.00"), (Decimal(str(fee)) / Decimal("80")).quantize(Decimal("1.00"))))
|
matches[code] = (plan, max(Decimal("1.00"), (Decimal(str(fee)) / Decimal("80")).quantize(Decimal("1.00"))))
|
||||||
break
|
break
|
||||||
elif plan_curr in {"USD", "EUR"} and curr == "INR":
|
elif plan_curr == "USD" and curr == "INR":
|
||||||
matches[code] = (plan, (Decimal(str(fee)) * Decimal("80")).quantize(Decimal("1.00")))
|
matches[code] = (plan, (Decimal(str(fee)) * Decimal("80")).quantize(Decimal("1.00")))
|
||||||
break
|
break
|
||||||
elif plan_curr in {"USD", "EUR"} and curr in {"USD", "EUR"}:
|
|
||||||
matches[code] = (plan, Decimal(str(fee)))
|
|
||||||
break
|
|
||||||
elif fee is not None:
|
elif fee is not None:
|
||||||
matches[code] = (plan, Decimal(str(fee)))
|
matches[code] = (plan, Decimal(str(fee)))
|
||||||
break
|
break
|
||||||
|
|
@ -151,7 +148,7 @@ class CartRepository:
|
||||||
))
|
))
|
||||||
return items
|
return items
|
||||||
|
|
||||||
async def get_coupon(self, code: str | None, currency: str, user_id: UUID | None = None) -> tuple[PricingCoupon | None, str | None]:
|
async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
|
||||||
if not code or not code.strip():
|
if not code or not code.strip():
|
||||||
return None, None
|
return None, None
|
||||||
clean_code = code.strip().upper()
|
clean_code = code.strip().upper()
|
||||||
|
|
@ -169,61 +166,31 @@ class CartRepository:
|
||||||
return None, "This coupon code has expired."
|
return None, "This coupon code has expired."
|
||||||
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
|
if coupon.usage_limit > 0 and coupon.usage_count >= coupon.usage_limit:
|
||||||
return None, "Coupon usage limit reached."
|
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."
|
|
||||||
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
|
metadata = getattr(coupon, "metadata_json", {}) if hasattr(coupon, "metadata_json") else {}
|
||||||
value = Decimal(coupon.value)
|
value = Decimal(coupon.value)
|
||||||
if coupon.discount_type in {"flat", "flat_amount"}:
|
if coupon.discount_type in {"flat", "flat_amount"}:
|
||||||
currency_values = metadata.get("currency_values") if isinstance(metadata, dict) else None
|
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()]))
|
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))
|
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()
|
app_plan_ids: set[str] = set()
|
||||||
if coupon.applicable_plan_ids:
|
if coupon.applicable_plan_ids:
|
||||||
for pid in coupon.applicable_plan_ids:
|
for pid in coupon.applicable_plan_ids:
|
||||||
app_plan_ids.add(str(pid))
|
app_plan_ids.add(str(pid))
|
||||||
# Include paired currency versions (e.g. LIFETIME_ALL, LIFETIME_ALL_USD, LIFETIME_ALL_EUR)
|
# Include paired currency versions (e.g. LIFETIME_ALL and LIFETIME_ALL_USD)
|
||||||
p_rows = (await self.session.execute(
|
p_rows = (await self.session.execute(
|
||||||
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
|
select(AccessPlan.code).where(AccessPlan.id.in_(coupon.applicable_plan_ids))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
base_codes: set[str] = set()
|
base_codes: set[str] = set()
|
||||||
for c in p_rows:
|
for c in p_rows:
|
||||||
code_up = c.upper()
|
code_up = c.upper()
|
||||||
if code_up.endswith("_USD"):
|
base_codes.add(code_up[:-4] if code_up.endswith("_USD") else code_up)
|
||||||
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:
|
if base_codes:
|
||||||
sibling_codes: set[str] = set()
|
sibling_codes: set[str] = set()
|
||||||
for bc in base_codes:
|
for bc in base_codes:
|
||||||
sibling_codes.add(bc)
|
sibling_codes.add(bc)
|
||||||
sibling_codes.add(f"{bc}_USD")
|
sibling_codes.add(f"{bc}_USD")
|
||||||
sibling_codes.add(f"{bc}_EUR")
|
|
||||||
sibling_rows = (await self.session.execute(
|
sibling_rows = (await self.session.execute(
|
||||||
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
|
select(AccessPlan.id).where(AccessPlan.code.in_(sibling_codes))
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
|
|
@ -238,7 +205,7 @@ class CartRepository:
|
||||||
discount_type=coupon.discount_type,
|
discount_type=coupon.discount_type,
|
||||||
value=value,
|
value=value,
|
||||||
description=coupon.description,
|
description=coupon.description,
|
||||||
max_discount_limit=max_cap,
|
max_discount_limit=Decimal(coupon.max_discount_limit or 0),
|
||||||
min_purchase_amount=min_spend,
|
min_purchase_amount=min_spend,
|
||||||
applicable_plan_ids=tuple(app_plan_ids),
|
applicable_plan_ids=tuple(app_plan_ids),
|
||||||
applicable_module_ids=app_mod_ids,
|
applicable_module_ids=app_mod_ids,
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ class CartService:
|
||||||
resolved = {i.code.upper() for i in items}
|
resolved = {i.code.upper() for i in items}
|
||||||
missing = [c for c in request.cart_item_codes if c.strip().upper() not in resolved]
|
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)}")
|
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)
|
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency)
|
||||||
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
||||||
if request.owned_category_names:
|
if request.owned_category_names:
|
||||||
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
owned = list(set(owned + [c for c in request.owned_category_names if c]))
|
||||||
|
|
|
||||||
|
|
@ -13,42 +13,13 @@ 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 generate_next_invoice_number, get_razorpay_service, record_coupon_redemption
|
||||||
from .schema import CheckoutOrderRequest, CheckoutOrderResponse, CheckoutVerifyRequest
|
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:
|
class CheckoutService:
|
||||||
def __init__(self, *, session: AsyncSession, cart_repository: CartRepository) -> None:
|
def __init__(self, *, session: AsyncSession, cart_repository: CartRepository) -> None:
|
||||||
self.session = session
|
self.session = session
|
||||||
self.cart_service = CartService(cart_repository)
|
self.cart_service = CartService(cart_repository)
|
||||||
|
|
||||||
async def create_order(self, user: AppUser, request: CheckoutOrderRequest) -> CheckoutOrderResponse:
|
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)
|
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:
|
if calc.grand_total <= 0:
|
||||||
raise ValueError("Grand total must be greater than zero to checkout.")
|
raise ValueError("Grand total must be greater than zero to checkout.")
|
||||||
rzp = get_razorpay_service()
|
rzp = get_razorpay_service()
|
||||||
|
|
@ -59,14 +30,6 @@ class CheckoutService:
|
||||||
await self.session.flush()
|
await self.session.flush()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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]}"
|
receipt = f"rcpt_{uuid.uuid4().hex[:12]}"
|
||||||
applied_coupon_code = (
|
applied_coupon_code = (
|
||||||
request.coupon_code.strip().upper()
|
request.coupon_code.strip().upper()
|
||||||
|
|
@ -174,12 +137,6 @@ class CheckoutService:
|
||||||
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
||||||
)).scalar_one_or_none() if coupon_code else None
|
)).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(
|
invoice, invoice_url = await self._create_invoice(
|
||||||
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
|
rzp, transaction, profile, payment, plan_names, meta, applied_coupon_id=coupon.id if coupon else None
|
||||||
)
|
)
|
||||||
|
|
@ -201,19 +158,6 @@ class CheckoutService:
|
||||||
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
stmt = stmt.where(UserBillingProfile.is_default.is_(True))
|
||||||
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
profile = (await self.session.execute(stmt)).scalar_one_or_none()
|
||||||
if profile:
|
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
|
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)
|
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)
|
self.session.add(profile)
|
||||||
|
|
@ -232,31 +176,8 @@ class CheckoutService:
|
||||||
) -> tuple[Invoice, str | None]:
|
) -> tuple[Invoice, str | None]:
|
||||||
currency = tx.currency.upper()
|
currency = tx.currency.upper()
|
||||||
inv_number = await generate_next_invoice_number(self.session)
|
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"
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
cust_data: dict[str, Any] = {
|
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}})
|
||||||
"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},
|
|
||||||
})
|
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
# Always use internal branded Acupedia Tax Invoice view URL
|
# Always use internal branded Acupedia Tax Invoice view URL
|
||||||
|
|
@ -265,20 +186,12 @@ class CheckoutService:
|
||||||
discount = Decimal(str(meta.get("total_discounts", 0)))
|
discount = Decimal(str(meta.get("total_discounts", 0)))
|
||||||
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
taxable = Decimal(str(meta.get("taxable_amount", 0)))
|
||||||
gst = Decimal(str(meta.get("gst_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(
|
invoice = Invoice(
|
||||||
payment_transaction_id=tx.id,
|
payment_transaction_id=tx.id,
|
||||||
invoice_number=inv_number,
|
invoice_number=inv_number,
|
||||||
billing_name=profile.billing_name,
|
billing_name=profile.billing_name,
|
||||||
billing_email=profile.billing_email,
|
billing_email=profile.billing_email,
|
||||||
billing_address=final_billing_address,
|
billing_address=f"{profile.address_line1}, {profile.city}, {profile.state}, {profile.postal_code}, {profile.country}",
|
||||||
gstin=profile.gstin,
|
gstin=profile.gstin,
|
||||||
billing_profile_id=profile.id,
|
billing_profile_id=profile.id,
|
||||||
applied_coupon_id=applied_coupon_id,
|
applied_coupon_id=applied_coupon_id,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ from datetime import datetime
|
||||||
|
|
||||||
from sqlalchemy import select, bindparam, text, func
|
from sqlalchemy import select, bindparam, text, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.orm import aliased
|
|
||||||
|
|
||||||
from app.db.enums import ModuleStatus, RecordStatus
|
from app.db.enums import ModuleStatus, RecordStatus
|
||||||
|
|
||||||
|
|
@ -67,21 +66,6 @@ from .schema import (
|
||||||
|
|
||||||
_SHORT_TEMPLATE_RE = re.compile(r"^CT\d+$", re.IGNORECASE)
|
_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 = {
|
_SYSTEM_SORT_FIELDS = {
|
||||||
"module_sort_order",
|
"module_sort_order",
|
||||||
"title",
|
"title",
|
||||||
|
|
@ -404,10 +388,11 @@ class ContentRepository:
|
||||||
if include_draft
|
if include_draft
|
||||||
else [RecordStatus.PUBLISHED]
|
else [RecordStatus.PUBLISHED]
|
||||||
),
|
),
|
||||||
|
Module.is_active.is_(True),
|
||||||
Module.status.in_(
|
Module.status.in_(
|
||||||
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE]
|
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
|
||||||
if include_draft
|
if include_draft
|
||||||
else [ModuleStatus.ACTIVE, ModuleStatus.INACTIVE]
|
else [ModuleStatus.ACTIVE]
|
||||||
),
|
),
|
||||||
AttributeDefinitionSet.is_active.is_(True),
|
AttributeDefinitionSet.is_active.is_(True),
|
||||||
)
|
)
|
||||||
|
|
@ -477,184 +462,6 @@ class ContentRepository:
|
||||||
|
|
||||||
return resolved
|
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(
|
async def get_content_by_id(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ from enum import StrEnum
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
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
|
from app.db.enums import ModuleStatus, RecordStatus
|
||||||
|
|
||||||
|
|
@ -84,17 +84,10 @@ class ModuleResponse(BaseModel):
|
||||||
serialization_alias="metadata",
|
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
|
created_by: UUID | None = None
|
||||||
updated_by: UUID | None = None
|
updated_by: UUID | None = None
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
plan_code: str | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class ModuleListResponse(BaseModel):
|
class ModuleListResponse(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -125,34 +125,12 @@ class ContentService:
|
||||||
session=self.session,
|
session=self.session,
|
||||||
include_draft=preview,
|
include_draft=preview,
|
||||||
)
|
)
|
||||||
plan_map: dict[UUID, str] = {}
|
return ModuleListResponse(
|
||||||
if modules:
|
modules=[
|
||||||
from app.db.enums import PlanType
|
ModuleResponse.model_validate(module)
|
||||||
from app.db.models import AccessPlan, AccessPlanModule
|
for module in modules
|
||||||
|
]
|
||||||
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)
|
|
||||||
|
|
||||||
if preview:
|
if preview:
|
||||||
return await loader()
|
return await loader()
|
||||||
|
|
@ -1359,123 +1337,20 @@ class ContentService:
|
||||||
self._collect_content_reference_lookups(payload, references)
|
self._collect_content_reference_lookups(payload, references)
|
||||||
|
|
||||||
if not references:
|
if not references:
|
||||||
hydrated = [
|
return [
|
||||||
self._hydrate_reference_value(payload, {})
|
self._hydrate_reference_value(payload, {})
|
||||||
for payload in payloads
|
for payload in payloads
|
||||||
]
|
]
|
||||||
else:
|
|
||||||
resolved = await self.repository.resolve_content_reference_targets(
|
resolved = await self.repository.resolve_content_reference_targets(
|
||||||
references=references,
|
references=references,
|
||||||
include_draft=preview,
|
include_draft=preview,
|
||||||
)
|
)
|
||||||
hydrated = [
|
return [
|
||||||
self._hydrate_reference_value(payload, resolved)
|
self._hydrate_reference_value(payload, resolved)
|
||||||
for payload in payloads
|
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
|
@classmethod
|
||||||
def _extract_referenced_content_items(
|
def _extract_referenced_content_items(
|
||||||
cls,
|
cls,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from sqlalchemy import or_, select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from app.db.models import Coupon, CouponRedemption
|
from app.db.models import Coupon, CouponRedemption
|
||||||
|
|
||||||
|
|
@ -15,7 +15,7 @@ async def record_coupon_redemption(
|
||||||
user_id: UUID,
|
user_id: UUID,
|
||||||
invoice_id: UUID | None = None,
|
invoice_id: UUID | None = None,
|
||||||
) -> Coupon | None:
|
) -> Coupon | None:
|
||||||
"""Increment coupon usage_count and record a per-invoice CouponRedemption entry."""
|
"""Increment coupon usage_count and record CouponRedemption entry."""
|
||||||
if coupon is None:
|
if coupon is None:
|
||||||
if not coupon_code or not str(coupon_code).strip():
|
if not coupon_code or not str(coupon_code).strip():
|
||||||
return None
|
return None
|
||||||
|
|
@ -27,38 +27,24 @@ async def record_coupon_redemption(
|
||||||
if not coupon:
|
if not coupon:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if invoice_id is not None:
|
coupon.usage_count = (coupon.usage_count or 0) + 1
|
||||||
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(
|
existing = (await session.execute(
|
||||||
select(CouponRedemption)
|
select(CouponRedemption).where(
|
||||||
.where(
|
|
||||||
CouponRedemption.coupon_id == coupon.id,
|
CouponRedemption.coupon_id == coupon.id,
|
||||||
CouponRedemption.user_id == user_id,
|
CouponRedemption.user_id == user_id,
|
||||||
existing_filter,
|
|
||||||
)
|
)
|
||||||
.limit(1)
|
|
||||||
)).scalar_one_or_none()
|
)).scalar_one_or_none()
|
||||||
|
|
||||||
if existing:
|
if not 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(
|
session.add(CouponRedemption(
|
||||||
coupon_id=coupon.id,
|
coupon_id=coupon.id,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
invoice_id=invoice_id,
|
invoice_id=invoice_id,
|
||||||
redeemed_at=datetime.now(timezone.utc),
|
redeemed_at=datetime.now(timezone.utc),
|
||||||
))
|
))
|
||||||
|
elif invoice_id and not existing.invoice_id:
|
||||||
|
existing.invoice_id = invoice_id
|
||||||
|
|
||||||
return coupon
|
return coupon
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from app.db.session import get_db_session
|
from app.db.session import get_db_session
|
||||||
from app.db.models import AccessPlan, AccessPlanModule, Module
|
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"])
|
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()
|
all_plans = plans_q.scalars().all()
|
||||||
|
|
||||||
plan_mods_q = await session.execute(
|
plan_mods_q = await session.execute(
|
||||||
select(
|
select(AccessPlanModule.plan_id, Module.slug, Module.name)
|
||||||
AccessPlanModule.plan_id,
|
|
||||||
Module.code,
|
|
||||||
Module.slug,
|
|
||||||
Module.name,
|
|
||||||
Module.description,
|
|
||||||
Module.metadata_json,
|
|
||||||
)
|
|
||||||
.join(Module, AccessPlanModule.module_id == Module.id)
|
.join(Module, AccessPlanModule.module_id == Module.id)
|
||||||
.where(Module.is_active.is_(True))
|
.where(Module.is_active.is_(True))
|
||||||
)
|
)
|
||||||
mod_map: dict[str, list[dict[str, Any]]] = {}
|
mod_map: dict[str, list[dict[str, str]]] = {}
|
||||||
for pid, m_code, slug, name, desc, m_meta in plan_mods_q.all():
|
for pid, slug, name in plan_mods_q.all():
|
||||||
pid_str = str(pid)
|
pid_str = str(pid)
|
||||||
if pid_str not in mod_map:
|
if pid_str not in mod_map:
|
||||||
mod_map[pid_str] = []
|
mod_map[pid_str] = []
|
||||||
meta_dict = m_meta or {}
|
mod_map[pid_str].append({"slug": slug, "name": name})
|
||||||
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"]))
|
|
||||||
|
|
||||||
groups: dict[str, dict[str, Any]] = {}
|
groups: dict[str, dict[str, Any]] = {}
|
||||||
for p in all_plans:
|
for p in all_plans:
|
||||||
code = p.code
|
code = p.code
|
||||||
is_usd = code.endswith("_USD") or p.currency_code == "USD"
|
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") else code
|
||||||
base_code = code[:-4] if (code.endswith("_USD") or code.endswith("_EUR")) else code
|
|
||||||
|
|
||||||
pid_str = str(p.id)
|
pid_str = str(p.id)
|
||||||
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
fee = float(p.total_fee if p.total_fee is not None else p.module_fee)
|
||||||
|
|
||||||
meta = p.metadata_json or {}
|
meta = p.metadata_json or {}
|
||||||
if base_code not in groups:
|
if base_code not in groups:
|
||||||
clean_name = (
|
|
||||||
p.name.replace(" (USD)", "")
|
|
||||||
.replace(" - USD", "")
|
|
||||||
.replace(" (EUR)", "")
|
|
||||||
.replace(" - EUR", "")
|
|
||||||
)
|
|
||||||
groups[base_code] = {
|
groups[base_code] = {
|
||||||
"code": base_code,
|
"code": base_code,
|
||||||
"name": clean_name,
|
"name": p.name.replace(" (USD)", "").replace(" - USD", ""),
|
||||||
"description": p.description or "",
|
"description": p.description or "",
|
||||||
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
"plan_type": getattr(p.plan_type, "value", p.plan_type),
|
||||||
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
"billing_period": getattr(p.billing_period, "value", p.billing_period),
|
||||||
"price_inr": 0.0,
|
"price_inr": 0.0,
|
||||||
"price_usd": 0.0,
|
"price_usd": 0.0,
|
||||||
"price_eur": 0.0,
|
|
||||||
"is_active": p.is_active,
|
"is_active": p.is_active,
|
||||||
"badge_text": meta.get("badge_text"),
|
"badge_text": meta.get("badge_text"),
|
||||||
"heading": meta.get("heading"),
|
"heading": meta.get("heading"),
|
||||||
|
|
@ -89,17 +58,11 @@ async def get_public_plans(session: AsyncSession = Depends(get_db_session)) -> l
|
||||||
"modules": [],
|
"modules": [],
|
||||||
"module_slugs": [],
|
"module_slugs": [],
|
||||||
"is_featured": meta.get("is_featured", False),
|
"is_featured": meta.get("is_featured", False),
|
||||||
"pricing_status": meta.get("pricing_status"),
|
|
||||||
"color": meta.get("color"),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
grp = groups[base_code]
|
grp = groups[base_code]
|
||||||
if is_usd:
|
if is_usd:
|
||||||
grp["price_usd"] = fee
|
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:
|
else:
|
||||||
grp["price_inr"] = fee
|
grp["price_inr"] = fee
|
||||||
grp["name"] = p.name
|
grp["name"] = p.name
|
||||||
|
|
|
||||||
|
|
@ -163,14 +163,12 @@ class SearchRepository:
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
effective_scope = scope or SearchScope()
|
effective_scope = scope or SearchScope()
|
||||||
params: dict[str, Any] = {}
|
params: dict[str, Any] = {}
|
||||||
|
where = ["is_active = true", "status = 'active'"]
|
||||||
if effective_scope.module_codes:
|
if effective_scope.module_codes:
|
||||||
where = ["status in ('active', 'inactive')"]
|
|
||||||
params["capability_module_codes"] = [
|
params["capability_module_codes"] = [
|
||||||
code.strip().lower() for code in effective_scope.module_codes if code and code.strip()
|
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[]))")
|
where.append("code = any(cast(:capability_module_codes as text[]))")
|
||||||
else:
|
|
||||||
where = ["is_active = true", "status = 'active'"]
|
|
||||||
|
|
||||||
result = await self.session.execute(
|
result = await self.session.execute(
|
||||||
text(
|
text(
|
||||||
|
|
@ -542,7 +540,7 @@ class SearchRepository:
|
||||||
join {self.schema}.modules scope_m on scope_m.id = scope_mc.module_id
|
join {self.schema}.modules scope_m on scope_m.id = scope_mc.module_id
|
||||||
where scope_mc.content_id = {ci_alias}.id
|
where scope_mc.content_id = {ci_alias}.id
|
||||||
and scope_m.code = any(cast(:scope_module_codes as text[]))
|
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:
|
if scope.content_kinds:
|
||||||
|
|
@ -696,8 +694,6 @@ class SearchRepository:
|
||||||
|
|
||||||
tok_conditions: list[str] = []
|
tok_conditions: list[str] = []
|
||||||
tok_score_parts: 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]):
|
for idx, tok in enumerate(list(stem_tokens)[:8]):
|
||||||
p_name = f"tok_{idx}"
|
p_name = f"tok_{idx}"
|
||||||
params[p_name] = f"%{tok}%"
|
params[p_name] = f"%{tok}%"
|
||||||
|
|
@ -705,7 +701,7 @@ class SearchRepository:
|
||||||
f"(ci.title ilike :{p_name} or csd.search_text ilike :{p_name} or exists ("
|
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"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"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"where mc_tok.content_id = ci.id and m_tok.is_active = true and ("
|
||||||
f"m_tok.name ilike :{p_name} or m_tok.code ilike :{p_name})"
|
f"m_tok.name ilike :{p_name} or m_tok.code ilike :{p_name})"
|
||||||
f"))"
|
f"))"
|
||||||
)
|
)
|
||||||
|
|
@ -713,14 +709,13 @@ class SearchRepository:
|
||||||
f"(case when ci.title ilike :{p_name} then 6.0 else 0.0 end) + "
|
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"(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"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"where mc_s.content_id = ci.id and m_s.is_active = true and ("
|
||||||
f"m_s.name ilike :{p_name} or m_s.code ilike :{p_name})) then 4.0 else 0.0 end)"
|
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)
|
combined_tok_cond = " or ".join(tok_conditions)
|
||||||
tok_score_sql = " + ".join(tok_score_parts) if tok_score_parts else "0.0"
|
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(
|
where.append(
|
||||||
f"""(
|
f"""(
|
||||||
csd.search_vector @@ to_tsquery('simple', :and_prefix_query)
|
csd.search_vector @@ to_tsquery('simple', :and_prefix_query)
|
||||||
|
|
@ -733,7 +728,7 @@ class SearchRepository:
|
||||||
from {self.schema}.module_contents mc_mod
|
from {self.schema}.module_contents mc_mod
|
||||||
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
||||||
where mc_mod.content_id = ci.id
|
where mc_mod.content_id = ci.id
|
||||||
and {mod_filter_gate}
|
and m_mod.is_active = true
|
||||||
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
||||||
)
|
)
|
||||||
or ({combined_tok_cond})
|
or ({combined_tok_cond})
|
||||||
|
|
@ -752,12 +747,11 @@ class SearchRepository:
|
||||||
from {self.schema}.module_contents mc_mod
|
from {self.schema}.module_contents mc_mod
|
||||||
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
||||||
where mc_mod.content_id = ci.id
|
where mc_mod.content_id = ci.id
|
||||||
and {mod_filter_gate}
|
and m_mod.is_active = true
|
||||||
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
||||||
) then 15.0 else 0.0 end)
|
) then 15.0 else 0.0 end)
|
||||||
)"""
|
)"""
|
||||||
else:
|
else:
|
||||||
mod_filter_gate = "m_mod.status in ('active', 'inactive')" if scope.module_codes else "m_mod.is_active = true"
|
|
||||||
where.append(
|
where.append(
|
||||||
f"""(
|
f"""(
|
||||||
csd.search_text ilike :like_query
|
csd.search_text ilike :like_query
|
||||||
|
|
@ -767,7 +761,7 @@ class SearchRepository:
|
||||||
from {self.schema}.module_contents mc_mod
|
from {self.schema}.module_contents mc_mod
|
||||||
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
|
||||||
where mc_mod.content_id = ci.id
|
where mc_mod.content_id = ci.id
|
||||||
and {mod_filter_gate}
|
and m_mod.is_active = true
|
||||||
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
|
||||||
)
|
)
|
||||||
)"""
|
)"""
|
||||||
|
|
@ -825,7 +819,7 @@ class SearchRepository:
|
||||||
m.name as module_name
|
m.name as module_name
|
||||||
from {self.schema}.module_contents mc
|
from {self.schema}.module_contents mc
|
||||||
join {self.schema}.modules m on m.id = mc.module_id
|
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 ""}
|
{"and m.code = any(:scope_module_codes)" if scope.module_codes else ""}
|
||||||
order by mc.content_id, mc.sort_order, m.code
|
order by mc.content_id, mc.sort_order, m.code
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -102,12 +102,6 @@ class RazorpayWebhookService:
|
||||||
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
select(Coupon).where(Coupon.code == str(coupon_code).strip().upper())
|
||||||
)).scalar_one_or_none() if coupon_code else None
|
)).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 = Invoice(
|
||||||
payment_transaction_id=transaction.id,
|
payment_transaction_id=transaction.id,
|
||||||
invoice_number=invoice_number,
|
invoice_number=invoice_number,
|
||||||
|
|
|
||||||
|
|
@ -39,18 +39,11 @@ With the clean Acupedia naming conventions:
|
||||||
- **Database**: `acupedia_db`
|
- **Database**: `acupedia_db`
|
||||||
- **User**: `db_admin` / Password: `C1234spl`
|
- **User**: `db_admin` / Password: `C1234spl`
|
||||||
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
|
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
|
||||||
- **MinIO Bucket**: `acupedia-media`
|
- **MinIO Bucket**: `accupedia-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`:
|
|
||||||
|
|
||||||
|
### Start the containers:
|
||||||
```bash
|
```bash
|
||||||
cd ~/acupedia/acupedia_ops
|
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
|
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)
|
### Step 3.2: Seed Authentication & Super Admin User
|
||||||
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
|
|
||||||
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
|
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
|
||||||
|
|
||||||
```bash
|
```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`):
|
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -109,7 +89,7 @@ docker compose -f docker-compose.dev.yml exec backend \
|
||||||
---
|
---
|
||||||
|
|
||||||
### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
|
### 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):**
|
**Option A (Recommended — Automated 1-line loop for all 4 modules):**
|
||||||
```bash
|
```bash
|
||||||
|
|
@ -206,25 +186,3 @@ After running the manual steps above, test your endpoints:
|
||||||
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
|
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
|
||||||
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
|
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
|
||||||
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
|
| **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
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -76,36 +76,3 @@ async def test_admin_endpoint_authorized_for_admin(
|
||||||
data = response.json()
|
data = response.json()
|
||||||
assert len(data) == 1
|
assert len(data) == 1
|
||||||
assert data[0]["email"] == "superadmin@acupedia.test"
|
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"
|
|
||||||
|
|
|
||||||
|
|
@ -187,22 +187,3 @@ async def test_change_password_same_password_returns_400(async_client: AsyncClie
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
assert "New password cannot be the same as current password" in response.json()["detail"]
|
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"]
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
@ -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"
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -173,56 +173,5 @@ async def test_list_coupons_exhausted_marked_expired():
|
||||||
|
|
||||||
assert len(result) == 1
|
assert len(result) == 1
|
||||||
assert result[0]["usage_count"] == 5
|
assert result[0]["usage_count"] == 5
|
||||||
# Since usage_count (5) >= usage_limit (5), status should be fully_redeemed
|
# Since usage_count (5) >= usage_limit (5), status should be expired
|
||||||
assert result[0]["schedule_status"] == "fully_redeemed"
|
assert result[0]["schedule_status"] == "expired"
|
||||||
|
|
||||||
|
|
||||||
@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()
|
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,6 @@ async def test_create_coupon_valid_date_range():
|
||||||
code="TESTVALID",
|
code="TESTVALID",
|
||||||
discount_type="percentage",
|
discount_type="percentage",
|
||||||
value=10.0,
|
value=10.0,
|
||||||
per_user_limit=1,
|
|
||||||
start_date="2026-12-01T00:00:00Z",
|
start_date="2026-12-01T00:00:00Z",
|
||||||
end_date="2026-12-31T00:00:00Z",
|
end_date="2026-12-31T00:00:00Z",
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -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()
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -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()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -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")
|
|
||||||
|
|
@ -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",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
@ -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")
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
||||||
|
|
@ -21,7 +21,6 @@ class TestEmailAndPhoneNormalization:
|
||||||
def test_normalize_valid_email(self) -> None:
|
def test_normalize_valid_email(self) -> None:
|
||||||
assert normalize_email(" USER@Example.COM ") == "user@example.com"
|
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("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:
|
def test_normalize_invalid_email_raises(self) -> None:
|
||||||
invalid_emails = [
|
invalid_emails = [
|
||||||
|
|
@ -31,13 +30,6 @@ class TestEmailAndPhoneNormalization:
|
||||||
"username@.com",
|
"username@.com",
|
||||||
"user name@domain.com",
|
"user name@domain.com",
|
||||||
"user@domain",
|
"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:
|
for email in invalid_emails:
|
||||||
with pytest.raises(InvalidEmailError):
|
with pytest.raises(InvalidEmailError):
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue