Files
swiftcontrol/lib/utils/analytics/install_referrer_parser.dart
Jonas Bark 0f5be96bcc feat(attribution): send the campaign to RevenueCat as subscriber attributes
setAttributes() already carried trainer, target, controllers, keymap and the
Supabase user id, but nothing about where the customer came from -- so revenue
could not be attributed to a campaign at all. This adds the Play install
referrer's UTMs on RevenueCat's reserved keys ($campaign, $mediaSource,
$adGroup, $ad) plus bikecontrol_utm_medium, which has no reserved equivalent.

That turns cost-per-install into trial-to-paid conversion and revenue per
campaign -- the difference between "the ads produce clicks" and "the ads
produce customers".

The reporter now persists the raw referrer, because the Play Install Referrer
API is readable only once and early, while RevenueCat attributes have to be
re-sent on every launch.

Corrects the parser's documented exception type while here: splitQueryString
raises ArgumentError on a bad percent escape, not FormatException.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 20:15:58 +02:00

47 lines
1.7 KiB
Dart

/// The only UTM keys this product captures, matching `UTM_KEYS` in the
/// website's `src/utils/utm.ts`.
const List<String> utmKeys = <String>['utm_source', 'utm_medium', 'utm_campaign', 'utm_content'];
/// Matches `MAX_VALUE_LENGTH` on the website and `MAX_UTM_LENGTH` in the
/// track-analytics edge function, which truncates anything longer anyway.
const int _maxValueLength = 200;
/// Pulls UTM parameters out of a Google Play install referrer.
///
/// The referrer is a bare query string such as
/// `utm_source=facebook&utm_medium=paid`. Organic installs get Play's own
/// value (`utm_source=google-play&utm_medium=organic`), which is worth keeping
/// — it is how paid and organic installs are told apart.
///
/// Throws [FormatException] if the referrer contains malformed percent-encoding.
/// Callers must catch and route that through `recordError`.
Map<String, String> parseInstallReferrer(String? referrer) {
if (referrer == null || referrer.trim().isEmpty) return const <String, String>{};
final Map<String, String> params;
try {
params = Uri.splitQueryString(referrer);
} on FormatException {
rethrow;
} catch (e) {
// Uri.splitQueryString throws ArgumentError (not FormatException) for
// malformed percent-encoding, e.g. a truncated '%' or an invalid escape.
// Normalise to FormatException so callers can rely on a single type.
throw FormatException('Malformed install referrer: $referrer ($e)');
}
final result = <String, String>{};
for (final key in utmKeys) {
final raw = params[key];
if (raw == null) continue;
var value = raw.trim();
if (value.length > _maxValueLength) {
value = value.substring(0, _maxValueLength);
}
if (value.isNotEmpty) result[key] = value;
}
return result;
}