-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPayerController.java
More file actions
314 lines (287 loc) · 18.4 KB
/
PayerController.java
File metadata and controls
314 lines (287 loc) · 18.4 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package org.swasth.hcx.controllers.v1;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import io.hcxprotocol.utils.Operations;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.r4.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.swasth.hcx.controllers.BaseController;
import org.swasth.hcx.dto.Response;
import org.swasth.hcx.exception.ClientException;
import org.swasth.hcx.service.PostgresService;
import org.swasth.hcx.utils.Constants;
import org.swasth.hcx.utils.JSONUtils;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.*;
import static org.swasth.hcx.utils.Constants.*;
@RestController
public class PayerController extends BaseController {
@Value("${postgres.table.payerData}")
private String table;
@Autowired
private PostgresService postgres;
@Value("${request_list.default_limit}")
private int listLimit;
@Value("${request_list.default_latest_data_by_day}")
private int dayLimit;
IParser p = FhirContext.forR4().newJsonParser().setPrettyPrint(true);
@PostMapping(value = "/request/list")
public ResponseEntity<Object> requestList(@RequestBody Map<String, Object> requestBody) {
try {
String type = (String) requestBody.getOrDefault("type", "");
long days = System.currentTimeMillis()-(int) requestBody.getOrDefault("days", dayLimit)*24*60*60*1000;
int limit = (int) requestBody.getOrDefault("limit", listLimit);
int offset = (int) requestBody.getOrDefault("offset", 0);
String senderCode = (String) requestBody.getOrDefault("sender_code", "");
String recipientCode = (String) requestBody.getOrDefault("recipient_code", "");
validateStr("type", type);
List<Object> result = new ArrayList<>();
StringBuilder countQuery = new StringBuilder("SELECT count(*) FROM " + table + " WHERE action = '" + type + "' AND created_on > " + days);
addToQuery(countQuery, senderCode, "sender_code");
addToQuery(countQuery, recipientCode, "recipient_code");
ResultSet resultSet1 = postgres.executeQuery(countQuery.toString());
Map<String, Object> resp = new HashMap<>();
while (resultSet1.next()) {
resp.put("count", resultSet1.getInt("count"));
}
String query = countQuery.toString().replace("count(*)", "count(*) over(),*") + " ORDER BY created_on DESC LIMIT " + limit + " OFFSET " + offset;
ResultSet resultSet = postgres.executeQuery(query);
while (resultSet.next()) {
Map<String, Object> map = new HashMap<>();
map.put("sender_code", resultSet.getString("sender_code"));
map.put("recipient_code", resultSet.getString("recipient_code"));
map.put("request_id", resultSet.getString("request_id"));
map.put("response_fhir", JSONUtils.deserialize(resultSet.getString("response_fhir"), Map.class));
map.put("status", resultSet.getString("status"));
map.put("additional_info", JSONUtils.deserialize(resultSet.getString("additional_info"), Map.class));
map.put("payload", JSONUtils.deserialize(resultSet.getString("request_fhir"), Map.class));
map.put("otp_verification", resultSet.getString("otp_verification"));
map.put("account_number", resultSet.getString("account_number"));
map.put("ifsc_code", resultSet.getString("ifsc_code"));
map.put("app", resultSet.getString("app"));
result.add(map);
}
resp.put(type, result);
return new ResponseEntity<>(resp, HttpStatus.OK);
} catch (Exception e) {
return exceptionHandler(new Response(), e);
}
}
private void addToQuery(StringBuilder query, String code, String field){
if(!StringUtils.isEmpty(code)) {
query.append(" AND " + field + " = '" + code + "'");
}
}
@PostMapping(value = "/coverageeligibility/approve")
public ResponseEntity<Object> coverageEligibilityApprove(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"coverageeligibility", APPROVED);
}
@PostMapping(value = "/coverageeligibility/reject")
public ResponseEntity<Object> coverageEligibilityReject(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"coverageeligibility", REJECTED);
}
@PostMapping(value = "/preauth/approve")
public ResponseEntity<Object> preauthApprove(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"preauth", APPROVED);
}
@PostMapping(value = "/preauth/reject")
public ResponseEntity<Object> preauthReject(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"preauth", REJECTED);
}
@PostMapping(value = "/claim/approve")
public ResponseEntity<Object> claimApprove(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"claim", APPROVED);
}
@PostMapping(value = "/claim/reject")
public ResponseEntity<Object> claimReject(@RequestBody Map<String, Object> requestBody) {
return review(requestBody,"claim", REJECTED);
}
@PostMapping(value = "/response/update")
public ResponseEntity<Object> updateResponse(@RequestBody Map<String, Object> requestBody) throws ClientException {
updateDB((String) requestBody.get("request_id"), (String) requestBody.get("response_fhir"), "response.complete");
return new ResponseEntity<>(new Response(), HttpStatus.OK);
}
public void updateDB(String requestId, String respfhir, String onActionStatus) throws ClientException {
String query = String.format("UPDATE %s SET response_fhir = '%s', on_action_status= '%s' WHERE request_id ='%s'", table, respfhir, onActionStatus, requestId);
postgres.execute(query);
}
public ResponseEntity<Object> review(Map<String, Object> requestBody, String entity, String status){
try {
System.out.println("Review: " + status + " :: entity: " + entity + " :: request body: " + requestBody);
String id = (String) requestBody.getOrDefault("request_id", "");
validateStr("request_id", id);
validateStr("recipient_code", (String) requestBody.getOrDefault("recipient_code", ""));
Map<String,Object> output = new HashMap<>();
if (StringUtils.equals(entity, "coverageeligibility")) {
String updateQuery = String.format("UPDATE %s SET status='%s',updated_on=%d WHERE request_id='%s' RETURNING %s,%s",
table, status, System.currentTimeMillis(), id, "raw_payload", "response_fhir");
ResultSet resultset = postgres.executeQuery(updateQuery);
String respfhir = "";
String actionJwe = "";
while(resultset.next()){
respfhir = resultset.getString("response_fhir");
actionJwe = resultset.getString("raw_payload");
}
if(status.equals(APPROVED)){
onActionCall.sendOnAction((String) requestBody.get("recipient_code"), respfhir, Operations.COVERAGE_ELIGIBILITY_ON_CHECK, actionJwe, "response.complete", output);
} else {
String bundleString = getCoverageRejectedBundle(respfhir);
System.out.println("Rejected Response bundle: " + bundleString);
onActionCall.sendOnAction((String) requestBody.get("recipient_code"), bundleString, Operations.COVERAGE_ELIGIBILITY_ON_CHECK, actionJwe, "response.complete", output);
}
} else {
String type = (String) requestBody.getOrDefault("type", "");
String remarks = (String) requestBody.getOrDefault("remarks", "");
validateStr("type", type);
if (!Constants.PAYOR_APPROVAL_TYPES.contains(type))
throw new ClientException("Invalid type, allowed types are: " + Constants.PAYOR_APPROVAL_TYPES);
Map<String, Object> info = new HashMap<>();
info.put("status", status);
info.put("remarks", remarks);
if(StringUtils.equals(APPROVED, status)) {
if(!requestBody.containsKey("approved_amount") || !(requestBody.get("approved_amount") instanceof Integer))
throw new ClientException("Approved amount is mandatory field and should be a number");
info.put("approved_amount", requestBody.getOrDefault("approved_amount", 0));
info.put("account_number", requestBody.getOrDefault("account_number", 0));
info.put("ifsc_code", requestBody.getOrDefault("ifsc_code", ""));
}
String query = String.format("UPDATE %s SET additional_info = jsonb_set(additional_info::jsonb, '{%s}', '%s'),updated_on = %d WHERE request_id = '%s' RETURNING %s,%s,%s,%s,%s",
table, type, JSONUtils.serialize(info), System.currentTimeMillis(), id, "additional_info", "status", "raw_payload", "response_fhir", "action");
ResultSet resultSet = postgres.executeQuery(query);
Map<String, Object> addInfo = new HashMap<>();
String existingStatus = PENDING;
String respfhir = "";
String actionJwe = "";
String action = "";
while (resultSet.next()) {
addInfo.putAll(JSONUtils.deserialize(resultSet.getString("additional_info"), Map.class));
existingStatus = resultSet.getString("status");
respfhir = resultSet.getString("response_fhir");
actionJwe = resultSet.getString("raw_payload");
action = resultSet.getString("action");
}
if (!addInfo.isEmpty()) {
String overallStatus = getStatus(addInfo);
if (!StringUtils.equalsIgnoreCase(overallStatus, existingStatus)) {
String updateQuery = String.format("UPDATE %s SET status = '%s',updated_on = %d WHERE request_id = '%s'"
, table, overallStatus, System.currentTimeMillis(), id);
postgres.execute(updateQuery);
}
if (overallStatus.equals(APPROVED)) {
String bundleString = getApprovedClaimBundle(requestBody, entity, respfhir);
System.out.println("Approved Response bundle: " + bundleString);
Bundle parsed = p.parseResource(Bundle.class, bundleString);
// for (Bundle.BundleEntryComponent bundleEntryComponent : parsed.getEntry()) {
// if (Objects.equals(bundleEntryComponent.getResource().getResourceType().toString(), "ClaimResponse")) {
// ClaimResponse claimRes = p.parseResource(ClaimResponse.class, p.encodeResourceToString(bundleEntryComponent.getResource()));
// Long approvedAmount = Long.valueOf((Integer) requestBody.getOrDefault("approved_amount", 0));
// claimRes.getTotal().add(new ClaimResponse.TotalComponent().setCategory(new CodeableConcept(new Coding().setSystem("http://terminology.hl7.org/CodeSystem/adjudication").setCode("benefit"))).setAmount(new Money().setValue(approvedAmount).setCurrency("INR")));
// }
// }
bundleString = p.encodeResourceToString(parsed);
System.out.println("Claim request after creating -----------" + bundleString);
onActionCall.sendOnAction((String) requestBody.get("recipient_code"), bundleString, action.contains("preauth") ? Operations.PRE_AUTH_ON_SUBMIT : Operations.CLAIM_ON_SUBMIT, actionJwe, "response.complete", output);
} else if (overallStatus.equals(REJECTED)){
String bundleString = getRejectedClaimBundle(entity, type, respfhir);
Bundle parsed = p.parseResource(Bundle.class, bundleString);
for (Bundle.BundleEntryComponent bundleEntryComponent : parsed.getEntry()) {
if(Objects.equals(bundleEntryComponent.getResource().getResourceType().toString(), "ClaimResponse")) {
ClaimResponse claimRes = p.parseResource(ClaimResponse.class, p.encodeResourceToString(bundleEntryComponent.getResource()));
ClaimResponse.NoteComponent note = new ClaimResponse.NoteComponent();
note.setText(remarks);
claimRes.addProcessNote(note);
Long approvedAmount = Long.valueOf((Integer) requestBody.getOrDefault("approved_amount",0));
claimRes.getTotal().add(new ClaimResponse.TotalComponent().setCategory(new CodeableConcept(new Coding().setSystem("http://terminology.hl7.org/CodeSystem/adjudication").setCode("benefit"))).setAmount(new Money().setValue(approvedAmount).setCurrency("INR")));
}
}
System.out.println("Rejected Response bundle: " + bundleString);
bundleString = p.encodeResourceToString(parsed);
onActionCall.sendOnAction((String) requestBody.get("recipient_code"), bundleString, action.contains("preauth") ? Operations.PRE_AUTH_ON_SUBMIT : Operations.CLAIM_ON_SUBMIT, actionJwe, "response.complete", output);
}
}
}
Map<String,Object> resp = new HashMap<>();
resp.put("timestamp", System.currentTimeMillis());
resp.put("status", Constants.SUCCESSFUL);
resp.put("reason", "");
System.out.println("Process completed :: request id :" + id);
return new ResponseEntity<>(resp, HttpStatus.OK);
} catch (Exception e) {
return exceptionHandler(new Response(), e);
}
}
private static String getCoverageRejectedBundle(String respfhir) {
IParser p = FhirContext.forR4().newJsonParser().setPrettyPrint(true);
Bundle newBundle = p.parseResource(Bundle.class, respfhir);
for(int i=0; i < newBundle.getEntry().size(); i++){
Bundle.BundleEntryComponent par = newBundle.getEntry().get(i);
DomainResource dm = (DomainResource) par.getResource();
System.out.println("type of dm" + dm);
if(dm.getClass() == CoverageEligibilityResponse.class){
System.out.println("index " + i);
((CoverageEligibilityResponse) dm).getError().add(new CoverageEligibilityResponse.ErrorsComponent(new CodeableConcept(new Coding().setSystem("http://terminology.hl7.org/CodeSystem/adjudication-error").setCode("a001").setDisplay("Coverage Eligibility Request has been rejected"))));
}
}
return p.encodeResourceToString(newBundle);
}
private static String getApprovedClaimBundle(Map<String, Object> requestBody, String entity, String respfhir) {
IParser p = FhirContext.forR4().newJsonParser().setPrettyPrint(true);
Bundle newBundle = p.parseResource(Bundle.class, respfhir);
for(int i=0; i < newBundle.getEntry().size(); i++){
Bundle.BundleEntryComponent par = newBundle.getEntry().get(i);
DomainResource dm = (DomainResource) par.getResource();
System.out.println("type of dm" + dm);
if(dm.getClass() == ClaimResponse.class){
System.out.println("index " + i);
if(entity.equals("preauth")){
((ClaimResponse) dm).setUse(ClaimResponse.Use.PREAUTHORIZATION);
}
ClaimResponse.NoteComponent note = new ClaimResponse.NoteComponent();
note.setText((String) requestBody.getOrDefault("remarks", ""));
((ClaimResponse) dm).addProcessNote(note);
((ClaimResponse) dm).getTotal().set(0,new ClaimResponse.TotalComponent().setCategory(new CodeableConcept(new Coding().setSystem("http://terminology.hl7.org/CodeSystem/adjudication").setCode("benefit"))).setAmount(new Money().setValue((int) requestBody.getOrDefault("approved_amount", 0)).setCurrency("INR")));
}
}
return p.encodeResourceToString(newBundle);
}
private static String getRejectedClaimBundle(String entity, String type, String respfhir) {
IParser p = FhirContext.forR4().newJsonParser().setPrettyPrint(true);
Bundle newBundle = p.parseResource(Bundle.class, respfhir);
for(int i=0; i < newBundle.getEntry().size(); i++){
Bundle.BundleEntryComponent par = newBundle.getEntry().get(i);
DomainResource dm = (DomainResource) par.getResource();
System.out.println("type of dm" + dm);
if(dm.getClass() == ClaimResponse.class){
System.out.println("index " + i);
if(entity.equals("preauth")){
((ClaimResponse) dm).setUse(ClaimResponse.Use.PREAUTHORIZATION);
}
((ClaimResponse) dm).getError().add(new ClaimResponse.ErrorComponent(new CodeableConcept(new Coding().setSystem("http://hcxprotocol.io/codes/claim-error-codes").setCode("AUTH-001").setDisplay(StringUtils.capitalize(type) + " adjudication failed"))));
}
}
return p.encodeResourceToString(newBundle);
}
private String getStatus(Map<String,Object> addInfo){
String status = PENDING;
Set<String> statuses = new HashSet<>();
for (Map.Entry<String, Object> entry : addInfo.entrySet()) {
String objStatus = ((Map<String, Object>) entry.getValue()).getOrDefault("status","").toString();
statuses.add(objStatus);
}
if(statuses.contains(REJECTED)) {
status = REJECTED;
} else if (statuses.contains(PENDING)) {
status = PENDING;
} else if (statuses.contains(APPROVED)) {
status = APPROVED;
}
return status;
}
}