-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathagencies.py
More file actions
265 lines (233 loc) · 8.07 KB
/
agencies.py
File metadata and controls
265 lines (233 loc) · 8.07 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import logging
from typing import Optional, List
from backend.auth.jwt import min_role_required
from backend.schemas import (
validate_request, paginate_results, ordered_jsonify,
NodeConflictException)
from backend.mixpanel.mix import track_to_mp
from backend.database.models.user import UserRole
from backend.database.models.agency import Agency
from flask import Blueprint, abort, request
from flask_jwt_extended.view_decorators import jwt_required
from npdi_oas.agencies import CreateAgency, UpdateAgency
from pydantic import BaseModel
bp = Blueprint("agencies_routes", __name__, url_prefix="/api/v1/agencies")
class AddOfficerSchema(BaseModel):
officer_id: int
badge_number: str
agency_id: Optional[int]
highest_rank: Optional[str]
earliest_employment: Optional[str]
latest_employment: Optional[str]
unit: Optional[str]
currently_employed: bool = True
class AddOfficerListSchema(BaseModel):
officers: List[AddOfficerSchema]
# Create agency profile
@bp.route("/", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.CONTRIBUTOR)
@validate_request(CreateAgency)
def create_agency():
logger = logging.getLogger("create_agency")
"""Create an agency profile.
User must be a Contributor to create an agency.
Must include a name and jurisdiction.
"""
body: CreateAgency = request.validated_body
try:
agency = Agency.from_dict(body.model_dump())
except NodeConflictException:
abort(409, description="Agency already exists")
except Exception as e:
logger.error(f"Error, Agency.from_dict: {e}")
abort(400)
track_to_mp(
request,
"create_agency",
{
"name": agency.name
},
)
return agency.to_json()
# Get agency profile
@bp.route("/<agency_id>", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def get_agency(agency_id: str):
"""Get an agency profile.
"""
# logger = logging.getLogger("get_agency")
agency = Agency.nodes.get_or_none(uid=agency_id)
if agency is None:
abort(404, description="Agency not found")
try:
return agency.to_json()
except Exception as e:
abort(500, description=str(e))
# Update agency profile
@bp.route("/<agency_uid>", methods=["PUT"])
@jwt_required()
@min_role_required(UserRole.CONTRIBUTOR)
@validate_request(UpdateAgency)
def update_agency(agency_uid: str):
"""Update an agency profile.
"""
# logger = logging.getLogger("update_agency")
body: UpdateAgency = request.validated_body
agency = Agency.nodes.get_or_none(uid=agency_uid)
if agency is None:
abort(404, description="Agency not found")
try:
agency = Agency.from_dict(body.model_dump(), agency_uid)
agency.refresh()
track_to_mp(
request,
"update_agency",
{
"name": agency.name
}
)
return agency.to_json()
except Exception as e:
abort(400, description=str(e))
# Delete agency profile
@bp.route("/<agency_id>", methods=["DELETE"])
@jwt_required()
@min_role_required(UserRole.ADMIN)
def delete_agency(agency_id: str):
"""Delete an agency profile.
Must be an admin to delete an agency.
"""
agency = Agency.nodes.get_or_none(uid=agency_id)
if agency is None:
abort(404, description="Agency not found")
try:
name = agency.name
agency.delete()
track_to_mp(
request,
"delete_agency",
{
"name": name
}
)
return {"message": "Agency deleted successfully"}
except Exception as e:
abort(400, description=str(e))
# Get all agencies
@bp.route("/", methods=["GET"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
def get_all_agencies():
"""Get all agencies.
Accepts Query Parameters for pagination:
per_page: number of results per page
page: page number
"""
args = request.args
q_page = args.get("page", 1, type=int)
q_per_page = args.get("per_page", 20, type=int)
all_agencies = Agency.nodes.all()
results = paginate_results(all_agencies, q_page, q_per_page)
return ordered_jsonify(results), 200
# # Add officer employment information
# @bp.route("/<int:agency_id>/officers", methods=["POST"])
# @jwt_required()
# @min_role_required(UserRole.CONTRIBUTOR)
# @validate(json=AddOfficerListSchema)
# def add_officer_to_agency(agency_id: int):
# """Add any number of officer employment records to an agency.
# Must be a Contributor to add officers to an agency.
# """
# agency = Agency.nodes.get_or_none(uid=agency_id)
# if agency is None:
# abort(404, description="Agency not found")
# records = request.context.json.officers
# created = []
# failed = []
# for record in records:
# try:
# officer = db.session.query(Officer).get(
# record.officer_id)
# if officer is None:
# failed.append({
# "officer_id": record.officer_id,
# "reason": "Officer not found"
# })
# else:
# employments = db.session.query(Employment).filter(
# and_(
# and_(
# Employment.officer_id == record.officer_id,
# Employment.agency_id == agency_id
# ),
# Employment.badge_number == record.badge_number
# )
# )
# if employments is not None:
# # If the officer already has a records for this agency,
# # we need to update the earliest and
# # latest employment dates
# employment = employment_to_orm(record)
# employment.agency_id = agency_id
# employment = merge_employment_records(
# employments.all() + [employment],
# currently_employed=record.currently_employed
# )
# # Delete the old records and replace them with the new one
# employments.delete()
# created.append(employment.create())
# else:
# record.agency_id = agency_id
# employment = employment_to_orm(record)
# created.append(employment.create())
# except Exception as e:
# failed.append({
# "officer_id": record.officer_id,
# "reason": str(e)
# })
# try:
# track_to_mp(
# request,
# "add_officers_to_agency",
# {
# "agency_id": agency.id,
# "officers_added": len(created),
# "officers_failed": len(failed)
# },
# )
# return {
# "created": [
# employment_orm_to_json(item) for item in created],
# "failed": failed,
# "totalCreated": len(created),
# "totalFailed": len(failed),
# }
# except Exception as e:
# abort(400, description=str(e))
# # Get agency officers
# @bp.route("/<int:agency_id>/officers", methods=["GET"])
# @jwt_required()
# @min_role_required(UserRole.PUBLIC)
# @validate()
# def get_agency_officers(agency_id: int):
# """Get all officers for an agency.
# Pagination currently isn't enabled due to the use of an association proxy.
# """
# # args = request.args
# # q_page = args.get("page", 1, type=int)
# # q_per_page = args.get("per_page", 20, type=int)
# # TODO: Add pagination
# try:
# agency = Agency.nodes.get_or_none(uid=agency_id)
# all_officers = agency.officers
# return {
# "results": [
# officer_orm_to_json(officer) for officer in all_officers],
# "page": 1,
# "totalPages": 1,
# "totalResults": len(all_officers),
# }
# except Exception as e:
# abort(400, description=str(e))