fix(search,content): allow inactive modules in scoped search and content reference resolution #43

Merged
amit merged 1 commits from fix/inactive-module-search-and-refs into main 2026-11-27 04:45:09 +00:00
3 changed files with 131 additions and 12 deletions

View File

@ -388,11 +388,10 @@ class ContentRepository:
if include_draft
else [RecordStatus.PUBLISHED]
),
Module.is_active.is_(True),
Module.status.in_(
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT]
[ModuleStatus.ACTIVE, ModuleStatus.DRAFT, ModuleStatus.INACTIVE]
if include_draft
else [ModuleStatus.ACTIVE]
else [ModuleStatus.ACTIVE, ModuleStatus.INACTIVE]
),
AttributeDefinitionSet.is_active.is_(True),
)

View File

@ -163,12 +163,14 @@ class SearchRepository:
) -> list[dict[str, Any]]:
effective_scope = scope or SearchScope()
params: dict[str, Any] = {}
where = ["is_active = true", "status = 'active'"]
if effective_scope.module_codes:
where = ["status in ('active', 'inactive')"]
params["capability_module_codes"] = [
code.strip().lower() for code in effective_scope.module_codes if code and code.strip()
]
where.append("code = any(cast(:capability_module_codes as text[]))")
else:
where = ["is_active = true", "status = 'active'"]
result = await self.session.execute(
text(
@ -534,13 +536,13 @@ class SearchRepository:
code.strip().lower() for code in scope.module_codes if code and code.strip()
]
clauses.append(
f"""exists (
f"""exists (
select 1
from {self.schema}.module_contents scope_mc
join {self.schema}.modules scope_m on scope_m.id = scope_mc.module_id
where scope_mc.content_id = {ci_alias}.id
and scope_m.code = any(cast(:scope_module_codes as text[]))
and scope_m.is_active = true
and scope_m.status in ('active', 'inactive')
)"""
)
if scope.content_kinds:
@ -694,6 +696,8 @@ class SearchRepository:
tok_conditions: list[str] = []
tok_score_parts: list[str] = []
mod_tok_gate = "m_tok.status in ('active', 'inactive')" if scope.module_codes else "m_tok.is_active = true"
mod_s_gate = "m_s.status in ('active', 'inactive')" if scope.module_codes else "m_s.is_active = true"
for idx, tok in enumerate(list(stem_tokens)[:8]):
p_name = f"tok_{idx}"
params[p_name] = f"%{tok}%"
@ -701,7 +705,7 @@ class SearchRepository:
f"(ci.title ilike :{p_name} or csd.search_text ilike :{p_name} or exists ("
f"select 1 from {self.schema}.module_contents mc_tok "
f"join {self.schema}.modules m_tok on m_tok.id = mc_tok.module_id "
f"where mc_tok.content_id = ci.id and m_tok.is_active = true and ("
f"where mc_tok.content_id = ci.id and {mod_tok_gate} and ("
f"m_tok.name ilike :{p_name} or m_tok.code ilike :{p_name})"
f"))"
)
@ -709,13 +713,14 @@ class SearchRepository:
f"(case when ci.title ilike :{p_name} then 6.0 else 0.0 end) + "
f"(case when exists (select 1 from {self.schema}.module_contents mc_s "
f"join {self.schema}.modules m_s on m_s.id = mc_s.module_id "
f"where mc_s.content_id = ci.id and m_s.is_active = true and ("
f"where mc_s.content_id = ci.id and {mod_s_gate} and ("
f"m_s.name ilike :{p_name} or m_s.code ilike :{p_name})) then 4.0 else 0.0 end)"
)
combined_tok_cond = " or ".join(tok_conditions)
tok_score_sql = " + ".join(tok_score_parts) if tok_score_parts else "0.0"
mod_filter_gate = "m_mod.status in ('active', 'inactive')" if scope.module_codes else "m_mod.is_active = true"
where.append(
f"""(
csd.search_vector @@ to_tsquery('simple', :and_prefix_query)
@ -728,7 +733,7 @@ class SearchRepository:
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and m_mod.is_active = true
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
)
or ({combined_tok_cond})
@ -747,11 +752,12 @@ class SearchRepository:
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and m_mod.is_active = true
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
) then 15.0 else 0.0 end)
)"""
else:
mod_filter_gate = "m_mod.status in ('active', 'inactive')" if scope.module_codes else "m_mod.is_active = true"
where.append(
f"""(
csd.search_text ilike :like_query
@ -761,7 +767,7 @@ class SearchRepository:
from {self.schema}.module_contents mc_mod
join {self.schema}.modules m_mod on m_mod.id = mc_mod.module_id
where mc_mod.content_id = ci.id
and m_mod.is_active = true
and {mod_filter_gate}
and (m_mod.name ilike :like_query or m_mod.code ilike :like_query)
)
)"""
@ -819,7 +825,7 @@ class SearchRepository:
m.name as module_name
from {self.schema}.module_contents mc
join {self.schema}.modules m on m.id = mc.module_id
where m.is_active = true
where {"m.status in ('active', 'inactive')" if scope.module_codes else "m.is_active = true"}
{"and m.code = any(:scope_module_codes)" if scope.module_codes else ""}
order by mc.content_id, mc.sort_order, m.code
)

View File

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