From 593056f82f30851879639c300e7ba2987467d18f Mon Sep 17 00:00:00 2001 From: pegahtah <47120870+pegahtah@users.noreply.github.com> Date: Tue, 22 Aug 2023 16:40:19 -0400 Subject: [PATCH] [DSM] Juniper's kitStatus endpoint PEPPER-841 (#2647) * PEPPER-841 Created StatusKitRoute and NonPepperStatusKitService to return the status of * PEPPER-841 more endpoints to call for kit status * PEPPER-841 added the get and post endpoints, and according methods in KitDao and KitDaoImpl, moved the error strings to KitResponse, created new methods in NonPepperStatusKitService * PEPPER-841 added the new POST endpoint * PEPPER-841 changed JsonTransformer to include null values in response removed extra space at the end of query conditions in KitDaoImpl Added more tests in NonPepperKitServiceTest Corrected some bugs in NonPepperStatusKitService Added more exception handling * PEPPER-841 Fixed the bug in the POST endpoint where result set was getting closed in StatusKitRoute and NonPepperStatusKitService and getKitsByKitId in KitDaoImpl Added more tests * PEPPER-841 removed unused coded and renamed code * PEPPER-841 reverted back JsonTransformer class , changed endpoints names to have RESTful standards,created a KitStatusDao class and moved my changes from KitDao into that, also deleted KitDaoMock.java changed Strings in KitResponse to enums, added checks for request methods in StatusKitRoute, changed NonPepperKitStatus to NonPepperKitStatusDto * PEPPER-1052 Added JuniperSetupUtil with methods to create a fake Juniper study and to delete all of the added data later. made changes to KitStatusTest to ame sure it can still run * PEPPER-1052 fixed JuniperKitCreationTest to inherit DbTxnBaseTest * PEPPER-1052 tweaked main-config.yml to have DSM config in it as well * PEPPER-1052 changed secret name * PEPPER-1052 changed main-config.yml * PEPPER-1052 adding env variable * PEPPER-1052 removed env variable * PEPPER-1052 adding PEPPER-* to branch name possibilities * PEPPER-1052 fixed java code to get the VM variable * PEPPER-1052 added instructions on how to run tests * PEPPER-1023 changing the docker image version to use in main-config.yml * PEPPER-1023 checking if config is being read appropriately * PEPPER-1052 changing the secret ci gets * PEPPER-1052 adding more logs and more config reads * PEPPER-1052 moved checkAddress to from NonPepperKitCreationService to EasyPostUtil, changed pom to add Mockito and used Mockito to mock EasyPostUtil, removed reading dsm secrets from both main-config.yml and JuniperSetupUtil * PEPPER-1052 checking something in ci * PEPPER-1052 moving query into classes * PEPPER-1052 removing old comment * PEPPER-814 PR comments addressed * PEPPER-814 PR comments addressed in tests, also PEPPER-1023 * PEPPER-814 PR comments addressed in tests, addressed as many sonar errors as I could * PEPPER-814 PR comments addressed in tests,refactored JuniperSetupUtil * PEPPER-814 PR comments addressed, merged KitResponseError.java and StatusKitResponse.java in KitResponse and removed those two classes, removed unused and committed out code * PEPPER-814 fixed missed value * PEPPER-814 added comments to EasyPostUtil, added "juniper_study" to DBConstants as a static String, changed makeKitResponseError and makeKitStatusResponse to static methods, added a helper method to StatusKitRoute * PEPPER-841 PR comments applied, fixed the problem in StatusKitRoute and renamed method to deleteJuniperInstanceAndSettings in JuniperSetupUtil * PEPPER-841 PR comments applied, renamed setupJuniperInstance to setupJuniperInstanceAndSettings in JuniperSetupUtil, fixed the return of error true in times of success in NonPepperKitCreationService and fixed url for KIT_STATUS_PARTICIPANT_ID * PEPPER-841 fix for tests failing * PEPPER-841 fix for tests failing * PEPPER-841 added logs for tests and fixed a bug in logging in NonPepperKitCreationService * PEPPER-841 testing a theory * PEPPER-841 testing a theory * Testing a theory * PEPPER-841 testing a theory of why tests do not pass --- .circleci/main-config.yml | 4 +- .../org/broadinstitute/dsm/DSMServer.java | 13 +- .../dsm/db/KitRequestShipping.java | 27 +- .../broadinstitute/dsm/db/dao/kit/KitDao.java | 2 +- .../dsm/db/dao/kit/KitDaoImpl.java | 33 +- .../dsm/db/dao/kit/KitStatusDao.java | 170 ++++++++++ .../dsm/db/dao/user/UserDao.java | 37 +++ .../nonPepperKit/NonPepperKitStatusDto.java | 188 +++++++++++ .../dsm/exception/DSMBadRequestException.java | 1 - .../dsm/exception/DsmInternalError.java | 4 + .../model/nonpepperkit/JuniperKitStatus.java | 7 - .../dsm/model/nonpepperkit/KitResponse.java | 66 +++- .../NonPepperKitCreationService.java | 143 ++------ .../NonPepperStatusKitService.java | 103 ++++++ .../dsm/route/JuniperShipKitRoute.java | 51 --- .../dsm/route/KitUploadRoute.java | 2 +- .../route/juniper/JuniperShipKitRoute.java | 87 +++++ .../dsm/route/juniper/StatusKitRoute.java | 80 +++++ .../statics/ApplicationConfigConstants.java | 2 - .../dsm/statics/DBConstants.java | 12 + .../dsm/statics/RequestParameter.java | 3 + .../broadinstitute/dsm/statics/RoutePath.java | 8 + .../broadinstitute/dsm/util/EasyPostUtil.java | 59 +++- .../src/main/resources/application.conf | 14 - .../broadinstitute/dsm/RouteTestSample.java | 2 +- .../JuniperKitCreationStatusTest.java | 308 ++++++++++++++++++ .../juniperkits/JuniperKitCreationTest.java | 226 ------------- .../dsm/juniperkits/JuniperSetupUtil.java | 307 +++++++++++++++++ .../juniperkits/NonPepperKitServiceTest.java | 75 +++++ .../dsm/model/kit/KitDaoMock.java | 99 ------ .../dsm/util/tools/CreateLabelTool.java | 2 +- pepper-apis/parent-pom.xml | 2 +- 32 files changed, 1574 insertions(+), 563 deletions(-) create mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitStatusDao.java create mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dto/kit/nonPepperKit/NonPepperKitStatusDto.java delete mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/JuniperKitStatus.java create mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperStatusKitService.java delete mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/JuniperShipKitRoute.java create mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/JuniperShipKitRoute.java create mode 100644 pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/StatusKitRoute.java create mode 100644 pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationStatusTest.java delete mode 100644 pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationTest.java create mode 100644 pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperSetupUtil.java create mode 100644 pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/NonPepperKitServiceTest.java delete mode 100644 pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/model/kit/KitDaoMock.java diff --git a/.circleci/main-config.yml b/.circleci/main-config.yml index 7c30ef8bfd..e8aacc14d1 100644 --- a/.circleci/main-config.yml +++ b/.circleci/main-config.yml @@ -9,7 +9,7 @@ references: tcell_config_file: &tcell_config_file tcell_agent.config ci_support_image: &ci_support_image - broadinstitute/study-server-build:2022-06-01A + broadinstitute/study-server-build:2023-03-28C root_path: &root_path /home/circleci repo_path: &repo_path @@ -48,7 +48,7 @@ references: executors: test-executor: docker: - - image: broadinstitute/study-server-build:java-2022-06-01A + - image: broadinstitute/study-server-build:2023-03-28C # start pubsub emulator - image: broadinstitute/study-server-build:pubsub-1 - image: cimg/redis:5.0 diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/DSMServer.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/DSMServer.java index c68b6cae4e..9bca686be0 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/DSMServer.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/DSMServer.java @@ -67,6 +67,7 @@ import org.broadinstitute.dsm.jobs.PubSubLookUp; import org.broadinstitute.dsm.log.SlackAppender; import org.broadinstitute.dsm.model.nonpepperkit.NonPepperKitCreationService; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperStatusKitService; import org.broadinstitute.dsm.pubsub.AntivirusScanningStatusListener; import org.broadinstitute.dsm.pubsub.DSMtasksSubscription; import org.broadinstitute.dsm.pubsub.MercuryOrderStatusListener; @@ -96,7 +97,6 @@ import org.broadinstitute.dsm.route.FieldSettingsRoute; import org.broadinstitute.dsm.route.FilterRoute; import org.broadinstitute.dsm.route.InstitutionRoute; -import org.broadinstitute.dsm.route.JuniperShipKitRoute; import org.broadinstitute.dsm.route.KitAuthorizationRoute; import org.broadinstitute.dsm.route.KitDeactivationRoute; import org.broadinstitute.dsm.route.KitDiscardRoute; @@ -127,6 +127,8 @@ import org.broadinstitute.dsm.route.admin.UserRoute; import org.broadinstitute.dsm.route.dashboard.NewDashboardRoute; import org.broadinstitute.dsm.route.familymember.AddFamilyMemberRoute; +import org.broadinstitute.dsm.route.juniper.JuniperShipKitRoute; +import org.broadinstitute.dsm.route.juniper.StatusKitRoute; import org.broadinstitute.dsm.route.kit.KitFinalScanRoute; import org.broadinstitute.dsm.route.kit.KitInitialScanRoute; import org.broadinstitute.dsm.route.kit.KitTrackingScanRoute; @@ -586,8 +588,13 @@ protected void setupCustomRouting(@NonNull Config cfg) { get(apiRoot + RoutePath.CLINICAL_KIT_ENDPOINT, new ClinicalKitsRoute(notificationUtil), new JsonTransformer()); if (!cfg.getBoolean("ui.production")) { - NonPepperKitCreationService nonPepperKitCreationService = new NonPepperKitCreationService(); - post(apiRoot + RoutePath.SHIP_KIT_ENDPOINT, new JuniperShipKitRoute(nonPepperKitCreationService), new JsonTransformer()); + post(apiRoot + RoutePath.SHIP_KIT_ENDPOINT, new JuniperShipKitRoute(), new JsonTransformer()); + + StatusKitRoute statusKitRoute = new StatusKitRoute(); + get(apiRoot + RoutePath.KIT_STATUS_ENDPOINT_STUDY, statusKitRoute, new JsonTransformer()); + get(apiRoot + RoutePath.KIT_STATUS_ENDPOINT_JUNIPER_KIT_ID, statusKitRoute, new JsonTransformer()); + get(apiRoot + RoutePath.KIT_STATUS_ENDPOINT_PARTICIPANT_ID, statusKitRoute, new JsonTransformer()); + post(apiRoot + RoutePath.KIT_STATUS_ENDPOINT_KIT_IDS, statusKitRoute, new JsonTransformer()); } if (!cfg.getBoolean("ui.production")) { diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/KitRequestShipping.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/KitRequestShipping.java index 46c86ac592..ddb36cb85c 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/KitRequestShipping.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/KitRequestShipping.java @@ -197,6 +197,13 @@ public class KitRequestShipping extends KitRequest implements HasDdpInstanceId { + "denial_reason = ?, authorized_by = ? WHERE kit.dsm_kit_request_id = ?"; private static final String MARK_ORDER_AS_TRANSMITTED = "update ddp_kit_request set order_transmitted_at = ? where external_order_number = ?"; + + private static final String GET_COUNT_KITS_WITH_SAME_COLLABORATOR_SAMPLE_ID_AND_KIT_TYPE = + " SELECT count(*) kitRequestCount from ddp_kit_request where bsp_collaborator_sample_id REGEXP \"^%1\" and kit_type_id = ?"; + + private static final String GET_FOUND_IF_KIT_WITH_DDP_LABEL_ALREADY_EXISTS = + " select 1 from ddp_kit_request req where req.ddp_label = ? "; + private static final String QUEUE = "queue"; private static final String ERROR = "error"; private static final String SENT = "sent"; @@ -924,6 +931,8 @@ public static void addKitRequests(@NonNull String instanceId, @NonNull String ki // called by // 1. hourly job to add kit requests into db // 2. kit upload + // 3. Juniper shipKit route + // BSP and Mercury dummy kit routes in non-prod public static String writeRequest(@NonNull String instanceId, @NonNull String ddpKitRequestId, int kitTypeId, @NonNull String ddpParticipantId, String bspCollaboratorParticipantId, String collaboratorSampleId, @NonNull String createdBy, String addressIdTo, String errorMessage, String externalOrderNumber, @@ -991,7 +1000,7 @@ public static String writeRequest(@NonNull String instanceId, @NonNull String dd DDPInstanceDto ddpInstanceDto = new DDPInstanceDao().getDDPInstanceByInstanceId(Integer.valueOf(ddpInstance.getDdpInstanceId())).orElseThrow(); - // update ES only if it's a pepper study + // update ES only if it's a pepper study, not for Darwin's arc or Juniper studies if (ddpInstanceDto.isESUpdatePossible()) { try { UpsertPainlessFacade.of(DBConstants.DDP_KIT_REQUEST_ALIAS, kitRequestShipping, ddpInstanceDto, @@ -999,11 +1008,9 @@ public static String writeRequest(@NonNull String instanceId, @NonNull String dd Exportable.getParticipantGuid(ddpParticipantId, ddpInstance.getParticipantIndexES()), new PutToNestedScriptBuilder()).export(); } catch (Exception e) { - //This error will trigger on studies with no participants, this skips - //the error log if that is the reason for the upsert failure. - logger.error(String.format("Error inserting newly created kit request shipping with dsm kit request id: %s in " + logger.error(String.format("Error inserting newly created kit request shipping with dsm kit request id: %s in " + "ElasticSearch", kitRequestShipping.getDsmKitRequestId())); - e.printStackTrace(); + e.printStackTrace(); } } @@ -1271,8 +1278,7 @@ public static String generateBspSampleID(@NonNull Connection conn, String collab } public static int getKitCounter(@NonNull Connection conn, String collaboratorSampleId, int kitTypeId) { - String query = DSMConfig.getSqlFromConfig(ApplicationConfigConstants.GET_COUNT_KITS_WITH_SAME_COLLABORATOR_SAMPLE_ID_AND_KIT_TYPE) - .replace("%1", collaboratorSampleId); + String query = GET_COUNT_KITS_WITH_SAME_COLLABORATOR_SAMPLE_ID_AND_KIT_TYPE.replace("%1", collaboratorSampleId); try (PreparedStatement stmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)) { stmt.setInt(1, kitTypeId); try (ResultSet rs = stmt.executeQuery()) { @@ -1294,8 +1300,7 @@ public static int getKitCounter(@NonNull Connection conn, String collaboratorSam * and checking it against db if unique */ public static String generateDdpLabelID() { - return generateDdpLabelID(15, - DSMConfig.getSqlFromConfig(ApplicationConfigConstants.GET_FOUND_IF_KIT_WITH_DDP_LABEL_ALREADY_EXISTS)); + return generateDdpLabelID(15, GET_FOUND_IF_KIT_WITH_DDP_LABEL_ALREADY_EXISTS); } public static String generateDdpLabelID(int length, String query) { @@ -1355,7 +1360,7 @@ public static Address getToAddressId(@NonNull EasyPostUtil easyPostUtil, KitRequ DDPParticipant participant, DDPInstanceDto ddpInstanceDto) throws Exception { Address toAddress = null; if (addressId == null && participant == null) { //if both are set to null then it is return label! - toAddress = easyPostUtil.createBroadAddress(kitRequestSettings.getReturnName(), kitRequestSettings.getReturnStreet1(), + toAddress = easyPostUtil.createAddressWithoutValidation(kitRequestSettings.getReturnName(), kitRequestSettings.getReturnStreet1(), kitRequestSettings.getReturnStreet2(), kitRequestSettings.getReturnCity(), kitRequestSettings.getReturnZip(), kitRequestSettings.getReturnState(), kitRequestSettings.getReturnCountry(), kitRequestSettings.getPhone()); } else { @@ -1428,7 +1433,7 @@ public static Shipment getShipment(@NonNull EasyPostUtil easyPostUtil, String bi if (kitType != null) { Address returnAddress = - easyPostUtil.createBroadAddress(kitRequestSettings.getReturnName(), kitRequestSettings.getReturnStreet1(), + easyPostUtil.createAddressWithoutValidation(kitRequestSettings.getReturnName(), kitRequestSettings.getReturnStreet1(), kitRequestSettings.getReturnStreet2(), kitRequestSettings.getReturnCity(), kitRequestSettings.getReturnZip(), kitRequestSettings.getReturnState(), kitRequestSettings.getReturnCountry(), kitRequestSettings.getPhone()); diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDao.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDao.java index 205932d2ca..8ba375bf76 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDao.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDao.java @@ -32,10 +32,10 @@ public interface KitDao extends Dao { Integer deleteKit(Long kitId); Optional getKitByDdpLabel(String ddpLabel, String kitLabel); + Optional> getSubkitsByDdpLabel(String ddpLabel, String kitLabel); List getKitsByHruid(String hruid); Optional updateKitLabel(KitRequestShipping kitRequestShipping); - } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDaoImpl.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDaoImpl.java index c94dbceddb..8ad3b11619 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDaoImpl.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitDaoImpl.java @@ -26,8 +26,6 @@ public class KitDaoImpl implements KitDao { - private static final Logger logger = LoggerFactory.getLogger(KitDaoImpl.class); - public static final String SQL_SELECT_KIT_REQUEST = "SELECT * FROM ( SELECT req.upload_reason, kt.kit_type_name, ddp_site.instance_name, ddp_site.ddp_instance_id, " + "ddp_site.base_url, ddp_site.auth0_token, ddp_site.billing_reference, " @@ -56,7 +54,7 @@ public class KitDaoImpl implements KitDao { public static final String KIT_BY_KIT_ID = " and kit.dsm_kit_id = ?"; public static final String KIT_BY_HRUID = " and bsp_collaborator_participant_id like ? AND not kit_complete <=> 1 " + "AND deactivated_date is null"; - + private static final Logger logger = LoggerFactory.getLogger(KitDaoImpl.class); private static final String SQL_IS_BLOOD_KIT_QUERY = "SELECT kt.requires_insert_in_kit_tracking AS found " + "FROM ddp_kit_request request " + "LEFT JOIN kit_type kt on (kt.kit_type_id = request.kit_type_id) " @@ -96,18 +94,20 @@ public class KitDaoImpl implements KitDao { + "LEFT JOIN ddp_kit_request_settings AS ks ON ks.kit_type_id = req.kit_type_id AND ks.ddp_instance_id = req.ddp_instance_id " + "WHERE req.ddp_label = ?"; - private static final String SQL_GET_SUB_KIT_BY_DDP_LABEL = "SELECT req.ddp_kit_request_id, req.ddp_instance_id, req.ddp_kit_request_id, " - + "req.kit_type_id, req.bsp_collaborator_participant_id, req.bsp_collaborator_sample_id, req.ddp_participant_id, " - + "req.ddp_label, req.created_by, req.created_date, req.external_order_number, " - + "req.external_order_date, req.external_order_status, req.external_response, req.upload_reason, " - + "req.order_transmitted_at, req.dsm_kit_request_id, kit.kit_label, kit.dsm_kit_id," - + "kt.requires_insert_in_kit_tracking, kt.kit_type_name, track.tracking_id, ks.kit_label_prefix, ks.kit_label_length " - + "FROM ddp_kit as kit " - + "LEFT JOIN ddp_kit_request AS req ON req.dsm_kit_request_id = kit.dsm_kit_request_id " - + "LEFT JOIN ddp_kit_tracking AS track ON track.kit_label = ?" - + "LEFT JOIN kit_type AS kt ON kt.kit_type_id = req.kit_type_id " - + "LEFT JOIN ddp_kit_request_settings AS ks ON ks.kit_type_id = req.kit_type_id AND ks.ddp_instance_id = req.ddp_instance_id " - + "WHERE ( req.ddp_label = ? or ddp_label like ? )"; + private static final String SQL_GET_SUB_KIT_BY_DDP_LABEL = + "SELECT req.ddp_kit_request_id, req.ddp_instance_id, req.ddp_kit_request_id, " + + "req.kit_type_id, req.bsp_collaborator_participant_id, req.bsp_collaborator_sample_id, req.ddp_participant_id, " + + "req.ddp_label, req.created_by, req.created_date, req.external_order_number, " + + "req.external_order_date, req.external_order_status, req.external_response, req.upload_reason, " + + "req.order_transmitted_at, req.dsm_kit_request_id, kit.kit_label, kit.dsm_kit_id," + + "kt.requires_insert_in_kit_tracking, kt.kit_type_name, track.tracking_id, ks.kit_label_prefix, ks.kit_label_length " + + "FROM ddp_kit as kit " + + "LEFT JOIN ddp_kit_request AS req ON req.dsm_kit_request_id = kit.dsm_kit_request_id " + + "LEFT JOIN ddp_kit_tracking AS track ON track.kit_label = ?" + + "LEFT JOIN kit_type AS kt ON kt.kit_type_id = req.kit_type_id " + + + "LEFT JOIN ddp_kit_request_settings AS ks ON ks.kit_type_id = req.kit_type_id AND ks.ddp_instance_id = req.ddp_instance_id " + + "WHERE ( req.ddp_label = ? or ddp_label like ? )"; private static final String INSERT_KIT = "INSERT INTO " + "ddp_kit " @@ -569,7 +569,7 @@ public Optional insertKitTracking(KitRequestShipping kitRequestShippi return dbVals; }); if (Objects.nonNull(results.resultValue)) { - result = Optional.ofNullable((ScanError)results.resultValue); + result = Optional.ofNullable((ScanError) results.resultValue); } return result; } @@ -666,4 +666,5 @@ public boolean hasKitReceived(Connection connection, String ddpParticipantId) { } return false; } + } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitStatusDao.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitStatusDao.java new file mode 100644 index 0000000000..3f4f94d94d --- /dev/null +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/kit/KitStatusDao.java @@ -0,0 +1,170 @@ +package org.broadinstitute.dsm.db.dao.kit; + +import static org.broadinstitute.ddp.db.TransactionWrapper.inTransaction; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.broadinstitute.dsm.db.DDPInstance; +import org.broadinstitute.dsm.db.dao.Dao; +import org.broadinstitute.dsm.db.dto.kit.nonPepperKit.NonPepperKitStatusDto; +import org.broadinstitute.dsm.db.dto.user.UserDto; +import org.broadinstitute.dsm.exception.DsmInternalError; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperStatusKitService; +import org.broadinstitute.dsm.statics.DBConstants; +import org.broadinstitute.lddp.db.SimpleResult; + +public class KitStatusDao implements Dao { + + private static final String SELECT_KIT_STATUS = + " SELECT req.*, k.*, discard.*, tracking.tracking_id as return_tracking_number, tracking.scan_by as tracking_scan_by, " + + " tracking.scan_date as tracking_scan_date FROM ddp_kit_request req " + + " LEFT JOIN ddp_kit k on (k.dsm_kit_request_id = req.dsm_kit_request_id) " + + " LEFT JOIN ddp_kit_discard discard on (discard.dsm_kit_request_id = req.dsm_kit_request_id) " + + " LEFT JOIN ddp_kit_tracking tracking on (tracking.kit_label = k.kit_label) "; + + private static final String BY_INSTANCE_ID = " WHERE ddp_instance_id = ?"; + private static final String BY_JUNIPER_KIT_ID = " WHERE ddp_kit_request_id = ?"; + private static final String BY_PARTICIPANT_ID = " WHERE ddp_participant_id = ?"; + + @Override + public int create(NonPepperKitStatusDto nonPepperKitStatusDto) { + return 0; + } + + @Override + public int delete(int id) { + return 0; + } + + @Override + public Optional get(long id) { + return Optional.empty(); + } + + public List getKitsByInstanceId(DDPInstance ddpInstance, Map users) { + List list = new ArrayList<>(); + BuildNonPepperKitStatusDto builder = new BuildNonPepperKitStatusDto(); + SimpleResult simpleResult = inTransaction(conn -> { + SimpleResult dbVals = new SimpleResult(); + try (PreparedStatement stmt = conn.prepareStatement(SELECT_KIT_STATUS.concat(BY_INSTANCE_ID))) { + stmt.setString(1, ddpInstance.getDdpInstanceId()); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + list.add(builder.build(rs, users)); + } + } catch (Exception ex) { + dbVals.resultException = new Exception(String.format("Error getting kits for %s", ddpInstance.getDdpInstanceId())); + } + return dbVals; + }); + if (simpleResult.resultException != null) { + throw new DsmInternalError(simpleResult.resultException); + } + return list; + + } + + public List getKitsByJuniperKitId(String juniperKitId, Map users) { + List list = new ArrayList<>(); + BuildNonPepperKitStatusDto builder = new BuildNonPepperKitStatusDto(); + SimpleResult simpleResult = inTransaction(conn -> { + SimpleResult dbVals = new SimpleResult(); + try (PreparedStatement stmt = conn.prepareStatement(SELECT_KIT_STATUS.concat(BY_JUNIPER_KIT_ID))) { + stmt.setString(1, juniperKitId); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + list.add(builder.build(rs, users)); + } + } catch (Exception ex) { + dbVals.resultException = new Exception(String.format("Error getting kits with juniper kit id %s", juniperKitId)); + } + return dbVals; + }); + if (simpleResult.resultException != null) { + throw new DsmInternalError(simpleResult.resultException); + } + return list; + } + + public List getKitsByParticipantId(String participantId, Map users) { + List list = new ArrayList<>(); + BuildNonPepperKitStatusDto builder = new BuildNonPepperKitStatusDto(); + SimpleResult simpleResult = inTransaction(conn -> { + SimpleResult dbVals = new SimpleResult(); + try (PreparedStatement stmt = conn.prepareStatement(SELECT_KIT_STATUS.concat(BY_PARTICIPANT_ID))) { + stmt.setString(1, participantId); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + list.add(builder.build(rs, users)); + } + } catch (Exception ex) { + dbVals.resultException = new Exception(String.format("Error getting kits with participant id %s", participantId)); + } + return dbVals; + }); + if (simpleResult.resultException != null) { + throw new DsmInternalError(simpleResult.resultException); + } + return list; + } + + public List getKitsByKitIdArray(String[] kitIdsArray, Map users) { + List list = new ArrayList<>(); + for (String kitId : kitIdsArray) { + List listForKitId = this.getKitsByJuniperKitId(kitId, users); + list.addAll(listForKitId); + } + return list; + } + + private static class BuildNonPepperKitStatusDto { + public NonPepperKitStatusDto build(ResultSet foundKitResults, Map users) throws DsmInternalError { + try { + return new NonPepperKitStatusDto.Builder() + .withJuniperKitId(foundKitResults.getString(DBConstants.DDP_KIT_REQUEST_ID)) + .withDsmShippingLabel(foundKitResults.getString(DBConstants.DSM_LABEL)) + .withParticipantId(foundKitResults.getString(DBConstants.DDP_PARTICIPANT_ID)) + .withReceiveBy(foundKitResults.getString(DBConstants.RECEIVE_BY)) + .withDeactivationReason(foundKitResults.getString(DBConstants.DEACTIVATION_REASON)) + .withTrackingNumber(foundKitResults.getString(DBConstants.TRACKING_TO_ID)) + .withReturnTrackingNumber(foundKitResults.getString(DBConstants.RETURN_TRACKING_NUMBER)) + .withError(foundKitResults.getBoolean(DBConstants.ERROR)) + .withErrorMessage(foundKitResults.getString(DBConstants.ERROR_MESSAGE)) + .withLabelDate( + NonPepperStatusKitService.convertTimeStringIntoTimeStamp(foundKitResults.getLong(DBConstants.LABEL_DATE))) + .withLabelByEmail( + NonPepperStatusKitService.getUserEmailForFields(foundKitResults.getString(DBConstants.LABEL_BY), users)) + .withScanDate( + NonPepperStatusKitService.convertTimeStringIntoTimeStamp( + foundKitResults.getLong(DBConstants.DSM_SCAN_DATE))) + .withScanByEmail( + NonPepperStatusKitService.getUserEmailForFields(foundKitResults.getString(DBConstants.SCAN_BY), users)) + .withReceiveDate( + NonPepperStatusKitService.convertTimeStringIntoTimeStamp( + foundKitResults.getLong(DBConstants.DSM_RECEIVE_DATE))) + .withDeactivationDate(NonPepperStatusKitService.convertTimeStringIntoTimeStamp( + foundKitResults.getLong(DBConstants.DSM_DEACTIVATED_DATE))) + .withDeactivationByEmail( + NonPepperStatusKitService.getUserEmailForFields(foundKitResults.getString(DBConstants.DEACTIVATED_BY), + users)) + .withTrackingScanBy( + NonPepperStatusKitService.getUserEmailForFields(foundKitResults.getString(DBConstants.TRACKING_SCAN_BY), + users)) + .withDiscardDate( + NonPepperStatusKitService.convertTimeStringIntoTimeStamp(foundKitResults.getLong(DBConstants.DISCARD_DATE))) + .withDiscardBy( + NonPepperStatusKitService.getUserEmailForFields(foundKitResults.getString(DBConstants.DISCARD_BY), users)) + .build(); + } catch (SQLException e) { + throw new DsmInternalError("Error building the NonPepperKitStatusDto object from resultSet", e); + } + } + + } +} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/user/UserDao.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/user/UserDao.java index 4f40736e79..f42a93b7cc 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/user/UserDao.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dao/user/UserDao.java @@ -6,6 +6,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import lombok.NonNull; @@ -34,6 +36,9 @@ public class UserDao implements Dao { "SELECT user.user_id, user.name, user.email, user.phone_number, user.is_active FROM access_user user " + "WHERE user.user_id = ?"; + private static final String SQL_SELECT_ALL_USERS = + "SELECT user.user_id, user.name, user.email, user.phone_number, user.is_active FROM access_user user"; + public Optional getUserByEmail(@NonNull String email) { SimpleResult results = inTransaction((conn) -> { SimpleResult dbVals = new SimpleResult(); @@ -141,4 +146,36 @@ public int delete(int id) { } return (int) simpleResult.resultValue; } + + /** + * generates a map of all of the users in the DSM, + * returns both active and deactivated users. + * @return Map instance, key is the user id and value is UserDto + * */ + public static Map selectAllUsers() { + Map users = new HashMap<>(); + SimpleResult results = inTransaction((conn) -> { + SimpleResult dbVals = new SimpleResult(); + try (PreparedStatement stmt = conn.prepareStatement(SQL_SELECT_ALL_USERS)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + UserDto user = new UserDto(rs.getInt(USER_ID), + rs.getString(NAME), + rs.getString(EMAIL), + rs.getString(PHONE_NUMBER), + rs.getInt(IS_ACTIVE)); + users.put(user.getId(), user); + } + } + } catch (SQLException ex) { + dbVals.resultException = ex; + } + return dbVals; + }); + + if (results.resultException != null) { + throw new DsmInternalError("Error getting list of all users ", results.resultException); + } + return users; + } } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dto/kit/nonPepperKit/NonPepperKitStatusDto.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dto/kit/nonPepperKit/NonPepperKitStatusDto.java new file mode 100644 index 0000000000..26c4c66445 --- /dev/null +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/db/dto/kit/nonPepperKit/NonPepperKitStatusDto.java @@ -0,0 +1,188 @@ +package org.broadinstitute.dsm.db.dto.kit.nonPepperKit; + +import lombok.Getter; + +/** +* Represents the various statuses a kit can take in their time in DSM. + * From being new to being received. Each of the fields respond to + * one of the kit's variables +* **/ +@Getter +public class NonPepperKitStatusDto { + Boolean error; + private String juniperKitId; + private String dsmShippingLabel; + private String participantId; + private String labelDate; + private String labelByEmail; + private String scanDate; + private String scanByEmail; + private String receiveDate; + private String receiveBy; + private String deactivationDate; + private String deactivationByEmail; + private String deactivationReason; + private String trackingNumber; + private String returnTrackingNumber; + private String trackingScanBy; + private String errorMessage; + private String discardDate; + private String discardBy; + + public NonPepperKitStatusDto() { + } + + /** + * Creates a NonPepperKitStatusDto from a builder + * */ + public NonPepperKitStatusDto(Builder builder) { + this.juniperKitId = builder.juniperKitId; + this.dsmShippingLabel = builder.dsmShippingLabel; + this.participantId = builder.participantId; + this.labelDate = builder.labelDate; + this.labelByEmail = builder.labelByEmail; + this.scanDate = builder.scanDate; + this.scanByEmail = builder.scanByEmail; + this.receiveDate = builder.receiveDate; + this.receiveBy = builder.receiveBy; + this.deactivationDate = builder.deactivationDate; + this.deactivationByEmail = builder.deactivationByEmail; + this.deactivationReason = builder.deactivationReason; + this.trackingNumber = builder.trackingNumber; + this.returnTrackingNumber = builder.returnTrackingNumber; + this.trackingScanBy = builder.trackingScanBy; + this.error = builder.error; + this.errorMessage = builder.errorMessage; + this.discardDate = builder.discardDate; + this.discardBy = builder.discardBy; + } + + public static class Builder { + + private Boolean error; + private String juniperKitId; + private String dsmShippingLabel; + private String participantId; + private String labelDate; + private String labelByEmail; + private String scanDate; + private String scanByEmail; + private String receiveDate; + private String receiveBy; + private String deactivationDate; + private String deactivationByEmail; + private String deactivationReason; + private String trackingNumber; + private String returnTrackingNumber; + private String trackingScanBy; + private String errorMessage; + private String discardDate; + private String discardBy; + + + public Builder() { + } + + public Builder withJuniperKitId(String juniperKitId) { + this.juniperKitId = juniperKitId; + return this; + } + + public Builder withDsmShippingLabel(String dsmShippingLabel) { + this.dsmShippingLabel = dsmShippingLabel; + return this; + } + + public Builder withParticipantId(String participantId) { + this.participantId = participantId; + return this; + } + + public Builder withLabelDate(String labelDate) { + this.labelDate = labelDate; + return this; + } + + public Builder withLabelByEmail(String labelByEmail) { + this.labelByEmail = labelByEmail; + return this; + } + + public Builder withScanDate(String scanDate) { + this.scanDate = scanDate; + return this; + } + + public Builder withScanByEmail(String scanByEmail) { + this.scanByEmail = scanByEmail; + return this; + } + + public Builder withReceiveDate(String receiveDate) { + this.receiveDate = receiveDate; + return this; + } + + public Builder withReceiveBy(String receiveBy) { + this.receiveBy = receiveBy; + return this; + } + + public Builder withDeactivationDate(String deactivationDate) { + this.deactivationDate = deactivationDate; + return this; + } + + public Builder withDeactivationByEmail(String deactivationByEmail) { + this.deactivationByEmail = deactivationByEmail; + return this; + } + + public Builder withDeactivationReason(String deactivationReason) { + this.deactivationReason = deactivationReason; + return this; + } + + public Builder withTrackingNumber(String trackingNumber) { + this.trackingNumber = trackingNumber; + return this; + } + + public Builder withReturnTrackingNumber(String returnTrackingNumber) { + this.returnTrackingNumber = returnTrackingNumber; + return this; + } + + public Builder withTrackingScanBy(String trackingScanBy) { + this.trackingScanBy = trackingScanBy; + return this; + } + + public Builder withError(Boolean error) { + this.error = error; + return this; + } + + public Builder withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + public Builder withDiscardDate(String discardDate) { + this.discardDate = discardDate; + return this; + } + + public Builder withDiscardBy(String discardBy) { + this.discardBy = discardBy; + return this; + } + + public NonPepperKitStatusDto build() { + return new NonPepperKitStatusDto(this); + } + + } + + +} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DSMBadRequestException.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DSMBadRequestException.java index 8553c22d6e..53cc266c5f 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DSMBadRequestException.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DSMBadRequestException.java @@ -4,5 +4,4 @@ public class DSMBadRequestException extends RuntimeException { public DSMBadRequestException(String message) { super(message); } - } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DsmInternalError.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DsmInternalError.java index 9b0383bfde..64aca8d872 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DsmInternalError.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/exception/DsmInternalError.java @@ -8,4 +8,8 @@ public DsmInternalError(String message) { public DsmInternalError(String message, Throwable e) { super(message, e); } + + public DsmInternalError(Throwable e) { + super(e); + } } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/JuniperKitStatus.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/JuniperKitStatus.java deleted file mode 100644 index 98be4e9b36..0000000000 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/JuniperKitStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.broadinstitute.dsm.model.nonpepperkit; - -public class JuniperKitStatus extends KitResponse { - public JuniperKitStatus(String errorMessage, String juniperKitId, String studyGuid) { - super(errorMessage, juniperKitId, studyGuid); - } -} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/KitResponse.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/KitResponse.java index 7a18131f6d..f5f61ed0c9 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/KitResponse.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/KitResponse.java @@ -1,10 +1,66 @@ package org.broadinstitute.dsm.model.nonpepperkit; -import lombok.AllArgsConstructor; +import java.util.List; -@AllArgsConstructor +import lombok.Getter; +import org.broadinstitute.dsm.db.dto.kit.nonPepperKit.NonPepperKitStatusDto; + +@Getter public class KitResponse { - public String errorMessage; - public String juniperKitId; - public Object value; + private ErrorMessage errorMessage; + private String juniperKitId; + private Object value; + private List kits; + private boolean isError; + + public static KitResponse makeKitResponseError(ErrorMessage errorMessage, String juniperKitId, Object value) { + KitResponse kitResponse = new KitResponse(); + kitResponse.errorMessage = errorMessage; + kitResponse.juniperKitId = juniperKitId; + kitResponse.value = value; + kitResponse.isError = true; + kitResponse.setKitsListNull(); + return kitResponse; + } + + public static KitResponse makeKitResponseError(ErrorMessage errorMessage) { + return makeKitResponseError(errorMessage, null, null); + } + + public static KitResponse makeKitResponseError(ErrorMessage errorMessage, String juniperKitId) { + return makeKitResponseError(errorMessage, juniperKitId, null); + } + + public static KitResponse makeKitStatusResponse(List kits) { + KitResponse kitResponse = new KitResponse(); + kitResponse.kits = kits; + kitResponse.removeErrorFields(); + return kitResponse; + } + + private void removeErrorFields() { + this.errorMessage = null; + this.juniperKitId = null; + this.value = null; + this.isError = false; + } + + private void setKitsListNull() { + this.kits = null; + } + + public enum ErrorMessage { + ADDRESS_VALIDATION_ERROR, + UNKNOWN_KIT_TYPE, + UNKNOWN_STUDY, + MISSING_JUNIPER_KIT_ID, + MISSING_JUNIPER_PARTICIPANT_ID, + MISSING_STUDY_GUID, + DSM_ERROR_SOMETHING_WENT_WRONG, + EMPTY_REQUEST, + JSON_SYNTAX_EXCEPTION, + EMPTY_STUDY_NAME, EMPTY_KIT_TYPE, NOT_IMPLEMENTED + + } + } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperKitCreationService.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperKitCreationService.java index a122591a54..8c3e3e663f 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperKitCreationService.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperKitCreationService.java @@ -13,135 +13,67 @@ import org.broadinstitute.ddp.db.TransactionWrapper; import org.broadinstitute.dsm.db.DDPInstance; import org.broadinstitute.dsm.db.KitRequestShipping; +import org.broadinstitute.dsm.exception.DsmInternalError; import org.broadinstitute.dsm.model.KitRequest; import org.broadinstitute.dsm.model.KitRequestSettings; import org.broadinstitute.dsm.model.KitType; import org.broadinstitute.dsm.util.DDPKitRequest; import org.broadinstitute.dsm.util.EasyPostUtil; import org.broadinstitute.lddp.db.SimpleResult; -import org.broadinstitute.lddp.util.DeliveryAddress; @Slf4j public class NonPepperKitCreationService { public static final String JUNIPER = "JUNIPER"; - public static final String JUNIPER_UNDERSCORE = "JUNIPER_"; //These are the Error Strings that are expected by Juniper - public static final String ADDRESS_VALIDATION_ERROR = "UNABLE_TO_VERIFY_ADDRESS"; - public static final String UNKNOWN_KIT_TYPE = "UNKNOWN_KIT_TYPE"; - public static final String UNKNOWN_STUDY = "UNKNOWN_STUDY"; - public static final String MISSING_JUNIPER_KIT_ID = "MISSING_JUNIPER_KIT_ID"; - public static final String MISSING_JUNIPER_PARTICIPANT_ID = "MISSING_JUNIPER_PARTICIPANT_ID"; - public static final String DSM_ERROR = "DSM_ERROR_SOMETHING_WENT_WRONG"; - public KitResponse createNonPepperKit(JuniperKitRequest juniperKitRequest, String studyGuid, String kitTypeName) { + public KitResponse createNonPepperKit(JuniperKitRequest juniperKitRequest, String kitTypeName, EasyPostUtil easyPostUtil, + DDPInstance ddpInstance) { if (StringUtils.isBlank(juniperKitRequest.getJuniperParticipantID())) { - return new KitResponse(MISSING_JUNIPER_PARTICIPANT_ID, juniperKitRequest.getJuniperKitId(), + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_JUNIPER_PARTICIPANT_ID, + juniperKitRequest.getJuniperKitId(), juniperKitRequest.getJuniperParticipantID()); } if (StringUtils.isBlank(juniperKitRequest.getJuniperKitId())) { - return new KitResponse(MISSING_JUNIPER_KIT_ID, null, juniperKitRequest.getJuniperKitId()); - } - //getting the instance with isHasRole being set to true if the instance has role juniper_study - DDPInstance ddpInstance = DDPInstance.getDDPInstanceWithRoleByStudyGuid(studyGuid, "juniper_study"); - if (ddpInstance == null) { - log.error(studyGuid + " is not a study!"); - return new KitResponse(UNKNOWN_STUDY, juniperKitRequest.getJuniperKitId(), studyGuid); - } - if (!ddpInstance.isHasRole()) { - log.error(studyGuid + " is not a Juniper study!"); - return new KitResponse(UNKNOWN_STUDY, juniperKitRequest.getJuniperKitId(), studyGuid); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_JUNIPER_KIT_ID , null, + juniperKitRequest.getJuniperKitId()); } HashMap kitTypes = KitType.getKitLookup(); String key = KitType.createKitTypeKey(kitTypeName, ddpInstance.getDdpInstanceId()); KitType kitType = kitTypes.get(key); if (kitType == null) { - return new KitResponse(UNKNOWN_KIT_TYPE, juniperKitRequest.getJuniperKitId(), kitTypeName); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.UNKNOWN_KIT_TYPE , juniperKitRequest.getJuniperKitId(), + kitTypeName); } Map kitRequestSettingsMap = KitRequestSettings.getKitRequestSettings(String.valueOf(ddpInstance.getDdpInstanceId())); KitRequestSettings kitRequestSettings = kitRequestSettingsMap.get(kitType.getKitTypeId()); - // if the kit type has sub kits > like for testBoston - // boolean kitHasSubKits = kitRequestSettings.getHasSubKits() != 0; - - log.info("Setup EasyPost..."); - EasyPostUtil easyPostUtil = new EasyPostUtil(ddpInstance.getName()); + // if the kit type has sub kits check that here - if (!checkAddress(juniperKitRequest, kitRequestSettings.getPhone(), easyPostUtil)) { - return new KitResponse(ADDRESS_VALIDATION_ERROR, juniperKitRequest.getJuniperKitId(), null); + if (!easyPostUtil.checkAddress(juniperKitRequest, kitRequestSettings.getPhone())) { + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.ADDRESS_VALIDATION_ERROR , + juniperKitRequest.getJuniperKitId(), null); } - ArrayList orderKits = new ArrayList<>(); - - SimpleResult result = TransactionWrapper.inTransaction(conn -> { SimpleResult transactionResults = new SimpleResult(); - return createKit(ddpInstance, kitType, juniperKitRequest, kitRequestSettings, easyPostUtil, kitTypeName, orderKits, conn, + return createKit(ddpInstance, kitType, juniperKitRequest, kitRequestSettings, easyPostUtil, kitTypeName, conn, transactionResults); - // only order if external shipper name is set for that kit request, not needed for now - // if (StringUtils.isNotBlank(kitRequestSettings.getExternalShipper())) { - // return orderExternalKits(kitRequestSettings, orderKits, easyPostUtil, shippingCarrier, conn); - // } + // order external kits here if external shipper name is set for that kit request, not needed for now }); if (result.resultException != null) { log.error(String.format("Unable to create Juniper kit for %s", juniperKitRequest), result.resultException); - return new KitResponse(DSM_ERROR, juniperKitRequest.getJuniperKitId(), result.resultException); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.DSM_ERROR_SOMETHING_WENT_WRONG, + juniperKitRequest.getJuniperKitId()); } log.info(juniperKitRequest.getJuniperKitId() + " " + ddpInstance.getName() + " " + kitTypeName + " kit created"); - return new JuniperKitStatus(null, null, null); - } - - /** - * checkAddress tries creating an address in EasyPost. If it is successful, - * sets the kit's easypostAddressId and returns true, if not returns false - * An address is valid only if participant has shortId, first - and lastName, for Juniper shortId is the juniperParticipantId - * - * @param juniperKitRequest the JuniperKitRequest with address to check - */ - - public boolean checkAddress(JuniperKitRequest juniperKitRequest, String phone, EasyPostUtil easyPostUtil) { - if ((StringUtils.isBlank(juniperKitRequest.getJuniperParticipantID())) - || StringUtils.isBlank(juniperKitRequest.getLastName())) { - return false; - } - //let's validate the participant's address - String name = ""; - if (StringUtils.isNotBlank(juniperKitRequest.getFirstName())) { - name += juniperKitRequest.getFirstName() + " "; - } - name += juniperKitRequest.getLastName(); - if (juniperKitRequest.isSkipAddressValidation()) { - try { - Address address = easyPostUtil.createBroadAddress(name, juniperKitRequest.getStreet1(), juniperKitRequest.getStreet2(), - juniperKitRequest.getCity(), - juniperKitRequest.getPostalCode(), juniperKitRequest.getState(), juniperKitRequest.getCountry(), phone); - juniperKitRequest.setEasypostAddressId(address.getId()); - return true; - } catch (EasyPostException e) { - // log the reason for address creation failure and return false. The method will then return the error code - log.warn("Easypost couldn't create an address for " + juniperKitRequest.getShortId(), e); - return false; - } - } - DeliveryAddress deliveryAddress = - new DeliveryAddress(juniperKitRequest.getStreet1(), juniperKitRequest.getStreet2(), juniperKitRequest.getCity(), - juniperKitRequest.getState(), - juniperKitRequest.getPostalCode(), juniperKitRequest.getCountry(), name, phone); - deliveryAddress.validate(); - if (deliveryAddress.isValid()) { - //store the address back - juniperKitRequest.setEasypostAddressId(deliveryAddress.getId()); - return true; - } - log.info("Address is not valid " + juniperKitRequest.getShortId()); - return false; - + return KitResponse.makeKitStatusResponse(null); } @@ -152,13 +84,12 @@ public boolean checkAddress(JuniperKitRequest juniperKitRequest, String phone, E */ private SimpleResult createKit(@NonNull DDPInstance ddpInstance, @NonNull KitType kitType, JuniperKitRequest kit, @NonNull KitRequestSettings kitRequestSettings, @NonNull EasyPostUtil easyPostUtil, - @NonNull String kitTypeName, ArrayList orderKits, Connection conn, - SimpleResult transactionResults) { + @NonNull String kitTypeName, Connection conn, SimpleResult transactionResults) { String juniperKitRequestId; String userId; //checking ddpInstance.isHasRole() to know this is a Juniper Kit if (ddpInstance.isHasRole()) { - juniperKitRequestId = JUNIPER_UNDERSCORE + kit.getJuniperKitId(); + juniperKitRequestId = kit.getJuniperKitId(); userId = JUNIPER; } else { log.warn("Seems like {} is not configured as a JUNIPER study! ", ddpInstance.getName()); @@ -182,17 +113,13 @@ private SimpleResult createKit(@NonNull DDPInstance ddpInstance, @NonNull KitTyp addJuniperKitRequest(conn, kitTypeName, kitRequestSettings, ddpInstance, kitType.getKitTypeId(), collaboratorParticipantId, errorMessage, easyPostUtil, kit, externalOrderNumber, juniperKitRequestId, null, userId, transactionResults); - // Not needed now, uncomment later when needed for external shippers - // orderKits.add(kit); - return transactionResults; } private SimpleResult addJuniperKitRequest(Connection conn, String kitTypeName, KitRequestSettings kitRequestSettings, - DDPInstance ddpInstance, - int kitTypeId, String collaboratorParticipantId, String errorMessage, - EasyPostUtil easyPostUtil, - JuniperKitRequest kit, String externalOrderNumber, String juniperKitRequestId, + DDPInstance ddpInstance, int kitTypeId, String collaboratorParticipantId, + String errorMessage, EasyPostUtil easyPostUtil, JuniperKitRequest kit, + String externalOrderNumber, String juniperKitRequestId, String ddpLabel, String userId, SimpleResult transactionResults) { String collaboratorSampleId = null; String bspCollaboratorSampleType = kitTypeName; @@ -203,7 +130,7 @@ private SimpleResult addJuniperKitRequest(Connection conn, String kitTypeName, K addressId = address.getId(); } } catch (EasyPostException e) { - throw new RuntimeException("EasyPost addressId could not be received ", e); + throw new DsmInternalError("EasyPost addressId could not be received ", e); } if (StringUtils.isNotBlank(kitRequestSettings.getExternalShipper())) { @@ -243,8 +170,7 @@ private SimpleResult addJuniperKitRequest(Connection conn, String kitTypeName, K kit.getExternalOrderNumber(), false, null, ddpInstance, bspCollaboratorSampleType, ddpLabel); - log.info("Created new kit in DSM with dsm_kit_request_id {} and ddpLabel {} for JuniperKitId {}", dsmKitRequestId, ddpLabel, - juniperKitRequestId); + log.info("Created new kit in DSM with dsm_kit_request_id {} for JuniperKitId {}", dsmKitRequestId, juniperKitRequestId); } catch (Exception e) { transactionResults.resultException = e; } @@ -253,23 +179,4 @@ private SimpleResult addJuniperKitRequest(Connection conn, String kitTypeName, K return transactionResults; } - // private Result orderExternalKits(KitRequestSettings kitRequestSettings, ArrayList orderKits, - // EasyPostUtil easyPostUtil, AtomicReference shippingCarrier, Connection conn) { - // try { - // logger.info("placing order with external shipper"); - // ExternalShipper shipper = - // (ExternalShipper) Class.forName(DSMServer.getClassName(kitRequestSettings.getExternalShipper())) - // .newInstance(); - // shipper.orderKitRequests(orderKits, easyPostUtil, kitRequestSettings, shippingCarrier.get()); - // // mark kits as transmitted so that background jobs don't try to double order it - // for (KitRequest orderKit : orderKits) { - // KitRequestShipping.markOrderTransmittedAt(conn, orderKit.getExternalOrderNumber(), Instant.now()); - // } - // } catch (Exception e) { - // logger.error("Failed to sent kit request order to " + kitRequestSettings.getExternalShipper(), e); - // return new Result(500, "Failed to sent kit request order to " + kitRequestSettings.getExternalShipper()); - // } - // return null; - // } - } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperStatusKitService.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperStatusKitService.java new file mode 100644 index 0000000000..4e27238e30 --- /dev/null +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/model/nonpepperkit/NonPepperStatusKitService.java @@ -0,0 +1,103 @@ +package org.broadinstitute.dsm.model.nonpepperkit; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.broadinstitute.dsm.db.DDPInstance; +import org.broadinstitute.dsm.db.dao.kit.KitStatusDao; +import org.broadinstitute.dsm.db.dao.user.UserDao; +import org.broadinstitute.dsm.db.dto.kit.nonPepperKit.NonPepperKitStatusDto; +import org.broadinstitute.dsm.db.dto.user.UserDto; +import org.broadinstitute.dsm.statics.DBConstants; + +/** + * This service returns a Juniper kit's status + */ +@Slf4j +public class NonPepperStatusKitService { + private KitStatusDao kitStatusDao; + + public NonPepperStatusKitService() { + this.kitStatusDao = new KitStatusDao(); + } + + public static String getUserEmailForFields(String userIdInDB, Map users) { + String userEmail = ""; + if (StringUtils.isBlank(userIdInDB)) { + return userEmail; + } + try { + Integer userId = Integer.parseInt(userIdInDB); + userEmail = users.containsKey(userId) ? users.get(userId).getEmail().orElse("DSM User") : "DSM User"; + } catch (NumberFormatException e) { + log.info(String.format(" User Id %s is not a valid integer, returning it as is. ", userIdInDB)); + return userIdInDB; + } + return userEmail; + } + + public static String convertTimeStringIntoTimeStamp(Long dateMillis) { + if (dateMillis == null || dateMillis == 0L) { + return null; + } + Instant instant = Instant.ofEpochMilli(dateMillis); + return instant.toString(); + } + + public KitResponse getKitsByStudyName(String studyGuid) { + if (StringUtils.isBlank(studyGuid)) { + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_STUDY_GUID); + } + DDPInstance ddpInstance = DDPInstance.getDDPInstanceWithRoleByStudyGuid(studyGuid, DBConstants.JUNIPER_STUDY_INSTANCE_ROLE); + if (ddpInstance == null || !ddpInstance.isHasRole()) { + log.info(studyGuid + " is not a Juniper study!"); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.UNKNOWN_STUDY); + } + HashMap users = (HashMap) UserDao.selectAllUsers(); + // get all the kits + ArrayList list = (ArrayList) kitStatusDao.getKitsByInstanceId(ddpInstance, users); + return KitResponse.makeKitStatusResponse(list); + + } + + public KitResponse getKitsBasedOnJuniperKitId(String juniperKitId) { + if (StringUtils.isBlank(juniperKitId)) { + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_JUNIPER_KIT_ID); + } + HashMap users = (HashMap) UserDao.selectAllUsers(); + // get the kit with that juniperKitId + ArrayList list = (ArrayList) kitStatusDao.getKitsByJuniperKitId(juniperKitId, users); + return KitResponse.makeKitStatusResponse(list); + + } + + public KitResponse getKitsBasedOnParticipantId(String participantId) { + if (StringUtils.isBlank(participantId)) { + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_JUNIPER_PARTICIPANT_ID); + } + HashMap users = (HashMap) UserDao.selectAllUsers(); + // get the kit with that participantId + ArrayList list = + (ArrayList) kitStatusDao.getKitsByParticipantId(participantId, users); + return KitResponse.makeKitStatusResponse(list); + } + + public KitResponse getKitsFromKitIds(String[] kitIdsArray) { + HashMap users = (HashMap) UserDao.selectAllUsers(); + // get the kits with the given kit ids + try { + List list = kitStatusDao.getKitsByKitIdArray(kitIdsArray, users); + return KitResponse.makeKitStatusResponse(list); + + } catch (Exception e) { + log.error("Error getting kits by an array of kit ids", e); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.DSM_ERROR_SOMETHING_WENT_WRONG); + } + } + +} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/JuniperShipKitRoute.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/JuniperShipKitRoute.java deleted file mode 100644 index 8e04591262..0000000000 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/JuniperShipKitRoute.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.broadinstitute.dsm.route; - -import com.google.gson.Gson; -import org.apache.commons.lang3.StringUtils; -import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitRequest; -import org.broadinstitute.dsm.model.nonpepperkit.KitResponse; -import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitStatus; -import org.broadinstitute.dsm.model.nonpepperkit.NonPepperKitCreationService; -import org.broadinstitute.dsm.model.nonpepperkit.ShipKitRequest; -import spark.Request; -import spark.Response; -import spark.Route; - -public class JuniperShipKitRoute implements Route { - - NonPepperKitCreationService kitCreationService; - - public JuniperShipKitRoute(NonPepperKitCreationService kitCreationService) { - this.kitCreationService = kitCreationService; - } - - public KitResponse createNonPepperKit(Request request, Response response) { - ShipKitRequest shipKitRequest = new Gson().fromJson(request.body(), ShipKitRequest.class); - JuniperKitRequest juniperKitRequest = shipKitRequest.getJuniperKitRequest(); - if (juniperKitRequest == null) { - response.status(400); - return new KitResponse("EMPTY_REQUEST", null, juniperKitRequest); - } - if (StringUtils.isBlank(shipKitRequest.getJuniperStudyGUID())) { - response.status(400); - return new KitResponse("EMPTY_STUDY_NAME", null, null); - } - if (StringUtils.isBlank(shipKitRequest.getKitType())) { - response.status(400); - return new KitResponse("EMPTY_KIT_TYPE", null, shipKitRequest.getKitType()); - } - KitResponse kitResponse = this.kitCreationService.createNonPepperKit(juniperKitRequest, shipKitRequest.getJuniperStudyGUID(), - shipKitRequest.getKitType()); - if (kitResponse instanceof JuniperKitStatus) { - response.status(200); - } else { - response.status(400); - } - return kitResponse; - } - - @Override - public Object handle(Request request, Response response) throws Exception { - return createNonPepperKit(request, response); - } -} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/KitUploadRoute.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/KitUploadRoute.java index 61f67a81c1..e815897f77 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/KitUploadRoute.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/KitUploadRoute.java @@ -576,7 +576,7 @@ public Map checkAddress(List kitUploadObjects, S if (skipAddressValidation) { try { - Address address = easyPostUtil.createBroadAddress(name, object.getStreet1(), object.getStreet2(), object.getCity(), + Address address = easyPostUtil.createAddressWithoutValidation(name, object.getStreet1(), object.getStreet2(), object.getCity(), object.getPostalCode(), object.getState(), object.getCountry(), phone); object.setEasyPostAddressId(address.getId()); } catch (EasyPostException e) { diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/JuniperShipKitRoute.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/JuniperShipKitRoute.java new file mode 100644 index 0000000000..874b5c14d4 --- /dev/null +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/JuniperShipKitRoute.java @@ -0,0 +1,87 @@ +package org.broadinstitute.dsm.route.juniper; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.broadinstitute.dsm.db.DDPInstance; +import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitRequest; +import org.broadinstitute.dsm.model.nonpepperkit.KitResponse; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperKitCreationService; +import org.broadinstitute.dsm.model.nonpepperkit.ShipKitRequest; +import org.broadinstitute.dsm.statics.DBConstants; +import org.broadinstitute.dsm.util.EasyPostUtil; +import spark.Request; +import spark.Response; +import spark.Route; + +/** + * This is the route that is called by Juniper to create a new kit in DSM + */ + +@Slf4j +public class JuniperShipKitRoute implements Route { + + private final NonPepperKitCreationService kitCreationService; + + public JuniperShipKitRoute() { + this.kitCreationService = new NonPepperKitCreationService(); + } + + public KitResponse createNonPepperKit(Request request, Response response) { + try { + ShipKitRequest shipKitRequest = new Gson().fromJson(request.body(), ShipKitRequest.class); + + JuniperKitRequest juniperKitRequest = shipKitRequest.getJuniperKitRequest(); + if (juniperKitRequest == null) { + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.EMPTY_REQUEST, null, null); + } + if (StringUtils.isBlank(shipKitRequest.getJuniperStudyGUID())) { + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.EMPTY_STUDY_NAME, null, null); + } + if (StringUtils.isBlank(shipKitRequest.getKitType())) { + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.EMPTY_KIT_TYPE, null, shipKitRequest.getKitType()); + } + //getting the instance with isHasRole being set to true if the instance has role juniper_study + String studyGuid = shipKitRequest.getJuniperStudyGUID(); + DDPInstance ddpInstance = DDPInstance.getDDPInstanceWithRoleByStudyGuid(studyGuid, DBConstants.JUNIPER_STUDY_INSTANCE_ROLE); + if (ddpInstance == null) { + log.warn(studyGuid + " is not a study!"); + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.UNKNOWN_STUDY, juniperKitRequest.getJuniperKitId(), + studyGuid); + } + //check it the study is set to use this endpoint + if (!ddpInstance.isHasRole()) { + log.info(studyGuid + " is not a Juniper study!"); + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.UNKNOWN_STUDY, juniperKitRequest.getJuniperKitId(), + studyGuid); + } + + log.info("Setup EasyPost..."); + EasyPostUtil easyPostUtil = new EasyPostUtil(ddpInstance.getName()); + KitResponse kitResponse = + this.kitCreationService.createNonPepperKit(juniperKitRequest, shipKitRequest.getKitType(), easyPostUtil, + ddpInstance); + if (!kitResponse.isError()) { + response.status(200); + } else { + response.status(400); + } + return kitResponse; + } catch (JsonSyntaxException exception) { + response.status(400); + log.warn("Bad Json Syntax exception, will return 400", exception); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.JSON_SYNTAX_EXCEPTION, null, exception); + } + } + + @Override + public Object handle(Request request, Response response) { + return createNonPepperKit(request, response); + } +} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/StatusKitRoute.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/StatusKitRoute.java new file mode 100644 index 0000000000..069eb32497 --- /dev/null +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/route/juniper/StatusKitRoute.java @@ -0,0 +1,80 @@ +package org.broadinstitute.dsm.route.juniper; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.broadinstitute.dsm.exception.DSMBadRequestException; +import org.broadinstitute.dsm.model.nonpepperkit.KitResponse; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperStatusKitService; +import org.broadinstitute.dsm.statics.RequestParameter; +import org.broadinstitute.dsm.statics.RoutePath; +import spark.Request; +import spark.Response; +import spark.Route; + +@Slf4j +public class StatusKitRoute implements Route { + private final NonPepperStatusKitService nonPepperStatusKitService; + + public StatusKitRoute() { + this.nonPepperStatusKitService = new NonPepperStatusKitService(); + } + + @Override + public Object handle(Request request, Response response) throws Exception { + KitResponse kitResponse; + if (request.requestMethod().equals(RoutePath.RequestMethod.GET.toString())) { + if (request.url().contains(RoutePath.KIT_STATUS_STUDY)) { + String study = getParam(RequestParameter.STUDY, request); + log.info("Got a request to return information of kits in non-pepper study {}", study); + kitResponse = this.nonPepperStatusKitService.getKitsByStudyName(study); + } else if (request.url().contains(RoutePath.KIT_STATUS_JUNIPER_KIT_ID)) { + String juniperKitId = getParam(RequestParameter.JUNIPER_KIT_ID, request); + log.info("Got a request to return information of kit with Juniper Kit Id {}", juniperKitId); + kitResponse = this.nonPepperStatusKitService.getKitsBasedOnJuniperKitId(juniperKitId); + } else if (request.url().contains(RoutePath.KIT_STATUS_PARTICIPANT_ID)) { + String participantId = getParam(RequestParameter.JUNIPER_PARTICIPANT_ID, request); + log.info("Got a request to return information of kits with participant Id {}", participantId); + kitResponse = this.nonPepperStatusKitService.getKitsBasedOnParticipantId(participantId); + } else { + response.status(400); + return KitResponse.ErrorMessage.NOT_IMPLEMENTED; + } + } else if (request.requestMethod().equals(RoutePath.RequestMethod.POST.toString()) + && request.url().contains(RoutePath.KIT_STATUS_ENDPOINT_KIT_IDS)) { + try { + String[] kitIds = new Gson().fromJson(request.queryMap().get(RoutePath.JUNIPER_KIT_IDS).value(), String[].class); + kitResponse = getStatusByKitIdList(kitIds); + } catch (JsonSyntaxException e) { + log.warn("Json does not have the expected syntax", e); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.JSON_SYNTAX_EXCEPTION, null, e); + } + } else { + response.status(400); + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.NOT_IMPLEMENTED, null, null); + } + if (!kitResponse.isError()) { + response.status(200); + } else { + response.status(400); + } + return kitResponse; + } + + private String getParam(String paramName, Request request) { + String value = request.params(paramName); + if (StringUtils.isBlank(value)) { + throw new DSMBadRequestException(String.format("value provided for %s was invalid", paramName)); + } + return value; + } + + private KitResponse getStatusByKitIdList(String[] kitIds) { + try { + return this.nonPepperStatusKitService.getKitsFromKitIds(kitIds); + } catch (DSMBadRequestException e) { + return KitResponse.makeKitResponseError(KitResponse.ErrorMessage.MISSING_JUNIPER_KIT_ID, null, kitIds); + } + } +} diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/ApplicationConfigConstants.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/ApplicationConfigConstants.java index b53dd7c774..86b4c60a98 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/ApplicationConfigConstants.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/ApplicationConfigConstants.java @@ -89,11 +89,9 @@ public class ApplicationConfigConstants { public static final String GET_DASHBOARD_INFORMATION_OF_KIT_REQUESTS_DEACTIVATED = "portal.dashboardKitDeactivated"; public static final String GET_DASHBOARD_INFORMATION_OF_KIT_REQUESTS_SENT_REPORT = "portal.dashboardReportKitSent"; public static final String GET_DASHBOARD_INFORMATION_OF_KIT_REQUESTS_RECEIVED_REPORT = "portal.dashboardReportKitReceived"; - public static final String GET_FOUND_IF_KIT_WITH_DDP_LABEL_ALREADY_EXISTS = "portal.checkDdpLabelIdQuery"; public static final String GET_FOUND_IF_KIT_LABEL_ALREADY_EXISTS_IN_TRACKING_TABLE = "portal.checkTrackingQuery"; public static final String GET_KIT_TYPE_NEED_TRACKING_BY_DDP_LABEL = "portal.checkKitTypeNeedsTrackingQuery"; public static final String INSERT_KIT = "portal.insertKit"; - public static final String GET_COUNT_KITS_WITH_SAME_COLLABORATOR_SAMPLE_ID_AND_KIT_TYPE = "portal.counterCollaboratorSample"; public static final String GET_UNSENT_KIT_REQUESTS_FOR_REALM = "portal.unsentKitRequestsPerRealmQuery"; public static final String GET_UPLOADED_KITS = "portal.selectUploadedKits"; public static final String GET_LABEL_SETTINGS = "portal.labelSettingsQuery"; diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/DBConstants.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/DBConstants.java index 3be820556e..e4caf4a629 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/DBConstants.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/DBConstants.java @@ -314,6 +314,7 @@ public class DBConstants { public static final String HAS_CLINICAL_KIT = "has_clinical_kit"; public static final String SHOW_GROUP_FIELDS = "show_group_fields"; public static final String GBF_SHIPPED_DSS_DELIVERED = "GBF_SHIPPED_DSS_DELIVERED"; + public static final String JUNIPER_STUDY_INSTANCE_ROLE = "juniper_study"; //user role public static final String MAILINGLIST_VIEW = "mailingList_view"; @@ -565,4 +566,15 @@ public class DBConstants { //INDEXES public static final String OSTEO_INDEX = "participants_structured.cmi.cmi-osteo"; + + // ddp_kit table columns + public static final String LABEL_BY = "label_by"; + public static final String LABEL_DATE = "label_date"; + public static final String SCAN_BY = "scan_by"; + public static final String DEACTIVATED_BY = "deactivated_by"; + public static final String RECEIVE_BY = "receive_by"; + public static final String TRACKING_TO_ID = "tracking_to_id"; + public static final String ERROR_MESSAGE = "message"; + public static final String RETURN_TRACKING_NUMBER = "return_tracking_number"; + public static final String TRACKING_SCAN_BY = "tracking_scan_by"; } diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RequestParameter.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RequestParameter.java index 2c148c6330..a87f253aea 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RequestParameter.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RequestParameter.java @@ -3,6 +3,9 @@ public class RequestParameter { public static final String LABEL = ":label"; + public static final String STUDY = ":study"; + public static final String JUNIPER_KIT_ID = ":juniperKitId"; + public static final String JUNIPER_PARTICIPANT_ID = ":participantId"; public static final String KIT_TYPE = ":type"; public static final String START = ":start"; public static final String END = ":end"; diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RoutePath.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RoutePath.java index 699437d9a0..c2b427205a 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RoutePath.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/statics/RoutePath.java @@ -7,6 +7,7 @@ public class RoutePath { public static final String REALM = "realm"; + public static final String JUNIPER_KIT_IDS = "kitIds"; public static final String STUDY_GROUP = "studyGroup"; public static final String KIT_TYPE = "kitType"; public static final String UPLOAD_REASONS = "uploadReasons"; @@ -31,6 +32,13 @@ public class RoutePath { public static final String CREATE_CLINICAL_KIT_ENDPOINT_WITH_PARTICIPANT = "/createClinicalDummy/:label/:type/:participantId"; public static final String CLINICAL_KIT_ENDPOINT = "/ClinicalKits/:label"; public static final String SHIP_KIT_ENDPOINT = "/shipKit"; + public static final String KIT_STATUS_ENDPOINT_STUDY = "/kitstatus/study/:study"; + public static final String KIT_STATUS_STUDY = "/kitstatus/study/"; + public static final String KIT_STATUS_ENDPOINT_JUNIPER_KIT_ID = "/kitstatus/juniperKit/:juniperKitId"; + public static final String KIT_STATUS_JUNIPER_KIT_ID = "/kitstatus/juniperKit"; + public static final String KIT_STATUS_ENDPOINT_KIT_IDS = "/kitstatus/kits"; + public static final String KIT_STATUS_ENDPOINT_PARTICIPANT_ID = "/kitstatus/participant/:participantId"; + public static final String KIT_STATUS_PARTICIPANT_ID = "/kitstatus/participant"; //Drug list endpoint route public static final String DRUG_LIST_REQUEST = "/drugs"; // display names only (for survey display) public static final String CANCER_LIST_REQUEST = "/cancers"; diff --git a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/util/EasyPostUtil.java b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/util/EasyPostUtil.java index 2e18a77d81..01686fb36f 100644 --- a/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/util/EasyPostUtil.java +++ b/pepper-apis/dsm-core/src/main/java/org/broadinstitute/dsm/util/EasyPostUtil.java @@ -23,6 +23,8 @@ import org.broadinstitute.dsm.exception.RateNotAvailableException; import org.broadinstitute.dsm.model.EasypostLabelRate; import org.broadinstitute.dsm.model.ddp.DDPParticipant; +import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitRequest; +import org.broadinstitute.lddp.util.DeliveryAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -230,9 +232,9 @@ public Address createAddress(DDPParticipant ddpParticipant, @NonNull String phon return Address.create(toAddressMap); } - public Address createBroadAddress(@NonNull String name, @NonNull String street1, @NonNull String street2, - @NonNull String city, @NonNull String zip, @NonNull String state, - @NonNull String country, @NonNull String phone) throws EasyPostException { + public Address createAddressWithoutValidation(@NonNull String name, @NonNull String street1, @NonNull String street2, + @NonNull String city, @NonNull String zip, @NonNull String state, + @NonNull String country, @NonNull String phone) throws EasyPostException { Map fromAddressMap = new HashMap<>(); fromAddressMap.put(this.name, name); fromAddressMap.put(this.street1, street1); @@ -295,4 +297,55 @@ public Address getAddress(String addressId) throws EasyPostException { public Shipment getShipment(String shipmentId) throws EasyPostException { return Shipment.retrieve(shipmentId); } + + /** + * checkAddress tries creating an address in EasyPost. If it is successful, + * sets the kit's easypostAddressId and returns true, if not returns false + * An address is valid only if participant has shortId, first - and lastName, for Juniper shortId is the juniperParticipantId + * + * @param juniperKitRequest the JuniperKitRequest with address to check + * @return true if easypost was able to create the address, false otherwise + */ + + public boolean checkAddress(@NonNull JuniperKitRequest juniperKitRequest, String phone) { + if ((StringUtils.isBlank(juniperKitRequest.getJuniperParticipantID())) + || StringUtils.isBlank(juniperKitRequest.getLastName())) { + return false; + } + //let's validate the participant's address + String name = ""; + if (StringUtils.isNotBlank(juniperKitRequest.getFirstName())) { + name += juniperKitRequest.getFirstName() + " "; + } + name += juniperKitRequest.getLastName(); + if (juniperKitRequest.isSkipAddressValidation()) { + //if no validation is needed, we just need to create the Address instance in easypost and get its id back + try { + Address address = createAddressWithoutValidation(name, juniperKitRequest.getStreet1(), juniperKitRequest.getStreet2(), + juniperKitRequest.getCity(), + juniperKitRequest.getPostalCode(), juniperKitRequest.getState(), juniperKitRequest.getCountry(), phone); + juniperKitRequest.setEasypostAddressId(address.getId()); + return true; + } catch (EasyPostException e) { + // log the reason for address creation failure and return false. The method will then return the error code + logger.warn("Easypost couldn't create an address for " + juniperKitRequest.getShortId(), e); + return false; + } + } + //to validate the address, first we need create the Address instance + DeliveryAddress deliveryAddress = + new DeliveryAddress(juniperKitRequest.getStreet1(), juniperKitRequest.getStreet2(), juniperKitRequest.getCity(), + juniperKitRequest.getState(), + juniperKitRequest.getPostalCode(), juniperKitRequest.getCountry(), name, phone); + //call easypost apis to make sure the address is valid + deliveryAddress.validate(); + if (deliveryAddress.isValid()) { + //store the address back + juniperKitRequest.setEasypostAddressId(deliveryAddress.getId()); + return true; + } + logger.info(String.format("Address is not valid %s", juniperKitRequest.getShortId())); + return false; + + } } diff --git a/pepper-apis/dsm-core/src/main/resources/application.conf b/pepper-apis/dsm-core/src/main/resources/application.conf index 72b11a5c02..7946311fa0 100644 --- a/pepper-apis/dsm-core/src/main/resources/application.conf +++ b/pepper-apis/dsm-core/src/main/resources/application.conf @@ -189,14 +189,6 @@ portal { kit_label = ? """ - checkDdpLabelIdQuery:""" - select 1 as found - from - (select 1 from - ddp_kit_request req - where req.ddp_label = ?) as existing_rows - """ - checkKitTypeNeedsTrackingQuery:""" select kt.requires_insert_in_kit_tracking as found from ddp_kit_request request @@ -481,12 +473,6 @@ portal { where part.participant_id = ?; """ - counterCollaboratorSample:""" - select count(*) kitRequestCount - from ddp_kit_request - where bsp_collaborator_sample_id REGEXP "^%1" and kit_type_id = ? - """ - updateKitRequestError:""" update ddp_kit kit INNER JOIN( diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/RouteTestSample.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/RouteTestSample.java index 5ff8ab1097..cde020dad4 100644 --- a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/RouteTestSample.java +++ b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/RouteTestSample.java @@ -415,7 +415,7 @@ public Address easyPost(String instanceId, String instanceName, DDPParticipant p EasyPostUtil easyPostUtil = new EasyPostUtil(instanceName); Address toAddress = easyPostUtil.createAddress(participant, "617-714-8952"); Address returnAddress = - easyPostUtil.createBroadAddress("Broad Institute", "320 Charles St - Lab 181", "Attn. Broad Genomics", "Cambridge", "02141", + easyPostUtil.createAddressWithoutValidation("Broad Institute", "320 Charles St - Lab 181", "Attn. Broad Genomics", "Cambridge", "02141", "MA", "US", "617-714-8952"); Parcel parcel = easyPostUtil.createParcel("3.2", "6.9", "1.3", "5.2"); CustomsInfo customs = null; diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationStatusTest.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationStatusTest.java new file mode 100644 index 0000000000..febb61f6c9 --- /dev/null +++ b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationStatusTest.java @@ -0,0 +1,308 @@ +package org.broadinstitute.dsm.juniperkits; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import com.google.gson.Gson; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.broadinstitute.dsm.DbTxnBaseTest; +import org.broadinstitute.dsm.db.DDPInstance; +import org.broadinstitute.dsm.db.KitRequestShipping; +import org.broadinstitute.dsm.db.dto.kit.nonPepperKit.NonPepperKitStatusDto; +import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitRequest; +import org.broadinstitute.dsm.model.nonpepperkit.KitResponse; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperKitCreationService; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperStatusKitService; +import org.broadinstitute.dsm.statics.DBConstants; +import org.broadinstitute.dsm.util.EasyPostUtil; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + +/** + * Tests the NonPepperKitCreationService and NonPepperStatusKitService class + * To run this class use the following VM variables + * -ea -Dconfig.file=[path to /pepper-apis/output-build-config/testing-inmemorydb.conf] + */ + +@Slf4j +@RunWith(MockitoJUnitRunner.class) +public class JuniperKitCreationStatusTest extends DbTxnBaseTest { + + static final String instanceGuid = "Juniper-test-guid"; + static final String instanceName = "Juniper-test"; + static final String bspPrefix = "JuniperTestProject"; + static List createdKitIds = new ArrayList<>(); + static DDPInstance ddpInstance; + final String salivaKitType = "SALIVA"; + NonPepperKitCreationService nonPepperKitCreationService = new NonPepperKitCreationService(); + static EasyPostUtil mockEasyPostUtil = mock(EasyPostUtil.class); + + NonPepperStatusKitService nonPepperStatusKitService = new NonPepperStatusKitService(); + + @BeforeClass + public static void setupJuniperBefore() { + JuniperSetupUtil juniperSetupUtil = new JuniperSetupUtil(instanceName, instanceGuid, "Juniper-Test", "JuniperTestProject"); + ; + juniperSetupUtil.setupJuniperInstanceAndSettings(); + ddpInstance = DDPInstance.getDDPInstanceWithRoleByStudyGuid(instanceGuid, DBConstants.JUNIPER_STUDY_INSTANCE_ROLE); + when(mockEasyPostUtil.checkAddress(any(), anyString())).thenReturn(true); + } + + @AfterClass + public static void deleteJuniperInstance() { + JuniperSetupUtil.deleteKitsArray(createdKitIds); + JuniperSetupUtil.deleteJuniperInstanceAndSettings(); + } + + @Test + public void testStatusKitEndpointByJuniperStudyGuid() { + int rand = new Random().nextInt() & Integer.MAX_VALUE; + JuniperKitRequest juniperTestKit = generateJuniperKit(rand); + + try { + createAndAssertNonPepperCreation(juniperTestKit); + + KitResponse kitResponse = nonPepperStatusKitService.getKitsByStudyName(instanceGuid); + Assert.assertNotNull(kitResponse); + Assert.assertNotNull(kitResponse.getKits()); + Assert.assertNotEquals(0, kitResponse.getKits().size()); + Assert.assertNotNull( + kitResponse.getKits().stream().filter(kitStatus -> kitStatus.getJuniperKitId().equals("JuniperTestKitId_" + rand)) + .findAny()); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + @Test + public void testStatusByJuniperKitId() { + int rand = new Random().nextInt() & Integer.MAX_VALUE; + JuniperKitRequest juniperTestKit = generateJuniperKit(rand); + try { + createAndAssertNonPepperCreation(juniperTestKit); + + KitResponse kitResponse = nonPepperStatusKitService.getKitsBasedOnJuniperKitId(juniperTestKit.getJuniperKitId()); + + assertStatusKitResponse(kitResponse, juniperTestKit, rand); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + @Test + public void testStatusByKitIdTest() { + int rand = new Random().nextInt() & Integer.MAX_VALUE; + JuniperKitRequest juniperTestKit = generateJuniperKit(rand); + try { + createAndAssertNonPepperCreation(juniperTestKit); + KitResponse kitResponse = nonPepperStatusKitService.getKitsBasedOnJuniperKitId(juniperTestKit.getJuniperKitId()); + assertStatusKitResponse(kitResponse, juniperTestKit, rand); + + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + private void createAndAssertNonPepperCreation(JuniperKitRequest juniperTestKit) { + List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", salivaKitType); + KitResponse kitResponse = nonPepperKitCreationService.createNonPepperKit(juniperTestKit, salivaKitType, mockEasyPostUtil, ddpInstance); + Assert.assertFalse(kitResponse.isError()); + List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", salivaKitType); + Assert.assertEquals(oldkits.size() + 1, newKits.size()); + } + + private void assertStatusKitResponse(KitResponse kitResponse, JuniperKitRequest juniperTestKit, int testRandomNumber) { + Assert.assertNotNull(kitResponse); + Assert.assertNotNull(kitResponse.getKits()); + Assert.assertEquals(1, kitResponse.getKits().size()); + Assert.assertNotNull( + kitResponse.getKits().stream() + .filter(kitStatus -> kitStatus.getJuniperKitId().equals("JuniperTestKitId_" + testRandomNumber)) + .findAny()); + NonPepperKitStatusDto nonPepperKitStatus = kitResponse.getKits().get(0); + Assert.assertEquals(juniperTestKit.getJuniperKitId(), nonPepperKitStatus.getJuniperKitId()); + Assert.assertEquals(juniperTestKit.getJuniperParticipantID(), nonPepperKitStatus.getParticipantId()); + Assert.assertEquals("", nonPepperKitStatus.getErrorMessage()); + Assert.assertEquals(false, nonPepperKitStatus.getError()); + Assert.assertTrue(StringUtils.isNotBlank(nonPepperKitStatus.getDsmShippingLabel())); + } + + private JuniperKitRequest generateJuniperKit(int random) { + String participantId = "TEST_PARTICIPANT"; + + String json = "{ \"firstName\":\"P\"," + + "\"lastName\":\"T\"," + + "\"street1\":\"415 Main st\"," + + "\"street2\":null," + + "\"city\":\"Cambridge\"," + + "\"state\":\"MA\"," + + "\"postalCode\":\"02142\"," + + "\"country\":\"USA\"," + + "\"phoneNumber\":\" 111 - 222 - 3344\"," + + "\"juniperKitId\":\"JuniperTestKitId_" + random + "\"," + + "\"juniperParticipantID\":\"" + participantId + random + "\"," + + "\"forceUpload\":false," + + "\"skipAddressValidation\":false," + + "\"juniperStudyID\":\"Juniper-test-guid\"}"; + + return new Gson().fromJson(json, JuniperKitRequest.class); + } + + @Test + public void createNewJuniperKitTest() { + String participantId = "OHSALK_"; + int rand = new Random().nextInt() & Integer.MAX_VALUE; + String kitType = salivaKitType; + String json = "{ \"firstName\":\"P\"," + + "\"lastName\":\"T\"," + + "\"street1\":\"415 Main st\"," + + "\"street2\":null," + + "\"city\":\"Cambridge\"," + + "\"state\":\"MA\"," + + "\"postalCode\":\"02142\"," + + "\"country\":\"USA\"," + + "\"phoneNumber\":\" 111 - 222 - 3344\"," + + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," + + "\"juniperParticipantID\":\"" + participantId + rand + "\"," + + "\"forceUpload\":false," + + "\"skipAddressValidation\":false," + + "\"juniperStudyID\":\"Juniper-test-guid\"}"; + + JuniperKitRequest juniperTestKit = new Gson().fromJson(json, JuniperKitRequest.class); + log.info("Juniper test kit id is {} ", juniperTestKit.getJuniperKitId()); + when(mockEasyPostUtil.checkAddress(any(), anyString())).thenReturn(true); + try { + List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + KitResponse kitCreationResponse = + nonPepperKitCreationService.createNonPepperKit(juniperTestKit, salivaKitType, mockEasyPostUtil, ddpInstance); + List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", salivaKitType); + if (kitCreationResponse.isError()){ + log.error(kitCreationResponse.getErrorMessage().toString()); + } + Assert.assertFalse(kitCreationResponse.isError()); + Assert.assertEquals(newKits.size(), oldkits.size() + 1); + KitRequestShipping newKit = + newKits.stream().filter(kitRequestShipping -> kitRequestShipping.getDdpParticipantId().equals(participantId + rand)) + .findAny().get(); + Assert.assertEquals(newKit.getBspCollaboratorParticipantId(), bspPrefix + "_" + participantId + rand); + Assert.assertEquals(newKit.getBspCollaboratorSampleId(), bspPrefix + "_" + participantId + rand + "_" + kitType); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + @Test + public void noJuniperKitIdTest() { + String participantId = "OHSALK_"; + int rand = new Random().nextInt() & Integer.MAX_VALUE; + String kitType = salivaKitType; + List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + String json = "{ \"firstName\":\"P\"," + + "\"lastName\":\"T\"," + + "\"street1\":\"415 Main st\"," + + "\"street2\":null," + + "\"city\":\"Cambridge\"," + + "\"state\":\"MA\"," + + "\"postalCode\":\"02142\"," + + "\"country\":\"USA\"," + + "\"phoneNumber\":\" 111 - 222 - 3344\"," + + "\"juniperKitId\":null," + + "\"juniperParticipantID\":\"" + participantId + rand + "\"," + + "\"forceUpload\":false," + + "\"skipAddressValidation\":false," + + "\"juniperStudyID\":\"Juniper-test-guid\"}"; + + JuniperKitRequest juniperTestKit = new Gson().fromJson(json, JuniperKitRequest.class); + try { + KitResponse kitResponse = + nonPepperKitCreationService.createNonPepperKit(juniperTestKit, kitType, mockEasyPostUtil, ddpInstance); + Assert.assertEquals(KitResponse.ErrorMessage.MISSING_JUNIPER_KIT_ID, kitResponse.getErrorMessage()); + Assert.assertEquals(null, kitResponse.getValue()); + List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + Assert.assertEquals(newKits.size(), oldkits.size()); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + @Test + public void noJuniperParticipantIdTest() { + String participantId = ""; + int rand = new Random().nextInt() & Integer.MAX_VALUE; + String kitType = salivaKitType; + List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + String json = "{ \"firstName\":\"P\"," + + "\"lastName\":\"T\"," + + "\"street1\":\"415 Main st\"," + + "\"street2\":null," + + "\"city\":\"Cambridge\"," + + "\"state\":\"MA\"," + + "\"postalCode\":\"02142\"," + + "\"country\":\"USA\"," + + "\"phoneNumber\":\" 111 - 222 - 3344\"," + + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," + + "\"juniperParticipantID\":\"" + participantId + "\"," + + "\"forceUpload\":false," + + "\"skipAddressValidation\":false," + + "\"juniperStudyID\":\"Juniper-test-guid\"}"; + + JuniperKitRequest juniperTestKit = new Gson().fromJson(json, JuniperKitRequest.class); + try { + KitResponse kitResponse = + nonPepperKitCreationService.createNonPepperKit(juniperTestKit, salivaKitType, mockEasyPostUtil, ddpInstance); + Assert.assertEquals(KitResponse.ErrorMessage.MISSING_JUNIPER_PARTICIPANT_ID, kitResponse.getErrorMessage()); + Assert.assertEquals("", kitResponse.getValue()); + List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + Assert.assertEquals(newKits.size(), oldkits.size()); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + + @Test + public void invalidKitTypeTest() { + String participantId = "OHSALK_"; + int rand = new Random().nextInt() & Integer.MAX_VALUE; + String kitType = "BLOOD"; + List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + String json = "{ \"firstName\":\"P\"," + + "\"lastName\":\"T\"," + + "\"street1\":\"415 Main st\"," + + "\"street2\":null," + + "\"city\":\"Cambridge\"," + + "\"state\":\"MA\"," + + "\"postalCode\":\"02142\"," + + "\"country\":\"USA\"," + + "\"phoneNumber\":\" 111 - 222 - 3344\"," + + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," + + "\"juniperParticipantID\":\"" + participantId + rand + "\"," + + "\"forceUpload\":false," + + "\"skipAddressValidation\":false," + + "\"juniperStudyID\":\"Juniper-test-guid\"}"; + + JuniperKitRequest juniperTestKit = new Gson().fromJson(json, JuniperKitRequest.class); + try { + KitResponse kitResponse = + nonPepperKitCreationService.createNonPepperKit(juniperTestKit, kitType, mockEasyPostUtil, ddpInstance); + Assert.assertEquals(KitResponse.ErrorMessage.UNKNOWN_KIT_TYPE, kitResponse.getErrorMessage()); + Assert.assertEquals(kitResponse.getValue(), kitType); + List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); + Assert.assertEquals(newKits.size(), oldkits.size()); + } finally { + createdKitIds.add(juniperTestKit.getJuniperKitId()); + } + } + +} diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationTest.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationTest.java deleted file mode 100644 index f723d71fb4..0000000000 --- a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperKitCreationTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package org.broadinstitute.dsm.juniperkits; - -import java.util.List; -import java.util.Random; - -import com.google.gson.Gson; -import com.typesafe.config.Config; -import org.broadinstitute.dsm.DSMServer; -import org.broadinstitute.dsm.TestHelper; -import org.broadinstitute.dsm.db.KitRequestShipping; -import org.broadinstitute.dsm.model.nonpepperkit.JuniperKitRequest; -import org.broadinstitute.dsm.model.nonpepperkit.KitResponse; -import org.broadinstitute.dsm.model.nonpepperkit.NonPepperKitCreationService; -import org.broadinstitute.dsm.statics.ApplicationConfigConstants; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -public class JuniperKitCreationTest { - NonPepperKitCreationService nonPepperKitCreationService = new NonPepperKitCreationService(); - private Config cfg; - - @Before - public void beforeClass() { - TestHelper.setupDB(); - cfg = TestHelper.cfg; - - DSMServer.setupDDPConfigurationLookup(cfg.getString(ApplicationConfigConstants.DDP)); - } - - @Test - @Ignore - public void createNewMockJuniperKitTest() { - String instanceGuid = "Juniper-mock-guid"; - String instanceName = "Juniper-mock"; - String participantId = "OHSALK_"; - int rand = new Random().nextInt() & Integer.MAX_VALUE; - String kitType = "SALIVA"; - - String json = "{ \"firstName\":\"P\"," - + "\"lastName\":\"T\"," - + "\"street1\":\"415 Main st\"," - + "\"street2\":null," - + "\"city\":\"Cambridge\"," - + "\"state\":\"MA\"," - + "\"postalCode\":\"02142\"," - + "\"country\":\"USA\"," - + "\"phoneNumber\":\" 111 - 222 - 3344\"," - + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," - + "\"juniperParticipantID\":\"" + participantId + rand + "\"," - + "\"forceUpload\":false," - + "\"skipAddressValidation\":false," - + "\"juniperStudyID\":\"Juniper-mock-guid\"}"; - - // String json3 = "{\"firstName\":\"P\",\"lastName\":\"T\",\"street1\":\"415 Main st\",\"street2\":\"\",\"city\": - // \"Cambridge\", - // \"state\":\"MA\",\"postalCode\":\"02142\",\"country\":\"USA\",\"phoneNumber\":\"111-222-3344\",\"juniperKitId\": - // \"JuniperTestKitId_110958866\",\"juniperParticipantID\":\"JuniperParticipantId_110958866\",\"juniperStudyID\": - // \"Juniper-mock-guid\"}"; - - JuniperKitRequest mockJuniperKit = new Gson().fromJson(json, JuniperKitRequest.class); - List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - - nonPepperKitCreationService.createNonPepperKit(mockJuniperKit, instanceGuid, "SALIVA"); - List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", "SALIVA"); - Assert.assertEquals(newKits.size(), oldkits.size() + 1); - KitRequestShipping newKit = newKits.stream().filter(kitRequestShipping -> kitRequestShipping.getDdpParticipantId().equals(participantId + rand)).findAny() - .get(); - Assert.assertEquals(newKit.getBspCollaboratorParticipantId(), "JuniperProject_" + participantId + rand); - Assert.assertEquals(newKit.getBspCollaboratorSampleId(), "JuniperProject_" + participantId + rand + "_" + kitType); - } - - @Test - @Ignore - public void noJuniperKitIdTest() { - String instanceGuid = "Juniper-mock-guid"; - String instanceName = "Juniper-mock"; - String participantId = "OHSALK_"; - - int rand = new Random().nextInt() & Integer.MAX_VALUE; - - String kitType = "SALIVA"; - List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - - String json = "{ \"firstName\":\"P\"," - + "\"lastName\":\"T\"," - + "\"street1\":\"415 Main st\"," - + "\"street2\":null," - + "\"city\":\"Cambridge\"," - + "\"state\":\"MA\"," - + "\"postalCode\":\"02142\"," - + "\"country\":\"USA\"," - + "\"phoneNumber\":\" 111 - 222 - 3344\"," - + "\"juniperKitId\":null," - + "\"juniperParticipantID\":\"" + participantId + rand + "\"," - + "\"forceUpload\":false," - + "\"skipAddressValidation\":false," - + "\"juniperStudyID\":\"Juniper-mock-guid\"}"; - - - JuniperKitRequest mockJuniperKit = new Gson().fromJson(json, JuniperKitRequest.class); - - KitResponse kitResponse = nonPepperKitCreationService.createNonPepperKit(mockJuniperKit, instanceGuid, kitType); - Assert.assertEquals(kitResponse.errorMessage, NonPepperKitCreationService.MISSING_JUNIPER_KIT_ID); - Assert.assertEquals(kitResponse.value, null); - - List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - Assert.assertEquals(newKits.size(), oldkits.size()); - } - - @Test - @Ignore - public void noJuniperParticipantIdTest() { - String instanceGuid = "Juniper-mock-guid"; - String instanceName = "Juniper-mock"; - String participantId = ""; - int rand = new Random().nextInt() & Integer.MAX_VALUE; - - String kitType = "SALIVA"; - List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - - - String json = "{ \"firstName\":\"P\"," - + "\"lastName\":\"T\"," - + "\"street1\":\"415 Main st\"," - + "\"street2\":null," - + "\"city\":\"Cambridge\"," - + "\"state\":\"MA\"," - + "\"postalCode\":\"02142\"," - + "\"country\":\"USA\"," - + "\"phoneNumber\":\" 111 - 222 - 3344\"," - + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," - + "\"juniperParticipantID\":\"" + participantId + "\"," - + "\"forceUpload\":false," - + "\"skipAddressValidation\":false," - + "\"juniperStudyID\":\"Juniper-mock-guid\"}"; - - - JuniperKitRequest mockJuniperKit = new Gson().fromJson(json, JuniperKitRequest.class); - - KitResponse kitResponse = nonPepperKitCreationService.createNonPepperKit(mockJuniperKit, instanceGuid, "SALIVA"); - Assert.assertEquals(kitResponse.errorMessage, NonPepperKitCreationService.MISSING_JUNIPER_PARTICIPANT_ID); - Assert.assertEquals(kitResponse.value, ""); - - List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - Assert.assertEquals(newKits.size(), oldkits.size()); - } - - @Test - @Ignore - public void invalidKitTypeTest() { - String instanceGuid = "Juniper-mock-guid"; - String instanceName = "Juniper-mock"; - String participantId = "OHSALK_"; - int rand = new Random().nextInt() & Integer.MAX_VALUE; - - String kitType = "BLOOD"; - List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - - - String json = "{ \"firstName\":\"P\"," - + "\"lastName\":\"T\"," - + "\"street1\":\"415 Main st\"," - + "\"street2\":null," - + "\"city\":\"Cambridge\"," - + "\"state\":\"MA\"," - + "\"postalCode\":\"02142\"," - + "\"country\":\"USA\"," - + "\"phoneNumber\":\" 111 - 222 - 3344\"," - + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," - + "\"juniperParticipantID\":\"" + participantId + rand + "\"," - + "\"forceUpload\":false," - + "\"skipAddressValidation\":false," - + "\"juniperStudyID\":\"Juniper-mock-guid\"}"; - - - JuniperKitRequest mockJuniperKit = new Gson().fromJson(json, JuniperKitRequest.class); - - KitResponse kitResponse = nonPepperKitCreationService.createNonPepperKit(mockJuniperKit, instanceGuid, kitType); - Assert.assertEquals(kitResponse.errorMessage, NonPepperKitCreationService.UNKNOWN_KIT_TYPE); - Assert.assertEquals(kitResponse.value, kitType); - - List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - Assert.assertEquals(newKits.size(), oldkits.size()); - } - - @Test - @Ignore - public void invalidStudyNameTest() { - String fakeInstanceGuid = "Juniper-mock-guid-fake"; - String instanceName = "Juniper-mock"; - String participantId = "OHSALK_"; - int rand = new Random().nextInt() & Integer.MAX_VALUE; - - String kitType = "SALIVA"; - List oldkits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - - - String json = "{ \"firstName\":\"P\"," - + "\"lastName\":\"T\"," - + "\"street1\":\"415 Main st\"," - + "\"street2\":null," - + "\"city\":\"Cambridge\"," - + "\"state\":\"MA\"," - + "\"postalCode\":\"02142\"," - + "\"country\":\"USA\"," - + "\"phoneNumber\":\" 111 - 222 - 3344\"," - + "\"juniperKitId\":\"JuniperTestKitId_" + rand + "\"," - + "\"juniperParticipantID\":\"" + participantId + rand + "\"," - + "\"forceUpload\":false," - + "\"skipAddressValidation\":false," - + "\"juniperStudyID\":\"Juniper-mock-guid\"}"; - - - JuniperKitRequest mockJuniperKit = new Gson().fromJson(json, JuniperKitRequest.class); - - KitResponse kitResponse = nonPepperKitCreationService.createNonPepperKit(mockJuniperKit, fakeInstanceGuid, kitType); - Assert.assertEquals(kitResponse.errorMessage, NonPepperKitCreationService.UNKNOWN_STUDY); - Assert.assertEquals(kitResponse.value, fakeInstanceGuid); - - List newKits = KitRequestShipping.getKitRequestsByRealm(instanceName, "overview", kitType); - Assert.assertEquals(newKits.size(), oldkits.size()); - } - -} diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperSetupUtil.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperSetupUtil.java new file mode 100644 index 0000000000..1871b779e0 --- /dev/null +++ b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/JuniperSetupUtil.java @@ -0,0 +1,307 @@ +package org.broadinstitute.dsm.juniperkits; + +import static org.broadinstitute.ddp.db.TransactionWrapper.inTransaction; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.broadinstitute.dsm.exception.DsmInternalError; +import org.broadinstitute.lddp.db.SimpleResult; + +/** + * This class has methods to set up a Juniper study in DSM database. + * It creates the instance, group, instance_role, kit_type, carrier, + * kit_dimensions, kit_return and ddp_kit_request_settings for the + * newly created study. + * It also contains methods to delete what was set up after tests are complete + */ +@Slf4j +public class JuniperSetupUtil { + private static final String INSERT_JUNIPER_GROUP = + "INSERT INTO ddp_group (name) VALUES ('juniper test') ON DUPLICATE KEY UPDATE name = 'juniper test';"; + private static final String INSERT_JUNIPER_INSTANCE = + "INSERT INTO ddp_instance (instance_name, study_guid, display_name, is_active, bsp_organism, " + + " collaborator_id_prefix, auth0_token) VALUES (?, ?, ?, 1, 1, ?, 0) ON DUPLICATE KEY UPDATE auth0_token = 0;"; + private static final String INSERT_DDP_INSTANCE_GROUP = "INSERT INTO ddp_instance_group (ddp_instance_id, ddp_group_id) " + + " VALUES (?, ?) ON DUPLICATE KEY UPDATE ddp_group_id = ?;"; + private static final String INSERT_INSTANCE_ROLE = "INSERT INTO instance_role (name) " + + " VALUES ('juniper_study') ON DUPLICATE KEY UPDATE name = 'juniper_study';"; + private static final String INSERT_DDP_INSTANCE_ROLE = "INSERT INTO ddp_instance_role (ddp_instance_id, instance_role_id) " + + " VALUES (?, ?) ON DUPLICATE KEY UPDATE instance_role_id = ?;"; + private static final String INSERT_KIT_TYPE = "INSERT INTO kit_type (kit_type_name, bsp_material_type, bsp_receptacle_type) " + + " VALUES ('SALIVA', 'juniper Saliva', 'Oragene Kit') ;"; + private static final String INSERT_KIT_DIMENSION = "INSERT INTO kit_dimension (kit_width, kit_height, kit_length, kit_weight) " + + " VALUES ('6.9', '1.3', '5.2', '3.2') ON DUPLICATE KEY UPDATE kit_width = '6.9';"; + private static final String INSERT_KIT_RETURN = "INSERT INTO kit_return_information (return_address_name, return_address_phone) " + + " VALUES ('Broad Institute', '1111112222') ON DUPLICATE KEY UPDATE return_address_name = 'Broad Institute';"; + private static final String INSERT_CARRIER = "INSERT INTO carrier_service (carrier, service) " + + " VALUES ('FedEx', 'FEDEX_2_DAY') ON DUPLICATE KEY UPDATE carrier = 'FedEx';"; + private static final String INSERT_DDP_KIT_REQUEST_SETTINGS = + "INSERT INTO ddp_kit_request_settings (ddp_instance_id, kit_type_id, kit_return_id, carrier_service_to_id, kit_dimension_id) " + + " VALUES (?, ?, ?, ?, ?) ;"; + private static final String SELECT_DSM_KIT_REQUEST_ID = "SELECT dsm_kit_request_id from ddp_kit_request where ddp_kit_request_id = ?"; + public static String ddpGroupId; + public static String ddpInstanceId; + public static String ddpInstanceGroupId; + public static String instanceRoleId; + public static String ddpInstanceRoleId; + private static String kitTypeId; + private static String kitDimensionId; + private static String kitReturnId; + private static String carrierId; + private static String ddpKitRequestSettingsId; + + private static String instanceName; + private static String studyGuid; + private static String displayName; + private static String collaboratorPrefix; + + public JuniperSetupUtil(String instanceName, String studyGuid, String displayName, String collaboratorPrefix) { + this.instanceName = instanceName; + this.studyGuid = studyGuid; + this.displayName = displayName; + this.collaboratorPrefix = collaboratorPrefix; + + } + + private static String createDdpGroupForJuniper(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(ddpGroupId)) { + return ddpGroupId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_JUNIPER_GROUP, Statement.RETURN_GENERATED_KEYS); + int result = stmt.executeUpdate(); + if (result != 1) { + throw new DsmInternalError("More than 1 row updated"); + } + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "ddp_group"); + } + + public static void deleteJuniperInstanceAndSettings() { + SimpleResult results = inTransaction((conn) -> { + SimpleResult dbVals = new SimpleResult(); + try { + delete(conn, "kit_type", "kit_type_id", kitTypeId); + delete(conn, "kit_dimension", "kit_dimension_id", kitDimensionId); + delete(conn, "kit_return_information", "kit_return_id", kitReturnId); + delete(conn, "carrier_service", "carrier_service_id", carrierId); + delete(conn, "ddp_kit_request_settings", "ddp_kit_request_settings_id", ddpKitRequestSettingsId); + delete(conn, "ddp_instance_role", "ddp_instance_role_id", ddpInstanceRoleId); + delete(conn, "instance_role", "instance_role_id", instanceRoleId); + delete(conn, "ddp_instance_group", "instance_group_id", ddpInstanceGroupId); + delete(conn, "ddp_instance", "ddp_instance_id", ddpInstanceId); + delete(conn, "ddp_group", "group_id", ddpGroupId); + } catch (Exception e) { + dbVals.resultException = e; + } + return dbVals; + }); + + } + + private static void delete(Connection conn, String tableName, String primaryColumn, String id) { + try (PreparedStatement stmt = conn.prepareStatement("DELETE from " + tableName + " WHERE " + primaryColumn + " = ? ;")) { + stmt.setString(1, id); + try { + stmt.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException("Error deleting from " + tableName, e); + } + } catch (SQLException ex) { + throw new RuntimeException("Error deleting ", ex); + } + } + + public static void deleteJuniperKit(String ddpKitRequestId) { + SimpleResult results = inTransaction((conn) -> { + String dsmKitRequestId; + try (PreparedStatement stmt = conn.prepareStatement(SELECT_DSM_KIT_REQUEST_ID)) { + stmt.setString(1, ddpKitRequestId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + dsmKitRequestId = rs.getString("dsm_kit_request_id"); + } else { + log.warn("Kit Not Found " + ddpKitRequestId); + return null; + } + } catch (SQLException e) { + throw new RuntimeException("Error selecting dsm_kit_request_id", e); + } + } catch (SQLException ex) { + throw new RuntimeException("Error deleting ", ex); + } + try { + delete(conn, "ddp_kit", "dsm_kit_request_id", dsmKitRequestId); + delete(conn, "ddp_kit_request", "dsm_kit_request_id", dsmKitRequestId); + } catch (Exception ex) { + throw new RuntimeException("Error deleting kits", ex); + } + return null; + }); + } + + public static void deleteKitsArray(List kitIds) { + for (String kitId : kitIds) { + try { + deleteJuniperKit(kitId); + } catch (Exception e) { + log.error("unable to delete kitId {}", kitId, e); + } finally { + continue; + } + } + + } + + private static String getPrimaryKey(ResultSet rs, String table) throws SQLException { + if (rs.next()) { + return rs.getString(1); + } else { + throw new DsmInternalError(String.format("Unable to set up data in %s for juniper, going to role back transaction", table)); + } + } + + public void setupJuniperInstanceAndSettings() { + + //everything should get inserted in one transaction + SimpleResult results = inTransaction((conn) -> { + SimpleResult simpleResult = new SimpleResult(); + try { + ddpGroupId = createDdpGroupForJuniper(conn); + ddpInstanceId = createDdpInstanceForJuniper(conn); + if (ddpGroupId == null || ddpInstanceId == null) { + throw new DsmInternalError("Something went wrong"); + } + ddpInstanceGroupId = createDdpInstanceGroup(conn); + instanceRoleId = createInstanceRole(conn); + ddpInstanceRoleId = createDdpInstanceRole(conn); + kitTypeId = createKitType(conn); + kitDimensionId = createKitDimension(conn); + kitReturnId = createKitReturnInformation(conn); + carrierId = createCarrierInformation(conn); + ddpKitRequestSettingsId = createKitRequestSettingsInformation(conn); + } catch (SQLException e) { + simpleResult.resultException = e; + } + return simpleResult; + }); + if (results.resultException != null) { + log.error("Error creating juniper data ", results.resultException); + } + } + + private String createKitRequestSettingsInformation(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(ddpKitRequestSettingsId)) { + return ddpKitRequestSettingsId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_DDP_KIT_REQUEST_SETTINGS, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, ddpInstanceId); + stmt.setString(2, kitTypeId); + stmt.setString(3, kitReturnId); + stmt.setString(4, carrierId); + stmt.setString(5, kitDimensionId); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "ddp_kit_request_settings"); + } + + private String createCarrierInformation(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(carrierId)) { + return carrierId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_CARRIER, Statement.RETURN_GENERATED_KEYS); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "carrier_service"); + } + + private String createKitReturnInformation(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(kitReturnId)) { + return kitReturnId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_KIT_RETURN, Statement.RETURN_GENERATED_KEYS); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "kit_return_information"); + } + + private String createKitDimension(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(kitDimensionId)) { + return kitDimensionId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_KIT_DIMENSION, Statement.RETURN_GENERATED_KEYS); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "kit_dimension"); + } + + private String createKitType(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(kitTypeId)) { + return kitTypeId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_KIT_TYPE, Statement.RETURN_GENERATED_KEYS); + int result = stmt.executeUpdate(); + if (result != 1) { + throw new DsmInternalError("More than 1 row updated"); + } + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "kit_type"); + } + + private String createInstanceRole(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(instanceRoleId)) { + return instanceRoleId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_INSTANCE_ROLE, Statement.RETURN_GENERATED_KEYS); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "instance_role"); + } + + private String createDdpInstanceRole(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(ddpInstanceRoleId)) { + return ddpInstanceRoleId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_DDP_INSTANCE_ROLE, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, ddpInstanceId); + stmt.setString(2, instanceRoleId); + stmt.setString(3, instanceRoleId); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "ddp_instance_role"); + } + + private String createDdpInstanceGroup(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(ddpInstanceGroupId)) { + return ddpInstanceGroupId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_DDP_INSTANCE_GROUP, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, ddpInstanceId); + stmt.setString(2, ddpGroupId); + stmt.setString(3, ddpGroupId); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "ddp_instance_group"); + } + + public String createDdpInstanceForJuniper(Connection conn) throws SQLException { + if (StringUtils.isNotBlank(ddpInstanceId)) { + return ddpGroupId; + } + PreparedStatement stmt = conn.prepareStatement(INSERT_JUNIPER_INSTANCE, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, instanceName); + stmt.setString(2, studyGuid); + stmt.setString(3, displayName); + stmt.setString(4, collaboratorPrefix); + stmt.executeUpdate(); + ResultSet rs = stmt.getGeneratedKeys(); + return getPrimaryKey(rs, "ddp_instance"); + } + +} diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/NonPepperKitServiceTest.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/NonPepperKitServiceTest.java new file mode 100644 index 0000000000..4ac968fc60 --- /dev/null +++ b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/juniperkits/NonPepperKitServiceTest.java @@ -0,0 +1,75 @@ +package org.broadinstitute.dsm.juniperkits; + +import static junit.framework.TestCase.assertEquals; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Date; +import java.util.HashMap; +import java.util.TimeZone; + +import org.broadinstitute.dsm.db.dto.user.UserDto; +import org.broadinstitute.dsm.model.nonpepperkit.NonPepperStatusKitService; +import org.junit.Assert; +import org.junit.Test; + +public class NonPepperKitServiceTest { + NonPepperStatusKitService nonPepperStatusKitService = new NonPepperStatusKitService(); + + @Test + public void getUserEmailForFieldsTest() { + UserDto userDto1 = new UserDto(1, "user1", "user1Email", null, 1); + UserDto userDto2 = new UserDto(2, "user2", "user2Email", null, 1); + UserDto userDto3 = new UserDto(3, "user3", "user3Email", null, 1); + UserDto userDto4 = new UserDto(4, "user4", "user4Email", null, 1); + UserDto userDto5 = new UserDto(5, "user5", "user5Email", null, 1); + + HashMap map = new HashMap<>(); + map.put(1, userDto1); + map.put(2, userDto2); + map.put(3, userDto3); + map.put(4, userDto4); + map.put(5, userDto5); + + String user1TestEmail = nonPepperStatusKitService.getUserEmailForFields("1", map); + Assert.assertEquals("user1Email", user1TestEmail); + + String userNewTestEmail = nonPepperStatusKitService.getUserEmailForFields("user6Email", map); + Assert.assertEquals("user6Email", userNewTestEmail); + + String user7TestEmail = nonPepperStatusKitService.getUserEmailForFields("7", map); + Assert.assertEquals("DSM User", user7TestEmail); + + Assert.assertEquals( "", nonPepperStatusKitService.getUserEmailForFields(null, map)); + } + + @Test + public void convertTimeStringIntoTimeStampTest() { + Long now = System.currentTimeMillis(); + String timeStamp = nonPepperStatusKitService.convertTimeStringIntoTimeStamp(now); + Assert.assertNotNull(timeStamp); + + Instant instant = Instant.ofEpochMilli(now).atZone(ZoneId.of("UTC")).toInstant(); + assertEquals(instant.toString(), timeStamp); + + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + formatter.setTimeZone(TimeZone.getTimeZone("UTC")); + //To make strict date format validation + formatter.setLenient(false); + Date parsedDate = null; + try { + parsedDate = formatter.parse(timeStamp); + System.out.println("++validated DATE TIME ++" + formatter.format(parsedDate)); + Assert.assertNotNull(parsedDate); + Assert.assertEquals(parsedDate.toInstant().atZone(ZoneId.of("UTC")).toInstant(), instant); + } catch (ParseException e) { + Assert.fail(); + } + + Long nullValue = null; + timeStamp = nonPepperStatusKitService.convertTimeStringIntoTimeStamp(nullValue); + Assert.assertNull(timeStamp); + } +} diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/model/kit/KitDaoMock.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/model/kit/KitDaoMock.java deleted file mode 100644 index 36f29f20e8..0000000000 --- a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/model/kit/KitDaoMock.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.broadinstitute.dsm.model.kit; - -import java.util.List; -import java.util.Optional; - -import org.broadinstitute.dsm.db.KitRequestShipping; -import org.broadinstitute.dsm.db.dao.kit.KitDao; - -public class KitDaoMock implements KitDao { - @Override - public int create(KitRequestShipping kitRequestShipping) { - return 0; - } - - @Override - public int delete(int id) { - return 0; - } - - @Override - public Optional get(long id) { - return Optional.empty(); - } - - @Override - public Boolean isBloodKit(String kitLabel) { - return false; - } - - @Override - public Boolean hasTrackingScan(String kitLabel) { - return null; - } - - @Override - public Optional updateKitRequest(KitRequestShipping kitRequestShipping, String userId) { - return Optional.empty(); - } - - @Override - public Optional insertKitTracking(KitRequestShipping kitRequestShipping, String userId) { - return Optional.empty(); - } - - @Override - public Optional updateKitReceived(KitRequestShipping kitRequestShipping, String userId) { - return Optional.empty(); - } - - @Override - public Integer insertKit(KitRequestShipping kitRequestShipping) { - return null; - } - - @Override - public Integer insertKitRequest(KitRequestShipping kitRequestShipping) { - return null; - } - - @Override - public Optional getKitRequest(Long kitRequestId) { - return Optional.empty(); - } - - @Override - public Optional getKit(Long kitId) { - return Optional.empty(); - } - - @Override - public Integer deleteKitRequest(Long kitRequestId) { - return null; - } - - @Override - public Integer deleteKit(Long kitId) { - return null; - } - - @Override - public Optional getKitByDdpLabel(String ddpLabel, String kitLabel) { - return Optional.empty(); - } - - @Override - public Optional> getSubkitsByDdpLabel(String ddpLabel, String kitLabel) { - return null; - } - - @Override - public List getKitsByHruid(String hruid) { - return null; - } - - @Override - public Optional updateKitLabel(KitRequestShipping kitRequestShipping) { - return Optional.empty(); - } -} diff --git a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/util/tools/CreateLabelTool.java b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/util/tools/CreateLabelTool.java index f0aa7d0b59..b596aefc0d 100644 --- a/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/util/tools/CreateLabelTool.java +++ b/pepper-apis/dsm-core/src/test/java/org/broadinstitute/dsm/util/tools/CreateLabelTool.java @@ -41,7 +41,7 @@ public static void createEasyPostLabel() { EasyPostUtil easyPostUtil = new EasyPostUtil(null, apiKey); Address toAddress = easyPostUtil.createAddress(participant, "413-404-9083");// pegah's email Address returnAddress = - easyPostUtil.createBroadAddress("Broad Institute", "320 Charles St - Lab 181", "Attn. Broad Genomics", "Cambridge", + easyPostUtil.createAddressWithoutValidation("Broad Institute", "320 Charles St - Lab 181", "Attn. Broad Genomics", "Cambridge", "02141", "MA", "US", "617-714-8952"); // inches and oz Parcel parcel = easyPostUtil.createParcel("8", "2", "7.3", "9.5"); //stool kit sizes diff --git a/pepper-apis/parent-pom.xml b/pepper-apis/parent-pom.xml index 7ad41e97df..774f27ed04 100644 --- a/pepper-apis/parent-pom.xml +++ b/pepper-apis/parent-pom.xml @@ -346,7 +346,7 @@ org.mockito mockito-core - 3.6.28 + 5.4.0 test