Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(api): finish account controller application boundary (#40440)

Byron.wangb38d907edef7
diff --git a/api/.importlinter b/api/.importlinter
index 55e265a03cf..f1683b8871b 100644
--- a/api/.importlinter
+++ b/api/.importlinter
@@ -101,6 +101,8 @@ source_modules =
services.account_change_email_ports
services.account_change_email_service
services.account_deletion_service
+ services.account_deletion_feedback_service
+ services.account_education_service
services.account_errors
services.account_initialization_service
services.account_integration_service
diff --git a/api/controllers/console/flask_admission.py b/api/controllers/console/flask_admission.py
index c5bd2703c1d..5eafc9c4741 100644
--- a/api/controllers/console/flask_admission.py
+++ b/api/controllers/console/flask_admission.py
@@ -9,7 +9,12 @@ from werkzeug.exceptions import Forbidden
from configs import dify_config
from controllers.common.wraps import enforce_rbac_access
-from controllers.console.wraps import account_initialization_required, enterprise_license_required, setup_required
+from controllers.console.wraps import (
+ account_initialization_required,
+ enable_change_email,
+ enterprise_license_required,
+ setup_required,
+)
from core.logging.context import get_request_id, get_trace_id
from core.rbac import RBACPermission, RBACResourceScope
from enums import DeploymentEdition
@@ -22,6 +27,7 @@ from models.account import TenantAccountRole
def console_account_admission[T, **P, R](
*,
editions: frozenset[DeploymentEdition] | None = None,
+ require_change_email_enabled: bool = False,
require_initialized: bool = True,
require_valid_enterprise_license: bool = False,
allowed_roles: frozenset[TenantAccountRole] | None = None,
@@ -71,6 +77,8 @@ def console_account_admission[T, **P, R](
return view(self, request_context, *args, **kwargs)
admitted: Callable[Concatenate[T, P], R | Response] = inject_request_context
+ if require_change_email_enabled:
+ admitted = enable_change_email(admitted)
if require_valid_enterprise_license:
admitted = enterprise_license_required(admitted)
if require_initialized:
diff --git a/api/controllers/console/workspace/account.py b/api/controllers/console/workspace/account.py
index 08a92a39f86..21b28c58352 100644
--- a/api/controllers/console/workspace/account.py
+++ b/api/controllers/console/workspace/account.py
@@ -4,7 +4,6 @@ from datetime import datetime
from http import HTTPStatus
from typing import Annotated, Literal
-import pytz
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
@@ -45,23 +44,14 @@ from controllers.console.workspace.error import (
MissingInvitationCodeRequestError,
RepeatPasswordNotMatchError,
)
-from controllers.console.wraps import (
- account_initialization_required,
- enable_change_email,
- model_validate,
- only_edition_cloud,
- setup_required,
- with_current_user,
-)
+from controllers.console.wraps import model_validate, setup_required
+from enums import DeploymentEdition
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from fields.member_fields import AccountResponse
from libs.helper import EmailStr, dump_response, extract_remote_ip, timezone, to_timestamp
-from libs.login import login_required
from machinery.context import RequestContext
-from models import Account
from services import account_errors
-from services.billing_service import BillingService
from services.entities.account_entities import AccountProfileChanges
@@ -526,23 +516,21 @@ class AccountDeleteUpdateFeedbackApi(Resource):
payload = console_ns.payload or {}
args = AccountDeletionFeedbackPayload.model_validate(payload)
- BillingService.update_account_deletion_feedback(args.email, args.feedback)
+ application_services().accounts.deletion_feedback.submit(email=args.email, feedback=args.feedback)
return SimpleResultResponse(result="success").model_dump(mode="json")
@console_ns.route("/account/education/verify")
class EducationVerifyApi(Resource):
- @setup_required
- @login_required
- @account_initialization_required
- @only_edition_cloud
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationVerifyResponse.__name__])
- @with_current_user
- def get(self, account: Account):
- return dump_response(
- EducationVerifyResponse, BillingService.EducationIdentity.verify(account.id, account.email) or {}
- )
+ @console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))
+ def get(self, request_context: RequestContext):
+ try:
+ verification = application_services().accounts.education.verify(request_context)
+ except account_errors.AccountNotFoundError:
+ raise AccountNotFound() from None
+ return dump_response(EducationVerifyResponse, verification)
@console_ns.route("/account/education")
@@ -550,47 +538,43 @@ class EducationApi(Resource):
@console_ns.expect(console_ns.models[EducationActivatePayload.__name__])
# response-contract:ignore billing-service activation payload; TODO: model education activation result.
@console_ns.response(HTTPStatus.OK, "Success")
- @setup_required
- @login_required
- @account_initialization_required
- @only_edition_cloud
- @with_current_user
- def post(self, account: Account):
+ @console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))
+ def post(self, request_context: RequestContext):
payload = console_ns.payload or {}
args = EducationActivatePayload.model_validate(payload)
+ try:
+ return application_services().accounts.education.activate(
+ request_context,
+ token=args.token,
+ institution=args.institution,
+ role=args.role,
+ )
+ except account_errors.AccountNotFoundError:
+ raise AccountNotFound() from None
- result = BillingService.EducationIdentity.activate(account, args.token, args.institution, args.role)
- return result
-
- @setup_required
- @login_required
- @account_initialization_required
- @only_edition_cloud
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationStatusResponse.__name__])
- @with_current_user
- def get(self, account: Account):
- res = BillingService.EducationIdentity.status(account.id) or {}
- # convert expire_at to UTC timestamp from isoformat
- if res and "expire_at" in res:
- res["expire_at"] = datetime.fromisoformat(res["expire_at"]).astimezone(pytz.utc)
- return dump_response(EducationStatusResponse, res)
+ @console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))
+ def get(self, request_context: RequestContext):
+ return dump_response(EducationStatusResponse, application_services().accounts.education.status(request_context))
@console_ns.route("/account/education/autocomplete")
class EducationAutoCompleteApi(Resource):
@console_ns.doc(params=query_params_from_model(EducationAutocompleteQuery))
- @setup_required
- @login_required
- @account_initialization_required
- @only_edition_cloud
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[EducationAutocompleteResponse.__name__])
- def get(self):
+ @console_account_admission(editions=frozenset({DeploymentEdition.CLOUD}))
+ def get(self, request_context: RequestContext):
payload = request.args.to_dict(flat=True)
args = EducationAutocompleteQuery.model_validate(payload)
return dump_response(
EducationAutocompleteResponse,
- BillingService.EducationIdentity.autocomplete(args.keywords, args.page, args.limit) or {},
+ application_services().accounts.education.autocomplete(
+ request_context,
+ keywords=args.keywords,
+ page=args.page,
+ limit=args.limit,
+ ),
)
@@ -598,8 +582,7 @@ class EducationAutoCompleteApi(Resource):
class ChangeEmailSendEmailApi(Resource):
@console_ns.expect(console_ns.models[ChangeEmailSendPayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultDataResponse.__name__])
- @enable_change_email
- @console_account_admission()
+ @console_account_admission(require_change_email_enabled=True)
def post(self, request_context: RequestContext):
payload = console_ns.payload or {}
args = ChangeEmailSendPayload.model_validate(payload)
@@ -632,8 +615,7 @@ class ChangeEmailSendEmailApi(Resource):
class ChangeEmailCheckApi(Resource):
@console_ns.expect(console_ns.models[ChangeEmailValidityPayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[VerificationTokenResponse.__name__])
- @enable_change_email
- @console_account_admission()
+ @console_account_admission(require_change_email_enabled=True)
def post(self, request_context: RequestContext):
payload = console_ns.payload or {}
args = ChangeEmailValidityPayload.model_validate(payload)
@@ -661,9 +643,8 @@ class ChangeEmailCheckApi(Resource):
@console_ns.route("/account/change-email/reset")
class ChangeEmailResetApi(Resource):
@console_ns.expect(console_ns.models[ChangeEmailResetPayload.__name__])
- @enable_change_email
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AccountResponse.__name__])
- @console_account_admission()
+ @console_account_admission(require_change_email_enabled=True)
def post(self, request_context: RequestContext):
payload = console_ns.payload or {}
args = ChangeEmailResetPayload.model_validate(payload)
diff --git a/api/extensions/ext_application_services.py b/api/extensions/ext_application_services.py
index 9035f5a6580..24d5efa8673 100644
--- a/api/extensions/ext_application_services.py
+++ b/api/extensions/ext_application_services.py
@@ -40,6 +40,10 @@ from services.account_activation_adapters import (
from services.account_activation_service import AccountActivationService
from services.account_avatar_file_gateway import SQLAlchemyAccountAvatarFileGateway
from services.account_avatar_service import AccountAvatarService
+from services.account_billing_adapters import (
+ BillingAccountDeletionFeedbackGateway,
+ BillingAccountEducationGateway,
+)
from services.account_change_email_adapters import (
BillingAccountEmailPolicyGateway,
CeleryChangeEmailNotificationGateway,
@@ -55,7 +59,9 @@ from services.account_deletion_adapters import (
EnterpriseAccountDeletionSyncGateway,
TokenManagerAccountDeletionVerificationGateway,
)
+from services.account_deletion_feedback_service import AccountDeletionFeedbackService
from services.account_deletion_service import AccountDeletionService
+from services.account_education_service import AccountEducationService
from services.account_initialization_service import AccountInitializationService
from services.account_integration_service import AccountIntegrationService
from services.account_password_hasher import LegacyAccountPasswordHasher
@@ -122,6 +128,8 @@ class AccountServices:
avatar: AccountAvatarService
change_email: AccountChangeEmailService
deletion: AccountDeletionService
+ deletion_feedback: AccountDeletionFeedbackService
+ education: AccountEducationService
initialization: AccountInitializationService
integrations: AccountIntegrationService
password: AccountPasswordService
@@ -214,6 +222,13 @@ def build_application_services(
synchronization=EnterpriseAccountDeletionSyncGateway(),
scheduler=CeleryAccountDeletionScheduler(),
),
+ deletion_feedback=AccountDeletionFeedbackService(
+ feedback=BillingAccountDeletionFeedbackGateway(),
+ ),
+ education=AccountEducationService(
+ accounts=accounts,
+ education=BillingAccountEducationGateway(),
+ ),
initialization=AccountInitializationService(
accounts=accounts,
invitation_required=deployment_edition == DeploymentEdition.CLOUD,
diff --git a/api/services/account_billing_adapters.py b/api/services/account_billing_adapters.py
new file mode 100644
index 00000000000..c64b70f01ad
--- /dev/null
+++ b/api/services/account_billing_adapters.py
@@ -0,0 +1,71 @@
+"""Billing adapters for account education and deletion-feedback use cases."""
+
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Any, cast, override
+
+from services.account_deletion_feedback_service import AccountDeletionFeedbackGateway
+from services.account_education_service import AccountEducationGateway
+from services.billing_service import BillingService
+from services.entities.account_entities import (
+ AccountEducationAutocomplete,
+ AccountEducationStatus,
+ AccountEducationVerification,
+)
+
+if TYPE_CHECKING:
+ from models.account import Account
+
+
+@dataclass(frozen=True, slots=True)
+class _EducationAccount:
+ id: str
+ email: str
+ current_tenant_id: str
+
+
+class BillingAccountEducationGateway(AccountEducationGateway):
+ @override
+ def verify(self, *, account_id: str, email: str) -> AccountEducationVerification:
+ result = BillingService.EducationIdentity.verify(account_id, email) or {}
+ return AccountEducationVerification(token=result.get("token"))
+
+ @override
+ def activate(
+ self,
+ *,
+ account_id: str,
+ email: str,
+ tenant_id: str,
+ token: str,
+ institution: str,
+ role: str,
+ ) -> dict[str, Any] | None:
+ account = cast("Account", _EducationAccount(id=account_id, email=email, current_tenant_id=tenant_id))
+ return BillingService.EducationIdentity.activate(account, token, institution, role)
+
+ @override
+ def status(self, account_id: str) -> AccountEducationStatus:
+ result: dict[str, Any] = BillingService.EducationIdentity.status(account_id) or {}
+ expire_at = result.get("expire_at")
+ return AccountEducationStatus(
+ result=result.get("result"),
+ is_student=result.get("is_student"),
+ expire_at=datetime.fromisoformat(expire_at).astimezone(UTC) if isinstance(expire_at, str) else expire_at,
+ allow_refresh=result.get("allow_refresh"),
+ )
+
+ @override
+ def autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete:
+ result: dict[str, Any] = BillingService.EducationIdentity.autocomplete(keywords, page, limit) or {}
+ return AccountEducationAutocomplete(
+ data=tuple(result.get("data") or ()),
+ curr_page=result.get("curr_page"),
+ has_next=result.get("has_next"),
+ )
+
+
+class BillingAccountDeletionFeedbackGateway(AccountDeletionFeedbackGateway):
+ @override
+ def submit(self, *, email: str, feedback: str) -> None:
+ BillingService.update_account_deletion_feedback(email, feedback)
diff --git a/api/services/account_deletion_feedback_service.py b/api/services/account_deletion_feedback_service.py
new file mode 100644
index 00000000000..baf0c5065c4
--- /dev/null
+++ b/api/services/account_deletion_feedback_service.py
@@ -0,0 +1,15 @@
+"""Application service for submitting account deletion feedback."""
+
+from typing import Protocol
+
+
+class AccountDeletionFeedbackGateway(Protocol):
+ def submit(self, *, email: str, feedback: str) -> None: ...
+
+
+class AccountDeletionFeedbackService:
+ def __init__(self, *, feedback: AccountDeletionFeedbackGateway) -> None:
+ self._feedback = feedback
+
+ def submit(self, *, email: str, feedback: str) -> None:
+ self._feedback.submit(email=email, feedback=feedback)
diff --git a/api/services/account_education_service.py b/api/services/account_education_service.py
new file mode 100644
index 00000000000..1217802dba3
--- /dev/null
+++ b/api/services/account_education_service.py
@@ -0,0 +1,84 @@
+"""Application service for account education-discount use cases."""
+
+from typing import Any, Protocol
+
+from machinery.context import RequestContext
+from machinery.errors import ActiveWorkspaceRequiredError
+from services.account_errors import AccountNotFoundError
+from services.account_ports import AccountRepository
+from services.entities.account_entities import (
+ AccountEducationAutocomplete,
+ AccountEducationStatus,
+ AccountEducationVerification,
+)
+
+
+class AccountEducationGateway(Protocol):
+ def verify(self, *, account_id: str, email: str) -> AccountEducationVerification: ...
+
+ def activate(
+ self,
+ *,
+ account_id: str,
+ email: str,
+ tenant_id: str,
+ token: str,
+ institution: str,
+ role: str,
+ ) -> dict[str, Any] | None: ...
+
+ def status(self, account_id: str) -> AccountEducationStatus: ...
+
+ def autocomplete(self, *, keywords: str, page: int, limit: int) -> AccountEducationAutocomplete: ...
+
+
+class AccountEducationService:
+ def __init__(
+ self,
+ *,
+ accounts: AccountRepository,
+ education: AccountEducationGateway,
+ ) -> None:
+ self._accounts = accounts
+ self._education = education
+
+ def verify(self, context: RequestContext) -> AccountEducationVerification:
+ account = self._accounts.get(context.account_id)
+ if account is None:
+ raise AccountNotFoundError
+ return self._education.verify(account_id=account.id, email=account.email)
+
+ def activate(
+ self,
+ context: RequestContext,
+ *,
+ token: str,
+ institution: str,
+ role: str,
+ ) -> dict[str, Any] | None:
+ account = self._accounts.get(context.account_id)
+ if account is None:
+ raise AccountNotFoundError
+ if context.active_workspace_id is None:
+ raise ActiveWorkspaceRequiredError
+ return self._education.activate(
+ account_id=account.id,
+ email=account.email,
+ tenant_id=context.active_workspace_id,
+ token=token,
+ institution=institution,
+ role=role,
+ )
+
+ def status(self, context: RequestContext) -> AccountEducationStatus:
+ return self._education.status(context.account_id)
+
+ def autocomplete(
+ self,
+ context: RequestContext,
+ *,
+ keywords: str,
+ page: int,
+ limit: int,
+ ) -> AccountEducationAutocomplete:
+ return self._education.autocomplete(keywords=keywords, page=page, limit=limit)
diff --git a/api/services/account_errors.py b/api/services/account_errors.py
index 1146fab3ff3..353de34188a 100644
--- a/api/services/account_errors.py
+++ b/api/services/account_errors.py
@@ -83,3 +83,7 @@ class AccountEmailDomainSuspendedError(AccountEmailFrozenError):
class AccountEmailAlreadyInUseError(AccountApplicationError):
"""The target email already belongs to an account."""
+
+
+class EducationDiscountPausedError(AccountApplicationError):
+ """Education discount activation is temporarily paused."""
diff --git a/api/services/entities/account_entities.py b/api/services/entities/account_entities.py
index 7d80c122817..fdf61e4c040 100644
--- a/api/services/entities/account_entities.py
+++ b/api/services/entities/account_entities.py
@@ -176,3 +176,23 @@ type AccountChangeEmailTokenData = (
| AccountChangeEmailNewEmailToken
| AccountChangeEmailNewEmailVerifiedToken
)
+
+
+@dataclass(frozen=True, slots=True)
+class AccountEducationVerification:
+ token: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class AccountEducationStatus:
+ result: bool | None
+ is_student: bool | None
+ expire_at: datetime | None
+ allow_refresh: bool | None
+
+
+@dataclass(frozen=True, slots=True)
+class AccountEducationAutocomplete:
+ data: tuple[str, ...]
+ curr_page: int | None
+ has_next: bool | None
diff --git a/api/tests/unit_tests/controllers/console/test_workspace_account.py b/api/tests/unit_tests/controllers/console/test_workspace_account.py
index fa61aed18db..08799614a33 100644
--- a/api/tests/unit_tests/controllers/console/test_workspace_account.py
+++ b/api/tests/unit_tests/controllers/console/test_workspace_account.py
@@ -103,22 +103,38 @@ def _build_change_email_token(
class TestEducationApi:
- @patch("controllers.console.workspace.account.BillingService.EducationIdentity.activate")
- def test_post_activates_education_discount(self, mock_activate: MagicMock, app: Flask):
- account = _build_account("[email protected]")
- mock_activate.return_value = {"message": "success"}
-
- with app.test_request_context(
- "/account/education",
- method="POST",
- json={"token": "education-token", "institution": "Dify University", "role": "Student"},
+ def test_post_activates_education_discount(self, app: Flask):
+ education = MagicMock()
+ education.activate.return_value = {"message": "success"}
+ request_context = RequestContext(
+ request_id="request-1",
+ trace_id=None,
+ account_id="account-1",
+ active_workspace_id="workspace-1",
+ )
+
+ with (
+ app.test_request_context(
+ "/account/education",
+ method="POST",
+ json={"token": "education-token", "institution": "Dify University", "role": "Student"},
+ ),
+ patch(
+ "controllers.console.workspace.account.application_services",
+ return_value=SimpleNamespace(accounts=SimpleNamespace(education=education)),
+ ),
):
api = EducationApi()
method = inspect.unwrap(api.post)
- result = method(api, account)
+ result = method(api, request_context)
assert result == {"message": "success"}
- mock_activate.assert_called_once_with(account, "education-token", "Dify University", "Student")
+ education.activate.assert_called_once_with(
+ request_context,
+ token="education-token",
+ institution="Dify University",
+ role="Student",
+ )
def _change_email_context(account_id: str = "acc") -> RequestContext:
@@ -353,19 +369,27 @@ class TestAccountServiceGetChangeEmailData:
class TestAccountDeletionFeedback:
- @patch("controllers.console.workspace.account.BillingService.update_account_deletion_feedback")
- def test_should_normalize_feedback_email(self, mock_update, app: Flask):
- with app.test_request_context(
- "/account/delete/feedback",
- method="POST",
- json={"email": "[email protected]", "feedback": "test"},
+ def test_delegates_feedback_to_application_service(self, app: Flask):
+ deletion_feedback = MagicMock()
+ with (
+ app.test_request_context(
+ "/account/delete/feedback",
+ method="POST",
+ json={"email": "[email protected]", "feedback": "test"},
+ ),
+ patch(
+ "controllers.console.workspace.account.application_services",
+ return_value=SimpleNamespace(
+ accounts=SimpleNamespace(deletion_feedback=deletion_feedback),
+ ),
+ ),
):
api = AccountDeleteUpdateFeedbackApi()
method = inspect.unwrap(api.post)
response = method(api)
assert response == {"result": "success"}
- mock_update.assert_called_once_with("[email protected]", "test")
+ deletion_feedback.submit.assert_called_once_with(email="[email protected]", feedback="test")
class TestCheckEmailUnique:
diff --git a/api/tests/unit_tests/controllers/console/test_wraps.py b/api/tests/unit_tests/controllers/console/test_wraps.py
index 7b5e9d913be..188e5884526 100644
--- a/api/tests/unit_tests/controllers/console/test_wraps.py
+++ b/api/tests/unit_tests/controllers/console/test_wraps.py
@@ -130,7 +130,11 @@ class TestCurrentContextInjection:
"""Test request context injection decorators."""
def test_console_maps_missing_active_workspace_to_safe_internal_error(self):
- handler = console_api.error_handlers[ActiveWorkspaceRequiredError]
+ handler = next(
+ handler
+ for error_type, handler in console_api.error_handlers.items()
+ if error_type is ActiveWorkspaceRequiredError
+ )
with Flask(__name__).app_context():
body, status = handler(ActiveWorkspaceRequiredError())
@@ -264,6 +268,7 @@ class TestCurrentContextInjection:
with Flask(__name__).test_request_context(headers={"X-Trace-Id": "trace-1"}):
result = Handler().post()
+ assert isinstance(result, RequestContext)
assert result.active_workspace_id == "tenant-123"
assert result.trace_id == "trace-1"
enforce_rbac_access.assert_called_once_with(
@@ -303,9 +308,28 @@ class TestCurrentContextInjection:
with Flask(__name__).test_request_context():
result = Handler().post()
+ assert isinstance(result, RequestContext)
assert result.account_id == current_user.id
account_initialization_required.assert_not_called()
+ def test_console_account_admission_declares_optional_change_email_gate(self):
+ with (
+ patch("controllers.console.flask_admission.setup_required", side_effect=lambda view: view),
+ patch("controllers.console.flask_admission.login_required", side_effect=lambda view: view),
+ patch("controllers.console.flask_admission.account_initialization_required", side_effect=lambda view: view),
+ patch(
+ "controllers.console.flask_admission.enable_change_email",
+ side_effect=lambda view: view,
+ ) as change_email_enabled,
+ ):
+
+ class Handler:
+ @flask_admission.console_account_admission(require_change_email_enabled=True)
+ def get(self, request_context: RequestContext):
+ return request_context
+
+ change_email_enabled.assert_called_once()
+
def test_with_current_tenant_id_injects_tenant_id(self):
class Handler:
@with_current_tenant_id
diff --git a/api/tests/unit_tests/extensions/test_ext_application_services.py b/api/tests/unit_tests/extensions/test_ext_application_services.py
index 82f11568a25..9bb8b83d0e2 100644
--- a/api/tests/unit_tests/extensions/test_ext_application_services.py
+++ b/api/tests/unit_tests/extensions/test_ext_application_services.py
@@ -188,6 +188,7 @@ def test_build_application_services_wires_account_profile_repository(
assert services.accounts.initialization._accounts is accounts
assert not services.accounts.initialization._invitation_required
assert services.accounts.change_email._accounts is accounts
+ assert services.accounts.education._accounts is accounts
assert services.accounts.deletion._accounts is accounts
assert services.accounts.deletion._memberships is services.workspace_queries._workspaces
integrations = services.accounts.integrations._integrations
diff --git a/api/tests/unit_tests/services/test_account_billing_adapters.py b/api/tests/unit_tests/services/test_account_billing_adapters.py
new file mode 100644
index 00000000000..9f6e1f4bd7c
--- /dev/null
+++ b/api/tests/unit_tests/services/test_account_billing_adapters.py
@@ -0,0 +1,63 @@
+from datetime import UTC, datetime
+from unittest.mock import patch
+
+from services.account_billing_adapters import BillingAccountEducationGateway
+from services.entities.account_entities import AccountEducationAutocomplete, AccountEducationStatus
+
+
+def test_education_gateway_normalizes_billing_status_timestamp() -> None:
+ gateway = BillingAccountEducationGateway()
+
+ with patch(
+ "services.account_billing_adapters.BillingService.EducationIdentity.status",
+ return_value={
+ "result": True,
+ "is_student": True,
+ "expire_at": "2027-01-01T00:00:00+00:00",
+ "allow_refresh": False,
+ },
+ ):
+ result = gateway.status("account-1")
+
+ assert result == AccountEducationStatus(
+ result=True,
+ is_student=True,
+ expire_at=datetime(2027, 1, 1, tzinfo=UTC),
+ allow_refresh=False,
+ )
+
+
+def test_education_gateway_activates_with_primitive_account_context() -> None:
+ gateway = BillingAccountEducationGateway()
+
+ with patch(
+ "services.account_billing_adapters.BillingService.EducationIdentity.activate",
+ return_value={"message": "success"},
+ ) as activate:
+ result = gateway.activate(
+ account_id="account-1",
+ tenant_id="workspace-1",
+ token="education-token",
+ institution="Dify University",
+ role="Student",
+ )
+
+ assert result == {"message": "success"}
+ account = activate.call_args.args[0]
+ assert account.id == "account-1"
+ assert account.email == "[email protected]"
+ assert account.current_tenant_id == "workspace-1"
+ assert activate.call_args.args[1:] == ("education-token", "Dify University", "Student")
+
+
+def test_education_gateway_normalizes_autocomplete_defaults() -> None:
+ gateway = BillingAccountEducationGateway()
+
+ with patch(
+ "services.account_billing_adapters.BillingService.EducationIdentity.autocomplete",
+ return_value=None,
+ ):
+ result = gateway.autocomplete(keywords="Example", page=0, limit=20)
+
+ assert result == AccountEducationAutocomplete(data=(), curr_page=None, has_next=None)
diff --git a/api/tests/unit_tests/services/test_account_deletion_feedback_service.py b/api/tests/unit_tests/services/test_account_deletion_feedback_service.py
new file mode 100644
index 00000000000..7d427c94c6d
--- /dev/null
+++ b/api/tests/unit_tests/services/test_account_deletion_feedback_service.py
@@ -0,0 +1,12 @@
+from unittest.mock import Mock
+
+from services.account_deletion_feedback_service import AccountDeletionFeedbackGateway, AccountDeletionFeedbackService
+
+
+def test_submit_delegates_to_billing_gateway() -> None:
+ feedback = Mock(spec=AccountDeletionFeedbackGateway)
+ service = AccountDeletionFeedbackService(feedback=feedback)
+
+ service.submit(email="[email protected]", feedback="No longer needed")
+
+ feedback.submit.assert_called_once_with(email="[email protected]", feedback="No longer needed")
diff --git a/api/tests/unit_tests/services/test_account_education_service.py b/api/tests/unit_tests/services/test_account_education_service.py
new file mode 100644
index 00000000000..5c77ca12864
--- /dev/null
+++ b/api/tests/unit_tests/services/test_account_education_service.py
@@ -0,0 +1,106 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from unittest.mock import Mock
+
+from machinery.context import RequestContext
+from services.account_education_service import AccountEducationGateway, AccountEducationService
+from services.account_ports import AccountRepository
+from services.entities.account_entities import (
+ AccountEducationAutocomplete,
+ AccountEducationStatus,
+ AccountEducationVerification,
+ AccountSnapshot,
+)
+
+
+def _context() -> RequestContext:
+ return RequestContext(
+ request_id="request-1",
+ trace_id="trace-1",
+ account_id="account-1",
+ active_workspace_id="workspace-1",
+ )
+
+
+def _account() -> AccountSnapshot:
+ return AccountSnapshot(
+ id="account-1",
+ name="Student",
+ avatar=None,
+ is_password_set=True,
+ interface_language="en-US",
+ interface_theme="light",
+ timezone="UTC",
+ last_login_at=None,
+ last_login_ip=None,
+ status="active",
+ initialized_at=datetime(2026, 1, 1),
+ created_at=datetime(2026, 1, 1),
+ )
+
+
+def test_verify_reads_account_before_billing_gateway_call() -> None:
+ accounts = Mock(spec=AccountRepository)
+ accounts.get.return_value = _account()
+ education = Mock(spec=AccountEducationGateway)
+ education.verify.return_value = AccountEducationVerification(token="education-token")
+ service = AccountEducationService(accounts=accounts, education=education)
+
+ result = service.verify(_context())
+
+ assert result == AccountEducationVerification(token="education-token")
+ accounts.get.assert_called_once_with("account-1")
+ education.verify.assert_called_once_with(account_id="account-1", email="[email protected]")
+
+
+def test_status_and_autocomplete_delegate_framework_neutral_contracts() -> None:
+ accounts = Mock(spec=AccountRepository)
+ education = Mock(spec=AccountEducationGateway)
+ status = AccountEducationStatus(
+ result=True,
+ is_student=True,
+ expire_at=datetime(2027, 1, 1, tzinfo=UTC),
+ allow_refresh=False,
+ )
+ autocomplete = AccountEducationAutocomplete(data=("Example University",), curr_page=0, has_next=False)
+ education.status.return_value = status
+ education.autocomplete.return_value = autocomplete
+ service = AccountEducationService(
+ accounts=accounts,
+ education=education,
+ )
+
+ assert service.status(_context()) == status
+ assert service.autocomplete(_context(), keywords="Example", page=0, limit=20) == autocomplete
+ education.status.assert_called_once_with("account-1")
+ education.autocomplete.assert_called_once_with(keywords="Example", page=0, limit=20)
+
+
+def test_activate_delegates_account_and_workspace_context() -> None:
+ accounts = Mock(spec=AccountRepository)
+ accounts.get.return_value = _account()
+ education = Mock(spec=AccountEducationGateway)
+ education.activate.return_value = {"message": "success"}
+ service = AccountEducationService(
+ accounts=accounts,
+ education=education,
+ )
+
+ result = service.activate(
+ _context(),
+ token="education-token",
+ institution="Dify University",
+ role="Student",
+ )
+
+ assert result == {"message": "success"}
+ education.activate.assert_called_once_with(
+ account_id="account-1",
+ tenant_id="workspace-1",
+ token="education-token",
+ institution="Dify University",
+ role="Student",
+ )