-
Notifications
You must be signed in to change notification settings - Fork 0
/
webapi.py
80 lines (67 loc) · 2.55 KB
/
webapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from datetime import date, datetime
from flask import Flask, abort
from flask_restx import Api, Resource, fields
from pydantic import BaseModel, ValidationError, validator
from returns.pipeline import is_successful
from toolz.itertoolz import groupby
from bootstrap import bootstrap
from inviter.usecase import InviteAdultsToBar
app = Flask(__name__)
api = Api(app)
ns = api.namespace("invite", description="Send Invitations")
invitation_request = api.model(
"InvitationRequest",
{
"date": fields.Date(required=True, description="Invitation date in ISO format yyyy-mm-dd"),
"hour": fields.Integer(required=True, description="Hour"),
"minute": fields.Integer(required=True, description="Minute"),
},
)
invitation_response = api.model(
"InvitationResponse",
{
"success": fields.Integer(required=True, description="Total count of invitations sent successfully"),
"failed": fields.Integer(
required=True,
description="Total count of invitations that failed and weren't sent",
),
},
)
class InvitationRequest(BaseModel):
date: date
hour: int
minute: int
@validator("hour")
def less_than_24(cls, value):
if 0 < value >= 24:
raise ValueError("Values between 0 and 23 are valid")
return value
@validator("minute")
def less_than_60(cls, value):
if 0 < value >= 60:
raise ValueError("Values between 0 and 59 are valid")
return value
@ns.route("/adults")
class InviteAdults(Resource):
@ns.doc("Send invitation to adults from the repository")
@ns.expect(invitation_request)
@ns.marshal_with(invitation_response, code=200)
def post(self):
try:
invitation_request = InvitationRequest(**api.payload)
except ValidationError as e:
abort(400, str(e))
raw_invitation_datetime = f"{invitation_request.date} {invitation_request.hour}:{invitation_request.minute}"
invitation_date = datetime.strptime(raw_invitation_datetime, "%Y-%m-%d %H:%M")
command_bus = bootstrap()
command = InviteAdultsToBar(invitation_date=invitation_date)
send_invites_result = command_bus.handle(command)
result = {"success": 0, "failed": 0}
result_by_success = groupby(is_successful, send_invites_result)
for is_success, results in result_by_success.items():
cnt = len([r for r in results])
if is_success:
result["success"] = cnt
else:
result["failed"] = cnt
return result