customerIntelligence static method

Future<Result> customerIntelligence()

Implementation

static Future<Result<dynamic>> customerIntelligence() async {
  final result = await checkKwikpassHealth();
  if(result.isSuccess) {
    final healthData = result.getDataOrThrow();
    if(healthData?.isKwikpassHealthy == false){
      throw Exception('Kwikpass is unhealthy');
    }
  }

  final merchantJson =
      await cacheInstance.getValue(cdnConfigInstance.getKeys(StorageKeyKeys.gkMerchantConfig)!);
  if (merchantJson == null) {
    return const Success(null); // No merchant config, not an error.
  }

  final merchant = MerchantConfig.fromJson(jsonDecode(merchantJson));
  if (merchant.customerIntelligenceEnabled != true) {
    return const Success(null);
  }

  final customerIntelligenceMetrics =
      merchant.customerIntelligenceMetrics ?? {};
  final gokwik = DioClient().getClient();

  List<String> reduceKeys(Map<String, dynamic> innerObj) {
    return innerObj.entries.fold([], (List<String> acc, entry) {
      if (entry.value == true) {
        acc.add(entry.key);
      } else if (entry.value is Map) {
        acc.addAll(reduceKeys(entry.value as Map<String, dynamic>));
      }
      return acc;
    });
  }

  final trueKeys = reduceKeys(customerIntelligenceMetrics).toSet().toList();

  try {
    final response = (await gokwik.get(
      cdnConfigInstance.getEndpoint(APIEndpointKeys.customerIntelligence)!,
      queryParameters: {'cstmr-mtrcs': trueKeys.join(',')},
    ))
        .toBaseResponse();
    if (response.isSuccess ?? false) {
      return Success(response.data);
    }

    return Failure(
        response.errorMessage ?? 'Failed to fetch customer intelligence');
  } catch (err) {
    final apiError = handleApiError(err);

    return apiError;
  }
}