diff --git a/app/bootstrap/adapters.py b/app/bootstrap/adapters.py index 6e743e7..e20e99f 100644 --- a/app/bootstrap/adapters.py +++ b/app/bootstrap/adapters.py @@ -53,6 +53,7 @@ class ContentBootstrapAdapter: skip_search_facets: bool = False, publish_content: bool = False, cleanup: bool = False, + cleanup_mode: str | None = None, continue_on_error: bool = False, created_by: UUID | None = None, ) -> dict[str, object]: @@ -68,6 +69,7 @@ class ContentBootstrapAdapter: skip_search_facets=skip_search_facets, publish_content=publish_content, cleanup=cleanup, + cleanup_mode=cleanup_mode, continue_on_error=continue_on_error, created_by=created_by, ) diff --git a/app/bootstrap/cli.py b/app/bootstrap/cli.py index 5ddfe12..a847ce3 100644 --- a/app/bootstrap/cli.py +++ b/app/bootstrap/cli.py @@ -158,9 +158,18 @@ def _add_content_args( "--cleanup", action="store_true", help=( - "Delete existing seeded content for exactly one --module-code before " - "normal reseeding. Cannot be combined with template/content selectors " - "or --seed-search-facets-only." + "Backward-compatible alias for --cleanup-mode archive. " + "Requires exactly one --module-code." + ), + ) + parser.add_argument( + "--cleanup-mode", + choices=("archive", "delete"), + default=None, + help=( + "Reset existing seeded content for --module-code before seeding. " + "archive preserves content rows for compatible reseeds; delete physically " + "removes them and releases unique slug/source_key values." ), ) parser.add_argument("--continue-on-error", action="store_true") @@ -252,6 +261,7 @@ def _validate_content_args( skip_search_facets: bool, publish_content: bool, cleanup: bool = False, + cleanup_mode: str | None = None, ) -> None: if template_codes and (not module_codes or len(module_codes) != 1): raise SeederError( @@ -265,16 +275,20 @@ def _validate_content_args( if not template_codes or len(template_codes) != 1: raise SeederError("--content-code requires exactly one --template-code") - if cleanup: + if cleanup and cleanup_mode is not None: + raise SeederError("--cleanup cannot be combined with --cleanup-mode") + + effective_cleanup_mode = "archive" if cleanup else cleanup_mode + if effective_cleanup_mode is not None: if not module_codes or len(module_codes) != 1: - raise SeederError("--cleanup requires exactly one --module-code") + raise SeederError("cleanup requires exactly one --module-code") if template_codes or content_codes: raise SeederError( - "--cleanup cannot be combined with --template-code or --content-code" + "cleanup cannot be combined with --template-code or --content-code" ) if seed_search_facets_only: raise SeederError( - "--cleanup cannot be combined with --seed-search-facets-only" + "cleanup cannot be combined with --seed-search-facets-only" ) if seed_search_facets_only: @@ -394,6 +408,7 @@ async def async_main() -> int: skip_search_facets=args.skip_search_facets, publish_content=args.publish_content, cleanup=args.cleanup, + cleanup_mode=args.cleanup_mode, ) result = await orchestrator.run_content( @@ -406,6 +421,7 @@ async def async_main() -> int: skip_search_facets=args.skip_search_facets, publish_content=args.publish_content, cleanup=args.cleanup, + cleanup_mode=args.cleanup_mode, continue_on_error=args.continue_on_error, created_by=args.created_by, ) diff --git a/app/bootstrap/orchestrator.py b/app/bootstrap/orchestrator.py index ed8f529..6899f07 100644 --- a/app/bootstrap/orchestrator.py +++ b/app/bootstrap/orchestrator.py @@ -61,6 +61,7 @@ class BootstrapOrchestrator: skip_search_facets: bool = False, publish_content: bool = False, cleanup: bool = False, + cleanup_mode: str | None = None, continue_on_error: bool = False, created_by: UUID | None = None, ) -> BootstrapRunResult: @@ -76,6 +77,7 @@ class BootstrapOrchestrator: skip_search_facets=skip_search_facets, publish_content=publish_content, cleanup=cleanup, + cleanup_mode=cleanup_mode, continue_on_error=continue_on_error, created_by=created_by, ) diff --git a/app/bootstrap/seed_content/cleanup.py b/app/bootstrap/seed_content/cleanup.py index 2dff38a..eb6d395 100644 --- a/app/bootstrap/seed_content/cleanup.py +++ b/app/bootstrap/seed_content/cleanup.py @@ -24,16 +24,21 @@ class ModuleContentCleanupResult: class ModuleContentCleaner: - """Archive/reset all bootstrap-owned content configuration for one module. + """Reset all bootstrap-owned content configuration for one module. - ``--cleanup`` is a logical module reset, not a destructive schema delete. + Cleanup supports two explicit modes: + + * ``archive`` keeps module-owned content rows and marks them as bootstrap + cleanup archives so a compatible reseed can restore them in place; + * ``delete`` physically removes module-owned content rows so unique slugs + and source keys are released for identity/schema migrations. The module's definition-set rows are retained as stable template identities so their UUIDs remain reusable across subsequent bootstrap runs. Everything owned beneath those sets is reset to a state that the normal idempotent seeders can reconcile: - * content_items are archived/inactivated rather than deleted; + * content_items are archived or deleted according to the selected mode; * module/search projections for those contents are removed; * attribute_definitions are deactivated rather than deleted; * attribute_definition_members are deleted because the table has no @@ -43,10 +48,9 @@ class ModuleContentCleaner: deactivated and reused by the facet seeder; * attribute_definition_sets remain active and keep their UUIDs. - Archived content receives a private metadata marker. ContentSeeder uses - that marker to distinguish a bootstrap cleanup archive from a genuinely - business-archived record, and only the former may be restored automatically - during reseeding. + Archive mode adds a private metadata marker. ContentSeeder uses that marker + to distinguish a bootstrap cleanup archive from a genuinely business-archived + record, and only the former may be restored automatically during reseeding. Callers own the transaction boundary. This class never commits. """ @@ -57,17 +61,28 @@ class ModuleContentCleaner: self._session = session self._schema = resolve_content_schema(schema) - async def cleanup(self, module_code: str) -> ModuleContentCleanupResult: - normalized_code = module_code.strip().upper() + async def cleanup( + self, + module_code: str, + *, + mode: str = "archive", + ) -> ModuleContentCleanupResult: + normalized_code = module_code.strip().lower() if not normalized_code: raise ValueError("module_code must be a non-empty string") + normalized_mode = mode.strip().lower() + if normalized_mode not in {"archive", "delete"}: + raise ValueError( + "cleanup mode must be either 'archive' or 'delete'" + ) + module_id = await self._session.scalar( text( f""" SELECT id FROM {self._schema}.modules - WHERE upper(code) = :module_code + WHERE lower(code) = :module_code """ ), {"module_code": normalized_code}, @@ -99,12 +114,12 @@ class ModuleContentCleaner: INSERT INTO tmp_acupedia_module_cleanup_sets (definition_set_id) SELECT ads.id FROM {self._schema}.attribute_definition_sets ads - WHERE upper(ads.code) LIKE :template_pattern - OR upper(ads.attribute_prefix_code) LIKE :template_pattern + WHERE lower(ads.code) LIKE :template_pattern + OR lower(ads.attribute_prefix_code) LIKE :template_pattern ON CONFLICT (definition_set_id) DO NOTHING """ ), - {"template_pattern": f"{normalized_code}_CT%"}, + {"template_pattern": f"{normalized_code}_ct%"}, ) definition_set_count = int( @@ -186,31 +201,45 @@ class ModuleContentCleaner: {"module_id": module_id}, ) - # Archive content rather than deleting it. Keep attributes/history in - # place until the content seeder restores a row; _seed_row already - # replaces content_attributes for a successfully reseeded item. - content_result = await self._session.execute( - text( - f""" - UPDATE {self._schema}.content_items ci - SET status = 'archived', - is_active = false, - published_at = null, - metadata = coalesce(ci.metadata, '{{}}'::jsonb) - || jsonb_build_object( - '_bootstrap_cleanup', - jsonb_build_object( - 'module_code', CAST(:module_code AS text), - 'archived_at', to_jsonb(now()) - ) - ), - updated_at = now() - FROM tmp_acupedia_module_cleanup_content t - WHERE ci.id = t.content_id - """ - ), - {"module_code": normalized_code}, - ) + if normalized_mode == "delete": + # Development reset: physically delete module-owned content rows so + # unique slugs/source_keys are released for identity/schema changes. + # Content-owned dependants are removed by FK cascade; runtime + # projections and module associations were removed explicitly above. + content_result = await self._session.execute( + text( + f""" + DELETE FROM {self._schema}.content_items ci + USING tmp_acupedia_module_cleanup_content t + WHERE ci.id = t.content_id + """ + ) + ) + else: + # Safe/reset mode: retain content rows and mark them as bootstrap + # cleanup archives. A compatible reseed can restore the same row. + content_result = await self._session.execute( + text( + f""" + UPDATE {self._schema}.content_items ci + SET status = 'archived', + is_active = false, + published_at = null, + metadata = coalesce(ci.metadata, '{{}}'::jsonb) + || jsonb_build_object( + '_bootstrap_cleanup', + jsonb_build_object( + 'module_code', CAST(:module_code AS text), + 'archived_at', to_jsonb(now()) + ) + ), + updated_at = now() + FROM tmp_acupedia_module_cleanup_content t + WHERE ci.id = t.content_id + """ + ), + {"module_code": normalized_code}, + ) # Capture all current definitions owned by the module's stable sets. await self._session.execute( diff --git a/app/bootstrap/seed_content/contents.py b/app/bootstrap/seed_content/contents.py index a001090..bfad8d1 100644 --- a/app/bootstrap/seed_content/contents.py +++ b/app/bootstrap/seed_content/contents.py @@ -134,8 +134,8 @@ class ContentSeeder: "type": "content_ref", "label": "ST-36", "target": { - "module_code": "M0001", - "template_code": "M0001_CT0003", + "module_code": "m0001", + "template_code": "m0001_ct0003", "source_code": "ST-36" } } @@ -146,9 +146,9 @@ class ContentSeeder: "type": "content_ref", "label": "ST-36", "target": { - "module_code": "M0001", - "template_code": "M0001_CT0003", - "source_key": "M0001_CT0003:st-36" + "module_code": "m0001", + "template_code": "m0001_ct0003", + "source_key": "m0001_ct0003:st-36" } } @@ -206,10 +206,10 @@ class ContentSeeder: module_code = cls._required_content_reference_string( target_dict, "module_code" - ).upper() + ).lower() template_code = cls._required_content_reference_string( target_dict, "template_code" - ).upper() + ).lower() source_code = cls._required_content_reference_string( target_dict, "source_code" ) diff --git a/app/bootstrap/seed_content/definitions.py b/app/bootstrap/seed_content/definitions.py index d098976..b69ee0f 100644 --- a/app/bootstrap/seed_content/definitions.py +++ b/app/bootstrap/seed_content/definitions.py @@ -127,7 +127,7 @@ class AttributeDefinitionSeeder: ) -> DefinitionSet: code = str( document["code"] - ).strip() + ).strip().lower() name = str( document["name"] @@ -137,7 +137,7 @@ class AttributeDefinitionSeeder: document[ "attribute_prefix_code" ] - ).strip() + ).strip().lower() attribute_prefix_name = str( document[ @@ -174,9 +174,8 @@ class AttributeDefinitionSeeder: code, attribute_prefix_code from {self._schema}.attribute_definition_sets - where code = :code - or attribute_prefix_code = - :attribute_prefix_code + where lower(code) = :code + or lower(attribute_prefix_code) = :attribute_prefix_code for update """ ), diff --git a/app/bootstrap/seed_content/models.py b/app/bootstrap/seed_content/models.py index 241d525..efdb5c7 100644 --- a/app/bootstrap/seed_content/models.py +++ b/app/bootstrap/seed_content/models.py @@ -86,6 +86,7 @@ class ModuleManifest: description: str | None short_description: str | None kind: str | None + default_template_code: str | None metadata: dict[str, Any] content_mapping: tuple[ModuleContentMapping, ...] diff --git a/app/bootstrap/seed_content/modules.py b/app/bootstrap/seed_content/modules.py index 9a5038d..23ed6c8 100644 --- a/app/bootstrap/seed_content/modules.py +++ b/app/bootstrap/seed_content/modules.py @@ -35,17 +35,43 @@ class ModuleSeeder: release_version = str(metadata.get("version")).strip() if metadata.get("version") is not None else None status = config.status + # Bootstrap migration lookup: source manifests are canonical lowercase, + # but an existing development database may still contain the pre-migration + # uppercase module code. Resolve that physical row by case-insensitive code + # or by its unique slug, then canonicalize it in-place below. This is a + # seeding/migration concern only; runtime module identity remains exact + # lowercase. result = await self._session.execute( - text(f"select id from {self._schema}.modules where code = :code for update"), - {"code": config.code}, + text( + f""" + select id, code, slug + from {self._schema}.modules + where lower(code) = :code + or slug = :slug + for update + """ + ), + {"code": config.code, "slug": slug}, ) - existing_id = result.scalar_one_or_none() + matches = result.mappings().all() + if len(matches) > 1: + identities = [ + {"id": str(row["id"]), "code": row["code"], "slug": row["slug"]} + for row in matches + ] + raise ModuleValidationError( + "Multiple module rows match the requested bootstrap identity: " + f"code={config.code!r}, slug={slug!r}, matches={identities!r}" + ) + match = matches[0] if matches else None + existing_id = match["id"] if match else None params = { "code": config.code, "name": manifest.name, "slug": slug, "description": manifest.description, + "default_template_code": manifest.default_template_code, "status": status, "is_active": status not in {"inactive", "archived"}, "release_version": release_version, @@ -56,9 +82,11 @@ class ModuleSeeder: await self._session.execute( text(f""" update {self._schema}.modules - set name = :name, + set code = :code, + name = :name, slug = :slug, description = :description, + default_template_code = :default_template_code, status = cast(:status as {self._schema}.module_status_enum), is_active = :is_active, release_version = :release_version, @@ -74,10 +102,10 @@ class ModuleSeeder: await self._session.execute( text(f""" insert into {self._schema}.modules ( - id, code, name, slug, description, status, is_active, + id, code, name, slug, description, default_template_code, status, is_active, preview_enabled, preview_item_limit, release_version, metadata ) values ( - :id, :code, :name, :slug, :description, + :id, :code, :name, :slug, :description, :default_template_code, cast(:status as {self._schema}.module_status_enum), :is_active, false, 0, :release_version, cast(:metadata as jsonb) ) diff --git a/app/bootstrap/seed_content/orchestrator.py b/app/bootstrap/seed_content/orchestrator.py index 6c76b15..240ee1c 100644 --- a/app/bootstrap/seed_content/orchestrator.py +++ b/app/bootstrap/seed_content/orchestrator.py @@ -58,13 +58,24 @@ class SeedOrchestrator: skip_search_facets: bool = False, publish_content: bool = False, cleanup: bool = False, + cleanup_mode: str | None = None, continue_on_error: bool = False, created_by: UUID | None = None, ) -> tuple[ModuleProcessSummary, ...]: entries = parse_config_document(load_json(config_path), modules_root=modules_root) summaries: list[ModuleProcessSummary] = [] - if cleanup: + if cleanup and cleanup_mode is not None: + raise ModuleValidationError( + "cleanup alias cannot be combined with an explicit cleanup mode" + ) + + effective_cleanup_mode = "archive" if cleanup else cleanup_mode + if effective_cleanup_mode is not None: + if effective_cleanup_mode not in {"archive", "delete"}: + raise ModuleValidationError( + f"unsupported cleanup mode: {effective_cleanup_mode!r}" + ) if not module_codes or len(module_codes) != 1: raise ModuleValidationError( "cleanup requires exactly one module code" @@ -83,18 +94,19 @@ class SeedOrchestrator: if module_codes and entry.code not in module_codes: continue - if cleanup: + if effective_cleanup_mode is not None: async with self._session.begin(): cleanup_result = await ModuleContentCleaner( self._session, schema=self._schema - ).cleanup(entry.code) + ).cleanup(entry.code, mode=effective_cleanup_mode) await self._session.execute(text("SET CONSTRAINTS ALL IMMEDIATE")) logger.info( - "Archived module bootstrap state: module=%s definition_sets=%s " + "Cleaned module bootstrap state: mode=%s module=%s definition_sets=%s " "contents=%s search_facets=%s search_documents=%s associations=%s " "content_items=%s definitions=%s members_removed=%s " "presentation_contracts=%s search_mappings=%s", + effective_cleanup_mode, cleanup_result.module_code, cleanup_result.definition_set_count, cleanup_result.content_count, @@ -213,12 +225,12 @@ class SeedOrchestrator: manifest = parse_module_manifest(load_json(module_json_path), module_dir=config.path) requested_template_codes = ( - {code.strip().upper() for code in template_codes if code.strip()} + {code.strip().lower() for code in template_codes if code.strip()} if template_codes else None ) if requested_template_codes: - manifest_codes = {mapping.code.upper() for mapping in manifest.content_mapping} + manifest_codes = {mapping.code for mapping in manifest.content_mapping} missing_template_codes = requested_template_codes - manifest_codes if missing_template_codes: raise ModuleValidationError( @@ -245,7 +257,7 @@ class SeedOrchestrator: mapping_failed = False for mapping in manifest.content_mapping: - if requested_template_codes and mapping.code.upper() not in requested_template_codes: + if requested_template_codes and mapping.code not in requested_template_codes: continue try: @@ -257,7 +269,7 @@ class SeedOrchestrator: raise ModuleValidationError(f"Data file not found: {mapping.data_path}") template_document = load_json(mapping.template_path) - template_code = str(template_document.get("code", "")).strip() + template_code = str(template_document.get("code", "")).strip().lower() if template_code != mapping.code: raise ModuleValidationError( f"content_mapping code {mapping.code!r} does not match " diff --git a/app/bootstrap/seed_content/search_facets.py b/app/bootstrap/seed_content/search_facets.py index cb9196b..a0fe7df 100644 --- a/app/bootstrap/seed_content/search_facets.py +++ b/app/bootstrap/seed_content/search_facets.py @@ -46,7 +46,7 @@ class SearchFacetSeeder: if not isinstance(facets, list): raise SearchFacetSeedError("search_facets.json.facets must be an array") - module_code = module_code.strip().upper() + module_code = module_code.strip().lower() module_result = await self.session.execute( text( f"select id from {self.schema}.modules where code = :code" @@ -131,7 +131,7 @@ class SearchFacetSeeder: template_code = _required_string( mapping_raw.get("template_code"), f"facet[{code}].mappings[{index}].template_code", - ).upper() + ).lower() definition_result = await self.session.execute( text( diff --git a/app/bootstrap/seed_content/validators.py b/app/bootstrap/seed_content/validators.py index 1cfe7e5..c5bf0a4 100644 --- a/app/bootstrap/seed_content/validators.py +++ b/app/bootstrap/seed_content/validators.py @@ -80,7 +80,7 @@ def build_source_key(*, template_code: str, source_code: str) -> str: """ normalized_template = require_non_empty_string( template_code, "template_code" - ).upper() + ).lower() normalized_source_code = require_non_empty_string( source_code, "source_code" ) @@ -448,7 +448,7 @@ def parse_config_document(document: Mapping[str, Any], *, modules_root: Path) -> raise ModuleValidationError(f"modules[{index}] must be an object") name = require_non_empty_string(raw.get("name"), f"modules[{index}].name") - code = require_non_empty_string(raw.get("code"), f"modules[{index}].code") + code = require_non_empty_string(raw.get("code"), f"modules[{index}].code").lower() path_value = require_non_empty_string(raw.get("path"), f"modules[{index}].path") status = require_non_empty_string(raw.get("status"), f"modules[{index}].status") @@ -465,7 +465,7 @@ def parse_config_document(document: Mapping[str, Any], *, modules_root: Path) -> def parse_module_manifest(document: Mapping[str, Any], *, module_dir: Path) -> ModuleManifest: name = require_non_empty_string(document.get("name"), "module.name") - code = require_non_empty_string(document.get("code"), "module.code") + code = require_non_empty_string(document.get("code"), "module.code").lower() raw_mapping = document.get("content_mapping") if not isinstance(raw_mapping, list) or not raw_mapping: @@ -479,7 +479,7 @@ def parse_module_manifest(document: Mapping[str, Any], *, module_dir: Path) -> M raise ModuleValidationError(f"content_mapping[{index}] must be an object") mapping_name = require_non_empty_string(raw.get("name"), f"content_mapping[{index}].name") - mapping_code = require_non_empty_string(raw.get("code"), f"content_mapping[{index}].code") + mapping_code = require_non_empty_string(raw.get("code"), f"content_mapping[{index}].code").lower() data_path = require_non_empty_string(raw.get("data_path"), f"content_mapping[{index}].data_path") template_path = require_non_empty_string(raw.get("template_path"), f"content_mapping[{index}].template_path") @@ -495,6 +495,19 @@ def parse_module_manifest(document: Mapping[str, Any], *, module_dir: Path) -> M template_path=(module_dir / template_path).resolve(), )) + default_template_code_raw = document.get("default_template_code") + default_template_code: str | None = None + if default_template_code_raw is not None: + default_template_code = require_non_empty_string( + default_template_code_raw, + "module.default_template_code", + ).lower() + if default_template_code not in seen_codes: + raise ModuleValidationError( + f"module.default_template_code {default_template_code!r} must reference " + f"a code declared in module {code!r} content_mapping" + ) + metadata = document.get("metadata") or {} if not isinstance(metadata, Mapping): raise ModuleValidationError("module.metadata must be an object") @@ -505,6 +518,7 @@ def parse_module_manifest(document: Mapping[str, Any], *, module_dir: Path) -> M description=document.get("description"), short_description=document.get("short_description"), kind=document.get("kind"), + default_template_code=default_template_code, metadata=dict(metadata), content_mapping=tuple(mappings), ) diff --git a/app/bootstrap/seed_media/identity.py b/app/bootstrap/seed_media/identity.py index 2180fc7..c77f7e5 100644 --- a/app/bootstrap/seed_media/identity.py +++ b/app/bootstrap/seed_media/identity.py @@ -19,7 +19,7 @@ def slugify(value: str) -> str: def build_source_key(*, template_code: str, source_code: str) -> str: normalized_template = require_non_empty_string( template_code, "template_code" - ).upper() + ).lower() normalized_source_code = require_non_empty_string( source_code, "source_code" ) @@ -44,7 +44,7 @@ def canonical_media_filename( extension = f".{extension}" return ( - f"{template_code.upper()}--{source_component}--" + f"{require_non_empty_string(template_code, 'template_code').lower()}--{source_component}--" f"{usage_component}--{ordinal:02d}{extension}" ) @@ -57,6 +57,6 @@ def build_storage_key( filename: str, ) -> str: return ( - f"images/{module_code.upper()}/{template_code.upper()}/" + f"images/{require_non_empty_string(module_code, 'module_code').lower()}/{require_non_empty_string(template_code, 'template_code').lower()}/" f"{slugify(source_code)}/{Path(filename).name}" ) diff --git a/app/bootstrap/seed_media/models.py b/app/bootstrap/seed_media/models.py index 3d79de7..2d55887 100644 --- a/app/bootstrap/seed_media/models.py +++ b/app/bootstrap/seed_media/models.py @@ -12,10 +12,17 @@ SUPPORTED_MIME_TYPES = {"image/webp", "image/png", "image/jpeg"} class MediaTarget(BaseModel): model_config = ConfigDict(extra="forbid") - module_code: str = Field(pattern=r"^M\d{4}$") - template_code: str = Field(pattern=r"^M\d{4}_CT\d{4}$") + module_code: str = Field(pattern=r"^m\d{4}$") + template_code: str = Field(pattern=r"^m\d{4}_ct\d{4}$") source_code: str = Field(min_length=1) + @field_validator("module_code", "template_code", mode="before") + @classmethod + def normalize_codes(cls, value: str) -> str: + if not isinstance(value, str): + return value + return value.strip().lower() + @field_validator("source_code") @classmethod def strip_source_code(cls, value: str) -> str: @@ -50,9 +57,16 @@ class MediaManifest(BaseModel): model_config = ConfigDict(extra="forbid") version: Literal["1.0"] = "1.0" - module_code: str = Field(pattern=r"^M\d{4}$") + module_code: str = Field(pattern=r"^m\d{4}$") media: list[MediaEntry] = Field(default_factory=list) + @field_validator("module_code", mode="before") + @classmethod + def normalize_module_code(cls, value: str) -> str: + if not isinstance(value, str): + return value + return value.strip().lower() + @model_validator(mode="after") def validate_module_consistency(self) -> "MediaManifest": for index, entry in enumerate(self.media): diff --git a/app/cli/bootstrap.py b/app/cli/bootstrap.py index dfe9f0b..0dab501 100644 --- a/app/cli/bootstrap.py +++ b/app/cli/bootstrap.py @@ -158,8 +158,18 @@ def _add_content_args( "--cleanup", action="store_true", help=( - "Delete existing seeded content for --module-code before seeding. " - "Requires --module-code. Module/template/definition configuration is preserved." + "Backward-compatible alias for --cleanup-mode archive. " + "Requires exactly one --module-code." + ), + ) + parser.add_argument( + "--cleanup-mode", + choices=("archive", "delete"), + default=None, + help=( + "Reset existing seeded content for --module-code before seeding. " + "archive preserves content rows for compatible reseeds; delete physically " + "removes them and releases unique slug/source_key values." ), ) parser.add_argument("--continue-on-error", action="store_true") @@ -250,6 +260,7 @@ def _validate_content_args( skip_search_facets: bool, publish_content: bool, cleanup: bool = False, + cleanup_mode: str | None = None, ) -> None: if template_codes and (not module_codes or len(module_codes) != 1): raise SeederError( @@ -263,16 +274,20 @@ def _validate_content_args( if not template_codes or len(template_codes) != 1: raise SeederError("--content-code requires exactly one --template-code") - if cleanup: + if cleanup and cleanup_mode is not None: + raise SeederError("--cleanup cannot be combined with --cleanup-mode") + + effective_cleanup_mode = "archive" if cleanup else cleanup_mode + if effective_cleanup_mode is not None: if not module_codes or len(module_codes) != 1: - raise SeederError("--cleanup requires exactly one --module-code") + raise SeederError("cleanup requires exactly one --module-code") if template_codes or content_codes: raise SeederError( - "--cleanup cannot be combined with --template-code or --content-code" + "cleanup cannot be combined with --template-code or --content-code" ) if seed_search_facets_only: raise SeederError( - "--cleanup cannot be combined with --seed-search-facets-only" + "cleanup cannot be combined with --seed-search-facets-only" ) if seed_search_facets_only: @@ -393,6 +408,7 @@ async def async_main() -> int: skip_search_facets=args.skip_search_facets, publish_content=args.publish_content, cleanup=args.cleanup, + cleanup_mode=args.cleanup_mode, ) result = await orchestrator.run_content( @@ -405,6 +421,7 @@ async def async_main() -> int: skip_search_facets=args.skip_search_facets, publish_content=args.publish_content, cleanup=args.cleanup, + cleanup_mode=args.cleanup_mode, continue_on_error=args.continue_on_error, created_by=args.created_by, ) @@ -426,8 +443,12 @@ async def async_main() -> int: elif args.command == "validate": result = await orchestrator.run_validate() - elif args.command == "content" and args.cleanup and not args.module_code: - parser.error("--cleanup requires --module-code") + elif ( + args.command == "content" + and (args.cleanup or args.cleanup_mode is not None) + and not args.module_code + ): + parser.error("cleanup requires --module-code") elif args.command == "all": module_codes = ( set(args.content_module_codes) diff --git a/app/db/migrations/20260912_add_default_template_code_to_modules.sql b/app/db/migrations/20260912_add_default_template_code_to_modules.sql new file mode 100644 index 0000000..1184a7d --- /dev/null +++ b/app/db/migrations/20260912_add_default_template_code_to_modules.sql @@ -0,0 +1,8 @@ +-- Adds the canonical module landing-template code. +-- Safe to run repeatedly. Existing modules remain NULL until reseeded from module.json. + +ALTER TABLE content.modules + ADD COLUMN IF NOT EXISTS default_template_code text; + +COMMENT ON COLUMN content.modules.default_template_code IS + 'Template code opened by default when entering this module; seeded from module.json.'; diff --git a/app/db/models/content.py b/app/db/models/content.py index 96526cf..78936dd 100644 --- a/app/db/models/content.py +++ b/app/db/models/content.py @@ -589,6 +589,7 @@ class Module(Base): name: Mapped[str] = mapped_column(Text, nullable=False) slug: Mapped[str] = mapped_column(Text, nullable=False) description: Mapped[str | None] = mapped_column(Text) + default_template_code: Mapped[str | None] = mapped_column(Text) thumbnail_media_asset_id: Mapped[UUID | None] = mapped_column(PGUUID(as_uuid=True), ForeignKey(f"{CONTENT_SCHEMA}.media_assets.id", ondelete="SET NULL")) status: Mapped[ModuleStatus] = mapped_column(MODULE_STATUS_ENUM, nullable=False, server_default=text("'draft'")) is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true")) diff --git a/app/features/admin/services/module_service.py b/app/features/admin/services/module_service.py index 91f61b3..2eb1996 100644 --- a/app/features/admin/services/module_service.py +++ b/app/features/admin/services/module_service.py @@ -41,6 +41,7 @@ class AdminModuleService: "slug": m.slug, "name": m.name, "description": m.description or "", + "default_template_code": m.default_template_code, "status": getattr(m.status, "value", m.status), "is_active": m.is_active, "category": category, diff --git a/app/features/content/repository.py b/app/features/content/repository.py index ca477fd..c15620a 100644 --- a/app/features/content/repository.py +++ b/app/features/content/repository.py @@ -8,7 +8,7 @@ from typing import Any from uuid import UUID from datetime import datetime -from sqlalchemy import select, bindparam, text +from sqlalchemy import select, bindparam, text, func from sqlalchemy.ext.asyncio import AsyncSession from app.db.models import ( @@ -366,33 +366,41 @@ class ContentRepository: result = await self._session.execute(stmt) requested = set(references) + requested_by_identity: dict[tuple[str, str, str], list[ContentReferenceLookup]] = {} + for ref in requested: + identity = ( + ref.module_code, + ref.template_code, + ref.source_key, + ) + requested_by_identity.setdefault(identity, []).append(ref) + resolved: dict[ContentReferenceLookup, ResolvedContentReference] = {} for row in result.mappings(): - lookup = ContentReferenceLookup( - module_code=str(row["module_code"]), - template_code=str(row["template_code"]), - source_key=str(row["source_key"]), + row_identity = ( + str(row["module_code"]), + str(row["template_code"]), + str(row["source_key"]), ) - - # The broad IN filters intentionally over-fetch combinations; only - # exact requested triples are accepted. - if lookup not in requested: + matching_requests = requested_by_identity.get(row_identity, []) + if not matching_requests: continue - existing = resolved.get(lookup) - if existing is not None and existing.content_id != row["content_id"]: - raise ContentReferenceResolutionError( - "Content reference resolves to multiple content items: " - f"module_code={lookup.module_code!r}, " - f"template_code={lookup.template_code!r}, " - f"source_key={lookup.source_key!r}" - ) + for lookup in matching_requests: + existing = resolved.get(lookup) + if existing is not None and existing.content_id != row["content_id"]: + raise ContentReferenceResolutionError( + "Content reference resolves to multiple content items: " + f"module_code={lookup.module_code!r}, " + f"template_code={lookup.template_code!r}, " + f"source_key={lookup.source_key!r}" + ) - resolved[lookup] = ResolvedContentReference( - lookup=lookup, - content_id=row["content_id"], - ) + resolved[lookup] = ResolvedContentReference( + lookup=lookup, + content_id=row["content_id"], + ) missing = sorted( requested.difference(resolved.keys()), diff --git a/app/features/content/schema.py b/app/features/content/schema.py index ddaf74a..02172f2 100644 --- a/app/features/content/schema.py +++ b/app/features/content/schema.py @@ -54,6 +54,7 @@ class ModuleSummaryResponse(BaseModel): code: str name: str slug: str + default_template_code: str | None = None class ModuleResponse(BaseModel): @@ -66,6 +67,7 @@ class ModuleResponse(BaseModel): name: str slug: str description: str | None = None + default_template_code: str | None = None thumbnail_media_asset_id: UUID | None = None status: ModuleStatus is_active: bool diff --git a/app/features/content/service.py b/app/features/content/service.py index 4dbff34..13c78b5 100644 --- a/app/features/content/service.py +++ b/app/features/content/service.py @@ -1302,7 +1302,14 @@ class ContentService: ) if match is None: return None - return match.group(1).upper() + # Preserve the canonical casing stored in the template code. + # + # Module/template identifiers are data identities, not display values. + # Earlier code forced the derived module prefix to uppercase, which + # caused lowercase canonical templates such as ``m0042_ct0001`` to + # produce ``M0042`` in the contract response and to fail module/template + # ownership checks against a persisted ``m0042`` module code. + return match.group(1) @staticmethod def _content_list_item_response( diff --git a/app/features/search/repository.py b/app/features/search/repository.py index a16a76e..d5c1ea7 100644 --- a/app/features/search/repository.py +++ b/app/features/search/repository.py @@ -148,8 +148,10 @@ class SearchRepository: params: dict[str, Any] = {} where = ["is_active = true", "status = 'active'"] if effective_scope.module_codes: - params["capability_module_codes"] = effective_scope.module_codes - where.append("code = any(:capability_module_codes)") + params["capability_module_codes"] = [ + code.strip() for code in effective_scope.module_codes if code and code.strip() + ] + where.append("code = any(cast(:capability_module_codes as text[]))") result = await self.session.execute( text( @@ -439,14 +441,16 @@ class SearchRepository: params: dict[str, Any] = {} module_clause = "" if module_codes: - params["module_codes"] = [code.strip().upper() for code in module_codes] + params["module_codes"] = [ + code.strip() for code in module_codes if code and code.strip() + ] module_clause = f""" and exists ( select 1 from {self.schema}.module_contents mc join {self.schema}.modules m on m.id = mc.module_id where mc.content_id = ci.id - and m.code = any(:module_codes) + and m.code = any(cast(:module_codes as text[])) ) """ result = await self.session.execute( @@ -471,14 +475,16 @@ class SearchRepository: def _scope_sql(self, scope: SearchScope, params: dict[str, Any], *, ci_alias: str = "ci") -> str: clauses: list[str] = [] if scope.module_codes: - params["scope_module_codes"] = scope.module_codes + params["scope_module_codes"] = [ + code.strip() for code in scope.module_codes if code and code.strip() + ] clauses.append( 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(:scope_module_codes) + and scope_m.code = any(cast(:scope_module_codes as text[])) and scope_m.is_active = true )""" ) diff --git a/app/features/search/schema.py b/app/features/search/schema.py index 1a0a16b..a48d55b 100644 --- a/app/features/search/schema.py +++ b/app/features/search/schema.py @@ -46,7 +46,7 @@ class SearchScope(StrictModel): @model_validator(mode="after") def normalize(self) -> "SearchScope": if self.module_codes is not None: - values = [value.strip().upper() for value in self.module_codes if value.strip()] + values = [value.strip() for value in self.module_codes if value.strip()] self.module_codes = list(dict.fromkeys(values)) or None if self.content_kinds is not None: values = [value.strip().lower() for value in self.content_kinds if value.strip()] diff --git a/app/main.py b/app/main.py index 824428b..fc23f18 100644 --- a/app/main.py +++ b/app/main.py @@ -20,11 +20,8 @@ from app.features.webhooks import router as webhooks_router from app.cache.health import router as cache_health_router from app.core.settings import settings -<<<<<<< HEAD from sqlalchemy.ext.asyncio import AsyncSession -======= from app.core.exception_handlers import register_exception_handlers ->>>>>>> origin/main from app.db.session import get_db_session from app.lifespan import lifespan diff --git a/docs/accupedia_db_v5.sql b/docs/accupedia_db_v5.sql index 6a66844..b210f07 100644 --- a/docs/accupedia_db_v5.sql +++ b/docs/accupedia_db_v5.sql @@ -2915,4 +2915,7 @@ create index if not exists ix_content_search_facets_content create index if not exists ix_content_search_facets_label_trgm on content.content_search_facets using gin (value_label gin_trgm_ops); +ALTER TABLE content.modules + ADD COLUMN IF NOT EXISTS default_template_code text; + commit; \ No newline at end of file diff --git a/versions/acupedia-api-v0.1.zip b/versions/acupedia-api-v0.1.zip deleted file mode 100644 index 0053107..0000000 Binary files a/versions/acupedia-api-v0.1.zip and /dev/null differ diff --git a/versions/acupedia-api.zip b/versions/acupedia-api.zip deleted file mode 100644 index 69872b0..0000000 Binary files a/versions/acupedia-api.zip and /dev/null differ diff --git a/versions/app-v0.2.zip b/versions/app-v0.2.zip deleted file mode 100644 index 40d6d68..0000000 Binary files a/versions/app-v0.2.zip and /dev/null differ