downloadReservedValueByAttribute method

dynamic downloadReservedValueByAttribute(
  1. ProgramTrackedEntityAttribute reservedAttribute, {
  2. Dio? dioTestClient,
})

Implementation

downloadReservedValueByAttribute(
    ProgramTrackedEntityAttribute reservedAttribute,
    {Dio? dioTestClient}) async {
  final int reservedCount =
      await AttributeReservedValueQuery(database: database)
          .where(attribute: 'attribute', value: reservedAttribute.attribute)
          .count();

  final numberToReserve = 100 - reservedCount;

  if (numberToReserve <= 0) {
    return null;
  }

  List<OrganisationUnit>? userOrganisationUnitInfo =
      await OrganisationUnitQuery(database: database).getUserOrgUnits();

  final response;

  if (userOrganisationUnitInfo != null &&
      userOrganisationUnitInfo.isNotEmpty) {
    OrganisationUnit organisationUnit = userOrganisationUnitInfo[0];
    String code = organisationUnit.code ?? '';

    response = await HttpClient.get(
        'trackedEntityAttributes/${reservedAttribute.attribute}/generateAndReserve?numberToReserve=$numberToReserve&ORG_UNIT_CODE=$code',
        database: database,
        dioTestClient: dioTestClient);
  } else {
    response = await HttpClient.get(
        'trackedEntityAttributes/${reservedAttribute.attribute}/generateAndReserve?numberToReserve=$numberToReserve',
        database: database,
        dioTestClient: dioTestClient);
  }

  List<AttributeReservedValue> reservedValues = [];

  for (dynamic reservedResult in response.body ?? []) {
    // ignore: unnecessary_null_comparison
    if (reservedAttribute != null) {
      reservedValues.add(AttributeReservedValue.fromJson(
          {...reservedResult, 'dirty': false}));
    }
  }

  return AttributeReservedValueQuery(database: database)
      .setData(reservedValues)
      .save();
}