stapel-courses 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. stapel_courses/CONFIG.MD +43 -0
  2. stapel_courses/__init__.py +31 -0
  3. stapel_courses/_capabilities.py +39 -0
  4. stapel_courses/_codegen.py +123 -0
  5. stapel_courses/_codegen_settings.py +119 -0
  6. stapel_courses/access.py +152 -0
  7. stapel_courses/actions.py +78 -0
  8. stapel_courses/admin.py +135 -0
  9. stapel_courses/apps.py +23 -0
  10. stapel_courses/beat.py +48 -0
  11. stapel_courses/blocks.py +168 -0
  12. stapel_courses/checks.py +154 -0
  13. stapel_courses/codegen_urls.py +6 -0
  14. stapel_courses/conf.py +100 -0
  15. stapel_courses/conftest.py +163 -0
  16. stapel_courses/docs/capabilities.json +299 -0
  17. stapel_courses/docs/errors.json +644 -0
  18. stapel_courses/docs/flows.json +639 -0
  19. stapel_courses/docs/llms.txt +214 -0
  20. stapel_courses/dto.py +353 -0
  21. stapel_courses/errors.py +81 -0
  22. stapel_courses/flows.py +68 -0
  23. stapel_courses/fsm.py +54 -0
  24. stapel_courses/functions.py +66 -0
  25. stapel_courses/gdpr.py +128 -0
  26. stapel_courses/management/__init__.py +0 -0
  27. stapel_courses/management/commands/__init__.py +0 -0
  28. stapel_courses/management/commands/courses_housekeeping.py +10 -0
  29. stapel_courses/management/commands/courses_seed_demo.py +16 -0
  30. stapel_courses/migrations/0001_initial.py +228 -0
  31. stapel_courses/migrations/__init__.py +0 -0
  32. stapel_courses/models.py +502 -0
  33. stapel_courses/pagination.py +47 -0
  34. stapel_courses/presenters.py +416 -0
  35. stapel_courses/preset.py +27 -0
  36. stapel_courses/py.typed +0 -0
  37. stapel_courses/schemas/consumes/orders.order.paid.json +11 -0
  38. stapel_courses/schemas/consumes/orders.order.placed.json +23 -0
  39. stapel_courses/schemas/consumes/orders.order.refunded.json +11 -0
  40. stapel_courses/schemas/consumes/orders.order.status_changed.json +12 -0
  41. stapel_courses/schemas/consumes/user.merged.json +19 -0
  42. stapel_courses/schemas/emits/courses.certificate.issued.json +15 -0
  43. stapel_courses/schemas/emits/courses.course.completed.json +15 -0
  44. stapel_courses/schemas/emits/courses.enrollment.activated.json +17 -0
  45. stapel_courses/schemas/emits/courses.enrollment.status_changed.json +17 -0
  46. stapel_courses/schemas/functions/courses.certificate.verify.json +11 -0
  47. stapel_courses/schemas/functions/courses.enrollment.status.json +12 -0
  48. stapel_courses/schemas/functions/courses.purchasables.json +37 -0
  49. stapel_courses/seed.py +82 -0
  50. stapel_courses/serializers.py +725 -0
  51. stapel_courses/services/__init__.py +46 -0
  52. stapel_courses/services/authoring.py +351 -0
  53. stapel_courses/services/catalog.py +57 -0
  54. stapel_courses/services/certificates.py +112 -0
  55. stapel_courses/services/enrollments.py +300 -0
  56. stapel_courses/services/entitlements.py +67 -0
  57. stapel_courses/services/events.py +155 -0
  58. stapel_courses/services/gate.py +216 -0
  59. stapel_courses/services/learners.py +48 -0
  60. stapel_courses/services/progress.py +179 -0
  61. stapel_courses/services/purchases.py +177 -0
  62. stapel_courses/services/quizzes.py +307 -0
  63. stapel_courses/translations/errors.es.json +31 -0
  64. stapel_courses/translations/errors.ru.json +31 -0
  65. stapel_courses/urls.py +14 -0
  66. stapel_courses/urls_v1.py +71 -0
  67. stapel_courses/views.py +777 -0
  68. stapel_courses-0.1.0.dist-info/METADATA +155 -0
  69. stapel_courses-0.1.0.dist-info/RECORD +72 -0
  70. stapel_courses-0.1.0.dist-info/WHEEL +5 -0
  71. stapel_courses-0.1.0.dist-info/licenses/LICENSE +21 -0
  72. stapel_courses-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,43 @@
