Compare commits
19 Commits
feat/cli-d
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
58c0b66154 | |
|
|
ae36c05a16 | |
|
|
03583bf62a | |
|
|
3c15e0cf7a | |
|
|
5c87aef1f9 | |
|
|
7ae65d8c4f | |
|
|
8a37b8f7ef | |
|
|
06e6d91927 | |
|
|
664f5d869b | |
|
|
4698deb69d | |
|
|
0b32506d74 | |
|
|
d2ad675073 | |
|
|
ec3129a889 | |
|
|
464350cce4 | |
|
|
896bea8a83 | |
|
|
aa7ec0c679 | |
|
|
cfaba87dc3 | |
|
|
0fd7bda955 | |
|
|
53407e255b |
|
|
@ -0,0 +1,182 @@
|
||||||
|
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
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
"""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)
|
||||||
|
|
@ -20,6 +20,7 @@ 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"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -216,6 +216,7 @@ 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)))
|
||||||
|
|
@ -291,7 +292,10 @@ class InvoiceMonthlySequence(Base):
|
||||||
|
|
||||||
class CouponRedemption(Base):
|
class CouponRedemption(Base):
|
||||||
__tablename__ = "coupon_redemptions"
|
__tablename__ = "coupon_redemptions"
|
||||||
__table_args__ = (UniqueConstraint("coupon_id", "user_id", name="uq_coupon_user"), {"schema": COMMERCE_SCHEMA})
|
__table_args__ = (
|
||||||
|
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)
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ from .schema import (
|
||||||
LIFETIME_PLAN_CODES = frozenset({
|
LIFETIME_PLAN_CODES = frozenset({
|
||||||
"LIFETIME_ALL",
|
"LIFETIME_ALL",
|
||||||
"LIFETIME_ALL_USD",
|
"LIFETIME_ALL_USD",
|
||||||
|
"LIFETIME_ALL_EUR",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from __future__ import annotations
|
||||||
import io
|
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
|
||||||
|
|
@ -419,6 +420,8 @@ 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
|
||||||
|
|
||||||
|
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
@ -543,6 +546,13 @@ async def export_report_csv(
|
||||||
# MODULE BUILDER ENDPOINTS
|
# 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])
|
@router.get("/module-builder/modules", response_model=list[BuilderModuleSummary])
|
||||||
async def list_builder_modules(
|
async def list_builder_modules(
|
||||||
admin: AppUser = Depends(get_current_admin),
|
admin: AppUser = Depends(get_current_admin),
|
||||||
|
|
@ -783,6 +793,11 @@ async def sync_builder_module_to_repo(
|
||||||
admin: AppUser = Depends(get_current_admin),
|
admin: AppUser = Depends(get_current_admin),
|
||||||
service: AdminService = Depends(get_admin_service),
|
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:
|
try:
|
||||||
return await service.builder.sync_content_repo(module_code)
|
return await service.builder.sync_content_repo(module_code)
|
||||||
except HTTPException:
|
except HTTPException:
|
||||||
|
|
|
||||||
|
|
@ -75,7 +75,7 @@ class PatternClinicalData(BaseModel):
|
||||||
clinical_manifestations: list[str] = Field(default_factory=list)
|
clinical_manifestations: list[str] = Field(default_factory=list)
|
||||||
tongue: str = ""
|
tongue: str = ""
|
||||||
pulse: str = ""
|
pulse: str = ""
|
||||||
treatment_principle: str = ""
|
treatment_principle: list[str] | str = ""
|
||||||
acupuncture: AcupunctureDetails = Field(default_factory=AcupunctureDetails)
|
acupuncture: AcupunctureDetails = Field(default_factory=AcupunctureDetails)
|
||||||
explanation: list[str] = Field(default_factory=list)
|
explanation: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
@ -6,6 +6,7 @@ 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
|
||||||
|
|
||||||
|
|
@ -13,7 +14,7 @@ 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 ({"super_admin", "admin", "finance_admin"} & set(roles)):
|
if not has_admin_role(roles):
|
||||||
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,7 @@ class PlanPricingUpdateRequest(BaseModel):
|
||||||
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
|
||||||
|
|
@ -97,6 +98,7 @@ class CreateCouponRequest(BaseModel):
|
||||||
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_inr: float | None = None
|
||||||
min_purchase_usd: float | None = None
|
min_purchase_usd: float | None = None
|
||||||
|
|
@ -122,6 +124,7 @@ class UpdateCouponRequest(BaseModel):
|
||||||
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_inr: float | None = None
|
||||||
min_purchase_usd: float | None = None
|
min_purchase_usd: float | None = None
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,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 = "expired"
|
status = "fully_redeemed"
|
||||||
elif now < s_date:
|
elif now < s_date:
|
||||||
status = "scheduled"
|
status = "scheduled"
|
||||||
elif now > e_date:
|
elif now > e_date:
|
||||||
|
|
@ -164,6 +164,11 @@ class AdminCouponService:
|
||||||
"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_inr": min_inr,
|
||||||
|
|
@ -198,6 +203,10 @@ 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)
|
expanded_plan_uuids = await self._expand_plan_ids(payload.applicable_plan_ids)
|
||||||
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
|
||||||
|
|
@ -216,6 +225,7 @@ class AdminCouponService:
|
||||||
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(base_min)),
|
||||||
is_first_purchase_only=payload.is_first_purchase_only,
|
is_first_purchase_only=payload.is_first_purchase_only,
|
||||||
|
|
@ -262,7 +272,13 @@ class AdminCouponService:
|
||||||
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.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:
|
if payload.min_purchase_inr is not None:
|
||||||
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
|
coupon.min_purchase_amount = Decimal(str(payload.min_purchase_inr))
|
||||||
elif payload.min_purchase_amount is not None:
|
elif payload.min_purchase_amount is not None:
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ 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
|
||||||
|
|
@ -27,31 +28,40 @@ 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()
|
||||||
out: list[AdminUserListResponse] = []
|
if not users:
|
||||||
for user in users:
|
return []
|
||||||
roles = list((await self.session.execute(
|
|
||||||
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
user_ids = [u.id for u in users]
|
||||||
)).scalars().all())
|
|
||||||
if super_admin_only != ("super_admin" in roles):
|
role_rows = (await self.session.execute(
|
||||||
continue
|
select(UserRole.user_id, Role.role_name)
|
||||||
subs = (await self.session.execute(
|
.join(Role, Role.id == UserRole.role_id)
|
||||||
|
.where(UserRole.user_id.in_(user_ids))
|
||||||
|
)).all()
|
||||||
|
roles_by_user: dict[UUID, list[str]] = {}
|
||||||
|
for uid, role_name in role_rows:
|
||||||
|
roles_by_user.setdefault(uid, []).append(role_name)
|
||||||
|
|
||||||
|
matching_users = [
|
||||||
|
user for user in users
|
||||||
|
if super_admin_only == has_admin_role(roles_by_user.get(user.id))
|
||||||
|
]
|
||||||
|
if not matching_users:
|
||||||
|
return []
|
||||||
|
|
||||||
|
matching_ids = [u.id for u in matching_users]
|
||||||
|
sub_rows = (await self.session.execute(
|
||||||
select(UserSubscription, AccessPlan)
|
select(UserSubscription, AccessPlan)
|
||||||
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
||||||
.where(UserSubscription.user_id == user.id, UserSubscription.status != SubscriptionStatus.PENDING)
|
.where(
|
||||||
|
UserSubscription.user_id.in_(matching_ids),
|
||||||
|
UserSubscription.status != SubscriptionStatus.PENDING,
|
||||||
|
)
|
||||||
.order_by(UserSubscription.started_at.desc())
|
.order_by(UserSubscription.started_at.desc())
|
||||||
)).all()
|
)).all()
|
||||||
out.append(
|
subs_by_user: dict[UUID, list[dict]] = {}
|
||||||
AdminUserListResponse(
|
for s, p in sub_rows:
|
||||||
id=user.id,
|
subs_by_user.setdefault(s.user_id, []).append({
|
||||||
email=user.email,
|
|
||||||
display_name=user.display_name,
|
|
||||||
phone_number=user.phone_number,
|
|
||||||
country=user.country,
|
|
||||||
is_active=user.is_active,
|
|
||||||
roles=roles,
|
|
||||||
external_ref=user.external_ref,
|
|
||||||
subscriptions=[
|
|
||||||
{
|
|
||||||
"id": str(s.id),
|
"id": str(s.id),
|
||||||
"plan_code": p.code if p else "UNKNOWN",
|
"plan_code": p.code if p else "UNKNOWN",
|
||||||
"plan_name": p.name if p else "Unknown Access Plan",
|
"plan_name": p.name if p else "Unknown Access Plan",
|
||||||
|
|
@ -59,13 +69,23 @@ class AdminCustomerService:
|
||||||
"started_at": s.started_at.isoformat() if s.started_at else None,
|
"started_at": s.started_at.isoformat() if s.started_at else None,
|
||||||
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
||||||
"payment_reference": s.payment_reference,
|
"payment_reference": s.payment_reference,
|
||||||
}
|
})
|
||||||
for s, p in subs
|
|
||||||
],
|
return [
|
||||||
|
AdminUserListResponse(
|
||||||
|
id=user.id,
|
||||||
|
email=user.email,
|
||||||
|
display_name=user.display_name,
|
||||||
|
phone_number=user.phone_number,
|
||||||
|
country=user.country,
|
||||||
|
is_active=user.is_active,
|
||||||
|
roles=roles_by_user.get(user.id, []),
|
||||||
|
external_ref=user.external_ref,
|
||||||
|
subscriptions=subs_by_user.get(user.id, []),
|
||||||
created_at=user.created_at.isoformat() if user.created_at else None,
|
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(
|
||||||
|
|
|
||||||
|
|
@ -101,7 +101,42 @@ class ModuleBuilderService:
|
||||||
self, module_code: str, repo_root: Any = None
|
self, module_code: str, repo_root: Any = None
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
await self._verify_module_editable(module_code)
|
await self._verify_module_editable(module_code)
|
||||||
return await self.compiler.sync_to_content_repo(module_code, repo_root=repo_root)
|
result = await self.compiler.sync_to_content_repo(module_code, repo_root=repo_root)
|
||||||
|
|
||||||
|
target_dir = result.get("target_dir")
|
||||||
|
if target_dir:
|
||||||
|
from pathlib import Path
|
||||||
|
from app.bootstrap.seed_content.orchestrator import SeedOrchestrator
|
||||||
|
|
||||||
|
modules_root = Path(target_dir).parent
|
||||||
|
config_path = modules_root / "config.json"
|
||||||
|
if config_path.exists():
|
||||||
|
from app.bootstrap.seed_content.orchestrator import SeedOrchestrator
|
||||||
|
|
||||||
|
clean_code = module_code.strip().lower()
|
||||||
|
existing_mod = (
|
||||||
|
await self.session.execute(select(Module).where(Module.code == clean_code))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if existing_mod is None:
|
||||||
|
if self.session.in_transaction():
|
||||||
|
await self.session.commit()
|
||||||
|
summaries = await SeedOrchestrator(self.session).process_config(
|
||||||
|
config_path=config_path,
|
||||||
|
modules_root=modules_root,
|
||||||
|
module_codes={clean_code},
|
||||||
|
publish_content=True,
|
||||||
|
skip_search_facets=True,
|
||||||
|
)
|
||||||
|
result["db_synced"] = bool(summaries)
|
||||||
|
else:
|
||||||
|
result["db_synced"] = True
|
||||||
|
|
||||||
|
from .plan_service import AdminPlanService
|
||||||
|
|
||||||
|
pending_plan_code = await AdminPlanService(self.session).ensure_pending_pricing_plan_for_module(module_code)
|
||||||
|
if pending_plan_code:
|
||||||
|
result["pending_plan_code"] = pending_plan_code
|
||||||
|
return result
|
||||||
|
|
||||||
# =========================================================================
|
# =========================================================================
|
||||||
# MODULES
|
# MODULES
|
||||||
|
|
|
||||||
|
|
@ -362,7 +362,6 @@ class ModuleContentCompiler:
|
||||||
master_detail_items.append({
|
master_detail_items.append({
|
||||||
"code": source_code,
|
"code": source_code,
|
||||||
"slug": f"{module_code}-ct0005-{source_code}",
|
"slug": f"{module_code}-ct0005-{source_code}",
|
||||||
"name": pat.name,
|
|
||||||
"title": f"{dis.name} - {pat.name}",
|
"title": f"{dis.name} - {pat.name}",
|
||||||
"pattern_name": pat.name,
|
"pattern_name": pat.name,
|
||||||
"pattern_number": p_idx + 1,
|
"pattern_number": p_idx + 1,
|
||||||
|
|
@ -1023,7 +1022,7 @@ class ModuleContentCompiler:
|
||||||
"display_order": 0,
|
"display_order": 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"attribute_key": f"{template_code}.name",
|
"attribute_key": f"{template_code}.pattern_name",
|
||||||
"empty_behavior": "hide",
|
"empty_behavior": "hide",
|
||||||
"visibility": "show",
|
"visibility": "show",
|
||||||
"display_order": 0,
|
"display_order": 0,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
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 select, func
|
from sqlalchemy import delete, 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
|
||||||
|
|
@ -109,6 +109,8 @@ 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, [])
|
||||||
|
|
@ -291,8 +293,27 @@ 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."}
|
||||||
|
|
||||||
|
|
@ -304,6 +325,15 @@ class AdminPlanService:
|
||||||
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()
|
||||||
|
|
@ -312,3 +342,67 @@ 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
|
||||||
|
|
|
||||||
|
|
@ -356,7 +356,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 = "Exhausted"
|
schedule_status = "Fully Redeemed"
|
||||||
|
|
||||||
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"
|
||||||
|
|
|
||||||
|
|
@ -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 select
|
from sqlalchemy import func, 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, Module, UserEntitlement, UserSubscription
|
from app.db.models import AccessPlan, AccessPlanModule, Coupon, CouponRedemption, Module, UserEntitlement, UserSubscription
|
||||||
from app.features.payments.pricing import PricingCoupon, PricingItem
|
from app.features.payments.pricing import PricingCoupon, PricingItem
|
||||||
|
|
||||||
class CartRepository:
|
class CartRepository:
|
||||||
|
|
@ -151,7 +151,7 @@ class CartRepository:
|
||||||
))
|
))
|
||||||
return items
|
return items
|
||||||
|
|
||||||
async def get_coupon(self, code: str | None, currency: str) -> tuple[PricingCoupon | None, str | None]:
|
async def get_coupon(self, code: str | None, currency: str, user_id: UUID | None = None) -> tuple[PricingCoupon | None, str | None]:
|
||||||
if not code or not code.strip():
|
if not code or not code.strip():
|
||||||
return None, None
|
return None, None
|
||||||
clean_code = code.strip().upper()
|
clean_code = code.strip().upper()
|
||||||
|
|
@ -169,6 +169,21 @@ 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"}:
|
||||||
|
|
|
||||||
|
|
@ -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)
|
coupon, coupon_error = await self.repository.get_coupon(request.coupon_code, currency, user_id=user_id)
|
||||||
owned = await self.repository.get_owned_categories(user_id) if user_id else []
|
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]))
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,8 @@ class CheckoutService:
|
||||||
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)
|
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()
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ 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
|
||||||
|
|
||||||
|
|
@ -66,6 +67,21 @@ 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",
|
||||||
|
|
@ -461,6 +477,184 @@ 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,
|
||||||
*,
|
*,
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,7 @@ class ModuleResponse(BaseModel):
|
||||||
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,12 +125,34 @@ class ContentService:
|
||||||
session=self.session,
|
session=self.session,
|
||||||
include_draft=preview,
|
include_draft=preview,
|
||||||
)
|
)
|
||||||
return ModuleListResponse(
|
plan_map: dict[UUID, str] = {}
|
||||||
modules=[
|
if modules:
|
||||||
ModuleResponse.model_validate(module)
|
from app.db.enums import PlanType
|
||||||
for module in modules
|
from app.db.models import AccessPlan, AccessPlanModule
|
||||||
]
|
|
||||||
|
rows = (
|
||||||
|
await self.session.execute(
|
||||||
|
select(AccessPlanModule.module_id, AccessPlan.code)
|
||||||
|
.join(AccessPlan, AccessPlanModule.plan_id == AccessPlan.id)
|
||||||
|
.where(
|
||||||
|
AccessPlanModule.module_id.in_([m.id for m in modules]),
|
||||||
|
AccessPlan.plan_type == PlanType.ONE_TIME,
|
||||||
|
AccessPlan.currency_code == "INR",
|
||||||
|
AccessPlan.is_active.is_(True),
|
||||||
)
|
)
|
||||||
|
)
|
||||||
|
).all()
|
||||||
|
for mod_id, p_code in rows:
|
||||||
|
if mod_id not in plan_map:
|
||||||
|
plan_map[mod_id] = p_code
|
||||||
|
|
||||||
|
responses = []
|
||||||
|
for module in modules:
|
||||||
|
resp = ModuleResponse.model_validate(module)
|
||||||
|
if module.id in plan_map:
|
||||||
|
resp.plan_code = plan_map[module.id]
|
||||||
|
responses.append(resp)
|
||||||
|
return ModuleListResponse(modules=responses)
|
||||||
|
|
||||||
if preview:
|
if preview:
|
||||||
return await loader()
|
return await loader()
|
||||||
|
|
@ -1337,20 +1359,123 @@ class ContentService:
|
||||||
self._collect_content_reference_lookups(payload, references)
|
self._collect_content_reference_lookups(payload, references)
|
||||||
|
|
||||||
if not references:
|
if not references:
|
||||||
return [
|
hydrated = [
|
||||||
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,
|
||||||
)
|
)
|
||||||
return [
|
hydrated = [
|
||||||
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 select
|
from sqlalchemy import or_, 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 CouponRedemption entry."""
|
"""Increment coupon usage_count and record a per-invoice 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,24 +27,38 @@ async def record_coupon_redemption(
|
||||||
if not coupon:
|
if not coupon:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
coupon.usage_count = (coupon.usage_count or 0) + 1
|
if invoice_id is not None:
|
||||||
|
existing_filter = or_(
|
||||||
|
CouponRedemption.invoice_id == invoice_id,
|
||||||
|
CouponRedemption.invoice_id.is_(None),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
existing_filter = CouponRedemption.invoice_id.is_(None)
|
||||||
|
|
||||||
existing = (await session.execute(
|
existing = (await session.execute(
|
||||||
select(CouponRedemption).where(
|
select(CouponRedemption)
|
||||||
|
.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 not existing:
|
if existing:
|
||||||
|
if invoice_id is not None and existing.invoice_id == invoice_id:
|
||||||
|
return coupon
|
||||||
|
coupon.usage_count = (coupon.usage_count or 0) + 1
|
||||||
|
if invoice_id and not existing.invoice_id:
|
||||||
|
existing.invoice_id = invoice_id
|
||||||
|
return coupon
|
||||||
|
|
||||||
|
coupon.usage_count = (coupon.usage_count or 0) + 1
|
||||||
session.add(CouponRedemption(
|
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,6 +5,7 @@ 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"])
|
||||||
|
|
||||||
|
|
@ -22,16 +23,37 @@ 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(AccessPlanModule.plan_id, Module.slug, Module.name)
|
select(
|
||||||
|
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, str]]] = {}
|
mod_map: dict[str, list[dict[str, Any]]] = {}
|
||||||
for pid, slug, name in plan_mods_q.all():
|
for pid, m_code, slug, name, desc, m_meta 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] = []
|
||||||
mod_map[pid_str].append({"slug": slug, "name": name})
|
meta_dict = m_meta or {}
|
||||||
|
try:
|
||||||
|
sort_order = int(meta_dict.get("sort_order", 99999))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
sort_order = 99999
|
||||||
|
mod_map[pid_str].append({
|
||||||
|
"code": m_code,
|
||||||
|
"slug": slug,
|
||||||
|
"name": name,
|
||||||
|
"description": desc or "",
|
||||||
|
"category": resolve_module_category(meta_dict),
|
||||||
|
"sort_order": sort_order,
|
||||||
|
})
|
||||||
|
for mods_list in mod_map.values():
|
||||||
|
mods_list.sort(key=lambda m: (m["sort_order"], m["name"]))
|
||||||
|
|
||||||
groups: dict[str, dict[str, Any]] = {}
|
groups: dict[str, dict[str, Any]] = {}
|
||||||
for p in all_plans:
|
for p in all_plans:
|
||||||
|
|
@ -67,6 +89,8 @@ 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]
|
||||||
|
|
|
||||||
|
|
@ -173,5 +173,56 @@ 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 expired
|
# Since usage_count (5) >= usage_limit (5), status should be fully_redeemed
|
||||||
assert result[0]["schedule_status"] == "expired"
|
assert result[0]["schedule_status"] == "fully_redeemed"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_record_coupon_redemption_allows_repeat_purchase_across_distinct_invoices():
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = MagicMock(spec=Coupon)
|
||||||
|
coupon.id = uuid4()
|
||||||
|
coupon.usage_count = 1
|
||||||
|
user_id = uuid4()
|
||||||
|
invoice_id = uuid4()
|
||||||
|
|
||||||
|
exec_redemption = MagicMock()
|
||||||
|
exec_redemption.scalar_one_or_none.return_value = None
|
||||||
|
session.execute.return_value = exec_redemption
|
||||||
|
|
||||||
|
await record_coupon_redemption(
|
||||||
|
session,
|
||||||
|
coupon=coupon,
|
||||||
|
user_id=user_id,
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert coupon.usage_count == 2
|
||||||
|
session.add.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_record_coupon_redemption_is_idempotent_for_same_invoice():
|
||||||
|
session = AsyncMock()
|
||||||
|
coupon = MagicMock(spec=Coupon)
|
||||||
|
coupon.id = uuid4()
|
||||||
|
coupon.usage_count = 2
|
||||||
|
user_id = uuid4()
|
||||||
|
invoice_id = uuid4()
|
||||||
|
|
||||||
|
existing_redemption = MagicMock(spec=CouponRedemption)
|
||||||
|
existing_redemption.invoice_id = invoice_id
|
||||||
|
|
||||||
|
exec_redemption = MagicMock()
|
||||||
|
exec_redemption.scalar_one_or_none.return_value = existing_redemption
|
||||||
|
session.execute.return_value = exec_redemption
|
||||||
|
|
||||||
|
await record_coupon_redemption(
|
||||||
|
session,
|
||||||
|
coupon=coupon,
|
||||||
|
user_id=user_id,
|
||||||
|
invoice_id=invoice_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert coupon.usage_count == 2
|
||||||
|
session.add.assert_not_called()
|
||||||
|
|
|
||||||
|
|
@ -92,6 +92,7 @@ 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",
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,187 @@
|
||||||
|
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()
|
||||||
|
|
@ -500,6 +500,17 @@ async def test_module_content_compiler_full_pipeline(db_session: AsyncSession):
|
||||||
det_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0005.json"])
|
det_tpl = json.loads(compiled_files[f"templates/{mod_code}_ct0005.json"])
|
||||||
validate_definition_document(det_tpl)
|
validate_definition_document(det_tpl)
|
||||||
validate_presentation_contracts(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
|
# 6. Validate Data Documents with Seeder Validators
|
||||||
validate_content_document(json.loads(compiled_files["data/list.json"]))
|
validate_content_document(json.loads(compiled_files["data/list.json"]))
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
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")
|
||||||
|
|
@ -0,0 +1,85 @@
|
||||||
|
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",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
@ -0,0 +1,201 @@
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
@ -0,0 +1,170 @@
|
||||||
|
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
|
||||||
|
|
||||||
Loading…
Reference in New Issue