add report submission

This commit is contained in:
2025-12-11 20:46:34 -03:00
parent 3fb8488074
commit 1e1a0ae24c
10 changed files with 281 additions and 54 deletions

View File

@@ -51,6 +51,7 @@ app.include_router(orgs.add, prefix='/orgs')
app.include_router(orgs.admins, prefix='/orgs')
app.include_router(orgs.custom_pricing, prefix='/orgs')
app.include_router(orgs.scheduled, prefix='/orgs')
app.include_router(orgs.submission, prefix='/orgs')
app.include_router(orgs.users, prefix='/orgs')
app.include_router(orgs.batch_jobs, prefix='/orgs')

View File

@@ -18,17 +18,10 @@ router = Router()
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
class CancelPolicyConflictError(BadRequestError):
def __init__(self, *_):
super().__init__('Cancellation policy not found')
class CancelPolicyConflictError(BadRequestError): ...
class SlotConflictError(BadRequestError):
def __init__(self, *_):
super().__init__('Slot not found')
@router.post('/<enrollment_id>/cancel')
@router.patch('/<enrollment_id>/cancel')
def cancel(
enrollment_id: str,
lock_hash: Annotated[str | None, Body(embed=True)] = None,
@@ -44,12 +37,11 @@ def cancel(
canceled_at = :now, \
updated_at = :now',
expr_attr_names={
':status': 'status',
'#status': 'status',
},
expr_attr_values={
':pending': 'PENDING',
':canceled': 'CANCELED',
':true': True,
':now': now_,
},
)
@@ -89,9 +81,7 @@ def cancel(
key=KeyPair(
pk=enrollment_id,
sk='METADATA#PARENT_SLOT',
),
cond_expr='attribute_exists(sk)',
exc_cls=SlotConflictError,
)
)
if lock_hash:

View File

@@ -8,9 +8,10 @@ import pytz
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler.api_gateway import Router
from aws_lambda_powertools.event_handler.exceptions import (
NotFoundError,
ServiceError,
)
from aws_lambda_powertools.event_handler.openapi.params import Body
from aws_lambda_powertools.shared.functions import extract_event_from_common_models
from layercake.batch import BatchProcessor
from layercake.dateutils import now, ttl
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
@@ -19,9 +20,8 @@ from layercake.strutils import md5_hash
from pydantic import UUID4, BaseModel, EmailStr, Field, FutureDate
from typing_extensions import TypedDict
from api_gateway import JSONResponse
from boto3clients import dynamodb_client
from config import DEDUP_WINDOW_OFFSET_DAYS, ENROLLMENT_TABLE, TZ
from config import DEDUP_WINDOW_OFFSET_DAYS, ENROLLMENT_TABLE, TZ, USER_TABLE
from exceptions import ConflictError
from middlewares.authentication_middleware import User as Authenticated
@@ -31,7 +31,9 @@ dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
processor = BatchProcessor()
class SubscriptionNotFoundError(NotFoundError): ...
class SubscriptionRequiredError(ServiceError):
def __init__(self, msg: str | dict):
super().__init__(HTTPStatus.NOT_ACCEPTABLE, msg)
class DeduplicationConflictError(ConflictError): ...
@@ -74,30 +76,32 @@ class Org(BaseModel):
@router.post('/')
def enroll(
org_id: Annotated[UUID4 | str, Body(embed=True)],
org_id: Annotated[str | UUID4, Body(embed=True)],
enrollments: Annotated[tuple[Enrollment, ...], Body(embed=True)],
):
now_ = now()
org = dyn.collection.get_items(
KeyPair(
pk=str(org_id),
sk='0',
table_name=USER_TABLE,
)
+ KeyPair(
pk=str(org_id),
sk='METADATA#SUBSCRIPTION_TERMS',
rename_key='terms',
table_name=USER_TABLE,
)
+ KeyPair(
pk='SUBSCRIPTION',
sk=f'ORG#{org_id}',
rename_key='subscribed',
table_name=USER_TABLE,
)
)
if 'subscribed' not in org:
return JSONResponse(
status_code=HTTPStatus.NOT_ACCEPTABLE,
)
raise SubscriptionRequiredError('Organization not subscribed')
ctx = {
'org': Org.model_validate(org),
@@ -105,20 +109,38 @@ def enroll(
'terms': SubscriptionTerms.model_validate(org['terms']),
}
now = [e for e in enrollments if not e.scheduled_for]
immediate = [e for e in enrollments if not e.scheduled_for]
later = [e for e in enrollments if e.scheduled_for]
with processor(now, enroll_now, ctx) as batch:
with processor(immediate, enroll_now, ctx) as batch:
now_out = batch.process()
with processor(later, enroll_later, ctx) as batch:
later_out = batch.process()
return {
'enrolled': now_out,
'scheduled': later_out,
def fmt(r):
return {
'status': r.status.value,
'input_record': extract_event_from_common_models(r.input_record),
'output': extract_event_from_common_models(r.output),
'cause': extract_event_from_common_models(r.cause),
}
item = {
'id': f'SUBMISSION#ORG#{org_id}',
'sk': now_,
'enrolled': list(map(fmt, now_out)) if now_out else None,
'scheduled': list(map(fmt, later_out)) if later_out else None,
'ttl': ttl(start_dt=now_, days=30 * 6),
}
try:
dyn.put_item(item=item)
except Exception as exc:
logger.exception(exc)
finally:
return item
Context = TypedDict(
'Context',
@@ -155,6 +177,9 @@ def enroll_now(enrollment: Enrollment, context: Context):
item={
'id': enrollment.id,
'sk': '0',
'score': None,
'progress': 0,
'status': 'PENDING',
'user': user.model_dump(),
'course': course.model_dump(),
'access_expires_at': access_expires_at,
@@ -230,7 +255,8 @@ def enroll_now(enrollment: Enrollment, context: Context):
'created_at': now_,
},
)
return True
return enrollment
def enroll_later(enrollment: Enrollment, context: Context):

View File

@@ -2,7 +2,16 @@ from .add import router as add
from .admins import router as admins
from .custom_pricing import router as custom_pricing
from .enrollments.scheduled import router as scheduled
from .enrollments.submission import router as submission
from .users.add import router as users
from .users.batch_jobs import router as batch_jobs
__all__ = ['add', 'admins', 'custom_pricing', 'scheduled', 'users', 'batch_jobs']
__all__ = [
'add',
'admins',
'custom_pricing',
'scheduled',
'submission',
'users',
'batch_jobs',
]

View File

@@ -0,0 +1,22 @@
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler.api_gateway import Router
from aws_lambda_powertools.event_handler.exceptions import NotFoundError
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE
logger = Logger(__name__)
router = Router()
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
@router.get('/<org_id>/enrollments/<submission_id>/submitted')
def submitted(org_id: str, submission_id: str):
return dyn.collection.get_item(
KeyPair(
pk=f'SUBMISSION#ORG#{org_id}',
sk=submission_id,
),
exc_cls=NotFoundError,
)