createOrModifyHealthcareElements method
Future<List<HealthcareElement> ?>
createOrModifyHealthcareElements(
- String patientId,
- List<
HealthcareElement> healthcareElements
override
Implementation
@override
Future<List<HealthcareElement>?> createOrModifyHealthcareElements(String patientId, List<HealthcareElement> healthcareElements) async {
final localCrypto = api.crypto;
final currentUser = (await api.baseUserApi.getCurrentUser())
?? (throw StateError("There is no user currently logged in. You must call this method from an authenticated MedTechApi"));
final ccHealthElement = healthElementCryptoConfig(localCrypto);
final ccPatient = patientCryptoConfig(localCrypto);
final healthcareElementsToCreate = healthcareElements.where((element) => element.rev == null).toSet();
final healthcareElementsToUpdate = healthcareElements.toSet().difference(healthcareElementsToCreate).toSet();
if (healthcareElementsToUpdate.any((element) => element.id == null || !Uuid.isValidUUID(fromString: element.id!))) {
throw FormatException("Error while updating: HealthcareElement id should be provided as an UUID v4 (String)");
}
final healthElementDtosToUpdate = healthcareElementsToUpdate.map((e) => e.toHealthElementDto()).toList();
final healthElementDtosToCreate = healthcareElementsToCreate.map((e) => e.toHealthElementDto()).toList();
final patient = await api.patientApi.getPatientAndTryDecrypt(patientId) ?? (throw StateError("Error while getting patient with id $patientId"));
final heCreated = await api.baseHealthElementApi.createHealthElementsWithPatientInfo(
currentUser,
patient.id!,
patient.systemMetaData!.delegations.toDelegationMapDto(),
healthElementDtosToCreate,
ccHealthElement
);
final heUpdated = await api.baseHealthElementApi.modifyHealthElements(currentUser, healthElementDtosToUpdate, ccHealthElement);
final heProcessed = [...?heCreated, ...heUpdated];
return heProcessed.map((e) => e.toHealthcareElement()).toList();
}