feat: implement definition-aware forms runtime
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Forms Runtime database models."""
|
||||
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from govoplan_core.db.base import Base, TimestampMixin
|
||||
|
||||
|
||||
def new_uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class FormInstanceIdentity(Base, TimestampMixin):
|
||||
__tablename__ = "form_instance_identities"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
name="uq_form_instance_identity",
|
||||
),
|
||||
Index(
|
||||
"ix_form_instance_owner",
|
||||
"tenant_id",
|
||||
"created_by",
|
||||
"definition_id",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
instance_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
definition_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
definition_revision: Mapped[str] = mapped_column(
|
||||
String(255), nullable=False, index=True
|
||||
)
|
||||
created_by: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
|
||||
|
||||
class FormInstanceRevision(Base, TimestampMixin):
|
||||
__tablename__ = "form_instance_revisions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"revision",
|
||||
name="uq_form_instance_revision",
|
||||
),
|
||||
Index(
|
||||
"ix_form_instance_current",
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"superseded_at",
|
||||
),
|
||||
Index(
|
||||
"ix_form_instance_catalog",
|
||||
"tenant_id",
|
||||
"status",
|
||||
"recorded_at",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
instance_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
identity_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("form_instance_identities.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
previous_revision_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("form_instance_revisions.id", ondelete="RESTRICT"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
status: Mapped[str] = mapped_column(String(30), nullable=False, index=True)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, index=True
|
||||
)
|
||||
superseded_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True, index=True
|
||||
)
|
||||
snapshot: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||
changed_by: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
|
||||
|
||||
class FormInstanceEvent(Base, TimestampMixin):
|
||||
__tablename__ = "form_instance_events"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"event_id",
|
||||
name="uq_form_instance_event",
|
||||
),
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"idempotency_key",
|
||||
name="uq_form_instance_idempotency",
|
||||
),
|
||||
Index(
|
||||
"ix_form_instance_event_history",
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"occurred_at",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
instance_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
instance_revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
event_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(120), nullable=False, index=True)
|
||||
status: Mapped[str] = mapped_column(String(30), nullable=False, index=True)
|
||||
occurred_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, index=True
|
||||
)
|
||||
actor_id: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
request_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
payload: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FormInstanceEvent",
|
||||
"FormInstanceIdentity",
|
||||
"FormInstanceRevision",
|
||||
]
|
||||
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field, replace
|
||||
from datetime import datetime
|
||||
from typing import Mapping
|
||||
|
||||
from govoplan_core.core.institutional import (
|
||||
EvidenceReference,
|
||||
InstitutionalContextError,
|
||||
InstitutionalReference,
|
||||
ServiceBinding,
|
||||
)
|
||||
|
||||
|
||||
FORM_INSTANCE_STATUSES = frozenset(
|
||||
{
|
||||
"started",
|
||||
"draft",
|
||||
"submitted",
|
||||
"validated",
|
||||
"needs_review",
|
||||
"accepted",
|
||||
"rejected",
|
||||
"handed_off",
|
||||
"archived",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FormInstance:
|
||||
tenant_id: str
|
||||
instance_id: str
|
||||
revision: int
|
||||
status: str
|
||||
definition_ref: InstitutionalReference
|
||||
values: Mapping[str, object]
|
||||
validation_results: tuple[Mapping[str, object], ...]
|
||||
recorded_at: datetime
|
||||
change_reason: str
|
||||
created_by: str
|
||||
changed_by: str
|
||||
attachment_refs: tuple[EvidenceReference, ...] = ()
|
||||
signature_refs: tuple[EvidenceReference, ...] = ()
|
||||
handoff_refs: tuple[InstitutionalReference, ...] = ()
|
||||
service_ref: InstitutionalReference | None = None
|
||||
service_binding: ServiceBinding | None = None
|
||||
receipt_id: str | None = None
|
||||
replayed: bool = False
|
||||
metadata: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.tenant_id or not self.instance_id:
|
||||
raise InstitutionalContextError(
|
||||
"A Form instance requires tenant and instance identities."
|
||||
)
|
||||
if self.revision < 1:
|
||||
raise InstitutionalContextError(
|
||||
"A Form instance revision must be positive."
|
||||
)
|
||||
if self.status not in FORM_INSTANCE_STATUSES:
|
||||
raise InstitutionalContextError(
|
||||
f"Unsupported Form instance status: {self.status!r}."
|
||||
)
|
||||
if (
|
||||
self.definition_ref.kind != "form"
|
||||
or self.definition_ref.owner_module != "forms"
|
||||
or self.definition_ref.tenant_id != self.tenant_id
|
||||
or not self.definition_ref.version
|
||||
):
|
||||
raise InstitutionalContextError(
|
||||
"A Form instance requires an exact same-tenant Forms definition."
|
||||
)
|
||||
if self.service_ref is not None and (
|
||||
self.service_ref.kind != "service"
|
||||
or self.service_ref.tenant_id != self.tenant_id
|
||||
or not self.service_ref.version
|
||||
):
|
||||
raise InstitutionalContextError(
|
||||
"Form instance Service provenance must be exact and same-tenant."
|
||||
)
|
||||
for item in (*self.attachment_refs, *self.signature_refs):
|
||||
if item.tenant_id != self.tenant_id:
|
||||
raise InstitutionalContextError(
|
||||
"Form instance evidence cannot cross tenants."
|
||||
)
|
||||
for item in self.handoff_refs:
|
||||
if item.tenant_id != self.tenant_id:
|
||||
raise InstitutionalContextError(
|
||||
"Form instance handoff references cannot cross tenants."
|
||||
)
|
||||
|
||||
@property
|
||||
def reference(self) -> InstitutionalReference:
|
||||
return InstitutionalReference(
|
||||
kind="form_submission",
|
||||
owner_module="forms_runtime",
|
||||
object_id=self.instance_id,
|
||||
tenant_id=self.tenant_id,
|
||||
version=str(self.revision),
|
||||
valid_at=self.recorded_at,
|
||||
)
|
||||
|
||||
def with_replay(self) -> "FormInstance":
|
||||
return replace(self, replayed=True)
|
||||
|
||||
def to_dict(self, *, include_values: bool = True) -> dict[str, object]:
|
||||
return {
|
||||
"reference": self.reference.to_dict(),
|
||||
"tenant_id": self.tenant_id,
|
||||
"instance_id": self.instance_id,
|
||||
"revision": self.revision,
|
||||
"status": self.status,
|
||||
"definition_ref": self.definition_ref.to_dict(disclose_label=True),
|
||||
"values": dict(self.values) if include_values else {},
|
||||
"validation_results": [dict(item) for item in self.validation_results],
|
||||
"attachment_refs": [
|
||||
item.to_dict(include_inspection=False) for item in self.attachment_refs
|
||||
],
|
||||
"signature_refs": [
|
||||
item.to_dict(include_inspection=False) for item in self.signature_refs
|
||||
],
|
||||
"handoff_refs": [item.to_dict() for item in self.handoff_refs],
|
||||
"service_ref": (
|
||||
self.service_ref.to_dict() if self.service_ref is not None else None
|
||||
),
|
||||
"service_binding": (
|
||||
self.service_binding.to_dict()
|
||||
if self.service_binding is not None
|
||||
else None
|
||||
),
|
||||
"receipt_id": self.receipt_id,
|
||||
"recorded_at": self.recorded_at.isoformat(),
|
||||
"change_reason": self.change_reason,
|
||||
"created_by": self.created_by,
|
||||
"changed_by": self.changed_by,
|
||||
"replayed": self.replayed,
|
||||
"metadata": dict(self.metadata),
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["FORM_INSTANCE_STATUSES", "FormInstance"]
|
||||
@@ -1,20 +1,59 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from govoplan_core.core.access import CAPABILITY_AUTH_PERMISSION_EVALUATOR, CAPABILITY_AUTH_PRINCIPAL_RESOLVER
|
||||
from govoplan_core.core.modules import DocumentationLink, DocumentationTopic, ModuleManifest, PermissionDefinition, RoleTemplate
|
||||
from pathlib import Path
|
||||
|
||||
from govoplan_core.core.access import (
|
||||
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
|
||||
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
|
||||
)
|
||||
from govoplan_core.core.institutional import CAPABILITY_FORM_DEFINITIONS
|
||||
from govoplan_core.core.module_guards import (
|
||||
drop_table_retirement_provider,
|
||||
persistent_table_uninstall_guard,
|
||||
)
|
||||
from govoplan_core.core.modules import (
|
||||
CapabilityDocumentation,
|
||||
DocumentationLink,
|
||||
DocumentationTopic,
|
||||
FrontendModule,
|
||||
FrontendRoute,
|
||||
MigrationSpec,
|
||||
ModuleContext,
|
||||
ModuleInterfaceProvider,
|
||||
ModuleInterfaceRequirement,
|
||||
ModuleManifest,
|
||||
NavItem,
|
||||
PermissionDefinition,
|
||||
RoleTemplate,
|
||||
)
|
||||
from govoplan_core.core.provider_governance import declared_module_architecture
|
||||
from govoplan_core.core.views import ViewSurface
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_forms_runtime.backend.db import models as runtime_models
|
||||
from govoplan_forms_runtime.backend.service import (
|
||||
CAPABILITY_FORMS_RUNTIME_POLICY_EVALUATOR,
|
||||
CAPABILITY_FORMS_RUNTIME_REGISTRY,
|
||||
CAPABILITY_FORMS_RUNTIME_SERVICE_LAUNCHER,
|
||||
FormRuntimeService,
|
||||
FormsServiceLauncher,
|
||||
)
|
||||
|
||||
|
||||
MODULE_ID = "forms_runtime"
|
||||
MODULE_NAME = "Forms Runtime"
|
||||
MODULE_VERSION = "0.1.8"
|
||||
MODULE_VERSION = "0.1.14"
|
||||
PARTICIPATE_SCOPE = "forms_runtime:submission:participate"
|
||||
READ_SCOPE = "forms_runtime:workspace:read"
|
||||
WRITE_SCOPE = "forms_runtime:workspace:write"
|
||||
ADMIN_SCOPE = "forms_runtime:workspace:admin"
|
||||
OPTIONAL_DEPENDENCIES = (
|
||||
"forms",
|
||||
"files",
|
||||
"approvals",
|
||||
"workflow_engine",
|
||||
"portal",
|
||||
"cases",
|
||||
"policy",
|
||||
"audit",
|
||||
)
|
||||
|
||||
|
||||
@@ -24,7 +63,7 @@ def _permission(scope: str, label: str, description: str) -> PermissionDefinitio
|
||||
scope=scope,
|
||||
label=label,
|
||||
description=description,
|
||||
category="Forms Runtime",
|
||||
category=MODULE_NAME,
|
||||
level="tenant",
|
||||
module_id=module_id,
|
||||
resource=resource,
|
||||
@@ -33,66 +72,255 @@ def _permission(scope: str, label: str, description: str) -> PermissionDefinitio
|
||||
|
||||
|
||||
PERMISSIONS = (
|
||||
_permission(READ_SCOPE, "View forms runtime workspace", "Read forms runtime records, configuration, and workflow context."),
|
||||
_permission(WRITE_SCOPE, "Manage forms runtime workspace", "Create and update forms runtime records and workflow state."),
|
||||
_permission(ADMIN_SCOPE, "Administer forms runtime workspace", "Configure forms runtime policies, templates, and tenant-level administration."),
|
||||
_permission(
|
||||
PARTICIPATE_SCOPE,
|
||||
"Complete assigned forms",
|
||||
"Start, read, save, and submit the acting account's own Form instances.",
|
||||
),
|
||||
_permission(
|
||||
READ_SCOPE,
|
||||
"View form submissions",
|
||||
"Read tenant Form instances, immutable history, and status evidence.",
|
||||
),
|
||||
_permission(
|
||||
WRITE_SCOPE,
|
||||
"Manage form submissions",
|
||||
"Review, transition, and hand off tenant Form submissions.",
|
||||
),
|
||||
_permission(
|
||||
ADMIN_SCOPE,
|
||||
"Administer Forms Runtime",
|
||||
"Administer Forms Runtime policy, recovery, and retirement.",
|
||||
),
|
||||
)
|
||||
|
||||
ROLE_TEMPLATES = (
|
||||
RoleTemplate(
|
||||
slug="forms_runtime_participant",
|
||||
name="Forms participant",
|
||||
description="Complete the acting account's own Forms.",
|
||||
permissions=(PARTICIPATE_SCOPE,),
|
||||
default_authenticated=True,
|
||||
),
|
||||
RoleTemplate(
|
||||
slug="forms_runtime_manager",
|
||||
name="Forms Runtime manager",
|
||||
description="Manage forms runtime records and workflow state.",
|
||||
permissions=(READ_SCOPE, WRITE_SCOPE),
|
||||
description="Review, transition, and hand off Form submissions.",
|
||||
permissions=(PARTICIPATE_SCOPE, READ_SCOPE, WRITE_SCOPE),
|
||||
),
|
||||
RoleTemplate(
|
||||
slug="forms_runtime_viewer",
|
||||
name="Forms Runtime viewer",
|
||||
description="Read forms runtime records and workflow context.",
|
||||
description="Read Form submissions and their immutable history.",
|
||||
permissions=(READ_SCOPE,),
|
||||
),
|
||||
)
|
||||
|
||||
DOCUMENTATION = (
|
||||
DocumentationTopic(
|
||||
id=f"{MODULE_ID}.module-boundary",
|
||||
title=f"{MODULE_NAME} module boundary",
|
||||
summary="Runtime form submissions for validation, drafts, attachments, signatures, status tracking, and handoff to domain modules.",
|
||||
body=(
|
||||
"This repository is currently a platform module seed. It registers the domain boundary, "
|
||||
"permission surface, role templates, and documentation metadata before runtime APIs, "
|
||||
"database models, migrations, and WebUI routes are introduced."
|
||||
),
|
||||
layer="available",
|
||||
documentation_types=("admin",),
|
||||
audience=("operator", "module_admin", "product_owner"),
|
||||
order=100,
|
||||
related_modules=OPTIONAL_DEPENDENCIES,
|
||||
links=(
|
||||
DocumentationLink(
|
||||
label="Repository domain boundary",
|
||||
href="govoplan-forms-runtime/docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",
|
||||
kind="repository",
|
||||
),
|
||||
),
|
||||
metadata={
|
||||
"seed": True,
|
||||
"domain_objects": ['form submissions', 'draft state', 'runtime validation results', 'attachment references', 'signature state', 'handoff status'],
|
||||
"first_slice": "Define submission, draft, validation, attachment, signature, status, and handoff contracts around existing form definitions.",
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
def _router(context: ModuleContext):
|
||||
from govoplan_forms_runtime.backend.router import create_router
|
||||
|
||||
return create_router(context.registry)
|
||||
|
||||
|
||||
def _registry(context: ModuleContext) -> FormRuntimeService:
|
||||
return FormRuntimeService(context.registry)
|
||||
|
||||
|
||||
def _service_launcher(context: ModuleContext) -> FormsServiceLauncher:
|
||||
return FormsServiceLauncher(context.registry)
|
||||
|
||||
|
||||
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
|
||||
current = session.query(runtime_models.FormInstanceRevision).filter(
|
||||
runtime_models.FormInstanceRevision.tenant_id == tenant_id,
|
||||
runtime_models.FormInstanceRevision.superseded_at.is_(None),
|
||||
)
|
||||
return {
|
||||
"form_instances": current.count(),
|
||||
"open_form_instances": current.filter(
|
||||
runtime_models.FormInstanceRevision.status.in_(
|
||||
("started", "draft", "submitted", "validated", "needs_review")
|
||||
)
|
||||
).count(),
|
||||
}
|
||||
|
||||
|
||||
manifest = ModuleManifest(
|
||||
id=MODULE_ID,
|
||||
name=MODULE_NAME,
|
||||
version=MODULE_VERSION,
|
||||
dependencies=("access",),
|
||||
dependencies=("access", "forms"),
|
||||
optional_dependencies=OPTIONAL_DEPENDENCIES,
|
||||
required_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR),
|
||||
required_capabilities=(
|
||||
CAPABILITY_AUTH_PRINCIPAL_RESOLVER,
|
||||
CAPABILITY_AUTH_PERMISSION_EVALUATOR,
|
||||
CAPABILITY_FORM_DEFINITIONS,
|
||||
),
|
||||
optional_capabilities=(CAPABILITY_FORMS_RUNTIME_POLICY_EVALUATOR,),
|
||||
permissions=PERMISSIONS,
|
||||
role_templates=ROLE_TEMPLATES,
|
||||
documentation=DOCUMENTATION,
|
||||
route_factory=_router,
|
||||
nav_items=(
|
||||
NavItem(
|
||||
path="/forms-runtime",
|
||||
label="Forms",
|
||||
icon="form",
|
||||
required_any=(PARTICIPATE_SCOPE, READ_SCOPE),
|
||||
order=37,
|
||||
),
|
||||
),
|
||||
frontend=FrontendModule(
|
||||
module_id=MODULE_ID,
|
||||
package_name="@govoplan/forms-runtime-webui",
|
||||
routes=(
|
||||
FrontendRoute(
|
||||
path="/forms-runtime",
|
||||
component="FormsRuntimePage",
|
||||
required_any=(PARTICIPATE_SCOPE, READ_SCOPE),
|
||||
order=37,
|
||||
),
|
||||
FrontendRoute(
|
||||
path="/forms-runtime/:instanceId",
|
||||
component="FormInstancePage",
|
||||
required_any=(PARTICIPATE_SCOPE, READ_SCOPE),
|
||||
order=38,
|
||||
),
|
||||
),
|
||||
nav_items=(
|
||||
NavItem(
|
||||
path="/forms-runtime",
|
||||
label="Forms",
|
||||
icon="form",
|
||||
required_any=(PARTICIPATE_SCOPE, READ_SCOPE),
|
||||
order=37,
|
||||
),
|
||||
),
|
||||
view_surfaces=(
|
||||
ViewSurface(
|
||||
id="forms_runtime.navigation",
|
||||
module_id=MODULE_ID,
|
||||
kind="navigation",
|
||||
label="Forms navigation",
|
||||
order=10,
|
||||
),
|
||||
ViewSurface(
|
||||
id="forms_runtime.workspace",
|
||||
module_id=MODULE_ID,
|
||||
kind="route",
|
||||
label="Forms workspace",
|
||||
order=20,
|
||||
),
|
||||
ViewSurface(
|
||||
id="forms_runtime.instance",
|
||||
module_id=MODULE_ID,
|
||||
kind="route",
|
||||
label="Form instance",
|
||||
order=30,
|
||||
),
|
||||
),
|
||||
),
|
||||
provides_interfaces=(
|
||||
ModuleInterfaceProvider(name="forms_runtime.registry", version="0.1.0"),
|
||||
ModuleInterfaceProvider(name="forms_runtime.service_launcher", version="0.1.0"),
|
||||
),
|
||||
requires_interfaces=(
|
||||
ModuleInterfaceRequirement(
|
||||
name="forms.definitions",
|
||||
version_min="0.1.0",
|
||||
version_max_exclusive="0.2.0",
|
||||
),
|
||||
),
|
||||
capability_factories={
|
||||
CAPABILITY_FORMS_RUNTIME_REGISTRY: _registry,
|
||||
CAPABILITY_FORMS_RUNTIME_SERVICE_LAUNCHER: _service_launcher,
|
||||
},
|
||||
capability_documentation={
|
||||
CAPABILITY_FORMS_RUNTIME_REGISTRY: CapabilityDocumentation(
|
||||
label="Forms Runtime registry",
|
||||
summary="Manages tenant-bound, revisioned Form instances and handoff evidence.",
|
||||
contract_version="0.1.0",
|
||||
),
|
||||
CAPABILITY_FORMS_RUNTIME_SERVICE_LAUNCHER: CapabilityDocumentation(
|
||||
label="Form-bound Service launcher",
|
||||
summary="Starts a replay-safe Form instance from an exact published Service and Form revision.",
|
||||
contract_version="0.1.0",
|
||||
),
|
||||
},
|
||||
migration_spec=MigrationSpec(
|
||||
module_id=MODULE_ID,
|
||||
metadata=Base.metadata,
|
||||
script_location=str(Path(__file__).with_name("migrations") / "versions"),
|
||||
migration_after=("forms",),
|
||||
retirement_supported=True,
|
||||
retirement_provider=drop_table_retirement_provider(
|
||||
runtime_models.FormInstanceEvent,
|
||||
runtime_models.FormInstanceRevision,
|
||||
runtime_models.FormInstanceIdentity,
|
||||
label=MODULE_NAME,
|
||||
),
|
||||
retirement_notes="Destructive retirement removes submissions and immutable status evidence and requires a verified database and referenced-evidence recovery plan.",
|
||||
),
|
||||
uninstall_guard_providers=(
|
||||
persistent_table_uninstall_guard(
|
||||
runtime_models.FormInstanceIdentity,
|
||||
runtime_models.FormInstanceRevision,
|
||||
runtime_models.FormInstanceEvent,
|
||||
label=MODULE_NAME,
|
||||
),
|
||||
),
|
||||
tenant_summary_providers=(_tenant_summary,),
|
||||
documentation=(
|
||||
DocumentationTopic(
|
||||
id="forms_runtime.submissions",
|
||||
title="Complete and manage Forms",
|
||||
summary="Save permitted drafts, submit validated values, and retain exact definition and handoff evidence.",
|
||||
body=(
|
||||
"Every instance resolves one immutable published Form revision. Draft and final values are validated on the server; final submission also enforces attachment, signature, and policy requirements. "
|
||||
"Service launches retain the exact Service and binding. History, receipts, and handoffs are append-only, replay-safe, and optimistic-concurrency guarded."
|
||||
),
|
||||
layer="configured",
|
||||
documentation_types=("admin", "user"),
|
||||
audience=("user", "operator", "module_admin", "product_owner"),
|
||||
links=(
|
||||
DocumentationLink(
|
||||
label="Forms Runtime security and recovery",
|
||||
href="govoplan-forms-runtime/docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",
|
||||
kind="repository",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
architecture=declared_module_architecture(
|
||||
layer="human_work_procedure",
|
||||
kind="runtime",
|
||||
maturity="vertical_slice",
|
||||
documentation_ref="docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",
|
||||
test_ref="tests/test_forms_runtime.py",
|
||||
known_limits=(
|
||||
"Anonymous public intake, concrete Files/signature adapters, and automatic target handoff execution remain adapter depth; authenticated Portal entry is supported.",
|
||||
),
|
||||
supported_authority_modes=("native_authoritative",),
|
||||
owned_concepts=(
|
||||
"form instance",
|
||||
"form submission",
|
||||
"runtime validation",
|
||||
"submission receipt",
|
||||
"form handoff evidence",
|
||||
),
|
||||
non_owned_concepts=(
|
||||
"form definition",
|
||||
"file content",
|
||||
"case",
|
||||
"workflow definition",
|
||||
"signature key custody",
|
||||
),
|
||||
reference_packages=("product.service-to-decision",),
|
||||
migration_docs=("docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",),
|
||||
recovery_docs=("docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",),
|
||||
security_docs=("docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",),
|
||||
operations_docs=("docs/FORMS_RUNTIME_DOMAIN_BOUNDARY.md",),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Forms Runtime Alembic revisions."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Forms Runtime migration versions."""
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
"""v0.1.14 definition-aware Forms Runtime.
|
||||
|
||||
Revision ID: f2a3b4c5d6e7
|
||||
Revises: None
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "f2a3b4c5d6e7"
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = "e1f2a3b4c5d6"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"form_instance_identities",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("instance_id", sa.String(length=255), nullable=False),
|
||||
sa.Column("definition_id", sa.String(length=255), nullable=False),
|
||||
sa.Column("definition_revision", sa.String(length=255), nullable=False),
|
||||
sa.Column("created_by", sa.String(length=255), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_form_instance_identities")),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
name="uq_form_instance_identity",
|
||||
),
|
||||
)
|
||||
for column in (
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"definition_id",
|
||||
"definition_revision",
|
||||
"created_by",
|
||||
):
|
||||
op.create_index(
|
||||
op.f(f"ix_form_instance_identities_{column}"),
|
||||
"form_instance_identities",
|
||||
[column],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_form_instance_owner",
|
||||
"form_instance_identities",
|
||||
["tenant_id", "created_by", "definition_id"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"form_instance_revisions",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("instance_id", sa.String(length=255), nullable=False),
|
||||
sa.Column("identity_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("revision", sa.Integer(), nullable=False),
|
||||
sa.Column("previous_revision_id", sa.String(length=36), nullable=True),
|
||||
sa.Column("status", sa.String(length=30), nullable=False),
|
||||
sa.Column("recorded_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("superseded_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("snapshot", sa.JSON(), nullable=False),
|
||||
sa.Column("changed_by", sa.String(length=255), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["identity_id"],
|
||||
["form_instance_identities.id"],
|
||||
name=op.f("fk_form_instance_revisions_identity_id_form_instance_identities"),
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["previous_revision_id"],
|
||||
["form_instance_revisions.id"],
|
||||
name=op.f("fk_form_instance_revisions_previous_revision_id_form_instance_revisions"),
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_form_instance_revisions")),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"revision",
|
||||
name="uq_form_instance_revision",
|
||||
),
|
||||
)
|
||||
for column in (
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"identity_id",
|
||||
"previous_revision_id",
|
||||
"status",
|
||||
"recorded_at",
|
||||
"superseded_at",
|
||||
"changed_by",
|
||||
):
|
||||
op.create_index(
|
||||
op.f(f"ix_form_instance_revisions_{column}"),
|
||||
"form_instance_revisions",
|
||||
[column],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_form_instance_current",
|
||||
"form_instance_revisions",
|
||||
["tenant_id", "instance_id", "superseded_at"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_form_instance_catalog",
|
||||
"form_instance_revisions",
|
||||
["tenant_id", "status", "recorded_at"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
"form_instance_events",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("instance_id", sa.String(length=255), nullable=False),
|
||||
sa.Column("instance_revision", sa.Integer(), nullable=False),
|
||||
sa.Column("event_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("event_type", sa.String(length=120), nullable=False),
|
||||
sa.Column("status", sa.String(length=30), nullable=False),
|
||||
sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("actor_id", sa.String(length=255), nullable=False),
|
||||
sa.Column("idempotency_key", sa.String(length=255), nullable=False),
|
||||
sa.Column("request_sha256", sa.String(length=64), nullable=False),
|
||||
sa.Column("payload", sa.JSON(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_form_instance_events")),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"event_id",
|
||||
name="uq_form_instance_event",
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"idempotency_key",
|
||||
name="uq_form_instance_idempotency",
|
||||
),
|
||||
)
|
||||
for column in (
|
||||
"tenant_id",
|
||||
"instance_id",
|
||||
"event_id",
|
||||
"event_type",
|
||||
"status",
|
||||
"occurred_at",
|
||||
"actor_id",
|
||||
):
|
||||
op.create_index(
|
||||
op.f(f"ix_form_instance_events_{column}"),
|
||||
"form_instance_events",
|
||||
[column],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_form_instance_event_history",
|
||||
"form_instance_events",
|
||||
["tenant_id", "instance_id", "occurred_at"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("form_instance_events")
|
||||
op.drop_table("form_instance_revisions")
|
||||
op.drop_table("form_instance_identities")
|
||||
@@ -0,0 +1,339 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
|
||||
from govoplan_core.core.institutional import (
|
||||
EvidenceReference,
|
||||
InstitutionalContextError,
|
||||
InstitutionalReference,
|
||||
)
|
||||
from govoplan_core.db.session import get_session
|
||||
from govoplan_forms_runtime.backend.manifest import (
|
||||
ADMIN_SCOPE,
|
||||
PARTICIPATE_SCOPE,
|
||||
READ_SCOPE,
|
||||
WRITE_SCOPE,
|
||||
)
|
||||
from govoplan_forms_runtime.backend.schemas import (
|
||||
FormDraftUpdateRequest,
|
||||
FormHandoffRequest,
|
||||
FormInstanceCreateRequest,
|
||||
FormInstanceEventsResponse,
|
||||
FormInstanceHistoryResponse,
|
||||
FormInstanceListResponse,
|
||||
FormSubmitRequest,
|
||||
FormTransitionRequest,
|
||||
)
|
||||
from govoplan_forms_runtime.backend.service import FormRuntimeError, FormRuntimeService
|
||||
|
||||
|
||||
def create_router(registry: object | None) -> APIRouter:
|
||||
router = APIRouter(prefix="/forms-runtime", tags=["forms-runtime"])
|
||||
runtime = FormRuntimeService(registry)
|
||||
|
||||
@router.get("/instances", response_model=FormInstanceListResponse)
|
||||
def api_list_instances(
|
||||
instance_status: list[str] | None = Query(default=None, alias="status"),
|
||||
definition_id: str | None = Query(default=None, max_length=255),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
limit: int = Query(default=100, ge=1, le=200),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> FormInstanceListResponse:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, READ_SCOPE)
|
||||
try:
|
||||
items, total = runtime.list_instances(
|
||||
session,
|
||||
principal,
|
||||
statuses=instance_status,
|
||||
definition_id=definition_id,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
allow_all=has_scope(principal, READ_SCOPE),
|
||||
)
|
||||
except FormRuntimeError as exc:
|
||||
raise _error(exc) from exc
|
||||
return FormInstanceListResponse(
|
||||
instances=[item.to_dict(include_values=False) for item in items],
|
||||
total=total,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
@router.post(
|
||||
"/instances",
|
||||
response_model=dict[str, object],
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def api_create_instance(
|
||||
payload: FormInstanceCreateRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, WRITE_SCOPE)
|
||||
try:
|
||||
item = runtime.create_instance(
|
||||
session,
|
||||
principal,
|
||||
definition_ref=InstitutionalReference.from_mapping(
|
||||
payload.definition_ref
|
||||
),
|
||||
values=payload.values,
|
||||
attachment_refs=_evidence(payload.attachment_refs),
|
||||
signature_refs=_evidence(payload.signature_refs),
|
||||
idempotency_key=payload.idempotency_key,
|
||||
recorded_at=payload.recorded_at,
|
||||
instance_id=payload.instance_id,
|
||||
metadata=payload.metadata,
|
||||
)
|
||||
session.commit()
|
||||
except (FormRuntimeError, InstitutionalContextError, PermissionError) as exc:
|
||||
session.rollback()
|
||||
raise _error(exc) from exc
|
||||
return item.to_dict()
|
||||
|
||||
@router.get("/instances/{instance_id}", response_model=dict[str, object])
|
||||
def api_get_instance(
|
||||
instance_id: str,
|
||||
revision: int | None = Query(default=None, ge=1),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, READ_SCOPE)
|
||||
try:
|
||||
item = runtime.get_instance(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
revision=revision,
|
||||
allow_all=has_scope(principal, READ_SCOPE),
|
||||
)
|
||||
except PermissionError as exc:
|
||||
raise _error(exc) from exc
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Form instance not found")
|
||||
return item.to_dict()
|
||||
|
||||
@router.get(
|
||||
"/instances/{instance_id}/definition",
|
||||
response_model=dict[str, object],
|
||||
)
|
||||
def api_get_instance_definition(
|
||||
instance_id: str,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, READ_SCOPE)
|
||||
try:
|
||||
item = runtime.get_instance_definition(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
allow_all=has_scope(principal, READ_SCOPE),
|
||||
)
|
||||
except PermissionError as exc:
|
||||
raise _error(exc) from exc
|
||||
if item is None:
|
||||
raise HTTPException(status_code=404, detail="Form instance not found")
|
||||
return item.to_dict()
|
||||
|
||||
@router.patch("/instances/{instance_id}", response_model=dict[str, object])
|
||||
def api_update_draft(
|
||||
instance_id: str,
|
||||
payload: FormDraftUpdateRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, WRITE_SCOPE)
|
||||
try:
|
||||
item = runtime.update_draft(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
expected_revision=payload.expected_revision,
|
||||
values=payload.values,
|
||||
attachment_refs=_evidence(payload.attachment_refs),
|
||||
signature_refs=_evidence(payload.signature_refs),
|
||||
idempotency_key=payload.idempotency_key,
|
||||
recorded_at=payload.recorded_at,
|
||||
change_reason=payload.change_reason,
|
||||
allow_all=has_scope(principal, WRITE_SCOPE),
|
||||
)
|
||||
session.commit()
|
||||
except (FormRuntimeError, InstitutionalContextError, LookupError, PermissionError) as exc:
|
||||
session.rollback()
|
||||
raise _error(exc) from exc
|
||||
return item.to_dict()
|
||||
|
||||
@router.post(
|
||||
"/instances/{instance_id}/submit",
|
||||
response_model=dict[str, object],
|
||||
)
|
||||
def api_submit_instance(
|
||||
instance_id: str,
|
||||
payload: FormSubmitRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, WRITE_SCOPE)
|
||||
try:
|
||||
item = runtime.submit_instance(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
expected_revision=payload.expected_revision,
|
||||
values=payload.values,
|
||||
attachment_refs=_evidence(payload.attachment_refs),
|
||||
signature_refs=_evidence(payload.signature_refs),
|
||||
idempotency_key=payload.idempotency_key,
|
||||
recorded_at=payload.recorded_at,
|
||||
allow_all=has_scope(principal, WRITE_SCOPE),
|
||||
)
|
||||
session.commit()
|
||||
except (FormRuntimeError, InstitutionalContextError, LookupError, PermissionError) as exc:
|
||||
session.rollback()
|
||||
raise _error(exc) from exc
|
||||
return item.to_dict()
|
||||
|
||||
@router.post(
|
||||
"/instances/{instance_id}/transition",
|
||||
response_model=dict[str, object],
|
||||
)
|
||||
def api_transition_instance(
|
||||
instance_id: str,
|
||||
payload: FormTransitionRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, WRITE_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
item = runtime.transition_instance(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
expected_revision=payload.expected_revision,
|
||||
status=payload.status,
|
||||
idempotency_key=payload.idempotency_key,
|
||||
recorded_at=payload.recorded_at,
|
||||
change_reason=payload.change_reason,
|
||||
allow_all=True,
|
||||
)
|
||||
session.commit()
|
||||
except (FormRuntimeError, InstitutionalContextError, LookupError, PermissionError) as exc:
|
||||
session.rollback()
|
||||
raise _error(exc) from exc
|
||||
return item.to_dict()
|
||||
|
||||
@router.post(
|
||||
"/instances/{instance_id}/handoffs",
|
||||
response_model=dict[str, object],
|
||||
)
|
||||
def api_handoff_instance(
|
||||
instance_id: str,
|
||||
payload: FormHandoffRequest,
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> dict[str, object]:
|
||||
_require_any(principal, WRITE_SCOPE, ADMIN_SCOPE)
|
||||
try:
|
||||
item = runtime.handoff_instance(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
expected_revision=payload.expected_revision,
|
||||
target_ref=InstitutionalReference.from_mapping(payload.target_ref),
|
||||
idempotency_key=payload.idempotency_key,
|
||||
recorded_at=payload.recorded_at,
|
||||
change_reason=payload.change_reason,
|
||||
allow_all=True,
|
||||
)
|
||||
session.commit()
|
||||
except (FormRuntimeError, InstitutionalContextError, LookupError, PermissionError) as exc:
|
||||
session.rollback()
|
||||
raise _error(exc) from exc
|
||||
return item.to_dict()
|
||||
|
||||
@router.get(
|
||||
"/instances/{instance_id}/history",
|
||||
response_model=FormInstanceHistoryResponse,
|
||||
)
|
||||
def api_instance_history(
|
||||
instance_id: str,
|
||||
limit: int = Query(default=100, ge=1, le=200),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> FormInstanceHistoryResponse:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, READ_SCOPE)
|
||||
try:
|
||||
items = runtime.history(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
limit=limit,
|
||||
allow_all=has_scope(principal, READ_SCOPE),
|
||||
)
|
||||
except PermissionError as exc:
|
||||
raise _error(exc) from exc
|
||||
if not items:
|
||||
raise HTTPException(status_code=404, detail="Form instance not found")
|
||||
return FormInstanceHistoryResponse(
|
||||
revisions=[item.to_dict() for item in items]
|
||||
)
|
||||
|
||||
@router.get(
|
||||
"/instances/{instance_id}/events",
|
||||
response_model=FormInstanceEventsResponse,
|
||||
)
|
||||
def api_instance_events(
|
||||
instance_id: str,
|
||||
limit: int = Query(default=200, ge=1, le=500),
|
||||
session: Session = Depends(get_session),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
) -> FormInstanceEventsResponse:
|
||||
_require_any(principal, PARTICIPATE_SCOPE, READ_SCOPE)
|
||||
try:
|
||||
items = runtime.events(
|
||||
session,
|
||||
principal,
|
||||
instance_id=instance_id,
|
||||
limit=limit,
|
||||
allow_all=has_scope(principal, READ_SCOPE),
|
||||
)
|
||||
except PermissionError as exc:
|
||||
raise _error(exc) from exc
|
||||
return FormInstanceEventsResponse(events=[dict(item) for item in items])
|
||||
|
||||
return router
|
||||
|
||||
|
||||
def _evidence(values: list[dict[str, object]]) -> tuple[EvidenceReference, ...]:
|
||||
return tuple(EvidenceReference.from_mapping(item) for item in values)
|
||||
|
||||
|
||||
def _require_any(principal: ApiPrincipal, *scopes: str) -> None:
|
||||
if not any(has_scope(principal, scope) for scope in scopes):
|
||||
raise HTTPException(
|
||||
status_code=403,
|
||||
detail=f"Missing one of the scopes: {', '.join(scopes)}",
|
||||
)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> HTTPException:
|
||||
message = str(exc)
|
||||
lowered = message.casefold()
|
||||
if isinstance(exc, LookupError):
|
||||
code = 404
|
||||
elif isinstance(exc, PermissionError):
|
||||
code = 403
|
||||
elif any(word in lowered for word in ("conflict", "stale", "already")):
|
||||
code = 409
|
||||
elif "validation" in lowered:
|
||||
code = 422
|
||||
else:
|
||||
code = 400
|
||||
return HTTPException(status_code=code, detail=message)
|
||||
|
||||
|
||||
__all__ = ["create_router"]
|
||||
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class FormInstanceCreateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
definition_ref: dict[str, Any]
|
||||
values: dict[str, Any] = Field(default_factory=dict)
|
||||
attachment_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
|
||||
signature_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=100)
|
||||
idempotency_key: str = Field(min_length=1, max_length=255)
|
||||
recorded_at: datetime
|
||||
instance_id: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
metadata: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class FormDraftUpdateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
expected_revision: int = Field(ge=1)
|
||||
values: dict[str, Any]
|
||||
attachment_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
|
||||
signature_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=100)
|
||||
idempotency_key: str = Field(min_length=1, max_length=255)
|
||||
recorded_at: datetime
|
||||
change_reason: str = Field(min_length=1, max_length=1000)
|
||||
|
||||
|
||||
class FormSubmitRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
expected_revision: int = Field(ge=1)
|
||||
values: dict[str, Any]
|
||||
attachment_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
|
||||
signature_refs: list[dict[str, Any]] = Field(default_factory=list, max_length=100)
|
||||
idempotency_key: str = Field(min_length=1, max_length=255)
|
||||
recorded_at: datetime
|
||||
|
||||
|
||||
class FormTransitionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
expected_revision: int = Field(ge=1)
|
||||
status: Literal[
|
||||
"validated",
|
||||
"needs_review",
|
||||
"accepted",
|
||||
"rejected",
|
||||
"archived",
|
||||
]
|
||||
idempotency_key: str = Field(min_length=1, max_length=255)
|
||||
recorded_at: datetime
|
||||
change_reason: str = Field(min_length=1, max_length=1000)
|
||||
|
||||
|
||||
class FormHandoffRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
expected_revision: int = Field(ge=1)
|
||||
target_ref: dict[str, Any]
|
||||
idempotency_key: str = Field(min_length=1, max_length=255)
|
||||
recorded_at: datetime
|
||||
change_reason: str = Field(min_length=1, max_length=1000)
|
||||
|
||||
|
||||
class FormInstanceListResponse(BaseModel):
|
||||
instances: list[dict[str, Any]]
|
||||
total: int
|
||||
offset: int
|
||||
limit: int
|
||||
|
||||
|
||||
class FormInstanceHistoryResponse(BaseModel):
|
||||
revisions: list[dict[str, Any]]
|
||||
|
||||
|
||||
class FormInstanceEventsResponse(BaseModel):
|
||||
events: list[dict[str, Any]]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FormDraftUpdateRequest",
|
||||
"FormHandoffRequest",
|
||||
"FormInstanceCreateRequest",
|
||||
"FormInstanceEventsResponse",
|
||||
"FormInstanceHistoryResponse",
|
||||
"FormInstanceListResponse",
|
||||
"FormSubmitRequest",
|
||||
"FormTransitionRequest",
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user