1
+ # CONFIG.MD — stapel-courses
2
+
3
+ Config registry for **stapel-courses**. One row per configuration key the
4
+ module reads, its **source** (`env` = the process environment / the
5
+ `STAPEL_COURSES` settings dict; `settings` = the settings module only), what
6
+ it is for, whether it is required, and its default.
7
+
8
+ Every key is read through `courses_settings` (`stapel_courses.conf`,
9
+ namespace `STAPEL_COURSES`). Resolution order per key:
10
+ `settings.STAPEL_COURSES` dict → a flat Django setting of the same name →
11
+ environment variable → the default below. `DEFAULT_ACCESS`,
12
+ `ENROLLMENT_REQUIRES_ACCOUNT`, `PURCHASE_ACTIVATION`, `DEFAULT_DRIP`,
13
+ `DEFAULT_SEQUENTIAL`, `AUTHORING` and `CERTIFICATES` are CTO-facing config
14
+ axes.
15
+
16
+ ## stapel-courses
17
+
18
+ | Key | Source | Purpose | Required | Default |
19
+ |-----|--------|---------|----------|---------|
20
+ | ACCESS_STRATEGIES | settings | access strategies `{name: dotted path or None}` merged over free / enrolled / purchased / entitlement; a dotted path under a built-in name replaces it. Checked by E001. | no | {} |
21
+ | DEFAULT_ACCESS | env | axis: the access strategy a new course starts with. Unknown name is E002. | no | enrolled |
22
+ | DEFAULT_DRIP | env | axis: the drip mode a new course starts with (none, days, date). E005. | no | none |
23
+ | DEFAULT_SEQUENTIAL | env | axis: a new course unlocks lessons strictly in order. | no | false |
24
+ | AUTHORING | env | axis: who creates courses (staff, members). E005. | no | staff |
25
+ | ENROLLMENT_REQUIRES_ACCOUNT | env | axis: a guest gets `error.403.enrollment_requires_account` on enroll / progress / attempts. | no | true |
26
+ | PURCHASABLE_TYPE | env | the orders purchasable type a course line carries. | no | course |
27
+ | PURCHASE_ACTIVATION | env | axis: which order fact activates a bought course (paid, confirmed, placed). E005. | no | paid |
28
+ | ENTITLEMENT_FUNCTION | env | the comm Function asked `{user_id, key}` for the entitlement strategy. | no | billing.check_entitlement |
29
+ | ENTITLEMENT_KEY_TEMPLATE | env | `{slug}` / `{course_id}` template of the entitlement key when a course names none. | no | course:{slug} |
30
+ | ENTITLEMENT_CACHE_SECONDS | env | how long an entitlement answer is cached; 0 = ask every time. | no | 300 |
31
+ | BLOCK_TYPES | settings | lesson block validators `{type: dotted path or None}` merged over text / video / attachment / embed. E004. | no | {} |
32
+ | CARDS_FUNCTION | env | the comm Function asked `{user_ids}` for learner display cards on the author/staff views (profiles.public_cards contract); empty = `user_id` only. | no | profiles.public_cards |
33
+ | EMBED_HOSTS | settings | exact hosts an embed block may use (https only); bare host names (E007); empty = no embed block is accepted. | no | youtube, youtube-nocookie, vimeo, google maps hosts |
34
+ | DEFAULT_PASS_MARK | env | pass mark (percent) of a new quiz. | no | 70 |
35
+ | DEFAULT_MAX_ATTEMPTS | env | attempt limit of a new quiz; 0 = unlimited. | no | 3 |
36
+ | COMPLETION_RULE | settings | dotted path `(enrollment) -> bool` deciding completion. E006. | no | stapel_courses.services.progress.default_completion_rule |
37
+ | CERTIFICATES | env | axis: issue a certificate on completion. | no | true |
38
+ | PUBLIC_VERIFY_FIELDS | settings | fields the public verification shows besides number and validity (holder_name, course_title, course_slug, issued_at). E003. | no | ["course_title", "issued_at"] |
39
+ | CERTIFICATE_NUMBER_PREFIX | env | prefix of certificate numbers. | no | CERT |
40
+ | HOLDER_NAME_RESOLVER | settings | dotted path `(user_id) -> str`, the name printed on a certificate. E006. | no | stapel_courses.services.certificates.default_holder_name |
41
+ | NOTIFY | env | best-effort notifications courses.enrollment_activated / .completed / .certificate_issued. | no | true |
42
+ | COURSE_URL_TEMPLATE | env | `{slug}` / `{course_id}` link for notifications and the purchasable `url`; empty = no link. | no | "" |
43
+ | CERTIFICATE_URL_TEMPLATE | env | `{number}` / `{slug}` / `{course_id}` link for the certificate notification; empty = no link. | no | "" |
@@ -0,0 +1,31 @@
1
+ """stapel-courses — Courses and learning for the Stapel framework.
2
+
3
+ Public API (lazily exported, PEP 562 — importing this package never pulls
4
+ in Django or requires configured settings):
5
+
6
+ - ``courses_settings`` — resolved app settings (``stapel_courses.conf``).
7
+ """
8
+
9
+ __all__ = [
10
+ "courses_settings",
11
+ ]
12
+
13
+ # name -> submodule that defines it. Resolution is deferred until first
14
+ # attribute access so that `import stapel_courses` stays Django-free.
15
+ _LAZY_EXPORTS = {
16
+ "courses_settings": ".conf",
17
+ }
18
+
19
+
20
+ def __getattr__(name):
21
+ if name in _LAZY_EXPORTS:
22
+ from importlib import import_module
23
+
24
+ value = getattr(import_module(_LAZY_EXPORTS[name], __name__), name)
25
+ globals()[name] = value # cache for subsequent lookups
26
+ return value
27
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
28
+
29
+
30
+ def __dir__():
31
+ return sorted(set(globals()) | set(__all__))
@@ -0,0 +1,39 @@
1
+ """stapel-courses capabilities.json emitter — thin shim over stapel_tools.capabilities."""
2
+ from pathlib import Path
3
+
4
+ from stapel_tools.capabilities import axis_group_rules, run_capabilities_cli
5
+
6
+ #: CTO-facing axes, all behavioural (no endpoint is unmounted).
7
+ AXES = {
8
+ "DEFAULT_ACCESS": "courses.access",
9
+ "ENROLLMENT_REQUIRES_ACCOUNT": "courses.access",
10
+ "PURCHASE_ACTIVATION": "courses.purchase",
11
+ "DEFAULT_DRIP": "courses.pacing",
12
+ "DEFAULT_SEQUENTIAL": "courses.pacing",
13
+ "AUTHORING": "courses.authoring",
14
+ "CERTIFICATES": "courses.certificates",
15
+ "EMBED_HOSTS": "courses.content",
16
+ }
17
+
18
+
19
+ def main(argv=None):
20
+ from stapel_courses._codegen import _configure
21
+
22
+ _configure()
23
+ from stapel_courses.conf import DEFAULTS
24
+ from stapel_courses.urls import GATE_REGISTRY
25
+
26
+ return run_capabilities_cli(
27
+ argv,
28
+ repo=Path(__file__).resolve().parent,
29
+ canonical_prefix="/courses/api/v1",
30
+ defaults=DEFAULTS,
31
+ registry=GATE_REGISTRY,
32
+ is_axis=lambda k: k in AXES,
33
+ axis_group=axis_group_rules(exact=AXES),
34
+ prog="stapel-courses-capabilities",
35
+ )
36
+
37
+
38
+ if __name__ == "__main__":
39
+ raise SystemExit(main())
@@ -0,0 +1,123 @@
1
+ """stapel-courses contract-emission harness (contract-pipeline.md §2-3).
2
+
3
+ Emits the module's own contract triad into ``docs/`` from a single-module
4
+ ``{courses + core}`` Django instance mounted at the canonical
5
+ ``courses/api/v1/`` prefix:
6
+
7
+ docs/schema.json drf-spectacular OpenAPI, this module only, canonical prefix
8
+ docs/flows.json generate_flow_docs machine artifact ([] — no @flow_step here)
9
+ docs/errors.json generate_error_keys registry
10
+
11
+ The *mechanism* is stapel_tools.codegen (shared, unchanged); this file is the
12
+ thin per-module *config* that wires the module's settings + canonical mount.
13
+
14
+ Usage:
15
+ python -m stapel_courses._codegen --out docs # `make contract`
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import os
21
+ import sys
22
+ from pathlib import Path
23
+
24
+
25
+ def _configure() -> None:
26
+ """Configure + boot the single-module Django instance for emission."""
27
+ repo_root = os.path.dirname(os.path.abspath(__file__))
28
+ sys.path[:] = [p for p in sys.path if os.path.abspath(p or os.getcwd()) != repo_root]
29
+
30
+ from django.conf import settings
31
+
32
+ if not settings.configured:
33
+ from stapel_courses._codegen_settings import settings_kwargs
34
+
35
+ settings.configure(
36
+ **settings_kwargs(root_urlconf="stapel_courses.codegen_urls", contract=True)
37
+ )
38
+
39
+ import django
40
+
41
+ django.setup()
42
+
43
+ from drf_spectacular.settings import spectacular_settings
44
+
45
+ from stapel_courses._codegen_settings import CODEGEN_SCHEMA_PATH_PREFIX
46
+
47
+ spectacular_settings.SCHEMA_PATH_PREFIX = CODEGEN_SCHEMA_PATH_PREFIX
48
+
49
+ # Stable enum component names (stapel-schema-lint SCH004).
50
+ from drf_spectacular.plumbing import _load_enum_name_overrides
51
+
52
+ from stapel_courses._codegen_settings import enum_name_overrides
53
+
54
+ spectacular_settings.ENUM_NAME_OVERRIDES = enum_name_overrides()
55
+ _load_enum_name_overrides.cache_clear()
56
+
57
+ # Register drf-spectacular's JWT cookie-auth extension explicitly (a real
58
+ # host triggers this as a side effect of wiring its Swagger URLs). Without
59
+ # it, the protected endpoints
60
+ # would emit without their `security: [{"JWTCookieAuth": []}]` entry — a
61
+ # real contract gap. Applied per stapel-calendar's precedent.
62
+ from stapel_core.django.openapi.swagger import _register_jwt_auth_extension
63
+
64
+ _register_jwt_auth_extension()
65
+
66
+
67
+ def _require_python_312() -> None:
68
+ """Abort emission if not running the pinned 3.12 interpreter.
69
+
70
+ drf-spectacular's rendering of component descriptions (``Optional[X]`` vs
71
+ ``X | None``) depends on the Python minor version — contracts emitted on
72
+ anything other than 3.12 (the CI/monolith pin) produce false diffs.
73
+ """
74
+ if sys.version_info[:2] != (3, 12):
75
+ got = f"{sys.version_info.major}.{sys.version_info.minor}"
76
+ raise SystemExit(
77
+ f"stapel-courses contract emission ABORTED: running Python {got}, "
78
+ "but contracts must be emitted on Python 3.12 (the CI/monolith "
79
+ "pin). drf-spectacular renders component descriptions (Optional[X] "
80
+ "vs X | None) differently across Python minor versions, so emitting "
81
+ "on any other minor produces false diffs against the committed "
82
+ "docs/*.json. Re-run under a 3.12 interpreter."
83
+ )
84
+
85
+
86
+ def main(argv: list[str] | None = None) -> int:
87
+ _require_python_312()
88
+
89
+ parser = argparse.ArgumentParser(
90
+ prog="stapel-courses-contract",
91
+ description="Emit this module's contract triad (schema.json + flows.json "
92
+ "+ errors.json) into --out, canonical /courses/api/v1/ prefix.",
93
+ )
94
+ parser.add_argument(
95
+ "--out",
96
+ default="docs",
97
+ help="Output directory for the triad (default: docs).",
98
+ )
99
+ args = parser.parse_args(argv)
100
+
101
+ _configure()
102
+
103
+ from stapel_tools.codegen import emit_errors, emit_flows, emit_schema
104
+
105
+ out = Path(args.out)
106
+ out.mkdir(parents=True, exist_ok=True)
107
+ paths = emit_schema(out / "schema.json")
108
+ # Profile 2 goes to its own file: docs/schema.json is what stapel-react's
109
+ # generators read, and stays profile 1.
110
+ emit_schema(out / "schema.v2.json", contract_profile=2)
111
+ flows = emit_flows(out / "flows.json")
112
+ errors = emit_errors(out / "errors.json")
113
+
114
+ print(
115
+ f"stapel-courses contract: {paths} paths, {flows} flows, {errors} error keys "
116
+ f"→ {out}/",
117
+ file=sys.stderr,
118
+ )
119
+ return 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ raise SystemExit(main())
@@ -0,0 +1,119 @@
1
+ """Single-module Django settings shared by the test suite and contract emission.
2
+
3
+ One copy, so the harness that emits ``docs/schema.json`` and the tests that
4
+ prove it can never drift in INSTALLED_APPS or comm config. The production
5
+ ``REST_FRAMEWORK`` (exception handler, schema class) is used by both: the
6
+ error envelope the tests assert is the one a host serves.
7
+ """
8
+ from __future__ import annotations
9
+
10
+
11
+ def settings_kwargs(
12
+ *,
13
+ root_urlconf: str = "stapel_courses.tests.urls",
14
+ contract: bool = False,
15
+ ) -> dict:
16
+ rest_framework = {
17
+ "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],
18
+ "DEFAULT_SCHEMA_CLASS": "stapel_core.django.openapi.schemas.PermissionAwareAutoSchema",
19
+ "EXCEPTION_HANDLER": "stapel_core.django.api.errors.stapel_exception_handler",
20
+ }
21
+ if contract:
22
+ rest_framework.update({
23
+ "DEFAULT_AUTHENTICATION_CLASSES": [
24
+ "stapel_core.django.jwt.authentication.JWTCookieAuthentication",
25
+ ],
26
+ "DEFAULT_PERMISSION_CLASSES": [
27
+ "stapel_core.django.api.permissions.IsServiceRequest",
28
+ "stapel_core.django.api.permissions.IsSuperUser",
29
+ ],
30
+ "DEFAULT_RENDERER_CLASSES": [
31
+ "rest_framework.renderers.JSONRenderer",
32
+ "rest_framework.renderers.BrowsableAPIRenderer",
33
+ ],
34
+ })
35
+ return dict(
36
+ SECRET_KEY="test-secret-key-not-for-production",
37
+ INSTALLED_APPS=[
38
+ "django.contrib.contenttypes",
39
+ "django.contrib.auth",
40
+ "django.contrib.sessions",
41
+ "django.contrib.admin",
42
+ "django.contrib.messages",
43
+ "stapel_core.django.apps.CommonDjangoConfig",
44
+ "stapel_core.django.users",
45
+ "rest_framework",
46
+ "drf_spectacular",
47
+ "stapel_courses",
48
+ ],
49
+ AUTH_USER_MODEL="users.User",
50
+ DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
51
+ DEFAULT_AUTO_FIELD="django.db.models.BigAutoField",
52
+ USE_TZ=True,
53
+ ROOT_URLCONF=root_urlconf,
54
+ CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
55
+ STAPEL_BUS_BACKEND="stapel_core.bus.backends.memory.MemoryBus",
56
+ STAPEL_COMM={
57
+ "OUTBOX_ENABLED": False,
58
+ "ACTION_TRANSPORT": "inprocess",
59
+ "VALIDATE_SCHEMAS": True,
60
+ },
61
+ TEMPLATES=[{
62
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
63
+ "APP_DIRS": True,
64
+ "OPTIONS": {"context_processors": [
65
+ "django.template.context_processors.request",
66
+ "django.contrib.auth.context_processors.auth",
67
+ "django.contrib.messages.context_processors.messages",
68
+ ]},
69
+ }],
70
+ MIDDLEWARE=[
71
+ "django.contrib.sessions.middleware.SessionMiddleware",
72
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
73
+ "django.contrib.messages.middleware.MessageMiddleware",
74
+ ],
75
+ MIGRATION_MODULES={"users": None},
76
+ REST_FRAMEWORK=rest_framework,
77
+ )
78
+
79
+
80
+ #: Forced on drf-spectacular's singleton so a single-module instance derives
81
+ #: the same operation ids as a multi-module aggregate.
82
+ CODEGEN_SCHEMA_PATH_PREFIX = "/"
83
+
84
+
85
+ def enum_name_overrides() -> dict:
86
+ """Stable enum component names (stapel-schema-lint SCH004). Called after setup."""
87
+ from stapel_courses.access import LOCK_REASONS
88
+ from stapel_courses.models import (
89
+ AttemptStatus,
90
+ CourseLevel,
91
+ CourseStatus,
92
+ DripMode,
93
+ EnrollmentSource,
94
+ EnrollmentStatus,
95
+ ProgressStatus,
96
+ QuestionKind,
97
+ RevealMode,
98
+ TextMatch,
99
+ )
100
+
101
+ return {
102
+ "CourseStatusEnum": CourseStatus,
103
+ "CourseLevelEnum": CourseLevel,
104
+ "DripModeEnum": DripMode,
105
+ "EnrollmentStatusEnum": EnrollmentStatus,
106
+ "EnrollmentSourceEnum": EnrollmentSource,
107
+ "ProgressStatusEnum": ProgressStatus,
108
+ "QuestionKindEnum": QuestionKind,
109
+ "RevealModeEnum": RevealMode,
110
+ "TextMatchEnum": TextMatch,
111
+ "AttemptStatusEnum": AttemptStatus,
112
+ "LockReasonEnum": [(r, r) for r in LOCK_REASONS],
113
+ "EnrollmentTransitionTargetEnum": [(s, s) for s in ("active", "expired", "cancelled")],
114
+ "TextBlockTypeEnum": [("text", "text")],
115
+ "VideoBlockTypeEnum": [("video", "video")],
116
+ "AttachmentBlockTypeEnum": [("attachment", "attachment")],
117
+ "EmbedBlockTypeEnum": [("embed", "embed")],
118
+ "TextFormatEnum": [("markdown", "markdown"), ("plain", "plain")],
119
+ }
@@ -0,0 +1,152 @@
1
+ """Access gate strategies and their registry (spec §4).
2
+
3
+ ``Course.access`` names a strategy. A strategy answers two questions:
4
+
5
+ - :meth:`AccessStrategy.self_enroll_source` — may this learner enroll
6
+ themself, and with which source? Raise :class:`~.services.CoursesError`
7
+ to refuse.
8
+ - :meth:`AccessStrategy.content_access` — does this learner (``user_id`` or
9
+ ``None`` for an anonymous request, and their enrollment or ``None``) see
10
+ the course's content? Answer a :class:`Decision` whose ``reason`` is a
11
+ lock reason from :data:`LOCK_REASONS`.
12
+
13
+ Staff and the course's author always pass (the gate in
14
+ ``services/gate.py`` asks before any strategy). A ``free_preview`` lesson
15
+ never reaches a strategy.
16
+
17
+ ``STAPEL_COURSES["ACCESS_STRATEGIES"]`` merges ``{name: "dotted.path" |
18
+ None}`` over the built-ins; a dotted path under a built-in name replaces it.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Optional
24
+
25
+ from django.utils.module_loading import import_string
26
+
27
+ from .models import EnrollmentSource
28
+
29
+ SIGN_IN_REQUIRED = "sign_in_required"
30
+ ENROLLMENT_REQUIRED = "enrollment_required"
31
+ PURCHASE_REQUIRED = "purchase_required"
32
+ ENTITLEMENT_REQUIRED = "entitlement_required"
33
+ ENROLLMENT_INACTIVE = "enrollment_inactive"
34
+ DRIP = "drip"
35
+ SEQUENTIAL = "sequential"
36
+
37
+ LOCK_REASONS = (
38
+ SIGN_IN_REQUIRED,
39
+ ENROLLMENT_REQUIRED,
40
+ PURCHASE_REQUIRED,
41
+ ENTITLEMENT_REQUIRED,
42
+ ENROLLMENT_INACTIVE,
43
+ DRIP,
44
+ SEQUENTIAL,
45
+ )
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Decision:
50
+ allowed: bool
51
+ reason: Optional[str] = None
52
+
53
+
54
+ OPEN = Decision(True)
55
+
56
+
57
+ class AccessStrategy:
58
+ """Base strategy: content needs an enrollment that grants access."""
59
+
60
+ #: The reason a learner without an enrollment is shown.
61
+ missing_reason = ENROLLMENT_REQUIRED
62
+
63
+ def self_enroll_source(self, course, user_id: str) -> str:
64
+ return EnrollmentSource.FREE
65
+
66
+ def content_access(self, course, user_id: Optional[str], enrollment) -> Decision:
67
+ if user_id is None:
68
+ return Decision(False, SIGN_IN_REQUIRED)
69
+ if enrollment is None:
70
+ return Decision(False, self.missing_reason)
71
+ if not enrollment.grants_access:
72
+ return Decision(False, ENROLLMENT_INACTIVE)
73
+ return OPEN
74
+
75
+
76
+ class FreeAccess(AccessStrategy):
77
+ """Content is open to everyone; enrolling only tracks progress."""
78
+
79
+ def content_access(self, course, user_id, enrollment) -> Decision:
80
+ return OPEN
81
+
82
+
83
+ class EnrolledAccess(AccessStrategy):
84
+ """Content needs an enrollment; anyone may enroll for free."""
85
+
86
+
87
+ class PurchasedAccess(AccessStrategy):
88
+ """Content needs an enrollment from an order (or a staff grant)."""
89
+
90
+ missing_reason = PURCHASE_REQUIRED
91
+
92
+ def self_enroll_source(self, course, user_id: str) -> str:
93
+ from .errors import ERR_403_PURCHASE_REQUIRED
94
+ from .services import CoursesError
95
+
96
+ raise CoursesError(403, ERR_403_PURCHASE_REQUIRED)
97
+
98
+
99
+ class EntitlementAccess(AccessStrategy):
100
+ """Content needs an enrollment and a plan entitlement (billing Function)."""
101
+
102
+ missing_reason = ENTITLEMENT_REQUIRED
103
+
104
+ def self_enroll_source(self, course, user_id: str) -> str:
105
+ from .errors import ERR_403_ENTITLEMENT_REQUIRED
106
+ from .services import CoursesError
107
+ from .services.entitlements import entitled
108
+
109
+ if not entitled(user_id, course):
110
+ raise CoursesError(403, ERR_403_ENTITLEMENT_REQUIRED)
111
+ return EnrollmentSource.ENTITLEMENT
112
+
113
+ def content_access(self, course, user_id, enrollment) -> Decision:
114
+ decision = super().content_access(course, user_id, enrollment)
115
+ if not decision.allowed or enrollment.source != EnrollmentSource.ENTITLEMENT:
116
+ return decision
117
+ from .services.entitlements import entitled
118
+
119
+ return OPEN if entitled(user_id, course) else Decision(False, ENTITLEMENT_REQUIRED)
120
+
121
+
122
+ BUILTIN_STRATEGIES: dict[str, str] = {
123
+ "free": "stapel_courses.access.FreeAccess",
124
+ "enrolled": "stapel_courses.access.EnrolledAccess",
125
+ "purchased": "stapel_courses.access.PurchasedAccess",
126
+ "entitlement": "stapel_courses.access.EntitlementAccess",
127
+ }
128
+
129
+
130
+ def strategy_paths() -> dict[str, str]:
131
+ """Effective registry: built-ins <- settings, live entries only."""
132
+ from .conf import courses_settings
133
+
134
+ merged: dict[str, Optional[str]] = dict(BUILTIN_STRATEGIES)
135
+ configured = courses_settings.ACCESS_STRATEGIES or {}
136
+ if isinstance(configured, dict):
137
+ merged.update(configured)
138
+ return {name: path for name, path in merged.items() if path}
139
+
140
+
141
+ def strategy_names() -> list[str]:
142
+ return sorted(strategy_paths())
143
+
144
+
145
+ def get_strategy(name: str) -> AccessStrategy:
146
+ """The strategy *name* resolves to; an unknown name gates like ``enrolled``.
147
+
148
+ A course whose strategy was removed from the registry stays closed to
149
+ non-enrolled learners instead of opening up (fail closed).
150
+ """
151
+ path = strategy_paths().get(name) or BUILTIN_STRATEGIES["enrolled"]
152
+ return import_string(path)()
@@ -0,0 +1,78 @@
1
+ """Action subscriptions of stapel-courses. Handlers are idempotent
2
+ (delivery is at-least-once).
3
+
4
+ - ``orders.order.placed`` / ``.paid`` / ``.status_changed`` /
5
+ ``.refunded`` — course purchases (``services/purchases.py``); a fact for
6
+ another purchasable type or an unknown course is someone else's event and
7
+ is ignored.
8
+ - ``user.merged`` (stapel-auth) — a guest's learning follows it into the
9
+ account on sign-in.
10
+ - ``user.deleted`` / ``gdpr.erasure.requested`` are answered by
11
+ ``register_gdpr_owner`` (``apps.py``), not here.
12
+ """
13
+ import json
14
+ import logging
15
+ from pathlib import Path
16
+
17
+ from stapel_core.comm import on_action
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _CONSUMES = Path(__file__).resolve().parent / "schemas" / "consumes"
22
+
23
+
24
+ def _schema(name: str) -> dict:
25
+ return json.loads((_CONSUMES / f"{name}.json").read_text(encoding="utf-8"))
26
+
27
+
28
+ @on_action("orders.order.placed", schema=_schema("orders.order.placed"))
29
+ def handle_order_placed(event):
30
+ from .services.purchases import order_placed
31
+
32
+ touched = order_placed(event.payload or {})
33
+ if touched:
34
+ logger.info("orders.order.placed %s: %d course purchase(s)", event.event_id, touched)
35
+
36
+
37
+ @on_action("orders.order.paid", schema=_schema("orders.order.paid"))
38
+ def handle_order_paid(event):
39
+ from .services.purchases import order_paid
40
+
41
+ order_paid(str((event.payload or {}).get("order_id") or ""))
42
+
43
+
44
+ @on_action("orders.order.status_changed", schema=_schema("orders.order.status_changed"))
45
+ def handle_order_status_changed(event):
46
+ from .services.purchases import order_cancelled, order_confirmed
47
+
48
+ payload = event.payload or {}
49
+ order_id = str(payload.get("order_id") or "")
50
+ if payload.get("to") == "cancelled":
51
+ order_cancelled(order_id, reason="order_cancelled")
52
+ elif payload.get("to") == "confirmed":
53
+ order_confirmed(order_id)
54
+
55
+
56
+ @on_action("orders.order.refunded", schema=_schema("orders.order.refunded"))
57
+ def handle_order_refunded(event):
58
+ from .services.purchases import order_cancelled
59
+
60
+ order_cancelled(str((event.payload or {}).get("order_id") or ""), reason="order_refunded")
61
+
62
+
63
+ @on_action("user.merged", schema=_schema("user.merged"))
64
+ def handle_user_merged(event):
65
+ """Re-parent the guest's enrollments, progress, attempts and certificates."""
66
+ from .services.enrollments import merge_users
67
+
68
+ payload = event.payload or {}
69
+ from_user_id = str(payload.get("from_user_id") or "")
70
+ into_user_id = str(payload.get("into_user_id") or "")
71
+ if not from_user_id or not into_user_id:
72
+ logger.error("user.merged without from/into user id: %s", event.event_id)
73
+ return
74
+ if from_user_id == into_user_id:
75
+ return
76
+ moved = merge_users(from_user_id, into_user_id)
77
+ if any(moved.values()):
78
+ logger.info("user.merged %s -> %s: %s", from_user_id, into_user_id, moved)