add cert_expires_at
This commit is contained in:
@@ -86,7 +86,7 @@ class Course:
|
||||
|
||||
def _get_courses(ids: set) -> tuple[Course, ...]:
|
||||
pairs = tuple(KeyPair(idx, '0') for idx in ids)
|
||||
result = course_layer.collection.get_items(
|
||||
r = course_layer.collection.get_items(
|
||||
KeyChain(pairs),
|
||||
flatten_top=False,
|
||||
)
|
||||
@@ -96,7 +96,7 @@ def _get_courses(ids: set) -> tuple[Course, ...]:
|
||||
name=obj['name'],
|
||||
access_period=obj['access_period'],
|
||||
)
|
||||
for idx, obj in result.items()
|
||||
for idx, obj in r.items()
|
||||
)
|
||||
|
||||
return courses
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import NotRequired, TypedDict
|
||||
|
||||
import requests
|
||||
from aws_lambda_powertools import Logger
|
||||
@@ -21,8 +22,7 @@ from config import (
|
||||
)
|
||||
|
||||
logger = Logger(__name__)
|
||||
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
|
||||
course_layer = DynamoDBPersistenceLayer(COURSE_TABLE, dynamodb_client)
|
||||
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
|
||||
|
||||
|
||||
@event_source(data_class=EventBridgeEvent)
|
||||
@@ -32,10 +32,11 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
now_ = now()
|
||||
enrollment_id = new_image['id']
|
||||
course_id = new_image['course']['id']
|
||||
cert = course_layer.collection.get_item(
|
||||
cert = dyn.collection.get_item(
|
||||
KeyPair(
|
||||
pk=course_id,
|
||||
sk=SortKey('0', path_spec='cert', rename_key='cert'),
|
||||
table_name=COURSE_TABLE,
|
||||
),
|
||||
raise_on_error=False,
|
||||
default=None,
|
||||
@@ -49,76 +50,36 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
started_at: datetime = fromisoformat(new_image['started_at']) # type: ignore
|
||||
completed_at: datetime = fromisoformat(new_image['completed_at']) # type: ignore
|
||||
# Certificate may have no expiration
|
||||
cert_expires_at = (
|
||||
expires_at = (
|
||||
completed_at + timedelta(days=int(cert['exp_interval']))
|
||||
if cert.get('exp_interval', 0) > 0
|
||||
else None
|
||||
)
|
||||
s3_uri = _gen_cert(
|
||||
enrollment_id,
|
||||
cert=cert,
|
||||
user=new_image['user'],
|
||||
score=new_image['score'],
|
||||
started_at=started_at,
|
||||
completed_at=completed_at,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
|
||||
try:
|
||||
if 's3_uri' not in cert:
|
||||
raise ValueError('Template URI is missing')
|
||||
update_expr = 'SET cert = :cert, updated_at = :now'
|
||||
expr_attr_values = {
|
||||
':now': now_,
|
||||
':cert': {'issued_at': now_} | ({'s3_uri': s3_uri} if s3_uri else {}),
|
||||
}
|
||||
|
||||
# Send template URI and data to Paperforge API to generate a PDF
|
||||
r = requests.post(
|
||||
PAPERFORGE_API,
|
||||
data=json.dumps(
|
||||
{
|
||||
'template_uri': cert['s3_uri'],
|
||||
'sign_uri': ESIGN_URI,
|
||||
'args': {
|
||||
'name': new_image['user']['name'],
|
||||
'cpf': _cpffmt(new_image['user']['cpf']),
|
||||
'score': new_image['score'],
|
||||
'started_at': started_at.strftime('%d/%m/%Y'),
|
||||
'completed_at': completed_at.strftime('%d/%m/%Y'),
|
||||
'today': _datefmt(now_),
|
||||
'year': now_.strftime('%Y'),
|
||||
}
|
||||
| (
|
||||
{'expires_at': cert_expires_at.strftime('%d/%m/%Y')}
|
||||
if cert_expires_at
|
||||
else {}
|
||||
),
|
||||
},
|
||||
),
|
||||
timeout=5,
|
||||
)
|
||||
r.raise_for_status()
|
||||
if expires_at:
|
||||
update_expr = 'SET cert = :cert, cert_expires_at = :cert_expires_at, \
|
||||
updated_at = :now'
|
||||
expr_attr_values[':cert_expires_at'] = expires_at
|
||||
|
||||
object_key = f'certs/{enrollment_id}.pdf'
|
||||
s3_uri = f's3://{BUCKET_NAME}/{object_key}'
|
||||
|
||||
s3_client.put_object(
|
||||
Bucket=BUCKET_NAME,
|
||||
Key=object_key,
|
||||
Body=r.content,
|
||||
ContentType='application/pdf',
|
||||
)
|
||||
|
||||
logger.debug(f'PDF uploaded successfully to {s3_uri}')
|
||||
except ValueError as exc:
|
||||
# PDF generation fails if template URI is missing
|
||||
s3_uri = None
|
||||
logger.exception(exc)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
logger.exception(exc)
|
||||
raise
|
||||
|
||||
return enrollment_layer.update_item(
|
||||
key=KeyPair(
|
||||
pk=enrollment_id,
|
||||
sk='0',
|
||||
),
|
||||
update_expr='SET cert = :cert, updated_at = :now',
|
||||
expr_attr_values={
|
||||
':now': now_,
|
||||
':cert': {
|
||||
'issued_at': now_,
|
||||
}
|
||||
| ({'expires_at': cert_expires_at} if cert_expires_at else {})
|
||||
| ({'s3_uri': s3_uri} if s3_uri else {}),
|
||||
},
|
||||
return dyn.update_item(
|
||||
key=KeyPair(pk=enrollment_id, sk='0'),
|
||||
update_expr=update_expr,
|
||||
expr_attr_values=expr_attr_values,
|
||||
cond_expr='attribute_exists(sk)',
|
||||
)
|
||||
|
||||
@@ -143,3 +104,67 @@ def _datefmt(dt: datetime) -> str:
|
||||
'Dezembro',
|
||||
]
|
||||
return f'{dt.day:02d} de {months[dt.month - 1]} de {dt.year}'
|
||||
|
||||
|
||||
User = TypedDict('User', {'name': str, 'cpf': str})
|
||||
Cert = TypedDict('Cert', {'s3_uri': NotRequired[str]})
|
||||
|
||||
|
||||
def _gen_cert(
|
||||
id: str,
|
||||
*,
|
||||
score: int | float,
|
||||
cert: Cert,
|
||||
user: User,
|
||||
started_at: datetime,
|
||||
completed_at: datetime,
|
||||
expires_at: datetime | None = None,
|
||||
) -> str | None:
|
||||
now_ = now()
|
||||
|
||||
if 's3_uri' not in cert:
|
||||
logger.debug('Template URI is missing')
|
||||
return None
|
||||
|
||||
try:
|
||||
# Send template URI and data to Paperforge API to generate a PDF
|
||||
r = requests.post(
|
||||
PAPERFORGE_API,
|
||||
data=json.dumps(
|
||||
{
|
||||
'template_uri': cert['s3_uri'],
|
||||
'sign_uri': ESIGN_URI,
|
||||
'args': {
|
||||
'name': user['name'],
|
||||
'cpf': _cpffmt(user['cpf']),
|
||||
'score': score,
|
||||
'started_at': started_at.strftime('%d/%m/%Y'),
|
||||
'completed_at': completed_at.strftime('%d/%m/%Y'),
|
||||
'today': _datefmt(now_),
|
||||
'year': now_.strftime('%Y'),
|
||||
'expires_at': expires_at.strftime('%d/%m/%Y')
|
||||
if expires_at
|
||||
else None,
|
||||
},
|
||||
},
|
||||
),
|
||||
timeout=5,
|
||||
)
|
||||
r.raise_for_status()
|
||||
|
||||
object_key = f'certs/{id}.pdf'
|
||||
s3_uri = f's3://{BUCKET_NAME}/{object_key}'
|
||||
|
||||
s3_client.put_object(
|
||||
Bucket=BUCKET_NAME,
|
||||
Key=object_key,
|
||||
Body=r.content,
|
||||
ContentType='application/pdf',
|
||||
)
|
||||
|
||||
logger.debug(f'PDF uploaded successfully to {s3_uri}')
|
||||
except requests.exceptions.RequestException as exc:
|
||||
logger.exception(exc)
|
||||
raise
|
||||
|
||||
return s3_uri
|
||||
|
||||
@@ -29,10 +29,7 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
path_spec='offset_days',
|
||||
rename_key='dedup_window_offset_days',
|
||||
)
|
||||
+ SortKey('ORG', rename_key='org')
|
||||
+ SortKey('konviva'),
|
||||
# Post-migration: uncomment the following lines
|
||||
# + SortKey('KONVIVA', rename_key='konviva')
|
||||
+ SortKey('ORG', rename_key='org'),
|
||||
flatten_top=False,
|
||||
)
|
||||
user = User.model_validate(new_image['user'])
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import timedelta
|
||||
|
||||
import pytz
|
||||
from aws_lambda_powertools import Logger
|
||||
@@ -8,7 +8,6 @@ from aws_lambda_powertools.utilities.data_classes import (
|
||||
event_source,
|
||||
)
|
||||
from aws_lambda_powertools.utilities.typing import LambdaContext
|
||||
from glom import glom
|
||||
from layercake.dateutils import fromisoformat, now, ttl
|
||||
from layercake.dynamodb import DynamoDBPersistenceLayer
|
||||
from layercake.funcs import pick
|
||||
@@ -25,14 +24,11 @@ tz = os.getenv('TZ', 'UTC')
|
||||
@logger.inject_lambda_context
|
||||
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool | None:
|
||||
new_image = event.detail['new_image']
|
||||
expires_at = glom(new_image, 'cert.expires_at', default=None)
|
||||
|
||||
if not expires_at:
|
||||
return None
|
||||
|
||||
enrollment_id = new_image['id']
|
||||
org_id = new_image['org_id']
|
||||
expires_at: datetime = fromisoformat(expires_at).replace(tzinfo=pytz.timezone(tz)) # type: ignore
|
||||
expires_at = fromisoformat(new_image['cert_expires_at']).replace( # type: ignore
|
||||
tzinfo=pytz.timezone(tz)
|
||||
)
|
||||
# The reporting month is the month before the certificate expires
|
||||
month_start = (expires_at.replace(day=1) - timedelta(days=1)).replace(day=1)
|
||||
now_ = now()
|
||||
@@ -59,11 +55,10 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool | No
|
||||
item={
|
||||
'id': pk,
|
||||
'sk': f'{sk}#ENROLLMENT#{enrollment_id}',
|
||||
'enrollment_id': new_image['id'],
|
||||
'user': pick(('id', 'name'), new_image['user']),
|
||||
'course': pick(('id', 'name'), new_image['course']),
|
||||
'enrolled_at': new_image['created_at'],
|
||||
'expires_at': expires_at, # type: ignore
|
||||
'expires_at': expires_at,
|
||||
'completed_at': new_image['completed_at'],
|
||||
'created_at': now_,
|
||||
},
|
||||
|
||||
@@ -52,14 +52,14 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
# Key pattern `CERT#REPORTING#ORG#{org_id}`
|
||||
*_, org_id = old_image['id'].split('#')
|
||||
event_name = old_image['sk']
|
||||
target_month = datetime.strptime(old_image['target_month'], '%Y-%m').date()
|
||||
month = _monthfmt(target_month)
|
||||
target_month = old_image['target_month']
|
||||
pretty_month = _monthfmt(datetime.strptime(target_month, '%Y-%m').date())
|
||||
now_ = now()
|
||||
|
||||
result = enrollment_layer.collection.query(
|
||||
r = enrollment_layer.collection.query(
|
||||
KeyPair(
|
||||
pk=old_image['id'],
|
||||
sk='MONTH#{}#ENROLLMENT'.format(target_month.strftime('%Y-%m')),
|
||||
sk=f'MONTH#{target_month}#ENROLLMENT',
|
||||
),
|
||||
limit=150,
|
||||
)
|
||||
@@ -68,8 +68,8 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
{
|
||||
'template_uri': CERT_REPORTING_URI,
|
||||
'args': {
|
||||
'month': month,
|
||||
'items': result['items'],
|
||||
'month': pretty_month,
|
||||
'items': r['items'],
|
||||
},
|
||||
},
|
||||
cls=Encoder,
|
||||
@@ -83,14 +83,14 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
to=_get_admin_emails(org_id),
|
||||
reply_to=REPLY_TO,
|
||||
bcc=BCC,
|
||||
subject=SUBJECT.format(month=month),
|
||||
subject=SUBJECT.format(month=pretty_month),
|
||||
)
|
||||
emailmsg.add_alternative(MESSAGE.format(month=month))
|
||||
emailmsg.add_alternative(MESSAGE.format(month=pretty_month))
|
||||
attachment = MIMEApplication(r.content)
|
||||
attachment.add_header(
|
||||
'Content-Disposition',
|
||||
'attachment',
|
||||
filename='{}.pdf'.format(target_month.strftime('%Y-%m')),
|
||||
filename=f'{target_month}.pdf',
|
||||
)
|
||||
emailmsg.attach(attachment)
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import timedelta
|
||||
|
||||
from aws_lambda_powertools import Logger
|
||||
@@ -17,8 +15,6 @@ from config import (
|
||||
ENROLLMENT_TABLE,
|
||||
)
|
||||
|
||||
sqlite3.register_converter('json', json.loads)
|
||||
|
||||
logger = Logger(__name__)
|
||||
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)
|
||||
course_layer = DynamoDBPersistenceLayer(COURSE_TABLE, dynamodb_client)
|
||||
|
||||
@@ -37,7 +37,7 @@ def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
|
||||
transact.update(
|
||||
key=KeyPair(new_image['id'], '0'),
|
||||
update_expr='SET subscription_covered = :subscription_covered, \
|
||||
updated_at = :now',
|
||||
updated_at = :now',
|
||||
expr_attr_values={
|
||||
':subscription_covered': True,
|
||||
':now': now_,
|
||||
|
||||
Reference in New Issue
Block a user