-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsearch_post_document_reference.py
More file actions
174 lines (150 loc) · 6.11 KB
/
search_post_document_reference.py
File metadata and controls
174 lines (150 loc) · 6.11 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
from pydantic import ValidationError
from nrlf.consumer.fhir.r4.model import Bundle, DocumentReference
from nrlf.core.codes import SpineErrorConcept
from nrlf.core.config import Config
from nrlf.core.decorators import request_handler
from nrlf.core.dynamodb.repository import DocumentPointerRepository
from nrlf.core.logger import LogReference, logger
from nrlf.core.model import ConnectionMetadata, ConsumerRequestParams
from nrlf.core.response import Response, SpineErrorResponse
from nrlf.core.validators import validate_category, validate_type
from nrlf.producer.fhir.r4.model import OperationOutcome, OperationOutcomeIssue
@request_handler(body=ConsumerRequestParams)
def handler(
body: ConsumerRequestParams,
metadata: ConnectionMetadata,
repository: DocumentPointerRepository,
) -> Response:
"""
Search for document references based on the provided parameters.
Args:
body (ConsumerRequestParams): The request parameters for the search.
metadata (ConnectionMetadata): The metadata containing pointer types.
repository (DocumentPointerRepository): The repository for document pointers.
Returns:
Response: The response containing the search results.
Raises:
SpineErrorResponse.INVALID_NHS_NUMBER: If a valid NHS number is not provided.
SpineErrorResponse.INVALID_CODE_SYSTEM: If the provided type system is invalid.
OperationOutcomeError: If an error occurs while parsing the document reference.
"""
logger.log(LogReference.CONPOSTSEARCH000)
if not body.nhs_number:
logger.log(
LogReference.CONPOSTSEARCH001, subject_identifier=body.subject_identifier
)
return SpineErrorResponse.INVALID_NHS_NUMBER(
diagnostics="A valid NHS number is required to search for document references",
expression="subject:identifier",
)
config = Config()
base_url = f"https://{config.ENVIRONMENT}.api.service.nhs.uk/"
self_link = f"{base_url}record-locator/consumer/FHIR/R4/DocumentReference?subject:identifier=https://fhir.nhs.uk/Id/nhs-number|{body.nhs_number}"
allowed_types = (
metadata.nrl_permissions_policy.types
if metadata.nrl_permissions_policy
else metadata.pointer_types
)
if not validate_type(body.type, allowed_types):
logger.log(
LogReference.CONPOSTSEARCH002,
type=body.type,
pointer_types=allowed_types,
)
return SpineErrorResponse.INVALID_CODE_SYSTEM(
diagnostics="The provided type does not match the allowed types for this organisation",
expression="type",
)
categories = body.category.root.split(",") if body.category else []
if not validate_category(categories):
logger.log(
LogReference.CONPOSTSEARCH002b,
category=body.category,
)
return SpineErrorResponse.INVALID_CODE_SYSTEM(
diagnostics="The provided category is not valid",
expression="category",
)
custodian_id = (
body.custodian_identifier.root.split("|", maxsplit=1)[1]
if body.custodian_identifier
else None
)
if custodian_id:
self_link += f"&custodian:identifier=https://fhir.nhs.uk/Id/ods-organization-code|{custodian_id}"
pointer_types = [body.type.root] if body.type else allowed_types
if body.type:
self_link += f"&type={body.type.root}"
if body.category:
self_link += f"&category={body.category.root}"
if body.field_summary:
self_link += f"&_summary={body.field_summary.root}"
bundle = {
"resourceType": "Bundle",
"type": "searchset",
"link": [{"relation": "self", "url": self_link}],
"total": 0,
"entry": [],
}
logger.log(
LogReference.CONPOSTSEARCH003,
nhs_number=body.nhs_number,
custodian_id=custodian_id,
pointer_types=pointer_types,
)
if body.field_summary and body.field_summary.root == "count":
bundle = {
"resourceType": "Bundle",
"type": "searchset",
"link": [{"relation": "self", "url": self_link}],
"total": 0,
}
logger.log(LogReference.CONPOSTSEARCH006)
total = repository.count_by_nhs_number(
nhs_number=body.nhs_number,
pointer_types=pointer_types,
)
bundle["total"] = total
logger.log(LogReference.CONPOSTSEARCH007, total=total)
response = Response.from_resource(Bundle.model_validate(bundle))
logger.log(LogReference.CONPOSTSEARCH999)
return response
for result in repository.search(
nhs_number=body.nhs_number,
custodian=custodian_id,
pointer_types=pointer_types,
categories=categories,
):
try:
document_reference = DocumentReference.model_validate_json(result.document)
bundle["total"] += 1
bundle["entry"].append(
{"resource": document_reference.model_dump(exclude_none=True)}
)
logger.log(
LogReference.CONPOSTSEARCH004,
id=document_reference.id,
count=bundle["total"],
)
except ValidationError as exc:
logger.log(
LogReference.CONPOSTSEARCH005, error=str(exc), document=result.document
)
operation_outcome = OperationOutcome(
resourceType="OperationOutcome",
issue=[
OperationOutcomeIssue(
severity="error",
code="exception",
details=SpineErrorConcept.from_code("INTERNAL_SERVER_ERROR"),
diagnostics="An error occurred whilst parsing the document reference search results",
)
],
)
bundle["total"] += 1
bundle["entry"].append(
{"resource": operation_outcome.model_dump(exclude_none=True)}
)
response = Response.from_resource(Bundle.model_validate(bundle))
logger.log(LogReference.CONPOSTSEARCH999)
return response