Compare commits
No commits in common. "main" and "feat/dynamic-catalog-pricing-api" have entirely different histories.
main
...
feat/dynam
|
|
@ -1,182 +0,0 @@
|
||||||
name: AcuPedia API CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
- master
|
|
||||||
- develop
|
|
||||||
- 'release/**'
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
tests:
|
|
||||||
name: Tests
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out source
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
cache: pip
|
|
||||||
|
|
||||||
- name: Install project and test dependencies
|
|
||||||
run: python -m pip install --upgrade pip && python -m pip install -e '.[dev]'
|
|
||||||
|
|
||||||
- name: Run test suite
|
|
||||||
run: python -m pytest
|
|
||||||
env:
|
|
||||||
ENVIRONMENT: test
|
|
||||||
JWT_SECRET: ci-only-test-secret-key-at-least-32-chars
|
|
||||||
REDIS_CACHE_ENABLED: "false"
|
|
||||||
|
|
||||||
coverage:
|
|
||||||
name: Test coverage
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out source
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
cache: pip
|
|
||||||
|
|
||||||
- name: Install project and test dependencies
|
|
||||||
run: python -m pip install --upgrade pip && python -m pip install -e '.[dev]'
|
|
||||||
|
|
||||||
- name: Run tests with coverage
|
|
||||||
run: >-
|
|
||||||
python -m pytest
|
|
||||||
--cov=app
|
|
||||||
--cov-report=term-missing
|
|
||||||
--cov-report=xml:coverage.xml
|
|
||||||
--cov-report=html:htmlcov
|
|
||||||
env:
|
|
||||||
ENVIRONMENT: test
|
|
||||||
JWT_SECRET: ci-only-test-secret-key-at-least-32-chars
|
|
||||||
REDIS_CACHE_ENABLED: "false"
|
|
||||||
|
|
||||||
- name: Add coverage summary
|
|
||||||
if: always()
|
|
||||||
run: |
|
|
||||||
if [ -f coverage.xml ]; then
|
|
||||||
python -c 'import xml.etree.ElementTree as ET; r=ET.parse("coverage.xml").getroot(); rate=float(r.attrib.get("line-rate", 0))*100; print("## Coverage\n\nLine coverage: **{:.2f}%**".format(rate))' >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
fi
|
|
||||||
|
|
||||||
deployment-test:
|
|
||||||
name: Build, deploy, and smoke test
|
|
||||||
runs-on: ci-docker
|
|
||||||
needs:
|
|
||||||
- tests
|
|
||||||
- coverage
|
|
||||||
steps:
|
|
||||||
- name: Check out source
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Python
|
|
||||||
uses: actions/setup-python@v5
|
|
||||||
with:
|
|
||||||
python-version: "3.12"
|
|
||||||
cache: pip
|
|
||||||
|
|
||||||
- name: Install project and runtime dependencies
|
|
||||||
run: python -m pip install --upgrade pip && python -m pip install -e .
|
|
||||||
|
|
||||||
- name: Start isolated PostgreSQL for container deployment
|
|
||||||
run: |
|
|
||||||
docker network create acupedia-ci || true
|
|
||||||
docker rm -f acupedia-postgres-ci >/dev/null 2>&1 || true
|
|
||||||
docker run -d --name acupedia-postgres-ci --network acupedia-ci \
|
|
||||||
-p 127.0.0.1:15432:5432 \
|
|
||||||
-e POSTGRES_DB=acupedia_ci \
|
|
||||||
-e POSTGRES_USER=acupedia \
|
|
||||||
-e POSTGRES_PASSWORD=ci-password \
|
|
||||||
postgres:16
|
|
||||||
for attempt in $(seq 1 30); do
|
|
||||||
if docker exec acupedia-postgres-ci pg_isready -U acupedia -d acupedia_ci; then
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
sleep 2
|
|
||||||
done
|
|
||||||
docker logs acupedia-postgres-ci
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
- name: Apply database migrations
|
|
||||||
run: python -m alembic upgrade head
|
|
||||||
env:
|
|
||||||
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
|
|
||||||
|
|
||||||
- name: Seed auth and commerce
|
|
||||||
run: |
|
|
||||||
acupedia-bootstrap auth
|
|
||||||
acupedia-bootstrap commerce
|
|
||||||
env:
|
|
||||||
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
|
|
||||||
|
|
||||||
- name: Validate seeded database
|
|
||||||
run: acupedia-bootstrap validate
|
|
||||||
env:
|
|
||||||
DATABASE_URL: postgresql+asyncpg://acupedia:ci-password@127.0.0.1:15432/acupedia_ci
|
|
||||||
|
|
||||||
- name: Build API image
|
|
||||||
run: docker build --pull -t "$CI_IMAGE" .
|
|
||||||
env:
|
|
||||||
CI_IMAGE: acupedia-api:${{ github.sha }}
|
|
||||||
|
|
||||||
- name: Deploy API container for acceptance checks
|
|
||||||
run: |
|
|
||||||
docker rm -f acupedia-api-ci >/dev/null 2>&1 || true
|
|
||||||
docker run -d --name acupedia-api-ci --network acupedia-ci -p 127.0.0.1:18000:8000 \
|
|
||||||
-e DATABASE_URL=postgresql+asyncpg://acupedia:ci-password@acupedia-postgres-ci:5432/acupedia_ci \
|
|
||||||
-e CACHE_ENABLED=false \
|
|
||||||
-e ENVIRONMENT=test \
|
|
||||||
-e JWT_SECRET=ci-only-test-secret-key-at-least-32-chars \
|
|
||||||
"$CI_IMAGE"
|
|
||||||
env:
|
|
||||||
CI_IMAGE: acupedia-api:${{ github.sha }}
|
|
||||||
|
|
||||||
- name: Run HTTP smoke tests against deployed container
|
|
||||||
run: |
|
|
||||||
if ! python scripts/smoke_deployed_api.py; then
|
|
||||||
docker logs acupedia-api-ci
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
env:
|
|
||||||
ACUPEDIA_BASE_URL: http://127.0.0.1:18000
|
|
||||||
|
|
||||||
- name: Install isolated AWS CLI
|
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/'))
|
|
||||||
run: |
|
|
||||||
python -m venv .artifact-venv
|
|
||||||
.artifact-venv/bin/pip install --disable-pip-version-check awscli
|
|
||||||
|
|
||||||
- name: Package and publish immutable S3 artifact
|
|
||||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/'))
|
|
||||||
run: bash scripts/publish_s3_artifact.sh
|
|
||||||
env:
|
|
||||||
AWS_ACCESS_KEY_ID: ${{ secrets.S3_ACCESS_KEY_ID }}
|
|
||||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.S3_SECRET_ACCESS_KEY }}
|
|
||||||
AWS_DEFAULT_REGION: ${{ secrets.S3_REGION || 'us-east-1' }}
|
|
||||||
AWS_EC2_METADATA_DISABLED: "true"
|
|
||||||
S3_ENDPOINT_URL: ${{ secrets.S3_ENDPOINT_URL }}
|
|
||||||
S3_BUCKET: ${{ secrets.S3_BUCKET }}
|
|
||||||
CI_IMAGE: acupedia-api:${{ github.sha }}
|
|
||||||
GITHUB_SHA: ${{ github.sha }}
|
|
||||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
|
||||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
|
||||||
GITHUB_RUN_ID: ${{ github.run_id }}
|
|
||||||
|
|
||||||
- name: Stop CI containers and network
|
|
||||||
if: always()
|
|
||||||
run: |
|
|
||||||
docker rm -f acupedia-api-ci acupedia-postgres-ci >/dev/null 2>&1 || true
|
|
||||||
docker network rm acupedia-ci >/dev/null 2>&1 || true
|
|
||||||
|
|
@ -20,7 +20,6 @@ class Settings(BaseSettings):
|
||||||
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
|
app_env: Literal["local", "dev", "test", "stage", "prod"] = "local"
|
||||||
debug: bool = False
|
debug: bool = False
|
||||||
content_preview_enabled: bool = False
|
content_preview_enabled: bool = False
|
||||||
enable_module_repo_sync: bool = False
|
|
||||||
api_prefix: str = "/api/v1"
|
api_prefix: str = "/api/v1"
|
||||||
cors_origins: str = "http://localhost:3000,http://localhost:8000"
|
cors_origins: str = "http://localhost:3000,http://localhost:8000"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ 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
|
||||||
|
|
@ -546,13 +545,6 @@ 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),
|
||||||
|
|
@ -793,11 +785,6 @@ 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: list[str] | str = ""
|
treatment_principle: 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)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from collections.abc import Iterable
|
|
||||||
|
|
||||||
ADMIN_ROLES: frozenset[str] = frozenset({"super_admin", "admin", "finance_admin"})
|
|
||||||
|
|
||||||
|
|
||||||
def has_admin_role(roles: Iterable[str] | None) -> bool:
|
|
||||||
"""Return True if any assigned role grants administrative privileges."""
|
|
||||||
if not roles:
|
|
||||||
return False
|
|
||||||
return any((role or "").strip().lower() in ADMIN_ROLES for role in roles)
|
|
||||||
|
|
||||||
|
|
@ -6,7 +6,6 @@ from app.cache.invalidation import ContentCacheInvalidator
|
||||||
from app.db.models import AppUser, Role, UserRole
|
from app.db.models import AppUser, Role, UserRole
|
||||||
from app.db.session import get_db_session
|
from app.db.session import get_db_session
|
||||||
from app.features.checkout.deps import get_current_user
|
from app.features.checkout.deps import get_current_user
|
||||||
from .constants import has_admin_role
|
|
||||||
from .repository import AdminRepository
|
from .repository import AdminRepository
|
||||||
from .service import AdminService
|
from .service import AdminService
|
||||||
|
|
||||||
|
|
@ -14,7 +13,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 has_admin_role(roles):
|
if not ({"super_admin", "admin", "finance_admin"} & set(roles)):
|
||||||
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
raise HTTPException(403, detail="Forbidden: Administrative privileges required.")
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ from app.db.models import (
|
||||||
UserRole,
|
UserRole,
|
||||||
UserSubscription,
|
UserSubscription,
|
||||||
)
|
)
|
||||||
from ..constants import has_admin_role
|
|
||||||
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
|
from ..schema import AdminCreateSuperAdminRequest, AdminPromoteUserRequest, AdminUserListResponse
|
||||||
from app.features.auth.security import hash_password, validate_password_strength
|
from app.features.auth.security import hash_password, validate_password_strength
|
||||||
from app.features.payments import get_razorpay_service
|
from app.features.payments import get_razorpay_service
|
||||||
|
|
@ -28,50 +27,20 @@ class AdminCustomerService:
|
||||||
|
|
||||||
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
async def list_users(self, super_admin_only: bool) -> list[AdminUserListResponse]:
|
||||||
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
|
users = (await self.session.execute(select(AppUser).order_by(AppUser.email))).scalars().all()
|
||||||
if not users:
|
out: list[AdminUserListResponse] = []
|
||||||
return []
|
for user in users:
|
||||||
|
roles = list((await self.session.execute(
|
||||||
user_ids = [u.id for u in users]
|
select(Role.role_name).join(UserRole, UserRole.role_id == Role.id).where(UserRole.user_id == user.id)
|
||||||
|
)).scalars().all())
|
||||||
role_rows = (await self.session.execute(
|
if super_admin_only != ("super_admin" in roles):
|
||||||
select(UserRole.user_id, Role.role_name)
|
continue
|
||||||
.join(Role, Role.id == UserRole.role_id)
|
subs = (await self.session.execute(
|
||||||
.where(UserRole.user_id.in_(user_ids))
|
|
||||||
)).all()
|
|
||||||
roles_by_user: dict[UUID, list[str]] = {}
|
|
||||||
for uid, role_name in role_rows:
|
|
||||||
roles_by_user.setdefault(uid, []).append(role_name)
|
|
||||||
|
|
||||||
matching_users = [
|
|
||||||
user for user in users
|
|
||||||
if super_admin_only == has_admin_role(roles_by_user.get(user.id))
|
|
||||||
]
|
|
||||||
if not matching_users:
|
|
||||||
return []
|
|
||||||
|
|
||||||
matching_ids = [u.id for u in matching_users]
|
|
||||||
sub_rows = (await self.session.execute(
|
|
||||||
select(UserSubscription, AccessPlan)
|
select(UserSubscription, AccessPlan)
|
||||||
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
.join(AccessPlan, AccessPlan.id == UserSubscription.plan_id, isouter=True)
|
||||||
.where(
|
.where(UserSubscription.user_id == user.id, UserSubscription.status != SubscriptionStatus.PENDING)
|
||||||
UserSubscription.user_id.in_(matching_ids),
|
|
||||||
UserSubscription.status != SubscriptionStatus.PENDING,
|
|
||||||
)
|
|
||||||
.order_by(UserSubscription.started_at.desc())
|
.order_by(UserSubscription.started_at.desc())
|
||||||
)).all()
|
)).all()
|
||||||
subs_by_user: dict[UUID, list[dict]] = {}
|
out.append(
|
||||||
for s, p in sub_rows:
|
|
||||||
subs_by_user.setdefault(s.user_id, []).append({
|
|
||||||
"id": str(s.id),
|
|
||||||
"plan_code": p.code if p else "UNKNOWN",
|
|
||||||
"plan_name": p.name if p else "Unknown Access Plan",
|
|
||||||
"status": getattr(s.status, "value", s.status),
|
|
||||||
"started_at": s.started_at.isoformat() if s.started_at else None,
|
|
||||||
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
|
||||||
"payment_reference": s.payment_reference,
|
|
||||||
})
|
|
||||||
|
|
||||||
return [
|
|
||||||
AdminUserListResponse(
|
AdminUserListResponse(
|
||||||
id=user.id,
|
id=user.id,
|
||||||
email=user.email,
|
email=user.email,
|
||||||
|
|
@ -79,13 +48,24 @@ class AdminCustomerService:
|
||||||
phone_number=user.phone_number,
|
phone_number=user.phone_number,
|
||||||
country=user.country,
|
country=user.country,
|
||||||
is_active=user.is_active,
|
is_active=user.is_active,
|
||||||
roles=roles_by_user.get(user.id, []),
|
roles=roles,
|
||||||
external_ref=user.external_ref,
|
external_ref=user.external_ref,
|
||||||
subscriptions=subs_by_user.get(user.id, []),
|
subscriptions=[
|
||||||
|
{
|
||||||
|
"id": str(s.id),
|
||||||
|
"plan_code": p.code if p else "UNKNOWN",
|
||||||
|
"plan_name": p.name if p else "Unknown Access Plan",
|
||||||
|
"status": getattr(s.status, "value", s.status),
|
||||||
|
"started_at": s.started_at.isoformat() if s.started_at else None,
|
||||||
|
"expires_at": s.expires_at.isoformat() if s.expires_at else None,
|
||||||
|
"payment_reference": s.payment_reference,
|
||||||
|
}
|
||||||
|
for s, p in subs
|
||||||
|
],
|
||||||
created_at=user.created_at.isoformat() if user.created_at else None,
|
created_at=user.created_at.isoformat() if user.created_at else None,
|
||||||
)
|
)
|
||||||
for user in matching_users
|
)
|
||||||
]
|
return out
|
||||||
|
|
||||||
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
|
async def promote(self, request: AdminPromoteUserRequest, admin: AppUser) -> dict:
|
||||||
user = (await self.session.execute(
|
user = (await self.session.execute(
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@ from datetime import datetime
|
||||||
|
|
||||||
from sqlalchemy import select, bindparam, text, func
|
from sqlalchemy import select, bindparam, text, func
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.orm import aliased
|
|
||||||
|
|
||||||
from app.db.enums import ModuleStatus, RecordStatus
|
from app.db.enums import ModuleStatus, RecordStatus
|
||||||
|
|
||||||
|
|
@ -67,21 +66,6 @@ from .schema import (
|
||||||
|
|
||||||
_SHORT_TEMPLATE_RE = re.compile(r"^CT\d+$", re.IGNORECASE)
|
_SHORT_TEMPLATE_RE = re.compile(r"^CT\d+$", re.IGNORECASE)
|
||||||
|
|
||||||
DYNAMIC_COUNT_COLLECTION_CODES: tuple[str, ...] = (
|
|
||||||
"points",
|
|
||||||
"patterns",
|
|
||||||
"food_items",
|
|
||||||
"items",
|
|
||||||
"ghost_points",
|
|
||||||
"four_seas",
|
|
||||||
"gao_wu_command_points",
|
|
||||||
"window_of_heaven_points",
|
|
||||||
"front_mu_points",
|
|
||||||
"horary_points",
|
|
||||||
"entry_exit_points",
|
|
||||||
"point_codes",
|
|
||||||
)
|
|
||||||
|
|
||||||
_SYSTEM_SORT_FIELDS = {
|
_SYSTEM_SORT_FIELDS = {
|
||||||
"module_sort_order",
|
"module_sort_order",
|
||||||
"title",
|
"title",
|
||||||
|
|
@ -477,184 +461,6 @@ class ContentRepository:
|
||||||
|
|
||||||
return resolved
|
return resolved
|
||||||
|
|
||||||
async def resolve_template_content_counts(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
template_refs: set[tuple[str, str]],
|
|
||||||
include_draft: bool = False,
|
|
||||||
) -> tuple[dict[tuple[str, str], int], dict[tuple[tuple[str, str], str], int]]:
|
|
||||||
"""
|
|
||||||
Count active items for template_ref targets across all modules.
|
|
||||||
|
|
||||||
Also aggregates child content_count totals grouped by content_label so
|
|
||||||
multi-level index entries (e.g. a top-level index summarizing sub-index
|
|
||||||
counts with the same label) sum child counts instead of collapsing to the
|
|
||||||
intermediate index row count.
|
|
||||||
"""
|
|
||||||
if not template_refs:
|
|
||||||
return {}, {}
|
|
||||||
|
|
||||||
normalized_pairs = {(m.lower(), t.lower()) for m, t in template_refs}
|
|
||||||
module_codes = sorted({m for m, _ in normalized_pairs})
|
|
||||||
template_codes = sorted({t for _, t in normalized_pairs})
|
|
||||||
allowed_content_statuses = (
|
|
||||||
[RecordStatus.PUBLISHED, RecordStatus.DRAFT]
|
|
||||||
if include_draft
|
|
||||||
else [RecordStatus.PUBLISHED]
|
|
||||||
)
|
|
||||||
allowed_module_statuses = (
|
|
||||||
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE]
|
|
||||||
if include_draft
|
|
||||||
else [ModuleStatus.ACTIVE, ModuleStatus.INACTIVE]
|
|
||||||
)
|
|
||||||
|
|
||||||
count_stmt = (
|
|
||||||
select(
|
|
||||||
func.lower(Module.code).label("module_code"),
|
|
||||||
func.lower(AttributeDefinitionSet.code).label("template_code"),
|
|
||||||
func.count(func.distinct(ContentItem.id)).label("item_count"),
|
|
||||||
)
|
|
||||||
.select_from(ContentItem)
|
|
||||||
.join(
|
|
||||||
AttributeDefinitionSet,
|
|
||||||
AttributeDefinitionSet.id == ContentItem.attribute_definition_set_id,
|
|
||||||
)
|
|
||||||
.join(ModuleContent, ModuleContent.content_id == ContentItem.id)
|
|
||||||
.join(Module, Module.id == ModuleContent.module_id)
|
|
||||||
.where(
|
|
||||||
func.lower(Module.code).in_(module_codes),
|
|
||||||
func.lower(AttributeDefinitionSet.code).in_(template_codes),
|
|
||||||
ContentItem.is_active.is_(True),
|
|
||||||
ContentItem.status.in_(allowed_content_statuses),
|
|
||||||
Module.status.in_(allowed_module_statuses),
|
|
||||||
AttributeDefinitionSet.is_active.is_(True),
|
|
||||||
)
|
|
||||||
.group_by(
|
|
||||||
func.lower(Module.code),
|
|
||||||
func.lower(AttributeDefinitionSet.code),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
count_result = await self._session.execute(count_stmt)
|
|
||||||
template_counts: dict[tuple[str, str], int] = {}
|
|
||||||
for row in count_result.mappings():
|
|
||||||
pair = (str(row["module_code"]), str(row["template_code"]))
|
|
||||||
if pair in normalized_pairs:
|
|
||||||
template_counts[pair] = int(row["item_count"] or 0)
|
|
||||||
|
|
||||||
ca_count = aliased(ContentAttribute)
|
|
||||||
ad_count = aliased(AttributeDefinition)
|
|
||||||
ca_label = aliased(ContentAttribute)
|
|
||||||
ad_label = aliased(AttributeDefinition)
|
|
||||||
|
|
||||||
sum_stmt = (
|
|
||||||
select(
|
|
||||||
func.lower(Module.code).label("module_code"),
|
|
||||||
func.lower(AttributeDefinitionSet.code).label("template_code"),
|
|
||||||
func.lower(func.btrim(ca_label.value_text)).label("content_label"),
|
|
||||||
func.sum(ca_count.value_number).label("total_count"),
|
|
||||||
)
|
|
||||||
.select_from(ContentItem)
|
|
||||||
.join(
|
|
||||||
AttributeDefinitionSet,
|
|
||||||
AttributeDefinitionSet.id == ContentItem.attribute_definition_set_id,
|
|
||||||
)
|
|
||||||
.join(ModuleContent, ModuleContent.content_id == ContentItem.id)
|
|
||||||
.join(Module, Module.id == ModuleContent.module_id)
|
|
||||||
.join(ca_count, ca_count.content_id == ContentItem.id)
|
|
||||||
.join(ad_count, ad_count.id == ca_count.attribute_definition_id)
|
|
||||||
.join(ca_label, ca_label.content_id == ContentItem.id)
|
|
||||||
.join(ad_label, ad_label.id == ca_label.attribute_definition_id)
|
|
||||||
.where(
|
|
||||||
func.lower(Module.code).in_(module_codes),
|
|
||||||
func.lower(AttributeDefinitionSet.code).in_(template_codes),
|
|
||||||
ContentItem.is_active.is_(True),
|
|
||||||
ContentItem.status.in_(allowed_content_statuses),
|
|
||||||
Module.status.in_(allowed_module_statuses),
|
|
||||||
AttributeDefinitionSet.is_active.is_(True),
|
|
||||||
ca_count.parent_attribute_value_id.is_(None),
|
|
||||||
ad_count.is_active.is_(True),
|
|
||||||
ad_count.is_root.is_(True),
|
|
||||||
func.split_part(ad_count.attribute_key, ".", 2) == "content_count",
|
|
||||||
ca_count.value_number.is_not(None),
|
|
||||||
ca_label.parent_attribute_value_id.is_(None),
|
|
||||||
ad_label.is_active.is_(True),
|
|
||||||
ad_label.is_root.is_(True),
|
|
||||||
func.split_part(ad_label.attribute_key, ".", 2) == "content_label",
|
|
||||||
ca_label.value_text.is_not(None),
|
|
||||||
)
|
|
||||||
.group_by(
|
|
||||||
func.lower(Module.code),
|
|
||||||
func.lower(AttributeDefinitionSet.code),
|
|
||||||
func.lower(func.btrim(ca_label.value_text)),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
sum_result = await self._session.execute(sum_stmt)
|
|
||||||
label_sums: dict[tuple[tuple[str, str], str], int] = {}
|
|
||||||
for row in sum_result.mappings():
|
|
||||||
pair = (str(row["module_code"]), str(row["template_code"]))
|
|
||||||
lbl = str(row["content_label"] or "").strip()
|
|
||||||
if pair in normalized_pairs and lbl:
|
|
||||||
label_sums[(pair, lbl)] = int(round(float(row["total_count"] or 0)))
|
|
||||||
|
|
||||||
return template_counts, label_sums
|
|
||||||
|
|
||||||
async def resolve_content_item_collection_counts(
|
|
||||||
self,
|
|
||||||
*,
|
|
||||||
content_ids: set[UUID],
|
|
||||||
) -> dict[UUID, int]:
|
|
||||||
"""
|
|
||||||
Count primary collection items (points, patterns, etc.) for target content items.
|
|
||||||
|
|
||||||
Only considers explicit collection attribute keys so descriptive/narrative
|
|
||||||
content items (e.g. Meridians, EOV) keep their authored counts untouched.
|
|
||||||
"""
|
|
||||||
if not content_ids:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
attr_code_expr = func.split_part(AttributeDefinition.attribute_key, ".", 2)
|
|
||||||
stmt = (
|
|
||||||
select(
|
|
||||||
ContentAttribute.content_id,
|
|
||||||
attr_code_expr.label("attr_code"),
|
|
||||||
AttributeDefinition.is_multivalue,
|
|
||||||
ContentAttribute.value_json,
|
|
||||||
)
|
|
||||||
.join(
|
|
||||||
AttributeDefinition,
|
|
||||||
AttributeDefinition.id == ContentAttribute.attribute_definition_id,
|
|
||||||
)
|
|
||||||
.where(
|
|
||||||
ContentAttribute.content_id.in_(sorted(content_ids)),
|
|
||||||
ContentAttribute.parent_attribute_value_id.is_(None),
|
|
||||||
AttributeDefinition.is_active.is_(True),
|
|
||||||
AttributeDefinition.is_root.is_(True),
|
|
||||||
attr_code_expr.in_(DYNAMIC_COUNT_COLLECTION_CODES),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
result = await self._session.execute(stmt)
|
|
||||||
|
|
||||||
counts_by_item: dict[UUID, dict[str, int]] = {}
|
|
||||||
for row in result.mappings():
|
|
||||||
cid = row["content_id"]
|
|
||||||
attr_code = str(row["attr_code"] or "")
|
|
||||||
if not attr_code:
|
|
||||||
continue
|
|
||||||
bucket = counts_by_item.setdefault(cid, {})
|
|
||||||
if row["is_multivalue"]:
|
|
||||||
bucket[attr_code] = bucket.get(attr_code, 0) + 1
|
|
||||||
elif isinstance(row["value_json"], (list, dict)):
|
|
||||||
bucket[attr_code] = bucket.get(attr_code, 0) + len(row["value_json"])
|
|
||||||
|
|
||||||
resolved: dict[UUID, int] = {}
|
|
||||||
for cid, per_attr in counts_by_item.items():
|
|
||||||
for code in DYNAMIC_COUNT_COLLECTION_CODES:
|
|
||||||
val = per_attr.get(code, 0)
|
|
||||||
if val > 0:
|
|
||||||
resolved[cid] = val
|
|
||||||
break
|
|
||||||
return resolved
|
|
||||||
|
|
||||||
async def get_content_by_id(
|
async def get_content_by_id(
|
||||||
self,
|
self,
|
||||||
*,
|
*,
|
||||||
|
|
|
||||||
|
|
@ -1359,123 +1359,20 @@ class ContentService:
|
||||||
self._collect_content_reference_lookups(payload, references)
|
self._collect_content_reference_lookups(payload, references)
|
||||||
|
|
||||||
if not references:
|
if not references:
|
||||||
hydrated = [
|
return [
|
||||||
self._hydrate_reference_value(payload, {})
|
self._hydrate_reference_value(payload, {})
|
||||||
for payload in payloads
|
for payload in payloads
|
||||||
]
|
]
|
||||||
else:
|
|
||||||
resolved = await self.repository.resolve_content_reference_targets(
|
resolved = await self.repository.resolve_content_reference_targets(
|
||||||
references=references,
|
references=references,
|
||||||
include_draft=preview,
|
include_draft=preview,
|
||||||
)
|
)
|
||||||
hydrated = [
|
return [
|
||||||
self._hydrate_reference_value(payload, resolved)
|
self._hydrate_reference_value(payload, resolved)
|
||||||
for payload in payloads
|
for payload in payloads
|
||||||
]
|
]
|
||||||
|
|
||||||
await self._hydrate_dynamic_content_counts(hydrated, preview=preview)
|
|
||||||
return hydrated
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _collect_dynamic_count_targets(
|
|
||||||
cls,
|
|
||||||
value: Any,
|
|
||||||
items: list[dict[str, Any]],
|
|
||||||
template_refs: set[tuple[str, str]],
|
|
||||||
content_ids: set[UUID],
|
|
||||||
) -> None:
|
|
||||||
if isinstance(value, list):
|
|
||||||
for entry in value:
|
|
||||||
cls._collect_dynamic_count_targets(
|
|
||||||
entry, items, template_refs, content_ids
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
if not isinstance(value, dict):
|
|
||||||
return
|
|
||||||
|
|
||||||
if "content_count" in value and isinstance(value.get("link"), dict):
|
|
||||||
link = value["link"]
|
|
||||||
link_type = link.get("type")
|
|
||||||
target = link.get("target")
|
|
||||||
if isinstance(target, dict):
|
|
||||||
if link_type == "template_ref":
|
|
||||||
mod = str(target.get("module_code") or "").strip()
|
|
||||||
tpl = str(target.get("template_code") or "").strip()
|
|
||||||
if mod and tpl:
|
|
||||||
template_refs.add((mod, tpl))
|
|
||||||
items.append(value)
|
|
||||||
elif link_type == "content_ref" and target.get("content_id"):
|
|
||||||
try:
|
|
||||||
content_ids.add(UUID(str(target["content_id"])))
|
|
||||||
items.append(value)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
for child in value.values():
|
|
||||||
cls._collect_dynamic_count_targets(
|
|
||||||
child, items, template_refs, content_ids
|
|
||||||
)
|
|
||||||
|
|
||||||
async def _hydrate_dynamic_content_counts(
|
|
||||||
self,
|
|
||||||
payloads: list[dict[str, Any]],
|
|
||||||
*,
|
|
||||||
preview: bool = False,
|
|
||||||
) -> None:
|
|
||||||
"""Update index entry content_count values dynamically from live targets across all modules."""
|
|
||||||
candidate_items: list[dict[str, Any]] = []
|
|
||||||
template_refs: set[tuple[str, str]] = set()
|
|
||||||
content_ids: set[UUID] = set()
|
|
||||||
|
|
||||||
for payload in payloads:
|
|
||||||
self._collect_dynamic_count_targets(
|
|
||||||
payload, candidate_items, template_refs, content_ids
|
|
||||||
)
|
|
||||||
|
|
||||||
if not candidate_items:
|
|
||||||
return
|
|
||||||
|
|
||||||
template_counts: dict[tuple[str, str], int] = {}
|
|
||||||
label_sums: dict[tuple[tuple[str, str], str], int] = {}
|
|
||||||
if template_refs:
|
|
||||||
res = await self.repository.resolve_template_content_counts(
|
|
||||||
template_refs=template_refs,
|
|
||||||
include_draft=preview,
|
|
||||||
)
|
|
||||||
if isinstance(res, tuple) and len(res) == 2:
|
|
||||||
template_counts, label_sums = res
|
|
||||||
|
|
||||||
item_counts: dict[UUID, int] = {}
|
|
||||||
if content_ids:
|
|
||||||
res_items = await self.repository.resolve_content_item_collection_counts(
|
|
||||||
content_ids=content_ids
|
|
||||||
)
|
|
||||||
if isinstance(res_items, dict):
|
|
||||||
item_counts = res_items
|
|
||||||
|
|
||||||
for item in candidate_items:
|
|
||||||
link = item.get("link") or {}
|
|
||||||
link_type = link.get("type")
|
|
||||||
target = link.get("target") or {}
|
|
||||||
if link_type == "template_ref":
|
|
||||||
pair = (
|
|
||||||
str(target.get("module_code") or "").strip().lower(),
|
|
||||||
str(target.get("template_code") or "").strip().lower(),
|
|
||||||
)
|
|
||||||
lbl = str(item.get("content_label") or "").strip().lower()
|
|
||||||
if lbl and (pair, lbl) in label_sums and label_sums[(pair, lbl)] > 0:
|
|
||||||
item["content_count"] = label_sums[(pair, lbl)]
|
|
||||||
elif pair in template_counts:
|
|
||||||
item["content_count"] = template_counts[pair]
|
|
||||||
elif link_type == "content_ref" and target.get("content_id"):
|
|
||||||
try:
|
|
||||||
cid = UUID(str(target["content_id"]))
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
continue
|
|
||||||
if cid in item_counts:
|
|
||||||
item["content_count"] = item_counts[cid]
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _extract_referenced_content_items(
|
def _extract_referenced_content_items(
|
||||||
cls,
|
cls,
|
||||||
|
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from types import SimpleNamespace
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from fastapi import HTTPException
|
|
||||||
|
|
||||||
from app.core.config import Settings
|
|
||||||
from app.features.admin import api as admin_api
|
|
||||||
|
|
||||||
|
|
||||||
def test_enable_module_repo_sync_defaults_to_false(monkeypatch):
|
|
||||||
monkeypatch.delenv("ENABLE_MODULE_REPO_SYNC", raising=False)
|
|
||||||
s = Settings(_env_file=None)
|
|
||||||
assert s.enable_module_repo_sync is False
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_get_builder_config_reflects_setting(monkeypatch):
|
|
||||||
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=False))
|
|
||||||
res_off = await admin_api.get_builder_config(admin=MagicMock())
|
|
||||||
assert res_off == {"sync_repo_enabled": False}
|
|
||||||
|
|
||||||
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=True))
|
|
||||||
res_on = await admin_api.get_builder_config(admin=MagicMock())
|
|
||||||
assert res_on == {"sync_repo_enabled": True}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sync_builder_module_to_repo_blocked_when_disabled(monkeypatch):
|
|
||||||
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=False))
|
|
||||||
service = SimpleNamespace(builder=SimpleNamespace(sync_content_repo=AsyncMock()))
|
|
||||||
|
|
||||||
with pytest.raises(HTTPException) as exc_info:
|
|
||||||
await admin_api.sync_builder_module_to_repo("m0042", admin=MagicMock(), service=service)
|
|
||||||
|
|
||||||
assert exc_info.value.status_code == 403
|
|
||||||
service.builder.sync_content_repo.assert_not_awaited()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sync_builder_module_to_repo_allowed_when_enabled(monkeypatch):
|
|
||||||
monkeypatch.setattr(admin_api, "get_settings", lambda: SimpleNamespace(enable_module_repo_sync=True))
|
|
||||||
service = SimpleNamespace(
|
|
||||||
builder=SimpleNamespace(sync_content_repo=AsyncMock(return_value={"status": "synced"}))
|
|
||||||
)
|
|
||||||
|
|
||||||
res = await admin_api.sync_builder_module_to_repo("m0042", admin=MagicMock(), service=service)
|
|
||||||
assert res == {"status": "synced"}
|
|
||||||
service.builder.sync_content_repo.assert_awaited_once_with("m0042")
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
from uuid import uuid4
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.db.models import AppUser
|
|
||||||
from app.features.admin.constants import has_admin_role
|
|
||||||
from app.features.admin.services.customer_service import AdminCustomerService
|
|
||||||
|
|
||||||
|
|
||||||
def _make_user(email: str, name: str) -> MagicMock:
|
|
||||||
user = MagicMock(spec=AppUser)
|
|
||||||
user.id = uuid4()
|
|
||||||
user.email = email
|
|
||||||
user.display_name = name
|
|
||||||
user.phone_number = "+919876543210"
|
|
||||||
user.country = "India"
|
|
||||||
user.is_active = True
|
|
||||||
user.external_ref = None
|
|
||||||
user.created_at = datetime(2026, 10, 1, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
return user
|
|
||||||
|
|
||||||
|
|
||||||
def _build_session(users: list[MagicMock], role_rows: list[tuple], sub_rows: list[tuple]) -> AsyncMock:
|
|
||||||
session = AsyncMock()
|
|
||||||
|
|
||||||
res_users = MagicMock()
|
|
||||||
res_users.scalars.return_value.all.return_value = users
|
|
||||||
|
|
||||||
res_roles = MagicMock()
|
|
||||||
res_roles.all.return_value = role_rows
|
|
||||||
|
|
||||||
res_subs = MagicMock()
|
|
||||||
res_subs.all.return_value = sub_rows
|
|
||||||
|
|
||||||
session.execute.side_effect = [res_users, res_roles, res_subs]
|
|
||||||
return session
|
|
||||||
|
|
||||||
|
|
||||||
def test_has_admin_role_handles_all_admin_variants() -> None:
|
|
||||||
assert has_admin_role(["super_admin"]) is True
|
|
||||||
assert has_admin_role(["admin"]) is True
|
|
||||||
assert has_admin_role(["finance_admin"]) is True
|
|
||||||
assert has_admin_role(["practitioner", "super_admin"]) is True
|
|
||||||
assert has_admin_role([" Finance_Admin "]) is True
|
|
||||||
assert has_admin_role(["practitioner"]) is False
|
|
||||||
assert has_admin_role([]) is False
|
|
||||||
assert has_admin_role(None) is False
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_list_users_excludes_all_admin_roles_from_customers() -> None:
|
|
||||||
practitioner = _make_user("prac@example.com", "Practitioner One")
|
|
||||||
unassigned = _make_user("guest@example.com", "Unassigned User")
|
|
||||||
super_admin = _make_user("super@example.com", "Super Admin")
|
|
||||||
regular_admin = _make_user("admin@example.com", "Admin User")
|
|
||||||
finance_admin = _make_user("finance@example.com", "Finance Admin")
|
|
||||||
|
|
||||||
users = [practitioner, unassigned, super_admin, regular_admin, finance_admin]
|
|
||||||
role_rows = [
|
|
||||||
(practitioner.id, "practitioner"),
|
|
||||||
# Super admins created via AdminCustomerService carry both roles
|
|
||||||
(super_admin.id, "practitioner"),
|
|
||||||
(super_admin.id, "super_admin"),
|
|
||||||
(regular_admin.id, "admin"),
|
|
||||||
(finance_admin.id, "finance_admin"),
|
|
||||||
]
|
|
||||||
|
|
||||||
# 1. Practitioners / Customers query should exclude all admin roles
|
|
||||||
svc_customers = AdminCustomerService(_build_session(users, role_rows, []))
|
|
||||||
customers = await svc_customers.list_users(super_admin_only=False)
|
|
||||||
assert [c.email for c in customers] == ["prac@example.com", "guest@example.com"]
|
|
||||||
|
|
||||||
# 2. Admins query should capture super_admin, admin, and finance_admin
|
|
||||||
svc_admins = AdminCustomerService(_build_session(users, role_rows, []))
|
|
||||||
admins = await svc_admins.list_users(super_admin_only=True)
|
|
||||||
assert [a.email for a in admins] == [
|
|
||||||
"super@example.com",
|
|
||||||
"admin@example.com",
|
|
||||||
"finance@example.com",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
@ -1,170 +0,0 @@
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
|
||||||
from uuid import uuid4
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from app.features.content.repository import ContentRepository
|
|
||||||
from app.features.content.service import ContentService
|
|
||||||
|
|
||||||
|
|
||||||
class _DummyMappings:
|
|
||||||
def __init__(self, rows: list[dict]):
|
|
||||||
self._rows = rows
|
|
||||||
|
|
||||||
def mappings(self):
|
|
||||||
return self._rows
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_resolve_content_item_collection_counts_prioritizes_structured_collections() -> None:
|
|
||||||
cid_points = uuid4()
|
|
||||||
cid_gao_wu = uuid4()
|
|
||||||
cid_patterns = uuid4()
|
|
||||||
cid_narrative = uuid4()
|
|
||||||
|
|
||||||
session = AsyncMock()
|
|
||||||
rows = [
|
|
||||||
# 12 multivalue points rows
|
|
||||||
*[
|
|
||||||
{"content_id": cid_points, "attr_code": "points", "is_multivalue": True, "value_json": None}
|
|
||||||
for _ in range(12)
|
|
||||||
],
|
|
||||||
# Gao Wu has 6 gao_wu_command_points rows AND 1 stale point_codes row -> must pick 6
|
|
||||||
*[
|
|
||||||
{"content_id": cid_gao_wu, "attr_code": "gao_wu_command_points", "is_multivalue": True, "value_json": None}
|
|
||||||
for _ in range(6)
|
|
||||||
],
|
|
||||||
{"content_id": cid_gao_wu, "attr_code": "point_codes", "is_multivalue": True, "value_json": None},
|
|
||||||
# Scalar JSON array for patterns (Four Levels)
|
|
||||||
{
|
|
||||||
"content_id": cid_patterns,
|
|
||||||
"attr_code": "patterns",
|
|
||||||
"is_multivalue": False,
|
|
||||||
"value_json": [{"name": "P1"}, {"name": "P2"}, {"name": "P3"}, {"name": "P4"}],
|
|
||||||
},
|
|
||||||
# Non-collection attribute (e.g. description) should not yield an override
|
|
||||||
]
|
|
||||||
session.execute = AsyncMock(return_value=_DummyMappings(rows))
|
|
||||||
repo = ContentRepository(session)
|
|
||||||
|
|
||||||
counts = await repo.resolve_content_item_collection_counts(
|
|
||||||
content_ids={cid_points, cid_gao_wu, cid_patterns, cid_narrative}
|
|
||||||
)
|
|
||||||
|
|
||||||
assert counts[cid_points] == 12
|
|
||||||
assert counts[cid_gao_wu] == 6
|
|
||||||
assert counts[cid_patterns] == 4
|
|
||||||
assert cid_narrative not in counts
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_resolve_template_content_counts_filters_statuses_and_label_sums() -> None:
|
|
||||||
session = AsyncMock()
|
|
||||||
count_rows = [
|
|
||||||
{"module_code": "m0012", "template_code": "m0012_ct0005", "item_count": 9},
|
|
||||||
{"module_code": "m0001", "template_code": "m0001_ct0002", "item_count": 15},
|
|
||||||
]
|
|
||||||
sum_rows = [
|
|
||||||
{
|
|
||||||
"module_code": "m0001",
|
|
||||||
"template_code": "m0001_ct0002",
|
|
||||||
"content_label": "points",
|
|
||||||
"total_count": 409,
|
|
||||||
}
|
|
||||||
]
|
|
||||||
session.execute = AsyncMock(
|
|
||||||
side_effect=[_DummyMappings(count_rows), _DummyMappings(sum_rows)]
|
|
||||||
)
|
|
||||||
repo = ContentRepository(session)
|
|
||||||
|
|
||||||
counts, sums = await repo.resolve_template_content_counts(
|
|
||||||
template_refs={("m0012", "m0012_ct0005"), ("m0001", "m0001_ct0002")},
|
|
||||||
include_draft=False,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert counts == {
|
|
||||||
("m0012", "m0012_ct0005"): 9,
|
|
||||||
("m0001", "m0001_ct0002"): 15,
|
|
||||||
}
|
|
||||||
assert sums == {(("m0001", "m0001_ct0002"), "points"): 409}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_hydrate_dynamic_content_counts_handles_template_and_content_refs_safely() -> None:
|
|
||||||
xi_cleft_id = uuid4()
|
|
||||||
meridian_id = uuid4()
|
|
||||||
|
|
||||||
repo = MagicMock()
|
|
||||||
repo.resolve_template_content_counts = AsyncMock(
|
|
||||||
return_value=(
|
|
||||||
{
|
|
||||||
("m0001", "m0001_ct0002"): 15,
|
|
||||||
("m0012", "m0012_ct0005"): 9,
|
|
||||||
("m0042", "m0042_ct0002"): 11,
|
|
||||||
},
|
|
||||||
{(("m0001", "m0001_ct0002"), "points"): 409},
|
|
||||||
)
|
|
||||||
)
|
|
||||||
repo.resolve_content_item_collection_counts = AsyncMock(
|
|
||||||
return_value={xi_cleft_id: 16}
|
|
||||||
)
|
|
||||||
|
|
||||||
service = ContentService(
|
|
||||||
session=AsyncMock(),
|
|
||||||
repository=repo,
|
|
||||||
cache=MagicMock(),
|
|
||||||
invalidator=MagicMock(),
|
|
||||||
search_projection_writer=MagicMock(),
|
|
||||||
)
|
|
||||||
|
|
||||||
payloads = [
|
|
||||||
# Nested index matching child content_label -> sums to 409
|
|
||||||
{
|
|
||||||
"name": "Acupoints",
|
|
||||||
"content_count": 100,
|
|
||||||
"content_label": "points",
|
|
||||||
"link": {"type": "template_ref", "target": {"module_code": "m0001", "template_code": "m0001_ct0002"}},
|
|
||||||
},
|
|
||||||
# Template index with differing label -> uses target template row count 9
|
|
||||||
{
|
|
||||||
"name": "Spleen",
|
|
||||||
"content_count": 10,
|
|
||||||
"content_label": "patterns",
|
|
||||||
"link": {"type": "template_ref", "target": {"module_code": "m0012", "template_code": "m0012_ct0005"}},
|
|
||||||
},
|
|
||||||
# Content ref with points collection -> updates 10 -> 16
|
|
||||||
{
|
|
||||||
"name": "Xi Cleft",
|
|
||||||
"content_count": 10,
|
|
||||||
"content_label": "points",
|
|
||||||
"link": {
|
|
||||||
"type": "content_ref",
|
|
||||||
"target": {"module_code": "m0001", "template_code": "m0001_ct0011", "content_id": str(xi_cleft_id)},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
# Content ref without collection count (e.g. Meridian) -> preserves authored 10
|
|
||||||
{
|
|
||||||
"name": "Lung",
|
|
||||||
"content_count": 10,
|
|
||||||
"link": {
|
|
||||||
"type": "content_ref",
|
|
||||||
"target": {"module_code": "m0001", "template_code": "m0001_ct0005", "content_id": str(meridian_id)},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
# Item without link -> untouched
|
|
||||||
{
|
|
||||||
"name": "Lung Points",
|
|
||||||
"content_count": 11,
|
|
||||||
"content_label": "points",
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
await service._hydrate_dynamic_content_counts(payloads, preview=False)
|
|
||||||
|
|
||||||
assert payloads[0]["content_count"] == 409
|
|
||||||
assert payloads[1]["content_count"] == 9
|
|
||||||
assert payloads[2]["content_count"] == 16
|
|
||||||
assert payloads[3]["content_count"] == 10
|
|
||||||
assert payloads[4]["content_count"] == 11
|
|
||||||
|
|
||||||
Loading…
Reference in New Issue