diff --git a/backend/pom.xml b/backend/pom.xml index e816504c..09481141 100755 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -7,6 +7,7 @@ 2.6.9 + com.Adapter icare 0.0.1-SNAPSHOT @@ -114,12 +115,6 @@ pact-jvm-provider-junit_2.10 2.4.20 - - junit - junit - 4.13.2 - test - org.mapstruct mapstruct @@ -130,6 +125,13 @@ bcprov-jdk15on 1.68 + + + commons-io + commons-io + 2.8.0 + + diff --git a/backend/src/main/java/com/Adapter/icare/Controllers/DatastoreController.java b/backend/src/main/java/com/Adapter/icare/Controllers/DatastoreController.java new file mode 100644 index 00000000..b4e20f77 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Controllers/DatastoreController.java @@ -0,0 +1,47 @@ +package com.Adapter.icare.Controllers; + + +import com.Adapter.icare.Domains.Datastore; +import com.Adapter.icare.Services.DatastoreService; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/v1/datastore") +public class DatastoreController { + + private final DatastoreService datastoreService; + + public DatastoreController(DatastoreService datastoreService) { + this.datastoreService = datastoreService; + } + + @GetMapping() + public List getDatastoreList() throws Exception { + return datastoreService.getDatastore(); + } + + @GetMapping("{uuid}") + public Datastore getDatastoreByUuid(@PathVariable("uuid") String uuid) throws Exception { + return datastoreService.getDatastoreByUuid(uuid); + } + + @PostMapping() + public Datastore saveDatastore(@RequestBody Datastore datastore) throws Exception { + return datastoreService.saveDatastore(datastore); + } + + @PutMapping("{uuid}") + public Datastore updateDatastore(@PathVariable("uuid") String uuid, @RequestBody Datastore datastore) throws Exception { + if (datastore.getUuid() == null) { + datastore.setUuid(uuid); + } + return datastoreService.updateDatastore(datastore); + } + + @DeleteMapping("{uuid}") + public void deleteDatastore(@PathVariable("uuid") String uuid) throws Exception { + datastoreService.deleteDatastore(uuid); + } +} diff --git a/backend/src/main/java/com/Adapter/icare/Controllers/MediatorsController.java b/backend/src/main/java/com/Adapter/icare/Controllers/MediatorsController.java new file mode 100644 index 00000000..de1b0d05 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Controllers/MediatorsController.java @@ -0,0 +1,75 @@ +package com.Adapter.icare.Controllers; + + +import com.Adapter.icare.Domains.Datastore; +import com.Adapter.icare.Domains.Mediator; +import com.Adapter.icare.Services.DatastoreService; +import com.Adapter.icare.Services.MediatorsService; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/") +public class MediatorsController { + + private final MediatorsService mediatorsService; + private final DatastoreService datastoreService; + + public MediatorsController(MediatorsService mediatorsService, DatastoreService datastoreService) { + this.mediatorsService = mediatorsService; + this.datastoreService = datastoreService; + } + + @PostMapping("mediators") + public Mediator saveMediator(@RequestBody Mediator mediator) throws Exception { + return mediatorsService.saveMediatorConfigs(mediator); + } + + @PutMapping("mediators/{uuid}") + public Mediator updateMediator(@PathVariable("uuid") String uuid, @RequestBody Mediator mediator) throws Exception { + if (mediator.getUuid() == null) { + mediator.setUuid(uuid); + } + return mediatorsService.updateMediator(mediator); + } + + @DeleteMapping("mediators/{uuid}") + public void deleteMediator(@PathVariable("uuid") String uuid) throws Exception { + mediatorsService.deleteMediator(uuid); + } + + @GetMapping("dataTemplates") + public List> getDataTemplatesList () throws Exception { + List dataTemplateNameSpaceDetails = datastoreService.getDatastoreNamespaceDetails("dataTemplates"); + List> dataTemplates = new ArrayList<>(); + for(Datastore datastore: dataTemplateNameSpaceDetails) { + Map dataTemplate = datastore.getValue(); + dataTemplate.put("uuid", datastore.getUuid()); + dataTemplates.add(dataTemplate); + } + return dataTemplates; + } + + @GetMapping("dataTemplates/{id}") + public Map getDataTemplateById(@PathVariable("id") String id) throws Exception { + Datastore datastore = datastoreService.getDatastoreByUuid(id); + if (datastore == null) { + throw new Exception("Data template for the id " + id + " does not exists"); + } + return datastore.getValue(); + } + + @PostMapping(value = "dataTemplates", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + public String passDataToMediator(@RequestBody Map data) throws Exception { + /** + * Send data to Mediator where all the logics will be done. + */ + + return mediatorsService.sendDataToMediator(data); + } +} diff --git a/backend/src/main/java/com/Adapter/icare/DHIS2/Controllers/DatasetQueryController.java b/backend/src/main/java/com/Adapter/icare/DHIS2/Controllers/DatasetQueryController.java index f967bf6d..f1317582 100644 --- a/backend/src/main/java/com/Adapter/icare/DHIS2/Controllers/DatasetQueryController.java +++ b/backend/src/main/java/com/Adapter/icare/DHIS2/Controllers/DatasetQueryController.java @@ -1,47 +1,58 @@ package com.Adapter.icare.DHIS2.Controllers; - import com.Adapter.icare.DHIS2.DHISDomains.DatasetQuery; import com.Adapter.icare.DHIS2.DHISServices.DataSetsService; import com.Adapter.icare.DHIS2.DHISServices.DatasetQueryService; import com.Adapter.icare.Domains.Datasets; -import com.Adapter.icare.Domains.Instances; import com.Adapter.icare.Services.DatasourceService; import com.Adapter.icare.Services.InstanceService; import com.Adapter.icare.Utils.EncryptionUtils; -import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.type.TypeReference; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*; - -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.sql.*; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; - +import java.util.List; +import java.util.Map; +import java.util.HashMap; +import com.Adapter.icare.Domains.Instances; +import org.springframework.web.bind.annotation.RequestMapping; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.io.IOUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.zip.ZipInputStream; +import org.springframework.web.bind.annotation.CrossOrigin; +@CrossOrigin(origins = "*") @RestController @RequestMapping("/api/v1/dataSetQueries") public class DatasetQueryController { private final DatasetQueryService datasetQueryService; - + private final ObjectMapper objectMapper; private final DataSetsService dataSetsService; private final InstanceService instanceService; - private final DatasourceService datasourceService; - public DatasetQueryController(DatasetQueryService datasetQueryService, DataSetsService dataSetsService, InstanceService instanceService, DatasourceService datasourceService) { + private final DatasourceService datasourceService; + + public DatasetQueryController(DatasetQueryService datasetQueryService, ObjectMapper objectMapper, DataSetsService dataSetsService, InstanceService instanceService, DatasourceService datasourceService) { this.datasetQueryService = datasetQueryService; + this.objectMapper = objectMapper; this.dataSetsService = dataSetsService; this.instanceService = instanceService; this.datasourceService = datasourceService; @@ -51,7 +62,7 @@ public DatasetQueryController(DatasetQueryService datasetQueryService, DataSetsS public DatasetQuery saveDataSetQuery(@RequestBody Map datasetQueryMap) throws Exception { //Manipulating the received request DatasetQuery datasetQuery = new DatasetQuery(); - datasetQuery.setDataSet(dataSetsService.getDataSetByUuid(((Map) datasetQueryMap.get("dataSetInstance")).get("uuid").toString())); + datasetQuery.setDataSet(dataSetsService.getDataSetInstanceByUuid(((Map) datasetQueryMap.get("dataSetInstance")).get("uuid").toString())); datasetQuery.setInstance(instanceService.getInstanceByUuid(((Map) datasetQueryMap.get("instance")).get("uuid").toString())); datasetQuery.setDataSource(datasourceService.getDataSourceByUuid(((Map) datasetQueryMap.get("dataSource")).get("uuid").toString())); datasetQuery.setSqlQuery(datasetQueryMap.get("sqlQuery").toString()); @@ -63,7 +74,7 @@ public DatasetQuery saveDataSetQuery(@RequestBody Map datasetQue @PutMapping public DatasetQuery updateDataSetQuery(@RequestBody Map datasetQueryMap) throws Exception { DatasetQuery datasetQuery = new DatasetQuery(); - datasetQuery.setDataSet(dataSetsService.getDataSetByUuid(((Map) datasetQueryMap.get("dataSetInstance")).get("uuid").toString())); + datasetQuery.setDataSet(dataSetsService.getDataSetInstanceByUuid(((Map) datasetQueryMap.get("dataSetInstance")).get("uuid").toString())); datasetQuery.setInstance(instanceService.getInstanceByUuid(((Map) datasetQueryMap.get("instance")).get("uuid").toString())); datasetQuery.setDataSource(datasourceService.getDataSourceByUuid(((Map) datasetQueryMap.get("dataSource")).get("uuid").toString())); datasetQuery.setSqlQuery(datasetQueryMap.get("sqlQuery").toString()); @@ -76,70 +87,26 @@ public DatasetQuery updateDataSetQuery(@RequestBody Map datasetQ return datasetQuery; } - @GetMapping() - public List GetAllDataSetsQueries(@RequestParam(name="dataSet", required = false) String dataSet){ + @GetMapping + public List GetAllDataSetsQueries(@RequestParam(name = "dataSet", required = false) String dataSet) { if (dataSet == null) { return datasetQueryService.getAllDataSetsQueries(); } else { List datasetQueries = new ArrayList<>(); - Datasets datasetInstance = dataSetsService.getDataSetByUuid(dataSet); + Datasets datasetInstance = dataSetsService.getDataSetInstanceByUuid(dataSet); DatasetQuery datasetQuery = datasetQueryService.getDataSetQueriesByDataSetInstanceId(datasetInstance); datasetQueries.add(datasetQuery); return datasetQueries; } - } @GetMapping("/{uuid}") - public DatasetQuery getDataSetQueryByUuid(@PathVariable("uuid" ) String uuid) { + public DatasetQuery getDataSetQueryByUuid(@PathVariable("uuid") String uuid) { return datasetQueryService.getDataSetQueryByUuid(uuid); } - @GetMapping("zip") - public List> downloadDataSetQueriesAsZip(@RequestParam(name="instance", required = true) String instance) throws Exception { - String uuid = instance; - Instances instanceData = instanceService.getInstanceByUuid(uuid); - -// response.setContentType("application/zip"); -// response.setHeader("Content-Disposition", "attachment; filename=\"dataset_queries_by_instance.zip\""); - - List datasetQueries = datasetQueryService.getDataSetQueriesByInstanceId(instanceData); - List> datasetQueriesData = new ArrayList<>(); -// for(DatasetQuery datasetQuery: datasetQueries) { -// Map datasetQueryInfo = new HashMap<>(); -// datasetQueryInfo.put("sqlQuery", datasetQuery.getSqlQuery().toString()); -// datasetQueryInfo.put("uuid", datasetQuery.getUuid()); -// datasetQueryInfo.put("dataSetUuid",datasetQuery.getDataSet().getId()); -// datasetQueryInfo.put("mappings", datasetQuery.getMappings()); -// datasetQueriesData.add(datasetQueryInfo); -// } -// String dataForQuery = new ObjectMapper().writeValueAsString(datasetQueriesData); -// String fileName = "datasetquery.zip"; -// String jsonName = "datasetquery.json"; -// byte[] data = dataForQuery.getBytes(); -// byte[] bytes; -// try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); -// ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) { -// zipOutputStream.setLevel(1); -// ZipEntry ze = new ZipEntry(jsonName); -// ze.setSize(data.length); -// zipOutputStream.putNextEntry(ze); -// zipOutputStream.write(data); -// zipOutputStream.closeEntry(); -// bytes = byteArrayOutputStream.toByteArray(); -// } -// response.setContentType("application/zip"); -// response.setContentLength(bytes.length); -// response.setHeader("Content-Disposition", "attachment; " -// + String.format("filename*=" + StandardCharsets.UTF_8.name() + "''%s", fileName)); -// ServletOutputStream outputStream = response.getOutputStream(); -// FileCopyUtils.copy(bytes, outputStream); -// outputStream.close(); - return datasetQueriesData; - } - @PostMapping("/{uuid}/generate") - public List> generatePayloadFromDataSetQuery(@PathVariable("uuid" ) String uuid, @RequestBody Map dataRequestPayload) throws Exception { + public List> generatePayloadFromDataSetQuery(@PathVariable("uuid") String uuid, @RequestBody Map dataRequestPayload) throws Exception { DatasetQuery datasetQuery = datasetQueryService.getDataSetQueryByUuid(uuid); String startPeriod = dataRequestPayload.get("periodStart").toString(); String endPeriod = dataRequestPayload.get("periodEnd").toString(); @@ -147,7 +114,7 @@ public List> generatePayloadFromDataSetQuery(@PathVariable(" String dataSourceUserName = datasetQuery.getDataSource().getUsername(); String decryptedPassword = EncryptionUtils.decrypt(datasetQuery.getDataSource().getPassword()); String dataSourcePassword = decryptedPassword; - String newQuery = datasetQuery.getSqlQuery().replaceAll("\\$\\{period-start\\}",startPeriod).replaceAll("\\$\\{period-end\\}",endPeriod); + String newQuery = datasetQuery.getSqlQuery().replaceAll("\\$\\{period-start\\}", startPeriod).replaceAll("\\$\\{period-end\\}", endPeriod); Connection con = DriverManager.getConnection(dataSourceUrl, dataSourceUserName, dataSourcePassword); ResultSet resultSet = con.prepareStatement(newQuery).executeQuery(); ResultSetMetaData metadata = resultSet.getMetaData(); @@ -155,15 +122,15 @@ public List> generatePayloadFromDataSetQuery(@PathVariable(" int numCols = metadata.getColumnCount(); List colNames = IntStream.range(0, numCols) - .mapToObj(index -> { - try { - return metadata.getColumnName(index + 1); - } catch (SQLException e) { - e.printStackTrace(); - return "?"; - } - }) - .collect(Collectors.toList()); + .mapToObj(index -> { + try { + return metadata.getColumnName(index + 1); + } catch (SQLException e) { + e.printStackTrace(); + return "?"; + } + }) + .collect(Collectors.toList()); List> results = new ArrayList<>(); while (resultSet.next()) { Map row = new HashMap<>(); @@ -179,15 +146,14 @@ public List> generatePayloadFromDataSetQuery(@PathVariable(" List> formattedResults = new ArrayList<>(); JSONArray mappingsArray = new JSONArray(mappings); - for(int count=0; count < mappingsArray.length(); count++) - { + for (int count = 0; count < mappingsArray.length(); count++) { Map formattedResult = new HashMap<>(); JSONObject object = mappingsArray.getJSONObject(count); Integer row = object.getInt("row"); Integer column = object.getInt("column"); - String key = row+ "-" + column; - for(Map result: results) { - if (result.get(key) != null ) { + String key = row + "-" + column; + for (Map result : results) { + if (result.get(key) != null) { formattedResult.put("id", object.getString("de") + "-" + object.getString("co") + "-val"); formattedResult.put("row", row); formattedResult.put("column", column); @@ -205,7 +171,7 @@ public List> generatePayloadFromDataSetQuery(@PathVariable(" public List> importDataSetQueries(@RequestBody Map datasetQueryImportMap) throws Exception { //Manipulating the received request List> dataSetQueryImportResponses = new ArrayList<>(); - for(Map datasetQueryMap: (List>) datasetQueryImportMap.get("dataSetQueries")) { + for (Map datasetQueryMap : (List>) datasetQueryImportMap.get("dataSetQueries")) { DatasetQuery datasetQuery = new DatasetQuery(); Datasets dataset = dataSetsService.getDataSetInstanceByDataSetId(datasetQueryMap.get("dataSetUuid").toString()); datasetQuery.setDataSet(dataset); @@ -220,4 +186,126 @@ public List> importDataSetQueries(@RequestBody Map datasetQueries = datasetQueryService.getDataSetQueriesByInstanceId(instanceData); + + List> datasetQueriesData = new ArrayList<>(); + + + for (DatasetQuery datasetQuery : datasetQueries) { + Map datasetQueryInfo = new HashMap<>(); + datasetQueryInfo.put("sqlQuery", datasetQuery.getSqlQuery()); + datasetQueryInfo.put("uuid", datasetQuery.getUuid()); + datasetQueryInfo.put("mappings", datasetQuery.getMappings()); + datasetQueryInfo.put("instance", datasetQuery.getInstance().getUuid()); + datasetQueryInfo.put("dataSetUuid", datasetQuery.getDataSet().getUuid()); + datasetQueryInfo.put("dataSource", datasetQuery.getDataSource().getUuid()); + datasetQueriesData.add(datasetQueryInfo); + } + + + String datasetQueriesDataString = objectMapper.writeValueAsString(datasetQueriesData); + + + byte[] datasetQueriesDataBytes = datasetQueriesDataString.getBytes(); + + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream); + ZipEntry zipEntry = new ZipEntry("datasetQueriesData.json"); + zipEntry.setSize(datasetQueriesDataBytes.length); + zipOutputStream.putNextEntry(zipEntry); + IOUtils.write(datasetQueriesDataBytes, zipOutputStream); + zipOutputStream.closeEntry(); + zipOutputStream.close(); + + + return byteArrayOutputStream.toByteArray(); + } + @PostMapping("/upload") + public ResponseEntity uploadDataSetQueriesByInstanceUuid(@RequestParam("file") MultipartFile file, @RequestParam("instance") String instanceUuid) { + + if (file.isEmpty()) { + System.out.println("File is empty"); + return new ResponseEntity<>("File is empty", HttpStatus.BAD_REQUEST); + } + + UUID instance = UUID.fromString(instanceUuid); + System.out.println("Instance UUID: " + instance); + + try (ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream())) { + ZipEntry zipEntry; + List> datasetQueryImportList = new ArrayList<>(); + while ((zipEntry = zipInputStream.getNextEntry()) != null) { +// System.out.println("Processing ZIP entry: " + zipEntry.getName()); + if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".json")) { + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + IOUtils.copy(zipInputStream, byteArrayOutputStream); + String jsonString = byteArrayOutputStream.toString(); +// System.out.println("JSON content for entry " + zipEntry.getName() + ": " + jsonString); + + try { + + List> datasetQueriesData = objectMapper.readValue(jsonString, new TypeReference>>() {}); + System.out.println("Parsed dataset queries data: " + datasetQueriesData); + + for (Map datasetQueryMap : datasetQueriesData) { + if (Objects.equals(datasetQueryMap.get("instance"), instanceUuid)) { + System.out.println("Instance UUID matches for dataset query: " + datasetQueryMap.get("uuid")); + DatasetQuery datasetQuery = new DatasetQuery(); + Datasets dataset = dataSetsService.getDataSetInstanceByDataSetId(datasetQueryMap.get("dataSetUuid").toString()); + datasetQuery.setDataSet(dataset); + datasetQuery.setInstance(dataset.getInstances()); + datasetQuery.setDataSource(datasourceService.getDataSourceByUuid(datasetQueryMap.get("dataSourceUuid").toString())); + datasetQuery.setSqlQuery(datasetQueryMap.get("sqlQuery").toString()); + datasetQuery.setMappings(datasetQueryMap.get("mappings").toString()); + datasetQuery.setUuid(datasetQueryMap.get("uuid").toString()); + datasetQueryService.saveDataSetQuery(datasetQuery); + + System.out.println("Data sent to database: " + datasetQuery); + } else { + System.out.println("Skipping dataset query with different instance UUID: " + datasetQueryMap.get("instance")); + } + } + } catch (Exception e) { + System.err.println("Failed to parse JSON from file: " + zipEntry.getName() + ". Error: " + e.getMessage()); + e.printStackTrace(); + continue; + } + } else { + System.out.println("Skipping non-JSON file: " + zipEntry.getName()); + } + zipInputStream.closeEntry(); + } + + System.out.println("Data uploaded successfully"); + return new ResponseEntity<>("Data uploaded successfully", HttpStatus.OK); + } catch (IOException e) { + System.err.println("Failed to process ZIP file: " + e.getMessage()); + e.printStackTrace(); + return new ResponseEntity<>("Error processing the file", HttpStatus.INTERNAL_SERVER_ERROR); + } + } + } + + + + + + + + + + + + + + + + + + diff --git a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISRepository/DatasetQueryRepository.java b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISRepository/DatasetQueryRepository.java index 53570b48..507c1bdd 100644 --- a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISRepository/DatasetQueryRepository.java +++ b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISRepository/DatasetQueryRepository.java @@ -16,5 +16,4 @@ public interface DatasetQueryRepository extends JpaRepository getDataSetQueriesByInstanceId(Long instanceId); - } diff --git a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetElementsService.java b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetElementsService.java index 439764ac..79426743 100755 --- a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetElementsService.java +++ b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetElementsService.java @@ -49,8 +49,10 @@ public DataSetElementsService(DataSetElementsRepository dataSetElementsRepositor } public void addDataSetElements(DataSetElements dataSetElements) { - UUID uuid = UUID.randomUUID(); - dataSetElements.setUuid(uuid.toString()); + if (dataSetElements.getUuid() == null) { + UUID uuid = UUID.randomUUID(); + dataSetElements.setUuid(uuid.toString()); + } dataSetElementsRepository.save(dataSetElements); } diff --git a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetsService.java b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetsService.java index 34413e88..56dd0f99 100755 --- a/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetsService.java +++ b/backend/src/main/java/com/Adapter/icare/DHIS2/DHISServices/DataSetsService.java @@ -248,7 +248,7 @@ public Optional GetSingleDataSet(String datasetId) { return dataSetsRepository.findById(datasetId); } - public Datasets getDataSetByUuid(String uuid) { + public Datasets getDataSetInstanceByUuid(String uuid) { return dataSetsRepository.getDatasetInstanceByUuid(uuid); } public Datasets getDataSetInstanceByDataSetId(String id) { diff --git a/backend/src/main/java/com/Adapter/icare/Domains/Datastore.java b/backend/src/main/java/com/Adapter/icare/Domains/Datastore.java new file mode 100644 index 00000000..80d043b0 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Domains/Datastore.java @@ -0,0 +1,38 @@ +package com.Adapter.icare.Domains; + +import com.Adapter.icare.Utils.HashMapConverter; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Map; + + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +@Entity +@Table(name="datastore",uniqueConstraints = { @UniqueConstraint( name = "namespace_and_data_key_unique_constraint", columnNames = { "namespace", "data_key" } ) }) +public class Datastore extends BaseEntity implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "namespace", nullable = false) + private String namespace; + + @Column(name = "description") + private String description; + + @Column(name = "data_key", nullable = false) + private String dataKey; + + + @Column(name = "value", columnDefinition = "json", nullable = false) + @Convert(converter = HashMapConverter.class) + private Map value; +} diff --git a/backend/src/main/java/com/Adapter/icare/Domains/Mediator.java b/backend/src/main/java/com/Adapter/icare/Domains/Mediator.java new file mode 100644 index 00000000..fb7a693a --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Domains/Mediator.java @@ -0,0 +1,63 @@ +package com.Adapter.icare.Domains; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.persistence.*; +import java.io.Serializable; + +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter +@Entity +@Table +public class Mediator extends BaseEntity implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String baseUrl; + private String path; + + @Column(name = "auth_token", nullable = true) + private String authToken; + + @Column(name = "auth_type", nullable = true) + private String authType; + + @Column(name="category", nullable = true) + private String category; + + public enum AuthType{ + BASIC("BASIC"), + TOKEN("TOKEN"); + final String value; + + AuthType(String value){ + this.value = value; + } + + public String getValue(){ + return value; + } + } + + public enum Category{ + DATA_TEMPLATE_METADATA("DATA_TEMPLATE_METADATA"), + DATA_TEMPLATE("DATA_TEMPLATE"), + ICD("ICD"), + LOINC("LOINC"); + + final String value; + + Category(String value){ + this.value = value; + } + + public String getValue(){ + return value; + } + } +} diff --git a/backend/src/main/java/com/Adapter/icare/Repository/DatastoreRepository.java b/backend/src/main/java/com/Adapter/icare/Repository/DatastoreRepository.java new file mode 100644 index 00000000..541bad0c --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Repository/DatastoreRepository.java @@ -0,0 +1,19 @@ +package com.Adapter.icare.Repository; + +import com.Adapter.icare.Domains.Datastore; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface DatastoreRepository extends JpaRepository { + List findAll(); + + @Query(value = "SELECT * FROM datastore WHERE uuid=:uuid",nativeQuery = true) + Datastore getDatastoreByUuid(String uuid); + + @Query(value = "SELECT * FROM datastore WHERE namespace=:namespace",nativeQuery = true) + List getDatastoreByNamespace(String namespace); + + +} diff --git a/backend/src/main/java/com/Adapter/icare/Repository/MediatorsRepository.java b/backend/src/main/java/com/Adapter/icare/Repository/MediatorsRepository.java new file mode 100644 index 00000000..9ac6e3d1 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Repository/MediatorsRepository.java @@ -0,0 +1,15 @@ +package com.Adapter.icare.Repository; + +import com.Adapter.icare.Domains.Mediator; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface MediatorsRepository extends JpaRepository { + + List findAll(); + + @Query(value = "SELECT * FROM mediator WHERE uuid=:uuid",nativeQuery = true) + Mediator getMediatorByUuid(String uuid); +} diff --git a/backend/src/main/java/com/Adapter/icare/Services/DatasourceService.java b/backend/src/main/java/com/Adapter/icare/Services/DatasourceService.java index 62fe7060..eb7f14fd 100755 --- a/backend/src/main/java/com/Adapter/icare/Services/DatasourceService.java +++ b/backend/src/main/java/com/Adapter/icare/Services/DatasourceService.java @@ -58,8 +58,10 @@ public Datasource AddNewDataSource(Datasource datasource) throws Exception { default: break; } - UUID uuid = UUID.randomUUID(); - datasource.setUuid(uuid.toString()); + if (datasource.getUuid() == null) { + UUID uuid = UUID.randomUUID(); + datasource.setUuid(uuid.toString()); + } // Password encryption String encryptedPassword = EncryptionUtils.encrypt(datasource.getPassword()); datasource.setPassword(encryptedPassword); diff --git a/backend/src/main/java/com/Adapter/icare/Services/DatastoreService.java b/backend/src/main/java/com/Adapter/icare/Services/DatastoreService.java new file mode 100644 index 00000000..e093c138 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Services/DatastoreService.java @@ -0,0 +1,66 @@ +package com.Adapter.icare.Services; + +import com.Adapter.icare.Domains.Datastore; +import com.Adapter.icare.Repository.DatastoreRepository; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.UUID; + +@Service +public class DatastoreService { + private final DatastoreRepository datastoreRepository; + + public DatastoreService(DatastoreRepository datastoreRepository) { + this.datastoreRepository = datastoreRepository; + } + + public Datastore saveDatastore(Datastore datastore) throws Exception { + if (datastore.getUuid() == null) { + UUID uuid = UUID.randomUUID(); + datastore.setUuid(uuid.toString()); + } + return datastoreRepository.save(datastore); + } + + public List getDatastore() throws Exception { + return datastoreRepository.findAll(); + } + + public Datastore getDatastoreByUuid(String uuid) throws Exception { + return datastoreRepository.getDatastoreByUuid(uuid); + } + + public Datastore updateDatastore(Datastore datastore) throws Exception { + if (datastore.getUuid() != null) { + String uuid = datastore.getUuid(); + Datastore datastoreToUpdate = datastoreRepository.getDatastoreByUuid(uuid); + if (datastoreToUpdate != null) { + return datastoreRepository.save(datastore); + } else { + throw new IllegalStateException("Datastore with uuid " + uuid + " does not exists"); + } + } else { + throw new IllegalStateException("Datastore uuid is not set"); + } + + } + + public void deleteDatastore(String uuid) throws Exception { + if (uuid == null) { + throw new IllegalStateException("uuid is missing"); + } else { + Datastore datastore = datastoreRepository.getDatastoreByUuid(uuid); + if (datastore != null) { + datastoreRepository.deleteById(datastore.getId()); + } else { + throw new IllegalStateException("Datastore with uuid " + uuid + " does not exists"); + } + + } + } + + public List getDatastoreNamespaceDetails(String namespace) throws Exception { + return datastoreRepository.getDatastoreByNamespace(namespace); + } +} diff --git a/backend/src/main/java/com/Adapter/icare/Services/MediatorsService.java b/backend/src/main/java/com/Adapter/icare/Services/MediatorsService.java new file mode 100644 index 00000000..1fceeee5 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Services/MediatorsService.java @@ -0,0 +1,140 @@ +package com.Adapter.icare.Services; + +import com.Adapter.icare.Domains.Mediator; +import com.Adapter.icare.Repository.MediatorsRepository; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONObject; +import org.springframework.stereotype.Service; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.*; + +@Service +public class MediatorsService { + private final MediatorsRepository mediatorsRepository; + + public MediatorsService(MediatorsRepository mediatorsRepository) { + this.mediatorsRepository = mediatorsRepository; + } + + public Mediator saveMediatorConfigs(Mediator mediator) throws Exception { + if (mediator.getUuid() == null) { + UUID uuid = UUID.randomUUID(); + mediator.setUuid(uuid.toString()); + } + return mediatorsRepository.save(mediator); + } + + public List getMediatorsConfigs() throws Exception { + return mediatorsRepository.findAll(); + } + + public Mediator getMediatorByUuid(String uuid) throws Exception { + return mediatorsRepository.getMediatorByUuid(uuid); + } + + public Mediator updateMediator(Mediator mediator) throws Exception { + if (mediator.getUuid() != null) { + String uuid = mediator.getUuid(); + Mediator mediatorToUpdate = mediatorsRepository.getMediatorByUuid(uuid); + if (mediatorToUpdate != null) { + return mediatorsRepository.save(mediator); + } else { + throw new IllegalStateException("Mediator with uuid " + uuid + " does not exists"); + } + } else { + throw new IllegalStateException("Mediator uuid is not set"); + } + + } + + public void deleteMediator(String uuid) throws Exception { + if (uuid == null) { + throw new IllegalStateException("uuid is missing"); + } else { + Mediator mediator = mediatorsRepository.getMediatorByUuid(uuid); + if (mediator != null) { + mediatorsRepository.deleteById(mediator.getId()); + } else { + throw new IllegalStateException("Mediator with uuid " + uuid + " does not exists"); + } + + } + } + + public List> getDataTemplatesList() throws Exception { + List> dataTemplates = new ArrayList<>(); + return dataTemplates; + } + + public Map getDataTemplateById(String id) throws Exception { + return new HashMap<>(); + } + + public String sendDataToMediator(Map data) throws Exception { + /** + * TODO: The base url, path and authentication details should be put on configurations + */ + Map workflow =(Map) ((Map) data.get("templateDetails")).get("workflow"); + if (workflow != null) { + if (workflow.get("uuid") != null) { + Mediator mediator = mediatorsRepository.getMediatorByUuid(workflow.get("uuid").toString()); + String authType = mediator.getAuthType(); + String authToken = mediator.getAuthToken(); + String baseUrl = mediator.getBaseUrl(); + String path = mediator.getPath(); + URL url = new URL(baseUrl + path); + BufferedReader reader; + String dataLine; + StringBuffer responseContent = new StringBuffer(); + JSONObject responseJsonObject = new JSONObject(); + String returnStr = ""; + try { + HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); + String authentication = ""; + if (authType.equals("BASIC")) { + authentication = "Basic " + authToken; + httpURLConnection.setRequestProperty("Authorization", authentication); + } else if (authType.equals("TOKEN")) { + authentication = "Bearer " + authToken; + httpURLConnection.setRequestProperty("Authorization", authentication); + } + httpURLConnection.setRequestMethod("POST"); + httpURLConnection.setRequestProperty("Content-Type", "application/json"); + httpURLConnection.setRequestProperty("Accept", "application/json"); + httpURLConnection.setDoOutput(true); + + ObjectMapper mapper = new ObjectMapper(); + String jsonString = mapper.writeValueAsString(data); + + try (OutputStream os = httpURLConnection.getOutputStream()) { + byte[] input = jsonString.getBytes("utf-8"); + os.write(input, 0, input.length); + } + + reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); + while ((dataLine = reader.readLine()) != null) { + responseContent.append(dataLine); + } + reader.close(); + // System.out.println(js); + responseJsonObject = new JSONObject(responseContent.toString()); + returnStr = responseJsonObject.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return returnStr; + } else { + throw new IllegalStateException("Workflow uuid is missing"); + } + + } else { + throw new IllegalStateException("Workflow not set"); + } + + } +} diff --git a/backend/src/main/java/com/Adapter/icare/Utils/HashMapConverter.java b/backend/src/main/java/com/Adapter/icare/Utils/HashMapConverter.java new file mode 100644 index 00000000..cc65fda0 --- /dev/null +++ b/backend/src/main/java/com/Adapter/icare/Utils/HashMapConverter.java @@ -0,0 +1,43 @@ +package com.Adapter.icare.Utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.persistence.AttributeConverter; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.ErrorManager; + +public class HashMapConverter implements AttributeConverter, String> { + + ErrorManager logger = new ErrorManager(); + ObjectMapper objectMapper = new ObjectMapper(); + @Override + public String convertToDatabaseColumn(Map customerInfo) { + + String customerInfoJson = null; + try { + customerInfoJson = objectMapper.writeValueAsString(customerInfo); + } catch (final JsonProcessingException e) { + logger.error("JSON writing error", e, 400); + } + + return customerInfoJson; + } + + @Override + public Map convertToEntityAttribute(String customerInfoJSON) { + + Map customerInfo = null; + try { + customerInfo = objectMapper.readValue(customerInfoJSON, + new TypeReference>() {}); + } catch (final IOException e) { + logger.error("JSON reading error", e, 400); + } + + return customerInfo; + } +} diff --git a/database-design/.sql b/database-design/.sql new file mode 100644 index 00000000..030d217a --- /dev/null +++ b/database-design/.sql @@ -0,0 +1,516 @@ +--CREATE concept SQL SCRIPT-- +CREATE TABLE `concept` ( + `concept_id` int NOT NULL AUTO_INCREMENT, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `short_name` varchar(255) DEFAULT NULL, + `description` text, + `form_text` text, + `datatype_id` int NOT NULL DEFAULT '0', + `class_id` int NOT NULL DEFAULT '0', + `is_set` tinyint(1) NOT NULL DEFAULT '0', + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `version` varchar(50) DEFAULT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_id`), + UNIQUE KEY `concept_uuid_index` (`uuid`), + KEY `user_who_changed_concept` (`changed_by`), + KEY `concept_classes` (`class_id`), + KEY `concept_creator` (`creator`), + KEY `concept_datatypes` (`datatype_id`), + KEY `user_who_retired_concept` (`retired_by`), + CONSTRAINT `concept_classes` FOREIGN KEY (`class_id`) REFERENCES `concept_class` (`concept_class_id`), + CONSTRAINT `concept_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_datatypes` FOREIGN KEY (`datatype_id`) REFERENCES `concept_datatype` (`concept_datatype_id`), + CONSTRAINT `user_who_changed_concept` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_retired_concept` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=220286 DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_answer SQL SCRIPT -- +CREATE TABLE `concept_answer` ( + `concept_answer_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int NOT NULL DEFAULT '0', + `answer_concept` int DEFAULT NULL, + `answer_drug` int DEFAULT NULL, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `sort_weight` double DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_answer_id`), + UNIQUE KEY `concept_answer_uuid_index` (`uuid`), + KEY `answer` (`answer_concept`), + KEY `answers_for_concept` (`concept_id`), + KEY `answer_creator` (`creator`), + KEY `answer_answer_drug_fk` (`answer_drug`), + CONSTRAINT `answer` FOREIGN KEY (`answer_concept`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `answer_answer_drug_fk` FOREIGN KEY (`answer_drug`) REFERENCES `drug` (`drug_id`), + CONSTRAINT `answer_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `answers_for_concept` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`) +) ENGINE=InnoDB AUTO_INCREMENT=8638 DEFAULT CHARSET=utf8mb3; + + + + +--CREATE concept_attribute SQL SCRIPT -- +CREATE TABLE `concept_attribute` ( + `concept_attribute_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int NOT NULL, + `attribute_type_id` int NOT NULL, + `value_reference` text NOT NULL, + `uuid` char(38) NOT NULL, + `creator` int NOT NULL, + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `voided` tinyint(1) NOT NULL DEFAULT '0', + `voided_by` int DEFAULT NULL, + `date_voided` datetime DEFAULT NULL, + `void_reason` varchar(255) DEFAULT NULL, + PRIMARY KEY (`concept_attribute_id`), + UNIQUE KEY `uuid` (`uuid`), + KEY `concept_attribute_concept_fk` (`concept_id`), + KEY `concept_attribute_attribute_type_id_fk` (`attribute_type_id`), + KEY `concept_attribute_creator_fk` (`creator`), + KEY `concept_attribute_changed_by_fk` (`changed_by`), + KEY `concept_attribute_voided_by_fk` (`voided_by`), + CONSTRAINT `concept_attribute_attribute_type_id_fk` FOREIGN KEY (`attribute_type_id`) REFERENCES `concept_attribute_type` (`concept_attribute_type_id`), + CONSTRAINT `concept_attribute_changed_by_fk` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_attribute_concept_fk` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `concept_attribute_creator_fk` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_attribute_voided_by_fk` FOREIGN KEY (`voided_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + + + + + +--CREATE concept_attribute_type SQL SCRIPT -- +CREATE TABLE `concept_attribute_type` ( + `concept_attribute_type_id` int NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `description` varchar(1024) DEFAULT NULL, + `datatype` varchar(255) DEFAULT NULL, + `datatype_config` text, + `preferred_handler` varchar(255) DEFAULT NULL, + `handler_config` text, + `min_occurs` int NOT NULL, + `max_occurs` int DEFAULT NULL, + `creator` int NOT NULL, + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_attribute_type_id`), + UNIQUE KEY `uuid` (`uuid`), + KEY `concept_attribute_type_creator_fk` (`creator`), + KEY `concept_attribute_type_changed_by_fk` (`changed_by`), + KEY `concept_attribute_type_retired_by_fk` (`retired_by`), + CONSTRAINT `concept_attribute_type_changed_by_fk` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_attribute_type_creator_fk` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_attribute_type_retired_by_fk` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3; + + + +--CREATE concept_class SQL SCRIPT -- +CREATE TABLE `concept_class` ( + `concept_class_id` int NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL DEFAULT '', + `description` varchar(255) DEFAULT NULL, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + `date_changed` datetime DEFAULT NULL, + `changed_by` int DEFAULT NULL, + PRIMARY KEY (`concept_class_id`), + UNIQUE KEY `concept_class_uuid_index` (`uuid`), + KEY `concept_class_retired_status` (`retired`), + KEY `concept_class_creator` (`creator`), + KEY `user_who_retired_concept_class` (`retired_by`), + KEY `concept_class_name_index` (`name`), + KEY `concept_class_changed_by` (`changed_by`), + CONSTRAINT `concept_class_changed_by` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_class_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_retired_concept_class` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_complex SQL SCRIPT-- +CREATE TABLE `concept_complex` ( + `concept_id` int NOT NULL, + `handler` varchar(255) DEFAULT NULL, + PRIMARY KEY (`concept_id`), + CONSTRAINT `concept_attributes` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_datatype SQL SCRIPT-- +CREATE TABLE `concept_datatype` ( + `concept_datatype_id` int NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL DEFAULT '', + `hl7_abbreviation` varchar(3) DEFAULT NULL, + `description` varchar(255) DEFAULT NULL, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_datatype_id`), + UNIQUE KEY `concept_datatype_uuid_index` (`uuid`), + KEY `concept_datatype_retired_status` (`retired`), + KEY `concept_datatype_creator` (`creator`), + KEY `user_who_retired_concept_datatype` (`retired_by`), + KEY `concept_datatype_name_index` (`name`), + CONSTRAINT `concept_datatype_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_retired_concept_datatype` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_description SQL SCRIPT-- +CREATE TABLE `concept_description` ( + `concept_description_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int NOT NULL DEFAULT '0', + `description` text NOT NULL, + `locale` varchar(50) NOT NULL DEFAULT '', + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_description_id`), + UNIQUE KEY `concept_description_uuid_index` (`uuid`), + KEY `user_who_changed_description` (`changed_by`), + KEY `description_for_concept` (`concept_id`), + KEY `user_who_created_description` (`creator`), + CONSTRAINT `description_for_concept` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `user_who_changed_description` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_created_description` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=19828 DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_map_type SQL SCRIPT -- +CREATE TABLE `concept_map_type` ( + `concept_map_type_id` int NOT NULL AUTO_INCREMENT, + `name` varchar(255) NOT NULL, + `description` varchar(255) DEFAULT NULL, + `creator` int NOT NULL, + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `is_hidden` tinyint(1) NOT NULL DEFAULT '0', + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_map_type_id`), + UNIQUE KEY `name` (`name`), + UNIQUE KEY `uuid` (`uuid`), + KEY `mapped_user_creator_concept_map_type` (`creator`), + KEY `mapped_user_changed_concept_map_type` (`changed_by`), + KEY `mapped_user_retired_concept_map_type` (`retired_by`), + CONSTRAINT `mapped_user_changed_concept_map_type` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `mapped_user_creator_concept_map_type` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `mapped_user_retired_concept_map_type` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_name SQL SCRIPT -- +CREATE TABLE `concept_name` ( + `concept_name_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int DEFAULT NULL, + `name` varchar(255) NOT NULL DEFAULT '', + `locale` varchar(50) NOT NULL DEFAULT '', + `locale_preferred` tinyint(1) DEFAULT '0', + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `concept_name_type` varchar(50) DEFAULT NULL, + `voided` tinyint(1) NOT NULL DEFAULT '0', + `voided_by` int DEFAULT NULL, + `date_voided` datetime DEFAULT NULL, + `void_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + `date_changed` datetime DEFAULT NULL, + `changed_by` int DEFAULT NULL, + PRIMARY KEY (`concept_name_id`), + UNIQUE KEY `concept_name_uuid_index` (`uuid`), + KEY `name_of_concept` (`name`), + KEY `name_for_concept` (`concept_id`), + KEY `user_who_created_name` (`creator`), + KEY `user_who_voided_this_name` (`voided_by`), + KEY `concept_name_changed_by` (`changed_by`), + KEY `concept_name_duplicate` (`name`,`locale`,`voided`), + CONSTRAINT `concept_name_changed_by` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `name_for_concept` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `user_who_created_name` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_voided_this_name` FOREIGN KEY (`voided_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=195867 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_name_tag SQL SCRIPT-- +CREATE TABLE `concept_name_tag` ( + `concept_name_tag_id` int NOT NULL AUTO_INCREMENT, + `tag` varchar(50) NOT NULL, + `description` text, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `voided` tinyint(1) NOT NULL DEFAULT '0', + `voided_by` int DEFAULT NULL, + `date_voided` datetime DEFAULT NULL, + `void_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + `date_changed` datetime DEFAULT NULL, + `changed_by` int DEFAULT NULL, + PRIMARY KEY (`concept_name_tag_id`), + UNIQUE KEY `concept_name_tag_unique_tags` (`tag`), + UNIQUE KEY `concept_name_tag_uuid_index` (`uuid`), + KEY `user_who_created_name_tag` (`creator`), + KEY `user_who_voided_name_tag` (`voided_by`), + KEY `concept_name_tag_changed_by` (`changed_by`), + CONSTRAINT `concept_name_tag_changed_by` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +--CREATE concept_name_tag_map SQL SCRIPT -- +CREATE TABLE `concept_name_tag_map` ( + `concept_name_id` int NOT NULL, + `concept_name_tag_id` int NOT NULL, + KEY `mapped_concept_name` (`concept_name_id`), + KEY `mapped_concept_name_tag` (`concept_name_tag_id`), + CONSTRAINT `mapped_concept_name` FOREIGN KEY (`concept_name_id`) REFERENCES `concept_name` (`concept_name_id`), + CONSTRAINT `mapped_concept_name_tag` FOREIGN KEY (`concept_name_tag_id`) REFERENCES `concept_name_tag` (`concept_name_tag_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_numeric SQL SCRIPT-- +CREATE TABLE `concept_numeric` ( + `concept_id` int NOT NULL DEFAULT '0', + `hi_absolute` double DEFAULT NULL, + `hi_critical` double DEFAULT NULL, + `hi_normal` double DEFAULT NULL, + `low_absolute` double DEFAULT NULL, + `low_critical` double DEFAULT NULL, + `low_normal` double DEFAULT NULL, + `units` varchar(50) DEFAULT NULL, + `allow_decimal` tinyint(1) DEFAULT NULL, + `display_precision` int DEFAULT NULL, + PRIMARY KEY (`concept_id`), + CONSTRAINT `numeric_attributes` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + + +--CREATE concept_proposal SQL SCRIPT-- +CREATE TABLE `concept_proposal` ( + `concept_proposal_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int DEFAULT NULL, + `encounter_id` int DEFAULT NULL, + `original_text` varchar(255) NOT NULL DEFAULT '', + `final_text` varchar(255) DEFAULT NULL, + `obs_id` int DEFAULT NULL, + `obs_concept_id` int DEFAULT NULL, + `state` varchar(32) NOT NULL DEFAULT 'UNMAPPED', + `comments` varchar(255) DEFAULT NULL, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `locale` varchar(50) NOT NULL DEFAULT '', + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_proposal_id`), + UNIQUE KEY `concept_proposal_uuid_index` (`uuid`), + KEY `user_who_changed_proposal` (`changed_by`), + KEY `concept_for_proposal` (`concept_id`), + KEY `user_who_created_proposal` (`creator`), + KEY `encounter_for_proposal` (`encounter_id`), + KEY `proposal_obs_concept_id` (`obs_concept_id`), + KEY `proposal_obs_id` (`obs_id`), + CONSTRAINT `concept_for_proposal` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `encounter_for_proposal` FOREIGN KEY (`encounter_id`) REFERENCES `encounter` (`encounter_id`), + CONSTRAINT `proposal_obs_concept_id` FOREIGN KEY (`obs_concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `proposal_obs_id` FOREIGN KEY (`obs_id`) REFERENCES `obs` (`obs_id`), + CONSTRAINT `user_who_changed_proposal` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_created_proposal` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +--CREATE concept_proposal_tag_map SQL SCRIPT -- +CREATE TABLE `concept_proposal_tag_map` ( + `concept_proposal_id` int NOT NULL, + `concept_name_tag_id` int NOT NULL, + KEY `mapped_concept_proposal_tag` (`concept_name_tag_id`), + KEY `mapped_concept_proposal` (`concept_proposal_id`), + CONSTRAINT `mapped_concept_proposal` FOREIGN KEY (`concept_proposal_id`) REFERENCES `concept_proposal` (`concept_proposal_id`), + CONSTRAINT `mapped_concept_proposal_tag` FOREIGN KEY (`concept_name_tag_id`) REFERENCES `concept_name_tag` (`concept_name_tag_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +--CREATE concept_reference_map SQL SCRIPT-- +CREATE TABLE `concept_reference_map` ( + `concept_map_id` int NOT NULL AUTO_INCREMENT, + `concept_reference_term_id` int NOT NULL, + `concept_map_type_id` int NOT NULL DEFAULT '1', + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `concept_id` int NOT NULL DEFAULT '0', + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_map_id`), + UNIQUE KEY `concept_reference_map_uuid_id` (`uuid`), + KEY `map_for_concept` (`concept_id`), + KEY `map_creator` (`creator`), + KEY `mapped_concept_map_type` (`concept_map_type_id`), + KEY `mapped_user_changed_ref_term` (`changed_by`), + KEY `mapped_concept_reference_term` (`concept_reference_term_id`), + CONSTRAINT `map_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `map_for_concept` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `mapped_concept_map_type` FOREIGN KEY (`concept_map_type_id`) REFERENCES `concept_map_type` (`concept_map_type_id`), + CONSTRAINT `mapped_concept_reference_term` FOREIGN KEY (`concept_reference_term_id`) REFERENCES `concept_reference_term` (`concept_reference_term_id`), + CONSTRAINT `mapped_user_changed_ref_term` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=289600 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_reference_source SQL SCRIPT -- +CREATE TABLE `concept_reference_source` ( + `concept_source_id` int NOT NULL AUTO_INCREMENT, + `name` varchar(50) NOT NULL DEFAULT '', + `description` text NOT NULL, + `hl7_code` varchar(50) DEFAULT '', + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + `unique_id` varchar(250) DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `changed_by` int DEFAULT NULL, + PRIMARY KEY (`concept_source_id`), + UNIQUE KEY `concept_reference_source_uuid_id` (`uuid`), + UNIQUE KEY `concept_source_unique_hl7_codes` (`hl7_code`), + UNIQUE KEY `concept_reference_source_unique_id_unique` (`unique_id`), + KEY `unique_hl7_code` (`hl7_code`), + KEY `concept_source_creator` (`creator`), + KEY `user_who_retired_concept_source` (`retired_by`), + KEY `concept_reference_source_changed_by` (`changed_by`), + KEY `concept_reference_source_name` (`name`), + CONSTRAINT `concept_reference_source_changed_by` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `concept_source_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `user_who_retired_concept_source` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=53 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_reference_term SQL SCRIPT -- +CREATE TABLE `concept_reference_term` ( + `concept_reference_term_id` int NOT NULL AUTO_INCREMENT, + `concept_source_id` int NOT NULL, + `name` varchar(255) DEFAULT NULL, + `code` varchar(255) NOT NULL, + `version` varchar(255) DEFAULT NULL, + `description` varchar(255) DEFAULT NULL, + `creator` int NOT NULL, + `date_created` datetime NOT NULL, + `date_changed` datetime DEFAULT NULL, + `changed_by` int DEFAULT NULL, + `retired` tinyint(1) NOT NULL DEFAULT '0', + `retired_by` int DEFAULT NULL, + `date_retired` datetime DEFAULT NULL, + `retire_reason` varchar(255) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_reference_term_id`), + UNIQUE KEY `uuid` (`uuid`), + KEY `mapped_user_creator` (`creator`), + KEY `mapped_user_changed` (`changed_by`), + KEY `mapped_user_retired` (`retired_by`), + KEY `mapped_concept_source` (`concept_source_id`), + KEY `idx_code_concept_reference_term` (`code`), + KEY `concept_reference_term_code` (`concept_source_id`,`code`), + CONSTRAINT `mapped_concept_source` FOREIGN KEY (`concept_source_id`) REFERENCES `concept_reference_source` (`concept_source_id`), + CONSTRAINT `mapped_user_changed` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `mapped_user_creator` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`), + CONSTRAINT `mapped_user_retired` FOREIGN KEY (`retired_by`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=307829 DEFAULT CHARSET=utf8mb3; + +--CREATE concept_reference_term_map SQL SCRIPT -- +CREATE TABLE `concept_reference_term_map` ( + `concept_reference_term_map_id` int NOT NULL AUTO_INCREMENT, + `term_a_id` int NOT NULL, + `term_b_id` int NOT NULL, + `a_is_to_b_id` int NOT NULL, + `creator` int NOT NULL, + `date_created` datetime NOT NULL, + `changed_by` int DEFAULT NULL, + `date_changed` datetime DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_reference_term_map_id`), + UNIQUE KEY `uuid` (`uuid`), + KEY `mapped_term_a` (`term_a_id`), + KEY `mapped_term_b` (`term_b_id`), + KEY `mapped_concept_map_type_ref_term_map` (`a_is_to_b_id`), + KEY `mapped_user_creator_ref_term_map` (`creator`), + KEY `mapped_user_changed_ref_term_map` (`changed_by`), + CONSTRAINT `mapped_concept_map_type_ref_term_map` FOREIGN KEY (`a_is_to_b_id`) REFERENCES `concept_map_type` (`concept_map_type_id`), + CONSTRAINT `mapped_term_a` FOREIGN KEY (`term_a_id`) REFERENCES `concept_reference_term` (`concept_reference_term_id`), + CONSTRAINT `mapped_term_b` FOREIGN KEY (`term_b_id`) REFERENCES `concept_reference_term` (`concept_reference_term_id`), + CONSTRAINT `mapped_user_changed_ref_term_map` FOREIGN KEY (`changed_by`) REFERENCES `users` (`user_id`), + CONSTRAINT `mapped_user_creator_ref_term_map` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + + + + +--CREATE concept_set SQL SCRIPT -- +CREATE TABLE `concept_set` ( + `concept_set_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int NOT NULL DEFAULT '0', + `concept_set` int NOT NULL DEFAULT '0', + `sort_weight` double DEFAULT NULL, + `creator` int NOT NULL DEFAULT '0', + `date_created` datetime NOT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_set_id`), + UNIQUE KEY `concept_set_uuid_index` (`uuid`), + KEY `idx_concept_set_concept` (`concept_id`), + KEY `has_a` (`concept_set`), + KEY `user_who_created` (`creator`), + CONSTRAINT `has_a` FOREIGN KEY (`concept_set`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `user_who_created` FOREIGN KEY (`creator`) REFERENCES `users` (`user_id`) +) ENGINE=InnoDB AUTO_INCREMENT=29871 DEFAULT CHARSET=utf8mb3; + + + +--CREATE concept_state_conversion SQL SCRIPT-- +CREATE TABLE `concept_state_conversion` ( + `concept_state_conversion_id` int NOT NULL AUTO_INCREMENT, + `concept_id` int DEFAULT '0', + `program_workflow_id` int DEFAULT '0', + `program_workflow_state_id` int DEFAULT '0', + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_state_conversion_id`), + UNIQUE KEY `concept_state_conversion_uuid_index` (`uuid`), + UNIQUE KEY `unique_workflow_concept_in_conversion` (`program_workflow_id`,`concept_id`), + KEY `concept_triggers_conversion` (`concept_id`), + KEY `conversion_to_state` (`program_workflow_state_id`), + CONSTRAINT `concept_triggers_conversion` FOREIGN KEY (`concept_id`) REFERENCES `concept` (`concept_id`), + CONSTRAINT `conversion_involves_workflow` FOREIGN KEY (`program_workflow_id`) REFERENCES `program_workflow` (`program_workflow_id`), + CONSTRAINT `conversion_to_state` FOREIGN KEY (`program_workflow_state_id`) REFERENCES `program_workflow_state` (`program_workflow_state_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +--CREATE concept_stop_word SQL SCRIPT-- +CREATE TABLE `concept_stop_word` ( + `concept_stop_word_id` int NOT NULL AUTO_INCREMENT, + `word` varchar(50) NOT NULL, + `locale` varchar(50) DEFAULT NULL, + `uuid` char(38) NOT NULL, + PRIMARY KEY (`concept_stop_word_id`), + UNIQUE KEY `Unique_StopWord_Key` (`word`,`locale`) +) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb3; diff --git a/package.json b/package.json new file mode 100644 index 00000000..dd57a486 --- /dev/null +++ b/package.json @@ -0,0 +1,7 @@ +{ + "dependencies": { + "file-saver": "^2.0.5", + "jszip": "^3.10.1", + "pako": "^2.1.0" + } +} diff --git a/ui/src/app/app.module.ts b/ui/src/app/app.module.ts index 0f06fc2a..a57cc90c 100755 --- a/ui/src/app/app.module.ts +++ b/ui/src/app/app.module.ts @@ -34,9 +34,7 @@ import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { RouterModule } from '@angular/router'; - import { AppComponent } from './app.component'; - import { appRoutes } from './routes'; import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field'; import { SharedModule } from './shared/shared.modules'; @@ -45,6 +43,7 @@ import { PeriodFilter } from './Helpers/period-filter'; import { MatDialogModule } from '@angular/material/dialog'; + @NgModule({ declarations: [AppComponent ], imports: [ @@ -66,6 +65,7 @@ import { MatDialogModule } from '@angular/material/dialog'; }), MatDialogModule, + ], providers: [ diff --git a/ui/src/app/modules/import-export/import-export.module.ts b/ui/src/app/modules/import-export/import-export.module.ts index e3af8124..bc16005e 100644 --- a/ui/src/app/modules/import-export/import-export.module.ts +++ b/ui/src/app/modules/import-export/import-export.module.ts @@ -4,6 +4,7 @@ import { components } from './components'; import { ImportExportRoutingModule } from './import-export.routing.module'; import { pages } from './pages'; + @NgModule({ imports: [ImportExportRoutingModule, SharedModule], exports: [...components, ...pages], diff --git a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.css b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.css index e69de29b..0519ecba 100644 --- a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.css +++ b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.css @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.html b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.html index 84133904..4af5b8f6 100644 --- a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.html +++ b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.html @@ -101,8 +101,84 @@ - - Import export works! + + + + + + + Instance: + + + {{ instance.name }} + + + + + cloud_download Export + + + + + + attach_file + {{ selectedFileName || "Choose File" }} + + + + + + cloud_upload Import + + + + diff --git a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.ts b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.ts index b64d9708..f1cb719f 100644 --- a/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.ts +++ b/ui/src/app/modules/import-export/pages/import-export-home/import-export-home.component.ts @@ -13,6 +13,12 @@ export class ImportExportHomeComponent implements OnInit { currentUser$: Observable | undefined; instances$: Observable; + downloadInProgress: boolean = false; + fileInput: HTMLInputElement | undefined; + + selectedFileName: string | null = null; + selectedFile: File | null = null; + selectedInstance: any | null = null; constructor( private router: Router, private instancesService: InstancesService @@ -30,11 +36,31 @@ export class ImportExportHomeComponent implements OnInit { event.stopPropagation(); this.showSideMenu = !this.showSideMenu; } - onLogout(): void { this.router.navigate(['/login']); } + onInstanceSelect(event: any): void { + const selectedUuid = event.value; + this.instances$.subscribe((instances) => { + this.selectedInstance = instances.find( + (instance) => instance.uuid === selectedUuid + ); + }); + } + + private downloadFile(data: Blob): void { + let url = window.URL || window.webkitURL; + let blobUrl = url.createObjectURL(data); + let a = document.createElement('a'); + a.href = blobUrl; + a.download = 'dataset_queries.zip'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(blobUrl); + } + onDownload(event: Event, instance: any): void { event.stopPropagation(); this.instancesService @@ -44,25 +70,57 @@ export class ImportExportHomeComponent implements OnInit { }); } - private downloadFile(data: any[]): void { - let jsonData = JSON.stringify(data); + handleFileSelection(): void { + const fileInput = document.getElementById('fileInput') as HTMLInputElement; + fileInput.click(); + } - //Convert JSON string to BLOB. - let blodData = new Blob([jsonData], { type: 'text/plain;charset=utf-8' }); + handleFileChange(event: Event): void { + const input = event.target as HTMLInputElement; + if (input.files && input.files.length > 0) { + const file = input.files[0]; + this.selectedFile = file; // Store the file object + this.selectedFileName = file.name; + } else { + this.selectedFile = undefined; + this.selectedFileName = undefined; + } + } - //Check the Browser. - let isIE = false; - if (isIE) { - // window.navigator.msSaveBlob(blob1, "datasetqueries.json"); + startImport(): void { + if (this.selectedInstance && this.selectedFile) { + const fileReader = new FileReader(); + fileReader.onload = (e) => { + const fileContent = e.target?.result; + if (fileContent) { + // Call the service method + this.instancesService + .postDataSetQueriesByInstanceUuid( + this.selectedFile!, + this.selectedInstance.uuid + ) + .subscribe({ + next: (response) => { + console.log('File upload response:', response); + }, + error: (error) => { + console.error('Error uploading file:', error); + }, + }); + } + }; + fileReader.onerror = (e) => { + console.error('Error reading file:', e); + }; + fileReader.readAsText(this.selectedFile); } else { - let url = window.URL || window.webkitURL; - let link = url.createObjectURL(blodData); - let a = document.createElement('a'); - a.download = 'datasetqueries.json'; - a.href = link; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); + console.error('Instance or file is not selected.'); + if (!this.selectedInstance) { + console.error('selectedInstance is not selected.'); + } + if (!this.selectedFile) { + console.error('selectedFile is not selected.'); + } } } } diff --git a/ui/src/app/services/instances/instances.service.ts b/ui/src/app/services/instances/instances.service.ts index 83084e03..adc0fd2b 100755 --- a/ui/src/app/services/instances/instances.service.ts +++ b/ui/src/app/services/instances/instances.service.ts @@ -45,7 +45,7 @@ export class InstancesService { constructor(private httpClient: HttpClient) { this.httpOptions = { headers: new HttpHeaders({ - 'Content-Type': 'application/json', + 'Content-Type': 'application/zip', Auth: 'Basic ' + localStorage.getItem('iadapterAuthKey'), }), }; @@ -106,9 +106,29 @@ export class InstancesService { ); } - getDataSetQueriesByInstanceUuid(uuid: string): Observable { - return this.httpClient.get(`./api/v1/dataSetQueries?instance=${uuid}`).pipe( - map((response: any) => response), + getDataSetQueriesByInstanceUuid(uuid: string): Observable { + const url = `./api/v1/dataSetQueries/download?instance=${uuid}`; + return this.httpClient + .get(url, { + responseType: 'blob', + headers: this.httpOptions.headers, + observe: 'response', + }) + .pipe( + map((response: any) => response.body), + catchError((error: any) => of(error)) + ); + } + + postDataSetQueriesByInstanceUuid(file: File, uuid: string): Observable { + const url = `./api/v1/dataSetQueries/upload?instance=${uuid}`; + const formData: FormData = new FormData(); + formData.append('file', file, file.name); + const httpOptions = { + headers: new HttpHeaders({}), + }; + return this.httpClient.post(url, formData, httpOptions).pipe( + map((response: any) => response.body), catchError((error: any) => of(error)) ); } diff --git a/ui/src/app/shared/shared.modules.ts b/ui/src/app/shared/shared.modules.ts index bfc7ba7f..6e63f03b 100755 --- a/ui/src/app/shared/shared.modules.ts +++ b/ui/src/app/shared/shared.modules.ts @@ -38,7 +38,7 @@ import { modals } from './modals'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; - +// feature/import-export @NgModule({ imports: [CommonModule, ...materialModules, NgxDhis2PeriodFilterModule], exports: [
Import export works!