makeGameOpenRequest static method

GameOpenRequest makeGameOpenRequest({
  1. required String entryHtml,
  2. required String chanceId,
  3. required GamificationConfig config,
  4. required CampaignModel campaign,
  5. required CEPTriggerPayload payload,
  6. required String userId,
  7. required GameSettle settle,
  8. String projectId = '',
  9. String? themeFontFamily,
  10. bool warm = false,
  11. String tier = '',
  12. GameOpenTiming? timing,
  13. void reportViewed(
    1. GameViewedEvent event,
    2. CEPTriggerPayload payload
    )?,
  14. void reportClicked(
    1. GameClickedEvent event,
    2. CEPTriggerPayload payload
    )?,
  15. void reportDismissed(
    1. GameDismissedEvent event,
    2. CEPTriggerPayload payload
    )?,
  16. void reportOpenFailed(
    1. GameOpenFailedEvent event,
    2. CEPTriggerPayload payload
    )?,
  17. void reportCepImpressed(
    1. CEPTriggerPayload payload
    )?,
  18. void reportCepClicked(
    1. CEPTriggerPayload payload,
    2. String elementId
    )?,
  19. void reportCepDismissed(
    1. CEPTriggerPayload payload,
    2. String elementId
    )?,
  20. void settleDirectFailure(
    1. CEPTriggerPayload payload,
    2. String elementId
    )?,
  21. void reportChanceEvents(
    1. List<ChanceAnalyticsEvent> events,
    2. CEPTriggerPayload payload
    )?,
})

Implementation

static GameOpenRequest makeGameOpenRequest({
  required String entryHtml,
  required String chanceId,
  required GamificationConfig config,
  required CampaignModel campaign,
  required CEPTriggerPayload payload,
  required String userId,
  required GameSettle settle,
  String projectId = '',
  String? themeFontFamily,
  bool warm = false,
  String tier = '',
  GameOpenTiming? timing,
  void Function(GameViewedEvent event, CEPTriggerPayload payload)?
      reportViewed,
  void Function(GameClickedEvent event, CEPTriggerPayload payload)?
      reportClicked,
  void Function(GameDismissedEvent event, CEPTriggerPayload payload)?
      reportDismissed,
  void Function(GameOpenFailedEvent event, CEPTriggerPayload payload)?
      reportOpenFailed,
  void Function(CEPTriggerPayload payload)? reportCepImpressed,
  void Function(CEPTriggerPayload payload, String elementId)?
      reportCepClicked,
  void Function(CEPTriggerPayload payload, String reason)? reportCepDismissed,
  void Function(CEPTriggerPayload payload, String reason)?
      settleDirectFailure,
  void Function(List<ChanceAnalyticsEvent> events, CEPTriggerPayload payload)?
      reportChanceEvents,
}) {
  // What this window did, for `Dismissed`: one per open, so play again
  // and play next keep counting into the same window.
  final stats = GameWindowStats(chanceId);
  var shown = false;
  // Answered plays this open, for the play/play_again CEP click.
  var answeredPlays = 0;
  GameDismissedEvent buildDismissed(String reason) => GameDismissedEvent(
        reason: reason,
        dwellMs: stats.dwellMs(),
        chanceId: stats.chanceId,
        skinId: config.skinId,
        skinVersion: config.skinVersion,
        plays: stats.plays,
        playRefused: stats.playRefused,
        entry: entryValueOf(settle),
      );
  final entryValue = entryValueOf(settle);
  bool isDirectPresentation() => switch (settle) {
        GameSettlePresentation(:final entry) =>
          entry == GamificationEntryKind.direct ||
              entry == GamificationEntryKind.unknown,
        _ => false,
      };
  bool isLiveTest() {
    try {
      return isLiveTestCepId(payload.cepCampaignId);
    } catch (_) {
      return false;
    }
  }

  void failRequest(String reason) {
    if (reason == 'busy') return;
    try {
      reportOpenFailed?.call(
        GameOpenFailedEvent(
          reason: reason,
          chanceId: chanceId,
          entry: entryValue,
          skinId: config.skinId,
          skinVersion: config.skinVersion,
          stage: timing?.stage?.wire ?? '',
        ),
        payload,
      );
    } catch (_) {}
    if (isDirectPresentation()) {
      try {
        settleDirectFailure?.call(payload, reason);
      } catch (_) {}
    }
  }

  /// A close before the first `ready`: the game never showed, so it fails
  /// instead of dismissing. `cancelled` and `superseded` keep their reason;
  /// anything ordinary reads `closed_before_ready`.
  void failForEarlyClose(String reason) {
    switch (reason) {
      case 'cancelled' || 'superseded' || 'screen_exit' || 'http_timeout':
        failRequest(reason);
      default:
        failRequest(GameFailureReason.closedBeforeReady.wireValue);
    }
  }

  // Resolve the marketer's text here: the skin only gets finished values.
  final scope = campaign.config.scopeFor(payload);
  // A live-test game carries its invocation into the skin's `state` call,
  // so a draft campaign answers for the test chance, not the user's real one.
  return GameOpenRequest(
    campaignKey: campaign.campaignKey,
    campaignId: campaign.campaignUid,
    skinId: config.skinId,
    skinVersion: config.skinVersion,
    chanceId: chanceId,
    testInvocationId:
        isLiveTest() ? testInvocationIdOf(payload.cepCampaignId) : null,
    projectId: projectId,
    userId: userId,
    entryHtml: entryHtml,
    showMute: config.showMute,
    showClose: config.showClose,
    payload: payload,
    entry: entryValue,
    themeFontFamily: themeFontFamily,
    themeFontsJson: _fontsJsonOf(config),
    valuesJson: _jsonOr(resolveGameValues(config.values, scope), '{}'),
    slotsJson: _slotsJsonOf(resolveGameSlots(config.slots, scope)),
    onClose: (reason) {
      // Never shown: no Dismissed without a Viewed — fail instead.
      if (!shown) {
        failForEarlyClose(reason);
        _log.d('Game closed before ready (reason=$reason, entry=$entryValue)',
            campaign: campaign.campaignKey);
        return;
      }
      final dismissedReason = gameDismissReason(reason);
      try {
        reportDismissed?.call(buildDismissed(dismissedReason), payload);
      } catch (_) {}
      if (isDirectPresentation()) {
        try {
          reportCepDismissed?.call(payload, dismissReason(reason));
        } catch (_) {}
      }
      _log.d('Game closed (reason=$reason, entry=$entryValue)',
          campaign: campaign.campaignKey);
    },
    onFailure: (reason) {
      if (shown) {
        try {
          reportDismissed?.call(buildDismissed('failure'), payload);
        } catch (_) {}
        if (isDirectPresentation()) {
          try {
            settleDirectFailure?.call(payload, reason.wireValue);
          } catch (_) {}
        }
        return;
      }
      failRequest(reason.wireValue);
    },
    onCta: (op) {
      // A skin CTA op ran: the funnel Clicked to Digia only. The CEP
      // click is the first play of a direct game, or the entry tap,
      // never a CTA.
      try {
        reportClicked?.call(
            GameClickedEvent(op, stats.chanceId, entry: entryValue), payload);
      } catch (_) {}
    },
    onShown: () {
      // A re-sent `ready` counts the impression once.
      if (shown) return;
      shown = true;
      stats.start();
      try {
        timing?.mark(GameOpenStage.ready);
      } catch (_) {}
      int msToReady = -1;
      try {
        msToReady = timing?.msToReady ?? -1;
      } catch (_) {}
      try {
        reportViewed?.call(
            GameViewedEvent(
              stats.chanceId,
              config.skinId,
              config.skinVersion,
              entry: entryValue,
              warm: warm,
              tier: tier,
              msToReady: msToReady,
            ),
            payload);
      } catch (_) {}
      // Only a Direct Viewed impresses the CEP: an entry-opened game
      // skips since its teaser already impressed.
      if (isDirectPresentation()) {
        try {
          reportCepImpressed?.call(payload);
        } catch (_) {}
      }
    },
    onHttpAnswer: (path, request, response) {
      stats.recordHttp(path, request, response);
      if (path != 'play') return;
      // The play answer's chance events go to Digia only , never
      // the CEP and never for a live test; the skin already got the body
      // unchanged.
      var serverEvents = 0;
      try {
        final events =
            chanceEventsOfAnswer(response, campaignKey: campaign.campaignKey);
        serverEvents = events.length;
        if (events.isNotEmpty && !isLiveTest()) {
          reportChanceEvents?.call(events, payload);
        }
      } catch (_) {}
      // A `GamePlayed` from the answer facts covers a silent server: only
      // when the answer carried no events of its own.
      if (serverEvents == 0 && !isLiveTest()) {
        try {
          final played = gamePlayedEventOfAnswer(
            playResponseOf(response),
            campaignId: campaign.campaignKey,
            entry: entryValue,
            playNumber: stats.plays == 0 ? 1 : stats.plays,
            chanceId: stats.chanceId,
          );
          if (played != null) reportChanceEvents?.call([played], payload);
        } catch (_) {}
      }
      // The CEP play click: a direct game's first answered play clicks
      // `play`, later ones `play_again`. An entry-opened game's first
      // play skips — the entry tap was the click — and later ones click
      // `play_again`.
      if (isDirectPresentation()) {
        answeredPlays++;
        try {
          reportCepClicked?.call(
              payload, answeredPlays == 1 ? 'play' : 'play_again');
        } catch (_) {}
      } else if (settle is GameSettlePresentation) {
        answeredPlays++;
        if (answeredPlays > 1) {
          try {
            reportCepClicked?.call(payload, 'play_again');
          } catch (_) {}
        }
      }
    },
    onHttpTimeout: (path) {
      // A shown hang settles `http_timeout`; a loading one fails to open.
      if (shown) {
        try {
          reportDismissed?.call(buildDismissed('http_timeout'), payload);
        } catch (_) {}
        if (isDirectPresentation()) {
          try {
            reportCepDismissed?.call(payload, dismissReason('http_timeout'));
          } catch (_) {}
        }
        return;
      }
      failRequest('http_timeout');
    },
    onForeground: (foreground) => stats.setForeground(foreground),
  );
}