state method

  1. @override
Future<ChanceStateResult> state(
  1. String campaignKey, {
  2. String? testInvocationId,
  3. String? chanceId,
})
override

The read-only state call after an entry's game closes. chanceId is the closed game's own chance, so a re-trigger cannot answer for it.

Implementation

@override
Future<ChanceStateResult> state(String campaignKey,
    {String? testInvocationId, String? chanceId}) async {
  final client = _client();
  if (client == null) {
    return const ChanceStateFailed(GameOutcomeFailure.transport);
  }
  final body = <String, Object?>{
    'campaignKey': campaignKey,
    if (testInvocationId != null && testInvocationId.trim().isNotEmpty)
      'testInvocationId': testInvocationId,
    if (chanceId != null && chanceId.trim().isNotEmpty)
      'chanceId': chanceId.trim(),
  };
  // Identity rides the headers the network client already sends.
  final post = await _post(client, DigiaEndpoints.gamificationState, body,
      const {'Content-Type': 'application/json'}, campaignKey);
  final response = post.response;
  if (response == null) {
    return ChanceStateFailed(GameOutcomeFailure.transport,
        timedOut: post.timedOut);
  }
  if (!response.isSuccessful) {
    return ChanceStateFailed(GameOutcomeFailure.httpStatus,
        statusCode: response.statusCode);
  }
  final payload = _responseBody(response.body, campaignKey);
  if (payload == null) {
    return ChanceStateFailed(GameOutcomeFailure.invalidResponse,
        statusCode: response.statusCode);
  }
  ChanceStateResult invalid(String message) {
    _invalid(message, campaignKey);
    return ChanceStateFailed(GameOutcomeFailure.invalidResponse,
        statusCode: response.statusCode);
  }

  if (payload.containsKey('refused')) {
    final reason = _nonBlank(payload['refused']);
    if (reason == null) {
      return invalid('Gamification state refused without a reason');
    }
    return ChanceRefused(reason);
  }
  // The next `init` for this chance carries the answer as `chanceState`.
  GameChanceStateCache.record(campaignKey, payload);
  final answeredChanceId = _nonBlank(payload['chanceId']);
  switch (payload['state']) {
    case 'playable':
      if (answeredChanceId == null) {
        return invalid('Gamification state playable without a chanceId');
      }
      return ChancePlayable(
          answeredChanceId, _nonBlank(payload['expiresAt']));
    case 'played':
      if (answeredChanceId == null) {
        return invalid('Gamification state played without a chanceId');
      }
      return ChancePlayed(answeredChanceId);
    case 'expired':
      return const ChanceExpired();
    case 'none':
      return const ChanceNone();
    default:
      return invalid('Gamification state has an unknown state');
  }
}