Advertisement
aka007

DWRPatientService.java

Feb 20th, 2014
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.35 KB | None | 0 0
  1. /**
  2. * The contents of this file are subject to the OpenMRS Public License
  3. * Version 1.0 (the "License"); you may not use this file except in
  4. * compliance with the License. You may obtain a copy of the License at
  5. * http://license.openmrs.org
  6. *
  7. * Software distributed under the License is distributed on an "AS IS"
  8. * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  9. * License for the specific language governing rights and limitations
  10. * under the License.
  11. *
  12. * Copyright (C) OpenMRS, LLC. All Rights Reserved.
  13. */
  14. package org.openmrs.web.dwr;
  15.  
  16. import java.text.ParseException;
  17. import java.text.SimpleDateFormat;
  18. import java.util.Collection;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Vector;
  24.  
  25. import org.apache.commons.lang.StringUtils;
  26. import org.apache.commons.logging.Log;
  27. import org.apache.commons.logging.LogFactory;
  28. import org.openmrs.Concept;
  29. import org.openmrs.GlobalProperty;
  30. import org.openmrs.Location;
  31. import org.openmrs.Patient;
  32. import org.openmrs.PatientIdentifier;
  33. import org.openmrs.PatientIdentifierType;
  34. import org.openmrs.PersonAddress;
  35. import org.openmrs.activelist.Allergy;
  36. import org.openmrs.activelist.AllergySeverity;
  37. import org.openmrs.activelist.AllergyType;
  38. import org.openmrs.activelist.Problem;
  39. import org.openmrs.activelist.ProblemModifier;
  40. import org.openmrs.api.APIAuthenticationException;
  41. import org.openmrs.api.APIException;
  42. import org.openmrs.api.ConceptService;
  43. import org.openmrs.api.DuplicateIdentifierException;
  44. import org.openmrs.api.GlobalPropertyListener;
  45. import org.openmrs.api.IdentifierNotUniqueException;
  46. import org.openmrs.api.InsufficientIdentifiersException;
  47. import org.openmrs.api.InvalidCheckDigitException;
  48. import org.openmrs.api.InvalidIdentifierFormatException;
  49. import org.openmrs.api.LocationService;
  50. import org.openmrs.api.PatientIdentifierException;
  51. import org.openmrs.api.PatientService;
  52. import org.openmrs.api.context.Context;
  53. import org.openmrs.patient.IdentifierValidator;
  54. import org.openmrs.patient.UnallowedIdentifierException;
  55. import org.openmrs.util.OpenmrsConstants;
  56.  
  57. /**
  58. * DWR patient methods. The methods in here are used in the webapp to get data from the database via
  59. * javascript calls.
  60. *
  61. * @see PatientService
  62. */
  63. public class DWRPatientService implements GlobalPropertyListener {
  64.  
  65. private static final Log log = LogFactory.getLog(DWRPatientService.class);
  66.  
  67. private static Integer maximumResults;
  68.  
  69. /**
  70. * Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
  71. * search. Else, do a name search
  72. *
  73. * @param searchValue string to be looked for
  74. * @param includeVoided true/false whether or not to included voided patients
  75. * @return Collection<Object> of PatientListItem or String
  76. * @should return only patient list items with nonnumeric search
  77. * @should return string warning if invalid patient identifier
  78. * @should not return string warning if searching with valid identifier
  79. * @should include string in results if doing extra decapitated search
  80. * @should not return duplicate patient list items if doing decapitated search
  81. * @should not do decapitated search if numbers are in the search string
  82. * @should get results for patients that have edited themselves
  83. * @should logged in user should load their own patient object
  84. */
  85. public Collection<Object> findPatients(String searchValue, boolean includeVoided) {
  86. return findBatchOfPatients(searchValue, includeVoided, null, null);
  87. }
  88.  
  89. public static void setMaximumResults(Integer maximumResults) {
  90. DWRPatientService.maximumResults = maximumResults;
  91. }
  92.  
  93. /**
  94. * Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
  95. * search. Else, do a name search
  96. *
  97. * @see PatientService#getPatients(String, String, List, boolean, int, Integer)
  98. * @param searchValue string to be looked for
  99. * @param includeVoided true/false whether or not to included voided patients
  100. * @param start The starting index for the results to return
  101. * @param length The number of results of return
  102. * @return Collection<Object> of PatientListItem or String
  103. * @since 1.8
  104. */
  105. public Collection<Object> findBatchOfPatients(String searchValue, boolean includeVoided, Integer start, Integer length) {
  106. if (maximumResults == null) {
  107. setMaximumResults(getMaximumSearchResults());
  108. }
  109. if (length != null && length > maximumResults) {
  110. length = maximumResults;
  111. }
  112.  
  113. // the list to return
  114. List<Object> patientList = new Vector<Object>();
  115.  
  116. PatientService ps = Context.getPatientService();
  117. Collection<Patient> patients;
  118.  
  119. try {
  120. patients = ps.getPatients(searchValue, start, length);
  121. }
  122. catch (APIAuthenticationException e) {
  123. patientList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
  124. return patientList;
  125. }
  126.  
  127. patientList = new Vector<Object>(patients.size());
  128. for (Patient p : patients) {
  129. patientList.add(new PatientListItem(p, searchValue));
  130. }
  131. //no results found and a number was in the search --
  132. //should check whether the check digit is correct.
  133. if (patients.size() == 0 && searchValue.matches(".*\\d+.*")) {
  134.  
  135. //Looks through all the patient identifier validators to see if this type of identifier
  136. //is supported for any of them. If it isn't, then no need to warn about a bad check
  137. //digit. If it does match, then if any of the validators validates the check digit
  138. //successfully, then the user is notified that the identifier has been entered correctly.
  139. //Otherwise, the user is notified that the identifier was entered incorrectly.
  140.  
  141. Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
  142. boolean shouldWarnUser = true;
  143. boolean validCheckDigit = false;
  144. boolean identifierMatchesValidationScheme = false;
  145.  
  146. for (IdentifierValidator piv : pivs) {
  147. try {
  148. if (piv.isValid(searchValue)) {
  149. shouldWarnUser = false;
  150. validCheckDigit = true;
  151. }
  152. identifierMatchesValidationScheme = true;
  153. }
  154. catch (UnallowedIdentifierException e) {}
  155. }
  156.  
  157. if (identifierMatchesValidationScheme) {
  158. if (shouldWarnUser) {
  159. patientList
  160. .add("<p style=\"color:red; font-size:big;\"><b>WARNING: Identifier has been typed incorrectly! Please double check the identifier.</b></p>");
  161. } else if (validCheckDigit) {
  162. patientList
  163. .add("<p style=\"color:green; font-size:big;\"><b>This identifier has been entered correctly, but still no patients have been found.</b></p>");
  164. }
  165. }
  166. }
  167.  
  168. return patientList;
  169. }
  170.  
  171. /**
  172. * Returns a map of results with the values as count of matches and a partial list of the
  173. * matching patients (depending on values of start and length parameters) while the keys are are
  174. * 'count' and 'objectList' respectively, if the length parameter is not specified, then all
  175. * matches will be returned from the start index if specified.
  176. *
  177. * @param searchValue patient name or identifier
  178. * @param start the beginning index
  179. * @param length the number of matching patients to return
  180. * @param getMatchCount Specifies if the count of matches should be included in the returned map
  181. * @return a map of results
  182. * @throws APIException
  183. * @since 1.8
  184. * @should signal for a new search if the new search value has matches and is a first call
  185. * @should not signal for a new search if it is not the first ajax call
  186. * @should not signal for a new search if the new search value has no matches
  187. * @should match patient with identifiers that contain no digit
  188. */
  189. @SuppressWarnings("unchecked")
  190. public Map<String, Object> findCountAndPatients1(String searchValue, boolean includeVoided, Integer start,
  191. Integer length, boolean getMatchCount) throws APIException {
  192. System.out.println("hie\n");
  193. //Map to return
  194. Map<String, Object> resultsMap = new HashMap<String, Object>();
  195. Collection<Object> objectList = new Vector<Object>();
  196. try {
  197. //PatientService ps = Context.getPatientService();
  198. int patientCount = 0;
  199. //patientCount+=ps.getCountOfPatients(searchValue);
  200. //if this is the first call
  201. if (getMatchCount) {
  202. //patientCount += ps.getCountOfPatients1(searchValue, includeVoided);
  203. patientCount += Context.getPatientService().getCountOfPatients(searchValue);
  204. //patientCount += Context.getPatientService().getCountOfPatients1(searchValue, includeVoided);
  205. // if there are no results found and a number was not in the
  206. // search and this is the first call, then do a decapitated search:
  207. //trim each word down to the first three characters and search again
  208. if (patientCount == 0 && start == 0 && !searchValue.matches(".*\\d+.*")) {
  209. String[] names = searchValue.split(" ");
  210. StringBuilder newSearch = new StringBuilder("");
  211. for (String name : names) {
  212. if (name.length() > 3) {
  213. name = name.substring(0, 3);
  214. }
  215. newSearch.append(" ").append(name);
  216. }
  217.  
  218. String newSearchStr = newSearch.toString().trim();
  219. if (!newSearchStr.equals(searchValue)) {
  220. //int newPatientCount = ps.getCountOfPatients1(newSearchStr, includeVoided);
  221. int newPatientCount = Context.getPatientService().getCountOfPatients(newSearchStr);
  222. //int newPatientCount = Context.getPatientService().getCountOfPatients1(newSearchStr, includeVoided);
  223. if (newPatientCount > 0) {
  224. // Send a signal to the core search widget to search again against newSearch
  225. resultsMap.put("searchAgain", newSearchStr);
  226. resultsMap.put("notification", Context.getMessageSourceService().getMessage(
  227. "searchWidget.noResultsFoundFor", new Object[] { searchValue, newSearchStr },
  228. Context.getLocale()));
  229. }
  230. }
  231. }
  232.  
  233. //no results found and a number was in the search --
  234. //should check whether the check digit is correct.
  235. else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) {
  236.  
  237. //Looks through all the patient identifier validators to see if this type of identifier
  238. //is supported for any of them. If it isn't, then no need to warn about a bad check
  239. //digit. If it does match, then if any of the validators validates the check digit
  240. //successfully, then the user is notified that the identifier has been entered correctly.
  241. //Otherwise, the user is notified that the identifier was entered incorrectly.
  242.  
  243. PatientService ps = Context.getPatientService();
  244. Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
  245. boolean shouldWarnUser = true;
  246. boolean validCheckDigit = false;
  247. boolean identifierMatchesValidationScheme = false;
  248.  
  249. for (IdentifierValidator piv : pivs) {
  250. try {
  251. if (piv.isValid(searchValue)) {
  252. shouldWarnUser = false;
  253. validCheckDigit = true;
  254. }
  255. identifierMatchesValidationScheme = true;
  256. }
  257. catch (UnallowedIdentifierException e) {}
  258. }
  259.  
  260. if (identifierMatchesValidationScheme) {
  261. if (shouldWarnUser) {
  262. resultsMap.put("notification", "<b>"
  263. + Context.getMessageSourceService().getMessage("Patient.warning.inValidIdentifier")
  264. + "<b/>");
  265. } else if (validCheckDigit) {
  266. resultsMap.put("notification", "<b style=\"color:green;\">"
  267. + Context.getMessageSourceService().getMessage("Patient.message.validIdentifier")
  268. + "<b/>");
  269. }
  270. }
  271. } else {
  272. //ensure that count never exceeds this value because the API's service layer would never
  273. //return more than it since it is limited in the DAO layer
  274. if (maximumResults == null) {
  275. setMaximumResults(getMaximumSearchResults());
  276. }
  277. if (length != null && length > maximumResults) {
  278. length = maximumResults;
  279. }
  280.  
  281. if (patientCount > maximumResults) {
  282. patientCount = maximumResults;
  283. if (log.isDebugEnabled()) {
  284. log.debug("Limitng the size of matching patients to " + maximumResults);
  285. }
  286. }
  287. }
  288.  
  289. }
  290.  
  291. //if we have any matches or this isn't the first ajax call when the caller
  292. //requests for the count
  293. if (patientCount > 0 || !getMatchCount) {
  294. objectList = findBatchOfPatients(searchValue, false, start, length);
  295. }
  296.  
  297. resultsMap.put("count", patientCount);
  298. resultsMap.put("objectList", objectList);
  299. }
  300. catch (Exception e) {
  301. log.error("Error while searching for patients", e);
  302. objectList.clear();
  303. objectList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
  304. resultsMap.put("count", 0);
  305. resultsMap.put("objectList", objectList);
  306. }
  307. return resultsMap;
  308. }
  309.  
  310. public Map<String, Object> findCountAndPatients(String searchValue, Integer start,
  311. Integer length, boolean getMatchCount) throws APIException {
  312.  
  313. //Map to return
  314. Map<String, Object> resultsMap = new HashMap<String, Object>();
  315. Collection<Object> objectList = new Vector<Object>();
  316. try {
  317. PatientService ps = Context.getPatientService();
  318. int patientCount = 0;
  319. //if this is the first call
  320. if (getMatchCount) {
  321. patientCount += ps.getCountOfPatients(searchValue);
  322.  
  323. // if there are no results found and a number was not in the
  324. // search and this is the first call, then do a decapitated search:
  325. //trim each word down to the first three characters and search again
  326. if (patientCount == 0 && start == 0 && !searchValue.matches(".*\\d+.*")) {
  327. String[] names = searchValue.split(" ");
  328. StringBuilder newSearch = new StringBuilder("");
  329. for (String name : names) {
  330. if (name.length() > 3) {
  331. name = name.substring(0, 3);
  332. }
  333. newSearch.append(" ").append(name);
  334. }
  335.  
  336. String newSearchStr = newSearch.toString().trim();
  337. if (!newSearchStr.equals(searchValue)) {
  338. int newPatientCount = ps.getCountOfPatients(newSearchStr);
  339. if (newPatientCount > 0) {
  340. // Send a signal to the core search widget to search again against newSearch
  341. resultsMap.put("searchAgain", newSearchStr);
  342. resultsMap.put("notification", Context.getMessageSourceService().getMessage(
  343. "searchWidget.noResultsFoundFor", new Object[] { searchValue, newSearchStr },
  344. Context.getLocale()));
  345. }
  346. }
  347. }
  348.  
  349. //no results found and a number was in the search --
  350. //should check whether the check digit is correct.
  351. else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) {
  352.  
  353. //Looks through all the patient identifier validators to see if this type of identifier
  354. //is supported for any of them. If it isn't, then no need to warn about a bad check
  355. //digit. If it does match, then if any of the validators validates the check digit
  356. //successfully, then the user is notified that the identifier has been entered correctly.
  357. //Otherwise, the user is notified that the identifier was entered incorrectly.
  358.  
  359. Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
  360. boolean shouldWarnUser = true;
  361. boolean validCheckDigit = false;
  362. boolean identifierMatchesValidationScheme = false;
  363.  
  364. for (IdentifierValidator piv : pivs) {
  365. try {
  366. if (piv.isValid(searchValue)) {
  367. shouldWarnUser = false;
  368. validCheckDigit = true;
  369. }
  370. identifierMatchesValidationScheme = true;
  371. }
  372. catch (UnallowedIdentifierException e) {}
  373. }
  374.  
  375. if (identifierMatchesValidationScheme) {
  376. if (shouldWarnUser) {
  377. resultsMap.put("notification", "<b>"
  378. + Context.getMessageSourceService().getMessage("Patient.warning.inValidIdentifier")
  379. + "<b/>");
  380. } else if (validCheckDigit) {
  381. resultsMap.put("notification", "<b style=\"color:green;\">"
  382. + Context.getMessageSourceService().getMessage("Patient.message.validIdentifier")
  383. + "<b/>");
  384. }
  385. }
  386. } else {
  387. //ensure that count never exceeds this value because the API's service layer would never
  388. //return more than it since it is limited in the DAO layer
  389. if (maximumResults == null) {
  390. setMaximumResults(getMaximumSearchResults());
  391. }
  392. if (length != null && length > maximumResults) {
  393. length = maximumResults;
  394. }
  395.  
  396. if (patientCount > maximumResults) {
  397. patientCount = maximumResults;
  398. if (log.isDebugEnabled()) {
  399. log.debug("Limitng the size of matching patients to " + maximumResults);
  400. }
  401. }
  402. }
  403.  
  404. }
  405.  
  406. //if we have any matches or this isn't the first ajax call when the caller
  407. //requests for the count
  408. if (patientCount > 0 || !getMatchCount) {
  409. objectList = findBatchOfPatients(searchValue, false, start, length);
  410. }
  411.  
  412. resultsMap.put("count", patientCount);
  413. resultsMap.put("objectList", objectList);
  414. }
  415. catch (Exception e) {
  416. log.error("Error while searching for patients", e);
  417. objectList.clear();
  418. objectList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
  419. resultsMap.put("count", 0);
  420. resultsMap.put("objectList", objectList);
  421. }
  422. return resultsMap;
  423. }
  424.  
  425. /**
  426. * Convenience method for dwr/javascript to convert a patient id into a Patient object (or at
  427. * least into data about the patient)
  428. *
  429. * @param patientId the {@link Patient#getPatientId()} to match on
  430. * @return a truncated Patient object in the form of a PatientListItem
  431. */
  432. public PatientListItem getPatient(Integer patientId) {
  433. PatientService ps = Context.getPatientService();
  434. Patient p = ps.getPatient(patientId);
  435. PatientListItem pli = new PatientListItem(p);
  436. if (p != null && p.getAddresses() != null && p.getAddresses().size() > 0) {
  437. PersonAddress pa = (PersonAddress) p.getAddresses().toArray()[0];
  438. pli.setAddress1(pa.getAddress1());
  439. pli.setAddress2(pa.getAddress2());
  440. }
  441. return pli;
  442. }
  443.  
  444. /**
  445. * find all patients with duplicate attributes (searchOn)
  446. *
  447. * @param searchOn
  448. * @return list of patientListItems
  449. */
  450. public Vector<Object> findDuplicatePatients(String[] searchOn) {
  451. Vector<Object> patientList = new Vector<Object>();
  452.  
  453. try {
  454. List<String> options = new Vector<String>(searchOn.length);
  455. for (String s : searchOn) {
  456. options.add(s);
  457. }
  458.  
  459. List<Patient> patients = Context.getPatientService().getDuplicatePatientsByAttributes(options);
  460.  
  461. if (patients.size() > 200) {
  462. patients.subList(0, 200);
  463. }
  464.  
  465. for (Patient p : patients) {
  466. patientList.add(new PatientListItem(p));
  467. }
  468. }
  469. catch (Exception e) {
  470. log.error(e);
  471. patientList.add("Error while attempting to find duplicate patients - " + e.getMessage());
  472. }
  473.  
  474. return patientList;
  475. }
  476.  
  477. /**
  478. * Auto generated method comment
  479. *
  480. * @param patientId
  481. * @param identifierType
  482. * @param identifier
  483. * @param identifierLocationId
  484. * @return
  485. */
  486. public String addIdentifier(Integer patientId, String identifierType, String identifier, Integer identifierLocationId) {
  487.  
  488. String ret = "";
  489.  
  490. if (identifier == null || identifier.length() == 0) {
  491. return "PatientIdentifier.error.general";
  492. }
  493. PatientService ps = Context.getPatientService();
  494. LocationService ls = Context.getLocationService();
  495. Patient p = ps.getPatient(patientId);
  496. PatientIdentifierType idType = ps.getPatientIdentifierTypeByName(identifierType);
  497. //ps.updatePatientIdentifier(pi);
  498. Location location = ls.getLocation(identifierLocationId);
  499. log.debug("idType=" + identifierType + "->" + idType + " , location=" + identifierLocationId + "->" + location
  500. + " identifier=" + identifier);
  501. PatientIdentifier id = new PatientIdentifier();
  502. id.setIdentifierType(idType);
  503. id.setIdentifier(identifier);
  504. id.setLocation(location);
  505.  
  506. // in case we are editing, check to see if there is already an ID of this type and location
  507. for (PatientIdentifier previousId : p.getActiveIdentifiers()) {
  508. if (previousId.getIdentifierType().equals(idType) && previousId.getLocation().equals(location)) {
  509. log.debug("Found equivalent ID: [" + idType + "][" + location + "][" + previousId.getIdentifier()
  510. + "], about to remove");
  511. p.removeIdentifier(previousId);
  512. } else {
  513. if (!previousId.getIdentifierType().equals(idType)) {
  514. log.debug("Previous ID id type does not match: [" + previousId.getIdentifierType().getName() + "]["
  515. + previousId.getIdentifier() + "]");
  516. }
  517. if (!previousId.getLocation().equals(location)) {
  518. log.debug("Previous ID location is: " + previousId.getLocation());
  519. log.debug("New location is: " + location);
  520. }
  521. }
  522. }
  523.  
  524. p.addIdentifier(id);
  525.  
  526. try {
  527. ps.savePatient(p);
  528. }
  529. catch (InvalidIdentifierFormatException iife) {
  530. log.error(iife);
  531. ret = "PatientIdentifier.error.formatInvalid";
  532. }
  533. catch (InvalidCheckDigitException icde) {
  534. log.error(icde);
  535. ret = "PatientIdentifier.error.checkDigit";
  536. }
  537. catch (IdentifierNotUniqueException inue) {
  538. log.error(inue);
  539. ret = "PatientIdentifier.error.notUnique";
  540. }
  541. catch (DuplicateIdentifierException die) {
  542. log.error(die);
  543. ret = "PatientIdentifier.error.duplicate";
  544. }
  545. catch (InsufficientIdentifiersException iie) {
  546. log.error(iie);
  547. ret = "PatientIdentifier.error.insufficientIdentifiers";
  548. }
  549. catch (PatientIdentifierException pie) {
  550. log.error(pie);
  551. ret = "PatientIdentifier.error.general";
  552. }
  553.  
  554. return ret;
  555. }
  556.  
  557. /**
  558. * Auto generated method comment
  559. *
  560. * @param patientId
  561. * @param reasonForExitId
  562. * @param dateOfExit
  563. * @param causeOfDeath
  564. * @param otherReason
  565. * @return
  566. */
  567. public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
  568. Integer causeOfDeathConceptId, String otherReason) {
  569. log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
  570. String ret = "";
  571.  
  572. PatientService ps = Context.getPatientService();
  573. ConceptService cs = Context.getConceptService();
  574.  
  575. Patient patient = null;
  576. try {
  577. patient = ps.getPatient(patientId);
  578. }
  579. catch (Exception e) {
  580. patient = null;
  581. }
  582.  
  583. if (patient == null) {
  584. ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
  585. }
  586.  
  587. // Get the exit reason concept (if possible)
  588. Concept exitReasonConcept = null;
  589. try {
  590. exitReasonConcept = cs.getConcept(exitReasonId);
  591. }
  592. catch (Exception e) {
  593. exitReasonConcept = null;
  594. }
  595.  
  596. // Exit reason error handling
  597. if (exitReasonConcept == null) {
  598. ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
  599. }
  600.  
  601. // Parse the exit date
  602. Date exitDate = null;
  603. if (exitDateStr != null) {
  604. SimpleDateFormat sdf = Context.getDateFormat();
  605. try {
  606. exitDate = sdf.parse(exitDateStr);
  607. }
  608. catch (ParseException e) {
  609. exitDate = null;
  610. }
  611. }
  612.  
  613. // Exit date error handling
  614. if (exitDate == null) {
  615. ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
  616. }
  617.  
  618. // If all data is provided as expected
  619. if (patient != null && exitReasonConcept != null && exitDate != null) {
  620.  
  621. // need to check first if this is death or not
  622. String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
  623.  
  624. Concept patientDiedConcept = null;
  625. if (patientDiedConceptId != null) {
  626. patientDiedConcept = cs.getConcept(patientDiedConceptId);
  627. }
  628.  
  629. // If there is a concept for death in the dictionary
  630. if (patientDiedConcept != null) {
  631.  
  632. // If the exist reason == patient died
  633. if (exitReasonConcept.equals(patientDiedConcept)) {
  634.  
  635. Concept causeOfDeathConcept = null;
  636. try {
  637. causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
  638. }
  639. catch (Exception e) {
  640. causeOfDeathConcept = null;
  641. }
  642.  
  643. // Cause of death concept exists
  644. if (causeOfDeathConcept != null) {
  645. try {
  646. ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
  647. }
  648. catch (Exception e) {
  649. log.warn("Caught error", e);
  650. ret = "Internal error while trying to process patient death - unable to proceed. Cause: "
  651. + e.getMessage();
  652. }
  653. }
  654. // cause of death concept does not exist
  655. else {
  656. ret = "Unable to locate cause of death in dictionary - cannot proceed";
  657. }
  658. }
  659.  
  660. // Otherwise, we process this as an exit
  661. else {
  662. try {
  663. ps.exitFromCare(patient, exitDate, exitReasonConcept);
  664. }
  665. catch (Exception e) {
  666. log.warn("Caught error", e);
  667. ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
  668. + e.getMessage();
  669. }
  670. }
  671. }
  672.  
  673. // If the system does not recognize death as a concept, then we exit from care
  674. else {
  675. try {
  676. ps.exitFromCare(patient, exitDate, exitReasonConcept);
  677. }
  678. catch (Exception e) {
  679. log.warn("Caught error", e);
  680. ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
  681. + e.getMessage();
  682. }
  683. }
  684. log.debug("Exited from care, it seems");
  685. }
  686.  
  687. return ret;
  688. }
  689.  
  690. /**
  691. * Auto generated method comment
  692. *
  693. * @param patientId
  694. * @param locationId
  695. * @return
  696. */
  697. public String changeHealthCenter(Integer patientId, Integer locationId) {
  698. log.warn("Deprecated method in 'DWRPatientService.changeHealthCenter'");
  699.  
  700. String ret = "";
  701.  
  702. /*
  703.  
  704. if ( patientId != null && locationId != null ) {
  705. Patient patient = Context.getPatientService().getPatient(patientId);
  706. Location location = Context.getEncounterService().getLocation(locationId);
  707.  
  708. if ( patient != null && location != null ) {
  709. patient.setHealthCenter(location);
  710. Context.getPatientService().updatePatient(patient);
  711. }
  712. }
  713. */
  714.  
  715. return ret;
  716. }
  717.  
  718. /**
  719. * Creates an Allergy Item
  720. *
  721. * @param patientId
  722. * @param allergenId
  723. * @param type
  724. * @param pStartDate
  725. * @param severity
  726. * @param reactionId
  727. */
  728. public void createAllergy(Integer patientId, Integer allergenId, String type, String pStartDate, String severity,
  729. Integer reactionId) {
  730. Date startDate = parseDate(pStartDate);
  731.  
  732. Patient patient = Context.getPatientService().getPatient(patientId);
  733. Concept allergyConcept = Context.getConceptService().getConcept(allergenId);
  734. Concept reactionConcept = (reactionId == null) ? null : Context.getConceptService().getConcept(reactionId);
  735. AllergySeverity allergySeverity = StringUtils.isBlank(severity) ? null : AllergySeverity.valueOf(severity);
  736. AllergyType allergyType = StringUtils.isBlank(type) ? null : AllergyType.valueOf(type);
  737.  
  738. Allergy allergy = new Allergy(patient, allergyConcept, startDate, allergyType, reactionConcept, allergySeverity);
  739. Context.getPatientService().saveAllergy(allergy);
  740. }
  741.  
  742. /**
  743. * Save an Allergy
  744. *
  745. * @param activeListItemId
  746. * @param allergenId Concept ID
  747. * @param type
  748. * @param pStartDate
  749. * @param severity
  750. * @param reactionId
  751. */
  752. public void saveAllergy(Integer activeListItemId, Integer allergenId, String type, String pStartDate, String severity,
  753. Integer reactionId) {
  754. //get the allergy
  755. Allergy allergy = Context.getPatientService().getAllergy(activeListItemId);
  756. allergy.setAllergen(Context.getConceptService().getConcept(allergenId));
  757. allergy.setAllergyType(type);
  758. allergy.setStartDate(parseDate(pStartDate));
  759. allergy.setSeverity(severity);
  760. allergy.setReaction((reactionId == null) ? null : Context.getConceptService().getConcept(reactionId));
  761. Context.getPatientService().saveAllergy(allergy);
  762. }
  763.  
  764. /**
  765. * Resolve an allergy
  766. *
  767. * @param activeListId
  768. * @param resolved
  769. * @param reason
  770. * @param pEndDate
  771. */
  772. public void removeAllergy(Integer activeListId, String reason) {
  773. Allergy allergy = Context.getPatientService().getAllergy(activeListId);
  774. Context.getPatientService().removeAllergy(allergy, reason);
  775. }
  776.  
  777. /**
  778. * Voids the Allergy
  779. *
  780. * @param activeListId
  781. * @param reason
  782. */
  783. public void voidAllergy(Integer activeListId, String reason) {
  784. Allergy allergy = Context.getPatientService().getAllergy(activeListId);
  785. if (reason == null) {
  786. reason = "Error - user entered incorrect data from UI";
  787. }
  788. Context.getPatientService().voidAllergy(allergy, reason);
  789. }
  790.  
  791. /**
  792. * Creates a Problem Item
  793. *
  794. * @param patientId
  795. * @param problemId
  796. * @param status
  797. * @param pStartDate
  798. * @param comments
  799. */
  800. public void createProblem(Integer patientId, Integer problemId, String status, String pStartDate, String comments) {
  801. Patient patient = Context.getPatientService().getPatient(patientId);
  802. Concept problemConcept = Context.getConceptService().getConcept(problemId);
  803. ProblemModifier modifier = StringUtils.isBlank(status) ? null : ProblemModifier.valueOf(status);
  804.  
  805. Problem problem = new Problem(patient, problemConcept, parseDate(pStartDate), modifier, comments, null);
  806. Context.getPatientService().saveProblem(problem);
  807. }
  808.  
  809. /**
  810. * Saves the Problem
  811. *
  812. * @param activeListId
  813. * @param problemId
  814. * @param status
  815. * @param pStartDate
  816. * @param comments
  817. */
  818. public void saveProblem(Integer activeListId, Integer problemId, String status, String pStartDate, String comments) {
  819. //get the allergy
  820. Problem problem = Context.getPatientService().getProblem(activeListId);
  821. problem.setProblem(Context.getConceptService().getConcept(problemId));
  822. problem.setModifier(status);
  823. problem.setStartDate(parseDate(pStartDate));
  824. problem.setComments(comments);
  825. Context.getPatientService().saveProblem(problem);
  826. }
  827.  
  828. /**
  829. * Remove a problem, sets the end date
  830. *
  831. * @param activeListId
  832. * @param resolved
  833. * @param reason
  834. * @param pEndDate
  835. */
  836. public void removeProblem(Integer activeListId, String reason, String pEndDate) {
  837. Problem problem = Context.getPatientService().getProblem(activeListId);
  838. problem.setEndDate(parseDate(pEndDate));
  839.  
  840. Context.getPatientService().removeProblem(problem, reason);
  841. }
  842.  
  843. /**
  844. * Voids the Problem
  845. *
  846. * @param activeListId
  847. * @param reason
  848. */
  849. public void voidProblem(Integer activeListId, String reason) {
  850. Problem problem = Context.getPatientService().getProblem(activeListId);
  851. if (reason == null) {
  852. reason = "Error - user entered incorrect data from UI";
  853. }
  854. Context.getPatientService().voidProblem(problem, reason);
  855. }
  856.  
  857. /**
  858. * Simple utility method to parse the date object into the correct, local format
  859. *
  860. * @param date
  861. * @return
  862. */
  863. private Date parseDate(String date) {
  864. if (date != null) {
  865. SimpleDateFormat sdf = Context.getDateFormat();
  866. try {
  867. return sdf.parse(date);
  868. }
  869. catch (ParseException e) {}
  870. }
  871. return null;
  872. }
  873.  
  874. @Override
  875. public boolean supportsPropertyName(String propertyName) {
  876. return propertyName.equals(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS);
  877. }
  878.  
  879. @Override
  880. public void globalPropertyChanged(GlobalProperty newValue) {
  881. try {
  882. setMaximumResults(Integer.valueOf(newValue.getPropertyValue()));
  883. }
  884. catch (NumberFormatException e) {
  885. setMaximumResults(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE);
  886. }
  887. }
  888.  
  889. @Override
  890. public void globalPropertyDeleted(String propertyName) {
  891. setMaximumResults(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE);
  892. }
  893.  
  894. /**
  895. * Fetch the max results value from the global properties table
  896. *
  897. * @return Integer value for the person search max results global property
  898. */
  899. private static Integer getMaximumSearchResults() {
  900. try {
  901. return Integer.valueOf(Context.getAdministrationService().getGlobalProperty(
  902. OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS,
  903. String.valueOf(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE)));
  904. }
  905. catch (Exception e) {
  906. log.warn("Unable to convert the global property " + OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS
  907. + "to a valid integer. Returning the default "
  908. + OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE);
  909. }
  910.  
  911. return OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
  912. }
  913. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement