grantChance method
Implementation
@override
Future<GrantChanceResult> grantChance(GrantChanceRequest request) async {
final client = _client();
if (client == null) return const GrantFailed(GameOutcomeFailure.transport);
final body = <String, Object?>{
'campaignKey': request.campaignKey,
'userId': request.userId,
'triggerId': request.triggerId,
'showNow': request.showNow,
if (request.userHash != null) 'userHash': request.userHash,
if (request.testInvocationId != null)
'testInvocationId': request.testInvocationId,
};
final deviceId = request.deviceId;
final headers = {
'Content-Type': 'application/json',
if (request.testInvocationId != null &&
deviceId != null &&
deviceId.trim().isNotEmpty)
'x-digia-device-id': deviceId,
};
final post = await _post(client, DigiaEndpoints.gamificationGrantChance,
body, headers, request.campaignKey);
final response = post.response;
if (response == null) {
return GrantFailed(GameOutcomeFailure.transport, null, post.timedOut);
}
if (!response.isSuccessful) {
return GrantFailed(GameOutcomeFailure.httpStatus, response.statusCode);
}
final payload = _responseBody(response.body, request.campaignKey);
if (payload == null) {
return GrantFailed(
GameOutcomeFailure.invalidResponse, response.statusCode);
}
// Strict like iOS: `granted` must be a real boolean, and a granted chance
// must carry a non-blank `chanceId`.
final granted = payload['granted'];
if (granted is! bool) {
_invalid(
'Gamification response has no granted flag', request.campaignKey);
return GrantFailed(
GameOutcomeFailure.invalidResponse, response.statusCode);
}
// A server that still sends its own events wins; otherwise the SDK builds
// them from the answer's facts, as Android does.
final serverEvents =
chanceEventsOf(payload['events'], campaignKey: request.campaignKey);
List<ChanceAnalyticsEvent> eventsFor(String? chanceId) =>
serverEvents.isNotEmpty
? serverEvents
: grantEventsOf(
payload,
granted: granted,
chanceId: chanceId,
userId: request.userId,
triggerId: request.triggerId,
testInvocationId: request.testInvocationId,
);
if (!granted) {
return ChanceDenied(_nonBlank(payload['denyReason']), eventsFor(null));
}
final chanceId = _nonBlank(payload['chanceId']);
if (chanceId == null) {
_invalid('Gamification response granted without a chanceId',
request.campaignKey);
return GrantFailed(
GameOutcomeFailure.invalidResponse, response.statusCode);
}
return ChanceGranted(chanceId, _nonBlank(payload['expiresAt']),
show: payload['show'] == true, events: eventsFor(chanceId));
}