feat: add material library crud
这个提交存在于:
父节点
31c4b753d2
当前提交
aae0ec5df7
共有 6 个文件被更改,包括 945 次插入 和 1 次删除
|
|
@ -1 +1,78 @@
|
|||
"""Material DTO placeholder."""
|
||||
"""Material library DTOs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MaterialCategory:
|
||||
category_id: str
|
||||
name: str
|
||||
parent_id: str | None
|
||||
category_type: str
|
||||
sort_order: int
|
||||
metadata: dict[str, Any]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"category_id": self.category_id,
|
||||
"name": self.name,
|
||||
"parent_id": self.parent_id,
|
||||
"category_type": self.category_type,
|
||||
"sort_order": self.sort_order,
|
||||
"metadata": self.metadata,
|
||||
"created_at": self.created_at,
|
||||
"updated_at": self.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Material:
|
||||
material_id: str
|
||||
category_id: str | None
|
||||
display_name: str
|
||||
image_uri: str | None
|
||||
thumbnail_uri: str | None
|
||||
prompt: str | None
|
||||
negative_prompt: str | None
|
||||
tags: list[str]
|
||||
recognition_status: str
|
||||
metadata: dict[str, Any]
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"material_id": self.material_id,
|
||||
"category_id": self.category_id,
|
||||
"display_name": self.display_name,
|
||||
"image_uri": self.image_uri,
|
||||
"thumbnail_uri": self.thumbnail_uri,
|
||||
"prompt": self.prompt,
|
||||
"negative_prompt": self.negative_prompt,
|
||||
"tags": self.tags,
|
||||
"recognition_status": self.recognition_status,
|
||||
"metadata": self.metadata,
|
||||
"created_at": self.created_at,
|
||||
"updated_at": self.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MaterialListResult:
|
||||
items: list[Material]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"items": [item.to_dict() for item in self.items],
|
||||
"total": self.total,
|
||||
"page": self.page,
|
||||
"page_size": self.page_size,
|
||||
}
|
||||
|
|
|
|||
168
backend/routes/material_routes.py
普通文件
168
backend/routes/material_routes.py
普通文件
|
|
@ -0,0 +1,168 @@
|
|||
"""Material library route handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from backend.routes.common import handle_request
|
||||
from backend.services.material_service import MaterialService
|
||||
from core.audit_service import AuditService
|
||||
from core.identity import RequestContext
|
||||
from core.security import require_authenticated, require_permission
|
||||
from database.db_helper import Database, load_database_settings
|
||||
from database.repositories.material_repository import MaterialRepository
|
||||
|
||||
|
||||
def list_material_categories(
|
||||
ctx: RequestContext,
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> list[dict[str, Any]]:
|
||||
require_authenticated(ctx)
|
||||
return [category.to_dict() for category in material_service.list_categories()]
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def create_material_category(
|
||||
ctx: RequestContext,
|
||||
payload: dict[str, Any],
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.create_category(payload, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def update_material_category(
|
||||
ctx: RequestContext,
|
||||
category_id: str,
|
||||
payload: dict[str, Any],
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.update_category(category_id, payload, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def delete_material_category(
|
||||
ctx: RequestContext,
|
||||
category_id: str,
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.delete_category(category_id, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def list_materials(
|
||||
ctx: RequestContext,
|
||||
query: dict[str, Any] | None = None,
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
params = query or {}
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_authenticated(ctx)
|
||||
return material_service.list_materials(
|
||||
category_id=_optional_str(params.get("category_id")),
|
||||
keyword=_optional_str(params.get("keyword")),
|
||||
page=_int_or_default(params.get("page"), 1),
|
||||
page_size=_int_or_default(params.get("page_size"), 30),
|
||||
).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def create_material(
|
||||
ctx: RequestContext,
|
||||
payload: dict[str, Any],
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.create_material(payload, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def get_material(
|
||||
ctx: RequestContext,
|
||||
material_id: str,
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_authenticated(ctx)
|
||||
return material_service.get_material(material_id).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def update_material(
|
||||
ctx: RequestContext,
|
||||
material_id: str,
|
||||
payload: dict[str, Any],
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.update_material(material_id, payload, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def delete_material(
|
||||
ctx: RequestContext,
|
||||
material_id: str,
|
||||
service: MaterialService | None = None,
|
||||
) -> dict:
|
||||
material_service = service or _create_material_service()
|
||||
|
||||
def action() -> dict[str, Any]:
|
||||
require_permission(ctx, "can_manage_materials")
|
||||
return material_service.delete_material(material_id, ctx).to_dict()
|
||||
|
||||
return handle_request(ctx, action)
|
||||
|
||||
|
||||
def _create_material_service() -> MaterialService:
|
||||
database = Database(load_database_settings())
|
||||
return MaterialService(
|
||||
repository=MaterialRepository(database),
|
||||
audit_service=AuditService(database),
|
||||
)
|
||||
|
||||
|
||||
def _optional_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _int_or_default(value: Any, default: int) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
199
backend/services/material_service.py
普通文件
199
backend/services/material_service.py
普通文件
|
|
@ -0,0 +1,199 @@
|
|||
"""Material library service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from backend.dto.common import ApiError, ErrorCode
|
||||
from backend.dto.material_dto import Material, MaterialCategory, MaterialListResult
|
||||
from core.audit_service import AuditService
|
||||
from core.identity import RequestContext
|
||||
from database.repositories.material_repository import MaterialRepository
|
||||
|
||||
|
||||
MATERIAL_STATUSES = {"pending_upload", "pending_recognition", "pending_confirm", "confirmed", "archived"}
|
||||
|
||||
|
||||
class MaterialService:
|
||||
def __init__(self, repository: MaterialRepository, audit_service: AuditService):
|
||||
self.repository = repository
|
||||
self.audit_service = audit_service
|
||||
|
||||
def create_category(self, payload: dict[str, Any], ctx: RequestContext) -> MaterialCategory:
|
||||
name = str(payload.get("name") or "").strip()
|
||||
if not name:
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "category name is required", {"field": "name"})
|
||||
parent_id = payload.get("parent_id")
|
||||
if parent_id and self.repository.get_category(parent_id) is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "parent category not found", {"parent_id": parent_id})
|
||||
category = self.repository.create_category(
|
||||
{
|
||||
"category_id": payload.get("category_id") or new_category_id(),
|
||||
"name": name,
|
||||
"parent_id": parent_id,
|
||||
"category_type": payload.get("category_type", "material"),
|
||||
"sort_order": payload.get("sort_order", 0),
|
||||
"metadata": payload.get("metadata") or {},
|
||||
}
|
||||
)
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="create_material_category",
|
||||
target_type="material_category",
|
||||
target_id=category.category_id,
|
||||
after_snapshot=category.to_dict(),
|
||||
)
|
||||
return category
|
||||
|
||||
def list_categories(self) -> list[MaterialCategory]:
|
||||
return self.repository.list_categories()
|
||||
|
||||
def update_category(self, category_id: str, payload: dict[str, Any], ctx: RequestContext) -> MaterialCategory:
|
||||
before = self.get_category(category_id)
|
||||
if "name" in payload and not str(payload["name"]).strip():
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "category name is required", {"field": "name"})
|
||||
after = self.repository.update_category(category_id, payload)
|
||||
if after is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id})
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="update_material_category",
|
||||
target_type="material_category",
|
||||
target_id=category_id,
|
||||
before_snapshot=before.to_dict(),
|
||||
after_snapshot=after.to_dict(),
|
||||
)
|
||||
return after
|
||||
|
||||
def delete_category(self, category_id: str, ctx: RequestContext) -> MaterialCategory:
|
||||
before = self.repository.delete_category(category_id)
|
||||
if before is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id})
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="delete_material_category",
|
||||
target_type="material_category",
|
||||
target_id=category_id,
|
||||
before_snapshot=before.to_dict(),
|
||||
)
|
||||
return before
|
||||
|
||||
def get_category(self, category_id: str) -> MaterialCategory:
|
||||
category = self.repository.get_category(category_id)
|
||||
if category is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id})
|
||||
return category
|
||||
|
||||
def create_material(self, payload: dict[str, Any], ctx: RequestContext) -> Material:
|
||||
display_name = str(payload.get("display_name") or "").strip()
|
||||
if not display_name:
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "display_name is required", {"field": "display_name"})
|
||||
self._validate_category(payload.get("category_id"))
|
||||
self._validate_storage_uri(payload.get("image_uri"), "image_uri")
|
||||
self._validate_storage_uri(payload.get("thumbnail_uri"), "thumbnail_uri")
|
||||
status = payload.get("recognition_status", "pending_upload")
|
||||
self._validate_status(status)
|
||||
material = self.repository.create_material(
|
||||
{
|
||||
"material_id": payload.get("material_id") or new_material_id(),
|
||||
"category_id": payload.get("category_id"),
|
||||
"display_name": display_name,
|
||||
"image_uri": payload.get("image_uri"),
|
||||
"thumbnail_uri": payload.get("thumbnail_uri"),
|
||||
"prompt": payload.get("prompt"),
|
||||
"negative_prompt": payload.get("negative_prompt"),
|
||||
"tags": payload.get("tags") or [],
|
||||
"recognition_status": status,
|
||||
"metadata": payload.get("metadata") or {},
|
||||
}
|
||||
)
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="create_material",
|
||||
target_type="material",
|
||||
target_id=material.material_id,
|
||||
after_snapshot=material.to_dict(),
|
||||
)
|
||||
return material
|
||||
|
||||
def list_materials(
|
||||
self,
|
||||
*,
|
||||
category_id: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 30,
|
||||
) -> MaterialListResult:
|
||||
normalized_page = max(page, 1)
|
||||
normalized_page_size = min(max(page_size, 1), 100)
|
||||
items, total = self.repository.list_materials(
|
||||
category_id=category_id,
|
||||
keyword=keyword,
|
||||
page=normalized_page,
|
||||
page_size=normalized_page_size,
|
||||
)
|
||||
return MaterialListResult(items=items, total=total, page=normalized_page, page_size=normalized_page_size)
|
||||
|
||||
def get_material(self, material_id: str) -> Material:
|
||||
material = self.repository.get_material(material_id)
|
||||
if material is None or material.recognition_status == "archived":
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "material not found", {"material_id": material_id})
|
||||
return material
|
||||
|
||||
def update_material(self, material_id: str, payload: dict[str, Any], ctx: RequestContext) -> Material:
|
||||
before = self.get_material(material_id)
|
||||
if "category_id" in payload:
|
||||
self._validate_category(payload.get("category_id"))
|
||||
if "image_uri" in payload:
|
||||
self._validate_storage_uri(payload.get("image_uri"), "image_uri")
|
||||
if "thumbnail_uri" in payload:
|
||||
self._validate_storage_uri(payload.get("thumbnail_uri"), "thumbnail_uri")
|
||||
if "recognition_status" in payload:
|
||||
self._validate_status(payload["recognition_status"])
|
||||
update_payload = dict(payload)
|
||||
if "display_name" in update_payload:
|
||||
update_payload["display_name"] = str(update_payload["display_name"]).strip()
|
||||
if not update_payload["display_name"]:
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, "display_name is required", {"field": "display_name"})
|
||||
after = self.repository.update_material(material_id, update_payload)
|
||||
if after is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "material not found", {"material_id": material_id})
|
||||
self.audit_service.record(
|
||||
ctx=ctx,
|
||||
action="update_material",
|
||||
target_type="material",
|
||||
target_id=material_id,
|
||||
before_snapshot=before.to_dict(),
|
||||
after_snapshot=after.to_dict(),
|
||||
)
|
||||
return after
|
||||
|
||||
def delete_material(self, material_id: str, ctx: RequestContext) -> Material:
|
||||
return self.update_material(material_id, {"recognition_status": "archived"}, ctx)
|
||||
|
||||
def _validate_category(self, category_id: Any) -> None:
|
||||
if category_id and self.repository.get_category(str(category_id)) is None:
|
||||
raise ApiError(ErrorCode.RESOURCE_NOT_FOUND, "category not found", {"category_id": category_id})
|
||||
|
||||
def _validate_status(self, status: Any) -> None:
|
||||
if status not in MATERIAL_STATUSES:
|
||||
raise ApiError(
|
||||
ErrorCode.VALIDATION_FAILED,
|
||||
"unsupported material status",
|
||||
{"field": "recognition_status", "allowed": sorted(MATERIAL_STATUSES)},
|
||||
)
|
||||
|
||||
def _validate_storage_uri(self, uri: Any, field: str) -> None:
|
||||
if uri is None:
|
||||
return
|
||||
if not str(uri).startswith("storage://"):
|
||||
raise ApiError(ErrorCode.VALIDATION_FAILED, f"{field} must use storage://", {"field": field})
|
||||
|
||||
|
||||
def new_category_id() -> str:
|
||||
return f"cat_{uuid4().hex}"
|
||||
|
||||
|
||||
def new_material_id() -> str:
|
||||
return f"mat_{uuid4().hex}"
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
CREATE TABLE IF NOT EXISTS material_categories (
|
||||
category_id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
parent_id TEXT,
|
||||
category_type TEXT NOT NULL DEFAULT 'material',
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
metadata_json TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(parent_id) REFERENCES material_categories(category_id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_material_categories_parent
|
||||
ON material_categories(parent_id, sort_order);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS materials (
|
||||
material_id TEXT PRIMARY KEY,
|
||||
category_id TEXT,
|
||||
display_name TEXT NOT NULL,
|
||||
image_uri TEXT,
|
||||
thumbnail_uri TEXT,
|
||||
prompt TEXT,
|
||||
negative_prompt TEXT,
|
||||
tags_json TEXT,
|
||||
recognition_status TEXT NOT NULL DEFAULT 'pending_upload',
|
||||
metadata_json TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY(category_id) REFERENCES material_categories(category_id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_materials_category
|
||||
ON materials(category_id, created_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_materials_status
|
||||
ON materials(recognition_status);
|
||||
|
|
@ -0,0 +1,327 @@
|
|||
"""Repository for material categories and materials."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from backend.dto.material_dto import Material, MaterialCategory
|
||||
from database.db_helper import Database
|
||||
|
||||
|
||||
CATEGORY_COLUMNS = """
|
||||
category_id,
|
||||
name,
|
||||
parent_id,
|
||||
category_type,
|
||||
sort_order,
|
||||
metadata_json,
|
||||
created_at,
|
||||
updated_at
|
||||
"""
|
||||
|
||||
MATERIAL_COLUMNS = """
|
||||
material_id,
|
||||
category_id,
|
||||
display_name,
|
||||
image_uri,
|
||||
thumbnail_uri,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
tags_json,
|
||||
recognition_status,
|
||||
metadata_json,
|
||||
created_at,
|
||||
updated_at
|
||||
"""
|
||||
|
||||
|
||||
class MaterialRepository:
|
||||
def __init__(self, database: Database):
|
||||
self.database = database
|
||||
|
||||
@property
|
||||
def placeholder(self) -> str:
|
||||
return self.database._placeholder
|
||||
|
||||
def create_category(self, payload: dict[str, Any]) -> MaterialCategory:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(
|
||||
f"""
|
||||
INSERT INTO material_categories (
|
||||
category_id, name, parent_id, category_type, sort_order, metadata_json
|
||||
) VALUES (
|
||||
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}
|
||||
)
|
||||
""",
|
||||
(
|
||||
payload["category_id"],
|
||||
payload["name"],
|
||||
payload.get("parent_id"),
|
||||
payload.get("category_type", "material"),
|
||||
int(payload.get("sort_order", 0)),
|
||||
_json_or_none(payload.get("metadata")),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
category = self.get_category(payload["category_id"])
|
||||
if category is None:
|
||||
raise RuntimeError("material category was inserted but could not be read back")
|
||||
return category
|
||||
|
||||
def get_category(self, category_id: str) -> MaterialCategory | None:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
f"SELECT {CATEGORY_COLUMNS} FROM material_categories WHERE category_id = {placeholder}",
|
||||
(category_id,),
|
||||
).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
return _row_to_category(row) if row else None
|
||||
|
||||
def list_categories(self) -> list[MaterialCategory]:
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {CATEGORY_COLUMNS}
|
||||
FROM material_categories
|
||||
ORDER BY parent_id ASC, sort_order ASC, created_at ASC
|
||||
"""
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [_row_to_category(row) for row in rows]
|
||||
|
||||
def update_category(self, category_id: str, payload: dict[str, Any]) -> MaterialCategory | None:
|
||||
allowed = {"name", "parent_id", "category_type", "sort_order", "metadata"}
|
||||
assignments: list[str] = []
|
||||
params: list[Any] = []
|
||||
placeholder = self.placeholder
|
||||
for key in allowed:
|
||||
if key not in payload:
|
||||
continue
|
||||
column = "metadata_json" if key == "metadata" else key
|
||||
value = _json_or_none(payload[key]) if key == "metadata" else payload[key]
|
||||
assignments.append(f"{column} = {placeholder}")
|
||||
params.append(value)
|
||||
if not assignments:
|
||||
return self.get_category(category_id)
|
||||
assignments.append("updated_at = CURRENT_TIMESTAMP")
|
||||
params.append(category_id)
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(
|
||||
f"UPDATE material_categories SET {', '.join(assignments)} WHERE category_id = {placeholder}",
|
||||
tuple(params),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return self.get_category(category_id)
|
||||
|
||||
def delete_category(self, category_id: str) -> MaterialCategory | None:
|
||||
before = self.get_category(category_id)
|
||||
if before is None:
|
||||
return None
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(f"DELETE FROM material_categories WHERE category_id = {placeholder}", (category_id,))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return before
|
||||
|
||||
def create_material(self, payload: dict[str, Any]) -> Material:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(
|
||||
f"""
|
||||
INSERT INTO materials (
|
||||
material_id,
|
||||
category_id,
|
||||
display_name,
|
||||
image_uri,
|
||||
thumbnail_uri,
|
||||
prompt,
|
||||
negative_prompt,
|
||||
tags_json,
|
||||
recognition_status,
|
||||
metadata_json
|
||||
) VALUES (
|
||||
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder},
|
||||
{placeholder}, {placeholder}, {placeholder}, {placeholder}, {placeholder}
|
||||
)
|
||||
""",
|
||||
(
|
||||
payload["material_id"],
|
||||
payload.get("category_id"),
|
||||
payload["display_name"],
|
||||
payload.get("image_uri"),
|
||||
payload.get("thumbnail_uri"),
|
||||
payload.get("prompt"),
|
||||
payload.get("negative_prompt"),
|
||||
_json_or_none(payload.get("tags") or []),
|
||||
payload.get("recognition_status", "pending_upload"),
|
||||
_json_or_none(payload.get("metadata")),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
material = self.get_material(payload["material_id"])
|
||||
if material is None:
|
||||
raise RuntimeError("material was inserted but could not be read back")
|
||||
return material
|
||||
|
||||
def get_material(self, material_id: str) -> Material | None:
|
||||
placeholder = self.placeholder
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
row = conn.execute(
|
||||
f"SELECT {MATERIAL_COLUMNS} FROM materials WHERE material_id = {placeholder}",
|
||||
(material_id,),
|
||||
).fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
return _row_to_material(row) if row else None
|
||||
|
||||
def list_materials(
|
||||
self,
|
||||
*,
|
||||
category_id: str | None = None,
|
||||
keyword: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 30,
|
||||
) -> tuple[list[Material], int]:
|
||||
placeholder = self.placeholder
|
||||
where = ["recognition_status != 'archived'"]
|
||||
params: list[Any] = []
|
||||
if category_id:
|
||||
where.append(f"category_id = {placeholder}")
|
||||
params.append(category_id)
|
||||
if keyword:
|
||||
where.append(f"(display_name LIKE {placeholder} OR prompt LIKE {placeholder})")
|
||||
like = f"%{keyword}%"
|
||||
params.extend([like, like])
|
||||
where_clause = f"WHERE {' AND '.join(where)}"
|
||||
offset = max(page - 1, 0) * page_size
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
total_row = conn.execute(
|
||||
f"SELECT COUNT(*) AS total FROM materials {where_clause}",
|
||||
tuple(params),
|
||||
).fetchone()
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT {MATERIAL_COLUMNS}
|
||||
FROM materials
|
||||
{where_clause}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT {placeholder} OFFSET {placeholder}
|
||||
""",
|
||||
tuple(params + [page_size, offset]),
|
||||
).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
return [_row_to_material(row) for row in rows], int(total_row["total"] if total_row else 0)
|
||||
|
||||
def update_material(self, material_id: str, payload: dict[str, Any]) -> Material | None:
|
||||
allowed = {
|
||||
"category_id",
|
||||
"display_name",
|
||||
"image_uri",
|
||||
"thumbnail_uri",
|
||||
"prompt",
|
||||
"negative_prompt",
|
||||
"tags",
|
||||
"recognition_status",
|
||||
"metadata",
|
||||
}
|
||||
assignments: list[str] = []
|
||||
params: list[Any] = []
|
||||
placeholder = self.placeholder
|
||||
for key in allowed:
|
||||
if key not in payload:
|
||||
continue
|
||||
column = key
|
||||
value = payload[key]
|
||||
if key == "tags":
|
||||
column = "tags_json"
|
||||
value = _json_or_none(value or [])
|
||||
elif key == "metadata":
|
||||
column = "metadata_json"
|
||||
value = _json_or_none(value)
|
||||
assignments.append(f"{column} = {placeholder}")
|
||||
params.append(value)
|
||||
if not assignments:
|
||||
return self.get_material(material_id)
|
||||
assignments.append("updated_at = CURRENT_TIMESTAMP")
|
||||
params.append(material_id)
|
||||
conn = self.database.connect()
|
||||
try:
|
||||
conn.execute(
|
||||
f"UPDATE materials SET {', '.join(assignments)} WHERE material_id = {placeholder}",
|
||||
tuple(params),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
return self.get_material(material_id)
|
||||
|
||||
|
||||
def _row_to_category(row) -> MaterialCategory:
|
||||
return MaterialCategory(
|
||||
category_id=row["category_id"],
|
||||
name=row["name"],
|
||||
parent_id=row["parent_id"],
|
||||
category_type=row["category_type"],
|
||||
sort_order=int(row["sort_order"] or 0),
|
||||
metadata=_json_loads(row["metadata_json"]),
|
||||
created_at=str(row["created_at"]),
|
||||
updated_at=str(row["updated_at"]),
|
||||
)
|
||||
|
||||
|
||||
def _row_to_material(row) -> Material:
|
||||
return Material(
|
||||
material_id=row["material_id"],
|
||||
category_id=row["category_id"],
|
||||
display_name=row["display_name"],
|
||||
image_uri=row["image_uri"],
|
||||
thumbnail_uri=row["thumbnail_uri"],
|
||||
prompt=row["prompt"],
|
||||
negative_prompt=row["negative_prompt"],
|
||||
tags=_json_loads_list(row["tags_json"]),
|
||||
recognition_status=row["recognition_status"],
|
||||
metadata=_json_loads(row["metadata_json"]),
|
||||
created_at=str(row["created_at"]),
|
||||
updated_at=str(row["updated_at"]),
|
||||
)
|
||||
|
||||
|
||||
def _json_or_none(value: Any | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def _json_loads(value: str | None) -> dict[str, Any]:
|
||||
if not value:
|
||||
return {}
|
||||
return json.loads(value)
|
||||
|
||||
|
||||
def _json_loads_list(value: str | None) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
loaded = json.loads(value)
|
||||
return [str(item) for item in loaded] if isinstance(loaded, list) else []
|
||||
137
tests/test_material_service.py
普通文件
137
tests/test_material_service.py
普通文件
|
|
@ -0,0 +1,137 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from backend.routes.material_routes import (
|
||||
create_material,
|
||||
create_material_category,
|
||||
delete_material,
|
||||
get_material,
|
||||
list_material_categories,
|
||||
list_materials,
|
||||
update_material,
|
||||
)
|
||||
from backend.services.material_service import MaterialService
|
||||
from core.audit_service import AuditService
|
||||
from core.identity import RequestContext
|
||||
from database.db_helper import Database, DatabaseSettings, SqliteSettings
|
||||
from database.repositories.material_repository import MaterialRepository
|
||||
|
||||
|
||||
class MaterialServiceTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.database = Database(
|
||||
DatabaseSettings(sqlite=SqliteSettings(path=str(Path(self.tmp.name) / "imagestudio.db")))
|
||||
)
|
||||
self.database.initialize()
|
||||
self.audit_service = AuditService(self.database)
|
||||
self.material_service = MaterialService(MaterialRepository(self.database), self.audit_service)
|
||||
self.ctx = RequestContext.from_astrbot(
|
||||
username="admin",
|
||||
user_id="user_001",
|
||||
permissions={"can_manage_materials"},
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_category_and_material_crud(self):
|
||||
category = self.material_service.create_category(
|
||||
{"name": "Upper", "category_id": "cat_upper", "sort_order": 10},
|
||||
self.ctx,
|
||||
)
|
||||
self.assertEqual(category.name, "Upper")
|
||||
|
||||
material = self.material_service.create_material(
|
||||
{
|
||||
"category_id": category.category_id,
|
||||
"display_name": "White blouse",
|
||||
"image_uri": "storage://materials/white_blouse.png",
|
||||
"thumbnail_uri": "storage://materials/white_blouse_thumb.png",
|
||||
"prompt": "white blouse, clean collar",
|
||||
"tags": ["upper", "white"],
|
||||
"recognition_status": "confirmed",
|
||||
},
|
||||
self.ctx,
|
||||
)
|
||||
self.assertTrue(material.material_id.startswith("mat_"))
|
||||
self.assertEqual(material.tags, ["upper", "white"])
|
||||
|
||||
listed = self.material_service.list_materials(category_id=category.category_id, keyword="blouse")
|
||||
self.assertEqual(listed.total, 1)
|
||||
self.assertEqual(listed.items[0].material_id, material.material_id)
|
||||
|
||||
updated = self.material_service.update_material(
|
||||
material.material_id,
|
||||
{"display_name": "White short sleeve blouse", "tags": ["summer"]},
|
||||
self.ctx,
|
||||
)
|
||||
self.assertEqual(updated.display_name, "White short sleeve blouse")
|
||||
self.assertEqual(updated.tags, ["summer"])
|
||||
|
||||
deleted = self.material_service.delete_material(material.material_id, self.ctx)
|
||||
self.assertEqual(deleted.recognition_status, "archived")
|
||||
self.assertEqual(self.material_service.list_materials().total, 0)
|
||||
|
||||
def test_material_requires_storage_uri(self):
|
||||
category = self.material_service.create_category({"name": "Upper"}, self.ctx)
|
||||
|
||||
with self.assertRaises(Exception):
|
||||
self.material_service.create_material(
|
||||
{
|
||||
"category_id": category.category_id,
|
||||
"display_name": "Bad path",
|
||||
"image_uri": "C:/real/path.png",
|
||||
},
|
||||
self.ctx,
|
||||
)
|
||||
|
||||
def test_material_routes_wrap_responses_and_require_permission(self):
|
||||
category = create_material_category(self.ctx, {"name": "Accessory"}, self.material_service)
|
||||
self.assertTrue(category["ok"])
|
||||
category_id = category["data"]["category_id"]
|
||||
|
||||
categories = list_material_categories(self.ctx, self.material_service)
|
||||
self.assertTrue(categories["ok"])
|
||||
self.assertEqual(len(categories["data"]), 1)
|
||||
|
||||
material = create_material(
|
||||
self.ctx,
|
||||
{
|
||||
"category_id": category_id,
|
||||
"display_name": "Blue ribbon",
|
||||
"image_uri": "storage://materials/ribbon.png",
|
||||
},
|
||||
self.material_service,
|
||||
)
|
||||
self.assertTrue(material["ok"])
|
||||
material_id = material["data"]["material_id"]
|
||||
|
||||
detail = get_material(self.ctx, material_id, self.material_service)
|
||||
self.assertTrue(detail["ok"])
|
||||
|
||||
updated = update_material(self.ctx, material_id, {"recognition_status": "confirmed"}, self.material_service)
|
||||
self.assertTrue(updated["ok"])
|
||||
self.assertEqual(updated["data"]["recognition_status"], "confirmed")
|
||||
|
||||
listed = list_materials(self.ctx, {"keyword": "ribbon"}, self.material_service)
|
||||
self.assertTrue(listed["ok"])
|
||||
self.assertEqual(listed["data"]["total"], 1)
|
||||
|
||||
read_only = RequestContext.from_astrbot(username="viewer", user_id="viewer_001")
|
||||
denied = create_material(read_only, {"display_name": "Denied"}, self.material_service)
|
||||
self.assertFalse(denied["ok"])
|
||||
self.assertEqual(denied["error_code"], "FORBIDDEN")
|
||||
|
||||
deleted = delete_material(self.ctx, material_id, self.material_service)
|
||||
self.assertTrue(deleted["ok"])
|
||||
missing = get_material(self.ctx, material_id, self.material_service)
|
||||
self.assertFalse(missing["ok"])
|
||||
self.assertEqual(missing["error_code"], "RESOURCE_NOT_FOUND")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用