diff --git a/sormas-api/src/main/java/de/symeda/sormas/api/FacadeProvider.java b/sormas-api/src/main/java/de/symeda/sormas/api/FacadeProvider.java index de45b55ba00..e465a734151 100644 --- a/sormas-api/src/main/java/de/symeda/sormas/api/FacadeProvider.java +++ b/sormas-api/src/main/java/de/symeda/sormas/api/FacadeProvider.java @@ -108,13 +108,13 @@ import de.symeda.sormas.api.sormastosormas.share.incoming.SormasToSormasShareRequestFacade; import de.symeda.sormas.api.sormastosormas.share.outgoing.ShareRequestInfoFacade; import de.symeda.sormas.api.sormastosormas.share.outgoing.SormasToSormasShareInfoFacade; -//import de.symeda.sormas.api.sormastosormas.caze.SormasToSormasCaseFacade; -//import de.symeda.sormas.api.sormastosormas.contact.SormasToSormasContactFacade; -//import de.symeda.sormas.api.sormastosormas.event.SormasToSormasEventFacade; -//import de.symeda.sormas.api.sormastosormas.externalmessage.SormasToSormasExternalMessageFacade; -//import de.symeda.sormas.api.sormastosormas.shareinfo.SormasToSormasShareInfoFacade; -//import de.symeda.sormas.api.sormastosormas.sharerequest.SormasToSormasShareRequestFacade; -//import de.symeda.sormas.api.sormastosormas.entities.ebs.SormasToSormasEbsFacade; +import de.symeda.sormas.api.sormastosormas.caze.SormasToSormasCaseFacade; +import de.symeda.sormas.api.sormastosormas.contact.SormasToSormasContactFacade; +import de.symeda.sormas.api.sormastosormas.event.SormasToSormasEventFacade; +import de.symeda.sormas.api.sormastosormas.externalmessage.SormasToSormasExternalMessageFacade; +import de.symeda.sormas.api.sormastosormas.shareinfo.SormasToSormasShareInfoFacade; +import de.symeda.sormas.api.sormastosormas.sharerequest.SormasToSormasShareRequestFacade; +import de.symeda.sormas.api.sormastosormas.entities.ebs.SormasToSormasEbsFacade; import de.symeda.sormas.api.symptoms.SymptomsFacade; import de.symeda.sormas.api.systemevents.SystemEventFacade; import de.symeda.sormas.api.systemevents.sync.SyncFacade; diff --git a/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Captions.java b/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Captions.java index df014d8832e..e8ec256b3f9 100644 --- a/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Captions.java +++ b/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Captions.java @@ -788,6 +788,8 @@ public interface Captions { String Configuration_Disease = "Configuration.Disease"; // FormType String Configuration_FormType = "Configuration.FormType"; + String Configuration_Diseases = "Configuration.Diseases"; + String Configuration_Disease = "Configuration.Disease"; String Configuration_Outbreaks = "Configuration.Outbreaks"; String Configuration_PointsOfEntry = "Configuration.PointsOfEntry"; String Contact = "Contact"; @@ -3504,7 +3506,6 @@ public interface Captions { String travelEntryOpenResultingCase = "travelEntryOpenResultingCase"; String travelEntryPointOfEntry = "travelEntryPointOfEntry"; String travelEntryTravelEntriesList = "travelEntryTravelEntriesList"; - String Triaging_animalLaboratoryCategoryDetails = "Triaging.animalFacilityCategoryDetails"; String Treatment = "Treatment"; String Treatment_additionalNotes = "Treatment.additionalNotes"; String Treatment_dose = "Treatment.dose"; @@ -3775,6 +3776,5 @@ public interface Captions { String years = "years"; String dashboardLastReportedDistrict = "Last Reported District"; String exportDownloadMergeFile ="exportDownloadMergeFile" ; - } diff --git a/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Strings.java b/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Strings.java index c84ea28bf45..9a882304c92 100644 --- a/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Strings.java +++ b/sormas-api/src/main/java/de/symeda/sormas/api/i18n/Strings.java @@ -647,6 +647,15 @@ public interface Strings { String headingFillThis = "headingFillThis"; String healthStaffDetailsLabel = "healthStaffDetailsLabel"; String headingChildSeek = "headingChildSeek"; + String headingSignalInformation = "headingSignalInformation"; + String headingSignalVerification = "headingSignalVerification"; + String headingRiskAssessment = "headingRiskAssessment"; + String headingEventDetails = "headingEventDetails"; + String headingRiskDetails = "headingRiskDetails"; + String headingTriagingDecision = "headingTriagingDecision"; + String headingSixtyDay = "headingSixtyDay"; + String headingFillThis = "headingFillThis"; + String headingChildSeek = "headingChildSeek"; String headingHowToMergeCases = "headingHowToMergeCases"; String headingHowToMergeContacts = "headingHowToMergeContacts"; String headingImmunizationsRestored = "headingImmunizationsRestored"; @@ -1769,4 +1778,29 @@ public interface Strings { String messageTriagingSavedShort = "messageTriagingSavedShort"; String messageAlertSavedShort = "messageAlertSavedShort"; String messageSignalVerificationSavedShort = "messageSignalVerificationSavedShort"; + String LowRiskReccomendation = "LowRiskReccomendation"; + String LowRiskNotificationTYpe = "LowRiskNotificationTYpe"; + String LowRiskNotificationAction = "LowRiskNotificationAction"; + String messageRiskAssessmentSavedShort = "messageRiskAssessmentSavedShort"; + String messageTriagingSavedShort = "messageTriagingSavedShort"; + String messageAlertSavedShort = "messageAlertSavedShort"; + String messageSignalVerificationSavedShort = "messageSignalVerificationSavedShort"; + String VeryHighRisk = "VeryHighRisk"; + String HighRisk = "HighRisk"; + String ModerateRisk = "ModerateRisk"; + String LowRisk = "LowRisk"; + String RecommendedActions = "RecommendedActions"; + String NotificationType = "NotificationType"; + String NotificationAction = "NotificationAction"; + String VeryHighRiskRecommendation = "VeryHighRiskRecommendation"; + String VeryHighRiskNotificationType = "VeryHighRiskNotificationType"; + String VeryHighRiskNotificationAction = "VeryHighRiskNotificationAction"; + String HighRiskRecommendation = "HighRiskRecommendation"; + String HighRiskNotificationType = "HighRiskNotificationType"; + String HighRiskNotificationAction = "HighRiskNotificationAction"; + String ModerateRiskRecommendation = "ModerateRiskRecommendation"; + String ModerateRiskNotifcationType = "ModerateRiskNotifcationType"; + String ModerateRiskNotificationAction = "ModerateRiskNotificationAction"; + String headingCreateNewAssessment = "headingCreateNewAssessment"; + String headingCreateNewAlert = "headingCreateNewAlert"; } diff --git a/sormas-api/src/main/java/de/symeda/sormas/api/sample/PathogenTestFacade.java b/sormas-api/src/main/java/de/symeda/sormas/api/sample/PathogenTestFacade.java index 8fd6c48e260..d0bc07e925f 100644 --- a/sormas-api/src/main/java/de/symeda/sormas/api/sample/PathogenTestFacade.java +++ b/sormas-api/src/main/java/de/symeda/sormas/api/sample/PathogenTestFacade.java @@ -67,5 +67,7 @@ public interface PathogenTestFacade { List getByPersonNames(List personUuid); + Boolean checkIfPathogenTestIsTheFirst(String sampleUuid, String pathogenTestUuid); + } diff --git a/sormas-api/src/main/java/de/symeda/sormas/api/share/ExternalShareInfoCriteria.java b/sormas-api/src/main/java/de/symeda/sormas/api/share/ExternalShareInfoCriteria.java index 59bf87612df..ebeaeed26fb 100644 --- a/sormas-api/src/main/java/de/symeda/sormas/api/share/ExternalShareInfoCriteria.java +++ b/sormas-api/src/main/java/de/symeda/sormas/api/share/ExternalShareInfoCriteria.java @@ -34,6 +34,7 @@ public class ExternalShareInfoCriteria implements Serializable { @AuditIncludeProperty private EbsReferenceDto ebs; + private EbsReferenceDto ebs; public CaseReferenceDto getCaze() { return caze; diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/caze/CaseDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/caze/CaseDtoHelper.java index fc937e96812..8412d039d68 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/caze/CaseDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/caze/CaseDtoHelper.java @@ -69,15 +69,6 @@ public class CaseDtoHelper extends PersonDependentDtoHelper { private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); private HealthConditionsDtoHelper healthConditionsDtoHelper = new HealthConditionsDtoHelper(); - public static CaseReferenceDto toReferenceDto(Case ado) { - if (ado == null) { - return null; - } - CaseReferenceDto dto = new CaseReferenceDto(ado.getUuid()); - - return dto; - } - @Override protected Class getAdoClass() { return Case.class; @@ -89,7 +80,7 @@ protected Class getDtoClass() { } @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { return RetroProvider.getCaseFacade().pullAllSince(since, size, lastSynchronizedUuid); } @@ -510,6 +501,15 @@ protected long getApproximateJsonSizeInBytes() { return CaseDataDto.APPROXIMATE_JSON_SIZE_IN_BYTES; } + public static CaseReferenceDto toReferenceDto(Case ado) { + if (ado == null) { + return null; + } + CaseReferenceDto dto = new CaseReferenceDto(ado.getUuid()); + + return dto; + } + @Override protected PersonReferenceDto getPerson(CaseDataDto dto) { return dto.getPerson(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/common/DatabaseHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/common/DatabaseHelper.java index b407c604ba1..67e4ec631bf 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/common/DatabaseHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/common/DatabaseHelper.java @@ -48,6 +48,7 @@ import de.symeda.sormas.api.Disease; import de.symeda.sormas.api.caze.VaccinationStatus; + import de.symeda.sormas.api.caze.Vaccine; import de.symeda.sormas.api.caze.VaccineManufacturer; import de.symeda.sormas.api.epidata.AnimalCondition; @@ -62,10 +63,10 @@ import de.symeda.sormas.api.user.JurisdictionLevel; import de.symeda.sormas.api.utils.DataHelper; import de.symeda.sormas.api.utils.YesNoUnknown; -import de.symeda.sormas.app.backend.activityascase.ActivityAsCase; -import de.symeda.sormas.app.backend.activityascase.ActivityAsCaseDao; import de.symeda.sormas.app.backend.auditlog.AuditLogEntry; import de.symeda.sormas.app.backend.auditlog.AuditLogEntryDao; +import de.symeda.sormas.app.backend.activityascase.ActivityAsCase; +import de.symeda.sormas.app.backend.activityascase.ActivityAsCaseDao; import de.symeda.sormas.app.backend.campaign.Campaign; import de.symeda.sormas.app.backend.campaign.CampaignDao; import de.symeda.sormas.app.backend.campaign.data.CampaignFormData; @@ -102,9 +103,6 @@ import de.symeda.sormas.app.backend.ebs.riskAssessment.RiskAssessment; import de.symeda.sormas.app.backend.ebs.riskAssessment.RiskAssessmentDao; import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerification; -import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerificationDao; -import de.symeda.sormas.app.backend.ebs.triaging.Triaging; -import de.symeda.sormas.app.backend.ebs.triaging.TriagingDao; import de.symeda.sormas.app.backend.environment.Environment; import de.symeda.sormas.app.backend.environment.EnvironmentDao; import de.symeda.sormas.app.backend.epidata.EpiData; @@ -168,6 +166,7 @@ import de.symeda.sormas.app.backend.sample.PathogenTestDao; import de.symeda.sormas.app.backend.sample.Sample; import de.symeda.sormas.app.backend.sample.SampleDao; +import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerificationDao; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfo; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfoDao; import de.symeda.sormas.app.backend.symptoms.Symptoms; @@ -182,6 +181,8 @@ import de.symeda.sormas.app.backend.therapy.TherapyDao; import de.symeda.sormas.app.backend.therapy.Treatment; import de.symeda.sormas.app.backend.therapy.TreatmentDao; +import de.symeda.sormas.app.backend.ebs.triaging.Triaging; +import de.symeda.sormas.app.backend.ebs.triaging.TriagingDao; import de.symeda.sormas.app.backend.user.User; import de.symeda.sormas.app.backend.user.UserDao; import de.symeda.sormas.app.backend.user.UserRole; @@ -207,15 +208,30 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // public static final int DATABASE_VERSION = 307; //public static final int DATABASE_VERSION = 343; - public static final int DATABASE_VERSION = 359; + public static final int DATABASE_VERSION = 347; private static DatabaseHelper instance = null; - private final Context context; - private final HashMap, AbstractAdoDao> adoDaos = new HashMap<>(); + + public static void init(Context context) { + init(context, DATABASE_NAME); + } + + public static void init(Context context, String databaseName) { + if (instance != null) { + Log.e(DatabaseHelper.class.getName(), "DatabaseHelper has already been initalized"); + } + instance = new DatabaseHelper(context, databaseName); + } + private boolean clearingTables = false; private ConfigDao configDao = null; + private final Context context; + + private final HashMap, AbstractAdoDao> adoDaos = new HashMap<>(); + private SyncLogDao syncLogDao = null; + private LbdsSyncDao lbdsSyncDao = null; private DatabaseHelper(Context context, String databaseName) { @@ -225,17 +241,6 @@ private DatabaseHelper(Context context, String databaseName) { this.getReadableDatabase(); } - public static void init(Context context) { - init(context, DATABASE_NAME); - } - - public static void init(Context context, String databaseName) { - if (instance != null) { - Log.e(DatabaseHelper.class.getName(), "DatabaseHelper has already been initalized"); - } - instance = new DatabaseHelper(context, databaseName); - } - public static void clearTables(boolean clearInfrastructure) { if (instance.clearingTables) { return; @@ -331,404 +336,94 @@ public static void clearConfigTable() { } } - public static AbstractAdoDao getAdoDao(Class type) { - - if (!instance.adoDaos.containsKey(type)) { - synchronized (DatabaseHelper.class) { - return instance.getAdoDaoInner(type); - } - } - return (AbstractAdoDao) instance.adoDaos.get(type); - } - - public static ConfigDao getConfigDao() { - if (instance.configDao == null) { - synchronized (DatabaseHelper.class) { - if (instance.configDao == null) { - try { - instance.configDao = new ConfigDao((Dao) instance.getDao(Config.class)); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't build ConfigDao", e); - throw new RuntimeException(e); - } - } - } + /** + * This is called when the database is first created. Usually you should call createTable statements here to build + * the tables that will store your data. + */ + @Override + public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { + try { + Log.i(DatabaseHelper.class.getName(), "onCreate"); + TableUtils.createTableIfNotExists(connectionSource, Config.class); + TableUtils.createTable(connectionSource, Location.class); + TableUtils.createTable(connectionSource, Continent.class); + TableUtils.createTable(connectionSource, Subcontinent.class); + TableUtils.createTable(connectionSource, Country.class); + TableUtils.createTable(connectionSource, Area.class); + TableUtils.createTable(connectionSource, Region.class); + TableUtils.createTable(connectionSource, District.class); + TableUtils.createTable(connectionSource, Community.class); + TableUtils.createTable(connectionSource, Facility.class); + TableUtils.createTable(connectionSource, PointOfEntry.class); + TableUtils.createTable(connectionSource, DiseaseConfiguration.class); + TableUtils.createTable(connectionSource, CustomizableEnumValue.class); + TableUtils.createTable(connectionSource, FeatureConfiguration.class); + TableUtils.createTable(connectionSource, UserRole.class); + TableUtils.createTable(connectionSource, User.class); + TableUtils.createTable(connectionSource, UserUserRole.class); + TableUtils.createTable(connectionSource, Person.class); + TableUtils.createTable(connectionSource, PersonContactDetail.class); + TableUtils.createTable(connectionSource, Case.class); + TableUtils.createTable(connectionSource, Immunization.class); + TableUtils.createTable(connectionSource, Vaccination.class); + TableUtils.createTable(connectionSource, Symptoms.class); + TableUtils.createTable(connectionSource, Therapy.class); + TableUtils.createTable(connectionSource, Prescription.class); + TableUtils.createTable(connectionSource, Treatment.class); + TableUtils.createTable(connectionSource, HealthConditions.class); + TableUtils.createTable(connectionSource, ClinicalCourse.class); + TableUtils.createTable(connectionSource, ClinicalVisit.class); + TableUtils.createTable(connectionSource, MaternalHistory.class); + TableUtils.createTable(connectionSource, PortHealthInfo.class); + TableUtils.createTable(connectionSource, Contact.class); + TableUtils.createTable(connectionSource, Visit.class); + TableUtils.createTable(connectionSource, Task.class); + TableUtils.createTable(connectionSource, Event.class); + TableUtils.createTable(connectionSource, Ebs.class); + TableUtils.createTable(connectionSource, Triaging.class); + TableUtils.createTable(connectionSource, SignalVerification.class); + TableUtils.createTable(connectionSource, RiskAssessment.class); + TableUtils.createTable(connectionSource, EbsAlert.class); + TableUtils.createTable(connectionSource, Sample.class); + TableUtils.createTable(connectionSource, PathogenTest.class); + TableUtils.createTable(connectionSource, AdditionalTest.class); + TableUtils.createTable(connectionSource, EventParticipant.class); + TableUtils.createTable(connectionSource, Hospitalization.class); + TableUtils.createTable(connectionSource, PreviousHospitalization.class); + TableUtils.createTable(connectionSource, EpiData.class); + TableUtils.createTable(connectionSource, Exposure.class); + TableUtils.createTable(connectionSource, ActivityAsCase.class); + TableUtils.createTable(connectionSource, SyncLog.class); + TableUtils.createTable(connectionSource, WeeklyReport.class); + TableUtils.createTable(connectionSource, WeeklyReportEntry.class); + TableUtils.createTable(connectionSource, AggregateReport.class); + TableUtils.createTable(connectionSource, Outbreak.class); + TableUtils.createTable(connectionSource, DiseaseClassificationCriteria.class); + TableUtils.createTable(connectionSource, SormasToSormasOriginInfo.class); + TableUtils.createTable(connectionSource, Campaign.class); + TableUtils.createTable(connectionSource, CampaignFormData.class); + TableUtils.createTable(connectionSource, CampaignFormMeta.class); + TableUtils.createTable(connectionSource, LbdsSync.class); + TableUtils.createTable(connectionSource, Environment.class); + TableUtils.createTable(connectionSource, FormBuilder.class); + TableUtils.createTable(connectionSource, FormField.class); + TableUtils.createTable(connectionSource, FormBuilderFormField.class); + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't build database", e); + throw new RuntimeException(e); } - return instance.configDao; } - public static SyncLogDao getSyncLogDao() { - if (instance.syncLogDao == null) { - synchronized (DatabaseHelper.class) { - if (instance.syncLogDao == null) { - try { - instance.syncLogDao = new SyncLogDao((Dao) instance.getDao(SyncLog.class)); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't build SyncLogDao", e); - throw new RuntimeException(e); - } - } - } - } - return instance.syncLogDao; - } + /** + * This is called when your application is upgraded and it has a higher version number. This allows you to adjust + * the various data to match the new version number. + */ + @Override + public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { - public static LbdsSyncDao getLbdsSyncDao() { - if (instance.lbdsSyncDao == null) { - synchronized (DatabaseHelper.class) { - if (instance.lbdsSyncDao == null) { - try { - instance.lbdsSyncDao = new LbdsSyncDao((Dao) instance.getDao(LbdsSync.class)); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't build SyncLogDao", e); - throw new RuntimeException(e); - } - } - } - } - return instance.lbdsSyncDao; - } - - public static CaseDao getCaseDao() { - return (CaseDao) getAdoDao(Case.class); - } - - public static ImmunizationDao getImmunizationDao() { - return (ImmunizationDao) getAdoDao(Immunization.class); - } - - public static VaccinationDao getVaccinationDao() { - return (VaccinationDao) getAdoDao(Vaccination.class); - } - - public static TherapyDao getTherapyDao() { - return (TherapyDao) getAdoDao(Therapy.class); - } - - public static PrescriptionDao getPrescriptionDao() { - return (PrescriptionDao) getAdoDao(Prescription.class); - } - - public static TreatmentDao getTreatmentDao() { - return (TreatmentDao) getAdoDao(Treatment.class); - } - - public static ClinicalCourseDao getClinicalCourseDao() { - return (ClinicalCourseDao) getAdoDao(ClinicalCourse.class); - } - - public static HealthConditionsDao getHealthConditionsDao() { - return (HealthConditionsDao) getAdoDao(HealthConditions.class); - } - - public static ClinicalVisitDao getClinicalVisitDao() { - return (ClinicalVisitDao) getAdoDao(ClinicalVisit.class); - } - - public static MaternalHistoryDao getMaternalHistoryDao() { - return (MaternalHistoryDao) getAdoDao(MaternalHistory.class); - } - - public static PortHealthInfoDao getPortHealthInfoDao() { - return (PortHealthInfoDao) getAdoDao(PortHealthInfo.class); - } - - public static PersonDao getPersonDao() { - return (PersonDao) getAdoDao(Person.class); - } - - public static LocationDao getLocationDao() { - return (LocationDao) getAdoDao(Location.class); - } - - public static PersonContactDetailDao getPersonContactDetailDao() { - return (PersonContactDetailDao) getAdoDao(PersonContactDetail.class); - } - - public static PointOfEntryDao getPointOfEntryDao() { - return (PointOfEntryDao) getAdoDao(PointOfEntry.class); - } - - public static FacilityDao getFacilityDao() { - return (FacilityDao) getAdoDao(Facility.class); - } - - public static ContinentDao getContinentDao() { - return (ContinentDao) getAdoDao(Continent.class); - } - - public static SubcontinentDao getSubcontinentDao() { - return (SubcontinentDao) getAdoDao(Subcontinent.class); - } - - public static CountryDao getCountryDao() { - return (CountryDao) getAdoDao(Country.class); - } - - public static RegionDao getRegionDao() { - return (RegionDao) getAdoDao(Region.class); - } - - public static AreaDao getAreaDao() { - return (AreaDao) getAdoDao(Area.class); - } - - public static DistrictDao getDistrictDao() { - return (DistrictDao) getAdoDao(District.class); - } - - public static CommunityDao getCommunityDao() { - return (CommunityDao) getAdoDao(Community.class); - } - - public static UserDao getUserDao() { - return (UserDao) getAdoDao(User.class); - } - - public static UserRoleDao getUserRoleDao() { - return (UserRoleDao) getAdoDao(UserRole.class); - } - - public static DiseaseConfigurationDao getDiseaseConfigurationDao() { - return (DiseaseConfigurationDao) getAdoDao(DiseaseConfiguration.class); - } - - public static CustomizableEnumValueDao getCustomizableEnumValueDao() { - return (CustomizableEnumValueDao) getAdoDao(CustomizableEnumValue.class); - } - - public static FeatureConfigurationDao getFeatureConfigurationDao() { - return (FeatureConfigurationDao) getAdoDao(FeatureConfiguration.class); - } - - public static FormFieldDao getFormFieldDao() { - return (FormFieldDao) getAdoDao(FormField.class); - } - - public static FormBuilderDao getFormBuilderDao() { - return (FormBuilderDao) getAdoDao(FormBuilder.class); - } - - public static SymptomsDao getSymptomsDao() { - return (SymptomsDao) getAdoDao(Symptoms.class); - } - - public static TaskDao getTaskDao() { - return (TaskDao) getAdoDao(Task.class); - } - - public static ContactDao getContactDao() { - return (ContactDao) getAdoDao(Contact.class); - } - - public static VisitDao getVisitDao() { - return (VisitDao) getAdoDao(Visit.class); - } - - public static EventDao getEventDao() { - return (EventDao) getAdoDao(Event.class); - } - - public static EbsDao getEbsDao() { - return (EbsDao) getAdoDao(Ebs.class); - } - - public static TriagingDao getTriagingDao() { - return (TriagingDao) getAdoDao(Triaging.class); - } - - public static SignalVerificationDao getSignalVerificationDao() { - return (SignalVerificationDao) getAdoDao(SignalVerification.class); - } - - public static RiskAssessmentDao getRiskAssessmentDao() { - return (RiskAssessmentDao) getAdoDao(RiskAssessment.class); - } - - public static EbsAlertDao getEbsAlertDao() { - return (EbsAlertDao) getAdoDao(EbsAlert.class); - } - - public static EventParticipantDao getEventParticipantDao() { - return (EventParticipantDao) getAdoDao(EventParticipant.class); - } - - public static SampleDao getSampleDao() { - return (SampleDao) getAdoDao(Sample.class); - } - - public static PathogenTestDao getSampleTestDao() { - return (PathogenTestDao) getAdoDao(PathogenTest.class); - } - - public static AdditionalTestDao getAdditionalTestDao() { - return (AdditionalTestDao) getAdoDao(AdditionalTest.class); - } - - public static HospitalizationDao getHospitalizationDao() { - return (HospitalizationDao) getAdoDao(Hospitalization.class); - } - - public static PreviousHospitalizationDao getPreviousHospitalizationDao() { - return (PreviousHospitalizationDao) getAdoDao(PreviousHospitalization.class); - } - - public static EpiDataDao getEpiDataDao() { - return (EpiDataDao) getAdoDao(EpiData.class); - } - - public static ExposureDao getExposureDao() { - return (ExposureDao) getAdoDao(Exposure.class); - } - - public static ActivityAsCaseDao getActivityAsCaseDao() { - return (ActivityAsCaseDao) getAdoDao(ActivityAsCase.class); - } - - public static WeeklyReportDao getWeeklyReportDao() { - return (WeeklyReportDao) getAdoDao(WeeklyReport.class); - } - - public static WeeklyReportEntryDao getWeeklyReportEntryDao() { - return (WeeklyReportEntryDao) getAdoDao(WeeklyReportEntry.class); - } - - public static OutbreakDao getOutbreakDao() { - return (OutbreakDao) getAdoDao(Outbreak.class); - } - - public static DiseaseClassificationCriteriaDao getDiseaseClassificationCriteriaDao() { - return (DiseaseClassificationCriteriaDao) getAdoDao(DiseaseClassificationCriteria.class); - } - - public static AggregateReportDao getAggregateReportDao() { - return (AggregateReportDao) getAdoDao(AggregateReport.class); - } - - public static CampaignDao getCampaignDao() { - return (CampaignDao) getAdoDao(Campaign.class); - } - - public static CampaignFormMetaDao getCampaignFormMetaDao() { - return (CampaignFormMetaDao) getAdoDao(CampaignFormMeta.class); - } - - public static CampaignFormDataDao getCampaignFormDataDao() { - return (CampaignFormDataDao) getAdoDao(CampaignFormData.class); - } - - public static AuditLogEntryDao getAuditLogEntryDao() { - return (AuditLogEntryDao) getAdoDao(AuditLogEntry.class); - } - - // TODO [vaccination info] integrate vaccination info -// public static VaccinationInfoDao getVaccinationInfoDao() { -// return (VaccinationInfoDao) getAdoDao(VaccinationInfo.class); -// } - public static EnvironmentDao getEnvironmentDao() { - return (EnvironmentDao) getAdoDao(Environment.class); - } - - public static Context getContext() { - return instance.context; - } - - public static String getString(int stringResourceId) { - if (instance.context == null) { - return null; - } - - return instance.context.getResources().getString(stringResourceId); - } - - /** - * This is called when the database is first created. Usually you should call createTable statements here to build - * the tables that will store your data. - */ - @Override - public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { - try { - Log.i(DatabaseHelper.class.getName(), "onCreate"); - TableUtils.createTableIfNotExists(connectionSource, Config.class); - TableUtils.createTable(connectionSource, Location.class); - TableUtils.createTable(connectionSource, Continent.class); - TableUtils.createTable(connectionSource, Subcontinent.class); - TableUtils.createTable(connectionSource, Country.class); - TableUtils.createTable(connectionSource, Area.class); - TableUtils.createTable(connectionSource, Region.class); - TableUtils.createTable(connectionSource, District.class); - TableUtils.createTable(connectionSource, Community.class); - TableUtils.createTable(connectionSource, Facility.class); - TableUtils.createTable(connectionSource, PointOfEntry.class); - TableUtils.createTable(connectionSource, DiseaseConfiguration.class); - TableUtils.createTable(connectionSource, CustomizableEnumValue.class); - TableUtils.createTable(connectionSource, FeatureConfiguration.class); - TableUtils.createTable(connectionSource, UserRole.class); - TableUtils.createTable(connectionSource, User.class); - TableUtils.createTable(connectionSource, UserUserRole.class); - TableUtils.createTable(connectionSource, Person.class); - TableUtils.createTable(connectionSource, PersonContactDetail.class); - TableUtils.createTable(connectionSource, Case.class); - TableUtils.createTable(connectionSource, Immunization.class); - TableUtils.createTable(connectionSource, Vaccination.class); - TableUtils.createTable(connectionSource, Symptoms.class); - TableUtils.createTable(connectionSource, Therapy.class); - TableUtils.createTable(connectionSource, Prescription.class); - TableUtils.createTable(connectionSource, Treatment.class); - TableUtils.createTable(connectionSource, HealthConditions.class); - TableUtils.createTable(connectionSource, ClinicalCourse.class); - TableUtils.createTable(connectionSource, ClinicalVisit.class); - TableUtils.createTable(connectionSource, MaternalHistory.class); - TableUtils.createTable(connectionSource, PortHealthInfo.class); - TableUtils.createTable(connectionSource, Contact.class); - TableUtils.createTable(connectionSource, Visit.class); - TableUtils.createTable(connectionSource, Task.class); - TableUtils.createTable(connectionSource, Event.class); - TableUtils.createTable(connectionSource, Ebs.class); - TableUtils.createTable(connectionSource, Triaging.class); - TableUtils.createTable(connectionSource, SignalVerification.class); - TableUtils.createTable(connectionSource, RiskAssessment.class); - TableUtils.createTable(connectionSource, EbsAlert.class); - TableUtils.createTable(connectionSource, Sample.class); - TableUtils.createTable(connectionSource, PathogenTest.class); - TableUtils.createTable(connectionSource, AdditionalTest.class); - TableUtils.createTable(connectionSource, EventParticipant.class); - TableUtils.createTable(connectionSource, Hospitalization.class); - TableUtils.createTable(connectionSource, PreviousHospitalization.class); - TableUtils.createTable(connectionSource, EpiData.class); - TableUtils.createTable(connectionSource, Exposure.class); - TableUtils.createTable(connectionSource, ActivityAsCase.class); - TableUtils.createTable(connectionSource, SyncLog.class); - TableUtils.createTable(connectionSource, WeeklyReport.class); - TableUtils.createTable(connectionSource, WeeklyReportEntry.class); - TableUtils.createTable(connectionSource, AggregateReport.class); - TableUtils.createTable(connectionSource, Outbreak.class); - TableUtils.createTable(connectionSource, DiseaseClassificationCriteria.class); - TableUtils.createTable(connectionSource, SormasToSormasOriginInfo.class); - TableUtils.createTable(connectionSource, Campaign.class); - TableUtils.createTable(connectionSource, CampaignFormData.class); - TableUtils.createTable(connectionSource, CampaignFormMeta.class); - TableUtils.createTable(connectionSource, LbdsSync.class); - TableUtils.createTable(connectionSource, Environment.class); - TableUtils.createTable(connectionSource, FormBuilder.class); - TableUtils.createTable(connectionSource, FormField.class); - TableUtils.createTable(connectionSource, FormBuilderFormField.class); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't build database", e); - throw new RuntimeException(e); - } - } - - /** - * This is called when your application is upgraded and it has a higher version number. This allows you to adjust - * the various data to match the new version number. - */ - @Override - public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { - - if (oldVersion < 91) { - upgradeFromUnupgradableVersion(db, connectionSource, oldVersion); - return; + if (oldVersion < 91) { + upgradeFromUnupgradableVersion(db, connectionSource, oldVersion); + return; } // see http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_4.html#Upgrading-Schema @@ -1836,46 +1531,46 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int getDao(Event.class).executeRaw("ALTER TABLE events RENAME TO tmp_events;"); //@formatter:off - getDao(Event.class).executeRaw( - "CREATE TABLE events (" - + " disease VARCHAR," - + " diseaseDetails VARCHAR," - + " endDate BIGINT," - + " eventDesc VARCHAR," - + " eventLocation_id BIGINT," - + " eventStatus VARCHAR," - + " eventType VARCHAR," - + " externalId VARCHAR," - + " nosocomial VARCHAR," - + " reportDateTime BIGINT," - + " reportLat DOUBLE PRECISION," - + " reportLatLonAccuracy FLOAT," - + " reportLon DOUBLE PRECISION," - + " reportingUser_id BIGINT," - + " srcEmail VARCHAR," - + " srcFirstName VARCHAR," - + " srcLastName VARCHAR," - + " srcMediaDetails VARCHAR," - + " srcMediaName VARCHAR," - + " srcMediaWebsite VARCHAR," - + " srcTelNo VARCHAR," - + " srcType VARCHAR," - + " startDate BIGINT," - + " surveillanceOfficer_id BIGINT," - + " typeOfPlace VARCHAR," - + " typeOfPlaceText VARCHAR," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Event.class).executeRaw( + "CREATE TABLE events (" + + " disease VARCHAR," + + " diseaseDetails VARCHAR," + + " endDate BIGINT," + + " eventDesc VARCHAR," + + " eventLocation_id BIGINT," + + " eventStatus VARCHAR," + + " eventType VARCHAR," + + " externalId VARCHAR," + + " nosocomial VARCHAR," + + " reportDateTime BIGINT," + + " reportLat DOUBLE PRECISION," + + " reportLatLonAccuracy FLOAT," + + " reportLon DOUBLE PRECISION," + + " reportingUser_id BIGINT," + + " srcEmail VARCHAR," + + " srcFirstName VARCHAR," + + " srcLastName VARCHAR," + + " srcMediaDetails VARCHAR," + + " srcMediaName VARCHAR," + + " srcMediaWebsite VARCHAR," + + " srcTelNo VARCHAR," + + " srcType VARCHAR," + + " startDate BIGINT," + + " surveillanceOfficer_id BIGINT," + + " typeOfPlace VARCHAR," + + " typeOfPlaceText VARCHAR," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on db.execSQL("INSERT INTO events (" + queryColumns.replace("eventDate", "startDate") + ") SELECT " + queryColumns + " FROM tmp_events"); db.execSQL("DROP TABLE tmp_events;"); @@ -1960,31 +1655,31 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int db.execSQL("ALTER TABLE visits RENAME TO visits_old;"); //@formatter:off - getDao(Visit.class).executeRaw( - "CREATE TABLE visits (" - + " disease VARCHAR," - + " person_id BIGINT NOT NULL," - + " reportLat DOUBLE PRECISION," - + " reportLatLonAccuracy FLOAT," - + " reportLon DOUBLE PRECISION," - + " symptoms_id BIGINT," - + " visitDateTime BIGINT NOT NULL," - + " visitRemarks VARCHAR," - + " visitStatus VARCHAR," - + " visitUser_id BIGINT," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Visit.class).executeRaw( + "CREATE TABLE visits (" + + " disease VARCHAR," + + " person_id BIGINT NOT NULL," + + " reportLat DOUBLE PRECISION," + + " reportLatLonAccuracy FLOAT," + + " reportLon DOUBLE PRECISION," + + " symptoms_id BIGINT," + + " visitDateTime BIGINT NOT NULL," + + " visitRemarks VARCHAR," + + " visitStatus VARCHAR," + + " visitUser_id BIGINT," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on db.execSQL("INSERT INTO visits (" + visitQueryColumns + ") SELECT " + visitQueryColumns + " FROM visits_old;"); db.execSQL("DROP TABLE visits_old;"); @@ -2164,64 +1859,64 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int db.execSQL("ALTER TABLE person RENAME TO person_old;"); //@formatter:off - getDao(Person.class).executeRaw( - "CREATE TABLE person (" - + " address_id BIGINT," - + " approximateAge INTEGER," - + " approximateAgeReferenceDate BIGINT," - + " approximateAgeType VARCHAR," - + " birthWeight INTEGER," - + " birthdateDD INTEGER," - + " birthdateMM INTEGER," - + " birthdateYYYY INTEGER," - + " burialConductor VARCHAR," - + " burialDate BIGINT," - + " burialPlaceDescription VARCHAR," - + " causeOfDeath VARCHAR," - + " causeOfDeathDetails VARCHAR," - + " causeOfDeathDisease VARCHAR," - + " deathDate BIGINT," - + " deathPlaceDescription VARCHAR," - + " deathPlaceType VARCHAR," - + " educationDetails VARCHAR," - + " educationType VARCHAR," - + " emailAddress VARCHAR," - + " externalId VARCHAR," - + " fathersName VARCHAR," - + " firstName VARCHAR NOT NULL," - + " generalPractitionerDetails VARCHAR," - + " gestationAgeAtBirth INTEGER," - + " lastName VARCHAR NOT NULL," - + " mothersMaidenName VARCHAR," - + " mothersName VARCHAR," - + " nationalHealthId VARCHAR," - + " nickname VARCHAR," - + " occupationDetails VARCHAR," - + " occupationType VARCHAR," - + " passportNumber VARCHAR," - + " phone VARCHAR," - + " phoneOwner VARCHAR," - + " placeOfBirthCommunity_id BIGINT," - + " placeOfBirthDistrict_id BIGINT," - + " placeOfBirthFacility_id BIGINT," - + " placeOfBirthFacilityDetails VARCHAR," - + " placeOfBirthFacilityType VARCHAR," - + " placeOfBirthRegion_id BIGINT," - + " presentCondition VARCHAR," - + " sex VARCHAR," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Person.class).executeRaw( + "CREATE TABLE person (" + + " address_id BIGINT," + + " approximateAge INTEGER," + + " approximateAgeReferenceDate BIGINT," + + " approximateAgeType VARCHAR," + + " birthWeight INTEGER," + + " birthdateDD INTEGER," + + " birthdateMM INTEGER," + + " birthdateYYYY INTEGER," + + " burialConductor VARCHAR," + + " burialDate BIGINT," + + " burialPlaceDescription VARCHAR," + + " causeOfDeath VARCHAR," + + " causeOfDeathDetails VARCHAR," + + " causeOfDeathDisease VARCHAR," + + " deathDate BIGINT," + + " deathPlaceDescription VARCHAR," + + " deathPlaceType VARCHAR," + + " educationDetails VARCHAR," + + " educationType VARCHAR," + + " emailAddress VARCHAR," + + " externalId VARCHAR," + + " fathersName VARCHAR," + + " firstName VARCHAR NOT NULL," + + " generalPractitionerDetails VARCHAR," + + " gestationAgeAtBirth INTEGER," + + " lastName VARCHAR NOT NULL," + + " mothersMaidenName VARCHAR," + + " mothersName VARCHAR," + + " nationalHealthId VARCHAR," + + " nickname VARCHAR," + + " occupationDetails VARCHAR," + + " occupationType VARCHAR," + + " passportNumber VARCHAR," + + " phone VARCHAR," + + " phoneOwner VARCHAR," + + " placeOfBirthCommunity_id BIGINT," + + " placeOfBirthDistrict_id BIGINT," + + " placeOfBirthFacility_id BIGINT," + + " placeOfBirthFacilityDetails VARCHAR," + + " placeOfBirthFacilityType VARCHAR," + + " placeOfBirthRegion_id BIGINT," + + " presentCondition VARCHAR," + + " sex VARCHAR," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on db.execSQL("INSERT INTO person (" + personQueryColumns + ") SELECT " + personQueryColumns + " FROM person_old;"); db.execSQL("DROP TABLE person_old;"); @@ -2239,26 +1934,26 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int currentVersion = 236; //@formatter:off - getDao(SormasToSormasOriginInfo.class).executeRaw( - "CREATE TABLE sormasToSormasOriginInfo (" - + " comment VARCHAR," - + " organizationId VARCHAR," - + " ownershipHandedOver SMALLINT," - + " senderEmail VARCHAR," - + " senderName VARCHAR," - + " senderPhoneNumber VARCHAR," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(SormasToSormasOriginInfo.class).executeRaw( + "CREATE TABLE sormasToSormasOriginInfo (" + + " comment VARCHAR," + + " organizationId VARCHAR," + + " ownershipHandedOver SMALLINT," + + " senderEmail VARCHAR," + + " senderName VARCHAR," + + " senderPhoneNumber VARCHAR," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on getDao(Case.class) .executeRaw("ALTER TABLE cases ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); @@ -2279,73 +1974,73 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int case 239: currentVersion = 239; - //@formatter:off - getDao(Campaign.class).executeRaw( - "CREATE TABLE campaigns (" - + " archived SMALLINT," - + " creatingUser_id BIGINT," - + " description VARCHAR," - + " endDate BIGINT," - + " name VARCHAR," - + " startDate BIGINT," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - - getDao(CampaignFormMeta.class).executeRaw( - "CREATE TABLE campaignformmeta (" - + " campaignFormElements VARCHAR," - + " campaignFormTranslations VARCHAR," - + " formId VARCHAR," - + " formName VARCHAR," - + " languageCode VARCHAR," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - - getDao(CampaignFormData.class).executeRaw( - "CREATE TABLE campaignFormData (" - + " archived SMALLINT," - + " campaign_id BIGINT," - + " campaignFormMeta_id BIGINT," - + " community_id BIGINT," - + " creatingUser_id BIGINT," - + " district_id BIGINT," - + " formDate BIGINT," - + " formValues VARCHAR," - + " region_id BIGINT," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on - + //@formatter:off + getDao(Campaign.class).executeRaw( + "CREATE TABLE campaigns (" + + " archived SMALLINT," + + " creatingUser_id BIGINT," + + " description VARCHAR," + + " endDate BIGINT," + + " name VARCHAR," + + " startDate BIGINT," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + + getDao(CampaignFormMeta.class).executeRaw( + "CREATE TABLE campaignformmeta (" + + " campaignFormElements VARCHAR," + + " campaignFormTranslations VARCHAR," + + " formId VARCHAR," + + " formName VARCHAR," + + " languageCode VARCHAR," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + + getDao(CampaignFormData.class).executeRaw( + "CREATE TABLE campaignFormData (" + + " archived SMALLINT," + + " campaign_id BIGINT," + + " campaignFormMeta_id BIGINT," + + " community_id BIGINT," + + " creatingUser_id BIGINT," + + " district_id BIGINT," + + " formDate BIGINT," + + " formValues VARCHAR," + + " region_id BIGINT," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on + case 240: currentVersion = 240; getDao(Visit.class).executeRaw("ALTER TABLE visits ADD COLUMN origin varchar(255);"); @@ -2375,93 +2070,93 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int currentVersion = 244; //@formatter:off - getDao(Country.class).executeRaw( - "CREATE TABLE IF NOT EXISTS country (" - + " isoCode VARCHAR," - + " name VARCHAR," - + " archived SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Country.class).executeRaw( + "CREATE TABLE IF NOT EXISTS country (" + + " isoCode VARCHAR," + + " name VARCHAR," + + " archived SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on case 245: currentVersion = 245; //@formatter:off - getDao(Exposure.class).executeRaw( - "CREATE TABLE exposures (" - + " animalCondition VARCHAR," - + " animalContactType VARCHAR," - + " animalContactTypeDetails text," - + " animalMarket VARCHAR," - + " animalVaccinated VARCHAR," - + " bodyOfWater VARCHAR," - + " connectionNumber VARCHAR," - + " contactToBodyFluids VARCHAR," - + " contactToCase_id BIGINT," - + " deceasedPersonIll VARCHAR," - + " deceasedPersonName VARCHAR," - + " deceasedPersonRelation VARCHAR," - + " description text," - + " eatingRawAnimalProducts VARCHAR," - + " endDate BIGINT," - + " epiData_id BIGINT," - + " exposureType VARCHAR," - + " exposureTypeDetails text," - + " gatheringDetails text," - + " gatheringType VARCHAR," - + " habitationDetails text," - + " habitationType VARCHAR," - + " handlingAnimals VARCHAR," - + " handlingSamples VARCHAR," - + " indoors VARCHAR," - + " location_id BIGINT," - + " longFaceToFaceContact VARCHAR," - + " meansOfTransport VARCHAR," - + " meansOfTransportDetails text," - + " otherProtectiveMeasures VARCHAR," - + " outdoors VARCHAR," - + " percutaneous VARCHAR," - + " physicalContactDuringPreparation VARCHAR," - + " physicalContactWithBody VARCHAR," - + " prophylaxis VARCHAR," - + " prophylaxisDate BIGINT," - + " protectiveMeasuresDetails text," - + " reportingUser_id BIGINT," - + " riskArea VARCHAR," - + " seatNumber VARCHAR," - + " shortDistance VARCHAR," - + " startDate BIGINT," - + " typeOfAnimal VARCHAR," - + " typeOfAnimalDetails text," - + " typeOfPlace VARCHAR," - + " typeOfPlaceDetails text," - + " waterSource VARCHAR," - + " waterSourceDetails text," - + " wearingMask VARCHAR," - + " wearingPpe VARCHAR," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Exposure.class).executeRaw( + "CREATE TABLE exposures (" + + " animalCondition VARCHAR," + + " animalContactType VARCHAR," + + " animalContactTypeDetails text," + + " animalMarket VARCHAR," + + " animalVaccinated VARCHAR," + + " bodyOfWater VARCHAR," + + " connectionNumber VARCHAR," + + " contactToBodyFluids VARCHAR," + + " contactToCase_id BIGINT," + + " deceasedPersonIll VARCHAR," + + " deceasedPersonName VARCHAR," + + " deceasedPersonRelation VARCHAR," + + " description text," + + " eatingRawAnimalProducts VARCHAR," + + " endDate BIGINT," + + " epiData_id BIGINT," + + " exposureType VARCHAR," + + " exposureTypeDetails text," + + " gatheringDetails text," + + " gatheringType VARCHAR," + + " habitationDetails text," + + " habitationType VARCHAR," + + " handlingAnimals VARCHAR," + + " handlingSamples VARCHAR," + + " indoors VARCHAR," + + " location_id BIGINT," + + " longFaceToFaceContact VARCHAR," + + " meansOfTransport VARCHAR," + + " meansOfTransportDetails text," + + " otherProtectiveMeasures VARCHAR," + + " outdoors VARCHAR," + + " percutaneous VARCHAR," + + " physicalContactDuringPreparation VARCHAR," + + " physicalContactWithBody VARCHAR," + + " prophylaxis VARCHAR," + + " prophylaxisDate BIGINT," + + " protectiveMeasuresDetails text," + + " reportingUser_id BIGINT," + + " riskArea VARCHAR," + + " seatNumber VARCHAR," + + " shortDistance VARCHAR," + + " startDate BIGINT," + + " typeOfAnimal VARCHAR," + + " typeOfAnimalDetails text," + + " typeOfPlace VARCHAR," + + " typeOfPlaceDetails text," + + " waterSource VARCHAR," + + " waterSourceDetails text," + + " wearingMask VARCHAR," + + " wearingPpe VARCHAR," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN exposureDetailsKnown varchar(255);"); getDao(EpiData.class).executeRaw( @@ -2482,2059 +2177,2637 @@ public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN highTransmissionRiskArea varchar(255);"); getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN largeOutbreaksArea varchar(255);"); - // case 247: - // currentVersion = 247; - // Mistakenly added - //getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN exposureDetailsKnown varchar(255);"); + // case 247: + // currentVersion = 247; + // Mistakenly added + //getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN exposureDetailsKnown varchar(255);"); + + case 247: + currentVersion = 247; + + TableUtils.createTable(connectionSource, AuditLogEntry.class); + + case 248: + currentVersion = 248; + + migrateEpiData(); + + getDao(EpiData.class).executeRaw("ALTER TABLE epidata RENAME TO tmp_epidata;"); + + //@formatter:off + getDao(EpiData.class).executeRaw( + "CREATE TABLE epidata (" + + " areaInfectedAnimals VARCHAR," + + " contactWithSourceCaseKnown VARCHAR," + + " exposureDetailsKnown VARCHAR," + + " highTransmissionRiskArea VARCHAR," + + " largeOutbreaksArea VARCHAR," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on + + getDao(EpiData.class).executeRaw( + "INSERT INTO epidata(exposureDetailsKnown, contactWithSourceCaseKnown, areaInfectedAnimals, changeDate, creationDate, " + + "id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, pseudonymized) " + + "SELECT exposureDetailsKnown, contactWithSourceCaseKnown, wildbirds, changeDate, creationDate, id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, pseudonymized " + + "FROM tmp_epidata;"); + getDao(EpiData.class).executeRaw("DROP TABLE tmp_epidata;"); + + case 249: + currentVersion = 249; + getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN patientConditionOnAdmission varchar(512);"); + + case 250: + currentVersion = 250; + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD column multiDayContact boolean default false;"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD column firstContactDate timestamp;"); + + case 251: + currentVersion = 251; + + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN armedForcesRelationType varchar(255);"); + + case 252: + currentVersion = 252; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN nosocomialOutbreak boolean DEFAULT false"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN infectionSetting varchar(255)"); + + case 253: + currentVersion = 253; + + getDao(Person.class).executeRaw("ALTER TABLE person ADD column namesOfGuardians varchar(512);"); + + case 254: + currentVersion = 254; + + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWork varchar(255);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWorkFrom timestamp;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWorkUntil timestamp;"); + + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWork varchar(255);"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWorkFrom timestamp;"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWorkUntil timestamp;"); + + case 255: + currentVersion = 255; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN srcInstitutionalPartnerType varchar(255)"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN srcInstitutionalPartnerTypeDetails varchar(512)"); + + case 256: + currentVersion = 256; + getDao(Contact.class).executeRaw("ALTER TABLE events ADD column riskLevel varchar(255);"); + + case 257: + currentVersion = 257; + + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN salutation varchar(255)"); + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN otherSalutation text"); + + case 258: + currentVersion = 258; + getDao(Person.class).executeRaw("ALTER TABLE person ADD column birthName varchar(255);"); + getDao(Person.class).executeRaw("ALTER TABLE person ADD column birthCountry_id bigint REFERENCES country (id);"); + getDao(Person.class).executeRaw("ALTER TABLE person ADD column citizenship_id bigint REFERENCES country (id);"); + + case 259: + currentVersion = 259; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN meansOfTransport varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN meansOfTransportDetails text;"); + + case 260: + currentVersion = 260; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN reportingDistrict_id REFERENCES district (id);"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN reportingDistrict_id REFERENCES district (id);"); + + case 261: + currentVersion = 261; + getDao(Location.class).executeRaw( + "UPDATE location SET facilitytype = 'HOSPITAL' " + "WHERE facilitytype IS NULL " + + "AND (SELECT typeofplace from events WHERE eventlocation_id = location.id) = 'HOSPITAL';"); + getDao(Event.class).executeRaw( + "UPDATE events SET typeofplace = 'FACILITY' " + + "WHERE (SELECT facilitytype FROM location WHERE id = events.eventlocation_id) IS NOT NULL;"); + + case 262: + currentVersion = 262; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN externalToken text;"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN externalToken text;"); + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN externalToken text;"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN externalToken text;"); + + case 263: + currentVersion = 263; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN transregionalOutbreak varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseTransmissionMode varchar(255);"); + + case 264: + currentVersion = 264; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN superordinateEventUuid varchar(36);"); + + case 265: + currentVersion = 265; + getDao(Location.class).executeRaw( + "UPDATE location SET facilityType = 'HOSPITAL' " + "WHERE facilityType IS NULL " + + "AND (SELECT typeOfPlace from exposures WHERE location_id = location.id) = 'HOSPITAL';"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET typeOfPlace = 'FACILITY' " + + "WHERE (SELECT facilityType FROM location WHERE id = exposures.location_id) IS NOT NULL;"); + + case 266: + currentVersion = 266; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN connectionNumber varchar(512);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN travelDate timestamp;"); + + case 267: + currentVersion = 267; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN evolutionDate timestamp;"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN evolutionComment text;"); + + case 268: + currentVersion = 268; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN firstVaccinationDate timestamp;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineName varchar(255);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN otherVaccineName text;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineManufacturer varchar(255);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN otherVaccineManufacturer text;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineInn text;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineBatchNumber text;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineUniiCode text;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineAtcCode text;"); + + case 269: + currentVersion = 269; + getDao(Case.class).executeRaw( + "CREATE TABLE diseaseVariant(" + " id integer not null primary key autoincrement," + " uuid varchar(36) not null unique," + + " changeDate TIMESTAMP not null," + " creationDate TIMESTAMP not null," + " disease varchar(255) not null," + + " name VARCHAR(512) not null," + " lastOpenedDate BIGINT," + " localChangeDate BIGINT NOT NULL," + " modified SMALLINT," + + " snapshot SMALLINT);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariant_id bigint REFERENCES diseaseVariant(id);"); + + case 270: + currentVersion = 270; + getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogentest ADD COLUMN typingId text;"); + + case 271: + currentVersion = 271; + getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN exposureRole varchar(255);"); + + // TODO [vaccination info] integrate vaccination info +// case 269: +// +// currentVersion = 269; +// +// getDao(VaccinationInfo.class).executeRaw( +// "CREATE TABLE vaccinationInfo(vaccination VARCHAR(255), vaccinationDoses TEXT, vaccinationInfoSource VARCHAR(255), firstVaccinationDate TIMESTAMP, lastVaccinationDate TIMESTAMP, vaccineName VARCHAR(255), otherVaccineName TEXT, " +// + "vaccineManufacturer VARCHAR(255), otherVaccineManufacturer TEXT, vaccineInn TEXT, vaccineBatchNumber TEXT, vaccineUniiCode TEXT, vaccineAtcCode TEXT, " +// + "changeDate BIGINT NOT NULL, creationDate BIGINT NOT NULL, id INTEGER, lastOpenedDate BIGINT, localChangeDate BIGINT NOT NULL, modified SMALLINT, snapshot SMALLINT, uuid VARCHAR NOT NULL, PRIMARY KEY(id AUTOINCREMENT), UNIQUE(snapshot, uuid));"); +// +// getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN vaccinationInfo_id references vaccinationInfo(id)"); +// getDao(EventParticipant.class) +// .executeRaw("ALTER TABLE eventParticipants ADD COLUMN vaccinationInfo_id references vaccinationInfo(id)"); + + case 272: + currentVersion = 272; + getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN workEnvironment varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN workEnvironment varchar(255);"); + + case 273: + currentVersion = 273; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN bloodOrganOrTissueDonated varchar(255);"); + + case 274: + currentVersion = 274; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonNegativeTest boolean DEFAULT false;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonPhysicianInformation boolean DEFAULT false;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonDifferentPathogen boolean DEFAULT false;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonOther boolean DEFAULT false;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonDetails text;"); + + case 275: + currentVersion = 275; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN caseIdentificationSource varchar(255);"); + + case 276: + currentVersion = 276; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN reInfection varchar(255);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN previousInfectionDate timestamp;"); + + case 277: + currentVersion = 277; + getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN hospitalizationReason varchar(255);"); + getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN otherHospitalizationReason text;"); + getDao(PreviousHospitalization.class) + .executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN hospitalizationReason varchar(255);"); + getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN otherHospitalizationReason text;"); + + case 278: + currentVersion = 278; + getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN reportDate timestamp;"); + + case 279: + currentVersion = 279; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN screeningType varchar(255);"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'ON_HOSPITAL_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_HOSPITAL_ADMISSION';"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'ON_CARE_HOME_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_CARE_HOME_ADMISSION';"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'ON_ASYLUM_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_ASYLUM_ADMISSION';"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'ON_ENTRY_FROM_RISK_AREA', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_ENTRY_FROM_RISK_AREA';"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'HEALTH_SECTOR_EMPLOYEE', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'HEALTH_SECTOR_EMPLOYEE';"); + getDao(Case.class).executeRaw( + "UPDATE cases SET screeningType = 'EDUCATIONAL_INSTITUTIONS', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'EDUCATIONAL_INSTITUTIONS';"); + + case 280: + currentVersion = 280; + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN country_id BIGINT REFERENCES country(id);"); + + case 281: + currentVersion = 281; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN caseTransmissionClassification varchar(512);"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN contactTransmissionClassification varchar(512);"); + + case 282: + currentVersion = 282; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN specifyOtherOutcome varchar(255);"); + + case 283: + currentVersion = 283; + + //@formatter:off + getDao(ActivityAsCase.class).executeRaw( + "CREATE TABLE activityascase (" + + " activityAsCaseType VARCHAR," + + " activityAsCaseTypeDetails text," + + " connectionNumber VARCHAR," + + " description text," + + " endDate BIGINT," + + " epiData_id BIGINT," + + " gatheringDetails text," + + " gatheringType VARCHAR," + + " habitationDetails text," + + " habitationType VARCHAR," + + " location_id BIGINT," + + " meansOfTransport VARCHAR," + + " meansOfTransportDetails text," + + " reportingUser_id BIGINT," + + " role VARCHAR," + + " seatNumber VARCHAR," + + " startDate BIGINT," + + " typeOfPlace VARCHAR," + + " typeOfPlaceDetails text," + + " workEnvironment VARCHAR," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on + + getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN activityAsCaseDetailsKnown varchar(255);"); - case 247: - currentVersion = 247; + getDao(Case.class).executeRaw("UPDATE cases SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(Therapy.class).executeRaw("UPDATE therapy SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(ClinicalCourse.class).executeRaw("UPDATE clinicalCourse SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(HealthConditions.class).executeRaw("UPDATE healthConditions SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(Symptoms.class).executeRaw("UPDATE symptoms SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(Hospitalization.class).executeRaw("UPDATE hospitalizations SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(PreviousHospitalization.class).executeRaw("UPDATE previoushospitalizations SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(EpiData.class).executeRaw("UPDATE epidata SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(Exposure.class).executeRaw("UPDATE exposures SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(MaternalHistory.class).executeRaw("UPDATE maternalHistory SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(PortHealthInfo.class).executeRaw("UPDATE portHealthInfo SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + getDao(Location.class).executeRaw("UPDATE location SET changeDate = 0 WHERE changeDate IS NOT NULL;"); + case 284: + currentVersion = 284; - TableUtils.createTable(connectionSource, AuditLogEntry.class); + getDao(Event.class) + .executeRaw("ALTER TABLE events ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN ownershipHandedOver boolean;"); - case 248: - currentVersion = 248; + getDao(EventParticipant.class).executeRaw( + "ALTER TABLE eventParticipants ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); + getDao(EventParticipant.class).executeRaw("ALTER TABLE eventParticipants ADD COLUMN ownershipHandedOver boolean;"); + case 285: + currentVersion = 285; - migrateEpiData(); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN street varchar(4096);"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN houseNumber varchar(512);"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN additionalInformation varchar(255);"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN postalCode varchar(512);"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN areaType varchar(255);"); + case 286: + currentVersion = 286; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN eventManagementStatus varchar(255);"); - getDao(EpiData.class).executeRaw("ALTER TABLE epidata RENAME TO tmp_epidata;"); + case 287: + currentVersion = 287; - //@formatter:off - getDao(EpiData.class).executeRaw( - "CREATE TABLE epidata (" - + " areaInfectedAnimals VARCHAR," - + " contactWithSourceCaseKnown VARCHAR," - + " exposureDetailsKnown VARCHAR," - + " highTransmissionRiskArea VARCHAR," - + " largeOutbreaksArea VARCHAR," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN largeAttendanceNumber varchar(255);"); - getDao(EpiData.class).executeRaw( - "INSERT INTO epidata(exposureDetailsKnown, contactWithSourceCaseKnown, areaInfectedAnimals, changeDate, creationDate, " - + "id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, pseudonymized) " - + "SELECT exposureDetailsKnown, contactWithSourceCaseKnown, wildbirds, changeDate, creationDate, id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, pseudonymized " - + "FROM tmp_epidata;"); - getDao(EpiData.class).executeRaw("DROP TABLE tmp_epidata;"); + case 288: + currentVersion = 288; + getDao(Sample.class).executeRaw("ALTER TABLE samples ADD COLUMN samplingReason varchar(255);"); + getDao(Sample.class).executeRaw("ALTER TABLE samples ADD COLUMN samplingReasonDetails text;"); - case 249: - currentVersion = 249; - getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN patientConditionOnAdmission varchar(512);"); + case 289: + currentVersion = 289; + getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN extendedClassification boolean;"); + getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN extendedClassificationMulti boolean;"); + getDao(DiseaseConfiguration.class) + .executeRaw("UPDATE diseaseconfiguration SET extendedClassification = 0 WHERE disease not in ('CORONAVIRUS', 'MEASLES');"); + getDao(DiseaseConfiguration.class) + .executeRaw("UPDATE diseaseconfiguration SET extendedClassificationMulti = 0 WHERE disease not in ('CORONAVIRUS');"); + getDao(DiseaseConfiguration.class) + .executeRaw("UPDATE diseaseconfiguration SET extendedClassification = 1 WHERE disease in ('CORONAVIRUS', 'MEASLES');"); + getDao(DiseaseConfiguration.class) + .executeRaw("UPDATE diseaseconfiguration SET extendedClassificationMulti = 1 WHERE disease in ('CORONAVIRUS');"); + getDao(DiseaseConfiguration.class).executeRaw("UPDATE diseaseconfiguration SET changeDate = 0;"); - case 250: - currentVersion = 250; - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD column multiDayContact boolean default false;"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD column firstContactDate timestamp;"); + case 290: + currentVersion = 290; + getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN viaLims boolean DEFAULT false;"); - case 251: - currentVersion = 251; + case 291: + currentVersion = 291; - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN armedForcesRelationType varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN infectionPathCertainty varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN humanTransmissionMode varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN parenteralTransmissionMode varchar(255);"); + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN medicallyAssociatedTransmissionMode varchar(255);"); - case 252: - currentVersion = 252; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN nosocomialOutbreak boolean DEFAULT false"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN infectionSetting varchar(255)"); + case 292: + currentVersion = 292; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN internalId text;"); - case 253: - currentVersion = 253; + case 293: + currentVersion = 293; - getDao(Person.class).executeRaw("ALTER TABLE person ADD column namesOfGuardians varchar(512);"); + //@formatter:off + getDao(PersonContactDetail.class).executeRaw( + "CREATE TABLE personContactDetail (" + + " additionalInformation text," + + " contactInformation text," + + " details text," + + " person_id BIGINT," + + " personContactDetailType VARCHAR," + + " phoneNumberType VARCHAR," + + " primaryContact SMALLINT," + + " thirdParty SMALLINT," + + " thirdPartyName text," + + " thirdPartyRole text," + + " pseudonymized SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on - case 254: - currentVersion = 254; + migratePersonContactDetails(); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWork varchar(255);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWorkFrom timestamp;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN prohibitionToWorkUntil timestamp;"); + case 294: + currentVersion = 294; + getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnit varchar(255);"); + getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnitStart timestamp;"); + getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnitEnd timestamp"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWork varchar(255);"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWorkFrom timestamp;"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN prohibitionToWorkUntil timestamp;"); + case 295: + currentVersion = 295; - case 255: - currentVersion = 255; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN srcInstitutionalPartnerType varchar(255)"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN srcInstitutionalPartnerTypeDetails varchar(512)"); + //@formatter:off + getDao(Continent.class).executeRaw( + "CREATE TABLE IF NOT EXISTS continent (" + + " defaultName text," + + " archived SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + + getDao(Subcontinent.class).executeRaw( + "CREATE TABLE IF NOT EXISTS subcontinent (" + + " continent_id BIGINT NOT NULL," + + " defaultName text," + + " archived SMALLINT," + + " changeDate BIGINT NOT NULL," + + " creationDate BIGINT NOT NULL," + + " id INTEGER PRIMARY KEY AUTOINCREMENT," + + " lastOpenedDate BIGINT," + + " localChangeDate BIGINT NOT NULL," + + " modified SMALLINT," + + " snapshot SMALLINT," + + " uuid VARCHAR NOT NULL," + + " UNIQUE (snapshot ASC, uuid ASC)" + + ");" + ); + //@formatter:on - case 256: - currentVersion = 256; - getDao(Contact.class).executeRaw("ALTER TABLE events ADD column riskLevel varchar(255);"); + getDao(Country.class).executeRaw("ALTER TABLE country ADD COLUMN subcontinent_id BIGINT REFERENCES subcontinent(id);"); - case 257: - currentVersion = 257; + case 296: + currentVersion = 296; + getDao(Region.class).executeRaw("ALTER TABLE region ADD COLUMN country_id bigint REFERENCES country(id);"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN salutation varchar(255)"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN otherSalutation text"); + case 297: + currentVersion = 297; + getDao(EpiData.class).executeRaw("ALTER TABLE exposures ADD COLUMN probableInfectionEnvironment boolean DEFAULT false;"); - case 258: - currentVersion = 258; - getDao(Person.class).executeRaw("ALTER TABLE person ADD column birthName varchar(255);"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD column birthCountry_id bigint REFERENCES country (id);"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD column citizenship_id bigint REFERENCES country (id);"); + case 298: + currentVersion = 298; + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN continent_id BIGINT REFERENCES continent(id);"); + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN subcontinent_id BIGINT REFERENCES subcontinent(id);"); - case 259: - currentVersion = 259; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN meansOfTransport varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN meansOfTransportDetails text;"); + case 299: + currentVersion = 299; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN followUpStatusChangeDate timestamp without time zone;"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN followUpStatusChangeUser_id BIGINT REFERENCES users(id);"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN followUpStatusChangeDate timestamp without time zone;"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN followUpStatusChangeUser_id BIGINT REFERENCES users(id);"); - case 260: - currentVersion = 260; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN reportingDistrict_id REFERENCES district (id);"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN reportingDistrict_id REFERENCES district (id);"); + case 300: + currentVersion = 300; + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonFirstName text"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonLastName text"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonPhone text"); + getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonEmail text"); - case 261: - currentVersion = 261; - getDao(Location.class).executeRaw( - "UPDATE location SET facilitytype = 'HOSPITAL' " + "WHERE facilitytype IS NULL " - + "AND (SELECT typeofplace from events WHERE eventlocation_id = location.id) = 'HOSPITAL';"); - getDao(Event.class).executeRaw( - "UPDATE events SET typeofplace = 'FACILITY' " - + "WHERE (SELECT facilitytype FROM location WHERE id = events.eventlocation_id) IS NOT NULL;"); + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonFirstName text;"); + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonLastName text;"); + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonPhone text;"); + getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonEmail text;"); - case 262: - currentVersion = 262; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN externalToken text;"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN externalToken text;"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN externalToken text;"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN externalToken text;"); + case 301: + currentVersion = 301; + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN additionalDetails text;"); - case 263: - currentVersion = 263; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN transregionalOutbreak varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseTransmissionMode varchar(255);"); + case 302: + currentVersion = 302; + getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN pcrTestSpecification varchar(255);"); + getDao(PathogenTest.class) + .executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariant_id bigint REFERENCES diseaseVariant(id);"); - case 264: - currentVersion = 264; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN superordinateEventUuid varchar(36);"); + case 303: + currentVersion = 303; + getDao(Area.class).executeRaw( + "CREATE TABLE area(" + "id integer primary key autoincrement," + "uuid varchar(36) not null unique," + + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," + + "archived SMALLINT DEFAULT 0," + "name varchar(255) not null," + "externalId varchar(255) not null" + ");"); + getDao(Region.class).executeRaw("ALTER TABLE region ADD COLUMN area_id BIGINT REFERENCES area(id);"); + getDao(Region.class).executeRaw("UPDATE region set changeDate=0;"); - case 265: - currentVersion = 265; - getDao(Location.class).executeRaw( - "UPDATE location SET facilityType = 'HOSPITAL' " + "WHERE facilityType IS NULL " - + "AND (SELECT typeOfPlace from exposures WHERE location_id = location.id) = 'HOSPITAL';"); - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET typeOfPlace = 'FACILITY' " - + "WHERE (SELECT facilityType FROM location WHERE id = exposures.location_id) IS NOT NULL;"); + case 304: + currentVersion = 304; + getDao(Campaign.class).executeRaw("ALTER TABLE campaigns ADD COLUMN campaignFormMetas text;"); + getDao(Campaign.class).executeRaw("UPDATE campaigns set changeDate=0;"); - case 266: - currentVersion = 266; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN connectionNumber varchar(512);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN travelDate timestamp;"); + case 305: + currentVersion = 305; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleRegion_id BIGINT REFERENCES region(id);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleDistrict_id BIGINT REFERENCES district(id);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleCommunity_id BIGINT REFERENCES community(id);"); - case 267: - currentVersion = 267; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN evolutionDate timestamp;"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN evolutionComment text;"); + case 306: + currentVersion = 306; + getDao(CustomizableEnumValue.class).executeRaw( + "CREATE TABLE customizableEnumValue(" + "id integer primary key autoincrement," + "uuid varchar(36) not null unique," + + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," + + "dataType varchar(255)," + "value text," + "caption text," + "translations text," + "diseases text," + "description text," + + "descriptionTranslations text," + "properties text);"); + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariant text;"); + getDao(Case.class).executeRaw( + "UPDATE cases SET diseaseVariant = UPPER(REPLACE((SELECT name FROM diseaseVariant WHERE diseaseVariant.id = cases.diseaseVariant_id), ' ', '_')) WHERE cases.diseaseVariant_id IS NOT NULL;"); + getDao(Case.class).executeRaw("UPDATE cases SET diseaseVariant_id = NULL;"); + getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariant text;"); + getDao(Case.class).executeRaw( + "UPDATE pathogenTest SET testedDiseaseVariant = UPPER(REPLACE((SELECT name FROM diseaseVariant WHERE diseaseVariant.id = pathogenTest.testedDiseaseVariant_id), ' ', '_')) WHERE pathogenTest.testedDiseaseVariant_id IS NOT NULL;"); + getDao(PathogenTest.class).executeRaw("UPDATE pathogenTest SET testedDiseaseVariant_id = NULL;"); + getDao(Case.class).executeRaw("DROP TABLE diseaseVariant;"); + + case 307: + currentVersion = 307; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN internalToken text;"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN internalToken text;"); + getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN internalToken text;"); - case 268: - currentVersion = 268; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN firstVaccinationDate timestamp;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineName varchar(255);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN otherVaccineName text;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineManufacturer varchar(255);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN otherVaccineManufacturer text;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineInn text;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineBatchNumber text;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineUniiCode text;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN vaccineAtcCode text;"); + case 308: + currentVersion = 308; + getDao(Case.class).executeRaw( + "UPDATE cases" + " SET responsibleRegion_id = region_id," + " responsibleDistrict_id = district_id," + + " responsibleCommunity_id = community_id," + " region_id = null," + " district_id = null," + " community_id = null," + + " reportingDistrict_id = null" + + " WHERE responsibleRegion_id IS NULL AND (reportingDistrict_id IS NULL OR reportingDistrict_id = district_id)"); - case 269: - currentVersion = 269; getDao(Case.class).executeRaw( - "CREATE TABLE diseaseVariant(" + " id integer not null primary key autoincrement," + " uuid varchar(36) not null unique," - + " changeDate TIMESTAMP not null," + " creationDate TIMESTAMP not null," + " disease varchar(255) not null," - + " name VARCHAR(512) not null," + " lastOpenedDate BIGINT," + " localChangeDate BIGINT NOT NULL," + " modified SMALLINT," - + " snapshot SMALLINT);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariant_id bigint REFERENCES diseaseVariant(id);"); + "UPDATE cases" + " SET responsibleRegion_id = (SELECT region_id from district where id = cases.reportingDistrict_id)," + + " responsibleDistrict_id = reportingDistrict_id," + " reportingDistrict_id = null" + + " WHERE responsibleRegion_id IS NULL AND reportingDistrict_id IS NOT NULL"); - case 270: - currentVersion = 270; - getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogentest ADD COLUMN typingId text;"); + case 309: + currentVersion = 309; + getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withAssociatedContacts boolean;"); + getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withSamples boolean;"); + getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withEventParticipants boolean;"); - case 271: - currentVersion = 271; - getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN exposureRole varchar(255);"); + case 310: + currentVersion = 310; + //@formatter:off + getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + + " id integer primary key autoincrement, uuid varchar(36) not null unique," + + " changeDate timestamp not null, creationDate timestamp not null, lastOpenedDate timestamp, localChangeDate timestamp not null," + + " modified SMALLINT DEFAULT 0, snapshot SMALLINT DEFAULT 0," + + " disease varchar(255) not null," + + " person_id bigint not null," + + " reportdate timestamp not null," + + " reportinguser_id bigint not null," + + " archived boolean DEFAULT false," + + " immunizationstatus varchar(255) not null," + + " meansofimmunization varchar(255) not null," + + " meansOfImmunizationDetails text," + + " immunizationmanagementstatus varchar(255) not null," + + " externalid varchar(255) not null," + + " responsibleregion_id bigint," + + " responsibledistrict_id bigint," + + " responsiblecommunity_id bigint," + + " country_id bigint," + + " startdate timestamp," + + " enddate timestamp," + + " numberofdoses int," + + " previousinfection varchar(255)," + + " lastinfectiondate timestamp," + + " additionaldetails text," + + " positivetestresultdate timestamp not null," + + " recoverydate timestamp not null," + + " relatedcase_id bigint)"); + //@formatter:on - // TODO [vaccination info] integrate vaccination info -// case 269: -// -// currentVersion = 269; -// -// getDao(VaccinationInfo.class).executeRaw( -// "CREATE TABLE vaccinationInfo(vaccination VARCHAR(255), vaccinationDoses TEXT, vaccinationInfoSource VARCHAR(255), firstVaccinationDate TIMESTAMP, lastVaccinationDate TIMESTAMP, vaccineName VARCHAR(255), otherVaccineName TEXT, " -// + "vaccineManufacturer VARCHAR(255), otherVaccineManufacturer TEXT, vaccineInn TEXT, vaccineBatchNumber TEXT, vaccineUniiCode TEXT, vaccineAtcCode TEXT, " -// + "changeDate BIGINT NOT NULL, creationDate BIGINT NOT NULL, id INTEGER, lastOpenedDate BIGINT, localChangeDate BIGINT NOT NULL, modified SMALLINT, snapshot SMALLINT, uuid VARCHAR NOT NULL, PRIMARY KEY(id AUTOINCREMENT), UNIQUE(snapshot, uuid));"); -// -// getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN vaccinationInfo_id references vaccinationInfo(id)"); -// getDao(EventParticipant.class) -// .executeRaw("ALTER TABLE eventParticipants ADD COLUMN vaccinationInfo_id references vaccinationInfo(id)"); + case 311: + currentVersion = 311; + getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN pseudonymized boolean;"); - case 272: - currentVersion = 272; - getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN workEnvironment varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN workEnvironment varchar(255);"); + case 312: + currentVersion = 312; + getDao(LbdsSync.class).executeRaw( + "CREATE TABLE lbdsSync(" + "sentUuid varchar(36) primary key," + "lastSendDate timestamp," + "lastReceivedDate timestamp);"); - case 273: - currentVersion = 273; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN bloodOrganOrTissueDonated varchar(255);"); + case 313: + currentVersion = 313; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseVariant text;"); - case 274: - currentVersion = 274; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonNegativeTest boolean DEFAULT false;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonPhysicianInformation boolean DEFAULT false;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonDifferentPathogen boolean DEFAULT false;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonOther boolean DEFAULT false;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN notACaseReasonDetails text;"); + case 314: + currentVersion = 314; + getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN eventIdentificationSource varchar(255);"); - case 275: - currentVersion = 275; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN caseIdentificationSource varchar(255);"); + case 315: + currentVersion = 315; + getDao(Immunization.class).executeRaw("DROP TABLE immunization"); + //@formatter:off + getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + + " id integer primary key autoincrement," + + " uuid varchar(36) not null unique," + + " changeDate timestamp not null," + + " creationDate timestamp not null," + + " lastOpenedDate timestamp," + + " localChangeDate timestamp not null," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + " pseudonymized SMALLINT," + + " disease varchar(255) not null," + + " person_id bigint not null," + + " reportDate timestamp not null," + + " reportingUser_id bigint not null," + + " archived boolean DEFAULT false," + + " immunizationStatus varchar(255) not null," + + " meansOfImmunization varchar(255) not null," + + " meansOfImmunizationDetails text," + + " immunizationManagementStatus varchar(255) not null," + + " externalId varchar(255) not null," + + " responsibleRegion_id bigint," + + " responsibleDistrict_id bigint," + + " responsibleCommunity_id bigint," + + " country_id bigint," + + " startDate timestamp," + + " endDate timestamp," + + " numberOfDoses int," + + " previousInfection varchar(255)," + + " lastInfectionDate timestamp," + + " additionalDetails text," + + " positiveTestResultDate timestamp not null," + + " recoveryDate timestamp not null," + + " relatedCase_id bigint)"); + //@formatter:on - case 276: - currentVersion = 276; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN reInfection varchar(255);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN previousInfectionDate timestamp;"); + case 316: + currentVersion = 316; - case 277: - currentVersion = 277; - getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN hospitalizationReason varchar(255);"); - getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN otherHospitalizationReason text;"); - getDao(PreviousHospitalization.class) - .executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN hospitalizationReason varchar(255);"); - getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN otherHospitalizationReason text;"); + getDao(Case.class).executeRaw("ALTER TABLE events ADD COLUMN specificRisk text;"); - case 278: - currentVersion = 278; - getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN reportDate timestamp;"); + case 317: + currentVersion = 317; + //@formatter:off + getDao(Vaccination.class).executeRaw( + "CREATE TABLE vaccination (" + + "id integer primary key autoincrement," + + " uuid varchar(36) unique," + + " changeDate timestamp," + + " creationDate timestamp," + + " immunization_id bigint," + + " healthConditions_id bigint," + + " reportDate timestamp," + + " reportingUser_id bigint," + + " vaccinationDate timestamp," + + " vaccineName varchar(255)," + + " otherVaccineName text," + + " vaccineManufacturer varchar(255)," + + " otherVaccineManufacturer text," + + " vaccineInn text," + + " vaccineBatchNumber text," + + " vaccineUniiCode text," + + " vaccineAtcCode text," + + " vaccinationInfoSource varchar(255)," + + " pregnant varchar(255)," + + " trimester varchar(255), pseudonymized boolean);"); + //@formatter:on - case 279: - currentVersion = 279; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN screeningType varchar(255);"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'ON_HOSPITAL_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_HOSPITAL_ADMISSION';"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'ON_CARE_HOME_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_CARE_HOME_ADMISSION';"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'ON_ASYLUM_ADMISSION', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_ASYLUM_ADMISSION';"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'ON_ENTRY_FROM_RISK_AREA', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'ON_ENTRY_FROM_RISK_AREA';"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'HEALTH_SECTOR_EMPLOYEE', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'HEALTH_SECTOR_EMPLOYEE';"); - getDao(Case.class).executeRaw( - "UPDATE cases SET screeningType = 'EDUCATIONAL_INSTITUTIONS', caseIdentificationSource = 'SCREENING' where caseIdentificationSource = 'EDUCATIONAL_INSTITUTIONS';"); + case 318: + currentVersion = 318; + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN vaccineType text;"); + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN vaccineDose text;"); - case 280: - currentVersion = 280; - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN country_id BIGINT REFERENCES country(id);"); + case 319: + currentVersion = 319; + getDao(Person.class).executeRaw("UPDATE person SET sex = 'UNKNOWN' WHERE sex IS NULL;"); - case 281: - currentVersion = 281; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN caseTransmissionClassification varchar(512);"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN contactTransmissionClassification varchar(512);"); + case 320: + currentVersion = 320; + getDao(Country.class).executeRaw( + "UPDATE country SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultName = 'Western Europe') WHERE isoCode = 'NCL';"); + getDao(Location.class).executeRaw( + "UPDATE location SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultname = 'Western Europe') WHERE location.subcontinent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isocode = 'NCL');"); + getDao(Location.class).executeRaw( + "UPDATE location SET continent_id = (SELECT continent.id FROM continent WHERE continent.defaultName = 'Europe') WHERE location.continent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isoCode = 'NCL');"); - case 282: - currentVersion = 282; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN specifyOtherOutcome varchar(255);"); + case 321: + currentVersion = 321; + getDao(Country.class).executeRaw( + "UPDATE country SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultName = 'Central Europe') WHERE isoCode = 'DEU';"); + getDao(Location.class).executeRaw( + "UPDATE location SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultname = 'Central Europe') WHERE location.subcontinent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isocode = 'DEU');"); - case 283: - currentVersion = 283; + case 322: + currentVersion = 322; + getDao(Symptoms.class).executeRaw( + "UPDATE symptoms SET symptomatic = null WHERE (SELECT visitStatus FROM visits WHERE visits.symptoms_id = symptoms.id) != 'COOPERATIVE';"); + case 323: + currentVersion = 323; + getDao(Immunization.class).executeRaw("DROP TABLE immunization"); //@formatter:off - getDao(ActivityAsCase.class).executeRaw( - "CREATE TABLE activityascase (" - + " activityAsCaseType VARCHAR," - + " activityAsCaseTypeDetails text," - + " connectionNumber VARCHAR," - + " description text," - + " endDate BIGINT," - + " epiData_id BIGINT," - + " gatheringDetails text," - + " gatheringType VARCHAR," - + " habitationDetails text," - + " habitationType VARCHAR," - + " location_id BIGINT," - + " meansOfTransport VARCHAR," - + " meansOfTransportDetails text," - + " reportingUser_id BIGINT," - + " role VARCHAR," - + " seatNumber VARCHAR," - + " startDate BIGINT," - + " typeOfPlace VARCHAR," - + " typeOfPlaceDetails text," - + " workEnvironment VARCHAR," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + + " id integer primary key autoincrement," + + " uuid varchar(36) not null unique," + + " changeDate timestamp not null," + + " creationDate timestamp not null," + + " lastOpenedDate timestamp," + + " localChangeDate timestamp not null," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + " pseudonymized SMALLINT," + + " disease varchar(255)," + + " diseaseDetails varchar(512)," + + " person_id bigint REFERENCES person(id)," + + " reportDate timestamp not null," + + " reportingUser_id bigint REFERENCES users(id)," + + " archived boolean DEFAULT false," + + " immunizationStatus varchar(255)," + + " meansOfImmunization varchar(255)," + + " meansOfImmunizationDetails text," + + " immunizationManagementStatus varchar(255)," + + " externalId varchar(255)," + + " responsibleRegion_id bigint," + + " responsibleDistrict_id bigint," + + " responsibleCommunity_id bigint," + + " country_id bigint REFERENCES country(id)," + + " facilityType varchar(255)," + + " healthFacility_id bigint REFERENCES facility(id)," + + " healthFacilityDetails varchar(512)," + + " startDate timestamp," + + " endDate timestamp," + + " validFrom timestamp," + + " validUntil timestamp," + + " numberOfDoses int," + + " previousInfection varchar(255)," + + " lastInfectionDate timestamp," + + " additionalDetails text," + + " positiveTestResultDate timestamp," + + " recoveryDate timestamp," + + " relatedCase_id bigint REFERENCES cases(id))"); + //@formatter:on - getDao(EpiData.class).executeRaw("ALTER TABLE epidata ADD COLUMN activityAsCaseDetailsKnown varchar(255);"); + case 324: + currentVersion = 324; + migrateVaccinationInfo(); + // Last vaccination date has been moved to the vaccination entity, but still has to be used for Monkeypox + getDao(Case.class).executeRaw("UPDATE cases SET vaccinationDate = null WHERE disease != 'MONKEYPOX';"); + getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN vaccinationStatus varchar(255);"); + getDao(EventParticipant.class).executeRaw("ALTER TABLE eventParticipants ADD COLUMN vaccinationStatus varchar(255);"); - getDao(Case.class).executeRaw("UPDATE cases SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(Therapy.class).executeRaw("UPDATE therapy SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(ClinicalCourse.class).executeRaw("UPDATE clinicalCourse SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(HealthConditions.class).executeRaw("UPDATE healthConditions SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(Symptoms.class).executeRaw("UPDATE symptoms SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(Hospitalization.class).executeRaw("UPDATE hospitalizations SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(PreviousHospitalization.class).executeRaw("UPDATE previoushospitalizations SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(EpiData.class).executeRaw("UPDATE epidata SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(Exposure.class).executeRaw("UPDATE exposures SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(MaternalHistory.class).executeRaw("UPDATE maternalHistory SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(PortHealthInfo.class).executeRaw("UPDATE portHealthInfo SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - getDao(Location.class).executeRaw("UPDATE location SET changeDate = 0 WHERE changeDate IS NOT NULL;"); - case 284: - currentVersion = 284; + case 325: + currentVersion = 325; + getDao(Immunization.class) + .executeRaw("ALTER TABLE immunization ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); + getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN ownershipHandedOver boolean;"); - getDao(Event.class) - .executeRaw("ALTER TABLE events ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN ownershipHandedOver boolean;"); + case 326: + currentVersion = 326; + getDao(Person.class).executeRaw("UPDATE person SET sex = 'UNKNOWN' WHERE sex IS NULL;"); + + case 327: + currentVersion = 327; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariantDetails varchar(512);"); + getDao(Case.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseVariantDetails varchar(512);"); + getDao(Case.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariantDetails varchar(512);"); + + case 328: + currentVersion = 328; + if (columnDoesNotExist("immunization", "sormasToSormasOriginInfo_id")) { + getDao(Immunization.class).executeRaw( + "ALTER TABLE immunization ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); + } + if (columnDoesNotExist("immunization", "ownershipHandedOver")) { + getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN ownershipHandedOver boolean;"); + } + + case 329: + currentVersion = 329; + if (columnDoesNotExist("users", "associatedOfficer_id")) { + getDao(User.class).executeRaw("ALTER TABLE users ADD COLUMN associatedOfficer_id bigint REFERENCES users(id);"); + } + + case 330: + currentVersion = 330; + getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN description varchar(512);"); + getDao(Hospitalization.class).executeRaw("ALTER TABLE Previoushospitalizations ADD COLUMN admittedToHealthFacility varchar(255);"); + getDao(Hospitalization.class).executeRaw("ALTER TABLE Previoushospitalizations ADD COLUMN isolationDate timestamp;"); + + case 331: + currentVersion = 331; + getDao(EventParticipant.class) + .executeRaw("ALTER TABLE eventParticipants ADD COLUMN responsibleRegion_id BIGINT REFERENCES region(id);"); + getDao(EventParticipant.class) + .executeRaw("ALTER TABLE eventParticipants ADD COLUMN responsibleDistrict_id BIGINT REFERENCES district(id);"); - getDao(EventParticipant.class).executeRaw( - "ALTER TABLE eventParticipants ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); - getDao(EventParticipant.class).executeRaw("ALTER TABLE eventParticipants ADD COLUMN ownershipHandedOver boolean;"); - case 285: - currentVersion = 285; + case 332: + currentVersion = 332; + getDao(FeatureConfiguration.class).executeRaw("ALTER TABLE featureconfiguration ADD COLUMN properties text;"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN street varchar(4096);"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN houseNumber varchar(512);"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN additionalInformation varchar(255);"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN postalCode varchar(512);"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN areaType varchar(255);"); - case 286: - currentVersion = 286; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN eventManagementStatus varchar(255);"); + case 333: + currentVersion = 333; +// Recreate immunization table because unique constraint was not taking snapshot into account + getDao(Immunization.class).executeRaw("ALTER TABLE immunization RENAME TO tmp_immunization;"); + getDao(Immunization.class).executeRaw( + "CREATE TABLE immunization (additionalDetails VARCHAR, " + + "archived boolean DEFAULT false, country_id BIGINT REFERENCES country(id), disease VARCHAR, diseaseDetails VARCHAR, endDate timestamp, externalId VARCHAR, immunizationManagementStatus VARCHAR, " + + "immunizationStatus VARCHAR, lastInfectionDate timestamp, meansOfImmunization VARCHAR, meansOfImmunizationDetails VARCHAR, " + + "numberOfDoses INTEGER, ownershipHandedOver boolean DEFAULT false, person_id BIGINT NOT NULL REFERENCES person(id), positiveTestResultDate timestamp, previousInfection VARCHAR, " + + "recoveryDate timestamp, relatedCase_id BIGINT REFERENCES cases(id), reportDate timestamp, reportingUser_id BIGINT REFERENCES users(id), responsibleCommunity_id BIGINT REFERENCES community(id), " + + "responsibleDistrict_id BIGINT REFERENCES district(id), responsibleRegion_id BIGINT REFERENCES region(id), sormasToSormasOriginInfo_id BIGINT REFERENCES sormasToSormasOriginInfo(id), startDate timestamp, pseudonymized SMALLINT, changeDate timestamp NOT NULL, " + + "creationDate timestamp NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT, lastOpenedDate timestamp, localChangeDate timestamp NOT NULL, " + + "modified SMALLINT DEFAULT 0, snapshot SMALLINT DEFAULT 0, uuid VARCHAR, validFrom timestamp, validUntil timestamp, facilityType VARCHAR, healthFacility_id BIGINT REFERENCES facility(id), healthFacilityDetails VARCHAR, UNIQUE (snapshot ASC, uuid ASC));"); + getDao(Immunization.class).executeRaw( + "INSERT INTO immunization (additionalDetails, archived, country_id, disease, diseaseDetails, endDate, externalId, immunizationManagementStatus, " + + "immunizationStatus, lastInfectionDate, meansOfImmunization, meansOfImmunizationDetails, numberOfDoses, ownershipHandedOver, person_id, positiveTestResultDate, previousInfection, " + + "recoveryDate, relatedCase_id, reportDate, reportingUser_id, responsibleCommunity_id, responsibleDistrict_id, responsibleRegion_id, sormasToSormasOriginInfo_id, startDate, pseudonymized, " + + "changeDate, creationDate, id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, validFrom, validUntil, facilityType, healthFacility_id, healthFacilityDetails) " + + "SELECT additionalDetails, archived, country_id, disease, diseaseDetails, endDate, externalId, immunizationManagementStatus, " + + "immunizationStatus, lastInfectionDate, meansOfImmunization, meansOfImmunizationDetails, numberOfDoses, ownershipHandedOver, person_id, positiveTestResultDate, previousInfection, recoveryDate, relatedCase_id, " + + "reportDate, reportingUser_id, responsibleCommunity_id, responsibleDistrict_id, responsibleRegion_id, sormasToSormasOriginInfo_id, startDate, pseudonymized, changeDate, creationDate, id, lastOpenedDate, localChangeDate, " + + "modified, snapshot, uuid, validFrom, validUntil, facilityType, healthFacility_id, healthFacilityDetails FROM tmp_immunization;"); + getDao(Immunization.class).executeRaw("DROP TABLE tmp_immunization"); - case 287: - currentVersion = 287; + case 334: + currentVersion = 334; - getDao(Exposure.class).executeRaw("ALTER TABLE exposures ADD COLUMN largeAttendanceNumber varchar(255);"); + if (columnDoesNotExist("vaccination", "snapshot")) { + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN snapshot SMALLINT DEFAULT 0;"); + } - case 288: - currentVersion = 288; - getDao(Sample.class).executeRaw("ALTER TABLE samples ADD COLUMN samplingReason varchar(255);"); - getDao(Sample.class).executeRaw("ALTER TABLE samples ADD COLUMN samplingReasonDetails text;"); + case 335: + currentVersion = 335; + getDao(EventParticipant.class).executeRaw( + "UPDATE eventParticipants SET reportingUser_id = (SELECT reportingUser_id FROM events WHERE events.id = eventParticipants.event_id) WHERE reportingUser_id IS NULL;"); - case 289: - currentVersion = 289; - getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN extendedClassification boolean;"); - getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN extendedClassificationMulti boolean;"); - getDao(DiseaseConfiguration.class) - .executeRaw("UPDATE diseaseconfiguration SET extendedClassification = 0 WHERE disease not in ('CORONAVIRUS', 'MEASLES');"); - getDao(DiseaseConfiguration.class) - .executeRaw("UPDATE diseaseconfiguration SET extendedClassificationMulti = 0 WHERE disease not in ('CORONAVIRUS');"); - getDao(DiseaseConfiguration.class) - .executeRaw("UPDATE diseaseconfiguration SET extendedClassification = 1 WHERE disease in ('CORONAVIRUS', 'MEASLES');"); - getDao(DiseaseConfiguration.class) - .executeRaw("UPDATE diseaseconfiguration SET extendedClassificationMulti = 1 WHERE disease in ('CORONAVIRUS');"); - getDao(DiseaseConfiguration.class).executeRaw("UPDATE diseaseconfiguration SET changeDate = 0;"); + case 336: + currentVersion = 336; + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN generalBodilyPains varchar(255);"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN lesionsNeck boolean;"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN lesionsTrunk boolean;"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN rashes varchar(255);"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN macularRash varchar(255);"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN papularRash varchar(255);"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN vesicularRash varchar(255);"); + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN otherLesionAreas varchar(255)"); + getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN healthFacilityRecordNumber varchar(255);"); + getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN healthFacilityRecordNumber varchar(255);"); - case 290: - currentVersion = 290; - getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN viaLims boolean DEFAULT false;"); + case 337: + currentVersion = 337; + getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN healthConditions_id BIGINT REFERENCES healthConditions(id);"); + getDao(Case.class).executeRaw( + "UPDATE cases SET healthConditions_id = (SELECT healthConditions_id from clinicalCourse where clinicalCourse.id = cases.clinicalCourse_id);"); - case 291: - currentVersion = 291; + case 338: + currentVersion = 338; + getDao(ClinicalCourse.class).executeRaw("ALTER TABLE clinicalCourse RENAME TO tmp_clinicalCourse"); + getDao(ClinicalCourse.class).executeRaw( + "CREATE TABLE clinicalCourse(" + "id integer primary key autoincrement," + "uuid varchar(36) not null," + + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," + + "UNIQUE(snapshot, uuid));"); + getDao(ClinicalCourse.class).executeRaw( + "INSERT INTO clinicalCourse(id, uuid, changeDate, creationDate, lastOpenedDate, " + "localChangeDate, modified, snapshot) " + + "SELECT id, uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, snapshot FROM tmp_clinicalCourse"); + getDao(ClinicalCourse.class).executeRaw("DROP TABLE tmp_clinicalCourse;"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN infectionPathCertainty varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN humanTransmissionMode varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN parenteralTransmissionMode varchar(255);"); - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN medicallyAssociatedTransmissionMode varchar(255);"); + case 339: + currentVersion = 339; + getDao(User.class).executeRaw("ALTER TABLE users ADD COLUMN jurisdictionLevel varchar(255);"); + fillJurisdictionLevels(); - case 292: - currentVersion = 292; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN internalId text;"); + case 340: + currentVersion = 340; + getDao(FeatureConfiguration.class).executeRaw("DELETE from featureConfiguration WHERE featureType = 'DELETE_PERMANENT';"); + fillJurisdictionLevels(); - case 293: - currentVersion = 293; + case 341: + currentVersion = 341; + getDao(UserRole.class).executeRaw("DROP TABLE userrolesconfig;"); + getDao(UserRole.class).executeRaw( + "CREATE TABLE userRoles(id integer primary key autoincrement, uuid varchar(36), changeDate timestamp, creationDate timestamp, lastOpenedDate timestamp, " + + "localChangeDate timestamp, modified integer, snapshot integer, userRights text, enabled boolean, caption varchar(512), description varchar(4096), " + + "hasOptionalHealthFacility boolean, hasAssociatedDistrictUser boolean, portHealthUser boolean, jurisdictionLevel varchar(255));"); + getDao(UserRole.class).executeRaw("CREATE TABLE users_userRoles(user_id integer, userRole_id integer);"); - //@formatter:off - getDao(PersonContactDetail.class).executeRaw( - "CREATE TABLE personContactDetail (" - + " additionalInformation text," - + " contactInformation text," - + " details text," - + " person_id BIGINT," - + " personContactDetailType VARCHAR," - + " phoneNumberType VARCHAR," - + " primaryContact SMALLINT," - + " thirdParty SMALLINT," - + " thirdPartyName text," - + " thirdPartyRole text," - + " pseudonymized SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" + case 342: + currentVersion = 342; + getDao(AggregateReport.class).executeRaw("ALTER TABLE aggregateReport ADD COLUMN ageGroup varchar(255);"); + getDao(AggregateReport.class).executeRaw("UPDATE aggregateReport SET changeDate = 0;"); + getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseConfiguration ADD COLUMN ageGroupsString text;"); + getDao(DiseaseConfiguration.class).executeRaw("UPDATE diseaseConfiguration SET changeDate = 0;"); + case 343: + currentVersion = 343; + getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN generalizedRash boolean;"); + case 344: + currentVersion = 344; + getDao(Ebs.class).executeRaw( + "CREATE TABLE ebs (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "uuid VARCHAR(256)," + + "localChangeDate timestamp not null," + + "changeDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "creationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + + "lastOpenedDate timestamp," + + "ebstdate TIMESTAMP," + + "endDate TIMESTAMP," + + "pseudonymized boolean," + + "triageDate TIMESTAMP," + + "reportDateTime TIMESTAMP," + + "reportingUser_id BIGINT," + + "location_id BIGINT," + + "externalToken VARCHAR(512)," + + "internalToken TEXT," + + "deleted BOOLEAN DEFAULT FALSE," + + "archiveUndoneReason VARCHAR(512)," + + "change_user_id BIGINT," + + "deletionReason VARCHAR(255)," + + "automaticScanningType VARCHAR(512)," + + "manualScanningType VARCHAR(512)," + + "scanningType VARCHAR(512)," + + "descriptionOccurrence VARCHAR(512)," + + "sourceName VARCHAR(512)," + + "sourceUrl VARCHAR(512)," + + "dateOnset TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + + "personRegistering VARCHAR(512)," + + "personDesignation VARCHAR(512)," + + "personPhone VARCHAR(512)," + + "other VARCHAR(512)," + + "ebsLongitude DOUBLE PRECISION," + + "ebsLatitude DOUBLE PRECISION," + + "ebsLatLon DOUBLE PRECISION," + + "ebslocation_id BIGINT," + + "sourceInformation VARCHAR(255)," + + "archived BOOLEAN DEFAULT FALSE," + + "sormasToSormasOriginInfo_id BIGINT," + + "categoryOfInformant VARCHAR(255)," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + "informantName VARCHAR(512)," + + "informantTel VARCHAR(20)," + + "responsibleUser_id BIGINT," + + "otherDeletionReason VARCHAR(255)," + + "externalId VARCHAR(512)," + + "otherInformant VARCHAR(255)," + + "triaging_id BIGINT," + + "signalverification_id BIGINT," + + "riskassessment_id BIGINT," + + "ebsalert_id BIGINT," + + // Define Foreign Key Constraints + "FOREIGN KEY (reportingUser_id) REFERENCES users(id)," + + "FOREIGN KEY (location_id) REFERENCES location(id)," + + "FOREIGN KEY (change_user_id) REFERENCES users(id)," + + "FOREIGN KEY (ebslocation_id) REFERENCES location(id)," + + "FOREIGN KEY (triaging_id) REFERENCES triaging(id)," + + "FOREIGN KEY (signalVerification_id) REFERENCES signalVerification(id)," + + "FOREIGN KEY (riskAssessment_id) REFERENCES riskAssessment(id)," + + "FOREIGN KEY (ebsalert_id) REFERENCES ebsAlert(id)" + + ");" + ); + case 345: + currentVersion = 345; + getDao(Triaging.class).executeRaw( + "CREATE TABLE triaging(" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "uuid varchar(256)," + + "earlyWarning varchar(3)," + + "pseudonymized boolean," + + "specificSignal varchar(3)," + + "signalCategory varchar(255)," + + "healthConcern varchar(3)," + + "categoryDetails varchar(255)," + + "occurrencePreviously varchar(3)," + + "triagingDecision varchar(255)," + + "decisionDate date," + + "triageDate date," + + "referredTo varchar(255)," + + "changeDate timestamp not null," + + "creationDate timestamp," + + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + + "change_user_id bigint," + + "responsibleUser_id bigint," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + "triagingDecisionString varchar(255)," + + "categoryDetailsString varchar(255)," + + "outcomeSupervisor varchar(255)," + + "notSignal boolean default false," + + "humanLaboratoryCategoryDetails varchar(255)," + + "humanCommunityCategoryDetails varchar(255)," + + "humanFacilityCategoryDetails varchar(255)," + + "animalCommunityCategoryDetails varchar(255)," + + "animalFacilityCategoryDetails varchar(255)," + + "environmentalCategoryDetails varchar(255)," + + "poeCategoryDetails varchar(255)," + + "animalLaboratoryCategoryDetails varchar(255)," + + "categoryDetailsLevel varchar(255)," + + "supervisorReview varchar(3)," + + "potentialRisk varchar(3)," + + "referred varchar(3)," + + "ebs_id INTEGER," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + + ");" ); - //@formatter:on + case 346: + currentVersion = 346; + getDao(RiskAssessment.class).executeRaw( + "CREATE TABLE riskAssessment(" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "uuid VARCHAR(256)," + + "changeDate timestamp not null," + + "creationDate timestamp not null," + + "pseudonymized boolean," + + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + + "morbidityMortality VARCHAR(3)," + + "spreadProbability VARCHAR(3)," + + "controlMeasures VARCHAR(3)," + + "riskAssessment VARCHAR(255)," + + "assessmentDate TIMESTAMP," + + "assessmentTime VARCHAR(255)," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + "ebs_id INTEGER," + + "morbidityMortalityComment VARCHAR(255)," + + "spreadProbabilityComment VARCHAR(255)," + + "controlMeasuresComment VARCHAR(255)," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + + ");" + ); - migratePersonContactDetails(); - case 294: - currentVersion = 294; - getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnit varchar(255);"); - getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnitStart timestamp;"); - getDao(PreviousHospitalization.class).executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN intensiveCareUnitEnd timestamp"); - case 295: - currentVersion = 295; + case 343: + currentVersion = 343; + getDao(Task.class).executeRaw("ALTER TABLE tasks ADD COLUMN assignedByUser_id BIGINT REFERENCES users(id);"); - //@formatter:off - getDao(Continent.class).executeRaw( - "CREATE TABLE IF NOT EXISTS continent (" - + " defaultName text," - + " archived SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); + case 344: + currentVersion = 344; + getDao(Environment.class).executeRaw( + "CREATE TABLE environments(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL, " + + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " + + "snapshot INTEGER, reportDate TIMESTAMP, reportingUser_id BIGINT REFERENCES users(id), environmentName text, description text, " + + "externalId varchar(255), responsibleUser_id BIGINT REFERENCES users(id), investigationStatus varchar(255), environmentMedia varchar(255), " + + "waterType varchar(255), otherWaterType text, infrastructureDetails varchar(255), otherInfrastructureDetails text, waterUse text, " + + "otherWaterUse text, location_id BIGINT, UNIQUE(snapshot, uuid));"); - getDao(Subcontinent.class).executeRaw( - "CREATE TABLE IF NOT EXISTS subcontinent (" - + " continent_id BIGINT NOT NULL," - + " defaultName text," - + " archived SMALLINT," - + " changeDate BIGINT NOT NULL," - + " creationDate BIGINT NOT NULL," - + " id INTEGER PRIMARY KEY AUTOINCREMENT," - + " lastOpenedDate BIGINT," - + " localChangeDate BIGINT NOT NULL," - + " modified SMALLINT," - + " snapshot SMALLINT," - + " uuid VARCHAR NOT NULL," - + " UNIQUE (snapshot ASC, uuid ASC)" - + ");" - ); - //@formatter:on + case 345: + currentVersion = 345; + getDao(Environment.class).executeRaw("ALTER TABLE environments RENAME TO tmp_environments;"); + getDao(Environment.class).executeRaw( + "CREATE TABLE environments(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL UNIQUE, " + + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " + + "snapshot INTEGER, reportDate TIMESTAMP NOT NULL, reportingUser_id BIGINT REFERENCES users(id), environmentName text, description text, " + + "externalId varchar(255), responsibleUser_id BIGINT REFERENCES users(id), investigationStatus varchar(255), environmentMedia varchar(255), " + + "waterType varchar(255), otherWaterType text, infrastructureDetails varchar(255), otherInfrastructureDetails text, waterUse text, " + + "otherWaterUse text, location_id BIGINT, UNIQUE(snapshot, uuid));"); + getDao(Environment.class).executeRaw( + "INSERT INTO environments (uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, " + + "snapshot, reportDate, reportingUser_id, environmentName, description, externalId, responsibleUser_id, investigationStatus, environmentMedia, " + + "waterType, otherWaterType, infrastructureDetails, otherInfrastructureDetails, waterUse, otherWaterUse, location_id, id) " + + "SELECT uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, " + + "snapshot, reportDate, reportingUser_id, environmentName, description, externalId, responsibleUser_id, investigationStatus, environmentMedia, " + + "waterType, otherWaterType, infrastructureDetails, otherInfrastructureDetails, waterUse, otherWaterUse, location_id, id FROM tmp_environments"); + getDao(Environment.class).executeRaw("DROP TABLE tmp_environments"); - getDao(Country.class).executeRaw("ALTER TABLE country ADD COLUMN subcontinent_id BIGINT REFERENCES subcontinent(id);"); + case 346: + currentVersion = 346; + getDao(FeatureConfiguration.class).executeRaw("DELETE FROM featureConfiguration WHERE featureType = 'DASHBOARD';"); + // update + case 347: + currentVersion = 347; + getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseConfiguration RENAME TO tmp_diseaseConfiguration"); + getDao(DiseaseConfiguration.class).executeRaw( + "CREATE TABLE diseaseConfiguration(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL, " + + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " + + "snapshot INTEGER, disease VARCHAR(255), active boolean, primaryDisease boolean, followUpEnabled boolean, followUpDuration INTEGER, " + + "caseSurveillanceEnabled boolean, caseFollowUpDuration INTEGER, eventParticipantFollowUpDuration INTEGER, " + + "extendedClassification boolean, extendedClassificationMulti boolean, ageGroupsString text, UNIQUE(snapshot, uuid));"); + getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN aggregateReportingEnabled boolean;"); + getDao(DiseaseConfiguration.class).executeRaw( + "INSERT INTO diseaseConfiguration (id, uuid, changeDate, creationDate, lastOpenedDate, " + + "localChangeDate, modified, snapshot, disease, active, primaryDisease, followUpEnabled, followUpDuration, " + + "caseSurveillanceEnabled, caseFollowUpDuration, eventParticipantFollowUpDuration, extendedClassification, extendedClassificationMulti, " + + "ageGroupsString, aggregateReportingEnabled) " + + "SELECT id, uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, snapshot, disease, active, primaryDisease, " + + "followUpEnabled, followUpDuration, caseBased, caseFollowUpDuration, eventParticipantFollowUpDuration, extendedClassification, " + + "extendedClassificationMulti, ageGroupsString, NOT caseBased " + "FROM tmp_diseaseConfiguration;"); + getDao(DiseaseConfiguration.class).executeRaw("DROP TABLE tmp_diseaseConfiguration"); - case 296: - currentVersion = 296; - getDao(Region.class).executeRaw("ALTER TABLE region ADD COLUMN country_id bigint REFERENCES country(id);"); + case 348: + currentVersion = 348; + getDao(UserRole.class).executeRaw( + "UPDATE userRoles set userRights = replace(replace(replace(userRights, '\"CONTACT_CLASSIFY\"', ''), '\"CONTACT_ASSIGN\"', ''), ',,', ',')"); - case 297: - currentVersion = 297; - getDao(EpiData.class).executeRaw("ALTER TABLE exposures ADD COLUMN probableInfectionEnvironment boolean DEFAULT false;"); + case 349: + currentVersion = 349; + getDao(FeatureConfiguration.class).executeRaw( + "UPDATE featureConfiguration set featuretype = 'SORMAS_TO_SORMAS_SHARE_CASES' where featuretype = 'SORMAS_TO_SORMAS_SHARE_CASES_WITH_CONTACTS_AND_SAMPLES'"); - case 298: - currentVersion = 298; - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN continent_id BIGINT REFERENCES continent(id);"); - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN subcontinent_id BIGINT REFERENCES subcontinent(id);"); + case 350: + currentVersion = 350; + getDao(CustomizableEnumValue.class).executeRaw("ALTER TABLE customizableEnumValue ADD COLUMN defaultValue boolean;"); - case 299: - currentVersion = 299; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN followUpStatusChangeDate timestamp without time zone;"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN followUpStatusChangeUser_id BIGINT REFERENCES users(id);"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN followUpStatusChangeDate timestamp without time zone;"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN followUpStatusChangeUser_id BIGINT REFERENCES users(id);"); + case 351: + currentVersion = 351; + getDao(UserRole.class).executeRaw("ALTER TABLE userRoles ADD COLUMN linkedDefaultUserRole varchar(255);"); - case 300: - currentVersion = 300; - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonFirstName text"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonLastName text"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonPhone text"); - getDao(Facility.class).executeRaw("ALTER TABLE facility ADD COLUMN contactPersonEmail text"); + case 352: + currentVersion = 352; - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonFirstName text;"); - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonLastName text;"); - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonPhone text;"); - getDao(Location.class).executeRaw("ALTER TABLE location ADD COLUMN contactPersonEmail text;"); + if (columnDoesNotExist("vaccination", "lastOpenedDate")) { + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN lastOpenedDate timestamp;"); + } + if (columnDoesNotExist("vaccination", "localChangeDate")) { + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN localChangeDate timestamp;"); + } + if (columnDoesNotExist("vaccination", "modified")) { + getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN modified SMALLINT DEFAULT 0;"); + } + case 353: + currentVersion = 353; + getDao(FormBuilder.class).executeRaw( + "CREATE TABLE forms_form_fields(" + + "form_id bigint not null," + + "formField_id bigint not null," + + "PRIMARY KEY (form_id, formField_id)," + + "FOREIGN KEY (form_id) REFERENCES forms(id)," + + "FOREIGN KEY (formField_id) REFERENCES form_fields(id)" + + ");" + ); + case 354: + currentVersion = 354; + getDao(Ebs.class).executeRaw( + "CREATE TABLE ebs(" + + "id bigint primary key not null," + + "uuid varchar(36) not null unique," + + "changedate timestamp not null default CURRENT_TIMESTAMP," + + "creationdate timestamp not null default CURRENT_TIMESTAMP," + + "ebstdate timestamp," + + "reportdatetime timestamp not null," + + "reportinguser_id bigint," + + "location_id bigint," + + "externaltoken varchar(512)," + + "internaltoken text," + + "deleted boolean default false," + + "archiveundonereason varchar(512)," + + "change_user_id bigint," + + "deletionreason varchar(255)," + + "automaticScanningType varchar(512)," + + "manualScanningType varchar(512)," + + "scanningType varchar(512)," + + "descriptionOccurrence varchar(512)," + + "sourceName varchar(512)," + + "sourceUrl varchar(512)," + + "dateOnset timestamp," + + "personRegistering varchar(512)," + + "personDesignation varchar(512)," + + "personPhone varchar(512)," + + "other varchar(512)," + + "ebsLongitude double precision," + + "ebsLatitude double precision," + + "ebsLatLon double precision," + + "ebslocation_id bigint," + + "sourceInformation varchar(255)," + + "archived boolean default false," + + "sormasToSormasOriginInfo_id bigint," + + "categoryOfInformant varchar(255)," + + "informantName varchar(512)," + + "informantTel varchar(20)," + + "responsibleuser_id bigint," + + "otherdeletionreason varchar(255)," + + "externalid varchar(512)," + + "otherInformant varchar(255)," + + "triaging_id bigint," + + "signalVerification_id bigint," + + "riskAssessment_id bigint," + + "ebsalert_id bigint" + + ");" + ); - case 301: - currentVersion = 301; - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN additionalDetails text;"); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_reportinguser_id FOREIGN KEY (reportinguser_id) REFERENCES users(id);" + ); - case 302: - currentVersion = 302; - getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN pcrTestSpecification varchar(255);"); - getDao(PathogenTest.class) - .executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariant_id bigint REFERENCES diseaseVariant(id);"); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_location_id FOREIGN KEY (location_id) REFERENCES location(id);" + ); + + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users(id);" + ); + + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_ebslocation_id FOREIGN KEY (ebslocation_id) REFERENCES location(id);" + ); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_triaging_id FOREIGN KEY (triaging_id) REFERENCES triaging (id);" + ); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_signalVerification_id FOREIGN KEY (signalVerification_id) REFERENCES signalVerification (id);" + ); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_riskAssessment_id FOREIGN KEY (riskAssessment_id) REFERENCES riskAssessment (id);" + ); + getDao(Ebs.class).executeRaw( + "ALTER TABLE ebs ADD CONSTRAINT fk_ebs_ebsAlert_id FOREIGN KEY (ebsAlert_id) REFERENCES ebsAlert (id);" + ); + case 355: + currentVersion = 355; + getDao(Triaging.class).executeRaw( + "CREATE TABLE triaging(" + + "id bigint primary key not null," + + "uuid varchar(36) not null unique," + + "earlyWarning varchar(3)," + + "specificSignal varchar(3)," + + "signalCategory varchar(255)," + + "healthConcern varchar(3)," + + "categoryDetails varchar(255)," + + "occurrencePreviously varchar(3)," + + "triagingDecision varchar(255)," + + "decisionDate date," + + "referredTo varchar(255)," + + "changedate timestamp not null," + + "creationdate timestamp not null," + + "change_user_id bigint," + + "responsibleuser_id bigint," + + "triagingDecisionString varchar(255)," + + "categoryDetailsString varchar(255)," + + "outcomeSupervisor varchar(255)," + + "notSignal boolean default false," + + "humanLaboratoryCategoryDetails varchar(255)," + + "animalCommunityCategoryDetails varchar(255)," + + "animalFacilityCategoryDetails varchar(255)," + + "environmentalCategoryDetails varchar(255)," + + "poeCategoryDetails varchar(255)," + + "animalLaboratoryCategoryDetails varchar(255)," + + "humanCommunityCategoryDetails varchar(255)," + + "categoryDetailsLevel varchar(255)," + + "supervisorreview varchar(3)," + + "referred varchar(3)" + + ");" + ); + case 356: + currentVersion = 356; + getDao(RiskAssessment.class).executeRaw( + "CREATE TABLE riskAssessment(" + + "id bigint primary key autoincrement," + + "morbidityMortality varchar(3)," + + "spreadProbability varchar(3)," + + "controlMeasures varchar(3)," + + "riskAssessment varchar(255)," + + "assessmentDate timestamp," + + "assessmentTime varchar(255)," + + "ebs_id bigint," + + "morbidityMortalityComment varchar(255)," + + "spreadProbabilityComment varchar(255)," + + "controlMeasuresComment varchar(255)," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + // Foreign key constraint + ");" + ); + case 357: + currentVersion = 357; + getDao(EbsAlert.class).executeRaw( + "CREATE TABLE ebsAlert(" + + "id bigint primary key autoincrement," + + "actionInitiated varchar(3)," + + "responseStatus varchar(255)," + + "responseDate timestamp," + + "detailsResponseActivities varchar(255)," + + "detailsGiven varchar(255)," + + "alertIssued varchar(3)," + + "detailsAlertUsed varchar(255)," + + "ebs_id bigint," + + "alertDate timestamp," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + + ");" + ); + + // ATTENTION: break should only be done after last version + break; + default: + case 347: + currentVersion = 347; + getDao(EbsAlert.class).executeRaw( + "CREATE TABLE ebsAlert(" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "uuid VARCHAR(256)," + + "changeDate timestamp not null," + + "creationDate timestamp not null," + + "pseudonymized boolean," + + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + + "actionInitiated varchar(3)," + + "responseStatus varchar(255)," + + "responseDate timestamp," + + "detailsResponseActivities varchar(255)," + + "detailsGiven varchar(255)," + + "alertIssued varchar(3)," + + "detailsAlertUsed varchar(255)," + + "ebs_id INTEGER," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + "alertDate timestamp," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + + ");" + ); + case 348: + currentVersion = 348; + getDao(SignalVerification.class).executeRaw( + "CREATE TABLE signalverification (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT," + + "uuid VARCHAR(256)," + + "verificationSent TEXT," + + "verified TEXT," + + "pseudonymized boolean," + + "verificationCompleteDate TIMESTAMP," + + "lastOpenedDate timestamp," + + "localChangeDate timestamp not null," + + "dateOfOccurrence timestamp," + + "numberOfPersonAnimal TEXT," + + "numberOfDeath TEXT," + + " modified SMALLINT DEFAULT 0," + + " snapshot SMALLINT DEFAULT 0," + + "numberOfPersonCases TEXT," + + "numberOfDeathPerson TEXT," + + "description TEXT," + + "whyNotVerify TEXT," + + "creationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + + "changeDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + + "ebs_id INTEGER," + + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + + ");" + ); + // ATTENTION: break should only be done after last version + break; + + default: + throw new IllegalStateException("onUpgrade() with unknown oldVersion " + oldVersion); + } + } catch ( - case 303: - currentVersion = 303; - getDao(Area.class).executeRaw( - "CREATE TABLE area(" + "id integer primary key autoincrement," + "uuid varchar(36) not null unique," - + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," - + "archived SMALLINT DEFAULT 0," + "name varchar(255) not null," + "externalId varchar(255) not null" + ");"); - getDao(Region.class).executeRaw("ALTER TABLE region ADD COLUMN area_id BIGINT REFERENCES area(id);"); - getDao(Region.class).executeRaw("UPDATE region set changeDate=0;"); + Exception ex) { + throw new RuntimeException("Database upgrade failed for version " + currentVersion + ": " + ex.getMessage(), ex); + } + } - case 304: - currentVersion = 304; - getDao(Campaign.class).executeRaw("ALTER TABLE campaigns ADD COLUMN campaignFormMetas text;"); - getDao(Campaign.class).executeRaw("UPDATE campaigns set changeDate=0;"); + private void fillJurisdictionLevels() throws SQLException { + getDao(User.class).queryForAll().forEach(user -> { + try { + getDao(User.class).executeRaw( + "UPDATE users SET jurisdictionLevel = '" + getJurisdictionLevel(user.getUserRoles()).name() + "' WHERE id = " + user.getId() + + ";"); + } catch (SQLException e) { + throw new RuntimeException(e); + } + }); + } - case 305: - currentVersion = 305; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleRegion_id BIGINT REFERENCES region(id);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleDistrict_id BIGINT REFERENCES district(id);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN responsibleCommunity_id BIGINT REFERENCES community(id);"); + /** + * Returns the jurisdiction level of a user based on its user roles; has to be replicated here + * because UserDao can't be properly accessed while setting up the database. + */ + private JurisdictionLevel getJurisdictionLevel(Collection roles) { - case 306: - currentVersion = 306; - getDao(CustomizableEnumValue.class).executeRaw( - "CREATE TABLE customizableEnumValue(" + "id integer primary key autoincrement," + "uuid varchar(36) not null unique," - + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," - + "dataType varchar(255)," + "value text," + "caption text," + "translations text," + "diseases text," + "description text," - + "descriptionTranslations text," + "properties text);"); - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariant text;"); - getDao(Case.class).executeRaw( - "UPDATE cases SET diseaseVariant = UPPER(REPLACE((SELECT name FROM diseaseVariant WHERE diseaseVariant.id = cases.diseaseVariant_id), ' ', '_')) WHERE cases.diseaseVariant_id IS NOT NULL;"); - getDao(Case.class).executeRaw("UPDATE cases SET diseaseVariant_id = NULL;"); - getDao(PathogenTest.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariant text;"); - getDao(Case.class).executeRaw( - "UPDATE pathogenTest SET testedDiseaseVariant = UPPER(REPLACE((SELECT name FROM diseaseVariant WHERE diseaseVariant.id = pathogenTest.testedDiseaseVariant_id), ' ', '_')) WHERE pathogenTest.testedDiseaseVariant_id IS NOT NULL;"); - getDao(PathogenTest.class).executeRaw("UPDATE pathogenTest SET testedDiseaseVariant_id = NULL;"); - getDao(Case.class).executeRaw("DROP TABLE diseaseVariant;"); + boolean laboratoryJurisdictionPresent = false; + for (UserRole role : roles) { + final JurisdictionLevel jurisdictionLevel = role.getJurisdictionLevel(); + if (roles.size() == 1 || (jurisdictionLevel != JurisdictionLevel.NONE && jurisdictionLevel != JurisdictionLevel.LABORATORY)) { + return jurisdictionLevel; + } else if (jurisdictionLevel == JurisdictionLevel.LABORATORY) { + laboratoryJurisdictionPresent = true; + } + } - case 307: - currentVersion = 307; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN internalToken text;"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN internalToken text;"); - getDao(Person.class).executeRaw("ALTER TABLE person ADD COLUMN internalToken text;"); + return laboratoryJurisdictionPresent ? JurisdictionLevel.LABORATORY : JurisdictionLevel.NONE; + } - case 308: - currentVersion = 308; - getDao(Case.class).executeRaw( - "UPDATE cases" + " SET responsibleRegion_id = region_id," + " responsibleDistrict_id = district_id," - + " responsibleCommunity_id = community_id," + " region_id = null," + " district_id = null," + " community_id = null," - + " reportingDistrict_id = null" - + " WHERE responsibleRegion_id IS NULL AND (reportingDistrict_id IS NULL OR reportingDistrict_id = district_id)"); + private boolean columnDoesNotExist(String tableName, String columnName) throws SQLException { + GenericRawResults tableColumns = getDao(User.class).queryRaw("pragma table_info(" + tableName + ")"); + int nameColumnIndex = Arrays.asList(tableColumns.getColumnNames()).indexOf("name"); + return tableColumns.getResults().stream().noneMatch(columnRowData -> columnName.equals(columnRowData[nameColumnIndex])); + } - getDao(Case.class).executeRaw( - "UPDATE cases" + " SET responsibleRegion_id = (SELECT region_id from district where id = cases.reportingDistrict_id)," - + " responsibleDistrict_id = reportingDistrict_id," + " reportingDistrict_id = null" - + " WHERE responsibleRegion_id IS NULL AND reportingDistrict_id IS NOT NULL"); + private void doNullCheckOnString(Object[] result, int index) { + if (DataHelper.isNullOrEmpty((String) result[index])) { + Array.set(result, index, null); + } + } - case 309: - currentVersion = 309; - getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withAssociatedContacts boolean;"); - getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withSamples boolean;"); - getDao(SormasToSormasOriginInfo.class).executeRaw("ALTER TABLE sormasToSormasOriginInfo ADD COLUMN withEventParticipants boolean;"); + private void formatRawResultDate(Object[] result, int index) { + if (result[index] != null && result[index] instanceof Date) { + long time = ((Date) result[index]).getTime(); + if (time == 0L) { + Array.set(result, index, null); + } else { + Array.set(result, index, time); + } + } + } - case 310: - currentVersion = 310; - //@formatter:off - getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + - " id integer primary key autoincrement, uuid varchar(36) not null unique," + - " changeDate timestamp not null, creationDate timestamp not null, lastOpenedDate timestamp, localChangeDate timestamp not null," + - " modified SMALLINT DEFAULT 0, snapshot SMALLINT DEFAULT 0," + - " disease varchar(255) not null," + - " person_id bigint not null," + - " reportdate timestamp not null," + - " reportinguser_id bigint not null," + - " archived boolean DEFAULT false," + - " immunizationstatus varchar(255) not null," + - " meansofimmunization varchar(255) not null," + - " meansOfImmunizationDetails text," + - " immunizationmanagementstatus varchar(255) not null," + - " externalid varchar(255) not null," + - " responsibleregion_id bigint," + - " responsibledistrict_id bigint," + - " responsiblecommunity_id bigint," + - " country_id bigint," + - " startdate timestamp," + - " enddate timestamp," + - " numberofdoses int," + - " previousinfection varchar(255)," + - " lastinfectiondate timestamp," + - " additionaldetails text," + - " positivetestresultdate timestamp not null," + - " recoverydate timestamp not null," + - " relatedcase_id bigint)"); - //@formatter:on + private String generateDateNowSQL() { + return "CAST(ROUND((julianday('now') - 2440587.5)*86400000) As INTEGER)"; + } - case 311: - currentVersion = 311; - getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN pseudonymized boolean;"); + private int executeRaw(Class clazz, String statement, Object... parameters) throws SQLException { + String[] parametersStringed = Arrays.stream(parameters).map(parameter -> Objects.toString(parameter, null)).toArray(String[]::new); - case 312: - currentVersion = 312; - getDao(LbdsSync.class).executeRaw( - "CREATE TABLE lbdsSync(" + "sentUuid varchar(36) primary key," + "lastSendDate timestamp," + "lastReceivedDate timestamp);"); + return getDao(clazz).executeRaw(statement, parametersStringed); + } - case 313: - currentVersion = 313; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseVariant text;"); + private void migrateVaccinationInfo() throws SQLException { + // Retrieve all new unsynchronized cases with vaccinationStatus == VACCINATED from the database + GenericRawResults caseInfoResult = getDao(Case.class).queryRaw( + "SELECT cases.id, person_id, disease, diseaseDetails, reportDate, reportingUser_id, responsibleRegion_id, responsibleDistrict_id, " + + "responsibleCommunity_id, COALESCE(symptoms.onsetDate, cases.reportDate), firstVaccinationDate, vaccinationDate, vaccinationDoses, vaccineName, otherVaccineName, vaccine, " + + "vaccineManufacturer, otherVaccineManufacturer, vaccinationInfoSource, vaccineInn, vaccineBatchNumber, vaccineUniiCode, vaccineAtcCode," + + "pregnant, trimester, healthConditions_id FROM cases LEFT JOIN clinicalCourse ON cases.clinicalCourse_id = clinicalCourse.id " + + "LEFT JOIN symptoms ON cases.symptoms_id = symptoms.id WHERE cases.snapshot = 0 AND cases.changeDate = 0 AND vaccination = 'VACCINATED';", + new DataType[] { + DataType.BIG_INTEGER, // 0: cases.id + DataType.BIG_INTEGER, // 1: person_id + DataType.ENUM_STRING, // 2: disease + DataType.STRING, // 3: diseaseDetails + DataType.DATE_LONG, // 4: reportDate + DataType.BIG_INTEGER, // 5: reportingUser_id + DataType.BIG_INTEGER, // 6: responsibleRegion_id + DataType.BIG_INTEGER, // 7: responsibleDistrict_id + DataType.BIG_INTEGER, // 8: responsibleCommunity_id + DataType.DATE_LONG, // 9: symptoms.onsetDate OR cases.reportDate + DataType.DATE_LONG, // 10: firstVaccinationDate + DataType.DATE_LONG, // 11: vaccinationDate + DataType.STRING, // 12: vaccinationDoses + DataType.ENUM_STRING, // 13: vaccineName + DataType.STRING, // 14: otherVaccineName + DataType.STRING, // 15: vaccine + DataType.ENUM_STRING, // 16: vaccineManufacturer + DataType.STRING, // 17: otherVaccineManufacturer + DataType.ENUM_STRING, // 18: vaccinationInfoSource + DataType.STRING, // 19: vaccineInn + DataType.STRING, // 20: vaccineBatchNumber + DataType.STRING, // 21: vaccineUniiCode + DataType.STRING, // 22: vaccineAtcCode + DataType.ENUM_STRING, // 23: pregnant + DataType.ENUM_STRING, // 24: trimester + DataType.BIG_INTEGER });// 25: healthConditions_id - case 314: - currentVersion = 314; - getDao(Event.class).executeRaw("ALTER TABLE events ADD COLUMN eventIdentificationSource varchar(255);"); + List caseInfoList = caseInfoResult.getResults(); - case 315: - currentVersion = 315; - getDao(Immunization.class).executeRaw("DROP TABLE immunization"); - //@formatter:off - getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + - " id integer primary key autoincrement," + - " uuid varchar(36) not null unique," + - " changeDate timestamp not null," + - " creationDate timestamp not null," + - " lastOpenedDate timestamp," + - " localChangeDate timestamp not null," + - " modified SMALLINT DEFAULT 0," + - " snapshot SMALLINT DEFAULT 0," + - " pseudonymized SMALLINT," + - " disease varchar(255) not null," + - " person_id bigint not null," + - " reportDate timestamp not null," + - " reportingUser_id bigint not null," + - " archived boolean DEFAULT false," + - " immunizationStatus varchar(255) not null," + - " meansOfImmunization varchar(255) not null," + - " meansOfImmunizationDetails text," + - " immunizationManagementStatus varchar(255) not null," + - " externalId varchar(255) not null," + - " responsibleRegion_id bigint," + - " responsibleDistrict_id bigint," + - " responsibleCommunity_id bigint," + - " country_id bigint," + - " startDate timestamp," + - " endDate timestamp," + - " numberOfDoses int," + - " previousInfection varchar(255)," + - " lastInfectionDate timestamp," + - " additionalDetails text," + - " positiveTestResultDate timestamp not null," + - " recoveryDate timestamp not null," + - " relatedCase_id bigint)"); - //@formatter:on + for (Object[] caseInfo : caseInfoList) { + doNullCheckOnString(caseInfo, 3); + doNullCheckOnString(caseInfo, 14); + doNullCheckOnString(caseInfo, 15); + doNullCheckOnString(caseInfo, 17); + doNullCheckOnString(caseInfo, 19); + doNullCheckOnString(caseInfo, 20); + doNullCheckOnString(caseInfo, 21); + doNullCheckOnString(caseInfo, 22); + formatRawResultDate(caseInfo, 4); + formatRawResultDate(caseInfo, 9); + formatRawResultDate(caseInfo, 10); + formatRawResultDate(caseInfo, 11); - case 316: - currentVersion = 316; + if (DataHelper.isNullOrEmpty((String) caseInfo[12])) { + Array.set(caseInfo, 12, null); + } else { + try { + Array.set(caseInfo, 12, new Integer((String) caseInfo[12])); + } catch (NumberFormatException e) { + Array.set(caseInfo, 12, 1); + } + } + } - getDao(Case.class).executeRaw("ALTER TABLE events ADD COLUMN specificRisk text;"); + // Retrieve earlier cases of each person for each disease + Comparator comparator = Comparator.comparing(c -> new Date((Long) c[9])); + List filteredCaseInfo = new ArrayList<>(); + Map> caseInfoByDisease = caseInfoList.stream().collect(Collectors.groupingBy(c -> Disease.valueOf((String) c[2]))); + caseInfoByDisease.keySet().forEach(d -> { + filteredCaseInfo.addAll( + caseInfoByDisease.get(d) + .stream() + .sorted(comparator) + .collect( + Collectors.collectingAndThen( + Collectors.toMap( + c -> ((BigInteger) c[1]), + Function.identity(), + (c1, c2) -> new Date((Long) c1[9]).after(new Date((Long) c2[9])) ? c1 : c2), + r -> new ArrayList<>(r.values())))); + }); + + filteredCaseInfo.forEach(objects -> { + // Retrieve all cases of the case person with the respective disease + final Object caseId = objects[0]; + final Object personId = objects[1]; + final List objectList = caseInfoByDisease.get(Disease.valueOf((String) objects[2])) + .stream() + .filter( + c -> ((BigInteger) c[0]).intValue() != ((BigInteger) caseId).intValue() + && ((BigInteger) c[1]).intValue() == ((BigInteger) personId).intValue()) + .collect(Collectors.toList()); - case 317: - currentVersion = 317; - //@formatter:off - getDao(Vaccination.class).executeRaw( - "CREATE TABLE vaccination (" - + "id integer primary key autoincrement," - + " uuid varchar(36) unique," - + " changeDate timestamp," - + " creationDate timestamp," - + " immunization_id bigint," - + " healthConditions_id bigint," - + " reportDate timestamp," - + " reportingUser_id bigint," - + " vaccinationDate timestamp," - + " vaccineName varchar(255)," - + " otherVaccineName text," - + " vaccineManufacturer varchar(255)," - + " otherVaccineManufacturer text," - + " vaccineInn text," - + " vaccineBatchNumber text," - + " vaccineUniiCode text," - + " vaccineAtcCode text," - + " vaccinationInfoSource varchar(255)," - + " pregnant varchar(255)," - + " trimester varchar(255), pseudonymized boolean);"); - //@formatter:on + // set earliest report date + Comparator reportDateComparator = Comparator.comparing(c -> new Date((Long) c[4])); + objectList.stream().min(reportDateComparator).ifPresent(earliestObject -> { + objects[4] = earliestObject[4]; + }); + // set earliest first vaccination date + if (objects[10] == null) { + Comparator firstVacDateComparator = Comparator.comparing(c -> new Date((Long) c[10])); + objectList.stream().filter(c -> c[10] != null).max(firstVacDateComparator).ifPresent(earliestObject -> { + objects[10] = earliestObject[10]; + }); + } + // set latest last vaccination date + if (objects[11] == null) { + Comparator lastVacDateComparator = Comparator.comparing(c -> new Date((Long) c[11])); + objectList.stream().filter(c -> c[11] != null).min(lastVacDateComparator).ifPresent(earliestObject -> { + objects[11] = earliestObject[11]; + }); + } + // set latest available vaccine name + if (objects[13] == null) { + objectList.stream().filter(c -> c[13] != null).min(comparator).ifPresent(latestObject -> { + objects[13] = latestObject[13]; + objects[14] = latestObject[14]; + }); + } + // set latest available vaccine + if (objects[15] == null) { + objectList.stream().filter(c -> c[15] != null).min(comparator).ifPresent(latestObject -> objects[15] = latestObject[15]); + } + // set latest available vaccine manufacturer + if (objects[16] == null) { + objectList.stream().filter(c -> c[16] != null).min(comparator).ifPresent(latestObject -> { + objects[16] = latestObject[16]; + objects[17] = latestObject[17]; + }); + } + // set latest available vaccination info source + if (objects[18] == null) { + objectList.stream().filter(c -> c[18] != null).min(comparator).ifPresent(latestObject -> objects[18] = latestObject[18]); + } + // set latest available INN + if (objects[19] == null) { + objectList.stream().filter(c -> c[19] != null).min(comparator).ifPresent(latestObject -> objects[19] = latestObject[19]); + } + // set latest available batch number + if (objects[20] == null) { + objectList.stream().filter(c -> c[20] != null).min(comparator).ifPresent(latestObject -> objects[20] = latestObject[20]); + } + // set latest available UNII code + if (objects[21] == null) { + objectList.stream().filter(c -> c[21] != null).min(comparator).ifPresent(latestObject -> objects[21] = latestObject[21]); + } + // set latest available ATC code + if (objects[22] == null) { + objectList.stream().filter(c -> c[22] != null).min(comparator).ifPresent(latestObject -> objects[22] = latestObject[22]); + } + }); - case 318: - currentVersion = 318; - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN vaccineType text;"); - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN vaccineDose text;"); + // Create immunizations and vaccinations for each case + for (Object[] caseInfo : filteredCaseInfo) { + // Create immunization + String immunizationInsertQuery = "INSERT INTO immunization " + "(" + " uuid, changeDate, localChangeDate, creationDate, person_id," + + " disease, diseaseDetails, reportDate, reportingUser_id, immunizationStatus, meansOfImmunization, immunizationManagementStatus," + + " responsibleRegion_id, responsibleDistrict_id, responsibleCommunity_id, startDate, endDate, numberOfDoses, pseudonymized," + + " modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - case 319: - currentVersion = 319; - getDao(Person.class).executeRaw("UPDATE person SET sex = 'UNKNOWN' WHERE sex IS NULL;"); + executeRaw( + Immunization.class, + immunizationInsertQuery, + DataHelper.createUuid(), + 0, + caseInfo[1], + caseInfo[2], + caseInfo[3], + caseInfo[4], + caseInfo[5], + ImmunizationStatus.ACQUIRED.name(), + MeansOfImmunization.VACCINATION.name(), + ImmunizationManagementStatus.COMPLETED.name(), + caseInfo[6], + caseInfo[7], + caseInfo[8], + caseInfo[10], + caseInfo[11], + caseInfo[12], + 0, + 1, + 0); - case 320: - currentVersion = 320; - getDao(Country.class).executeRaw( - "UPDATE country SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultName = 'Western Europe') WHERE isoCode = 'NCL';"); - getDao(Location.class).executeRaw( - "UPDATE location SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultname = 'Western Europe') WHERE location.subcontinent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isocode = 'NCL');"); - getDao(Location.class).executeRaw( - "UPDATE location SET continent_id = (SELECT continent.id FROM continent WHERE continent.defaultName = 'Europe') WHERE location.continent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isoCode = 'NCL');"); + if (caseInfo[12] == null) { + // No vaccination doses specified + if (caseInfo[10] != null || caseInfo[11] == null) { + cloneHealthConditions(caseInfo[25]); + insertFirstVaccination(caseInfo, caseInfo[10]); + } - case 321: - currentVersion = 321; - getDao(Country.class).executeRaw( - "UPDATE country SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultName = 'Central Europe') WHERE isoCode = 'DEU';"); - getDao(Location.class).executeRaw( - "UPDATE location SET subcontinent_id = (SELECT subcontinent.id FROM subcontinent WHERE subcontinent.defaultname = 'Central Europe') WHERE location.subcontinent_id IS NOT NULL AND location.country_id = (SELECT country.id FROM country WHERE isocode = 'DEU');"); + // Last vaccination + if (caseInfo[11] != null || ("ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) || "ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13]))) { + cloneHealthConditions(caseInfo[25]); + insertVaccination(caseInfo, caseInfo[11]); + } + } else { + // Vaccination doses specified + int vaccinationDoses = (int) caseInfo[12]; - case 322: - currentVersion = 322; - getDao(Symptoms.class).executeRaw( - "UPDATE symptoms SET symptomatic = null WHERE (SELECT visitStatus FROM visits WHERE visits.symptoms_id = symptoms.id) != 'COOPERATIVE';"); + if (vaccinationDoses == 1) { + cloneHealthConditions(caseInfo[25]); + insertFirstVaccination(caseInfo, caseInfo[11] != null ? caseInfo[11] : caseInfo[10]); + } else { + cloneHealthConditions(caseInfo[25]); + insertFirstVaccination(caseInfo, caseInfo[10]); + for (int i = 2; i <= vaccinationDoses - 1; i++) { + cloneHealthConditions(caseInfo[25]); + insertVaccination(caseInfo, null); + } + cloneHealthConditions(caseInfo[25]); + insertVaccination(caseInfo, caseInfo[11]); + } + } + } + } - case 323: - currentVersion = 323; - getDao(Immunization.class).executeRaw("DROP TABLE immunization"); - //@formatter:off - getDao(Immunization.class).executeRaw("CREATE TABLE immunization (" + - " id integer primary key autoincrement," + - " uuid varchar(36) not null unique," + - " changeDate timestamp not null," + - " creationDate timestamp not null," + - " lastOpenedDate timestamp," + - " localChangeDate timestamp not null," + - " modified SMALLINT DEFAULT 0," + - " snapshot SMALLINT DEFAULT 0," + - " pseudonymized SMALLINT," + - " disease varchar(255)," + - " diseaseDetails varchar(512)," + - " person_id bigint REFERENCES person(id)," + - " reportDate timestamp not null," + - " reportingUser_id bigint REFERENCES users(id)," + - " archived boolean DEFAULT false," + - " immunizationStatus varchar(255)," + - " meansOfImmunization varchar(255)," + - " meansOfImmunizationDetails text," + - " immunizationManagementStatus varchar(255)," + - " externalId varchar(255)," + - " responsibleRegion_id bigint," + - " responsibleDistrict_id bigint," + - " responsibleCommunity_id bigint," + - " country_id bigint REFERENCES country(id)," + - " facilityType varchar(255)," + - " healthFacility_id bigint REFERENCES facility(id)," + - " healthFacilityDetails varchar(512)," + - " startDate timestamp," + - " endDate timestamp," + - " validFrom timestamp," + - " validUntil timestamp," + - " numberOfDoses int," + - " previousInfection varchar(255)," + - " lastInfectionDate timestamp," + - " additionalDetails text," + - " positiveTestResultDate timestamp," + - " recoveryDate timestamp," + - " relatedCase_id bigint REFERENCES cases(id))"); - //@formatter:on + private void insertVaccination(Object[] caseInfo, Object vaccinationDate) throws SQLException { + Vaccine vaccineName = caseInfo[13] != null + ? (caseInfo[13].equals("ASTRA_ZENECA_COMIRNATY") + ? Vaccine.COMIRNATY + : (caseInfo[13].equals("ASTRA_ZENECA_MRNA_1273")) ? Vaccine.MRNA_1273 : Vaccine.valueOf((String) caseInfo[13])) + : (caseInfo[15] != null ? Vaccine.OTHER : null); + String otherVaccineName = vaccineName == Vaccine.OTHER && caseInfo[15] == null ? (String) caseInfo[14] : (String) caseInfo[15]; + VaccineManufacturer vaccineManufacturer = "ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) + ? VaccineManufacturer.BIONTECH_PFIZER + : ("ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13])) + ? VaccineManufacturer.MODERNA + : (caseInfo[16] != null ? VaccineManufacturer.valueOf((String) caseInfo[16]) : null); + insertVaccination(caseInfo, vaccineName, otherVaccineName, vaccineManufacturer, vaccinationDate); + } - case 324: - currentVersion = 324; - migrateVaccinationInfo(); - // Last vaccination date has been moved to the vaccination entity, but still has to be used for Monkeypox - getDao(Case.class).executeRaw("UPDATE cases SET vaccinationDate = null WHERE disease != 'MONKEYPOX';"); - getDao(Contact.class).executeRaw("ALTER TABLE contacts ADD COLUMN vaccinationStatus varchar(255);"); - getDao(EventParticipant.class).executeRaw("ALTER TABLE eventParticipants ADD COLUMN vaccinationStatus varchar(255);"); + private void insertFirstVaccination(Object[] caseInfo, Object vaccinationDate) throws SQLException { + Vaccine vaccineName = caseInfo[13] != null + ? (caseInfo[13].equals("ASTRA_ZENECA_COMIRNATY") || caseInfo[13].equals("ASTRA_ZENECA_MRNA_1273")) + ? Vaccine.OXFORD_ASTRA_ZENECA + : Vaccine.valueOf((String) caseInfo[13]) + : (caseInfo[15] != null ? Vaccine.OTHER : null); + String otherVaccineName = vaccineName == Vaccine.OTHER && caseInfo[15] == null ? (String) caseInfo[14] : (String) caseInfo[15]; + VaccineManufacturer vaccineManufacturer = ("ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) || "ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13])) + ? VaccineManufacturer.ASTRA_ZENECA + : (caseInfo[16] != null ? VaccineManufacturer.valueOf((String) caseInfo[16]) : null); + insertVaccination(caseInfo, vaccineName, otherVaccineName, vaccineManufacturer, vaccinationDate); + } - case 325: - currentVersion = 325; - getDao(Immunization.class) - .executeRaw("ALTER TABLE immunization ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); - getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN ownershipHandedOver boolean;"); + private void cloneHealthConditions(Object healthConditionsId) throws SQLException { + executeRaw(HealthConditions.class, "CREATE TEMPORARY TABLE tmp AS SELECT * FROM healthConditions WHERE id = ?;", healthConditionsId); + executeRaw(HealthConditions.class, "UPDATE tmp SET id = NULL, uuid = ?;", DataHelper.createUuid()); + getDao(HealthConditions.class).executeRaw("INSERT INTO healthConditions SELECT * FROM tmp;"); + getDao(HealthConditions.class).executeRaw("DROP TABLE tmp;"); + } - case 326: - currentVersion = 326; - getDao(Person.class).executeRaw("UPDATE person SET sex = 'UNKNOWN' WHERE sex IS NULL;"); + private void insertVaccination( + Object[] caseInfo, + Vaccine vaccineName, + String otherVaccineName, + VaccineManufacturer vaccineManufacturer, + Object vaccinationDate) + throws SQLException { - case 327: - currentVersion = 327; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN diseaseVariantDetails varchar(512);"); - getDao(Case.class).executeRaw("ALTER TABLE events ADD COLUMN diseaseVariantDetails varchar(512);"); - getDao(Case.class).executeRaw("ALTER TABLE pathogenTest ADD COLUMN testedDiseaseVariantDetails varchar(512);"); + Long immunizationId = getDao(Immunization.class).queryRawValue("SELECT MAX(id) FROM immunization;"); + Long healthConditionsId = getDao(HealthConditions.class).queryRawValue("SELECT MAX(id) FROM healthConditions;"); + String vaccineNameString = vaccineName != null ? vaccineName.name() : null; + String vaccineManufacturerString = vaccineManufacturer != null ? vaccineManufacturer.name() : null; + String vaccinationInsertQuery = + "INSERT INTO vaccination" + "(" + " uuid, changeDate, localChangeDate, creationDate, immunization_id, healthConditions_id, " + + " reportDate, reportingUser_id, vaccinationDate, vaccineName, otherVaccineName, vaccineManufacturer, otherVaccineManufacturer, " + + " vaccinationInfoSource, vaccineInn, vaccineBatchNumber, vaccineUniiCode, vaccineAtcCode, pregnant, trimester, pseudonymized, " + + " modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - case 328: - currentVersion = 328; - if (columnDoesNotExist("immunization", "sormasToSormasOriginInfo_id")) { - getDao(Immunization.class).executeRaw( - "ALTER TABLE immunization ADD COLUMN sormasToSormasOriginInfo_id bigint REFERENCES sormasToSormasOriginInfo(id);"); - } - if (columnDoesNotExist("immunization", "ownershipHandedOver")) { - getDao(Immunization.class).executeRaw("ALTER TABLE immunization ADD COLUMN ownershipHandedOver boolean;"); - } + executeRaw( + Vaccination.class, + vaccinationInsertQuery, + DataHelper.createUuid(), + 0, + immunizationId, + healthConditionsId, + caseInfo[4], + caseInfo[5], + vaccinationDate, + vaccineNameString, + otherVaccineName, + vaccineManufacturerString, + caseInfo[17], + caseInfo[18], + caseInfo[19], + caseInfo[20], + caseInfo[21], + caseInfo[22], + caseInfo[23], + caseInfo[24], + 0, + 1, + 0); + } - case 329: - currentVersion = 329; - if (columnDoesNotExist("users", "associatedOfficer_id")) { - getDao(User.class).executeRaw("ALTER TABLE users ADD COLUMN associatedOfficer_id bigint REFERENCES users(id);"); - } + private void migrateEpiData() throws SQLException { + getDao(EpiData.class) + .executeRaw("UPDATE epidata SET wildbirds = 'YES', poultryEat = 'YES' WHERE poultry = 'YES' AND changeDate = 0 AND snapshot = 0;"); - case 330: - currentVersion = 330; - getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN description varchar(512);"); - getDao(Hospitalization.class).executeRaw("ALTER TABLE Previoushospitalizations ADD COLUMN admittedToHealthFacility varchar(255);"); - getDao(Hospitalization.class).executeRaw("ALTER TABLE Previoushospitalizations ADD COLUMN isolationDate timestamp;"); + // Epi data field names sometimes don't match the actual field names because the columns were renamed in the past + migrateEpiDataField("processingConfirmedCaseFluidUnsafe", Exposure.HANDLING_SAMPLES, YesNoUnknown.YES, ExposureType.WORK); + migrateEpiDataField("percutaneousCaseBlood", Exposure.PERCUTANEOUS, YesNoUnknown.YES, ExposureType.WORK); + migrateEpiDataField("wildbirdsLocation", Exposure.PHYSICAL_CONTACT_WITH_BODY, YesNoUnknown.YES, ExposureType.BURIAL); + migrateEpiDataField("wildbirdsDetails", Exposure.HANDLING_SAMPLES, YesNoUnknown.YES, ExposureType.WORK); + migrateEpiDataField( + "poultrySick", + Exposure.ANIMAL_CONDITION, + AnimalCondition.DEAD, + ExposureType.ANIMAL_CONTACT, + "poultryDate", + "poultryDate", + "poultrySickDetails", + "poultryLocation"); + migrateEpiDataField( + "poultryEat", + Exposure.EATING_RAW_ANIMAL_PRODUCTS, + YesNoUnknown.YES, + ExposureType.ANIMAL_CONTACT, + null, + null, + "poultryDetails", + null); + migrateEpiDataField("rodents", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.RODENT, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("bats", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.BAT, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("primates", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.PRIMATE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("swine", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.SWINE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("birds", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.POULTRY, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("rabbits", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.RABBIT, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("cattle", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CATTLE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("dogs", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.DOG, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("cats", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CAT, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("canidae", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CANIDAE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("camels", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CAMEL, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("snakes", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.SNAKE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("tickBite", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.TICK, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("fleaBite", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.FLEA, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("otherAnimals", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.OTHER, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("waterBody", Exposure.BODY_OF_WATER, YesNoUnknown.YES, ExposureType.OTHER, null, null, "waterBodyDetails", null); + migrateEpiDataField("visitedHealthFacility", Exposure.HABITATION_TYPE, HabitationType.MEDICAL, ExposureType.HABITATION); + migrateEpiDataField("visitedAnimalMarket", Exposure.ANIMAL_MARKET, YesNoUnknown.YES, ExposureType.OTHER); + migrateEpiDataField("areaConfirmedCases", Exposure.RISK_AREA, YesNoUnknown.YES, ExposureType.TRAVEL); + migrateEpiDataField("kindOfExposureBite", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.BITE, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("kindOfExposureTouch", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.TOUCH, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("kindOfExposureScratch", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.SCRATCH, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("kindOfExposureLick", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.LICK, ExposureType.ANIMAL_CONTACT); + migrateEpiDataField("kindOfExposureOther", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.OTHER, ExposureType.ANIMAL_CONTACT); - case 331: - currentVersion = 331; - getDao(EventParticipant.class) - .executeRaw("ALTER TABLE eventParticipants ADD COLUMN responsibleRegion_id BIGINT REFERENCES region(id);"); - getDao(EventParticipant.class) - .executeRaw("ALTER TABLE eventParticipants ADD COLUMN responsibleDistrict_id BIGINT REFERENCES district(id);"); + GenericRawResults lastExposureInfo = getDao(EpiData.class).queryRaw( + "SELECT id, dateOfLastExposure, placeOfLastExposure, animalCondition, animalVaccinationStatus, prophylaxisStatus, dateOfProphylaxis" + + " FROM epidata WHERE changeDate = 0 AND snapshot = 0 AND (dateOfLastExposure IS NOT NULL OR placeOfLastExposure IS NOT NULL" + + " OR animalCondition IS NOT NULL OR animalVaccinationStatus IS NOT NULL OR prophylaxisStatus IS NOT NULL OR dateOfProphylaxis IS NOT NULL);", + new DataType[] { + DataType.BIG_INTEGER, + DataType.DATE_LONG, + DataType.STRING, + DataType.ENUM_STRING, + DataType.ENUM_STRING, + DataType.ENUM_STRING, + DataType.DATE_LONG }); - case 332: - currentVersion = 332; - getDao(FeatureConfiguration.class).executeRaw("ALTER TABLE featureconfiguration ADD COLUMN properties text;"); + for (Object[] result : lastExposureInfo) { + doNullCheckOnString(result, 2); + formatRawResultDate(result, 1); + formatRawResultDate(result, 6); - case 333: - currentVersion = 333; -// Recreate immunization table because unique constraint was not taking snapshot into account - getDao(Immunization.class).executeRaw("ALTER TABLE immunization RENAME TO tmp_immunization;"); - getDao(Immunization.class).executeRaw( - "CREATE TABLE immunization (additionalDetails VARCHAR, " - + "archived boolean DEFAULT false, country_id BIGINT REFERENCES country(id), disease VARCHAR, diseaseDetails VARCHAR, endDate timestamp, externalId VARCHAR, immunizationManagementStatus VARCHAR, " - + "immunizationStatus VARCHAR, lastInfectionDate timestamp, meansOfImmunization VARCHAR, meansOfImmunizationDetails VARCHAR, " - + "numberOfDoses INTEGER, ownershipHandedOver boolean DEFAULT false, person_id BIGINT NOT NULL REFERENCES person(id), positiveTestResultDate timestamp, previousInfection VARCHAR, " - + "recoveryDate timestamp, relatedCase_id BIGINT REFERENCES cases(id), reportDate timestamp, reportingUser_id BIGINT REFERENCES users(id), responsibleCommunity_id BIGINT REFERENCES community(id), " - + "responsibleDistrict_id BIGINT REFERENCES district(id), responsibleRegion_id BIGINT REFERENCES region(id), sormasToSormasOriginInfo_id BIGINT REFERENCES sormasToSormasOriginInfo(id), startDate timestamp, pseudonymized SMALLINT, changeDate timestamp NOT NULL, " - + "creationDate timestamp NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT, lastOpenedDate timestamp, localChangeDate timestamp NOT NULL, " - + "modified SMALLINT DEFAULT 0, snapshot SMALLINT DEFAULT 0, uuid VARCHAR, validFrom timestamp, validUntil timestamp, facilityType VARCHAR, healthFacility_id BIGINT REFERENCES facility(id), healthFacilityDetails VARCHAR, UNIQUE (snapshot ASC, uuid ASC));"); - getDao(Immunization.class).executeRaw( - "INSERT INTO immunization (additionalDetails, archived, country_id, disease, diseaseDetails, endDate, externalId, immunizationManagementStatus, " - + "immunizationStatus, lastInfectionDate, meansOfImmunization, meansOfImmunizationDetails, numberOfDoses, ownershipHandedOver, person_id, positiveTestResultDate, previousInfection, " - + "recoveryDate, relatedCase_id, reportDate, reportingUser_id, responsibleCommunity_id, responsibleDistrict_id, responsibleRegion_id, sormasToSormasOriginInfo_id, startDate, pseudonymized, " - + "changeDate, creationDate, id, lastOpenedDate, localChangeDate, modified, snapshot, uuid, validFrom, validUntil, facilityType, healthFacility_id, healthFacilityDetails) " - + "SELECT additionalDetails, archived, country_id, disease, diseaseDetails, endDate, externalId, immunizationManagementStatus, " - + "immunizationStatus, lastInfectionDate, meansOfImmunization, meansOfImmunizationDetails, numberOfDoses, ownershipHandedOver, person_id, positiveTestResultDate, previousInfection, recoveryDate, relatedCase_id, " - + "reportDate, reportingUser_id, responsibleCommunity_id, responsibleDistrict_id, responsibleRegion_id, sormasToSormasOriginInfo_id, startDate, pseudonymized, changeDate, creationDate, id, lastOpenedDate, localChangeDate, " - + "modified, snapshot, uuid, validFrom, validUntil, facilityType, healthFacility_id, healthFacilityDetails FROM tmp_immunization;"); - getDao(Immunization.class).executeRaw("DROP TABLE tmp_immunization"); + Long locationId = insertLocation((String) result[2]); + VaccinationStatus vaccinationStatus = result[4] != null ? VaccinationStatus.valueOf((String) result[4]) : null; - case 334: - currentVersion = 334; + String exposureQuery = "INSERT INTO exposures" + "(" + + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, exposureType, " + + " startDate, endDate, animalCondition, animalVaccinated, prophylaxis, prophylaxisDate, description, pseudonymized, modified, snapshot" + + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - if (columnDoesNotExist("vaccination", "snapshot")) { - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN snapshot SMALLINT DEFAULT 0;"); - } + executeRaw( + Exposure.class, + exposureQuery, + DataHelper.createUuid(), + 0, + result[0], + locationId, + ExposureType.ANIMAL_CONTACT.name(), + result[1], + result[1], + result[3], + (vaccinationStatus == VaccinationStatus.VACCINATED + ? YesNoUnknown.YES.name() + : vaccinationStatus == VaccinationStatus.UNVACCINATED + ? YesNoUnknown.NO.name() + : vaccinationStatus == VaccinationStatus.UNKNOWN ? YesNoUnknown.UNKNOWN.name() : null), + result[5], + result[6], + "Automatic epi data migration based on last exposure details; this exposure may be merged with another exposure with animal contact", + 0, + 0, + 0); + } - case 335: - currentVersion = 335; - getDao(EventParticipant.class).executeRaw( - "UPDATE eventParticipants SET reportingUser_id = (SELECT reportingUser_id FROM events WHERE events.id = eventParticipants.event_id) WHERE reportingUser_id IS NULL;"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET typeOfAnimalDetails = (SELECT otherAnimalsDetails FROM epidata WHERE id = exposures.epidata_id AND exposures.typeOfAnimal = 'OTHER');"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET animalContactTypeDetails = (SELECT kindOfExposureDetails FROM epidata WHERE id = exposures.epidata_id AND exposures.animalContactType = 'OTHER');"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET waterSource = (SELECT waterSource FROM epidata WHERE id = exposures.epidata_id AND exposures.bodyOfWater = 'YES');"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET waterSourceDetails = (SELECT waterSourceOther FROM epidata WHERE id = exposures.epidata_id AND exposures.bodyOfWater = 'YES');"); + getDao(Exposure.class).executeRaw( + "UPDATE exposures SET description = 'Automatic epi data migration based on selected kinds of exposure; this exposure may be merged with another exposure with animal contact' WHERE exposureType = 'ANIMAL_CONTACT' AND typeOfAnimal IS NULL;"); + getDao(EpiData.class).executeRaw( + "UPDATE epidata SET contactWithSourceCaseKnown = 'YES' WHERE snapshot = 0 AND changeDate = 0 AND (directContactConfirmedCase = 'YES' OR directContactProbableCase = 'YES' OR closeContactProbableCase = 'YES' OR contactWithSourceRespiratoryCase = 'YES');"); - case 336: - currentVersion = 336; - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN generalBodilyPains varchar(255);"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN lesionsNeck boolean;"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN lesionsTrunk boolean;"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN rashes varchar(255);"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN macularRash varchar(255);"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN papularRash varchar(255);"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN vesicularRash varchar(255);"); - getDao(Symptoms.class).executeRaw("ALTER TABLE symptoms ADD COLUMN otherLesionAreas varchar(255)"); - getDao(Hospitalization.class).executeRaw("ALTER TABLE hospitalizations ADD COLUMN healthFacilityRecordNumber varchar(255);"); - getDao(PreviousHospitalization.class) - .executeRaw("ALTER TABLE previoushospitalizations ADD COLUMN healthFacilityRecordNumber varchar(255);"); + getDao(EpiData.class).executeRaw( + "UPDATE epidata SET exposureDetailsKnown = 'YES' WHERE snapshot = 0 AND changeDate = 0 AND (exposureDetailsKnown IS NULL OR exposureDetailsKnown != 'YES') " + + "AND (SELECT COUNT(id) FROM exposures WHERE exposures.epidata_id = epidata.id LIMIT 1) > 0;"); + } - case 337: - currentVersion = 337; - getDao(Case.class).executeRaw("ALTER TABLE cases ADD COLUMN healthConditions_id BIGINT REFERENCES healthConditions(id);"); - getDao(Case.class).executeRaw( - "UPDATE cases SET healthConditions_id = (SELECT healthConditions_id from clinicalCourse where clinicalCourse.id = cases.clinicalCourse_id);"); + private void migrateEpiDataField(String epiDataFieldName, String exposuresFieldName, Enum exposuresFieldValue, ExposureType exposureType) + throws SQLException { + migrateEpiDataField(epiDataFieldName, exposuresFieldName, exposuresFieldValue, exposureType, null, null, null, null); + } - case 338: - currentVersion = 338; - getDao(ClinicalCourse.class).executeRaw("ALTER TABLE clinicalCourse RENAME TO tmp_clinicalCourse"); - getDao(ClinicalCourse.class).executeRaw( - "CREATE TABLE clinicalCourse(" + "id integer primary key autoincrement," + "uuid varchar(36) not null," - + "changeDate timestamp not null," + "creationDate timestamp not null," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "modified SMALLINT DEFAULT 0," + "snapshot SMALLINT DEFAULT 0," - + "UNIQUE(snapshot, uuid));"); - getDao(ClinicalCourse.class).executeRaw( - "INSERT INTO clinicalCourse(id, uuid, changeDate, creationDate, lastOpenedDate, " + "localChangeDate, modified, snapshot) " - + "SELECT id, uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, snapshot FROM tmp_clinicalCourse"); - getDao(ClinicalCourse.class).executeRaw("DROP TABLE tmp_clinicalCourse;"); + private void migrateEpiDataField( + String epiDataFieldName, + String exposuresFieldName, + Enum exposuresFieldValue, + ExposureType exposureType, + String startDateFieldName, + String endDateFieldName, + String descriptionFieldName, + String locationDetailsFieldName) + throws SQLException { - case 339: - currentVersion = 339; - getDao(User.class).executeRaw("ALTER TABLE users ADD COLUMN jurisdictionLevel varchar(255);"); - fillJurisdictionLevels(); + GenericRawResults epiDataInfo = getDao(EpiData.class).queryRaw( + "SELECT id, " + startDateFieldName + ", " + endDateFieldName + ", " + descriptionFieldName + ", " + locationDetailsFieldName + + " FROM epidata WHERE changeDate = 0 AND snapshot = 0 AND " + epiDataFieldName + " = 'YES';", + new DataType[] { + DataType.BIG_INTEGER, + DataType.DATE_LONG, + DataType.DATE_LONG, + DataType.STRING, + DataType.STRING }); - case 340: - currentVersion = 340; - getDao(FeatureConfiguration.class).executeRaw("DELETE from featureConfiguration WHERE featureType = 'DELETE_PERMANENT';"); - fillJurisdictionLevels(); + for (Object[] result : epiDataInfo) { + doNullCheckOnString(result, 3); + doNullCheckOnString(result, 4); + formatRawResultDate(result, 1); + formatRawResultDate(result, 2); - case 341: - currentVersion = 341; - getDao(UserRole.class).executeRaw("DROP TABLE userrolesconfig;"); - getDao(UserRole.class).executeRaw( - "CREATE TABLE userRoles(id integer primary key autoincrement, uuid varchar(36), changeDate timestamp, creationDate timestamp, lastOpenedDate timestamp, " - + "localChangeDate timestamp, modified integer, snapshot integer, userRights text, enabled boolean, caption varchar(512), description varchar(4096), " - + "hasOptionalHealthFacility boolean, hasAssociatedDistrictUser boolean, portHealthUser boolean, jurisdictionLevel varchar(255));"); - getDao(UserRole.class).executeRaw("CREATE TABLE users_userRoles(user_id integer, userRole_id integer);"); + Long locationId = insertLocation((String) result[4]); - case 342: - currentVersion = 342; - getDao(AggregateReport.class).executeRaw("ALTER TABLE aggregateReport ADD COLUMN ageGroup varchar(255);"); - getDao(AggregateReport.class).executeRaw("UPDATE aggregateReport SET changeDate = 0;"); - getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseConfiguration ADD COLUMN ageGroupsString text;"); - getDao(DiseaseConfiguration.class).executeRaw("UPDATE diseaseConfiguration SET changeDate = 0;"); + String exposureQuery = + "INSERT INTO exposures" + "(" + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, exposureType, " + + exposuresFieldName + ", " + "startDate, endDate, description, pseudonymized, modified, snapshot" + ") VALUES (?, ?, " + + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - case 343: - currentVersion = 343; - getDao(Task.class).executeRaw("ALTER TABLE tasks ADD COLUMN assignedByUser_id BIGINT REFERENCES users(id);"); + executeRaw( + Exposure.class, + exposureQuery, + DataHelper.createUuid(), + 0, + result[0], + locationId, + exposureType.name(), + exposuresFieldValue.name(), + result[1], + result[2], + result[3], + 0, + 0, + 0); + } + } - case 344: - currentVersion = 344; - getDao(Environment.class).executeRaw( - "CREATE TABLE environments(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL, " - + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " - + "snapshot INTEGER, reportDate TIMESTAMP, reportingUser_id BIGINT REFERENCES users(id), environmentName text, description text, " - + "externalId varchar(255), responsibleUser_id BIGINT REFERENCES users(id), investigationStatus varchar(255), environmentMedia varchar(255), " - + "waterType varchar(255), otherWaterType text, infrastructureDetails varchar(255), otherInfrastructureDetails text, waterUse text, " - + "otherWaterUse text, location_id BIGINT, UNIQUE(snapshot, uuid));"); + private long insertLocation(String locationDetails) throws SQLException { + String locationQuery = + "INSERT INTO location " + "(uuid, changeDate, localChangeDate, creationDate, details, pseudonymized, modified, snapshot) " + + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?);"; - case 345: - currentVersion = 345; - getDao(Environment.class).executeRaw("ALTER TABLE environments RENAME TO tmp_environments;"); - getDao(Environment.class).executeRaw( - "CREATE TABLE environments(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL UNIQUE, " - + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " - + "snapshot INTEGER, reportDate TIMESTAMP NOT NULL, reportingUser_id BIGINT REFERENCES users(id), environmentName text, description text, " - + "externalId varchar(255), responsibleUser_id BIGINT REFERENCES users(id), investigationStatus varchar(255), environmentMedia varchar(255), " - + "waterType varchar(255), otherWaterType text, infrastructureDetails varchar(255), otherInfrastructureDetails text, waterUse text, " - + "otherWaterUse text, location_id BIGINT, UNIQUE(snapshot, uuid));"); - getDao(Environment.class).executeRaw( - "INSERT INTO environments (uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, " - + "snapshot, reportDate, reportingUser_id, environmentName, description, externalId, responsibleUser_id, investigationStatus, environmentMedia, " - + "waterType, otherWaterType, infrastructureDetails, otherInfrastructureDetails, waterUse, otherWaterUse, location_id, id) " - + "SELECT uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, " - + "snapshot, reportDate, reportingUser_id, environmentName, description, externalId, responsibleUser_id, investigationStatus, environmentMedia, " - + "waterType, otherWaterType, infrastructureDetails, otherInfrastructureDetails, waterUse, otherWaterUse, location_id, id FROM tmp_environments"); - getDao(Environment.class).executeRaw("DROP TABLE tmp_environments"); + executeRaw(Location.class, locationQuery, DataHelper.createUuid(), 0, locationDetails, 0, 0, 0); - case 346: - currentVersion = 346; - getDao(FeatureConfiguration.class).executeRaw("DELETE FROM featureConfiguration WHERE featureType = 'DASHBOARD';"); - // update - case 347: - currentVersion = 347; - getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseConfiguration RENAME TO tmp_diseaseConfiguration"); - getDao(DiseaseConfiguration.class).executeRaw( - "CREATE TABLE diseaseConfiguration(id integer primary key autoincrement, uuid VARCHAR(36) NOT NULL, " - + "changeDate TIMESTAMP NOT NULL, creationDate TIMESTAMP NOT NULL, lastOpenedDate TIMESTAMP, localChangeDate TIMESTAMP NOT NULL, modified INTEGER, " - + "snapshot INTEGER, disease VARCHAR(255), active boolean, primaryDisease boolean, followUpEnabled boolean, followUpDuration INTEGER, " - + "caseSurveillanceEnabled boolean, caseFollowUpDuration INTEGER, eventParticipantFollowUpDuration INTEGER, " - + "extendedClassification boolean, extendedClassificationMulti boolean, ageGroupsString text, UNIQUE(snapshot, uuid));"); - getDao(DiseaseConfiguration.class).executeRaw("ALTER TABLE diseaseconfiguration ADD COLUMN aggregateReportingEnabled boolean;"); - getDao(DiseaseConfiguration.class).executeRaw( - "INSERT INTO diseaseConfiguration (id, uuid, changeDate, creationDate, lastOpenedDate, " - + "localChangeDate, modified, snapshot, disease, active, primaryDisease, followUpEnabled, followUpDuration, " - + "caseSurveillanceEnabled, caseFollowUpDuration, eventParticipantFollowUpDuration, extendedClassification, extendedClassificationMulti, " - + "ageGroupsString, aggregateReportingEnabled) " - + "SELECT id, uuid, changeDate, creationDate, lastOpenedDate, localChangeDate, modified, snapshot, disease, active, primaryDisease, " - + "followUpEnabled, followUpDuration, caseBased, caseFollowUpDuration, eventParticipantFollowUpDuration, extendedClassification, " - + "extendedClassificationMulti, ageGroupsString, NOT caseBased " + "FROM tmp_diseaseConfiguration;"); - getDao(DiseaseConfiguration.class).executeRaw("DROP TABLE tmp_diseaseConfiguration"); + return getDao(Location.class).queryRawValue("SELECT MAX(id) FROM location;"); + } - case 348: - currentVersion = 348; - getDao(UserRole.class).executeRaw( - "UPDATE userRoles set userRights = replace(replace(replace(userRights, '\"CONTACT_CLASSIFY\"', ''), '\"CONTACT_ASSIGN\"', ''), ',,', ',')"); + private void migratePersonContactDetails() throws SQLException { + GenericRawResults newPersons = getDao(Person.class).queryRaw( + "SELECT id, phone, phoneOwner, emailAddress, generalPractitionerDetails FROM person WHERE changeDate = 0 AND snapshot = 0;", + new DataType[] { + DataType.BIG_INTEGER, + DataType.STRING, + DataType.STRING, + DataType.STRING, + DataType.STRING }); - case 349: - currentVersion = 349; - getDao(FeatureConfiguration.class).executeRaw( - "UPDATE featureConfiguration set featuretype = 'SORMAS_TO_SORMAS_SHARE_CASES' where featuretype = 'SORMAS_TO_SORMAS_SHARE_CASES_WITH_CONTACTS_AND_SAMPLES'"); + for (Object[] pcd : newPersons) { - case 350: - currentVersion = 350; - getDao(CustomizableEnumValue.class).executeRaw("ALTER TABLE customizableEnumValue ADD COLUMN defaultValue boolean;"); + final String insertQuery = + "INSERT INTO personContactDetail " + "(" + " uuid, changeDate, localChangeDate, creationDate, person_id, primaryContact, " + + " personContactDetailType, phoneNumberType, contactInformation, additionalInformation, " + + " thirdParty, thirdPartyRole, thirdPartyName, snapshot" + ") " + "VALUES (?, ?, " + generateDateNowSQL() + ", " + + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; - case 351: - currentVersion = 351; - getDao(UserRole.class).executeRaw("ALTER TABLE userRoles ADD COLUMN linkedDefaultUserRole varchar(255);"); + BigInteger personId = (BigInteger) pcd[0]; + String phone = (String) pcd[1]; + String phoneOwner = (String) pcd[2]; + String emailAddress = (String) pcd[3]; + String generalPractitionerDetails = (String) pcd[4]; - case 352: - currentVersion = 352; + if (StringUtils.isNotEmpty(phone)) { + boolean phoneOwnerEmpty = StringUtils.isEmpty(phoneOwner); + executeRaw( + PersonContactDetail.class, + insertQuery, + DataHelper.createUuid(), + 0, + personId, + (phoneOwnerEmpty ? 1 : 0), + PersonContactDetailType.PHONE.name(), + null, + phone, + null, + (phoneOwnerEmpty ? 0 : 1), + null, + (phoneOwnerEmpty ? null : phoneOwner), + 0); + } - if (columnDoesNotExist("vaccination", "lastOpenedDate")) { - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN lastOpenedDate timestamp;"); - } - if (columnDoesNotExist("vaccination", "localChangeDate")) { - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN localChangeDate timestamp;"); - } - if (columnDoesNotExist("vaccination", "modified")) { - getDao(Vaccination.class).executeRaw("ALTER TABLE vaccination ADD COLUMN modified SMALLINT DEFAULT 0;"); - } - case 353: - currentVersion = 353; - getDao(FormBuilder.class).executeRaw( - "CREATE TABLE forms_form_fields(" + "form_id bigint not null," + "formField_id bigint not null," - + "PRIMARY KEY (form_id, formField_id)," + "FOREIGN KEY (form_id) REFERENCES forms(id)," - + "FOREIGN KEY (formField_id) REFERENCES form_fields(id)" + ");"); - case 354: - currentVersion = 354; - getDao(Ebs.class).executeRaw( - "CREATE TABLE ebs (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "uuid VARCHAR(256)," + "localChangeDate timestamp not null," - + "changeDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + "creationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," - + "lastOpenedDate timestamp," + "ebstdate TIMESTAMP," + "endDate TIMESTAMP," + "pseudonymized boolean," - + "triageDate TIMESTAMP," + "reportDateTime TIMESTAMP," + "reportingUser_id BIGINT," + "location_id BIGINT," - + "externalToken VARCHAR(512)," + "internalToken TEXT," + "deleted BOOLEAN DEFAULT FALSE," - + "archiveUndoneReason VARCHAR(512)," + "change_user_id BIGINT," + "deletionReason VARCHAR(255)," - + "automaticScanningType VARCHAR(512)," + "manualScanningType VARCHAR(512)," + "scanningType VARCHAR(512)," - + "descriptionOccurrence VARCHAR(512)," + "sourceName VARCHAR(512)," + "sourceUrl VARCHAR(512)," - + "dateOnset TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + "personRegistering VARCHAR(512)," + "personDesignation VARCHAR(512)," - + "personPhone VARCHAR(512)," + "other VARCHAR(512)," + "ebsLongitude DOUBLE PRECISION," + "ebsLatitude DOUBLE PRECISION," - + "ebsLatLon DOUBLE PRECISION," + "ebslocation_id BIGINT," + "sourceInformation VARCHAR(255)," - + "archived BOOLEAN DEFAULT FALSE," + "sormasToSormasOriginInfo_id BIGINT," + "categoryOfInformant VARCHAR(255)," - + " modified SMALLINT DEFAULT 0," + " snapshot SMALLINT DEFAULT 0," + "informantName VARCHAR(512)," - + "informantTel VARCHAR(20)," + "responsibleUser_id BIGINT," + "otherDeletionReason VARCHAR(255)," - + "externalId VARCHAR(512)," + "otherInformant VARCHAR(255)," + "triaging_id BIGINT," + "signalverification_id BIGINT," - + "riskassessment_id BIGINT," + "ebsalert_id BIGINT," + - // Define Foreign Key Constraints - "FOREIGN KEY (reportingUser_id) REFERENCES users(id)," + "FOREIGN KEY (location_id) REFERENCES location(id)," - + "FOREIGN KEY (change_user_id) REFERENCES users(id)," + "FOREIGN KEY (ebslocation_id) REFERENCES location(id)," - + "FOREIGN KEY (triaging_id) REFERENCES triaging(id)," - + "FOREIGN KEY (signalVerification_id) REFERENCES signalVerification(id)," - + "FOREIGN KEY (riskAssessment_id) REFERENCES riskAssessment(id)," + "FOREIGN KEY (ebsalert_id) REFERENCES ebsAlert(id)" - + ");"); - case 355: - currentVersion = 355; - getDao(Triaging.class).executeRaw( - "CREATE TABLE triaging(" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "uuid varchar(256)," + "earlyWarning varchar(3)," - + "pseudonymized boolean," + "specificSignal varchar(3)," + "signalCategory varchar(255)," + "healthConcern varchar(3)," - + "categoryDetails varchar(255)," + "occurrencePreviously varchar(3)," + "triagingDecision varchar(255)," - + "decisionDate date," + "triageDate date," + "referredTo varchar(255)," + "changeDate timestamp not null," - + "creationDate timestamp," + "lastOpenedDate timestamp," + "localChangeDate timestamp not null," + "change_user_id bigint," - + "responsibleUser_id bigint," + " modified SMALLINT DEFAULT 0," + " snapshot SMALLINT DEFAULT 0," - + "triagingDecisionString varchar(255)," + "categoryDetailsString varchar(255)," + "outcomeSupervisor varchar(255)," - + "notSignal boolean default false," + "humanLaboratoryCategoryDetails varchar(255)," - + "humanCommunityCategoryDetails varchar(255)," + "humanFacilityCategoryDetails varchar(255)," - + "animalCommunityCategoryDetails varchar(255)," + "animalFacilityCategoryDetails varchar(255)," - + "environmentalCategoryDetails varchar(255)," + "poeCategoryDetails varchar(255)," - + "animalLaboratoryCategoryDetails varchar(255)," + "categoryDetailsLevel varchar(255)," + "supervisorReview varchar(3)," - + "potentialRisk varchar(3)," + "referred varchar(3)," + "ebs_id INTEGER," + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" - + ");"); - case 356: - currentVersion = 356; - getDao(RiskAssessment.class).executeRaw( - "CREATE TABLE riskAssessment(" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "uuid VARCHAR(256)," + "changeDate timestamp not null," - + "creationDate timestamp not null," + "pseudonymized boolean," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "morbidityMortality VARCHAR(3)," + "spreadProbability VARCHAR(3)," - + "controlMeasures VARCHAR(3)," + "riskAssessment VARCHAR(255)," + "assessmentDate TIMESTAMP," - + "assessmentTime VARCHAR(255)," + " modified SMALLINT DEFAULT 0," + " snapshot SMALLINT DEFAULT 0," + "ebs_id INTEGER," - + "morbidityMortalityComment VARCHAR(255)," + "spreadProbabilityComment VARCHAR(255)," - + "controlMeasuresComment VARCHAR(255)," + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + ");"); - - case 357: - currentVersion = 357; - getDao(EbsAlert.class).executeRaw( - "CREATE TABLE ebsAlert(" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "uuid VARCHAR(256)," + "changeDate timestamp not null," - + "creationDate timestamp not null," + "pseudonymized boolean," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "actionInitiated varchar(3)," + "responseStatus varchar(255)," - + "responseDate timestamp," + "detailsResponseActivities varchar(255)," + "detailsGiven varchar(255)," - + "alertIssued varchar(3)," + "detailsAlertUsed varchar(255)," + "ebs_id INTEGER," + " modified SMALLINT DEFAULT 0," - + " snapshot SMALLINT DEFAULT 0," + "alertDate timestamp," + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + ");"); - case 358: - currentVersion = 358; - getDao(SignalVerification.class).executeRaw( - "CREATE TABLE signalverification (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "uuid VARCHAR(256)," + "verificationSent TEXT," - + "verified TEXT," + "pseudonymized boolean," + "verificationCompleteDate TIMESTAMP," + "lastOpenedDate timestamp," - + "localChangeDate timestamp not null," + "dateOfOccurrence timestamp," + "numberOfPersonAnimal TEXT," + "numberOfDeath TEXT," - + " modified SMALLINT DEFAULT 0," + " snapshot SMALLINT DEFAULT 0," + "numberOfPersonCases TEXT," - + "numberOfDeathPerson TEXT," + "description TEXT," + "whyNotVerify TEXT," - + "creationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + "changeDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + "ebs_id INTEGER," - + "FOREIGN KEY (ebs_id) REFERENCES ebs(id)" + ");"); - // ATTENTION: break should only be done after last version - break; - default: - throw new IllegalStateException("onUpgrade() with unknown oldVersion " + oldVersion); + if (StringUtils.isNotEmpty(emailAddress)) { + executeRaw( + PersonContactDetail.class, + insertQuery, + DataHelper.createUuid(), + 0, + personId, + 1, + PersonContactDetailType.EMAIL.name(), + null, + emailAddress, + null, + 0, + null, + null, + 0); } - } catch ( - Exception ex) { - throw new RuntimeException("Database upgrade failed for version " + currentVersion + ": " + ex.getMessage(), ex); + if (StringUtils.isNotEmpty(generalPractitionerDetails)) { + executeRaw( + PersonContactDetail.class, + insertQuery, + DataHelper.createUuid(), + 0, + personId, + 0, + PersonContactDetailType.OTHER.name(), + null, + null, + generalPractitionerDetails, + 1, + "General practitioner", + generalPractitionerDetails, + 0); + } } } - private void fillJurisdictionLevels() throws SQLException { - getDao(User.class).queryForAll().forEach(user -> { - try { - getDao(User.class).executeRaw( - "UPDATE users SET jurisdictionLevel = '" + getJurisdictionLevel(user.getUserRoles()).name() + "' WHERE id = " + user.getId() - + ";"); - } catch (SQLException e) { - throw new RuntimeException(e); - } - }); - } + private void migrateEmbeddedEpiDataToExposures() throws SQLException { + GenericRawResults newBurials = getDao(EpiData.class).queryRaw( + "SELECT epiData_id, burialAddress_id, burialPersonName, burialRelation," + + "burialTouching, burialIll, burialDateFrom, burialDateTo FROM epidataburial WHERE changeDate = 0 AND snapshot = 0;", + new DataType[] { + DataType.BIG_INTEGER, + DataType.BIG_INTEGER, + DataType.STRING, + DataType.STRING, + DataType.ENUM_STRING, + DataType.ENUM_STRING, + DataType.DATE_LONG, + DataType.DATE_LONG }); - /** - * Returns the jurisdiction level of a user based on its user roles; has to be replicated here - * because UserDao can't be properly accessed while setting up the database. - */ - private JurisdictionLevel getJurisdictionLevel(Collection roles) { + for (Object[] burial : newBurials) { + doNullCheckOnString(burial, 2); + doNullCheckOnString(burial, 3); + formatRawResultDate(burial, 6); + formatRawResultDate(burial, 7); - boolean laboratoryJurisdictionPresent = false; - for (UserRole role : roles) { - final JurisdictionLevel jurisdictionLevel = role.getJurisdictionLevel(); - if (roles.size() == 1 || (jurisdictionLevel != JurisdictionLevel.NONE && jurisdictionLevel != JurisdictionLevel.LABORATORY)) { - return jurisdictionLevel; - } else if (jurisdictionLevel == JurisdictionLevel.LABORATORY) { - laboratoryJurisdictionPresent = true; - } + String burialQuery = "INSERT INTO exposures" + "(" + + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, deceasedPersonName, deceasedPersonRelation, " + + " physicalContactWithBody, deceasedPersonIll, startDate, endDate, exposureType, pseudonymized, modified, snapshot" + ")" + + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + executeRaw( + Exposure.class, + burialQuery, + DataHelper.createUuid(), + 0, + burial[0], + burial[1], + burial[2], + burial[3], + burial[4], + burial[5], + burial[6], + burial[7], + "BURIAL", + 0, + 0, + 0); + } + + GenericRawResults newGatherings = getDao(EpiData.class).queryRaw( + "SELECT epiData_id, gatheringAddress_id, gatheringDate, description FROM epidatagathering WHERE changeDate = 0 AND snapshot = 0;", + new DataType[] { + DataType.BIG_INTEGER, + DataType.BIG_INTEGER, + DataType.DATE_LONG, + DataType.STRING }); + + for (Object[] gathering : newGatherings) { + doNullCheckOnString(gathering, 3); + formatRawResultDate(gathering, 2); + + String gatheringQuery = + "INSERT INTO exposures" + "(uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, startDate, endDate, " + + " description, exposureType, pseudonymized, modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + executeRaw( + Exposure.class, + gatheringQuery, + DataHelper.createUuid(), + 0, + gathering[0], + gathering[1], + gathering[2], + gathering[2], + gathering[3], + "GATHERING", + 0, + 0, + 0); } - return laboratoryJurisdictionPresent ? JurisdictionLevel.LABORATORY : JurisdictionLevel.NONE; - } + GenericRawResults newTravels = getDao(EpiData.class).queryRaw( + "SELECT epiData_id, travelDateFrom, travelDateTo, travelType, travelDestination FROM epidatatravel WHERE changeDate = 0 AND snapshot = 0;", + new DataType[] { + DataType.BIG_INTEGER, + DataType.DATE_LONG, + DataType.DATE_LONG, + DataType.ENUM_STRING, + DataType.STRING }); + + for (Object[] travel : newTravels) { + formatRawResultDate(travel, 1); + formatRawResultDate(travel, 2); + + String detailsString = Stream.of((String) travel[3] != null ? ((String) travel[3]).replace("_", " ") : null, (String) travel[4]) + .filter(Objects::nonNull) + .collect(Collectors.joining(", ")); + + String locationQuery = + "INSERT INTO location" + "(uuid, changeDate, localChangeDate, creationDate, details, pseudonymized, modified, snapshot)" + + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?)"; - private boolean columnDoesNotExist(String tableName, String columnName) throws SQLException { - GenericRawResults tableColumns = getDao(User.class).queryRaw("pragma table_info(" + tableName + ")"); - int nameColumnIndex = Arrays.asList(tableColumns.getColumnNames()).indexOf("name"); - return tableColumns.getResults().stream().noneMatch(columnRowData -> columnName.equals(columnRowData[nameColumnIndex])); - } + executeRaw(Location.class, locationQuery, DataHelper.createUuid(), 0, detailsString, 0, 0, 0); - private void doNullCheckOnString(Object[] result, int index) { - if (DataHelper.isNullOrEmpty((String) result[index])) { - Array.set(result, index, null); + Long locationId = getDao(Location.class).queryRawValue("SELECT MAX(id) FROM location;"); + + String travelQuery = "INSERT INTO exposures" + "(" + + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, startDate, endDate, exposureType, " + + " pseudonymized, modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + + ", ?, ?, ?, ?, ?, ?, ?, ?)"; + + executeRaw(Exposure.class, travelQuery, DataHelper.createUuid(), 0, travel[0], locationId, travel[1], travel[2], "TRAVEL", 0, 0, 0); } } - private void formatRawResultDate(Object[] result, int index) { - if (result[index] != null && result[index] instanceof Date) { - long time = ((Date) result[index]).getTime(); - if (time == 0L) { - Array.set(result, index, null); - } else { - Array.set(result, index, time); + private void upgradeFromUnupgradableVersion(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion) { + try { + Log.i(DatabaseHelper.class.getName(), "onUpgrade"); + TableUtils.dropTable(connectionSource, Case.class, true); + TableUtils.dropTable(connectionSource, Immunization.class, true); + TableUtils.dropTable(connectionSource, Vaccination.class, true); + TableUtils.dropTable(connectionSource, Prescription.class, true); + TableUtils.dropTable(connectionSource, Treatment.class, true); + TableUtils.dropTable(connectionSource, Therapy.class, true); + TableUtils.dropTable(connectionSource, ClinicalVisit.class, true); + TableUtils.dropTable(connectionSource, ClinicalCourse.class, true); + TableUtils.dropTable(connectionSource, HealthConditions.class, true); + TableUtils.dropTable(connectionSource, MaternalHistory.class, true); + TableUtils.dropTable(connectionSource, PortHealthInfo.class, true); + TableUtils.dropTable(connectionSource, Person.class, true); + TableUtils.dropTable(connectionSource, PersonContactDetail.class, true); + TableUtils.dropTable(connectionSource, Location.class, true); + TableUtils.dropTable(connectionSource, Continent.class, true); + TableUtils.dropTable(connectionSource, Subcontinent.class, true); + TableUtils.dropTable(connectionSource, Country.class, true); + TableUtils.dropTable(connectionSource, Area.class, true); + TableUtils.dropTable(connectionSource, Region.class, true); + TableUtils.dropTable(connectionSource, District.class, true); + TableUtils.dropTable(connectionSource, Community.class, true); + TableUtils.dropTable(connectionSource, Facility.class, true); + TableUtils.dropTable(connectionSource, PointOfEntry.class, true); + TableUtils.dropTable(connectionSource, User.class, true); + TableUtils.dropTable(connectionSource, Symptoms.class, true); + TableUtils.dropTable(connectionSource, Task.class, true); + TableUtils.dropTable(connectionSource, Contact.class, true); + TableUtils.dropTable(connectionSource, Visit.class, true); + TableUtils.dropTable(connectionSource, Event.class, true); + TableUtils.dropTable(connectionSource, Ebs.class, true); + TableUtils.dropTable(connectionSource, Triaging.class, true); + TableUtils.dropTable(connectionSource, SignalVerification.class, true); + TableUtils.dropTable(connectionSource, RiskAssessment.class, true); + TableUtils.dropTable(connectionSource, EbsAlert.class, true); + TableUtils.dropTable(connectionSource, Sample.class, true); + TableUtils.dropTable(connectionSource, PathogenTest.class, true); + TableUtils.dropTable(connectionSource, AdditionalTest.class, true); + TableUtils.dropTable(connectionSource, EventParticipant.class, true); + TableUtils.dropTable(connectionSource, Hospitalization.class, true); + TableUtils.dropTable(connectionSource, PreviousHospitalization.class, true); + TableUtils.dropTable(connectionSource, EpiData.class, true); + TableUtils.dropTable(connectionSource, Exposure.class, true); + TableUtils.dropTable(connectionSource, ActivityAsCase.class, true); + TableUtils.dropTable(connectionSource, SyncLog.class, true); + TableUtils.dropTable(connectionSource, WeeklyReport.class, true); + TableUtils.dropTable(connectionSource, WeeklyReportEntry.class, true); + TableUtils.dropTable(connectionSource, AggregateReport.class, true); + TableUtils.dropTable(connectionSource, Outbreak.class, true); + TableUtils.dropTable(connectionSource, DiseaseClassificationCriteria.class, true); + TableUtils.dropTable(connectionSource, DiseaseConfiguration.class, true); + TableUtils.dropTable(connectionSource, CustomizableEnumValue.class, true); + TableUtils.dropTable(connectionSource, FeatureConfiguration.class, true); + TableUtils.dropTable(connectionSource, Campaign.class, true); + TableUtils.dropTable(connectionSource, CampaignFormMeta.class, true); + TableUtils.dropTable(connectionSource, CampaignFormData.class, true); + TableUtils.dropTable(connectionSource, LbdsSync.class, true); + TableUtils.dropTable(connectionSource, Environment.class, true); + TableUtils.dropTable(connectionSource, FormField.class, true); + TableUtils.dropTable(connectionSource, FormBuilder.class, true); + TableUtils.dropTable(connectionSource, FormBuilderFormField.class, true); + + if (oldVersion < 30) { + TableUtils.dropTable(connectionSource, Config.class, true); } + // after we drop the old databases, we build the new ones + onCreate(db, connectionSource); + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); + throw new RuntimeException(e); } } - private String generateDateNowSQL() { - return "CAST(ROUND((julianday('now') - 2440587.5)*86400000) As INTEGER)"; - } + public AbstractAdoDao getAdoDaoInner(Class type) { - private int executeRaw(Class clazz, String statement, Object... parameters) throws SQLException { - String[] parametersStringed = Arrays.stream(parameters).map(parameter -> Objects.toString(parameter, null)).toArray(String[]::new); + if (!adoDaos.containsKey(type)) { - return getDao(clazz).executeRaw(statement, parametersStringed); - } + // build dao + AbstractAdoDao dao; + Dao innerDao; - private void migrateVaccinationInfo() throws SQLException { - // Retrieve all new unsynchronized cases with vaccinationStatus == VACCINATED from the database - GenericRawResults caseInfoResult = getDao(Case.class).queryRaw( - "SELECT cases.id, person_id, disease, diseaseDetails, reportDate, reportingUser_id, responsibleRegion_id, responsibleDistrict_id, " - + "responsibleCommunity_id, COALESCE(symptoms.onsetDate, cases.reportDate), firstVaccinationDate, vaccinationDate, vaccinationDoses, vaccineName, otherVaccineName, vaccine, " - + "vaccineManufacturer, otherVaccineManufacturer, vaccinationInfoSource, vaccineInn, vaccineBatchNumber, vaccineUniiCode, vaccineAtcCode," - + "pregnant, trimester, healthConditions_id FROM cases LEFT JOIN clinicalCourse ON cases.clinicalCourse_id = clinicalCourse.id " - + "LEFT JOIN symptoms ON cases.symptoms_id = symptoms.id WHERE cases.snapshot = 0 AND cases.changeDate = 0 AND vaccination = 'VACCINATED';", - new DataType[] { - DataType.BIG_INTEGER, // 0: cases.id - DataType.BIG_INTEGER, // 1: person_id - DataType.ENUM_STRING, // 2: disease - DataType.STRING, // 3: diseaseDetails - DataType.DATE_LONG, // 4: reportDate - DataType.BIG_INTEGER, // 5: reportingUser_id - DataType.BIG_INTEGER, // 6: responsibleRegion_id - DataType.BIG_INTEGER, // 7: responsibleDistrict_id - DataType.BIG_INTEGER, // 8: responsibleCommunity_id - DataType.DATE_LONG, // 9: symptoms.onsetDate OR cases.reportDate - DataType.DATE_LONG, // 10: firstVaccinationDate - DataType.DATE_LONG, // 11: vaccinationDate - DataType.STRING, // 12: vaccinationDoses - DataType.ENUM_STRING, // 13: vaccineName - DataType.STRING, // 14: otherVaccineName - DataType.STRING, // 15: vaccine - DataType.ENUM_STRING, // 16: vaccineManufacturer - DataType.STRING, // 17: otherVaccineManufacturer - DataType.ENUM_STRING, // 18: vaccinationInfoSource - DataType.STRING, // 19: vaccineInn - DataType.STRING, // 20: vaccineBatchNumber - DataType.STRING, // 21: vaccineUniiCode - DataType.STRING, // 22: vaccineAtcCode - DataType.ENUM_STRING, // 23: pregnant - DataType.ENUM_STRING, // 24: trimester - DataType.BIG_INTEGER });// 25: healthConditions_id + try { + innerDao = super.getDao(type); - List caseInfoList = caseInfoResult.getResults(); + if (type.equals(Case.class)) { + dao = (AbstractAdoDao) new CaseDao((Dao) innerDao); + } else if (type.equals(Immunization.class)) { + dao = (AbstractAdoDao) new ImmunizationDao((Dao) innerDao); + } else if (type.equals(Vaccination.class)) { + dao = (AbstractAdoDao) new VaccinationDao((Dao) innerDao); + } else if (type.equals(Therapy.class)) { + dao = (AbstractAdoDao) new TherapyDao((Dao) innerDao); + } else if (type.equals(Prescription.class)) { + dao = (AbstractAdoDao) new PrescriptionDao((Dao) innerDao); + } else if (type.equals(Treatment.class)) { + dao = (AbstractAdoDao) new TreatmentDao((Dao) innerDao); + } else if (type.equals(Person.class)) { + dao = (AbstractAdoDao) new PersonDao((Dao) innerDao); + } else if (type.equals(PersonContactDetail.class)) { + dao = (AbstractAdoDao) new PersonContactDetailDao((Dao) innerDao); + } else if (type.equals(Location.class)) { + dao = (AbstractAdoDao) new LocationDao((Dao) innerDao); + } else if (type.equals(PointOfEntry.class)) { + dao = (AbstractAdoDao) new PointOfEntryDao((Dao) innerDao); + } else if (type.equals(Facility.class)) { + dao = (AbstractAdoDao) new FacilityDao((Dao) innerDao); + } else if (type.equals(Continent.class)) { + dao = (AbstractAdoDao) new ContinentDao((Dao) innerDao); + } else if (type.equals(Subcontinent.class)) { + dao = (AbstractAdoDao) new SubcontinentDao((Dao) innerDao); + } else if (type.equals(Country.class)) { + dao = (AbstractAdoDao) new CountryDao((Dao) innerDao); + } else if (type.equals(Area.class)) { + dao = (AbstractAdoDao) new AreaDao((Dao) innerDao); + } else if (type.equals(Region.class)) { + dao = (AbstractAdoDao) new RegionDao((Dao) innerDao); + } else if (type.equals(District.class)) { + dao = (AbstractAdoDao) new DistrictDao((Dao) innerDao); + } else if (type.equals(Community.class)) { + dao = (AbstractAdoDao) new CommunityDao((Dao) innerDao); + } else if (type.equals(User.class)) { + dao = (AbstractAdoDao) new UserDao((Dao) innerDao, super.getDao(UserUserRole.class)); + } else if (type.equals(UserRole.class)) { + dao = (AbstractAdoDao) new UserRoleDao((Dao) innerDao); + } else if (type.equals(DiseaseConfiguration.class)) { + dao = (AbstractAdoDao) new DiseaseConfigurationDao((Dao) innerDao); + } else if (type.equals(CustomizableEnumValue.class)) { + dao = (AbstractAdoDao) new CustomizableEnumValueDao((Dao) innerDao); + } else if (type.equals(FeatureConfiguration.class)) { + dao = (AbstractAdoDao) new FeatureConfigurationDao((Dao) innerDao); + } else if (type.equals(Symptoms.class)) { + dao = (AbstractAdoDao) new SymptomsDao((Dao) innerDao); + } else if (type.equals(HealthConditions.class)) { + dao = (AbstractAdoDao) new HealthConditionsDao((Dao) innerDao); + } else if (type.equals(ClinicalCourse.class)) { + dao = (AbstractAdoDao) new ClinicalCourseDao((Dao) innerDao); + } else if (type.equals(ClinicalVisit.class)) { + dao = (AbstractAdoDao) new ClinicalVisitDao((Dao) innerDao); + } else if (type.equals(MaternalHistory.class)) { + dao = (AbstractAdoDao) new MaternalHistoryDao((Dao) innerDao); + } else if (type.equals(PortHealthInfo.class)) { + dao = (AbstractAdoDao) new PortHealthInfoDao((Dao) innerDao); + } else if (type.equals(Task.class)) { + dao = (AbstractAdoDao) new TaskDao((Dao) innerDao); + } else if (type.equals(Contact.class)) { + dao = (AbstractAdoDao) new ContactDao((Dao) innerDao); + } else if (type.equals(Visit.class)) { + dao = (AbstractAdoDao) new VisitDao((Dao) innerDao); + } else if (type.equals(Event.class)) { + dao = (AbstractAdoDao) new EventDao((Dao) innerDao); + } else if (type.equals(Ebs.class)) { + dao = (AbstractAdoDao) new EbsDao((Dao) innerDao); + } else if (type.equals(Triaging.class)) { + dao = (AbstractAdoDao) new TriagingDao((Dao) innerDao); + } else if (type.equals(SignalVerification.class)) { + dao = (AbstractAdoDao) new SignalVerificationDao((Dao) innerDao); + } else if (type.equals(RiskAssessment.class)) { + dao = (AbstractAdoDao) new RiskAssessmentDao((Dao) innerDao); + } else if (type.equals(EbsAlert.class)) { + dao = (AbstractAdoDao) new EbsAlertDao((Dao) innerDao); + } else if (type.equals(EventParticipant.class)) { + dao = (AbstractAdoDao) new EventParticipantDao((Dao) innerDao); + } else if (type.equals(Sample.class)) { + dao = (AbstractAdoDao) new SampleDao((Dao) innerDao); + } else if (type.equals(PathogenTest.class)) { + dao = (AbstractAdoDao) new PathogenTestDao((Dao) innerDao); + } else if (type.equals(AdditionalTest.class)) { + dao = (AbstractAdoDao) new AdditionalTestDao((Dao) innerDao); + } else if (type.equals(Hospitalization.class)) { + dao = (AbstractAdoDao) new HospitalizationDao((Dao) innerDao); + } else if (type.equals(PreviousHospitalization.class)) { + dao = (AbstractAdoDao) new PreviousHospitalizationDao((Dao) innerDao); + } else if (type.equals(EpiData.class)) { + dao = (AbstractAdoDao) new EpiDataDao((Dao) innerDao); + } else if (type.equals(Exposure.class)) { + dao = (AbstractAdoDao) new ExposureDao((Dao) innerDao); + } else if (type.equals(ActivityAsCase.class)) { + dao = (AbstractAdoDao) new ActivityAsCaseDao((Dao) innerDao); + } else if (type.equals(WeeklyReport.class)) { + dao = (AbstractAdoDao) new WeeklyReportDao((Dao) innerDao); + } else if (type.equals(WeeklyReportEntry.class)) { + dao = (AbstractAdoDao) new WeeklyReportEntryDao((Dao) innerDao); + } else if (type.equals(AggregateReport.class)) { + dao = (AbstractAdoDao) new AggregateReportDao((Dao) innerDao); + } else if (type.equals(Outbreak.class)) { + dao = (AbstractAdoDao) new OutbreakDao((Dao) innerDao); + } else if (type.equals(DiseaseClassificationCriteria.class)) { + dao = (AbstractAdoDao) new DiseaseClassificationCriteriaDao((Dao) innerDao); + } else if (type.equals(SormasToSormasOriginInfo.class)) { + dao = (AbstractAdoDao) new SormasToSormasOriginInfoDao((Dao) innerDao); + } else if (type.equals(Campaign.class)) { + dao = (AbstractAdoDao) new CampaignDao((Dao) innerDao); + } else if (type.equals(CampaignFormMeta.class)) { + dao = (AbstractAdoDao) new CampaignFormMetaDao((Dao) innerDao); + } else if (type.equals(CampaignFormData.class)) { + dao = (AbstractAdoDao) new CampaignFormDataDao((Dao) innerDao); +// } else if (type.equals(AuditLogEntry.class)) { +// dao = (AbstractAdoDao) new AuditLogEntryDao((Dao) innerDao); +// } +// // TODO [vaccination info] integrate vaccination info +// // else if (type.equals(VaccinationInfo.class)) { +// // dao = (AbstractAdoDao) new VaccinationInfoDao((Dao) innerDao); + } + else if (type.equals(Environment.class)) { + dao = (AbstractAdoDao) new EnvironmentDao((Dao) innerDao); + } + else if (type.equals(FormField.class)) { + dao = (AbstractAdoDao) new FormFieldDao((Dao) innerDao); + } else if (type.equals(FormBuilder.class)) { + dao = (AbstractAdoDao) new FormBuilderDao((Dao) innerDao, super.getDao(FormBuilderFormField.class)); + } else { + throw new UnsupportedOperationException(type.toString()); + } - for (Object[] caseInfo : caseInfoList) { - doNullCheckOnString(caseInfo, 3); - doNullCheckOnString(caseInfo, 14); - doNullCheckOnString(caseInfo, 15); - doNullCheckOnString(caseInfo, 17); - doNullCheckOnString(caseInfo, 19); - doNullCheckOnString(caseInfo, 20); - doNullCheckOnString(caseInfo, 21); - doNullCheckOnString(caseInfo, 22); - formatRawResultDate(caseInfo, 4); - formatRawResultDate(caseInfo, 9); - formatRawResultDate(caseInfo, 10); - formatRawResultDate(caseInfo, 11); + adoDaos.put(type, dao); - if (DataHelper.isNullOrEmpty((String) caseInfo[12])) { - Array.set(caseInfo, 12, null); - } else { - try { - Array.set(caseInfo, 12, new Integer((String) caseInfo[12])); - } catch (NumberFormatException e) { - Array.set(caseInfo, 12, 1); - } + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't build dao", e); + throw new RuntimeException(e); } } - // Retrieve earlier cases of each person for each disease - Comparator comparator = Comparator.comparing(c -> new Date((Long) c[9])); - List filteredCaseInfo = new ArrayList<>(); - Map> caseInfoByDisease = caseInfoList.stream().collect(Collectors.groupingBy(c -> Disease.valueOf((String) c[2]))); - caseInfoByDisease.keySet().forEach(d -> { - filteredCaseInfo.addAll( - caseInfoByDisease.get(d) - .stream() - .sorted(comparator) - .collect( - Collectors.collectingAndThen( - Collectors.toMap( - c -> ((BigInteger) c[1]), - Function.identity(), - (c1, c2) -> new Date((Long) c1[9]).after(new Date((Long) c2[9])) ? c1 : c2), - r -> new ArrayList<>(r.values())))); - }); + return (AbstractAdoDao) adoDaos.get(type); + } - filteredCaseInfo.forEach(objects -> { - // Retrieve all cases of the case person with the respective disease - final Object caseId = objects[0]; - final Object personId = objects[1]; - final List objectList = caseInfoByDisease.get(Disease.valueOf((String) objects[2])) - .stream() - .filter( - c -> ((BigInteger) c[0]).intValue() != ((BigInteger) caseId).intValue() - && ((BigInteger) c[1]).intValue() == ((BigInteger) personId).intValue()) - .collect(Collectors.toList()); + public static AbstractAdoDao getAdoDao(Class type) { - // set earliest report date - Comparator reportDateComparator = Comparator.comparing(c -> new Date((Long) c[4])); - objectList.stream().min(reportDateComparator).ifPresent(earliestObject -> { - objects[4] = earliestObject[4]; - }); - // set earliest first vaccination date - if (objects[10] == null) { - Comparator firstVacDateComparator = Comparator.comparing(c -> new Date((Long) c[10])); - objectList.stream().filter(c -> c[10] != null).max(firstVacDateComparator).ifPresent(earliestObject -> { - objects[10] = earliestObject[10]; - }); - } - // set latest last vaccination date - if (objects[11] == null) { - Comparator lastVacDateComparator = Comparator.comparing(c -> new Date((Long) c[11])); - objectList.stream().filter(c -> c[11] != null).min(lastVacDateComparator).ifPresent(earliestObject -> { - objects[11] = earliestObject[11]; - }); - } - // set latest available vaccine name - if (objects[13] == null) { - objectList.stream().filter(c -> c[13] != null).min(comparator).ifPresent(latestObject -> { - objects[13] = latestObject[13]; - objects[14] = latestObject[14]; - }); - } - // set latest available vaccine - if (objects[15] == null) { - objectList.stream().filter(c -> c[15] != null).min(comparator).ifPresent(latestObject -> objects[15] = latestObject[15]); - } - // set latest available vaccine manufacturer - if (objects[16] == null) { - objectList.stream().filter(c -> c[16] != null).min(comparator).ifPresent(latestObject -> { - objects[16] = latestObject[16]; - objects[17] = latestObject[17]; - }); - } - // set latest available vaccination info source - if (objects[18] == null) { - objectList.stream().filter(c -> c[18] != null).min(comparator).ifPresent(latestObject -> objects[18] = latestObject[18]); - } - // set latest available INN - if (objects[19] == null) { - objectList.stream().filter(c -> c[19] != null).min(comparator).ifPresent(latestObject -> objects[19] = latestObject[19]); - } - // set latest available batch number - if (objects[20] == null) { - objectList.stream().filter(c -> c[20] != null).min(comparator).ifPresent(latestObject -> objects[20] = latestObject[20]); - } - // set latest available UNII code - if (objects[21] == null) { - objectList.stream().filter(c -> c[21] != null).min(comparator).ifPresent(latestObject -> objects[21] = latestObject[21]); - } - // set latest available ATC code - if (objects[22] == null) { - objectList.stream().filter(c -> c[22] != null).min(comparator).ifPresent(latestObject -> objects[22] = latestObject[22]); + if (!instance.adoDaos.containsKey(type)) { + synchronized (DatabaseHelper.class) { + return instance.getAdoDaoInner(type); } - }); - - // Create immunizations and vaccinations for each case - for (Object[] caseInfo : filteredCaseInfo) { - // Create immunization - String immunizationInsertQuery = "INSERT INTO immunization " + "(" + " uuid, changeDate, localChangeDate, creationDate, person_id," - + " disease, diseaseDetails, reportDate, reportingUser_id, immunizationStatus, meansOfImmunization, immunizationManagementStatus," - + " responsibleRegion_id, responsibleDistrict_id, responsibleCommunity_id, startDate, endDate, numberOfDoses, pseudonymized," - + " modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() - + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - executeRaw( - Immunization.class, - immunizationInsertQuery, - DataHelper.createUuid(), - 0, - caseInfo[1], - caseInfo[2], - caseInfo[3], - caseInfo[4], - caseInfo[5], - ImmunizationStatus.ACQUIRED.name(), - MeansOfImmunization.VACCINATION.name(), - ImmunizationManagementStatus.COMPLETED.name(), - caseInfo[6], - caseInfo[7], - caseInfo[8], - caseInfo[10], - caseInfo[11], - caseInfo[12], - 0, - 1, - 0); + } + return (AbstractAdoDao) instance.adoDaos.get(type); + } - if (caseInfo[12] == null) { - // No vaccination doses specified - if (caseInfo[10] != null || caseInfo[11] == null) { - cloneHealthConditions(caseInfo[25]); - insertFirstVaccination(caseInfo, caseInfo[10]); + public static ConfigDao getConfigDao() { + if (instance.configDao == null) { + synchronized (DatabaseHelper.class) { + if (instance.configDao == null) { + try { + instance.configDao = new ConfigDao((Dao) instance.getDao(Config.class)); + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't build ConfigDao", e); + throw new RuntimeException(e); + } } + } + } + return instance.configDao; + } - // Last vaccination - if (caseInfo[11] != null || ("ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) || "ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13]))) { - cloneHealthConditions(caseInfo[25]); - insertVaccination(caseInfo, caseInfo[11]); + public static SyncLogDao getSyncLogDao() { + if (instance.syncLogDao == null) { + synchronized (DatabaseHelper.class) { + if (instance.syncLogDao == null) { + try { + instance.syncLogDao = new SyncLogDao((Dao) instance.getDao(SyncLog.class)); + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't build SyncLogDao", e); + throw new RuntimeException(e); + } } - } else { - // Vaccination doses specified - int vaccinationDoses = (int) caseInfo[12]; + } + } + return instance.syncLogDao; + } - if (vaccinationDoses == 1) { - cloneHealthConditions(caseInfo[25]); - insertFirstVaccination(caseInfo, caseInfo[11] != null ? caseInfo[11] : caseInfo[10]); - } else { - cloneHealthConditions(caseInfo[25]); - insertFirstVaccination(caseInfo, caseInfo[10]); - for (int i = 2; i <= vaccinationDoses - 1; i++) { - cloneHealthConditions(caseInfo[25]); - insertVaccination(caseInfo, null); + public static LbdsSyncDao getLbdsSyncDao() { + if (instance.lbdsSyncDao == null) { + synchronized (DatabaseHelper.class) { + if (instance.lbdsSyncDao == null) { + try { + instance.lbdsSyncDao = new LbdsSyncDao((Dao) instance.getDao(LbdsSync.class)); + } catch (SQLException e) { + Log.e(DatabaseHelper.class.getName(), "Can't build SyncLogDao", e); + throw new RuntimeException(e); } - cloneHealthConditions(caseInfo[25]); - insertVaccination(caseInfo, caseInfo[11]); } } } + return instance.lbdsSyncDao; } - private void insertVaccination(Object[] caseInfo, Object vaccinationDate) throws SQLException { - Vaccine vaccineName = caseInfo[13] != null - ? (caseInfo[13].equals("ASTRA_ZENECA_COMIRNATY") - ? Vaccine.COMIRNATY - : (caseInfo[13].equals("ASTRA_ZENECA_MRNA_1273")) ? Vaccine.MRNA_1273 : Vaccine.valueOf((String) caseInfo[13])) - : (caseInfo[15] != null ? Vaccine.OTHER : null); - String otherVaccineName = vaccineName == Vaccine.OTHER && caseInfo[15] == null ? (String) caseInfo[14] : (String) caseInfo[15]; - VaccineManufacturer vaccineManufacturer = "ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) - ? VaccineManufacturer.BIONTECH_PFIZER - : ("ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13])) - ? VaccineManufacturer.MODERNA - : (caseInfo[16] != null ? VaccineManufacturer.valueOf((String) caseInfo[16]) : null); - insertVaccination(caseInfo, vaccineName, otherVaccineName, vaccineManufacturer, vaccinationDate); + public static CaseDao getCaseDao() { + return (CaseDao) getAdoDao(Case.class); + } + + public static ImmunizationDao getImmunizationDao() { + return (ImmunizationDao) getAdoDao(Immunization.class); + } + + public static VaccinationDao getVaccinationDao() { + return (VaccinationDao) getAdoDao(Vaccination.class); + } + + public static TherapyDao getTherapyDao() { + return (TherapyDao) getAdoDao(Therapy.class); } - private void insertFirstVaccination(Object[] caseInfo, Object vaccinationDate) throws SQLException { - Vaccine vaccineName = caseInfo[13] != null - ? (caseInfo[13].equals("ASTRA_ZENECA_COMIRNATY") || caseInfo[13].equals("ASTRA_ZENECA_MRNA_1273")) - ? Vaccine.OXFORD_ASTRA_ZENECA - : Vaccine.valueOf((String) caseInfo[13]) - : (caseInfo[15] != null ? Vaccine.OTHER : null); - String otherVaccineName = vaccineName == Vaccine.OTHER && caseInfo[15] == null ? (String) caseInfo[14] : (String) caseInfo[15]; - VaccineManufacturer vaccineManufacturer = ("ASTRA_ZENECA_COMIRNATY".equals(caseInfo[13]) || "ASTRA_ZENECA_MRNA_1273".equals(caseInfo[13])) - ? VaccineManufacturer.ASTRA_ZENECA - : (caseInfo[16] != null ? VaccineManufacturer.valueOf((String) caseInfo[16]) : null); - insertVaccination(caseInfo, vaccineName, otherVaccineName, vaccineManufacturer, vaccinationDate); + public static PrescriptionDao getPrescriptionDao() { + return (PrescriptionDao) getAdoDao(Prescription.class); } - private void cloneHealthConditions(Object healthConditionsId) throws SQLException { - executeRaw(HealthConditions.class, "CREATE TEMPORARY TABLE tmp AS SELECT * FROM healthConditions WHERE id = ?;", healthConditionsId); - executeRaw(HealthConditions.class, "UPDATE tmp SET id = NULL, uuid = ?;", DataHelper.createUuid()); - getDao(HealthConditions.class).executeRaw("INSERT INTO healthConditions SELECT * FROM tmp;"); - getDao(HealthConditions.class).executeRaw("DROP TABLE tmp;"); + public static TreatmentDao getTreatmentDao() { + return (TreatmentDao) getAdoDao(Treatment.class); } - private void insertVaccination( - Object[] caseInfo, - Vaccine vaccineName, - String otherVaccineName, - VaccineManufacturer vaccineManufacturer, - Object vaccinationDate) - throws SQLException { + public static ClinicalCourseDao getClinicalCourseDao() { + return (ClinicalCourseDao) getAdoDao(ClinicalCourse.class); + } - Long immunizationId = getDao(Immunization.class).queryRawValue("SELECT MAX(id) FROM immunization;"); - Long healthConditionsId = getDao(HealthConditions.class).queryRawValue("SELECT MAX(id) FROM healthConditions;"); - String vaccineNameString = vaccineName != null ? vaccineName.name() : null; - String vaccineManufacturerString = vaccineManufacturer != null ? vaccineManufacturer.name() : null; - String vaccinationInsertQuery = - "INSERT INTO vaccination" + "(" + " uuid, changeDate, localChangeDate, creationDate, immunization_id, healthConditions_id, " - + " reportDate, reportingUser_id, vaccinationDate, vaccineName, otherVaccineName, vaccineManufacturer, otherVaccineManufacturer, " - + " vaccinationInfoSource, vaccineInn, vaccineBatchNumber, vaccineUniiCode, vaccineAtcCode, pregnant, trimester, pseudonymized, " - + " modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() - + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + public static HealthConditionsDao getHealthConditionsDao() { + return (HealthConditionsDao) getAdoDao(HealthConditions.class); + } - executeRaw( - Vaccination.class, - vaccinationInsertQuery, - DataHelper.createUuid(), - 0, - immunizationId, - healthConditionsId, - caseInfo[4], - caseInfo[5], - vaccinationDate, - vaccineNameString, - otherVaccineName, - vaccineManufacturerString, - caseInfo[17], - caseInfo[18], - caseInfo[19], - caseInfo[20], - caseInfo[21], - caseInfo[22], - caseInfo[23], - caseInfo[24], - 0, - 1, - 0); + public static ClinicalVisitDao getClinicalVisitDao() { + return (ClinicalVisitDao) getAdoDao(ClinicalVisit.class); } - private void migrateEpiData() throws SQLException { - getDao(EpiData.class) - .executeRaw("UPDATE epidata SET wildbirds = 'YES', poultryEat = 'YES' WHERE poultry = 'YES' AND changeDate = 0 AND snapshot = 0;"); + public static MaternalHistoryDao getMaternalHistoryDao() { + return (MaternalHistoryDao) getAdoDao(MaternalHistory.class); + } - // Epi data field names sometimes don't match the actual field names because the columns were renamed in the past - migrateEpiDataField("processingConfirmedCaseFluidUnsafe", Exposure.HANDLING_SAMPLES, YesNoUnknown.YES, ExposureType.WORK); - migrateEpiDataField("percutaneousCaseBlood", Exposure.PERCUTANEOUS, YesNoUnknown.YES, ExposureType.WORK); - migrateEpiDataField("wildbirdsLocation", Exposure.PHYSICAL_CONTACT_WITH_BODY, YesNoUnknown.YES, ExposureType.BURIAL); - migrateEpiDataField("wildbirdsDetails", Exposure.HANDLING_SAMPLES, YesNoUnknown.YES, ExposureType.WORK); - migrateEpiDataField( - "poultrySick", - Exposure.ANIMAL_CONDITION, - AnimalCondition.DEAD, - ExposureType.ANIMAL_CONTACT, - "poultryDate", - "poultryDate", - "poultrySickDetails", - "poultryLocation"); - migrateEpiDataField( - "poultryEat", - Exposure.EATING_RAW_ANIMAL_PRODUCTS, - YesNoUnknown.YES, - ExposureType.ANIMAL_CONTACT, - null, - null, - "poultryDetails", - null); - migrateEpiDataField("rodents", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.RODENT, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("bats", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.BAT, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("primates", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.PRIMATE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("swine", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.SWINE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("birds", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.POULTRY, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("rabbits", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.RABBIT, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("cattle", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CATTLE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("dogs", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.DOG, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("cats", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CAT, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("canidae", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CANIDAE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("camels", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.CAMEL, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("snakes", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.SNAKE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("tickBite", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.TICK, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("fleaBite", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.FLEA, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("otherAnimals", Exposure.TYPE_OF_ANIMAL, TypeOfAnimal.OTHER, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("waterBody", Exposure.BODY_OF_WATER, YesNoUnknown.YES, ExposureType.OTHER, null, null, "waterBodyDetails", null); - migrateEpiDataField("visitedHealthFacility", Exposure.HABITATION_TYPE, HabitationType.MEDICAL, ExposureType.HABITATION); - migrateEpiDataField("visitedAnimalMarket", Exposure.ANIMAL_MARKET, YesNoUnknown.YES, ExposureType.OTHER); - migrateEpiDataField("areaConfirmedCases", Exposure.RISK_AREA, YesNoUnknown.YES, ExposureType.TRAVEL); - migrateEpiDataField("kindOfExposureBite", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.BITE, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("kindOfExposureTouch", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.TOUCH, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("kindOfExposureScratch", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.SCRATCH, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("kindOfExposureLick", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.LICK, ExposureType.ANIMAL_CONTACT); - migrateEpiDataField("kindOfExposureOther", Exposure.ANIMAL_CONTACT_TYPE, AnimalContactType.OTHER, ExposureType.ANIMAL_CONTACT); + public static PortHealthInfoDao getPortHealthInfoDao() { + return (PortHealthInfoDao) getAdoDao(PortHealthInfo.class); + } - GenericRawResults lastExposureInfo = getDao(EpiData.class).queryRaw( - "SELECT id, dateOfLastExposure, placeOfLastExposure, animalCondition, animalVaccinationStatus, prophylaxisStatus, dateOfProphylaxis" - + " FROM epidata WHERE changeDate = 0 AND snapshot = 0 AND (dateOfLastExposure IS NOT NULL OR placeOfLastExposure IS NOT NULL" - + " OR animalCondition IS NOT NULL OR animalVaccinationStatus IS NOT NULL OR prophylaxisStatus IS NOT NULL OR dateOfProphylaxis IS NOT NULL);", - new DataType[] { - DataType.BIG_INTEGER, - DataType.DATE_LONG, - DataType.STRING, - DataType.ENUM_STRING, - DataType.ENUM_STRING, - DataType.ENUM_STRING, - DataType.DATE_LONG }); + public static PersonDao getPersonDao() { + return (PersonDao) getAdoDao(Person.class); + } - for (Object[] result : lastExposureInfo) { - doNullCheckOnString(result, 2); - formatRawResultDate(result, 1); - formatRawResultDate(result, 6); + public static LocationDao getLocationDao() { + return (LocationDao) getAdoDao(Location.class); + } - Long locationId = insertLocation((String) result[2]); - VaccinationStatus vaccinationStatus = result[4] != null ? VaccinationStatus.valueOf((String) result[4]) : null; + public static PersonContactDetailDao getPersonContactDetailDao() { + return (PersonContactDetailDao) getAdoDao(PersonContactDetail.class); + } - String exposureQuery = "INSERT INTO exposures" + "(" - + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, exposureType, " - + " startDate, endDate, animalCondition, animalVaccinated, prophylaxis, prophylaxisDate, description, pseudonymized, modified, snapshot" - + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + public static PointOfEntryDao getPointOfEntryDao() { + return (PointOfEntryDao) getAdoDao(PointOfEntry.class); + } - executeRaw( - Exposure.class, - exposureQuery, - DataHelper.createUuid(), - 0, - result[0], - locationId, - ExposureType.ANIMAL_CONTACT.name(), - result[1], - result[1], - result[3], - (vaccinationStatus == VaccinationStatus.VACCINATED - ? YesNoUnknown.YES.name() - : vaccinationStatus == VaccinationStatus.UNVACCINATED - ? YesNoUnknown.NO.name() - : vaccinationStatus == VaccinationStatus.UNKNOWN ? YesNoUnknown.UNKNOWN.name() : null), - result[5], - result[6], - "Automatic epi data migration based on last exposure details; this exposure may be merged with another exposure with animal contact", - 0, - 0, - 0); - } + public static FacilityDao getFacilityDao() { + return (FacilityDao) getAdoDao(Facility.class); + } - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET typeOfAnimalDetails = (SELECT otherAnimalsDetails FROM epidata WHERE id = exposures.epidata_id AND exposures.typeOfAnimal = 'OTHER');"); - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET animalContactTypeDetails = (SELECT kindOfExposureDetails FROM epidata WHERE id = exposures.epidata_id AND exposures.animalContactType = 'OTHER');"); - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET waterSource = (SELECT waterSource FROM epidata WHERE id = exposures.epidata_id AND exposures.bodyOfWater = 'YES');"); - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET waterSourceDetails = (SELECT waterSourceOther FROM epidata WHERE id = exposures.epidata_id AND exposures.bodyOfWater = 'YES');"); - getDao(Exposure.class).executeRaw( - "UPDATE exposures SET description = 'Automatic epi data migration based on selected kinds of exposure; this exposure may be merged with another exposure with animal contact' WHERE exposureType = 'ANIMAL_CONTACT' AND typeOfAnimal IS NULL;"); - getDao(EpiData.class).executeRaw( - "UPDATE epidata SET contactWithSourceCaseKnown = 'YES' WHERE snapshot = 0 AND changeDate = 0 AND (directContactConfirmedCase = 'YES' OR directContactProbableCase = 'YES' OR closeContactProbableCase = 'YES' OR contactWithSourceRespiratoryCase = 'YES');"); + public static ContinentDao getContinentDao() { + return (ContinentDao) getAdoDao(Continent.class); + } - getDao(EpiData.class).executeRaw( - "UPDATE epidata SET exposureDetailsKnown = 'YES' WHERE snapshot = 0 AND changeDate = 0 AND (exposureDetailsKnown IS NULL OR exposureDetailsKnown != 'YES') " - + "AND (SELECT COUNT(id) FROM exposures WHERE exposures.epidata_id = epidata.id LIMIT 1) > 0;"); + public static SubcontinentDao getSubcontinentDao() { + return (SubcontinentDao) getAdoDao(Subcontinent.class); } - private void migrateEpiDataField(String epiDataFieldName, String exposuresFieldName, Enum exposuresFieldValue, ExposureType exposureType) - throws SQLException { - migrateEpiDataField(epiDataFieldName, exposuresFieldName, exposuresFieldValue, exposureType, null, null, null, null); + public static CountryDao getCountryDao() { + return (CountryDao) getAdoDao(Country.class); } - private void migrateEpiDataField( - String epiDataFieldName, - String exposuresFieldName, - Enum exposuresFieldValue, - ExposureType exposureType, - String startDateFieldName, - String endDateFieldName, - String descriptionFieldName, - String locationDetailsFieldName) - throws SQLException { + public static RegionDao getRegionDao() { + return (RegionDao) getAdoDao(Region.class); + } - GenericRawResults epiDataInfo = getDao(EpiData.class).queryRaw( - "SELECT id, " + startDateFieldName + ", " + endDateFieldName + ", " + descriptionFieldName + ", " + locationDetailsFieldName - + " FROM epidata WHERE changeDate = 0 AND snapshot = 0 AND " + epiDataFieldName + " = 'YES';", - new DataType[] { - DataType.BIG_INTEGER, - DataType.DATE_LONG, - DataType.DATE_LONG, - DataType.STRING, - DataType.STRING }); + public static AreaDao getAreaDao() { + return (AreaDao) getAdoDao(Area.class); + } - for (Object[] result : epiDataInfo) { - doNullCheckOnString(result, 3); - doNullCheckOnString(result, 4); - formatRawResultDate(result, 1); - formatRawResultDate(result, 2); + public static DistrictDao getDistrictDao() { + return (DistrictDao) getAdoDao(District.class); + } - Long locationId = insertLocation((String) result[4]); + public static CommunityDao getCommunityDao() { + return (CommunityDao) getAdoDao(Community.class); + } - String exposureQuery = - "INSERT INTO exposures" + "(" + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, exposureType, " - + exposuresFieldName + ", " + "startDate, endDate, description, pseudonymized, modified, snapshot" + ") VALUES (?, ?, " - + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + public static UserDao getUserDao() { + return (UserDao) getAdoDao(User.class); + } - executeRaw( - Exposure.class, - exposureQuery, - DataHelper.createUuid(), - 0, - result[0], - locationId, - exposureType.name(), - exposuresFieldValue.name(), - result[1], - result[2], - result[3], - 0, - 0, - 0); - } + public static UserRoleDao getUserRoleDao() { + return (UserRoleDao) getAdoDao(UserRole.class); } - private long insertLocation(String locationDetails) throws SQLException { - String locationQuery = - "INSERT INTO location " + "(uuid, changeDate, localChangeDate, creationDate, details, pseudonymized, modified, snapshot) " - + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?);"; + public static DiseaseConfigurationDao getDiseaseConfigurationDao() { + return (DiseaseConfigurationDao) getAdoDao(DiseaseConfiguration.class); + } - executeRaw(Location.class, locationQuery, DataHelper.createUuid(), 0, locationDetails, 0, 0, 0); + public static CustomizableEnumValueDao getCustomizableEnumValueDao() { + return (CustomizableEnumValueDao) getAdoDao(CustomizableEnumValue.class); + } - return getDao(Location.class).queryRawValue("SELECT MAX(id) FROM location;"); + public static FeatureConfigurationDao getFeatureConfigurationDao() { + return (FeatureConfigurationDao) getAdoDao(FeatureConfiguration.class); } - private void migratePersonContactDetails() throws SQLException { - GenericRawResults newPersons = getDao(Person.class).queryRaw( - "SELECT id, phone, phoneOwner, emailAddress, generalPractitionerDetails FROM person WHERE changeDate = 0 AND snapshot = 0;", - new DataType[] { - DataType.BIG_INTEGER, - DataType.STRING, - DataType.STRING, - DataType.STRING, - DataType.STRING }); + public static FormFieldDao getFormFieldDao() { + return (FormFieldDao) getAdoDao(FormField.class); + } - for (Object[] pcd : newPersons) { + public static FormBuilderDao getFormBuilderDao() { + return (FormBuilderDao) getAdoDao(FormBuilder.class); + } - final String insertQuery = - "INSERT INTO personContactDetail " + "(" + " uuid, changeDate, localChangeDate, creationDate, person_id, primaryContact, " - + " personContactDetailType, phoneNumberType, contactInformation, additionalInformation, " - + " thirdParty, thirdPartyRole, thirdPartyName, snapshot" + ") " + "VALUES (?, ?, " + generateDateNowSQL() + ", " - + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"; + public static SymptomsDao getSymptomsDao() { + return (SymptomsDao) getAdoDao(Symptoms.class); + } - BigInteger personId = (BigInteger) pcd[0]; - String phone = (String) pcd[1]; - String phoneOwner = (String) pcd[2]; - String emailAddress = (String) pcd[3]; - String generalPractitionerDetails = (String) pcd[4]; + public static TaskDao getTaskDao() { + return (TaskDao) getAdoDao(Task.class); + } - if (StringUtils.isNotEmpty(phone)) { - boolean phoneOwnerEmpty = StringUtils.isEmpty(phoneOwner); - executeRaw( - PersonContactDetail.class, - insertQuery, - DataHelper.createUuid(), - 0, - personId, - (phoneOwnerEmpty ? 1 : 0), - PersonContactDetailType.PHONE.name(), - null, - phone, - null, - (phoneOwnerEmpty ? 0 : 1), - null, - (phoneOwnerEmpty ? null : phoneOwner), - 0); - } + public static ContactDao getContactDao() { + return (ContactDao) getAdoDao(Contact.class); + } - if (StringUtils.isNotEmpty(emailAddress)) { - executeRaw( - PersonContactDetail.class, - insertQuery, - DataHelper.createUuid(), - 0, - personId, - 1, - PersonContactDetailType.EMAIL.name(), - null, - emailAddress, - null, - 0, - null, - null, - 0); - } + public static VisitDao getVisitDao() { + return (VisitDao) getAdoDao(Visit.class); + } - if (StringUtils.isNotEmpty(generalPractitionerDetails)) { - executeRaw( - PersonContactDetail.class, - insertQuery, - DataHelper.createUuid(), - 0, - personId, - 0, - PersonContactDetailType.OTHER.name(), - null, - null, - generalPractitionerDetails, - 1, - "General practitioner", - generalPractitionerDetails, - 0); - } - } + public static EventDao getEventDao() { + return (EventDao) getAdoDao(Event.class); } - private void migrateEmbeddedEpiDataToExposures() throws SQLException { - GenericRawResults newBurials = getDao(EpiData.class).queryRaw( - "SELECT epiData_id, burialAddress_id, burialPersonName, burialRelation," - + "burialTouching, burialIll, burialDateFrom, burialDateTo FROM epidataburial WHERE changeDate = 0 AND snapshot = 0;", - new DataType[] { - DataType.BIG_INTEGER, - DataType.BIG_INTEGER, - DataType.STRING, - DataType.STRING, - DataType.ENUM_STRING, - DataType.ENUM_STRING, - DataType.DATE_LONG, - DataType.DATE_LONG }); + public static EbsDao getEbsDao() { + return (EbsDao) getAdoDao(Ebs.class); + } - for (Object[] burial : newBurials) { - doNullCheckOnString(burial, 2); - doNullCheckOnString(burial, 3); - formatRawResultDate(burial, 6); - formatRawResultDate(burial, 7); + public static TriagingDao getTriagingDao() { + return (TriagingDao) getAdoDao(Triaging.class); + } - String burialQuery = "INSERT INTO exposures" + "(" - + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, deceasedPersonName, deceasedPersonRelation, " - + " physicalContactWithBody, deceasedPersonIll, startDate, endDate, exposureType, pseudonymized, modified, snapshot" + ")" - + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + public static SignalVerificationDao getSignalVerificationDao() { + return (SignalVerificationDao) getAdoDao(SignalVerification.class); + } - executeRaw( - Exposure.class, - burialQuery, - DataHelper.createUuid(), - 0, - burial[0], - burial[1], - burial[2], - burial[3], - burial[4], - burial[5], - burial[6], - burial[7], - "BURIAL", - 0, - 0, - 0); - } + public static RiskAssessmentDao getRiskAssessmentDao() { + return (RiskAssessmentDao) getAdoDao(RiskAssessment.class); + } - GenericRawResults newGatherings = getDao(EpiData.class).queryRaw( - "SELECT epiData_id, gatheringAddress_id, gatheringDate, description FROM epidatagathering WHERE changeDate = 0 AND snapshot = 0;", - new DataType[] { - DataType.BIG_INTEGER, - DataType.BIG_INTEGER, - DataType.DATE_LONG, - DataType.STRING }); + public static EbsAlertDao getEbsAlertDao() { + return (EbsAlertDao) getAdoDao(EbsAlert.class); + } - for (Object[] gathering : newGatherings) { - doNullCheckOnString(gathering, 3); - formatRawResultDate(gathering, 2); + public static EventParticipantDao getEventParticipantDao() { + return (EventParticipantDao) getAdoDao(EventParticipant.class); + } - String gatheringQuery = - "INSERT INTO exposures" + "(uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, startDate, endDate, " - + " description, exposureType, pseudonymized, modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " - + generateDateNowSQL() + ", ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + public static SampleDao getSampleDao() { + return (SampleDao) getAdoDao(Sample.class); + } - executeRaw( - Exposure.class, - gatheringQuery, - DataHelper.createUuid(), - 0, - gathering[0], - gathering[1], - gathering[2], - gathering[2], - gathering[3], - "GATHERING", - 0, - 0, - 0); - } + public static PathogenTestDao getSampleTestDao() { + return (PathogenTestDao) getAdoDao(PathogenTest.class); + } - GenericRawResults newTravels = getDao(EpiData.class).queryRaw( - "SELECT epiData_id, travelDateFrom, travelDateTo, travelType, travelDestination FROM epidatatravel WHERE changeDate = 0 AND snapshot = 0;", - new DataType[] { - DataType.BIG_INTEGER, - DataType.DATE_LONG, - DataType.DATE_LONG, - DataType.ENUM_STRING, - DataType.STRING }); + public static AdditionalTestDao getAdditionalTestDao() { + return (AdditionalTestDao) getAdoDao(AdditionalTest.class); + } - for (Object[] travel : newTravels) { - formatRawResultDate(travel, 1); - formatRawResultDate(travel, 2); + public static HospitalizationDao getHospitalizationDao() { + return (HospitalizationDao) getAdoDao(Hospitalization.class); + } - String detailsString = Stream.of((String) travel[3] != null ? ((String) travel[3]).replace("_", " ") : null, (String) travel[4]) - .filter(Objects::nonNull) - .collect(Collectors.joining(", ")); + public static PreviousHospitalizationDao getPreviousHospitalizationDao() { + return (PreviousHospitalizationDao) getAdoDao(PreviousHospitalization.class); + } - String locationQuery = - "INSERT INTO location" + "(uuid, changeDate, localChangeDate, creationDate, details, pseudonymized, modified, snapshot)" - + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() + ", ?, ?, ?, ?)"; + public static EpiDataDao getEpiDataDao() { + return (EpiDataDao) getAdoDao(EpiData.class); + } - executeRaw(Location.class, locationQuery, DataHelper.createUuid(), 0, detailsString, 0, 0, 0); + public static ExposureDao getExposureDao() { + return (ExposureDao) getAdoDao(Exposure.class); + } - Long locationId = getDao(Location.class).queryRawValue("SELECT MAX(id) FROM location;"); + public static ActivityAsCaseDao getActivityAsCaseDao() { + return (ActivityAsCaseDao) getAdoDao(ActivityAsCase.class); + } - String travelQuery = "INSERT INTO exposures" + "(" - + " uuid, changeDate, localChangeDate, creationDate, epiData_id, location_id, startDate, endDate, exposureType, " - + " pseudonymized, modified, snapshot" + ")" + "VALUES (?, ?, " + generateDateNowSQL() + ", " + generateDateNowSQL() - + ", ?, ?, ?, ?, ?, ?, ?, ?)"; + public static WeeklyReportDao getWeeklyReportDao() { + return (WeeklyReportDao) getAdoDao(WeeklyReport.class); + } - executeRaw(Exposure.class, travelQuery, DataHelper.createUuid(), 0, travel[0], locationId, travel[1], travel[2], "TRAVEL", 0, 0, 0); - } + public static WeeklyReportEntryDao getWeeklyReportEntryDao() { + return (WeeklyReportEntryDao) getAdoDao(WeeklyReportEntry.class); } - private void upgradeFromUnupgradableVersion(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion) { - try { - Log.i(DatabaseHelper.class.getName(), "onUpgrade"); - TableUtils.dropTable(connectionSource, Case.class, true); - TableUtils.dropTable(connectionSource, Immunization.class, true); - TableUtils.dropTable(connectionSource, Vaccination.class, true); - TableUtils.dropTable(connectionSource, Prescription.class, true); - TableUtils.dropTable(connectionSource, Treatment.class, true); - TableUtils.dropTable(connectionSource, Therapy.class, true); - TableUtils.dropTable(connectionSource, ClinicalVisit.class, true); - TableUtils.dropTable(connectionSource, ClinicalCourse.class, true); - TableUtils.dropTable(connectionSource, HealthConditions.class, true); - TableUtils.dropTable(connectionSource, MaternalHistory.class, true); - TableUtils.dropTable(connectionSource, PortHealthInfo.class, true); - TableUtils.dropTable(connectionSource, Person.class, true); - TableUtils.dropTable(connectionSource, PersonContactDetail.class, true); - TableUtils.dropTable(connectionSource, Location.class, true); - TableUtils.dropTable(connectionSource, Continent.class, true); - TableUtils.dropTable(connectionSource, Subcontinent.class, true); - TableUtils.dropTable(connectionSource, Country.class, true); - TableUtils.dropTable(connectionSource, Area.class, true); - TableUtils.dropTable(connectionSource, Region.class, true); - TableUtils.dropTable(connectionSource, District.class, true); - TableUtils.dropTable(connectionSource, Community.class, true); - TableUtils.dropTable(connectionSource, Facility.class, true); - TableUtils.dropTable(connectionSource, PointOfEntry.class, true); - TableUtils.dropTable(connectionSource, User.class, true); - TableUtils.dropTable(connectionSource, Symptoms.class, true); - TableUtils.dropTable(connectionSource, Task.class, true); - TableUtils.dropTable(connectionSource, Contact.class, true); - TableUtils.dropTable(connectionSource, Visit.class, true); - TableUtils.dropTable(connectionSource, Event.class, true); - TableUtils.dropTable(connectionSource, Ebs.class, true); - TableUtils.dropTable(connectionSource, Triaging.class, true); - TableUtils.dropTable(connectionSource, SignalVerification.class, true); - TableUtils.dropTable(connectionSource, RiskAssessment.class, true); - TableUtils.dropTable(connectionSource, EbsAlert.class, true); - TableUtils.dropTable(connectionSource, Sample.class, true); - TableUtils.dropTable(connectionSource, PathogenTest.class, true); - TableUtils.dropTable(connectionSource, AdditionalTest.class, true); - TableUtils.dropTable(connectionSource, EventParticipant.class, true); - TableUtils.dropTable(connectionSource, Hospitalization.class, true); - TableUtils.dropTable(connectionSource, PreviousHospitalization.class, true); - TableUtils.dropTable(connectionSource, EpiData.class, true); - TableUtils.dropTable(connectionSource, Exposure.class, true); - TableUtils.dropTable(connectionSource, ActivityAsCase.class, true); - TableUtils.dropTable(connectionSource, SyncLog.class, true); - TableUtils.dropTable(connectionSource, WeeklyReport.class, true); - TableUtils.dropTable(connectionSource, WeeklyReportEntry.class, true); - TableUtils.dropTable(connectionSource, AggregateReport.class, true); - TableUtils.dropTable(connectionSource, Outbreak.class, true); - TableUtils.dropTable(connectionSource, DiseaseClassificationCriteria.class, true); - TableUtils.dropTable(connectionSource, DiseaseConfiguration.class, true); - TableUtils.dropTable(connectionSource, CustomizableEnumValue.class, true); - TableUtils.dropTable(connectionSource, FeatureConfiguration.class, true); - TableUtils.dropTable(connectionSource, Campaign.class, true); - TableUtils.dropTable(connectionSource, CampaignFormMeta.class, true); - TableUtils.dropTable(connectionSource, CampaignFormData.class, true); - TableUtils.dropTable(connectionSource, LbdsSync.class, true); - TableUtils.dropTable(connectionSource, Environment.class, true); - TableUtils.dropTable(connectionSource, FormField.class, true); - TableUtils.dropTable(connectionSource, FormBuilder.class, true); - TableUtils.dropTable(connectionSource, FormBuilderFormField.class, true); + public static OutbreakDao getOutbreakDao() { + return (OutbreakDao) getAdoDao(Outbreak.class); + } - if (oldVersion < 30) { - TableUtils.dropTable(connectionSource, Config.class, true); - } - // after we drop the old databases, we build the new ones - onCreate(db, connectionSource); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); - throw new RuntimeException(e); - } + public static DiseaseClassificationCriteriaDao getDiseaseClassificationCriteriaDao() { + return (DiseaseClassificationCriteriaDao) getAdoDao(DiseaseClassificationCriteria.class); } - public AbstractAdoDao getAdoDaoInner(Class type) { + public static AggregateReportDao getAggregateReportDao() { + return (AggregateReportDao) getAdoDao(AggregateReport.class); + } - if (!adoDaos.containsKey(type)) { + public static CampaignDao getCampaignDao() { + return (CampaignDao) getAdoDao(Campaign.class); + } - // build dao - AbstractAdoDao dao; - Dao innerDao; + public static CampaignFormMetaDao getCampaignFormMetaDao() { + return (CampaignFormMetaDao) getAdoDao(CampaignFormMeta.class); + } - try { - innerDao = super.getDao(type); + public static CampaignFormDataDao getCampaignFormDataDao() { + return (CampaignFormDataDao) getAdoDao(CampaignFormData.class); + } - if (type.equals(Case.class)) { - dao = (AbstractAdoDao) new CaseDao((Dao) innerDao); - } else if (type.equals(Immunization.class)) { - dao = (AbstractAdoDao) new ImmunizationDao((Dao) innerDao); - } else if (type.equals(Vaccination.class)) { - dao = (AbstractAdoDao) new VaccinationDao((Dao) innerDao); - } else if (type.equals(Therapy.class)) { - dao = (AbstractAdoDao) new TherapyDao((Dao) innerDao); - } else if (type.equals(Prescription.class)) { - dao = (AbstractAdoDao) new PrescriptionDao((Dao) innerDao); - } else if (type.equals(Treatment.class)) { - dao = (AbstractAdoDao) new TreatmentDao((Dao) innerDao); - } else if (type.equals(Person.class)) { - dao = (AbstractAdoDao) new PersonDao((Dao) innerDao); - } else if (type.equals(PersonContactDetail.class)) { - dao = (AbstractAdoDao) new PersonContactDetailDao((Dao) innerDao); - } else if (type.equals(Location.class)) { - dao = (AbstractAdoDao) new LocationDao((Dao) innerDao); - } else if (type.equals(PointOfEntry.class)) { - dao = (AbstractAdoDao) new PointOfEntryDao((Dao) innerDao); - } else if (type.equals(Facility.class)) { - dao = (AbstractAdoDao) new FacilityDao((Dao) innerDao); - } else if (type.equals(Continent.class)) { - dao = (AbstractAdoDao) new ContinentDao((Dao) innerDao); - } else if (type.equals(Subcontinent.class)) { - dao = (AbstractAdoDao) new SubcontinentDao((Dao) innerDao); - } else if (type.equals(Country.class)) { - dao = (AbstractAdoDao) new CountryDao((Dao) innerDao); - } else if (type.equals(Area.class)) { - dao = (AbstractAdoDao) new AreaDao((Dao) innerDao); - } else if (type.equals(Region.class)) { - dao = (AbstractAdoDao) new RegionDao((Dao) innerDao); - } else if (type.equals(District.class)) { - dao = (AbstractAdoDao) new DistrictDao((Dao) innerDao); - } else if (type.equals(Community.class)) { - dao = (AbstractAdoDao) new CommunityDao((Dao) innerDao); - } else if (type.equals(User.class)) { - dao = (AbstractAdoDao) new UserDao((Dao) innerDao, super.getDao(UserUserRole.class)); - } else if (type.equals(UserRole.class)) { - dao = (AbstractAdoDao) new UserRoleDao((Dao) innerDao); - } else if (type.equals(DiseaseConfiguration.class)) { - dao = (AbstractAdoDao) new DiseaseConfigurationDao((Dao) innerDao); - } else if (type.equals(CustomizableEnumValue.class)) { - dao = (AbstractAdoDao) new CustomizableEnumValueDao((Dao) innerDao); - } else if (type.equals(FeatureConfiguration.class)) { - dao = (AbstractAdoDao) new FeatureConfigurationDao((Dao) innerDao); - } else if (type.equals(Symptoms.class)) { - dao = (AbstractAdoDao) new SymptomsDao((Dao) innerDao); - } else if (type.equals(HealthConditions.class)) { - dao = (AbstractAdoDao) new HealthConditionsDao((Dao) innerDao); - } else if (type.equals(ClinicalCourse.class)) { - dao = (AbstractAdoDao) new ClinicalCourseDao((Dao) innerDao); - } else if (type.equals(ClinicalVisit.class)) { - dao = (AbstractAdoDao) new ClinicalVisitDao((Dao) innerDao); - } else if (type.equals(MaternalHistory.class)) { - dao = (AbstractAdoDao) new MaternalHistoryDao((Dao) innerDao); - } else if (type.equals(PortHealthInfo.class)) { - dao = (AbstractAdoDao) new PortHealthInfoDao((Dao) innerDao); - } else if (type.equals(Task.class)) { - dao = (AbstractAdoDao) new TaskDao((Dao) innerDao); - } else if (type.equals(Contact.class)) { - dao = (AbstractAdoDao) new ContactDao((Dao) innerDao); - } else if (type.equals(Visit.class)) { - dao = (AbstractAdoDao) new VisitDao((Dao) innerDao); - } else if (type.equals(Event.class)) { - dao = (AbstractAdoDao) new EventDao((Dao) innerDao); - } else if (type.equals(Ebs.class)) { - dao = (AbstractAdoDao) new EbsDao((Dao) innerDao); - } else if (type.equals(Triaging.class)) { - dao = (AbstractAdoDao) new TriagingDao((Dao) innerDao); - } else if (type.equals(SignalVerification.class)) { - dao = (AbstractAdoDao) new SignalVerificationDao((Dao) innerDao); - } else if (type.equals(RiskAssessment.class)) { - dao = (AbstractAdoDao) new RiskAssessmentDao((Dao) innerDao); - } else if (type.equals(EbsAlert.class)) { - dao = (AbstractAdoDao) new EbsAlertDao((Dao) innerDao); - } else if (type.equals(EventParticipant.class)) { - dao = (AbstractAdoDao) new EventParticipantDao((Dao) innerDao); - } else if (type.equals(Sample.class)) { - dao = (AbstractAdoDao) new SampleDao((Dao) innerDao); - } else if (type.equals(PathogenTest.class)) { - dao = (AbstractAdoDao) new PathogenTestDao((Dao) innerDao); - } else if (type.equals(AdditionalTest.class)) { - dao = (AbstractAdoDao) new AdditionalTestDao((Dao) innerDao); - } else if (type.equals(Hospitalization.class)) { - dao = (AbstractAdoDao) new HospitalizationDao((Dao) innerDao); - } else if (type.equals(PreviousHospitalization.class)) { - dao = (AbstractAdoDao) new PreviousHospitalizationDao((Dao) innerDao); - } else if (type.equals(EpiData.class)) { - dao = (AbstractAdoDao) new EpiDataDao((Dao) innerDao); - } else if (type.equals(Exposure.class)) { - dao = (AbstractAdoDao) new ExposureDao((Dao) innerDao); - } else if (type.equals(ActivityAsCase.class)) { - dao = (AbstractAdoDao) new ActivityAsCaseDao((Dao) innerDao); - } else if (type.equals(WeeklyReport.class)) { - dao = (AbstractAdoDao) new WeeklyReportDao((Dao) innerDao); - } else if (type.equals(WeeklyReportEntry.class)) { - dao = (AbstractAdoDao) new WeeklyReportEntryDao((Dao) innerDao); - } else if (type.equals(AggregateReport.class)) { - dao = (AbstractAdoDao) new AggregateReportDao((Dao) innerDao); - } else if (type.equals(Outbreak.class)) { - dao = (AbstractAdoDao) new OutbreakDao((Dao) innerDao); - } else if (type.equals(DiseaseClassificationCriteria.class)) { - dao = (AbstractAdoDao) new DiseaseClassificationCriteriaDao((Dao) innerDao); - } else if (type.equals(SormasToSormasOriginInfo.class)) { - dao = (AbstractAdoDao) new SormasToSormasOriginInfoDao((Dao) innerDao); - } else if (type.equals(Campaign.class)) { - dao = (AbstractAdoDao) new CampaignDao((Dao) innerDao); - } else if (type.equals(CampaignFormMeta.class)) { - dao = (AbstractAdoDao) new CampaignFormMetaDao((Dao) innerDao); - } else if (type.equals(CampaignFormData.class)) { - dao = (AbstractAdoDao) new CampaignFormDataDao((Dao) innerDao); -// } else if (type.equals(AuditLogEntry.class)) { -// dao = (AbstractAdoDao) new AuditLogEntryDao((Dao) innerDao); -// } -// // TODO [vaccination info] integrate vaccination info -// // else if (type.equals(VaccinationInfo.class)) { -// // dao = (AbstractAdoDao) new VaccinationInfoDao((Dao) innerDao); - } else if (type.equals(Environment.class)) { - dao = (AbstractAdoDao) new EnvironmentDao((Dao) innerDao); - } else if (type.equals(FormField.class)) { - dao = (AbstractAdoDao) new FormFieldDao((Dao) innerDao); - } else if (type.equals(FormBuilder.class)) { - dao = (AbstractAdoDao) new FormBuilderDao((Dao) innerDao, super.getDao(FormBuilderFormField.class)); - } else { - throw new UnsupportedOperationException(type.toString()); - } + public static AuditLogEntryDao getAuditLogEntryDao() { + return (AuditLogEntryDao) getAdoDao(AuditLogEntry.class); + } - adoDaos.put(type, dao); - } catch (SQLException e) { - Log.e(DatabaseHelper.class.getName(), "Can't build dao", e); - throw new RuntimeException(e); - } - } - return (AbstractAdoDao) adoDaos.get(type); +// TODO [vaccination info] integrate vaccination info +// public static VaccinationInfoDao getVaccinationInfoDao() { +// return (VaccinationInfoDao) getAdoDao(VaccinationInfo.class); +// } + public static EnvironmentDao getEnvironmentDao() { + return (EnvironmentDao) getAdoDao(Environment.class); } /** @@ -4547,4 +4820,16 @@ public void close() { adoDaos.clear(); syncLogDao = null; } + + public static Context getContext() { + return instance.context; + } + + public static String getString(int stringResourceId) { + if (instance.context == null) { + return null; + } + + return instance.context.getResources().getString(stringResourceId); + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/disease/DiseaseConfigurationDao.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/disease/DiseaseConfigurationDao.java index bcf46f78c7e..f26a8651731 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/disease/DiseaseConfigurationDao.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/disease/DiseaseConfigurationDao.java @@ -15,22 +15,30 @@ package de.symeda.sormas.app.backend.disease; -import java.sql.SQLException; +import android.util.Log; import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; -import android.util.Log; +import java.sql.SQLException; +import java.util.List; +import java.util.stream.Collectors; import de.symeda.sormas.api.Disease; import de.symeda.sormas.app.backend.common.AbstractAdoDao; +import de.symeda.sormas.app.backend.common.DatabaseHelper; +import de.symeda.sormas.app.backend.facility.Facility; import de.symeda.sormas.app.util.DiseaseConfigurationCache; public class DiseaseConfigurationDao extends AbstractAdoDao { - public DiseaseConfigurationDao(Dao innerDao) { + private Dao diseaseFacilityDao; + + public DiseaseConfigurationDao(Dao innerDao, Dao diseaseFacilityDao) { super(innerDao); + this.diseaseFacilityDao = diseaseFacilityDao; } @Override @@ -55,15 +63,68 @@ public DiseaseConfiguration getDiseaseConfiguration(Disease disease) { } } + public List getDiseaseFacilities(DiseaseConfiguration diseaseConfiguration) { + diseaseConfiguration.setFacilities( + loadDiseaseFacility(diseaseConfiguration.getId()).stream() + .map(diseaseFacility -> DatabaseHelper.getFacilityDao().queryForId(diseaseFacility.getFacility().getId())) + .collect(Collectors.toList())); + + List facilities = diseaseConfiguration.getFacilities(); + return facilities; + } + + private List loadDiseaseFacility(Long diseaseId) { + try { + QueryBuilder builder = diseaseFacilityDao.queryBuilder(); + Where where = builder.where(); + where.eq(DiseaseConfiguration.TABLE_NAME + "_id", diseaseId); + return (List) builder.query(); + } catch (SQLException e) { + Log.e(getTableName(), "Could not perform loadUserRoles"); + throw new RuntimeException(e); + } + } + @Override public void create(DiseaseConfiguration data) throws SQLException { + if (data == null) + return; super.create(data); DiseaseConfigurationCache.reset(); + if (data.getFacilities() != null) { + for (Facility facility : data.getFacilities()) { + int resultRowCount = diseaseFacilityDao.create(new DiseaseFacility(data, facility)); + if (resultRowCount < 1) + throw new SQLException( + "Database entry was not created - go back and try again.\n" + "Type: " + DiseaseFacility.class.getSimpleName() + ", Facility-UUID: " + + data.getUuid()); + } + } + } @Override protected void update(DiseaseConfiguration data) throws SQLException { + if (data == null) + return; + super.update(data); DiseaseConfigurationCache.reset(); + + // 1. Delete existing DiseaseFacility + DeleteBuilder diseaseFacilityLongDeleteBuilder = diseaseFacilityDao.deleteBuilder(); + diseaseFacilityLongDeleteBuilder.where().eq(DiseaseFacility.DISEASE_CONFIGURATION + "_id", data); + diseaseFacilityLongDeleteBuilder.delete(); + + // 2. Create new DiseaseFacility + if (data.getFacilities() != null) { + for (Facility facility : data.getFacilities()) { + int resultRowCount = diseaseFacilityDao.create(new DiseaseFacility(data, facility)); + if (resultRowCount < 1) + throw new SQLException( + "Database entry was not created - go back and try again.\n" + "Type: " + DiseaseFacility.class.getSimpleName() + ", Facility-UUID: " + + data.getUuid()); + } + } } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/EbsDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/EbsDtoHelper.java index 3fc3ed77b8a..a5a1598d64d 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/EbsDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/EbsDtoHelper.java @@ -2,15 +2,18 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.EbsDto; import de.symeda.sormas.api.ebs.EbsReferenceDto; +import de.symeda.sormas.api.ebs.SignalVerificationDto; +import de.symeda.sormas.api.ebs.TriagingDto; import de.symeda.sormas.app.backend.common.AdoDtoHelper; import de.symeda.sormas.app.backend.common.DatabaseHelper; import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerification; import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerificationDtoHelper; import de.symeda.sormas.app.backend.ebs.triaging.Triaging; import de.symeda.sormas.app.backend.ebs.triaging.TriagingDtoHelper; +import de.symeda.sormas.app.backend.event.Event; import de.symeda.sormas.app.backend.location.Location; import de.symeda.sormas.app.backend.location.LocationDtoHelper; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfoDtoHelper; @@ -19,121 +22,122 @@ import retrofit2.Call; public class EbsDtoHelper extends AdoDtoHelper { - - private LocationDtoHelper locationHelper = new LocationDtoHelper(); - - private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - private TriagingDtoHelper triagingDtoHelper = new TriagingDtoHelper(); - - private SignalVerificationDtoHelper signalVerificationDtoHelper = new SignalVerificationDtoHelper(); - - public static EbsReferenceDto toReferenceDto(Ebs ado) { - if (ado == null) { - return null; - } - EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); - - return dto; - } - - @Override - protected Class getAdoClass() { - return Ebs.class; - } - - @Override - protected Class getDtoClass() { - return EbsDto.class; - } - - @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { - return RetroProvider.getEbsFacade().pullAllSince(since, size, lastSynchronizedUuid); - } - - @Override - protected Call> pullByUuids(List uuids) throws NoConnectionException { - return RetroProvider.getEbsFacade().pullByUuids(uuids); - } - - @Override - protected Call> pushAll(List ebsDtos) throws NoConnectionException { - return RetroProvider.getEbsFacade().pushAll(ebsDtos); - } - - @Override - public void fillInnerFromDto(Ebs target, EbsDto source) { - target.setInformantName(source.getInformantName()); - target.setInformantTel(source.getInformantTel()); - target.setEndDate(source.getEndDate()); - target.setReportDateTime(source.getReportDateTime()); - target.setCategoryOfInformant(source.getCategoryOfInformant()); - target.setEbsLatLon(source.getEbsLatLon()); - target.setAutomaticScanningType(source.getAutomaticScanningType()); - target.setManualScanningType(source.getManualScanningType()); - target.setScanningType(source.getScanningType()); - target.setDescriptionOccurrence(source.getDescriptionOccurrence()); - target.setOther(source.getOther()); - target.setPersonDesignation(source.getPersonDesignation()); - target.setPersonPhone(source.getPersonPhone()); - target.setPersonRegistering(source.getPersonRegistering()); - target.setSourceName(source.getSourceName()); - target.setSourceInformation(source.getSourceInformation()); - target.setDateOnset(source.getDateOnset()); - target.setEbsLongitude(source.getEbsLongitude()); - target.setEbsLatitude(source.getEbsLongitude()); - target.setOtherInformant(source.getOtherInformant()); - target.setEbsLocation(locationHelper.fillOrCreateFromDto(target.getEbsLocation(), source.getEbsLocation())); - target.setTriaging(triagingDtoHelper.fillOrCreateFromDto(target.getTriaging(), source.getTriaging())); - target.setSignalVerification(signalVerificationDtoHelper.fillOrCreateFromDto(target.getSignalVerification(), source.getSignalVerification())); - } - - @Override - public void fillInnerFromAdo(EbsDto target, Ebs source) { - target.setInformantName(source.getInformantName()); - target.setInformantTel(source.getInformantTel()); - target.setEndDate(source.getEndDate()); - target.setReportDateTime(source.getReportDateTime()); - target.setCategoryOfInformant(source.getCategoryOfInformant()); - target.setEbsLatLon(source.getEbsLatLon()); - target.setAutomaticScanningType(source.getAutomaticScanningType()); - target.setManualScanningType(source.getManualScanningType()); - target.setScanningType(source.getScanningType()); - target.setDescriptionOccurrence(source.getDescriptionOccurrence()); - target.setOther(source.getOther()); - target.setPersonDesignation(source.getPersonDesignation()); - target.setPersonPhone(source.getPersonPhone()); - target.setPersonRegistering(source.getPersonRegistering()); - target.setSourceName(source.getSourceName()); - target.setSourceInformation(source.getSourceInformation()); - target.setDateOnset(source.getDateOnset()); - target.setEbsLongitude(source.getEbsLongitude()); - target.setEbsLatitude(source.getEbsLongitude()); - if (source.getEbsLocation() != null) { - Location location = DatabaseHelper.getLocationDao().queryForId(source.getEbsLocation().getId()); - target.setEbsLocation(locationHelper.adoToDto(location)); - } else { - target.setEbsLocation(null); - } - target.setOtherInformant(source.getOtherInformant()); - if (source.getTriaging() != null) { - Triaging triaging = DatabaseHelper.getTriagingDao().queryForId(source.getTriaging().getId()); - target.setTriaging(triagingDtoHelper.adoToDto(triaging)); - } else { - target.setTriaging(null); - } - if (source.getSignalVerification() != null) { - SignalVerification signalVerification = DatabaseHelper.getSignalVerificationDao().queryForId(source.getSignalVerification().getId()); - target.setSignalVerification(signalVerificationDtoHelper.adoToDto(signalVerification)); - } else { - target.setSignalVerification(null); - } - - } - - @Override - protected long getApproximateJsonSizeInBytes() { - return EbsDto.APPROXIMATE_JSON_SIZE_IN_BYTES; - } + private LocationDtoHelper locationHelper = new LocationDtoHelper(); + + private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); + private TriagingDtoHelper triagingDtoHelper = new TriagingDtoHelper(); + + private SignalVerificationDtoHelper signalVerificationDtoHelper = new SignalVerificationDtoHelper(); + + + + @Override + protected Class getAdoClass() { + return Ebs.class; + } + + @Override + protected Class getDtoClass() { + return EbsDto.class; + } + + @Override + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + return RetroProvider.getEbsFacade().pullAllSince(since, size, lastSynchronizedUuid); + } + + @Override + protected Call> pullByUuids(List uuids) throws NoConnectionException { + return RetroProvider.getEbsFacade().pullByUuids(uuids); + } + + @Override + protected Call> pushAll(List ebsDtos) throws NoConnectionException { + return RetroProvider.getEbsFacade().pushAll(ebsDtos); + } + + @Override + public void fillInnerFromDto(Ebs target, EbsDto source) { + target.setInformantName(source.getInformantName()); + target.setInformantTel(source.getInformantTel()); + target.setEndDate(source.getEndDate()); + target.setReportDateTime(source.getReportDateTime()); + target.setCategoryOfInformant(source.getCategoryOfInformant()); + target.setEbsLatLon(source.getEbsLatLon()); + target.setAutomaticScanningType(source.getAutomaticScanningType()); + target.setManualScanningType(source.getManualScanningType()); + target.setScanningType(source.getScanningType()); + target.setDescriptionOccurrence(source.getDescriptionOccurrence()); + target.setOther(source.getOther()); + target.setPersonDesignation(source.getPersonDesignation()); + target.setPersonPhone(source.getPersonPhone()); + target.setPersonRegistering(source.getPersonRegistering()); + target.setSourceName(source.getSourceName()); + target.setSourceInformation(source.getSourceInformation()); + target.setDateOnset(source.getDateOnset()); + target.setEbsLongitude(source.getEbsLongitude()); + target.setEbsLatitude(source.getEbsLongitude()); + target.setOtherInformant(source.getOtherInformant()); + target.setEbsLocation(locationHelper.fillOrCreateFromDto(target.getEbsLocation(), source.getEbsLocation())); + target.setTriaging(triagingDtoHelper.fillOrCreateFromDto(target.getTriaging(),source.getTriaging())); + target.setSignalVerification(signalVerificationDtoHelper.fillOrCreateFromDto(target.getSignalVerification(),source.getSignalVerification())); + } + + @Override + public void fillInnerFromAdo(EbsDto target, Ebs source) { + target.setInformantName(source.getInformantName()); + target.setInformantTel(source.getInformantTel()); + target.setEndDate(source.getEndDate()); + target.setReportDateTime(source.getReportDateTime()); + target.setCategoryOfInformant(source.getCategoryOfInformant()); + target.setEbsLatLon(source.getEbsLatLon()); + target.setAutomaticScanningType(source.getAutomaticScanningType()); + target.setManualScanningType(source.getManualScanningType()); + target.setScanningType(source.getScanningType()); + target.setDescriptionOccurrence(source.getDescriptionOccurrence()); + target.setOther(source.getOther()); + target.setPersonDesignation(source.getPersonDesignation()); + target.setPersonPhone(source.getPersonPhone()); + target.setPersonRegistering(source.getPersonRegistering()); + target.setSourceName(source.getSourceName()); + target.setSourceInformation(source.getSourceInformation()); + target.setDateOnset(source.getDateOnset()); + target.setEbsLongitude(source.getEbsLongitude()); + target.setEbsLatitude(source.getEbsLongitude()); + if (source.getEbsLocation() != null) { + Location location = DatabaseHelper.getLocationDao().queryForId(source.getEbsLocation().getId()); + target.setEbsLocation(locationHelper.adoToDto(location)); + } else { + target.setEbsLocation(null); + } + target.setOtherInformant(source.getOtherInformant()); + if (source.getTriaging() != null) { + Triaging triaging = DatabaseHelper.getTriagingDao().queryForId(source.getTriaging().getId()); + target.setTriaging(triagingDtoHelper.adoToDto(triaging)); + } else { + target.setTriaging(null); + } + if (source.getSignalVerification() != null) { + SignalVerification signalVerification = DatabaseHelper.getSignalVerificationDao().queryForId(source.getSignalVerification().getId()); + target.setSignalVerification(signalVerificationDtoHelper.adoToDto(signalVerification)); + } else { + target.setSignalVerification(null); + } + + } + + @Override + protected long getApproximateJsonSizeInBytes() { + return EbsDto.APPROXIMATE_JSON_SIZE_IN_BYTES; + } + + public static EbsReferenceDto toReferenceDto(Ebs ado) { + if (ado == null) { + return null; + } + EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); + + return dto; + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/ebsAlert/EbsAlertDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/ebsAlert/EbsAlertDtoHelper.java index f0196d3857b..5b1650caaed 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/ebsAlert/EbsAlertDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/ebsAlert/EbsAlertDtoHelper.java @@ -4,9 +4,9 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; -import de.symeda.sormas.api.ebs.EbsAlertDto; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.EbsReferenceDto; +import de.symeda.sormas.api.ebs.EbsAlertDto; import de.symeda.sormas.app.backend.common.AdoDtoHelper; import de.symeda.sormas.app.backend.common.DatabaseHelper; import de.symeda.sormas.app.backend.ebs.Ebs; @@ -17,77 +17,76 @@ import retrofit2.Call; public class EbsAlertDtoHelper extends AdoDtoHelper { - - private LocationDtoHelper locationHelper; - - private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - - public EbsAlertDtoHelper() { - locationHelper = new LocationDtoHelper(); - } - - public static EbsReferenceDto toReferenceDto(Ebs ado) { - if (ado == null) { - return null; - } - EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); - - return dto; - } - - @Override - protected Class getAdoClass() { - return EbsAlert.class; - } - - @Override - protected Class getDtoClass() { - return EbsAlertDto.class; - } - - @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { - return RetroProvider.getEbsAlertFacade().pullAllSince(since, 500, NO_LAST_SYNCED_UUID); - } - - @Override - protected Call> pullByUuids(List uuids) throws NoConnectionException { - return RetroProvider.getEbsAlertFacade().pullByUuids(uuids); - } - - @Override - protected Call> pushAll(List ebsAlertDtos) throws NoConnectionException { - return RetroProvider.getEbsAlertFacade().pushAll(ebsAlertDtos); - } - - @Override - public void fillInnerFromDto(EbsAlert target, EbsAlertDto source) { - target.setResponseDate(source.getResponseDate()); - target.setResponseStatus(source.getResponseStatus()); - target.setAlertIssued(source.getAlertIssued()); - target.setDetailsAlertUsed(source.getDetailsAlertUsed()); - target.setDetailsResponseActivities(source.getDetailsResponseActivities()); - target.setDetailsGiven(source.getDetailsGiven()); - target.setActionInitiated(source.getActionInitiated()); - target.setAlertDate(source.getAlertDate()); - target.setEbs(DatabaseHelper.getEbsDao().getByReferenceDto(source.getEbs())); - } - - @Override - public void fillInnerFromAdo(EbsAlertDto target, EbsAlert source) { - target.setActionInitiated(source.getActionInitiated()); - target.setResponseDate(source.getResponseDate()); - target.setResponseStatus(source.getResponseStatus()); - target.setAlertIssued(source.getAlertIssued()); - target.setDetailsAlertUsed(source.getDetailsAlertUsed()); - target.setDetailsResponseActivities(source.getDetailsResponseActivities()); - target.setDetailsGiven(source.getDetailsGiven()); - target.setAlertDate(source.getAlertDate()); - target.setEbs(EbsAlertDtoHelper.toReferenceDto(source.getEbs())); - } - - @Override - protected long getApproximateJsonSizeInBytes() { - return EbsAlertDto.APPROXIMATE_JSON_SIZE_IN_BYTES; - } + private LocationDtoHelper locationHelper; + + private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); + + public EbsAlertDtoHelper() { + locationHelper = new LocationDtoHelper(); + } + + @Override + protected Class getAdoClass() { + return EbsAlert.class; + } + + @Override + protected Class getDtoClass() { + return EbsAlertDto.class; + } + + @Override + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + return RetroProvider.getEbsAlertFacade().pullAllSince(since, 500, NO_LAST_SYNCED_UUID); + } + + @Override + protected Call> pullByUuids(List uuids) throws NoConnectionException { + return RetroProvider.getEbsAlertFacade().pullByUuids(uuids); + } + + @Override + protected Call> pushAll(List ebsAlertDtos) throws NoConnectionException { + return RetroProvider.getEbsAlertFacade().pushAll(ebsAlertDtos); + } + + @Override + public void fillInnerFromDto(EbsAlert target, EbsAlertDto source) { + target.setResponseDate(source.getResponseDate()); + target.setResponseStatus(source.getResponseStatus()); + target.setAlertIssued(source.getAlertIssued()); + target.setDetailsAlertUsed(source.getDetailsAlertUsed()); + target.setDetailsResponseActivities(source.getDetailsResponseActivities()); + target.setDetailsGiven(source.getDetailsGiven()); + target.setActionInitiated(source.getActionInitiated()); + target.setAlertDate(source.getAlertDate()); + target.setEbs(DatabaseHelper.getEbsDao().getByReferenceDto(source.getEbs())); + } + + @Override + public void fillInnerFromAdo(EbsAlertDto target, EbsAlert source) { + target.setActionInitiated(source.getActionInitiated()); + target.setResponseDate(source.getResponseDate()); + target.setResponseStatus(source.getResponseStatus()); + target.setAlertIssued(source.getAlertIssued()); + target.setDetailsAlertUsed(source.getDetailsAlertUsed()); + target.setDetailsResponseActivities(source.getDetailsResponseActivities()); + target.setDetailsGiven(source.getDetailsGiven()); + target.setAlertDate(source.getAlertDate()); + target.setEbs(EbsAlertDtoHelper.toReferenceDto(source.getEbs())); + } + + @Override + protected long getApproximateJsonSizeInBytes() { + return EbsAlertDto.APPROXIMATE_JSON_SIZE_IN_BYTES; + } + + public static EbsReferenceDto toReferenceDto(Ebs ado) { + if (ado == null) { + return null; + } + EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); + + return dto; + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/riskAssessment/RiskAssessmentDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/riskAssessment/RiskAssessmentDtoHelper.java index 3e08634a4c9..a5395f255aa 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/riskAssessment/RiskAssessmentDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/riskAssessment/RiskAssessmentDtoHelper.java @@ -4,12 +4,13 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.EbsReferenceDto; import de.symeda.sormas.api.ebs.RiskAssessmentDto; import de.symeda.sormas.app.backend.common.AdoDtoHelper; import de.symeda.sormas.app.backend.common.DatabaseHelper; import de.symeda.sormas.app.backend.ebs.Ebs; + import de.symeda.sormas.app.backend.location.LocationDtoHelper; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfoDtoHelper; import de.symeda.sormas.app.rest.NoConnectionException; @@ -17,79 +18,78 @@ import retrofit2.Call; public class RiskAssessmentDtoHelper extends AdoDtoHelper { - - private LocationDtoHelper locationHelper; - - private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - - public RiskAssessmentDtoHelper() { - locationHelper = new LocationDtoHelper(); - } - - public static EbsReferenceDto toReferenceDto(Ebs ado) { - if (ado == null) { - return null; - } - EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); - - return dto; - } - - @Override - protected Class getAdoClass() { - return RiskAssessment.class; - } - - @Override - protected Class getDtoClass() { - return RiskAssessmentDto.class; - } - - @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { - return RetroProvider.getRiskAssessmentFacade().pullAllSince(since, 500, NO_LAST_SYNCED_UUID); - } - - @Override - protected Call> pullByUuids(List uuids) throws NoConnectionException { - return RetroProvider.getRiskAssessmentFacade().pullByUuids(uuids); - } - - @Override - protected Call> pushAll(List riskAssessmentDtos) throws NoConnectionException { - return RetroProvider.getRiskAssessmentFacade().pushAll(riskAssessmentDtos); - } - - @Override - public void fillInnerFromDto(RiskAssessment target, RiskAssessmentDto source) { - target.setMorbidityMortality(source.getMorbidityMortality()); - target.setSpreadProbability(source.getSpreadProbability()); - target.setControlMeasures(source.getControlMeasures()); - target.setAssessmentDate(source.getAssessmentDate()); - target.setAssessmentTime(source.getAssessmentTime()); - target.setRiskAssessment(source.getRiskAssessment()); - target.setControlMeasuresComment(source.getControlMeasuresComment()); - target.setSpreadProbabilityComment(source.getSpreadProbabilityComment()); - target.setMorbidityMortalityComment(source.getMorbidityMortalityComment()); - target.setEbs(DatabaseHelper.getEbsDao().getByReferenceDto(source.getEbs())); - } - - @Override - public void fillInnerFromAdo(RiskAssessmentDto target, RiskAssessment source) { - target.setMorbidityMortality(source.getMorbidityMortality()); - target.setSpreadProbability(source.getSpreadProbability()); - target.setControlMeasures(source.getControlMeasures()); - target.setAssessmentDate(source.getAssessmentDate()); - target.setAssessmentTime(source.getAssessmentTime()); - target.setRiskAssessment(source.getRiskAssessment()); - target.setControlMeasuresComment(source.getControlMeasuresComment()); - target.setSpreadProbabilityComment(source.getSpreadProbabilityComment()); - target.setMorbidityMortalityComment(source.getMorbidityMortalityComment()); - target.setEbs(RiskAssessmentDtoHelper.toReferenceDto(source.getEbs())); - } - - @Override - protected long getApproximateJsonSizeInBytes() { - return RiskAssessmentDto.APPROXIMATE_JSON_SIZE_IN_BYTES; - } + private LocationDtoHelper locationHelper; + + private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); + + public RiskAssessmentDtoHelper() { + locationHelper = new LocationDtoHelper(); + } + + @Override + protected Class getAdoClass() { + return RiskAssessment.class; + } + + @Override + protected Class getDtoClass() { + return RiskAssessmentDto.class; + } + + @Override + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + return RetroProvider.getRiskAssessmentFacade().pullAllSince(since, 500, NO_LAST_SYNCED_UUID); + } + + @Override + protected Call> pullByUuids(List uuids) throws NoConnectionException { + return RetroProvider.getRiskAssessmentFacade().pullByUuids(uuids); + } + + @Override + protected Call> pushAll(List riskAssessmentDtos) throws NoConnectionException { + return RetroProvider.getRiskAssessmentFacade().pushAll(riskAssessmentDtos); + } + + @Override + public void fillInnerFromDto(RiskAssessment target, RiskAssessmentDto source) { + target.setMorbidityMortality(source.getMorbidityMortality()); + target.setSpreadProbability(source.getSpreadProbability()); + target.setControlMeasures(source.getControlMeasures()); + target.setAssessmentDate(source.getAssessmentDate()); + target.setAssessmentTime(source.getAssessmentTime()); + target.setRiskAssessment(source.getRiskAssessment()); + target.setControlMeasuresComment(source.getControlMeasuresComment()); + target.setSpreadProbabilityComment(source.getSpreadProbabilityComment()); + target.setMorbidityMortalityComment(source.getMorbidityMortalityComment()); + target.setEbs(DatabaseHelper.getEbsDao().getByReferenceDto(source.getEbs())); + } + + @Override + public void fillInnerFromAdo(RiskAssessmentDto target, RiskAssessment source) { + target.setMorbidityMortality(source.getMorbidityMortality()); + target.setSpreadProbability(source.getSpreadProbability()); + target.setControlMeasures(source.getControlMeasures()); + target.setAssessmentDate(source.getAssessmentDate()); + target.setAssessmentTime(source.getAssessmentTime()); + target.setRiskAssessment(source.getRiskAssessment()); + target.setControlMeasuresComment(source.getControlMeasuresComment()); + target.setSpreadProbabilityComment(source.getSpreadProbabilityComment()); + target.setMorbidityMortalityComment(source.getMorbidityMortalityComment()); + target.setEbs(RiskAssessmentDtoHelper.toReferenceDto(source.getEbs())); + } + + @Override + protected long getApproximateJsonSizeInBytes() { + return RiskAssessmentDto.APPROXIMATE_JSON_SIZE_IN_BYTES; + } + + public static EbsReferenceDto toReferenceDto(Ebs ado) { + if (ado == null) { + return null; + } + EbsReferenceDto dto = new EbsReferenceDto(ado.getUuid()); + + return dto; + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/signalVerification/SignalVerificationDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/signalVerification/SignalVerificationDtoHelper.java index 860c5ae64b0..ff000ee5fdb 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/signalVerification/SignalVerificationDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/signalVerification/SignalVerificationDtoHelper.java @@ -2,9 +2,11 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.SignalVerificationDto; +import de.symeda.sormas.api.ebs.SignalVerificationReferenceDto; import de.symeda.sormas.app.backend.common.AdoDtoHelper; +import de.symeda.sormas.app.backend.ebs.Ebs; import de.symeda.sormas.app.backend.location.LocationDtoHelper; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfoDtoHelper; import de.symeda.sormas.app.rest.NoConnectionException; @@ -12,71 +14,70 @@ import retrofit2.Call; public class SignalVerificationDtoHelper extends AdoDtoHelper { + private LocationDtoHelper locationHelper; - private LocationDtoHelper locationHelper; + private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); + public SignalVerificationDtoHelper() { + locationHelper = new LocationDtoHelper(); + } - public SignalVerificationDtoHelper() { - locationHelper = new LocationDtoHelper(); - } + @Override + protected Class getAdoClass() { + return SignalVerification.class; + } - @Override - protected Class getAdoClass() { - return SignalVerification.class; - } + @Override + protected Class getDtoClass() { + return SignalVerificationDto.class; + } - @Override - protected Class getDtoClass() { - return SignalVerificationDto.class; - } + @Override + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + return RetroProvider.getSignalVerificationFacade().pullAllSince(since, size, lastSynchronizedUuid); + } - @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { - return RetroProvider.getSignalVerificationFacade().pullAllSince(since, size, lastSynchronizedUuid); - } + @Override + protected Call> pullByUuids(List uuids) throws NoConnectionException { + return RetroProvider.getSignalVerificationFacade().pullByUuids(uuids); + } - @Override - protected Call> pullByUuids(List uuids) throws NoConnectionException { - return RetroProvider.getSignalVerificationFacade().pullByUuids(uuids); - } + @Override + protected Call> pushAll(List signalVerificationDtos) throws NoConnectionException { + return RetroProvider.getSignalVerificationFacade().pushAll(signalVerificationDtos); + } - @Override - protected Call> pushAll(List signalVerificationDtos) throws NoConnectionException { - return RetroProvider.getSignalVerificationFacade().pushAll(signalVerificationDtos); - } + @Override + public void fillInnerFromDto(SignalVerification target, SignalVerificationDto source) { + target.setVerificationSent(source.getVerificationSent()); + target.setVerified(source.getVerified()); + target.setVerificationCompleteDate(source.getVerificationCompleteDate()); + target.setDateOfOccurrence(source.getDateOfOccurrence()); + target.setNumberOfPersonAnimal(source.getNumberOfPersonAnimal()); + target.setNumberOfDeath(source.getNumberOfDeath()); + target.setDescription(source.getDescription()); + target.setWhyNotVerify(source.getWhyNotVerify()); + target.setNumberOfDeathPerson(source.getNumberOfDeathPerson()); + target.setNumberOfPersonCases(source.getNumberOfPersonCases()); + } - @Override - public void fillInnerFromDto(SignalVerification target, SignalVerificationDto source) { - target.setVerificationSent(source.getVerificationSent()); - target.setVerified(source.getVerified()); - target.setVerificationCompleteDate(source.getVerificationCompleteDate()); - target.setDateOfOccurrence(source.getDateOfOccurrence()); - target.setNumberOfPersonAnimal(source.getNumberOfPersonAnimal()); - target.setNumberOfDeath(source.getNumberOfDeath()); - target.setDescription(source.getDescription()); - target.setWhyNotVerify(source.getWhyNotVerify()); - target.setNumberOfDeathPerson(source.getNumberOfDeathPerson()); - target.setNumberOfPersonCases(source.getNumberOfPersonCases()); - } + @Override + public void fillInnerFromAdo(SignalVerificationDto target, SignalVerification source) { + target.setVerificationSent(source.getVerificationSent()); + target.setVerified(source.getVerified()); + target.setVerificationCompleteDate(source.getVerificationCompleteDate()); + target.setDateOfOccurrence(source.getDateOfOccurrence()); + target.setNumberOfPersonAnimal(source.getNumberOfPersonAnimal()); + target.setNumberOfDeath(source.getNumberOfDeath()); + target.setDescription(source.getDescription()); + target.setWhyNotVerify(source.getWhyNotVerify()); + target.setNumberOfDeathPerson(source.getNumberOfDeathPerson()); + target.setNumberOfPersonCases(source.getNumberOfPersonCases()); + } - @Override - public void fillInnerFromAdo(SignalVerificationDto target, SignalVerification source) { - target.setVerificationSent(source.getVerificationSent()); - target.setVerified(source.getVerified()); - target.setVerificationCompleteDate(source.getVerificationCompleteDate()); - target.setDateOfOccurrence(source.getDateOfOccurrence()); - target.setNumberOfPersonAnimal(source.getNumberOfPersonAnimal()); - target.setNumberOfDeath(source.getNumberOfDeath()); - target.setDescription(source.getDescription()); - target.setWhyNotVerify(source.getWhyNotVerify()); - target.setNumberOfDeathPerson(source.getNumberOfDeathPerson()); - target.setNumberOfPersonCases(source.getNumberOfPersonCases()); - } - - @Override - protected long getApproximateJsonSizeInBytes() { - return SignalVerificationDto.APPROXIMATE_JSON_SIZE_IN_BYTES; - } + @Override + protected long getApproximateJsonSizeInBytes() { + return SignalVerificationDto.APPROXIMATE_JSON_SIZE_IN_BYTES; + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/triaging/TriagingDtoHelper.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/triaging/TriagingDtoHelper.java index 1f9aec54993..38760f118c2 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/triaging/TriagingDtoHelper.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/ebs/triaging/TriagingDtoHelper.java @@ -2,9 +2,12 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.TriagingDto; +import de.symeda.sormas.api.ebs.TriagingReferenceDto; import de.symeda.sormas.app.backend.common.AdoDtoHelper; +import de.symeda.sormas.app.backend.ebs.Ebs; +import de.symeda.sormas.app.backend.event.Event; import de.symeda.sormas.app.backend.location.LocationDtoHelper; import de.symeda.sormas.app.backend.sormastosormas.SormasToSormasOriginInfoDtoHelper; import de.symeda.sormas.app.rest.NoConnectionException; @@ -12,89 +15,89 @@ import retrofit2.Call; public class TriagingDtoHelper extends AdoDtoHelper { + private LocationDtoHelper locationHelper = new LocationDtoHelper(); - private LocationDtoHelper locationHelper = new LocationDtoHelper(); + private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - private SormasToSormasOriginInfoDtoHelper sormasToSormasOriginInfoDtoHelper = new SormasToSormasOriginInfoDtoHelper(); - @Override - protected Class getAdoClass() { - return Triaging.class; - } + @Override + protected Class getAdoClass() { + return Triaging.class; + } - @Override - protected Class getDtoClass() { - return TriagingDto.class; - } + @Override + protected Class getDtoClass() { + return TriagingDto.class; + } - @Override - protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { - return RetroProvider.getTriagingFacade().pullAllSince(since, size, lastSynchronizedUuid); - } + @Override + protected Call> pullAllSince(long since, Integer size, String lastSynchronizedUuid) throws NoConnectionException { + return RetroProvider.getTriagingFacade().pullAllSince(since, size, lastSynchronizedUuid); + } - @Override - protected Call> pullByUuids(List uuids) throws NoConnectionException { - return RetroProvider.getTriagingFacade().pullByUuids(uuids); - } + @Override + protected Call> pullByUuids(List uuids) throws NoConnectionException { + return RetroProvider.getTriagingFacade().pullByUuids(uuids); + } - @Override - protected Call> pushAll(List triagingDtos) throws NoConnectionException { - return RetroProvider.getTriagingFacade().pushAll(triagingDtos); - } + @Override + protected Call> pushAll(List triagingDtos) throws NoConnectionException { + return RetroProvider.getTriagingFacade().pushAll(triagingDtos); + } - @Override - public void fillInnerFromDto(Triaging target, TriagingDto source) { - target.setSupervisorReview(source.getSupervisorReview()); - target.setDecisionDate(source.getDecisionDate()); - target.setHealthConcern(source.getHealthConcern()); - target.setReferredTo(source.getReferredTo()); - target.setOccurrencePreviously(source.getOccurrencePreviously()); - target.setSpecificSignal(source.getSpecificSignal()); - target.setSignalCategory(source.getSignalCategory()); - target.setHumanCommunityCategoryDetails(source.getHumanCommunityCategoryDetails()); - target.setHumanFacilityCategoryDetails(source.getHumanFacilityCategoryDetails()); - target.setHumanLaboratoryCategoryDetails(source.getHumanLaboratoryCategoryDetails()); - target.setAnimalCommunityCategoryDetails(source.getAnimalCommunityCategoryDetails()); - target.setAnimalFacilityCategoryDetails(source.getAnimalFacilityCategoryDetails()); - target.setAnimalLaboratoryCategoryDetails(source.getAnimalLaboratoryCategoryDetails()); - target.setEnvironmentalCategoryDetails(source.getEnvironmentalCategoryDetails()); - target.setPoeCategoryDetails(source.getPoeCategoryDetails()); - target.setTriagingDecision(source.getTriagingDecision()); - target.setOutcomeSupervisor(source.getOutcomeSupervisor()); - target.setNotSignal(source.getNotSignal()); - target.setCategoryDetailsLevel(source.getCategoryDetailsLevel()); - target.setPotentialRisk(source.getPotentialRisk()); - target.setReferred(source.getReferred()); - } + @Override + public void fillInnerFromDto(Triaging target, TriagingDto source) { + target.setSupervisorReview(source.getSupervisorReview()); + target.setDecisionDate(source.getDecisionDate()); + target.setHealthConcern(source.getHealthConcern()); + target.setReferredTo(source.getReferredTo()); + target.setOccurrencePreviously(source.getOccurrencePreviously()); + target.setSpecificSignal(source.getSpecificSignal()); + target.setSignalCategory(source.getSignalCategory()); + target.setHumanCommunityCategoryDetails(source.getHumanCommunityCategoryDetails()); + target.setHumanFacilityCategoryDetails(source.getHumanFacilityCategoryDetails()); + target.setHumanLaboratoryCategoryDetails(source.getHumanLaboratoryCategoryDetails()); + target.setAnimalCommunityCategoryDetails(source.getAnimalCommunityCategoryDetails()); + target.setAnimalFacilityCategoryDetails(source.getAnimalFacilityCategoryDetails()); + target.setAnimalLaboratoryCategoryDetails(source.getAnimalLaboratoryCategoryDetails()); + target.setEnvironmentalCategoryDetails(source.getEnvironmentalCategoryDetails()); + target.setPoeCategoryDetails(source.getPoeCategoryDetails()); + target.setTriagingDecision(source.getTriagingDecision()); + target.setOutcomeSupervisor(source.getOutcomeSupervisor()); + target.setNotSignal(source.getNotSignal()); + target.setCategoryDetailsLevel(source.getCategoryDetailsLevel()); + target.setPotentialRisk(source.getPotentialRisk()); + target.setReferred(source.getReferred()); + } - @Override - public void fillInnerFromAdo(TriagingDto target, Triaging source) { - target.setSupervisorReview(source.getSupervisorReview()); - target.setDecisionDate(source.getDecisionDate()); - target.setHealthConcern(source.getHealthConcern()); - target.setReferredTo(source.getReferredTo()); - target.setOccurrencePreviously(source.getOccurrencePreviously()); - target.setSpecificSignal(source.getSpecificSignal()); - target.setSignalCategory(source.getSignalCategory()); - target.setHumanCommunityCategoryDetails(source.getHumanCommunityCategoryDetails()); - target.setHumanFacilityCategoryDetails(source.getHumanFacilityCategoryDetails()); - target.setHumanLaboratoryCategoryDetails(source.getHumanLaboratoryCategoryDetails()); - target.setAnimalCommunityCategoryDetails(source.getAnimalCommunityCategoryDetails()); - target.setAnimalFacilityCategoryDetails(source.getAnimalFacilityCategoryDetails()); - target.setAnimalLaboratoryCategoryDetails(source.getAnimalLaboratoryCategoryDetails()); - target.setEnvironmentalCategoryDetails(source.getEnvironmentalCategoryDetails()); - target.setPoeCategoryDetails(source.getPoeCategoryDetails()); - target.setTriagingDecision(source.getTriagingDecision()); - target.setOutcomeSupervisor(source.getOutcomeSupervisor()); - target.setNotSignal(source.getNotSignal()); - target.setCategoryDetailsLevel(source.getCategoryDetailsLevel()); - target.setPotentialRisk(source.getPotentialRisk()); - target.setReferred(source.getReferred()); - } + @Override + public void fillInnerFromAdo(TriagingDto target, Triaging source) { + target.setSupervisorReview(source.getSupervisorReview()); + target.setDecisionDate(source.getDecisionDate()); + target.setHealthConcern(source.getHealthConcern()); + target.setReferredTo(source.getReferredTo()); + target.setOccurrencePreviously(source.getOccurrencePreviously()); + target.setSpecificSignal(source.getSpecificSignal()); + target.setSignalCategory(source.getSignalCategory()); + target.setHumanCommunityCategoryDetails(source.getHumanCommunityCategoryDetails()); + target.setHumanFacilityCategoryDetails(source.getHumanFacilityCategoryDetails()); + target.setHumanLaboratoryCategoryDetails(source.getHumanLaboratoryCategoryDetails()); + target.setAnimalCommunityCategoryDetails(source.getAnimalCommunityCategoryDetails()); + target.setAnimalFacilityCategoryDetails(source.getAnimalFacilityCategoryDetails()); + target.setAnimalLaboratoryCategoryDetails(source.getAnimalLaboratoryCategoryDetails()); + target.setEnvironmentalCategoryDetails(source.getEnvironmentalCategoryDetails()); + target.setPoeCategoryDetails(source.getPoeCategoryDetails()); + target.setTriagingDecision(source.getTriagingDecision()); + target.setOutcomeSupervisor(source.getOutcomeSupervisor()); + target.setNotSignal(source.getNotSignal()); + target.setCategoryDetailsLevel(source.getCategoryDetailsLevel()); + target.setPotentialRisk(source.getPotentialRisk()); + target.setReferred(source.getReferred()); + } - @Override - protected long getApproximateJsonSizeInBytes() { - return TriagingDto.APPROXIMATE_JSON_SIZE_IN_BYTES; - } + @Override + protected long getApproximateJsonSizeInBytes() { + return TriagingDto.APPROXIMATE_JSON_SIZE_IN_BYTES; + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/facility/FacilityDao.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/facility/FacilityDao.java index 5e2279bbb23..d2c58c5cbc3 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/facility/FacilityDao.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/backend/facility/FacilityDao.java @@ -26,11 +26,15 @@ import com.j256.ormlite.stmt.Where; import android.util.Log; + +import de.symeda.sormas.api.Disease; import de.symeda.sormas.api.infrastructure.facility.FacilityDto; import de.symeda.sormas.api.infrastructure.facility.FacilityType; import de.symeda.sormas.app.backend.common.AbstractDomainObject; import de.symeda.sormas.app.backend.common.AbstractInfrastructureAdoDao; +import de.symeda.sormas.app.backend.common.DatabaseHelper; import de.symeda.sormas.app.backend.common.InfrastructureAdo; +import de.symeda.sormas.app.backend.disease.DiseaseConfiguration; import de.symeda.sormas.app.backend.region.Community; import de.symeda.sormas.app.backend.region.District; import de.symeda.sormas.app.backend.region.Region; @@ -176,6 +180,16 @@ public List getActiveLaboratories(boolean includeOtherFacility) { } } + public List getActiveLaboratoriesByDisease(Disease disease, boolean includeOtherFacility) { + DiseaseConfiguration diseaseConfiguration = DatabaseHelper.getDiseaseConfigurationDao().getDiseaseConfiguration(disease); + List facilities = DatabaseHelper.getDiseaseConfigurationDao().getDiseaseFacilities(diseaseConfiguration); + + if (facilities.size() < 1) { + facilities = getActiveLaboratories(includeOtherFacility); + } + return facilities; + } + @Override public Facility saveAndSnapshot(Facility facility) { throw new UnsupportedOperationException(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/edit/EbsEditFragment.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/edit/EbsEditFragment.java index 737d5f513fa..622ffa59893 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/edit/EbsEditFragment.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/edit/EbsEditFragment.java @@ -16,8 +16,14 @@ package de.symeda.sormas.app.ebs.edit; import static android.view.View.GONE; + import static de.symeda.sormas.app.core.notification.NotificationType.ERROR; +import android.view.View; +import android.widget.Toast; + +import org.joda.time.DateTime; + import java.util.Arrays; import java.util.Calendar; import java.util.Collections; @@ -25,8 +31,6 @@ import java.util.List; import java.util.stream.Collectors; -import android.view.View; -import android.widget.Toast; import de.symeda.sormas.api.ebs.AutomaticScanningType; import de.symeda.sormas.api.ebs.EbsSourceType; @@ -44,8 +48,8 @@ import de.symeda.sormas.app.backend.config.ConfigProvider; import de.symeda.sormas.app.backend.ebs.Ebs; import de.symeda.sormas.app.backend.ebs.signalVerification.SignalVerification; -import de.symeda.sormas.app.backend.ebs.triaging.Triaging; import de.symeda.sormas.app.backend.location.Location; +import de.symeda.sormas.app.backend.ebs.triaging.Triaging; import de.symeda.sormas.app.component.Item; import de.symeda.sormas.app.component.controls.ControlDateField; import de.symeda.sormas.app.component.controls.ControlDateTimeField; @@ -63,9 +67,7 @@ import de.symeda.sormas.app.util.LocationService; public class EbsEditFragment extends BaseEditFragment { - - public final String THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE = - "The Date of Report cannot be earlier than the Date of Occurrence."; + public final String THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE = "The Date of Report cannot be earlier than the Date of Occurrence."; private Ebs record; private List sourceInformation; @@ -77,35 +79,34 @@ public class EbsEditFragment extends BaseEditFragment initialCommunities; private List mediaScanningType; + public static EbsEditFragment newInstance(Ebs activityRootData) { EbsEditFragment fragment = newInstanceWithFieldCheckers( - EbsEditFragment.class, - null, - activityRootData, - FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), - UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); + EbsEditFragment.class, + null, + activityRootData, + FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), + UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); return fragment; } - public static EbsEditFragment newInstance(Triaging activityRootData) { EbsEditFragment fragment = newInstanceWithFieldCheckers( - EbsEditFragment.class, - null, - activityRootData, - FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), - UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); + EbsEditFragment.class, + null, + activityRootData, + FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), + UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); return fragment; } - public static EbsEditFragment newInstance(SignalVerification activityRootData) { EbsEditFragment fragment = newInstanceWithFieldCheckers( - EbsEditFragment.class, - null, - activityRootData, - FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), - UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); + EbsEditFragment.class, + null, + activityRootData, + FieldVisibilityCheckers.withCountry(ConfigProvider.getServerCountryCode()), + UiFieldAccessCheckers.getDefault(activityRootData.isPseudonymized())); return fragment; } @@ -145,6 +146,7 @@ private void openAddressPopup(final FragmentEbsEditLayoutBinding contentBinding) }); } + // Overrides @Override @@ -165,9 +167,9 @@ public boolean isShowSaveAction() { @Override protected void prepareFragmentData() { record = getActivityRootData(); - sourceInformation = DataUtils.getEnumItems(EbsSourceType.class, true); - categoryOfInformant = DataUtils.getEnumItems(PersonReporting.class, true); - manualScanningType = DataUtils.getEnumItems(ManualScanningType.class, true); + sourceInformation = DataUtils.getEnumItems(EbsSourceType.class,true); + categoryOfInformant = DataUtils.getEnumItems(PersonReporting.class,true); + manualScanningType = DataUtils.getEnumItems(ManualScanningType.class,true); automaticScanningType = DataUtils.getEnumItems(AutomaticScanningType.class, true); mediaScanningType = DataUtils.getEnumItems(MediaScannningType.class, true); initialRegions = InfrastructureDaoHelper.loadRegionsByServerCountry(); @@ -187,15 +189,16 @@ public void onLayoutBinding(final FragmentEbsEditLayoutBinding contentBinding) { ValidationHelper.initEbsPhoneNumberValidator(contentBinding.ebsInformantTel); ValidationHelper.initEbsPhoneNumberValidator(contentBinding.ebsPersonPhone); InfrastructureFieldsDependencyHandler.instance.initializeRegionFields( - contentBinding.ebsRegion, - initialRegions, - record.getEbsLocation().getRegion(), - contentBinding.ebsDistrict, - initialDistricts, - record.getEbsLocation().getDistrict(), - contentBinding.ebsCommunity, - initialCommunities, - record.getEbsLocation().getCommunity()); + contentBinding.ebsRegion, + initialRegions, + record.getEbsLocation().getRegion(), + contentBinding.ebsDistrict, + initialDistricts, + record.getEbsLocation().getDistrict(), + contentBinding.ebsCommunity, + initialCommunities, + record.getEbsLocation().getCommunity() + ); } @Override @@ -213,11 +216,11 @@ protected void onAfterLayoutBinding(FragmentEbsEditLayoutBinding contentBinding) // "Pick GPS Coordinates" confirmation dialog contentBinding.pickGpsCoordinates.setOnClickListener(v -> { final ConfirmationDialog confirmationDialog = new ConfirmationDialog( - getActivity(), - R.string.heading_confirmation_dialog, - R.string.confirmation_pick_gps, - R.string.yes, - R.string.no); + getActivity(), + R.string.heading_confirmation_dialog, + R.string.confirmation_pick_gps, + R.string.yes, + R.string.no); confirmationDialog.setPositiveCallback(() -> { android.location.Location phoneLocation = LocationService.instance().getLocation(getActivity()); @@ -226,8 +229,7 @@ protected void onAfterLayoutBinding(FragmentEbsEditLayoutBinding contentBinding) contentBinding.ebsEbsLongitude.setDoubleValue(phoneLocation.getLongitude()); contentBinding.ebsEbsLatLon.setFloatValue(phoneLocation.getAccuracy()); } else { - NotificationHelper - .showDialogNotification((NotificationContext) getContext(), NotificationType.WARNING, R.string.message_gps_problem); + NotificationHelper.showDialogNotification((NotificationContext) getContext(), NotificationType.WARNING, R.string.message_gps_problem); } }); confirmationDialog.show(); @@ -236,97 +238,108 @@ protected void onAfterLayoutBinding(FragmentEbsEditLayoutBinding contentBinding) List itemsToAdd; Object value = contentBinding.ebsSourceInformation.getValue(); - if (value == null || !(value instanceof EbsSourceType)) { - contentBinding.ebsInformantName.setVisibility(GONE); - return; - } + if (value == null || !(value instanceof EbsSourceType)){ contentBinding.ebsInformantName.setVisibility(GONE); return;} EbsSourceType sourceType = (EbsSourceType) value; switch (sourceType) { - case CEBS: - itemsToAdd = Arrays.asList( - PersonReporting.COMMUNITY_SURVEILLANCE_VOLUNTEER, - PersonReporting.COMMUNITY_ANIMAL_HEALTH_WORKER, - PersonReporting.OTC_CHEMICAL_WORKER, - PersonReporting.COMMUNITY_MEMBER, - PersonReporting.OTHER); - contentBinding.ebsInformantName.setVisibility(View.VISIBLE); - break; - case HEBS: - itemsToAdd = Arrays.asList( - PersonReporting.PUBLIC_HEALTHCARE, - PersonReporting.PRIVATE_HEALTH, - PersonReporting.REFERENCE_LABORATORY, - PersonReporting.OTHER); - contentBinding.ebsInformantName.setVisibility(View.VISIBLE); - break; - case MEDIA_NEWS: - itemsToAdd = Arrays - .asList(PersonReporting.PERSON_DISTRICT, PersonReporting.PERSON_REGION, PersonReporting.PERSON_NATIONAL, PersonReporting.OTHER); - contentBinding.ebsInformantName.setVisibility(GONE); - break; - case HOTLINE_PERSON: - itemsToAdd = Arrays.asList(PersonReporting.GENERAL_PUBLIC_INFORMANT, PersonReporting.INSTITUTIONAL_INFORMANT, PersonReporting.OTHER); - contentBinding.ebsInformantName.setVisibility(View.VISIBLE); - break; - default: - itemsToAdd = Collections.emptyList(); - break; + case CEBS: + itemsToAdd = Arrays.asList( + PersonReporting.COMMUNITY_SURVEILLANCE_VOLUNTEER, + PersonReporting.COMMUNITY_ANIMAL_HEALTH_WORKER, + PersonReporting.OTC_CHEMICAL_WORKER, + PersonReporting.COMMUNITY_MEMBER, + PersonReporting.OTHER + ); + contentBinding.ebsInformantName.setVisibility(View.VISIBLE); + break; + case HEBS: + itemsToAdd = Arrays.asList( + PersonReporting.PUBLIC_HEALTHCARE, + PersonReporting.PRIVATE_HEALTH, + PersonReporting.REFERENCE_LABORATORY, + PersonReporting.OTHER + ); + contentBinding.ebsInformantName.setVisibility(View.VISIBLE); + break; + case MEDIA_NEWS: + itemsToAdd = Arrays.asList( + PersonReporting.PERSON_DISTRICT, + PersonReporting.PERSON_REGION, + PersonReporting.PERSON_NATIONAL, + PersonReporting.OTHER + ); + contentBinding.ebsInformantName.setVisibility(GONE); + break; + case HOTLINE_PERSON: + itemsToAdd = Arrays.asList( + PersonReporting.GENERAL_PUBLIC_INFORMANT, + PersonReporting.INSTITUTIONAL_INFORMANT, + PersonReporting.OTHER + ); + contentBinding.ebsInformantName.setVisibility(View.VISIBLE); + break; + default: + itemsToAdd = Collections.emptyList(); + break; } - List filteredInformant = - categoryOfInformant.stream().filter(item -> itemsToAdd.toString().contains(item.toString())).collect(Collectors.toList()); + List filteredInformant = categoryOfInformant.stream() + .filter(item -> itemsToAdd.toString().contains(item.toString())) + .collect(Collectors.toList()); contentBinding.ebsCategoryOfInformant.initializeSpinner(filteredInformant); contentBinding.ebsInformantName.setVisibility((e.getValue() == EbsSourceType.MEDIA_NEWS) ? GONE : View.VISIBLE); }); - contentBinding.ebsCategoryOfInformant.addValueChangedListener(e -> { + contentBinding.ebsCategoryOfInformant.addValueChangedListener(e->{ List itemsToAdd; if (e.getValue() != PersonReporting.PERSON_NATIONAL) { - itemsToAdd = Arrays.asList(MediaScannningType.MANUAL); - } else if (e.getValue() == PersonReporting.PERSON_NATIONAL) { - itemsToAdd = Arrays.asList(MediaScannningType.MANUAL, MediaScannningType.AUTOMATIC); - } else { + itemsToAdd = Arrays.asList( + MediaScannningType.MANUAL + ); + }else if (e.getValue() == PersonReporting.PERSON_NATIONAL){ + itemsToAdd = Arrays.asList( + MediaScannningType.MANUAL, + MediaScannningType.AUTOMATIC + ); + }else { itemsToAdd = Collections.emptyList(); } - List filteredInformant = - mediaScanningType.stream().filter(item -> itemsToAdd.toString().contains(item.toString())).collect(Collectors.toList()); + List filteredInformant = mediaScanningType.stream() + .filter(item -> itemsToAdd.toString().contains(item.toString())) + .collect(Collectors.toList()); contentBinding.ebsScanningType.initializeSpinner(filteredInformant); }); - contentBinding.ebsReportDateTime.addValueChangedListener(e -> { - validateDateFields(contentBinding); - }); - contentBinding.ebsDateOnset.addValueChangedListener(e -> { - validateDateFields(contentBinding); - }); + contentBinding.ebsReportDateTime.addValueChangedListener( + e->{ + validateDateFields(contentBinding); + } + ); + contentBinding.ebsDateOnset.addValueChangedListener( + e->{ + validateDateFields(contentBinding); + } + ); } - public void validateDateFields(FragmentEbsEditLayoutBinding contentBinding) { ControlDateField dateOfReport = contentBinding.ebsReportDateTime; ControlDateTimeField dateOfOccurrence = contentBinding.ebsDateOnset; - if (dateOfReport.getValue() != null - && dateOfOccurrence.getValue() != null - && dateOfReport.getValue().before((Date) dateOfOccurrence.getValue())) { + if (dateOfReport.getValue() != null && dateOfOccurrence.getValue() != null && dateOfReport.getValue().before((Date)dateOfOccurrence.getValue())) { Date dateOfReportDate = clearTime(dateOfReport.getValue()); Date dateOfOccurrenceDate = clearTime((Date) dateOfOccurrence.getValue()); if (!dateOfReportDate.toString().equals(dateOfOccurrenceDate.toString())) { showError(THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE); dateOfReport.setValidationCallback(() -> { - dateOfReport.enableErrorState( - I18nProperties.getValidationError( - THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE, - THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE)); + dateOfReport.enableErrorState(I18nProperties.getValidationError(THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE, THE_DATE_OF_REPORT_CANNOT_BE_EARLIER_THAN_THE_DATE_OF_OCCURRENCE)); return true; }); - } else { + }else { dateOfReport.setValidationCallback(() -> false); } - } else { + }else { dateOfReport.setValidationCallback(() -> false); } } - private Date clearTime(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); @@ -336,7 +349,6 @@ private Date clearTime(Date date) { calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } - private void showError(String message) { Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show(); } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/list/EbsListActivity.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/list/EbsListActivity.java index 7f368384a79..e8162b6a904 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/list/EbsListActivity.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebs/list/EbsListActivity.java @@ -1,17 +1,18 @@ package de.symeda.sormas.app.ebs.list; -import java.util.List; - import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.Menu; import android.view.View; +import android.widget.AdapterView; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.RecyclerView; +import java.util.List; + import de.symeda.sormas.api.ebs.EbsSourceType; import de.symeda.sormas.api.ebs.EbsTriagingDecision; import de.symeda.sormas.api.ebs.SignalCategory; @@ -22,6 +23,7 @@ import de.symeda.sormas.app.PagedBaseListFragment; import de.symeda.sormas.app.R; import de.symeda.sormas.app.backend.config.ConfigProvider; +import de.symeda.sormas.app.backend.ebs.Ebs; import de.symeda.sormas.app.backend.region.District; import de.symeda.sormas.app.backend.region.Region; import de.symeda.sormas.app.component.Item; @@ -34,165 +36,176 @@ public class EbsListActivity extends PagedBaseListActivity { - public static SignalOutcome[] signalOutcomes = new SignalOutcome[] { - SignalOutcome.NON_EVENT, - SignalOutcome.EVENT }; - public static boolean showWarningAlert = false; - public static int message = 0; - private EbsListViewModel model; - private FilterEbsListLayoutBinding filterBinding; - - public static void startActivity(Context context, SignalOutcome listFilter) { - BaseListActivity.startActivity(context, EbsListActivity.class, buildBundle(getStatusFilterPosition(signalOutcomes, listFilter))); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - showPreloader(); - adapter = new EbsListAdapter(); - adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { - - @Override - public void onItemRangeInserted(int positionStart, int itemCount) { - // Scroll to the topmost position after cases have been inserted - if (positionStart == 0) { - RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); - if (recyclerView != null) { - recyclerView.scrollToPosition(0); - } - } - } - }); - model = new ViewModelProvider(this).get(EbsListViewModel.class); - model.initializeViewModel(); - model.getEbs().observe(this, ebss -> { - adapter.submitList(ebss); - hidePreloader(); - }); - filterBinding.setCriteria(model.getEbsCriteria()); - setOpenPageCallback(p -> { - showPreloader(); - model.getEbsCriteria().setSignalOutcome(signalOutcomes[((PageMenuItem) p).getPosition()]); - model.notifyCriteriaUpdated(); - }); - } - - @Override - public void onPause() { - super.onPause(); - getIntent().putExtra("refreshOnResume", true); - } - - @Override - public void onResume() { - super.onResume(); - if (getIntent().getBooleanExtra("refreshOnResume", false)) { - showPreloader(); - model.getEbs().getValue().getDataSource().invalidate(); - } - } - - @Override - public List getPageMenuData() { - return PageMenuItem.fromEnum(signalOutcomes, getContext()); - } - - @Override - protected Callback getSynchronizeResultCallback() { - // Reload the list after a synchronization has been done - return () -> { - showPreloader(); - model.getEbs().getValue().getDataSource().invalidate(); - }; - } - - @Override - protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { - if (menuItem != null) { - SignalOutcome listFilter = signalOutcomes[menuItem.getPosition()]; - return EbsListFragment.newInstance(listFilter); - } - return null; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getNewMenu().setTitle(R.string.action_new_ebs); - return true; - } - - @Override - protected int getActivityTitle() { - if (showWarningAlert) { - showAlert(message); - showWarningAlert = false; - } - return R.string.heading_ebs_list; - } - - @Override - public void goToNewView() { - EbsNewActivity.startActivity(this); - finish(); - } - - @Override - protected boolean isEntryCreateAllowed() { - return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); - } - - @Override - public void addFiltersToPageMenu() { - View ebsListFilterView = getLayoutInflater().inflate(R.layout.filter_ebs_list_layout, null); - filterBinding = DataBindingUtil.bind(ebsListFilterView); - List sourceInformation = DataUtils.getEnumItems(EbsSourceType.class); - List triagingDecision = DataUtils.getEnumItems(EbsTriagingDecision.class); - List signalCategory = DataUtils.getEnumItems(SignalCategory.class); - - filterBinding.ebsSourceInformationFilter.initializeSpinner(sourceInformation); - filterBinding.triagingSignalCategoryFilter.initializeSpinner(signalCategory); - filterBinding.triagingTriagingDecisionFilter.initializeSpinner(triagingDecision); - filterBinding.ebsRegionFilter.initializeSpinner(InfrastructureDaoHelper.loadRegionsByServerCountry()); - filterBinding.ebsRegionFilter.addValueChangedListener(e -> { - filterBinding.ebsDistrictFilter.initializeSpinner(InfrastructureDaoHelper.loadDistricts((Region) e.getValue())); - }); - filterBinding.ebsDistrictFilter.addValueChangedListener(e -> { - filterBinding.ebsCommunityFilter.initializeSpinner(InfrastructureDaoHelper.loadCommunities((District) e.getValue())); - }); - - filterBinding.ebsReportDateTimeFilter.initializeDateField(getSupportFragmentManager()); - filterBinding.triagingDecisionDateFilter.initializeDateField(getSupportFragmentManager()); - - pageMenu.addFilter(ebsListFilterView); - - filterBinding.applyFilters.setOnClickListener(e -> { - showPreloader(); - pageMenu.hideAll(); - model.notifyCriteriaUpdated(); - }); - - filterBinding.resetFilters.setOnClickListener(e -> { - showPreloader(); - pageMenu.hideAll(); - model.getEbsCriteria().setSourceInformation(null); - model.getEbsCriteria().setRegion(null); - model.getEbsCriteria().setDistrict(null); - model.getEbsCriteria().setCommunity(null); - model.getEbsCriteria().setReportDateTime(null); - model.getEbsCriteria().triageDate(null); - model.getEbsCriteria().setSignalCategory(null); - model.getEbsCriteria().setTriagingDecision(null); - filterBinding.invalidateAll(); - filterBinding.executePendingBindings(); - model.notifyCriteriaUpdated(); - }); - } - - public void showAlert(int message) { - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setTitle(R.string.indicator_warning).setMessage(message).show(); - } + public static SignalOutcome[] signalOutcomes = new SignalOutcome[]{ + SignalOutcome.NON_EVENT, + SignalOutcome.EVENT + }; + private EbsListViewModel model; + private FilterEbsListLayoutBinding filterBinding; + public static boolean showWarningAlert = false; + public static int message = 0; + + public static void startActivity(Context context, SignalOutcome listFilter) { + BaseListActivity.startActivity(context, EbsListActivity.class, buildBundle(getStatusFilterPosition(signalOutcomes, listFilter))); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + showPreloader(); + adapter = new EbsListAdapter(); + adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { + + @Override + public void onItemRangeInserted(int positionStart, int itemCount) { + // Scroll to the topmost position after cases have been inserted + if (positionStart == 0) { + RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); + if (recyclerView != null) { + recyclerView.scrollToPosition(0); + } + } + } + }); + model = new ViewModelProvider(this).get(EbsListViewModel.class); + model.initializeViewModel(); + model.getEbs().observe(this, ebss -> { + adapter.submitList(ebss); + hidePreloader(); + }); + filterBinding.setCriteria(model.getEbsCriteria()); + setOpenPageCallback(p -> { + showPreloader(); + model.getEbsCriteria().setSignalOutcome(signalOutcomes[((PageMenuItem) p).getPosition()]); + model.notifyCriteriaUpdated(); + }); + } + + @Override + public void onPause() { + super.onPause(); + getIntent().putExtra("refreshOnResume", true); + } + + @Override + public void onResume() { + super.onResume(); + if (getIntent().getBooleanExtra("refreshOnResume", false)) { + showPreloader(); + model.getEbs().getValue().getDataSource().invalidate(); + } + } + + @Override + public List getPageMenuData() { + return PageMenuItem.fromEnum(signalOutcomes, getContext()); + } + + @Override + protected Callback getSynchronizeResultCallback() { + // Reload the list after a synchronization has been done + return () -> { + showPreloader(); + model.getEbs().getValue().getDataSource().invalidate(); + }; + } + + @Override + protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { + if (menuItem != null) { + SignalOutcome listFilter = signalOutcomes[menuItem.getPosition()]; + return EbsListFragment.newInstance(listFilter); + } + return null; + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getNewMenu().setTitle(R.string.action_new_ebs); + return true; + } + + @Override + protected int getActivityTitle() { + if (showWarningAlert){ + showAlert(message); + showWarningAlert = false; + } + return R.string.heading_ebs_list; + } + + @Override + public void goToNewView() { + EbsNewActivity.startActivity(this); + finish(); + } + + @Override + protected boolean isEntryCreateAllowed() { + return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); + } + + @Override + public int onNotificationCountChangingAsync(AdapterView parent, PageMenuItem menuItem, int position) { + return 0; + } + + @Override + public void addFiltersToPageMenu() { + View ebsListFilterView = getLayoutInflater().inflate(R.layout.filter_ebs_list_layout, null); + filterBinding = DataBindingUtil.bind(ebsListFilterView); + List sourceInformation = DataUtils.getEnumItems(EbsSourceType.class); + List triagingDecision = DataUtils.getEnumItems(EbsTriagingDecision.class); + List signalCategory = DataUtils.getEnumItems(SignalCategory.class); + + + filterBinding.ebsSourceInformationFilter.initializeSpinner(sourceInformation); + filterBinding.triagingSignalCategoryFilter.initializeSpinner(signalCategory); + filterBinding.triagingTriagingDecisionFilter.initializeSpinner(triagingDecision); + filterBinding.ebsRegionFilter.initializeSpinner(InfrastructureDaoHelper.loadRegionsByServerCountry()); + filterBinding.ebsRegionFilter.addValueChangedListener(e->{ + filterBinding.ebsDistrictFilter.initializeSpinner(InfrastructureDaoHelper.loadDistricts((Region) e.getValue())); + }); + filterBinding.ebsDistrictFilter.addValueChangedListener(e->{ + filterBinding.ebsCommunityFilter.initializeSpinner(InfrastructureDaoHelper.loadCommunities((District) e.getValue())); + }); + + + filterBinding.ebsReportDateTimeFilter.initializeDateField(getSupportFragmentManager()); + filterBinding.triagingDecisionDateFilter.initializeDateField(getSupportFragmentManager()); + + pageMenu.addFilter(ebsListFilterView); + + filterBinding.applyFilters.setOnClickListener(e -> { + showPreloader(); + pageMenu.hideAll(); + model.notifyCriteriaUpdated(); + }); + + filterBinding.resetFilters.setOnClickListener(e -> { + showPreloader(); + pageMenu.hideAll(); + model.getEbsCriteria().setSourceInformation(null); + model.getEbsCriteria().setRegion(null); + model.getEbsCriteria().setDistrict(null); + model.getEbsCriteria().setCommunity(null); + model.getEbsCriteria().setReportDateTime(null); + model.getEbsCriteria().triageDate(null); + model.getEbsCriteria().setSignalCategory(null); + model.getEbsCriteria().setTriagingDecision(null); + filterBinding.invalidateAll(); + filterBinding.executePendingBindings(); + model.notifyCriteriaUpdated(); + }); + } + public void showAlert(int message){ + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.indicator_warning) + .setMessage(message) + .show(); + } } + + diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebsAlert/list/EbsAlertListActivity.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebsAlert/list/EbsAlertListActivity.java index f278f385794..f2ed01a16de 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/ebsAlert/list/EbsAlertListActivity.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/ebsAlert/list/EbsAlertListActivity.java @@ -1,14 +1,16 @@ package de.symeda.sormas.app.ebsAlert.list; -import java.util.List; - +import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.Menu; +import android.widget.AdapterView; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.RecyclerView; +import java.util.List; + import de.symeda.sormas.api.ebs.ResponseStatus; import de.symeda.sormas.api.ebs.SignalOutcome; import de.symeda.sormas.api.user.UserRight; @@ -21,123 +23,129 @@ import de.symeda.sormas.app.ebs.edit.EbsEditActivity; import de.symeda.sormas.app.ebs.list.EbsListActivity; import de.symeda.sormas.app.ebsAlert.edit.EbsAlertNewActivity; +import de.symeda.sormas.app.triaging.edit.TriagingEditActivity; import de.symeda.sormas.app.util.Callback; public class EbsAlertListActivity extends PagedBaseListActivity { - public static ResponseStatus[] responseStatuses = new ResponseStatus[] { - null, - ResponseStatus.NOT_STARTED, - ResponseStatus.ON_GOING, - ResponseStatus.COMPLETED }; - private EbsAlertListViewModel model; - - public static void startActivity(Context context, ResponseStatus listFilter) { - BaseListActivity.startActivity(context, EbsAlertListActivity.class, buildBundle(getStatusFilterPosition(responseStatuses, listFilter))); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - showPreloader(); - adapter = new EbsAlertListAdapter(); - adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { - - @Override - public void onItemRangeInserted(int positionStart, int itemCount) { - if (positionStart == 0) { - RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); - if (recyclerView != null) { - recyclerView.scrollToPosition(0); - } - } - } - }); - - model = new ViewModelProvider(this).get(EbsAlertListViewModel.class); - model.initializeViewModel(EbsEditActivity.getParentEbs().getId()); - model.getEbsAlert().observe(this, tasks -> { - adapter.submitList(tasks); - hidePreloader(); - }); - - setOpenPageCallback(p -> { - showPreloader(); - model.getEbsAlertCriteria().setEbsId(EbsEditActivity.getParentEbs().getId()); - model.getEbsAlertCriteria().setResponseStatus(responseStatuses[((PageMenuItem) p).getPosition()]); - model.notifyCriteriaUpdated(); - }); - - } - - @Override - public void onPause() { - super.onPause(); - getIntent().putExtra("refreshOnResume", true); - } - - @Override - public void onResume() { - super.onResume(); - if (getIntent().getBooleanExtra("refreshOnResume", false)) { - showPreloader(); - model.getEbsAlert().getValue().getDataSource().invalidate(); - } - } - - @Override - public List getPageMenuData() { - if (EbsEditActivity.getParentEbs().getSignalVerification().getVerified() != SignalOutcome.EVENT) { - EbsListActivity.showWarningAlert = true; - EbsListActivity.message = R.string.risk_disabled_signal_not_verified; - EbsListActivity.startActivity(getContext(), null); - } - return PageMenuItem.fromEnum(responseStatuses, getContext()); - } - - @Override - protected Callback getSynchronizeResultCallback() { - // Reload the list after a synchronization has been done - return () -> { - showPreloader(); - model.getEbsAlert().getValue().getDataSource().invalidate(); - }; - } - - @Override - protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { - if (menuItem != null) { - ResponseStatus listFilter = responseStatuses[menuItem.getPosition()]; - return EbsAlertListFragment.newInstance(listFilter); - } - return null; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getNewMenu().setTitle(R.string.action_new_alert); - return true; - } - - @Override - protected int getActivityTitle() { - return R.string.heading_alert_list; - } - - @Override - public void goToNewView() { - EbsAlertNewActivity.startActivity(getContext()); - finish(); - } - - @Override - protected boolean isEntryCreateAllowed() { - return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); - } - - @Override - public void addFiltersToPageMenu() { + public static ResponseStatus[] responseStatuses = new ResponseStatus[]{ + null, + ResponseStatus.NOT_STARTED, + ResponseStatus.ON_GOING, + ResponseStatus.COMPLETED}; + private EbsAlertListViewModel model; + + public static void startActivity(Context context, ResponseStatus listFilter) { + BaseListActivity.startActivity(context, EbsAlertListActivity.class, buildBundle(getStatusFilterPosition(responseStatuses, listFilter))); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + showPreloader(); + adapter = new EbsAlertListAdapter(); + adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { + @Override + public void onItemRangeInserted(int positionStart, int itemCount) { + if (positionStart == 0) { + RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); + if (recyclerView != null) { + recyclerView.scrollToPosition(0); + } + } + } + }); + + model = new ViewModelProvider(this).get(EbsAlertListViewModel.class); + model.initializeViewModel(EbsEditActivity.getParentEbs().getId()); + model.getEbsAlert().observe(this, tasks -> { + adapter.submitList(tasks); + hidePreloader(); + }); + + setOpenPageCallback(p -> { + showPreloader(); + model.getEbsAlertCriteria().setEbsId(EbsEditActivity.getParentEbs().getId()); + model.getEbsAlertCriteria().setResponseStatus(responseStatuses[((PageMenuItem) p).getPosition()]); + model.notifyCriteriaUpdated(); + }); + + } + + + @Override + public void onPause() { + super.onPause(); + getIntent().putExtra("refreshOnResume", true); + } + + @Override + public void onResume() { + super.onResume(); + if (getIntent().getBooleanExtra("refreshOnResume", false)) { + showPreloader(); + model.getEbsAlert().getValue().getDataSource().invalidate(); + } + } + + @Override + public List getPageMenuData() { + if (EbsEditActivity.getParentEbs().getSignalVerification().getVerified() != SignalOutcome.EVENT){ + EbsListActivity.showWarningAlert = true; + EbsListActivity.message = R.string.risk_disabled_signal_not_verified; + EbsListActivity.startActivity(getContext(),null); + } + return PageMenuItem.fromEnum(responseStatuses, getContext()); + } + + @Override + protected Callback getSynchronizeResultCallback() { + // Reload the list after a synchronization has been done + return () -> { + showPreloader(); + model.getEbsAlert().getValue().getDataSource().invalidate(); + }; + } + + @Override + protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { + if (menuItem != null) { + ResponseStatus listFilter = responseStatuses[menuItem.getPosition()]; + return EbsAlertListFragment.newInstance(listFilter); + } + return null; + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getNewMenu().setTitle(R.string.action_new_alert); + return true; + } + + @Override + protected int getActivityTitle() { + return R.string.heading_alert_list; + } + + @Override + public void goToNewView() { + EbsAlertNewActivity.startActivity(getContext()); + finish(); + } + + @Override + protected boolean isEntryCreateAllowed() { + return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); + } + + @Override + public int onNotificationCountChangingAsync(AdapterView parent, PageMenuItem menuItem, int position) { + return 0; + } + + @Override + public void addFiltersToPageMenu() { // View ebsListFilterView = getLayoutInflater().inflate(R.layout.filter_ebs_list_layout, null); // FilterEbsListLayoutBinding ebsListFilterBinding = DataBindingUtil.bind(ebsListFilterView); @@ -153,5 +161,5 @@ public void addFiltersToPageMenu() { // model.notifyCriteriaUpdated(); // } // }); - } + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsAlertFacadeRetro.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsAlertFacadeRetro.java index 5114115b611..cb1df8919e3 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsAlertFacadeRetro.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsAlertFacadeRetro.java @@ -17,7 +17,7 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.EbsAlertDto; import retrofit2.Call; import retrofit2.http.Body; @@ -28,16 +28,13 @@ public interface EbsAlertFacadeRetro { @GET("ebsAlert/all/{since}/{size}/{lastSynchronizedUuid}") - Call> pullAllSince( - @Path("since") long since, - @Path("size") int size, - @Path("lastSynchronizedUuid") String lastSynchronizedUuid); + Call> pullAllSince(@Path("since") long since, @Path("size") int size, @Path("lastSynchronizedUuid") String lastSynchronizedUuid); @POST("ebsAlert/query") Call> pullByUuids(@Body List uuids); @POST("ebsAlert/push") - Call> pushAll(@Body List dtos); + Call> pushAll(@Body List dtos); @GET("ebsAlert/uuids") Call> pullUuids(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsFacadeRetro.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsFacadeRetro.java index 98ab459eefb..aa857d52437 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsFacadeRetro.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/EbsFacadeRetro.java @@ -17,8 +17,9 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.EbsDto; +import de.symeda.sormas.api.event.EventDto; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; @@ -34,7 +35,7 @@ public interface EbsFacadeRetro { Call> pullByUuids(@Body List uuids); @POST("ebs/push") - Call> pushAll(@Body List dtos); + Call> pushAll(@Body List dtos); @GET("ebs/uuids") Call> pullUuids(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/RiskAssessmentFacadeRetro.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/RiskAssessmentFacadeRetro.java index 4aca9d0824a..c77e2622b74 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/RiskAssessmentFacadeRetro.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/RiskAssessmentFacadeRetro.java @@ -17,7 +17,7 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.RiskAssessmentDto; import retrofit2.Call; import retrofit2.http.Body; @@ -28,16 +28,13 @@ public interface RiskAssessmentFacadeRetro { @GET("riskassessment/all/{since}/{size}/{lastSynchronizedUuid}") - Call> pullAllSince( - @Path("since") long since, - @Path("size") int size, - @Path("lastSynchronizedUuid") String lastSynchronizedUuid); + Call> pullAllSince(@Path("since") long since, @Path("size") int size, @Path("lastSynchronizedUuid") String lastSynchronizedUuid); @POST("riskassessment/query") Call> pullByUuids(@Body List uuids); @POST("riskassessment/push") - Call> pushAll(@Body List dtos); + Call> pushAll(@Body List dtos); @GET("riskassessment/uuids") Call> pullUuids(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/SignalVerificationFacadeRetro.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/SignalVerificationFacadeRetro.java index 9c6ef19427b..880460831cc 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/SignalVerificationFacadeRetro.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/SignalVerificationFacadeRetro.java @@ -17,7 +17,7 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.SignalVerificationDto; import retrofit2.Call; import retrofit2.http.Body; @@ -28,16 +28,13 @@ public interface SignalVerificationFacadeRetro { @GET("signalVerification/all/{since}/{size}/{lastSynchronizedUuid}") - Call> pullAllSince( - @Path("since") long since, - @Path("size") int size, - @Path("lastSynchronizedUuid") String lastSynchronizedUuid); + Call> pullAllSince(@Path("since") long since, @Path("size") int size, @Path("lastSynchronizedUuid") String lastSynchronizedUuid); @POST("signalVerification/query") Call> pullByUuids(@Body List uuids); @POST("signalVerification/push") - Call> pushAll(@Body List dtos); + Call> pushAll(@Body List dtos); @GET("signalVerification/uuids") Call> pullUuids(); diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/TriagingFacadeRetro.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/TriagingFacadeRetro.java index af1f15fdafe..fba434ab62e 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/TriagingFacadeRetro.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/rest/TriagingFacadeRetro.java @@ -17,7 +17,7 @@ import java.util.List; -import de.symeda.sormas.api.PostResponse; +import de.symeda.sormas.api.PushResult; import de.symeda.sormas.api.ebs.TriagingDto; import retrofit2.Call; import retrofit2.http.Body; @@ -28,15 +28,12 @@ public interface TriagingFacadeRetro { @GET("triaging/all/{since}/{size}/{lastSynchronizedUuid}") - Call> pullAllSince( - @Path("since") long since, - @Path("size") int size, - @Path("lastSynchronizedUuid") String lastSynchronizedUuid); + Call> pullAllSince(@Path("since") long since, @Path("size") int size, @Path("lastSynchronizedUuid") String lastSynchronizedUuid); @POST("triaging/query") Call> pullByUuids(@Body List uuids); @POST("triaging/push") - Call> pushAll(@Body List dtos); + Call> pushAll(@Body List dtos); } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/riskAssessment/list/RiskAssessmentListActivity.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/riskAssessment/list/RiskAssessmentListActivity.java index 1e898ec22df..7d4746bba4e 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/riskAssessment/list/RiskAssessmentListActivity.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/riskAssessment/list/RiskAssessmentListActivity.java @@ -1,17 +1,20 @@ package de.symeda.sormas.app.riskAssessment.list; -import java.util.List; - +import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.view.Menu; +import android.widget.AdapterView; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.RecyclerView; +import java.util.List; + import de.symeda.sormas.api.ebs.RiskAssesment; import de.symeda.sormas.api.ebs.SignalOutcome; import de.symeda.sormas.api.user.UserRight; +import de.symeda.sormas.app.BaseEditFragment; import de.symeda.sormas.app.BaseListActivity; import de.symeda.sormas.app.PagedBaseListActivity; import de.symeda.sormas.app.PagedBaseListFragment; @@ -19,63 +22,66 @@ import de.symeda.sormas.app.backend.config.ConfigProvider; import de.symeda.sormas.app.component.menu.PageMenuItem; import de.symeda.sormas.app.ebs.edit.EbsEditActivity; +import de.symeda.sormas.app.ebs.edit.EbsEditFragment; import de.symeda.sormas.app.ebs.list.EbsListActivity; +import de.symeda.sormas.app.riskAssessment.edit.RiskAssessmentEditActivity; import de.symeda.sormas.app.riskAssessment.edit.RiskAssessmentNewActivity; +import de.symeda.sormas.app.triaging.edit.TriagingEditActivity; import de.symeda.sormas.app.util.Callback; public class RiskAssessmentListActivity extends PagedBaseListActivity { - public static RiskAssesment[] riskAssessments = new RiskAssesment[] { - null, - RiskAssesment.VERY_HIGH, - RiskAssesment.HIGH, - RiskAssesment.MEDIUM, - RiskAssesment.LOW }; - private RiskAssessmentListViewModel model; - - public static void startActivity(Context context, RiskAssesment listFilter) { - BaseListActivity.startActivity(context, RiskAssessmentListActivity.class, buildBundle(getStatusFilterPosition(riskAssessments, listFilter))); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - showPreloader(); - adapter = new RiskAssessmentListAdapter(); - adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { - - @Override - public void onItemRangeInserted(int positionStart, int itemCount) { - if (positionStart == 0) { - RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); - if (recyclerView != null) { - recyclerView.scrollToPosition(0); - } - } - } - }); - - model = new ViewModelProvider(this).get(RiskAssessmentListViewModel.class); - model.initializeViewModel(EbsEditActivity.getParentEbs().getId()); - model.getRiskAssessment().observe(this, tasks -> { - adapter.submitList(tasks); - hidePreloader(); - }); - - setOpenPageCallback(p -> { - showPreloader(); - model.getRiskAssessmentCriteria().setEbsId(EbsEditActivity.getParentEbs().getId()); - model.getRiskAssessmentCriteria().setRiskAssesment(riskAssessments[((PageMenuItem) p).getPosition()]); - model.notifyCriteriaUpdated(); - }); - - } - - @Override - public void onPause() { - super.onPause(); - getIntent().putExtra("refreshOnResume", true); - } + public static RiskAssesment[] riskAssessments = new RiskAssesment[]{ + null, + RiskAssesment.VERY_HIGH, + RiskAssesment.HIGH, + RiskAssesment.MEDIUM, + RiskAssesment.LOW}; + private RiskAssessmentListViewModel model; + + public static void startActivity(Context context, RiskAssesment listFilter) { + BaseListActivity.startActivity(context, RiskAssessmentListActivity.class, buildBundle(getStatusFilterPosition(riskAssessments, listFilter))); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + showPreloader(); + adapter = new RiskAssessmentListAdapter(); + adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { + @Override + public void onItemRangeInserted(int positionStart, int itemCount) { + if (positionStart == 0) { + RecyclerView recyclerView = findViewById(R.id.recyclerViewForList); + if (recyclerView != null) { + recyclerView.scrollToPosition(0); + } + } + } + }); + + model = new ViewModelProvider(this).get(RiskAssessmentListViewModel.class); + model.initializeViewModel(EbsEditActivity.getParentEbs().getId()); + model.getRiskAssessment().observe(this, tasks -> { + adapter.submitList(tasks); + hidePreloader(); + }); + + setOpenPageCallback(p -> { + showPreloader(); + model.getRiskAssessmentCriteria().setEbsId(EbsEditActivity.getParentEbs().getId()); + model.getRiskAssessmentCriteria().setRiskAssesment(riskAssessments[((PageMenuItem) p).getPosition()]); + model.notifyCriteriaUpdated(); + }); + + } + + + @Override + public void onPause() { + super.onPause(); + getIntent().putExtra("refreshOnResume", true); + } // @Override // public void onResume() { @@ -86,59 +92,64 @@ public void onPause() { // } // } - @Override - public List getPageMenuData() { - if (EbsEditActivity.getParentEbs().getSignalVerification().getVerified() != SignalOutcome.EVENT) { - EbsListActivity.showWarningAlert = true; - EbsListActivity.message = R.string.risk_disabled_signal_not_verified; - EbsListActivity.startActivity(getContext(), null); - } - return PageMenuItem.fromEnum(riskAssessments, getContext()); - } - - @Override - protected Callback getSynchronizeResultCallback() { - // Reload the list after a synchronization has been done - return () -> { - showPreloader(); - model.getRiskAssessment().getValue().getDataSource().invalidate(); - }; - } - - @Override - protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { - if (menuItem != null) { - RiskAssesment listFilter = riskAssessments[menuItem.getPosition()]; - return RiskAssessmentListFragment.newInstance(listFilter); - } - return null; - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - super.onCreateOptionsMenu(menu); - getNewMenu().setTitle(R.string.action_new_risk_assessment); - return true; - } - - @Override - protected int getActivityTitle() { - return R.string.heading_risk_assessment_list; - } - - @Override - public void goToNewView() { - RiskAssessmentNewActivity.startActivity(getContext()); - finish(); - } - - @Override - protected boolean isEntryCreateAllowed() { - return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); - } - - @Override - public void addFiltersToPageMenu() { + @Override + public List getPageMenuData() { + if (EbsEditActivity.getParentEbs().getSignalVerification().getVerified() != SignalOutcome.EVENT){ + EbsListActivity.showWarningAlert = true; + EbsListActivity.message = R.string.risk_disabled_signal_not_verified; + EbsListActivity.startActivity(getContext(),null); + } + return PageMenuItem.fromEnum(riskAssessments, getContext()); + } + + @Override + protected Callback getSynchronizeResultCallback() { + // Reload the list after a synchronization has been done + return () -> { + showPreloader(); + model.getRiskAssessment().getValue().getDataSource().invalidate(); + }; + } + + @Override + protected PagedBaseListFragment buildListFragment(PageMenuItem menuItem) { + if (menuItem != null) { + RiskAssesment listFilter = riskAssessments[menuItem.getPosition()]; + return RiskAssessmentListFragment.newInstance(listFilter); + } + return null; + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getNewMenu().setTitle(R.string.action_new_risk_assessment); + return true; + } + + @Override + protected int getActivityTitle() { + return R.string.heading_risk_assessment_list; + } + + @Override + public void goToNewView() { + RiskAssessmentNewActivity.startActivity(getContext()); + finish(); + } + + @Override + protected boolean isEntryCreateAllowed() { + return ConfigProvider.hasUserRight(UserRight.EVENT_CREATE); + } + + @Override + public int onNotificationCountChangingAsync(AdapterView parent, PageMenuItem menuItem, int position) { + return 0; + } + + @Override + public void addFiltersToPageMenu() { // View ebsListFilterView = getLayoutInflater().inflate(R.layout.filter_ebs_list_layout, null); // FilterEbsListLayoutBinding ebsListFilterBinding = DataBindingUtil.bind(ebsListFilterView); @@ -154,5 +165,5 @@ public void addFiltersToPageMenu() { // model.notifyCriteriaUpdated(); // } // }); - } + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/sample/edit/SampleEditFragment.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/sample/edit/SampleEditFragment.java index f59e13c03ae..de3668f3f1d 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/sample/edit/SampleEditFragment.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/sample/edit/SampleEditFragment.java @@ -89,18 +89,6 @@ public static SampleEditFragment newInstance(Sample activityRootData) { UserRight.SAMPLE_EDIT); } - protected static Disease getDiseaseOfAssociatedEntity(Sample sample) { - if (sample.getAssociatedCase() != null) { - return sample.getAssociatedCase().getDisease(); - } else if (sample.getAssociatedContact() != null) { - return sample.getAssociatedContact().getDisease(); - } else if (sample.getAssociatedEventParticipant() != null) { - return sample.getAssociatedEventParticipant().getEvent().getDisease(); - } else { - return null; - } - } - private void setUpControlListeners(FragmentSampleEditLayoutBinding contentBinding) { if (!StringUtils.isEmpty(record.getReferredToUuid())) { contentBinding.sampleReferredToUuid.setOnClickListener(new View.OnClickListener() { @@ -120,8 +108,6 @@ public void onClick(View view) { } } - // Overrides - private void setUpFieldVisibilities(final FragmentSampleEditLayoutBinding contentBinding) { // Most recent test layout if (!record.isReceived() || record.getSpecimenCondition() != SpecimenCondition.ADEQUATE) { @@ -154,6 +140,8 @@ private void setUpFieldVisibilities(final FragmentSampleEditLayoutBinding conten } } + // Overrides + @Override protected String getSubHeadingTitle() { return getResources().getString(R.string.caption_sample_information); @@ -182,7 +170,7 @@ record = getActivityRootData(); sampleMaterialList = DataUtils.getEnumItems(SampleMaterial.class, true, getFieldVisibilityCheckers()); sampleSourceList = DataUtils.getEnumItems(SampleSource.class, true); - labList = DatabaseHelper.getFacilityDao().getActiveLaboratories(true); + labList = DatabaseHelper.getFacilityDao().getActiveLaboratoriesByDisease(getDiseaseOfAssociatedEntity(record), true); samplePurposeList = DataUtils.getEnumItems(SamplePurpose.class, true); samplingReasonList = DataUtils.getEnumItems(SamplingReason.class, true, getFieldVisibilityCheckers()); @@ -365,4 +353,16 @@ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent d super.onActivityResult(requestCode, resultCode, data); } } + + protected static Disease getDiseaseOfAssociatedEntity(Sample sample) { + if (sample.getAssociatedCase() != null) { + return sample.getAssociatedCase().getDisease(); + } else if (sample.getAssociatedContact() != null) { + return sample.getAssociatedContact().getDisease(); + } else if (sample.getAssociatedEventParticipant() != null) { + return sample.getAssociatedEventParticipant().getEvent().getDisease(); + } else { + return null; + } + } } diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsActivity.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsActivity.java index 3478d908c4c..0fbb4a3b16c 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsActivity.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsActivity.java @@ -15,10 +15,15 @@ package de.symeda.sormas.app.settings; +import static de.symeda.sormas.app.core.notification.NotificationType.ERROR; +import static de.symeda.sormas.app.core.notification.NotificationType.SUCCESS; + import android.app.Activity; import android.content.Intent; +import android.net.Uri; import android.view.Menu; import android.view.MenuItem; +import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; @@ -28,6 +33,7 @@ import de.symeda.sormas.app.BaseLandingFragment; import de.symeda.sormas.app.LocaleManager; import de.symeda.sormas.app.R; +import de.symeda.sormas.app.backend.common.DatabaseHelper; import de.symeda.sormas.app.backend.config.ConfigProvider; import de.symeda.sormas.app.core.notification.NotificationHelper; import de.symeda.sormas.app.core.notification.NotificationPosition; @@ -36,6 +42,7 @@ import de.symeda.sormas.app.util.AppUpdateController; public class SettingsActivity extends BaseLandingActivity { + private static final int PICK_FILE_REQUEST_CODE = 9; @Override public boolean onCreateOptionsMenu(Menu menu) { @@ -111,7 +118,7 @@ public BaseLandingFragment buildLandingFragment() { /** * Is a sub-activity when the user needs to go back to the LoginActivity - * + * * @see SettingsActivity#onOptionsItemSelected(MenuItem) */ @Override @@ -141,6 +148,24 @@ public void onActivityResult(int requestCode, int resultCode, Intent intent) { break; } } + + if (resultCode == Activity.RESULT_CANCELED) { + // User cancelled the file picker + Toast.makeText(this, "File selection canceled", Toast.LENGTH_SHORT).show(); + return; + } + + if (intent.getData() != null && resultCode == Activity.RESULT_OK) { + Uri fileUri = intent.getData(); + + if (fileUri != null) { + // Restore the database from the selected file URI + DatabaseHelper.restoreDatabaseFromUri(this, fileUri); + } else { + Toast.makeText(this, "Failed to get file", Toast.LENGTH_SHORT).show(); + } + } + } public void setNewLocale(AppCompatActivity mContext, Language language) { diff --git a/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsFragment.java b/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsFragment.java index 4e051a675ee..0356f173d81 100644 --- a/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsFragment.java +++ b/sormas-app/app/src/main/java/de/symeda/sormas/app/settings/SettingsFragment.java @@ -17,21 +17,23 @@ import static de.symeda.sormas.app.core.notification.NotificationType.ERROR; -import java.util.List; - -import org.hzi.sormas.lbds.messaging.LbdsRelated; - import android.content.Intent; import android.content.pm.PackageManager; +import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; +import org.hzi.sormas.lbds.messaging.LbdsRelated; + +import java.util.List; + import de.symeda.sormas.api.Language; import de.symeda.sormas.api.i18n.I18nProperties; import de.symeda.sormas.api.utils.InfoProvider; @@ -72,6 +74,8 @@ public class SettingsFragment extends BaseLandingFragment { private final int SHOW_DEV_OPTIONS_CLICK_LIMIT = 5; + private static final int PICK_FILE_REQUEST_CODE = 9; + private FragmentSettingsLayoutBinding binding; private int versionClickedCount; @@ -90,6 +94,8 @@ public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, binding.settingsServerUrl.setValue(ConfigProvider.getServerRestUrl()); binding.changePin.setOnClickListener(v -> changePIN()); + binding.backupDb.setOnClickListener(v -> backupDatabase()); + binding.restoreDb.setOnClickListener(v -> pickBackupFile()); binding.changePassword.setOnClickListener(v -> changePassword()); binding.resynchronizeData.setOnClickListener(v -> repullData()); binding.showSyncLog.setOnClickListener(v -> openSyncLog()); @@ -104,6 +110,8 @@ public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, versionClickedCount++; if (isShowDevOptions()) { binding.settingsServerUrl.setVisibility(View.VISIBLE); + binding.backupDb.setVisibility(View.VISIBLE); + binding.restoreDb.setVisibility(View.VISIBLE); if (isLbdsAppInstalled()) { binding.kexLbds.setVisibility(View.VISIBLE); binding.syncPersonLbds.setVisibility(View.VISIBLE); @@ -186,12 +194,37 @@ public void changePIN() { intent.putExtra(EnterPinActivity.CALLED_FROM_SETTINGS, true); startActivity(intent); } - public void changePassword() { Intent intent = new Intent(getActivity(), ChangePasswordActivity.class); startActivity(intent); } +// backupDatabase + public void backupDatabase() { + try { + DatabaseHelper.backupDatabase(getContext(), "sormas.db"); + Toast.makeText(getContext(), "Backup successful", Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toast.makeText(getContext(), "Backup failed: " + e.getMessage(), Toast.LENGTH_LONG).show(); + } + } + + private void pickBackupFile() { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("*/*"); // Filter to show only files + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(Intent.createChooser(intent, "Select Backup File"), PICK_FILE_REQUEST_CODE); +// try { +// startActivity(Intent.createChooser(intent, "Select a File to Restore")); +// onActivityResult(PICK_FILE_REQUEST_CODE, AppCompatActivity.RESULT_OK, intent); +// } catch (android.content.ActivityNotFoundException ex) { +// NotificationHelper +// .showNotification((SettingsActivity) getActivity(), ERROR, getString(R.string.message_language_change_unsuccessful)); +// } + } + + private void repullData() { checkAndShowUnsynchronizedChangesDialog(() -> showRepullDataConfirmationDialog(), "SYNC"); } diff --git a/sormas-app/app/src/main/res/values/strings.xml b/sormas-app/app/src/main/res/values/strings.xml index df0c7ab2003..6963f7189d5 100644 --- a/sormas-app/app/src/main/res/values/strings.xml +++ b/sormas-app/app/src/main/res/values/strings.xml @@ -41,8 +41,6 @@ Password Strength Cancel Change PIN - Backup DB - Restore DB Change Settings Clear Clear All @@ -298,7 +296,7 @@ %1$s pulled %1$s/%2$s pushed %1$s deleted - ` +` Are you sure you want to do this? Are you sure you want to delete this record? Are you in this place right now? @@ -773,12 +771,12 @@ Not a valid username Password must be >5 characters "Login failed" - "Enter Current Password" - "Enter New Password" - "Enter Confirm Password" - "Enter Current Password" - "Enter new Password" - "Confirm Password" + "Enter Current Password" + "Enter New Password" + "Enter Confirm Password" + "Enter Current Password" + "Enter new Password" + "Confirm Password" Signal Is not An Event Triaging Decision Is Discard Or Referred Risk assessment / Alert is disabled, Signal is not an event diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/caze/CaseFacadeEjb.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/caze/CaseFacadeEjb.java index 633425ee224..8be7dc17cc3 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/caze/CaseFacadeEjb.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/caze/CaseFacadeEjb.java @@ -886,10 +886,6 @@ public String getLastReportedDistrictName(CaseCriteria caseCriteria, boolean exc } } - @Override - public List getExportListDetailed(CaseCriteria caseCriteria, Collection selectedRows, CaseExportType exportType, int first, int max, ExportConfigurationDto exportConfiguration, Language userLanguage) { - return List.of(); - } @RightsAllowed(UserRight._CASE_MERGE) diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/Ebs.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/Ebs.java index b4f49576975..21d04a34939 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/Ebs.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/Ebs.java @@ -45,7 +45,7 @@ import de.symeda.sormas.backend.location.Location; import de.symeda.sormas.backend.sormastosormas.entities.SormasToSormasShareable; import de.symeda.sormas.backend.sormastosormas.origin.SormasToSormasOriginInfo; -import de.symeda.sormas.backend.sormastosormas.share.outgoing.SormasToSormasShareInfo; +import de.symeda.sormas.backend.sormastosormas.share.shareinfo.SormasToSormasShareInfo; import de.symeda.sormas.backend.user.User; @Entity(name = "ebs") diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsFacadeEjb.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsFacadeEjb.java index f20ac27ef66..29c0898c309 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsFacadeEjb.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsFacadeEjb.java @@ -276,7 +276,7 @@ public EbsReferenceDto getReferenceByUuid(String uuid) { return toReferenceDto(service.getByUuid(uuid)); } - + @Override protected void selectDtoFields(CriteriaQuery cq, Root root) { } @@ -348,11 +348,6 @@ public List delete(List uuids, DeletionDetails deletionDetails) return deletedEbsUuids; } - @Override - public List restore(List uuids) { - return List.of(); - } - @Override protected void pseudonymizeDto(Ebs source, EbsDto dto, Pseudonymizer pseudonymizer) { @@ -974,11 +969,6 @@ public void updateExternalData(@Valid List externalData) throws service.updateExternalData(externalData); } - @Override - public Integer saveBulkEbs(List ebsUuidList, EbsDto updatedTempEbs) { - return 0; - } - @Override public boolean hasRegionAndDistrict(String ebsUuid) { return service.hasRegionAndDistrict(ebsUuid); diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsJurisdictionPredicateValidator.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsJurisdictionPredicateValidator.java index 66b4ef48372..9f33b78c545 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsJurisdictionPredicateValidator.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsJurisdictionPredicateValidator.java @@ -15,7 +15,12 @@ package de.symeda.sormas.backend.ebs; -import de.symeda.sormas.backend.event.*; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; + +import de.symeda.sormas.backend.ebs.EbsJoins; +import de.symeda.sormas.backend.ebs.EbsQueryContext; import de.symeda.sormas.backend.infrastructure.community.Community; import de.symeda.sormas.backend.infrastructure.district.District; import de.symeda.sormas.backend.infrastructure.region.Region; @@ -23,10 +28,6 @@ import de.symeda.sormas.backend.user.User; import de.symeda.sormas.backend.util.PredicateJurisdictionValidator; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; - public class EbsJurisdictionPredicateValidator extends PredicateJurisdictionValidator { private final EbsJoins joins; @@ -53,12 +54,12 @@ public static EbsJurisdictionPredicateValidator of(EbsQueryContext qc, Path user } @Override - public Predicate isRootInJurisdiction() { - return super.isRootInJurisdiction(); + protected Predicate isInJurisdiction() { + return super.isInJurisdiction(); } @Override - public Predicate isRootInJurisdictionOrOwned() { + protected Predicate isInJurisdictionOrOwned() { final Predicate reportedByCurrentUser = cb.and( cb.isNotNull(joins.getRoot().get(Ebs.REPORTING_USER)), @@ -72,7 +73,7 @@ public Predicate isRootInJurisdictionOrOwned() { ? cb.equal(joins.getRoot().get(Ebs.RESPONSIBLE_USER).get(User.ID), user.getId()) : cb.equal(joins.getRoot().get(Ebs.RESPONSIBLE_USER).get(User.ID), userPath.get(User.ID))); - return cb.or(reportedByCurrentUser, currentUserResponsible, this.isRootInJurisdiction()); + return cb.or(reportedByCurrentUser, currentUserResponsible, isInJurisdiction()); } @Override @@ -118,6 +119,7 @@ protected Predicate whenPointOfEntryLevel() { @Override protected Predicate whenLaboratoryLevel() { - return cb.disjunction(); + return null; } -} \ No newline at end of file + +} diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsService.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsService.java index 61c99f6fbe1..59922ca8d37 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsService.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/ebs/EbsService.java @@ -17,7 +17,6 @@ import de.symeda.sormas.api.Disease; import de.symeda.sormas.api.EditPermissionType; -import de.symeda.sormas.api.RequestContextHolder; import de.symeda.sormas.api.common.DeletionDetails; import de.symeda.sormas.api.document.DocumentRelatedEntityType; import de.symeda.sormas.api.ebs.*; @@ -40,8 +39,8 @@ import de.symeda.sormas.backend.share.ExternalShareInfoCountAndLatestDate; import de.symeda.sormas.backend.share.ExternalShareInfoService; import de.symeda.sormas.backend.sormastosormas.SormasToSormasFacadeEjb; -import de.symeda.sormas.backend.sormastosormas.share.outgoing.SormasToSormasShareInfoFacadeEjb; -import de.symeda.sormas.backend.sormastosormas.share.outgoing.SormasToSormasShareInfoService; +import de.symeda.sormas.backend.sormastosormas.share.shareinfo.SormasToSormasShareInfoFacadeEjb; +import de.symeda.sormas.backend.sormastosormas.share.shareinfo.SormasToSormasShareInfoService; import de.symeda.sormas.backend.user.User; import de.symeda.sormas.backend.user.UserService; import de.symeda.sormas.backend.util.*; @@ -59,7 +58,7 @@ @Stateless @LocalBean -public class EbsService extends AbstractCoreAdoService { +public class EbsService extends AbstractCoreAdoService { @EJB private CaseService caseService; @@ -84,7 +83,6 @@ public EbsService() { super(Ebs.class); } - @Override @SuppressWarnings("rawtypes") protected Predicate createRelevantDataFilter(CriteriaBuilder cb, CriteriaQuery cq, From from) { @@ -102,7 +100,7 @@ protected Predicate createRelevantDataFilter(CriteriaBuilder cb, CriteriaQuery c return filter; } - @Override + protected List referencesToBeFetched() { return Arrays.asList(Ebs.EBS_LOCATION); } @@ -126,12 +124,12 @@ public List getAllActiveUuids() { filter = CriteriaBuilderHelper.and(cb, filter, userFilter); } - if (RequestContextHolder.isMobileSync()) { - Predicate predicate = createLimitedChangeDateFilter(cb, from); - if (predicate != null) { - filter = CriteriaBuilderHelper.and(cb, filter, predicate); - } - } +// if (RequestContextHolder.isMobileSync()) { +// Predicate predicate = createLimitedChangeDateFilter(cb, from); +// if (predicate != null) { +// filter = CriteriaBuilderHelper.and(cb, filter, predicate); +// } +// } cq.where(filter); cq.select(from.get(Ebs.UUID)); @@ -183,7 +181,7 @@ public void setArchiveInExternalSurveillanceToolForEntities(List entityU List sharedEbsUuids = getSharedEbsUuids(entityUuids); if (!sharedEbsUuids.isEmpty()) { try { - externalSurveillanceToolGatewayFacade.sendEbsInternal(sharedEbsUuids, archived); + externalSurveillanceToolGatewayFacade.sendEbs(sharedEbsUuids, archived); } catch (ExternalSurveillanceToolException e) { throw new ExternalSurveillanceToolRuntimeException(e.getMessage(), e.getErrorCode()); } @@ -195,7 +193,7 @@ public List getSharedEbsUuids(List entityUuids) { List ebsIds = getEbsIds(entityUuids); List sharedEbsUuids = new ArrayList<>(); List ebsShareInfos = - externalShareInfoService.getShareCountAndLatestDate(ebsIds, ExternalShareInfo.EBS); + externalShareInfoService.getShareCountAndLatestDate(ebsIds, ExternalShareInfo.EBS); ebsShareInfos.forEach(shareInfo -> { if (shareInfo.getLatestStatus() != ExternalShareStatus.DELETED) { sharedEbsUuids.add(shareInfo.getAssociatedObjectUuid()); @@ -288,7 +286,6 @@ protected Predicate createUserFilterInternal(CriteriaBuilder cb, CriteriaQuery c return createUserFilter(new EbsQueryContext(cb, cq, from)); } - @Override protected EbsJoins toJoins(From adoPath) { return new EbsJoins(adoPath); } @@ -312,12 +309,12 @@ public Predicate createUserFilter(final EbsQueryContext queryContext, final EbsU final EbsJoins ebsJoins = queryContext.getJoins(); final From ebsJoin = queryContext.getRoot(); - if (RequestContextHolder.isMobileSync()) { - Predicate limitedChangeDatePredicate = CriteriaBuilderHelper.and(cb, createLimitedChangeDateFilter(cb, ebsJoin)); - if (limitedChangeDatePredicate != null) { - filter = CriteriaBuilderHelper.and(cb, filter, limitedChangeDatePredicate); - } - } +// if (RequestContextHolder.isMobileSync()) { +// Predicate limitedChangeDatePredicate = CriteriaBuilderHelper.and(cb, createLimitedChangeDateFilter(cb, ebsJoin)); +// if (limitedChangeDatePredicate != null) { +// filter = CriteriaBuilderHelper.and(cb, filter, limitedChangeDatePredicate); +// } +// } return filter; } @@ -331,15 +328,14 @@ public Predicate createChangeDateFilter(CriteriaBuilder cb, EbsJoins joins, Expr return addChangeDates(new ChangeDateFilterBuilder(cb, dateExpression), joins, false).build(); } - @Override protected > T addChangeDates(T builder, EbsJoins joins, boolean includeExtendedChangeDateFilters) { final From ebsFrom = joins.getRoot(); - builder = super.addChangeDates(builder, joins, includeExtendedChangeDateFilters).add(ebsFrom, Ebs.EBS_LOCATION); + builder = super.addChangeDates(builder, ebsFrom, includeExtendedChangeDateFilters).add(ebsFrom, Ebs.EBS_LOCATION); if (includeExtendedChangeDateFilters) { builder.add(ebsFrom, Ebs.SORMAS_TO_SORMAS_ORIGIN_INFO) - .add(ebsFrom, Ebs.SORMAS_TO_SORMAS_SHARES); + .add(ebsFrom, Ebs.SORMAS_TO_SORMAS_SHARES); } return builder; @@ -517,41 +513,37 @@ public Predicate createDefaultFilter(CriteriaBuilder cb, From root) { } - @Override - public EditPermissionType getEditPermissionType(Ebs ebs) { - - if (!inJurisdictionOrOwned(ebs)) { - return EditPermissionType.OUTSIDE_JURISDICTION; - } + public Predicate inJurisdictionOrOwned(CriteriaBuilder cb, CriteriaQuery cq, From from) { + return inJurisdictionOrOwned(new EbsQueryContext(cb, cq, from)); + } - return super.getEditPermissionType(ebs); + public Predicate inJurisdictionOrOwned(EbsQueryContext qc) { + return inJurisdictionOrOwned(qc, getCurrentUser()); + } + public boolean inJurisdictionOrOwned(Ebs event) { + return inJurisdictionOrOwned(event, getCurrentUser()); + } + public Predicate inJurisdictionOrOwned(EbsQueryContext qc, User user) { + return EbsJurisdictionPredicateValidator.of(qc, user).inJurisdictionOrOwned(); } - public boolean inJurisdiction(Ebs ebs) { + public boolean inJurisdictionOrOwned(Ebs ebs, User user) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(Boolean.class); Root root = cq.from(Ebs.class); - cq.multiselect(JurisdictionHelper.booleanSelector(cb, inJurisdiction(new EbsQueryContext(cb, cq, root), userService.getCurrentUser()))); + cq.multiselect(JurisdictionHelper.booleanSelector(cb, inJurisdictionOrOwned(new EbsQueryContext(cb, cq, root), user))); cq.where(cb.equal(root.get(Ebs.UUID), ebs.getUuid())); return em.createQuery(cq).getResultList().stream().anyMatch(aBoolean -> aBoolean); } - public Predicate inJurisdiction(EbsQueryContext qc, User user) { - return EbsJurisdictionPredicateValidator.of(qc, user).inJurisdiction(); - } - - @Override - public Predicate inJurisdictionOrOwned(CriteriaBuilder cb, CriteriaQuery cq, From from) { - return inJurisdictionOrOwned(new EbsQueryContext(cb, cq, from)); - } - - public Predicate inJurisdictionOrOwned(EbsQueryContext qc) { - return inJurisdictionOrOwned(qc, getCurrentUser()); - } - - public Predicate inJurisdictionOrOwned(EbsQueryContext qc, User user) { - return EbsJurisdictionPredicateValidator.of(qc, user).inJurisdictionOrOwned(); + public boolean inJurisdiction(Ebs ebs) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Boolean.class); + Root root = cq.from(Ebs.class); + cq.multiselect(JurisdictionHelper.booleanSelector(cb, inJurisdictionOrOwned(new EbsQueryContext(cb, cq, root), userService.getCurrentUser()))); + cq.where(cb.equal(root.get(Ebs.UUID), ebs.getUuid())); + return em.createQuery(cq).getResultList().stream().anyMatch(aBoolean -> aBoolean); } @Transactional(rollbackOn = Exception.class) @@ -582,6 +574,20 @@ public List getAllByCase(String caseUuid) { return em.createQuery(cq).getResultList(); } + @Override + public EditPermissionType isEditAllowed(Ebs event) { + + if (event.getSormasToSormasOriginInfo() != null && !event.getSormasToSormasOriginInfo().isOwnershipHandedOver()) { + return EditPermissionType.REFUSED; + } + + if (!inJurisdictionOrOwned(event) || sormasToSormasShareInfoService.isEbsOwnershipHandedOver(event)) { + return EditPermissionType.REFUSED; + } + + return super.getEditPermissionType(event); + } + public String getUuidByCaseUuidOrPersonUuid(String searchTerm) { if (StringUtils.isEmpty(searchTerm)) { @@ -606,11 +612,11 @@ public boolean hasRegionAndDistrict(String ebsUuid) { Join locationJoin = from.join(Ebs.EBS_LOCATION, JoinType.LEFT); cq.where( - CriteriaBuilderHelper.and( - cb, - cb.equal(from.get(AbstractDomainObject.UUID), ebsUuid), - cb.isNotNull(locationJoin.get(Location.REGION)), - cb.isNotNull(locationJoin.get(Location.DISTRICT)))); + CriteriaBuilderHelper.and( + cb, + cb.equal(from.get(AbstractDomainObject.UUID), ebsUuid), + cb.isNotNull(locationJoin.get(Location.REGION)), + cb.isNotNull(locationJoin.get(Location.DISTRICT)))); cq.select(cb.count(from)); return em.createQuery(cq).getSingleResult() > 0; @@ -622,4 +628,4 @@ protected boolean hasLimitedChangeDateFilterImplementation() { return true; } -} \ No newline at end of file +} diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/externalsurveillancetool/ExternalSurveillanceToolGatewayFacadeEjb.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/externalsurveillancetool/ExternalSurveillanceToolGatewayFacadeEjb.java index 42a84bd957f..416d67c034b 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/externalsurveillancetool/ExternalSurveillanceToolGatewayFacadeEjb.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/externalsurveillancetool/ExternalSurveillanceToolGatewayFacadeEjb.java @@ -297,6 +297,11 @@ private void doDeleteEbs(List events) throws ExternalSurveillanceToolExc } + @Override + public void deleteEbs(List events) throws ExternalSurveillanceToolException { + return; + } + private void sendDeleteRequest(DeleteParameters params) throws ExternalSurveillanceToolException { String serviceUrl = configFacade.getExternalSurveillanceToolGatewayUrl().trim(); @@ -310,6 +315,13 @@ private void sendDeleteRequest(DeleteParameters params) throws ExternalSurveilla logger.error("Failed to send delete request to external surveillance tool", e); throw new ExternalSurveillanceToolException(I18nProperties.getString(Strings.ExternalSurveillanceToolGateway_notificationErrorDeleting)); } + Response response = ClientBuilder.newBuilder() + .connectTimeout(30, TimeUnit.SECONDS) + .build() + .target(serviceUrl) + .path("delete") + .request() + .post(Entity.json(params)); int statusCode = response.getStatus(); diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/infrastructure/diseasecon/DiseaseConConFacadeEjb.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/infrastructure/diseasecon/DiseaseConConFacadeEjb.java new file mode 100644 index 00000000000..c68717ba051 --- /dev/null +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/infrastructure/diseasecon/DiseaseConConFacadeEjb.java @@ -0,0 +1,213 @@ +package de.symeda.sormas.backend.infrastructure.diseasecon; + + +import de.symeda.sormas.api.common.Page; +import de.symeda.sormas.api.i18n.Validations; +import de.symeda.sormas.api.infrastructure.diseasecon.*; +import de.symeda.sormas.api.infrastructure.facility.FacilityHelper; +import de.symeda.sormas.api.utils.SortProperty; +import de.symeda.sormas.backend.common.CriteriaBuilderHelper; +import de.symeda.sormas.backend.disease.DiseaseConfiguration; +import de.symeda.sormas.backend.feature.FeatureConfigurationFacadeEjb; +import de.symeda.sormas.backend.infrastructure.AbstractInfrastructureFacadeEjb; +import de.symeda.sormas.backend.infrastructure.facility.Facility; +import de.symeda.sormas.backend.infrastructure.facility.FacilityFacadeEjb; +import de.symeda.sormas.backend.user.UserService; +import de.symeda.sormas.backend.util.DtoHelper; +import de.symeda.sormas.backend.util.QueryHelper; +import org.apache.commons.collections.CollectionUtils; + +import javax.ejb.Stateless; +import javax.inject.Inject; +import javax.persistence.criteria.*; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Stateless(name = "DiseaseConFacade") +public class DiseaseConConFacadeEjb extends AbstractInfrastructureFacadeEjb implements DiseaseConFacade { + + public DiseaseConConFacadeEjb(){} + + @Inject + protected DiseaseConConFacadeEjb(DiseaseConService service, FeatureConfigurationFacadeEjb.FeatureConfigurationFacadeEjbLocal featureConfiguration, + UserService userService) { + super(DiseaseConfiguration.class, DiseaseConDto.class, service, featureConfiguration, userService, + Validations.importFacilityAlreadyExists); + } + + @Override + public List getIndexList(DiseaseConCriteria diseaseConCriteria, Integer first, Integer max, List sortProperties) { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(DiseaseConIndexDto.class); + Root disease = cq.from(DiseaseConfiguration.class); + + if (diseaseConCriteria != null) { + Predicate filter = service.buildCriteriaFilter(diseaseConCriteria, cb, disease); + if (filter != null) { + filter = CriteriaBuilderHelper.and(cb, filter); + cq.where(filter); + } + } + + if (CollectionUtils.isNotEmpty(sortProperties)) { + List order = new ArrayList<>(sortProperties.size()); + for (SortProperty sortProperty : sortProperties) { + Expression expression; + switch (sortProperty.propertyName) { + case DiseaseConfiguration.UUID: + case DiseaseConfiguration.DISEASE: + case DiseaseConfiguration.ACTIVE: + case DiseaseConfiguration.PRIMARY_DISEASE: + case DiseaseConfiguration.CASE_BASED: + case DiseaseConfiguration.FOLLOW_UP_ENABLED: + case DiseaseConfiguration.FOLLOW_UP_DURATION: + case DiseaseConfiguration.EXTENDED_CLASSIFICATION: + expression = disease.get(sortProperty.propertyName); + break; + default: + throw new IllegalArgumentException(sortProperty.propertyName); + } + order.add(sortProperty.ascending ? cb.asc(expression) : cb.desc(expression)); + } + cq.orderBy(order); + } else { + cq.orderBy( + cb.asc(disease.get(DiseaseConfiguration.DISEASE)) + ); + } + + cq.multiselect( + disease.get(DiseaseConfiguration.UUID), + disease.get(DiseaseConfiguration.DISEASE) + ); + + List diseaseConIndexDtoList = QueryHelper.getResultList(em, cq, first, max); + return diseaseConIndexDtoList; + } + + @Override + public long count(DiseaseConCriteria criteria) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + Root root = cq.from(DiseaseConfiguration.class); + + if (criteria != null) { + Predicate filter = service.buildCriteriaFilter(criteria, cb, root); + if (filter != null){ + cq.where(filter); + } + } + + + cq.select(cb.countDistinct(root)); + long totalCount = em.createQuery(cq).getSingleResult(); + return totalCount; + } + + @Override + public DiseaseConDto save(DiseaseConDto dto, boolean allowMerge) { + return super.save(dto, allowMerge); + } + + @Override + public List getReferencesByExternalId(String externalId, boolean includeArchivedEntities) { + return null; + } + + @Override + public Page getIndexPage(DiseaseConCriteria criteria, Integer offset, Integer size, List sortProperties) { + List diseaseConIndexDtoList = getIndexList(criteria, offset, size, sortProperties); + long totalElementCount = count(criteria); + return new Page<>(diseaseConIndexDtoList, offset, size, totalElementCount); + } + + @Override + public List getAllActiveAsReference() { + return service.getAllActive().stream().map(DiseaseConConFacadeEjb::toReferenceDto).collect(Collectors.toList()); + } + + @Override + protected void selectDtoFields(CriteriaQuery cq, Root root) { + + } + + @Override + protected DiseaseConfiguration fillOrBuildEntity(DiseaseConDto source, DiseaseConfiguration target, boolean checkChangeDate) { + target = DtoHelper.fillOrBuildEntity(source, target, DiseaseConfiguration::new, checkChangeDate); + + target.setDisease(source.getDisease()); + if (source.getFacilities() == null) { + source.setFacilities(new ArrayList<>()); + } else { + target.setFacilities(source.getFacilities().stream().map(facilityReferenceDto -> { + return mapDtoToEntity(facilityReferenceDto.getUuid()); + }).collect(Collectors.toSet())); + } + + return target; + } + + private Facility mapDtoToEntity(String dto) { + Facility facility = service.getFacilityByUuid(dto); + return facility; + } + + @Override + public DiseaseConDto toDto(DiseaseConfiguration source) { + + if (source == null) { + return null; + } + + DiseaseConDto target = new DiseaseConDto(); + DtoHelper.fillDto(target, source); + + target.setDisease(source.getDisease()); + target.setActive(source.getActive()); + target.setPrimaryDisease(source.getPrimaryDisease()); + target.setCaseBased(source.getCaseBased()); + target.setFollowUpEnabled(source.getFollowUpEnabled()); + target.setFollowUpDuration(source.getFollowUpDuration()); + target.setCaseFollowUpDuration(source.getCaseFollowUpDuration()); + target.setEventParticipantFollowUpDuration(source.getEventParticipantFollowUpDuration()); + target.setExtendedClassification(source.getExtendedClassification()); + target.setExtendedClassificationMulti(source.getExtendedClassificationMulti()); + //target.setAgeGroups(source.getAgeGroups()); + + if (source.getFacilities() != null) { + target.setFacilities(source.getFacilities().stream().map(FacilityFacadeEjb::toReferenceDto).collect(Collectors.toList())); + } + return target; + } + + public static DiseaseConReferenceDto toReferenceDto(DiseaseConfiguration entity) { + + if (entity == null) { + return null; + } + + return new DiseaseConReferenceDto( + entity.getUuid(), + FacilityHelper.buildFacilityString(entity.getUuid(), entity.getDisease().getName()), + null); + } + + @Override + public DiseaseConReferenceDto toRefDto(DiseaseConfiguration disease) { + return null; + } + + @Override + protected List findDuplicates(DiseaseConDto dto, boolean includeArchived) { + return null; + } + + @Override + public DiseaseConDto getByUuid(String uuid) { + DiseaseConfiguration diseaseDto = service.getByUuid(uuid); + return toDto(diseaseDto); + } + +} diff --git a/sormas-backend/src/main/java/de/symeda/sormas/backend/sample/PathogenTestFacadeEjb.java b/sormas-backend/src/main/java/de/symeda/sormas/backend/sample/PathogenTestFacadeEjb.java index 9542ab97586..7e11a6c1746 100644 --- a/sormas-backend/src/main/java/de/symeda/sormas/backend/sample/PathogenTestFacadeEjb.java +++ b/sormas-backend/src/main/java/de/symeda/sormas/backend/sample/PathogenTestFacadeEjb.java @@ -769,4 +769,23 @@ public long count(SampleCriteria sampleCriteria) { return count; } + @Override + public Boolean checkIfPathogenTestIsTheFirst(String sampleUuid, String pathogenTestUuid) { + //return false if sampleUuid or pathogenTestUuid is null + if (sampleUuid == null || pathogenTestUuid == null) { + return false; + } + + //get sample and its first pathogen test + Sample sample = sampleService.getByUuid(sampleUuid); + //get associated pathogen tests and Order by creation date and select first + PathogenTest firstPathogenTest = sample.getPathogenTests().stream().sorted((p1, p2) -> p1.getCreationDate().compareTo(p2.getCreationDate())).findFirst().orElse(null); + + //check if the first pathogen test is the same as the pathogen test + if (firstPathogenTest != null && firstPathogenTest.getUuid().equals(pathogenTestUuid)) { + return true; + } + + return false; + } } diff --git a/sormas-backend/src/main/resources/sql/sormas_schema.sql b/sormas-backend/src/main/resources/sql/sormas_schema.sql index 35c607e5b82..4677b755093 100644 --- a/sormas-backend/src/main/resources/sql/sormas_schema.sql +++ b/sormas-backend/src/main/resources/sql/sormas_schema.sql @@ -13531,6 +13531,57 @@ ALTER TABLE cases ADD COLUMN lastvaccinationdate date; INSERT INTO schema_version (version_number, comment) VALUES (590, 'Added last vaccination date for IDSR 53'); -- *** Insert new sql commands BEFORE this line. Remember to always consider _history tables. *** +-- *** Insert new sql commands BEFORE this line. Remember to always consider _history tables. *** +-- *** Insert new sql commands BEFORE this line. Remember to always consider _history tables. *** +-- *** Insert new sql commands BEFORE this line. Remember to always consider _history tables. + +-- Create the 'ebs' table without columns that cause circular dependencies +CREATE TABLE ebs ( + id BIGINT NOT NULL PRIMARY KEY, + uuid VARCHAR(36) NOT NULL UNIQUE, + changedate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + creationdate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ebstdate TIMESTAMP, + reportdatetime TIMESTAMP NOT NULL, + reportinguser_id BIGINT, + location_id BIGINT, + deleted BOOLEAN DEFAULT FALSE, + archiveundonereason VARCHAR(512), + change_user_id BIGINT, + deletionreason VARCHAR(255), + triageDate TIMESTAMP, + automaticScanningType VARCHAR(512), + manualScanningType VARCHAR(512), + scanningType VARCHAR(512), + descriptionOccurrence VARCHAR(512), + sourceName VARCHAR(512), + sourceUrl VARCHAR(512), + dateOnset TIMESTAMP, + personRegistering VARCHAR(512), + personDesignation VARCHAR(512), + personPhone VARCHAR(512), + other VARCHAR(512), + ebsLongitude DOUBLE PRECISION, + ebsLatitude DOUBLE PRECISION, + ebsLatLon DOUBLE PRECISION, + ebslocation_id BIGINT, + sourceInformation VARCHAR(255), + archived BOOLEAN DEFAULT FALSE, + sormasToSormasOriginInfo_id BIGINT, + categoryOfInformant VARCHAR(255), + informantName VARCHAR(512), + informantTel VARCHAR(20), + enddate TIMESTAMP, + responsibleuser_id BIGINT, + otherInformant VARCHAR(255), + otherdeletionreason varchar(255), + externalid varchar(512), + endofprocessingdate varchar(255), + externaltoken VARCHAR(512), + internaltoken TEXT, + signalverification_id BIGINT, + triaging_id BIGINT +); -- VibrioRiskFactors create new table CREATE TABLE riskfactor ( @@ -14269,7 +14320,50 @@ ALTER TABLE person RENAME COLUMN placeStayedtenToFourteenMonthsDistrict_id TO ps ALTER TABLE person RENAME COLUMN placeStayedtenToFourteenMonthsRegion_id TO pst14MonthsRegion_id; ALTER TABLE person RENAME COLUMN placeStayedtenToFourteenMonthsCountry_id TO pst14MonthsCountry_id; INSERT INTO schema_version(version_number, comment) VALUES (646, 'Renamed placeStayedtenToFourteenMonths fields in person'); +-- Create 'ebsAlert' table with a foreign key reference to 'ebs' +CREATE TABLE ebsAlert ( + id BIGINT NOT NULL PRIMARY KEY, + uuid VARCHAR(36) NOT NULL UNIQUE, + actionInitiated VARCHAR(255), + responseStatus VARCHAR(255), + responseDate DATE, + detailsResponseActivities VARCHAR(255), + detailsGiven VARCHAR(255), + alertIssued VARCHAR(3), + detailsAlertUsed VARCHAR(255), + alertdate DATE, + ebs_id BIGINT, + changedate TIMESTAMP NOT NULL, + creationdate TIMESTAMP NOT NULL, + change_user_id BIGINT, + FOREIGN KEY (change_user_id) REFERENCES users (id), + FOREIGN KEY (ebs_id) REFERENCES ebs (id) +); +-- Create 'riskAssessment' table with a foreign key reference to 'ebs' +CREATE TABLE riskAssessment ( + id BIGINT NOT NULL PRIMARY KEY, + uuid VARCHAR(36) NOT NULL UNIQUE, + morbidityMortality VARCHAR(3), + spreadProbability VARCHAR(3), + controlMeasures VARCHAR(3), + riskAssessment VARCHAR(255), + morbiditymortalitycomment VARCHAR(255), + spreadprobabilitycomment VARCHAR(255), + controlmeasurescomment VARCHAR(255), + assessmentdate DATE, + assessmenttime VARCHAR(255), + archived BOOLEAN DEFAULT FALSE, + sormasToSormasOriginInfo_id BIGINT, + externalid VARCHAR(512), + responsibleuser_id BIGINT, + changedate TIMESTAMP NOT NULL, + creationdate TIMESTAMP NOT NULL, + change_user_id BIGINT, + ebs_id BIGINT, + FOREIGN KEY (change_user_id) REFERENCES users (id), + FOREIGN KEY (ebs_id) REFERENCES ebs (id) +); ALTER TABLE person ADD COLUMN placeOfResidenceSameAsReportingVillage varchar(255); ALTER TABLE person ADD COLUMN residenceSinceWhenInMonths varchar(255); INSERT INTO schema_version(version_number, comment) VALUES (647, 'Added new fields to person'); @@ -14440,6 +14534,194 @@ ALTER TABLE symptoms ADD COLUMN skinrashnew VARCHAR(255); INSERT INTO schema_version (version_number, comment) VALUES (663, 'added nationality to persons and difficultyswallow to symptoms'); +-- Define the ebs table +CREATE TABLE ebs ( + id bigint not null, + uuid VARCHAR(36) NOT NULL UNIQUE, + changedate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + creationdate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ebstdate TIMESTAMP, + reportdatetime TIMESTAMP NOT NULL, + reportinguser_id BIGINT, + location_id BIGINT, + externaltoken VARCHAR(512), + internaltoken TEXT, + deleted BOOLEAN DEFAULT FALSE, + archiveundonereason VARCHAR(512), + change_user_id BIGINT, + deletionreason VARCHAR(255), + triageDate TIMESTAMP, + automaticScanningType VARCHAR(512), + manualScanningType VARCHAR(512), + scanningType VARCHAR(512), + descriptionOccurrence VARCHAR(512), + sourceName VARCHAR(512), + sourceUrl VARCHAR(512), + dateOnset TIMESTAMP, + personRegistering VARCHAR(512), + personDesignation VARCHAR(512), + personPhone VARCHAR(512), + other VARCHAR(512), + ebsLongitude DOUBLE PRECISION, + ebsLatitude DOUBLE PRECISION, + ebsLatLon DOUBLE PRECISION, + ebslocation_id BIGINT, + sourceInformation VARCHAR(255), + archived boolean DEFAULT false, + sormasToSormasOriginInfo_id bigint, + categoryOfInformant varchar(255), + informantName VARCHAR(512), + informantTel VARCHAR(20), + endofprocessingdate varchar(255), + enddate timestamp, + responsibleuser_id bigint, + otherdeletionreason varchar(255), + cases varchar(255), + death varchar(255), + triagingdecision varchar(255), + risklevel varchar(255), + externalid varchar(512), + triaging_id BIGINT, + primary key(id) +); + +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_reportinguser_id FOREIGN KEY (reportinguser_id) REFERENCES users (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_location_id FOREIGN KEY (location_id) REFERENCES location (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_ebslocation_id FOREIGN KEY (ebslocation_id) REFERENCES location (id); + +CREATE TABLE ebs_history ( + LIKE ebs INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES +); + + + +CREATE TABLE triaging ( + id bigint not null, + uuid VARCHAR(36) NOT NULL UNIQUE, + earlyWarning VARCHAR(3), + specificSignal VARCHAR(3), + signalCategory VARCHAR(255), + healthConcern VARCHAR(3), + categoryDetails VARCHAR(255), + occurrencePreviously VARCHAR(3), + triagingDecision VARCHAR(255), + decisionDate DATE, + referredTo VARCHAR(255), + changedate timestamp not null, + creationdate timestamp not null, + change_user_id BIGINT, + responsibleuser_id bigint, + triagingDecisionString varchar(255), + categoryDetailsString varchar(255), + outcomeSupervisor varchar(255), + notSignal boolean DEFAULT false, + humanCommunityCategoryDetailsString varchar(255), + humanFacilityCategoryDetailsString varchar(255), + humanLaboratoryCategoryDetailsString varchar(255), + animalCommunityCategoryDetailsString varchar(255), + animalFacilityCategoryDetailsString varchar(255), + environmentalCategoryDetailsString varchar(255), + poeCategoryDetailsString varchar(255), + categoryDetailsLevel varchar(255), + primary key(id) +); + +ALTER TABLE triaging ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_triaging_id FOREIGN KEY (triaging_id) REFERENCES triaging (id); + + +CREATE TABLE triaging_history ( + LIKE triaging INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES +); + + +CREATE TABLE signalVerification ( + id bigint not null, + verificationSent VARCHAR(3), + verified VARCHAR(3), + verificationSentDate DATE, + verificationCompleteDate DATE, + dateOfOccurrence DATE, + numberOfPersonAnimal VARCHAR(255), + numberOfDeath VARCHAR(255), + description VARCHAR(255), + whyNotVerify VARCHAR(255), + archived boolean DEFAULT false, + sormasToSormasOriginInfo_id bigint, + externalid varchar(512), + responsibleuser_id bigint, + changedate timestamp not null, + creationdate timestamp not null, + change_user_id BIGINT, + uuid VARCHAR(36) NOT NULL UNIQUE, + primary key(id) +); + +ALTER TABLE signalVerification ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users (id); +ALTER TABLE ebs ADD COLUMN signalVerification_id BIGINT; +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_signalVerification_id FOREIGN KEY (signalVerification_id) REFERENCES signalVerification (id); +CREATE TABLE signalVerification_history ( + LIKE signalVerification INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES +); + +CREATE TABLE riskAssessment( + id bigint not null, + uuid VARCHAR(36) NOT NULL UNIQUE, + morbidityMortality VARCHAR(3), + spreadProbability VARCHAR(3), + controlMeasures VARCHAR(3), + riskAssessment VARCHAR(255), + archived boolean DEFAULT false, + sormasToSormasOriginInfo_id bigint, + externalid varchar(512), + responsibleuser_id bigint, + morbiditymortalitycomment VARCHAR(255), + assessmentdate DATE, + assessmenttime varchar(255), + spreadprobabilitycomment VARCHAR(255), + controlmeasurescomment varchar(255), + changedate timestamp not null, + creationdate timestamp not null, + change_user_id BIGINT, + primary key(id) +); + +ALTER TABLE riskAssessment ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users (id); +ALTER TABLE ebs ADD COLUMN riskAssessment_id BIGINT; +ALTER TABLE riskAssessment ADD COLUMN ebs_id bigint; +ALTER TABLE riskAssessment ADD CONSTRAINT fk_riskAssessment_ebs_id FOREIGN KEY (ebs_id) REFERENCES ebs (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_riskAssessment_id FOREIGN KEY (riskAssessment_id) REFERENCES riskAssessment (id); +CREATE TABLE riskAssessment_history ( + LIKE riskAssessment INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES +); + +CREATE TABLE ebsAlert( + id bigint not null, + actionInitiated VARCHAR(255), + responseStatus VARCHAR(255), + responseDate DATE, + detailsResponseActivities VARCHAR(255), + detailsGiven VARCHAR(255), + alertUsed VARCHAR(3), + detailsAlertUsed varchar(255), + ebs_id bigint, + changedate timestamp not null, + creationdate timestamp not null, + change_user_id BIGINT, + uuid VARCHAR(36) NOT NULL UNIQUE, + primary key(id) +); + +ALTER TABLE ebs ADD COLUMN ebsAlert_id BIGINT; +ALTER TABLE ebsAlert ADD CONSTRAINT fk_ebs_change_user_id FOREIGN KEY (change_user_id) REFERENCES users (id); +ALTER TABLE ebsAlert ADD CONSTRAINT fk_ebsAlert_ebs_id FOREIGN KEY (ebs_id) REFERENCES ebs (id); +ALTER TABLE ebs ADD CONSTRAINT fk_ebs_ebsAlert_id FOREIGN KEY (ebsAlert_id) REFERENCES ebsAlert (id); + +CREATE TABLE ebsAlert_history ( + LIKE ebsAlert INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES +); +INSERT INTO schema_version (version_number, comment) VALUES (664, 'added ebs,triaging,signalverification,riskassessment and alert'); ALTER TABLE epidata ADD COLUMN waterUsedForDrinking VARCHAR(255); ALTER TABLE epidata ADD COLUMN waterUsedNotForDrinking VARCHAR(255); @@ -14607,6 +14889,8 @@ ALTER TABLE samples ADD COLUMN labLocal VARCHAR(255); ALTER TABLE samples ADD COLUMN labLocalDetails VARCHAR(255); INSERT INTO schema_version(version_number, comment) VALUES (672, 'Added labLocal, labLocalDetails to samples'); +ALTER TABLE triaging ADD COLUMN potentialrisk VARCHAR(3); +INSERT INTO schema_version (version_number, comment) VALUES (673, 'added potential risk to ebs'); UPDATE userroles SET hasoptionalhealthfacility = true WHERE caption = 'Case Officer'; UPDATE userroles SET hasoptionalhealthfacility = true WHERE caption = 'Contact Officer'; @@ -14616,6 +14900,16 @@ UPDATE userroles SET hasoptionalhealthfacility = true WHERE caption = 'Hospital UPDATE userroles SET hasoptionalhealthfacility = true WHERE caption = 'Surveillance Officer'; INSERT INTO schema_version (version_number, comment) VALUES (674, 'updated hasoptionalhealthfacility for userroles'); +-- 2024-06-14 added alertdate to alert table +ALTER TABLE triaging ADD COLUMN supervisorreview VARCHAR(3); +ALTER TABLE triaging ADD COLUMN referred VARCHAR(3); +-- 2024-06-14 added alertdate to alert table +ALTER TABLE ebsAlert ADD COLUMN alertdate DATE; +-- 2024-06-14 added alertdate to alert table +ALTER TABLE signalVerification ADD numberOfPersonCases VARCHAR(255); +ALTER TABLE signalVerification ADD numberOfDeathPerson VARCHAR(255); +INSERT INTO schema_version (version_number, comment) VALUES (675, 'added new ebs related fields'); + ALTER TABLE samples ADD COLUMN ipsampletestresultsstring VARCHAR(512); ALTER TABLE samples ADD COLUMN selectedresultigm VARCHAR(55); ALTER TABLE samples ADD COLUMN selectedresultprnt VARCHAR(55); @@ -14651,6 +14945,34 @@ ALTER TABLE cases ADD COLUMN patientsex varchar(255); INSERT INTO schema_version (version_number, comment) VALUES (679, 'Added Mpox person data to cases'); +-- 2024-06-18 added alertdate to alert table +ALTER TABLE ebsAlert RENAME COLUMN alertUsed TO alertIssued; +INSERT INTO schema_version (version_number, comment) VALUES (680, 'rename alert used to alert issued fields'); +ALTER TABLE triaging ADD animalLaboratoryCategoryDetailsString varchar(255); +INSERT INTO schema_version (version_number, comment) VALUES (681, 'rename alert used to alert issued fields'); +ALTER TABLE triaging ADD humanCommunityCategoryDetails varchar(255); +INSERT INTO schema_version (version_number, comment) VALUES (682, 'rename alert used to alert issued fields'); +ALTER TABLE triaging Drop humanCommunityCategoryDetailsString; +ALTER TABLE triaging Drop humanFacilityCategoryDetailsString ; +ALTER TABLE triaging Drop humanLaboratoryCategoryDetailsString; +ALTER TABLE triaging Drop animalCommunityCategoryDetailsString; +ALTER TABLE triaging Drop animalFacilityCategoryDetailsString ; +ALTER TABLE triaging Drop environmentalCategoryDetailsString ; +ALTER TABLE triaging Drop poeCategoryDetailsString; +ALTER TABLE triaging ADD COLUMN humanFacilityCategoryDetails VARCHAR(255); +ALTER TABLE triaging ADD COLUMN humanLaboratoryCategoryDetails VARCHAR(255); +ALTER TABLE triaging ADD COLUMN animalCommunityCategoryDetails VARCHAR(255); +ALTER TABLE triaging ADD COLUMN animalFacilityCategoryDetails VARCHAR(255); +ALTER TABLE triaging ADD COLUMN environmentalCategoryDetails VARCHAR(255); +ALTER TABLE triaging ADD COLUMN poeCategoryDetails VARCHAR(255); +INSERT INTO schema_version (version_number, comment) VALUES (683, 'rename alert used to alert issued fields'); + +ALTER TABLE triaging ADD COLUMN animalLaboratoryCategoryDetails VARCHAR(255); +INSERT INTO schema_version (version_number, comment) VALUES (684, 'rename alert used to alert issued fields'); + +ALTER TABLE ebs ADD COLUMN otherInformant VARCHAR(255); +INSERT INTO schema_version (version_number, comment) VALUES (685, 'rename alert used to alert issued fields'); + ALTER TABLE samples_history ALTER COLUMN samplepurpose DROP NOT NULL; ALTER TABLE epidata DROP COLUMN yearofvaccinationcovid; ALTER TABLE epidata DROP COLUMN yearofvaccination; @@ -14800,99 +15122,11 @@ CREATE TRIGGER versioning_trigger ALTER TABLE forms_form_fields_history OWNER TO sormas_user; INSERT INTO schema_version (version_number, comment) VALUES (696, 'Added forms_form_fields table'); --- Create the 'ebs' table without columns that cause circular dependencies -CREATE TABLE ebs ( - id BIGINT NOT NULL PRIMARY KEY, - uuid VARCHAR(36) NOT NULL UNIQUE, - changedate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - creationdate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - ebstdate TIMESTAMP, - reportdatetime TIMESTAMP NOT NULL, - reportinguser_id BIGINT, - location_id BIGINT, - deleted BOOLEAN DEFAULT FALSE, - archiveundonereason VARCHAR(512), - change_user_id BIGINT, - deletionreason VARCHAR(255), - triageDate TIMESTAMP, - automaticScanningType VARCHAR(512), - manualScanningType VARCHAR(512), - scanningType VARCHAR(512), - descriptionOccurrence VARCHAR(512), - sourceName VARCHAR(512), - sourceUrl VARCHAR(512), - dateOnset TIMESTAMP, - personRegistering VARCHAR(512), - personDesignation VARCHAR(512), - personPhone VARCHAR(512), - other VARCHAR(512), - ebsLongitude DOUBLE PRECISION, - ebsLatitude DOUBLE PRECISION, - ebsLatLon DOUBLE PRECISION, - ebslocation_id BIGINT, - sourceInformation VARCHAR(255), - archived BOOLEAN DEFAULT FALSE, - sormasToSormasOriginInfo_id BIGINT, - categoryOfInformant VARCHAR(255), - informantName VARCHAR(512), - informantTel VARCHAR(20), - enddate TIMESTAMP, - responsibleuser_id BIGINT, - otherInformant VARCHAR(255), - otherdeletionreason varchar(255), - externalid varchar(512), - endofprocessingdate varchar(255), - externaltoken VARCHAR(512), - internaltoken TEXT, - signalverification_id BIGINT, - triaging_id BIGINT -); - --- Create 'ebsAlert' table with a foreign key reference to 'ebs' -CREATE TABLE ebsAlert ( - id BIGINT NOT NULL PRIMARY KEY, - uuid VARCHAR(36) NOT NULL UNIQUE, - actionInitiated VARCHAR(255), - responseStatus VARCHAR(255), - responseDate DATE, - detailsResponseActivities VARCHAR(255), - detailsGiven VARCHAR(255), - alertIssued VARCHAR(3), - detailsAlertUsed VARCHAR(255), - alertdate DATE, - ebs_id BIGINT, - changedate TIMESTAMP NOT NULL, - creationdate TIMESTAMP NOT NULL, - change_user_id BIGINT, - FOREIGN KEY (change_user_id) REFERENCES users (id), - FOREIGN KEY (ebs_id) REFERENCES ebs (id) -); - --- Create 'riskAssessment' table with a foreign key reference to 'ebs' -CREATE TABLE riskAssessment ( - id BIGINT NOT NULL PRIMARY KEY, - uuid VARCHAR(36) NOT NULL UNIQUE, - morbidityMortality VARCHAR(3), - spreadProbability VARCHAR(3), - controlMeasures VARCHAR(3), - riskAssessment VARCHAR(255), - morbiditymortalitycomment VARCHAR(255), - spreadprobabilitycomment VARCHAR(255), - controlmeasurescomment VARCHAR(255), - assessmentdate DATE, - assessmenttime VARCHAR(255), - archived BOOLEAN DEFAULT FALSE, - sormasToSormasOriginInfo_id BIGINT, - externalid VARCHAR(512), - responsibleuser_id BIGINT, - changedate TIMESTAMP NOT NULL, - creationdate TIMESTAMP NOT NULL, - change_user_id BIGINT, - ebs_id BIGINT, - FOREIGN KEY (change_user_id) REFERENCES users (id), - FOREIGN KEY (ebs_id) REFERENCES ebs (id) -); - +-- *** Insert new sql commands BEFORE this line. Remember to always consider _history tables. *** +ALTER TABLE signalVerification ALTER COLUMN verified TYPE VARCHAR(20); +INSERT INTO schema_version (version_number, comment) VALUES (694, 'updated the verified field'); +ALTER TABLE signalVerification ALTER COLUMN description TYPE TEXT; +INSERT INTO schema_version (version_number, comment) VALUES (695, 'updated the description field'); -- Create 'signalVerification' table with a foreign key reference to 'ebs' CREATE TABLE signalVerification ( id BIGINT NOT NULL PRIMARY KEY, @@ -14985,4 +15219,4 @@ CREATE TABLE ebsAlert_history ( ); -- Insert version information -INSERT INTO schema_version (version_number, comment) VALUES (697, 'Added ebs and supporting entities'); \ No newline at end of file +INSERT INTO schema_version (version_number, comment) VALUES (493, 'Added ebs and supporting entities'); \ No newline at end of file diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsAlertResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsAlertResource.java new file mode 100644 index 00000000000..9ef7d424867 --- /dev/null +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsAlertResource.java @@ -0,0 +1,72 @@ +/* + * SORMAS® - Surveillance Outbreak Response Management & Analysis System + * Copyright © 2016-2023 Helmholtz-Zentrum für Infektionsforschung GmbH (HZI) + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.symeda.sormas.rest; + +import java.util.Date; +import java.util.List; +import java.util.function.UnaryOperator; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import de.symeda.sormas.api.FacadeProvider; +import de.symeda.sormas.api.PushResult; +import de.symeda.sormas.api.ebs.EbsAlertDto; + +@Path("/ebsAlert") +@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") +@Consumes(MediaType.APPLICATION_JSON + "; charset=UTF-8") +public class EbsAlertResource extends EntityDtoResource { + + @GET + @Path("/all/{since}/{size}/{lastSynchronizedUuid}") + public List getAllAlerts(@PathParam("since") long since) { + return FacadeProvider.getAlertFacade().getAllAfter(new Date(since)); + } + + @GET + @Path("/{uuid}") + public EbsAlertDto getByUuid(@PathParam("uuid") String uuid) { + return FacadeProvider.getAlertFacade().getAlertByUuid(uuid, true); + } + + @GET + @Path("/uuids") + public List getAllActiveUuids() { + return FacadeProvider.getAlertFacade().getAllActiveUuids(); + } + + public UnaryOperator getSave() { + return FacadeProvider.getAlertFacade()::saveAlert; + } + + @POST + @Path("/push") + public List postTasks(@Valid List dtos) { + List result = savePushedDto(dtos, FacadeProvider.getAlertFacade()::saveAlert); + return result; + } + +// public Response postEntityDtos(List ebaDtos) { +// return super.postEntityDtos(ebaDtos); +// } +} diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsResource.java new file mode 100644 index 00000000000..4225e9b1b27 --- /dev/null +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/EbsResource.java @@ -0,0 +1,158 @@ +/* + * SORMAS® - Surveillance Outbreak Response Management & Analysis System + * Copyright © 2016-2023 Helmholtz-Zentrum für Infektionsforschung GmbH (HZI) + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.symeda.sormas.rest; + +import java.util.Date; +import java.util.List; +import java.util.function.UnaryOperator; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import de.symeda.sormas.api.FacadeProvider; +import de.symeda.sormas.api.PushResult; +import de.symeda.sormas.api.caze.CriteriaWithSorting; +import de.symeda.sormas.api.common.DeletionDetails; +import de.symeda.sormas.api.common.DeletionReason; +import de.symeda.sormas.api.common.Page; +import de.symeda.sormas.api.ebs.EbsCriteria; +import de.symeda.sormas.api.ebs.EbsDto; +import de.symeda.sormas.api.ebs.EbsIndexDto; +import de.symeda.sormas.api.externaldata.ExternalDataDto; +import de.symeda.sormas.api.externaldata.ExternalDataUpdateException; +import io.swagger.v3.oas.annotations.parameters.RequestBody; + +@Path("/ebs") +@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") +@Consumes(MediaType.APPLICATION_JSON + "; charset=UTF-8") +public class EbsResource extends EntityDtoResource { + + @GET + @Path("/all/{since}") + public List getAllEvents(@PathParam("since") long since) { + return FacadeProvider.getEbsFacade().getAllAfter(new Date(since)); + } + + @GET + @Path("/all/{since}/{size}/{lastSynchronizedUuid}") + public List getAllEvents( + @PathParam("since") long since, + @PathParam("size") int size, + @PathParam("lastSynchronizedUuid") String lastSynchronizedUuid) { + return FacadeProvider.getEbsFacade().getAllAfter(new Date(since), size, lastSynchronizedUuid); + } + + /** + * This method returns the eventDto that correspond to the given uuid. + * The return eventDto has the superordinateEvent of type EventDetailedReferenceDto. + * + * @param uuid + * @return + * The return eventDto has the superordinateEvent of type EventDetailedReferenceDto + */ + @GET + @Path("/{uuid}") + public EbsDto getByUuid(@PathParam("uuid") String uuid) { + return FacadeProvider.getEbsFacade().getEbsByUuid(uuid, true); + } + + @POST + @Path("/query") + public List getByUuids(List uuids) { + return FacadeProvider.getEbsFacade().getByUuids(uuids); + } + + @GET + @Path("/uuids") + public List getAllActiveUuids() { + return FacadeProvider.getEbsFacade().getAllActiveUuids(); + } + + @GET + @Path("/archived/{since}") + public List getArchivedUuidsSince(@PathParam("since") long since) { + return FacadeProvider.getEbsFacade().getArchivedUuidsSince(new Date(since)); + } + + @GET + @Path("/deleted/{since}") + public List getDeletedUuidsSince(@PathParam("since") long since) { + return FacadeProvider.getEbsFacade().getDeletedUuidsSince(new Date(since)); + } + + @GET + @Path("/obsolete/{since}") + public List getObsoleteUuidsSince(@PathParam("since") long since) { + return FacadeProvider.getEbsFacade().getObsoleteUuidsSince(new Date(since)); + } + + /** + * + * @param criteriaWithSorting + * - The criteria object inside criteriaWithSorting cannot be null. Use an empty criteria instead. + * @param offset + * @param size + * @return + */ + @POST + @Path("/indexList") + public Page getIndexList( + @RequestBody CriteriaWithSorting criteriaWithSorting, + @QueryParam("offset") int offset, + @QueryParam("size") int size) { + return FacadeProvider.getEbsFacade().getIndexPage(criteriaWithSorting.getCriteria(), offset, size, criteriaWithSorting.getSortProperties()); + } + + @POST + @Path("/externalData") + public Response updateExternalData(List externalData) { + try { + FacadeProvider.getEbsFacade().updateExternalData(externalData); + return Response.status(Response.Status.OK).build(); + } catch (ExternalDataUpdateException e) { + return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); + } + } + + @POST + @Path("/delete") + public List delete(List uuids) { + return FacadeProvider.getEbsFacade().delete(uuids, new DeletionDetails(DeletionReason.OTHER_REASON, "Deleted via ReST call")); + } + + public UnaryOperator getSave() { + return FacadeProvider.getEbsFacade()::save; + } + + @POST + @Path("/push") + public List postTasks(@Valid List dtos) { + List result = savePushedDto(dtos, FacadeProvider.getEbsFacade()::save); + return result; + } + +// public Response postEntityDtos(List ebaDtos) { +// return super.postEntityDtos(ebaDtos); +// } +} diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/RiskAssessmentResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/RiskAssessmentResource.java new file mode 100644 index 00000000000..78a6e440ca6 --- /dev/null +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/RiskAssessmentResource.java @@ -0,0 +1,73 @@ +/* + * SORMAS® - Surveillance Outbreak Response Management & Analysis System + * Copyright © 2016-2023 Helmholtz-Zentrum für Infektionsforschung GmbH (HZI) + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package de.symeda.sormas.rest; + +import java.util.Date; +import java.util.List; +import java.util.function.UnaryOperator; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import de.symeda.sormas.api.FacadeProvider; +import de.symeda.sormas.api.PushResult; +import de.symeda.sormas.api.ebs.RiskAssessmentDto; + +@Path("/riskassessment") +@Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8") +@Consumes(MediaType.APPLICATION_JSON + "; charset=UTF-8") +public class RiskAssessmentResource extends EntityDtoResource { + + @GET + @Path("/all/{since}/{size}/{lastSynchronizedUuid}") + public List getAllRisks(@PathParam("since") long since) { + return FacadeProvider.getRiskAssessmentFacade().getAllAfter(new Date(since)); + } + + @GET + @Path("/{uuid}") + public RiskAssessmentDto getByUuid(@PathParam("uuid") String uuid) { + return FacadeProvider.getRiskAssessmentFacade().getRiskByUuid(uuid, true); + } + + @GET + @Path("/uuids") + public List getAllActiveUuids() { + return FacadeProvider.getRiskAssessmentFacade().getAllActiveUuids(); + } + + public UnaryOperator getSave() { + return FacadeProvider.getRiskAssessmentFacade()::save; + } + + @POST + @Path("/push") + public List postTasks(@Valid List dtos) { + List result = savePushedDto(dtos, FacadeProvider.getRiskAssessmentFacade()::save); + return result; + } + +// @Override +// public Response postEntityDtos(List ebaDtos) { +// return super.postEntityDtos(ebaDtos); +// } +} diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/EbsAlertResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/EbsAlertResource.java index 2443da7982a..566afacef40 100644 --- a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/EbsAlertResource.java +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/EbsAlertResource.java @@ -58,4 +58,4 @@ public UnaryOperator getSave() { public Response postEntityDtos(List ebaDtos) { return super.postEntityDtos(ebaDtos); } -} \ No newline at end of file +} diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/ExternalVisitsResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/ExternalVisitsResource.java index 59744f2e8da..ae5a1109bc7 100644 --- a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/ExternalVisitsResource.java +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/ExternalVisitsResource.java @@ -30,7 +30,6 @@ import javax.ws.rs.core.Response; import de.symeda.sormas.api.FacadeProvider; -import de.symeda.sormas.api.event.EventDto; import de.symeda.sormas.api.person.JournalPersonDto; import de.symeda.sormas.api.person.PersonFollowUpEndDto; import de.symeda.sormas.api.person.PersonSymptomJournalStatusDto; @@ -106,6 +105,7 @@ public boolean postSymptomJournalStatus(@PathParam("personUuid") String personUu } @POST + @Path("/") @Operation(summary = "Save visits", description = "Upload visits with all symptom and disease related data to SORMAS.") @Override public Response postEntityDtos(List dtos) { diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/VisitResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/VisitResource.java index 16e817142a6..ba01a276618 100644 --- a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/VisitResource.java +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/VisitResource.java @@ -19,7 +19,6 @@ import java.util.List; import java.util.function.UnaryOperator; -import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -32,15 +31,7 @@ import de.symeda.sormas.api.FacadeProvider; import de.symeda.sormas.api.caze.CriteriaWithSorting; -import de.symeda.sormas.api.common.DeletionDetails; -import de.symeda.sormas.api.common.DeletionReason; import de.symeda.sormas.api.common.Page; -import de.symeda.sormas.api.ebs.EbsCriteria; -import de.symeda.sormas.api.ebs.EbsDto; -import de.symeda.sormas.api.ebs.EbsIndexDto; -import de.symeda.sormas.api.ebs.RiskAssessmentDto; -import de.symeda.sormas.api.externaldata.ExternalDataDto; -import de.symeda.sormas.api.externaldata.ExternalDataUpdateException; import de.symeda.sormas.api.visit.VisitCriteria; import de.symeda.sormas.api.visit.VisitDto; import de.symeda.sormas.api.visit.VisitIndexDto; diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/WeeklyReportResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/WeeklyReportResource.java index e4380d0f80d..5a05bc181f6 100644 --- a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/WeeklyReportResource.java +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/WeeklyReportResource.java @@ -31,7 +31,6 @@ import javax.ws.rs.core.SecurityContext; import de.symeda.sormas.api.FacadeProvider; -import de.symeda.sormas.api.ebs.EbsAlertDto; import de.symeda.sormas.api.report.WeeklyReportDto; import de.symeda.sormas.rest.resources.base.EntityDtoResource; diff --git a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/base/EntityDtoResource.java b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/base/EntityDtoResource.java index 328e1ba579f..932cd530740 100644 --- a/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/base/EntityDtoResource.java +++ b/sormas-rest/src/main/java/de/symeda/sormas/rest/resources/base/EntityDtoResource.java @@ -93,18 +93,18 @@ private PostResponse getPostResultError(Exception e) { * See https://github.com/swagger-api/swagger-core/issues/3916 */ @Operation(summary = "Create or update one or multiple entities.", - description = "A uuid will be generated for any entity that doesn't have one yet. " - + "Posting entities without uuid multiple times will also create them multiple times.") + description = "A uuid will be generated for any entity that doesn't have one yet. " + + "Posting entities without uuid multiple times will also create them multiple times.") @ApiResponses(value = { - @ApiResponse(responseCode = "207", - description = "Array of responses, matching the posted array of entities. " - + "Provides an HTML status code for every entity and an optional body (e.g. a string with an error message).", - content = { - @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = PostResponse.class))) }), - @ApiResponse(description = "When the request body has one or no entry. " - + "The status code of the response entry matches the response code and may have an optional body (e.g. a string with an error message).", - content = { - @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = PostResponse.class))) }) }) + @ApiResponse(responseCode = "207", + description = "Array of responses, matching the posted array of entities. " + + "Provides an HTML status code for every entity and an optional body (e.g. a string with an error message).", + content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = PostResponse.class))) }), + @ApiResponse(description = "When the request body has one or no entry. " + + "The status code of the response entry matches the response code and may have an optional body (e.g. a string with an error message).", + content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = PostResponse.class))) }) }) @POST @Path("/push") public Response postEntityDtos(@Valid List dtos) { @@ -113,4 +113,4 @@ public Response postEntityDtos(@Valid List dtos) { public abstract UnaryOperator getSave(); -} \ No newline at end of file +} diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/caze/CaseDataView.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/caze/CaseDataView.java index 798d4c1828b..adcd378f515 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/caze/CaseDataView.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/caze/CaseDataView.java @@ -37,10 +37,12 @@ import de.symeda.sormas.api.vaccination.VaccinationCriteria; import de.symeda.sormas.ui.ControllerProvider; import de.symeda.sormas.ui.UserProvider; +import de.symeda.sormas.ui.ViewModelProviders; import de.symeda.sormas.ui.caze.messaging.SmsListComponent; import de.symeda.sormas.ui.caze.surveillancereport.SurveillanceReportListComponent; import de.symeda.sormas.ui.docgeneration.QuarantineOrderDocumentsComponent; import de.symeda.sormas.ui.document.DocumentListComponent; +import de.symeda.sormas.ui.entitymap.DashboardMapComponent; import de.symeda.sormas.ui.events.eventLink.EventListComponent; import de.symeda.sormas.ui.externalsurveillanceservice.ExternalSurveillanceServiceGateway; import de.symeda.sormas.ui.immunization.immunizationlink.ImmunizationListComponent; @@ -77,6 +79,7 @@ public class CaseDataView extends AbstractCaseView { public static final String DOCUMENTS_LOC = "documents"; private static final long serialVersionUID = -1L; private CommitDiscardWrapperComponent editComponent; + public static final String SAMPLES_LOC = "samples"; public static final String CASE_MAP = "map"; private CaseCriteria criteria; diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/AbstractEbsView.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/AbstractEbsView.java index ed69e681a16..420ee5f90e1 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/AbstractEbsView.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/AbstractEbsView.java @@ -53,7 +53,7 @@ protected AbstractEbsView(String viewName,String currentView) { this.currentView = currentView; } - + @Override protected CoreFacade getEditPermissionFacade() { return FacadeProvider.getEbsFacade(); } diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsAlertView.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsAlertView.java index 15373df61f4..f21f00d8203 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsAlertView.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsAlertView.java @@ -50,7 +50,7 @@ protected void initView(String params) { EbsDto ebsDto = ControllerProvider.getEbsController().findEbs(getEbsRef().getUuid()); if (ebsAlertDto.isEmpty()) { ControllerProvider.getEbsController().createAlertComponent(getEbsRef().getUuid(), - UserProvider.getCurrent().hasUserRight(UserRight.EVENT_EDIT)); + isEditAllowed() && UserProvider.getCurrent().hasUserRight(UserRight.EVENT_EDIT)); } addButton = ButtonHelper.createIconButton( diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsDataForm.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsDataForm.java index 9efa2b7e5e7..8146b724981 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsDataForm.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/ebs/EbsDataForm.java @@ -178,7 +178,7 @@ protected void addFields() { TextField personPhone = addField(EbsDto.PERSON_PHONE, TextField.class); personPhone .addValidator(new EbsPhoneNumberValidator(I18nProperties.getValidationError(Validations.validPhoneNumber, personPhone.getCaption()))); - addField(EbsDto.EBS_LOCATION, new LocationEditForm(fieldVisibilityCheckers, createFieldAccessCheckers(isPseudonymized, false))) + addField(EbsDto.EBS_LOCATION, new LocationEditForm(fieldVisibilityCheckers, createFieldAccessCheckers(isPseudonymized, false), true)) .setCaption(null); locationForm = (LocationEditForm) getFieldGroup().getField(EbsDto.EBS_LOCATION); diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/location/LocationEditForm.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/location/LocationEditForm.java index 54c62f3cadd..b4e005908d2 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/location/LocationEditForm.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/location/LocationEditForm.java @@ -808,6 +808,14 @@ public void hideForEbsForm() { // getField(LocationDto.POSTAL_CODE).setVisible(false); } + //create a function to hide fields in ebs + public void hideForEbsForm() { + setVisible(false, LocationDto.STREET, LocationDto.ADDITIONAL_INFORMATION,LocationDto.HOUSE_NUMBER,LocationDto.AREA_TYPE,LocationDto.POSTAL_CODE); + getField(LocationDto.HOUSE_NUMBER).setVisible(false); + getField(LocationDto.AREA_TYPE).setVisible(false); + getField(LocationDto.POSTAL_CODE).setVisible(false); + } + public void setCountryDisabledWithHint(String hint) { country.setEnabled(false); Label infoLabel = new Label(VaadinIcons.INFO_CIRCLE.getHtml(), ContentMode.HTML); diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/AbstractEditForm.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/AbstractEditForm.java index 157b0cd1730..5eb5c0ac8bd 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/AbstractEditForm.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/AbstractEditForm.java @@ -179,6 +179,26 @@ protected AbstractEditForm( } } + protected AbstractEditForm( + Class type, + String propertyI18nPrefix, + boolean addFields, + FieldVisibilityCheckers fieldVisibilityCheckers, + UiFieldAccessCheckers fieldAccessCheckers, + boolean isEditAllowed) { + + super(type, propertyI18nPrefix, new SormasFieldGroupFieldFactory(fieldVisibilityCheckers, fieldAccessCheckers, isEditAllowed), false); + this.fieldVisibilityCheckers = fieldVisibilityCheckers; + this.fieldAccessCheckers = fieldAccessCheckers; + + getFieldGroup().addCommitHandler(this); + setWidth(900, Unit.PIXELS); + + if (addFields) { + addFields(); + } + } + protected AbstractEditForm( Class type, String propertyI18nPrefix, diff --git a/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/VaadinUiUtil.java b/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/VaadinUiUtil.java index 5a48a00adcc..b846aa33e25 100644 --- a/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/VaadinUiUtil.java +++ b/sormas-ui/src/main/java/de/symeda/sormas/ui/utils/VaadinUiUtil.java @@ -205,6 +205,12 @@ public Class getType() { }); } + public static void setupActionColumn(Grid.Column column) { + column.setRenderer(new HtmlRenderer()); + column.setWidth(20); + column.setSortable(false); + column.setHeaderCaption(""); + } public static Window showConfirmationPopup( String caption, diff --git a/sormas-ui/src/main/webapp/VAADIN/themes/sormas/styles.css b/sormas-ui/src/main/webapp/VAADIN/themes/sormas/styles.css index 76c8ada3642..d1587a5f8af 100644 --- a/sormas-ui/src/main/webapp/VAADIN/themes/sormas/styles.css +++ b/sormas-ui/src/main/webapp/VAADIN/themes/sormas/styles.css @@ -15594,7 +15594,7 @@ div.v-layout.v-horizontal.v-widget { } .sormas .moderate-risk-assessment { - border: 3px solid #FFFF00 !important; + border: 3px solid #FEC100 !important; } .sormas .low-risk-assessment { @@ -15616,17 +15616,13 @@ div.v-layout.v-horizontal.v-widget { } .sormas .moderate-risk-assessment .v-window-outerheader { - background: #FFFF00 !important; + background: #FEC100 !important; } .sormas .low-risk-assessment .v-window-outerheader { background: #93D150 !important; } -.sormas #manualScanningType { - width: 20em !important; -} - .sormas .window-text { text-wrap: wrap !important; font-size: 20px !important; @@ -15715,9 +15711,6 @@ div.v-layout.v-horizontal.v-widget { text-transform: uppercase; border-color: #005A9C; box-shadow: none; - height: fit-content; - text-wrap: wrap; - padding: 2px 5px; } .sormas .v-button.v-button-link, .sormas .sormas .v-button-link.v-link.v-link-button {