This commit is contained in:
2025-05-27 12:15:22 -03:00
parent 270e408c1d
commit 42e62ec183
30 changed files with 287 additions and 178 deletions

View File

@@ -5,8 +5,9 @@ from uuid import uuid4
from layercake.dateutils import now, ttl
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, TransactItems
from layercake.strutils import md5_hash
from conf import ORDER_TABLE
from config import ORDER_TABLE
from models import Course, Enrollment
@@ -23,6 +24,10 @@ class Author(TypedDict):
class Vacancy(TypedDict): ...
class DeduplicationWindow(TypedDict):
offset_days: int
class LifecycleEvents(str, Enum):
"""Lifecycle events related to scheduling actions."""
@@ -49,20 +54,23 @@ def enroll(
enrollment: Enrollment,
*,
tenant: Tenant,
vacancy: Vacancy | None = None,
deduplication_window: DeduplicationWindow | None = None,
persistence_layer: DynamoDBPersistenceLayer,
) -> bool:
"""Enrolls a user into a course and schedules lifecycle events."""
now_ = now()
user = enrollment.user
course = enrollment.course
tenant_id = tenant['id']
transact = TransactItems(persistence_layer.table_name)
transact.put(
item={
'sk': '0',
'create_date': now_,
'metadata__tenant_id': tenant['id'],
'metadata__related_ids': {tenant['id'], user.id},
'metadata__tenant_id': tenant_id,
'metadata__related_ids': {tenant_id, user.id},
**enrollment.model_dump(),
},
)
@@ -70,7 +78,7 @@ def enroll(
item={
'id': enrollment.id,
'sk': 'metadata#tenant',
'tenant_id': f'ORG#{tenant["id"]}',
'tenant_id': f'ORG#{tenant_id}',
'name': tenant['name'],
'create_date': now_,
},
@@ -97,7 +105,6 @@ def enroll(
'ttl': ttl(start_dt=now_ + timedelta(days=course.access_period - 30)),
},
)
transact.put(
item={
'id': enrollment.id,
@@ -110,6 +117,43 @@ def enroll(
},
)
# Prevents the user from enrolling in the same course again until
# the deduplication window expires or is removed
if deduplication_window:
lock_hash = md5_hash('%s%s' % (user.id, course.id))
offset_days = deduplication_window['offset_days']
ttl_expiration = ttl(
start_dt=now_ + timedelta(days=course.access_period - offset_days)
)
transact.put(
item={
'id': 'lock',
'sk': lock_hash,
'enrollment_id': enrollment.id,
'create_date': now_,
'ttl': ttl_expiration,
},
cond_expr='attribute_not_exists(sk)',
)
transact.put(
item={
'id': enrollment.id,
'sk': 'metadata#lock',
'hash': lock_hash,
'create_date': now_,
'ttl': ttl_expiration,
},
)
# Deduplication window can be recalculated if needed
transact.put(
item={
'id': enrollment.id,
'sk': 'metadata#deduplication_window',
'offset_days': offset_days,
'create_date': now_,
},
)
return persistence_layer.transact_write_items(transact)