createHealthElementsWithPatientInfo method

Future<List<DecryptedHealthElementDto>?> createHealthElementsWithPatientInfo(
  1. UserDto user,
  2. String patientId,
  3. Map<String, Set<DelegationDto>> patientDelegations,
  4. List<DecryptedHealthElementDto> healthElements,
  5. CryptoConfig<DecryptedHealthElementDto, HealthElementDto> config,
)

Implementation

Future<List<DecryptedHealthElementDto>?> createHealthElementsWithPatientInfo(
  UserDto user,
  String patientId,
  Map<String, Set<DelegationDto>> patientDelegations,
  List<DecryptedHealthElementDto> healthElements,
  CryptoConfig<DecryptedHealthElementDto, HealthElementDto> config
) async {
  final String? key = (await config.crypto.decryptEncryptionKeys(user.dataOwnerId()!, patientDelegations)).firstOrNull;
  if (key == null) {
    throw Exception("No delegation for user");
  }

  var delegations = <String>{...(user.autoDelegations["all"] ?? {}), ...(user.autoDelegations["medicalInformation"] ?? {})};
  final Set<String> newDelegations = [...delegations, user.dataOwnerId()!].toSet();
  final Set<String> secretFK = [key].toSet();

  var healthElementsToCreate = await Future.wait(healthElements.map((he) async {
    final secretForDelegates = await Future.wait(
        (newDelegations).map((String d) async => Tuple2(d, await config.crypto.encryptValueForHcp(user.dataOwnerId()!, d, he.id, patientId))));
    final HealthElementDto encryptedHealthElement =
    await config.encryptHealthElement(user.dataOwnerId()!, delegations, await he.initDelegations(user, config));

    encryptedHealthElement.secretForeignKeys = secretFK;
    encryptedHealthElement.cryptedForeignKeys = {
      ...he.cryptedForeignKeys,
      ...Map.fromEntries(secretForDelegates
          .map((t) => MapEntry(t.item1, <DelegationDto>{DelegationDto(owner: user.dataOwnerId()!, delegatedTo: t.item1, key: t.item2.item1)})))
    };

    return encryptedHealthElement;
  }));

  final List<HealthElementDto>? newHealthElements = await this.rawCreateHealthElements(healthElementsToCreate);
  return newHealthElements == null
      ? null
      : await Future.wait(newHealthElements.map((newHealthElement) => config.decryptHealthElement(user.dataOwnerId()!, newHealthElement)));
}