Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ native init threw).
| `stream` | `android` / `ios` | Traffic stream label; defaults to the current platform |
| `autoSendPushToken` | `true` | Fetches and sends the push token during init |
| `needReInitialization` | `false` | Forces a fresh session / device id |
| `enableAutoPopupPresentation` | `true` | Shows server popups without an `onPopup` handler, see [Popups](#popups) |

Push delivery needs platform setup of its own — a Firebase config on Android, the
Push Notifications capability on iOS. Without it initialization still succeeds;
Expand Down Expand Up @@ -138,6 +139,98 @@ without an id resolves only while exactly one shop is registered, and throws
never registered).


## Popups

Popups made in the REES46 admin arrive with the responses to init and tracking
calls. The SDK shows them over the app's root navigator — the one `MaterialApp`,
`CupertinoApp` or `MaterialApp.router` builds — with nothing to set up.

A popup sits in the centre, at the top or at the bottom as set in the admin, and
fills the screen when no position is set. It waits out the delay set in the admin,
one is shown at a time, and one shown within the last minute is not shown again.
The link button opens its link, the push-subscription button opens the app's
notification settings. A popup is reported as shown once it is on screen.

To decide yourself — hold a popup back on a checkout screen, or draw it your way —
take popups with `onPopup`. The SDK then shows nothing:

```dart
sdk.onPopup = (InAppPopup popup) {
if (onCheckout) {
held = popup; // later: sdk.presentPopup(held!)
return;
}
showDialog(
context: context,
builder: (context) => Center(
child: SizedBox(
width: 370,
// Unbounded in height, the popup takes the height of its content.
child: SingleChildScrollView(
child: PersonalizationInAppPopup(
view: popup.imageUrl == null
? PersonalizationInAppPopupView.text
: PersonalizationInAppPopupView.image,
title: popup.title,
text: popup.text,
actionText: popup.actionText,
closeText: popup.closeText,
image: popup.imageUrl == null ? null : NetworkImage(popup.imageUrl!),
onAction: () {
Navigator.pop(context);
// Open popup.linkUrl, or the notification settings when
// popup.pushSubscribeText is set — with url_launcher, for instance.
},
onClose: () => Navigator.pop(context),
),
),
),
),
);
sdk.tracking.popupShown(popup.id); // the SDK reports only what it shows itself
};
```

`sdk.presentPopup(popup)` shows a popup the way the SDK does and reports it. With
`enableAutoPopupPresentation: false` and no `onPopup`, popups are not shown.

## UI theme

The SDK's UI (popups, for now) is drawn in the REES46 design. Set your brand once, in
`main` before `runApp`; it applies in `MaterialApp`, `CupertinoApp` and without
either:

```dart
PersonalizationTheme.configure(
lightColors: PersonalizationColors.light.copyWith(
brandPrimary: const Color(0xFF7C3AED),
buttonPrimary: const Color(0xFF7C3AED),
),
darkColors: PersonalizationColors.dark.copyWith(
brandPrimary: const Color(0xFFA78BFA),
buttonPrimary: const Color(0xFFA78BFA),
),
fontFamily: const PersonalizationFontFamily(regular: 'Inter', emphasized: 'Inter'),
);
```

- Colours are set per scheme, font and radii once for both. Anything left out stays
as designed, so start from `PersonalizationColors.light` / `.dark` and change only
what you need.
- Without `darkColors` the dark scheme takes the brand colours (brand, primary
button, brand line and text) from `lightColors`, the rest from the design.
- The font families must be declared in your `pubspec.yaml`; pass `package:` for
fonts that come from another package.

Light or dark follows the app — its Material theme, else its Cupertino theme, else
the device setting. To keep the SDK's UI one way whatever the app is in:

```dart
PersonalizationTheme.mode = ThemeMode.dark; // or ThemeMode.light; ThemeMode.system by default
```

Both settings can change at runtime; what is on screen is redrawn.

## Track events

Standard events live in the `tracking` namespace of the handle:
Expand Down
2 changes: 1 addition & 1 deletion android/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ android {

dependencies {
// REES46 Android SDK.
val rees46AndroidSdkVersion = "v2.42.0"
val rees46AndroidSdkVersion = "v2.45.0"
add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion")

// Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK
Expand Down
45 changes: 45 additions & 0 deletions android/src/main/kotlin/com/rees46/rees46_flutter_sdk/PopupJson.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.rees46.rees46_flutter_sdk

import com.personalization.sdk.data.models.dto.popUp.PopupDto
import org.json.JSONObject

/**
* The popup as the server sends it — the keys the native SDK parsed it from — so Dart reads
* one shape from both platforms.
*/
internal fun PopupDto.toJson(): JSONObject = JSONObject().apply {
put("id", id)
put("position", position.value)
put("delay", delay)
components?.let { components ->
put(
"components",
JSONObject()
.put("header", components.header)
.put("text", components.text)
.put("image", components.image)
.put("button", components.button)
.put("header_enabled", components.headerEnabled)
.put("text_enabled", components.textEnabled)
.put("image_enabled", components.imageEnabled),
)
}
popupActions?.let { actions ->
val json = JSONObject()
actions.link?.let { link ->
json.put(
"link",
JSONObject()
.put("link_android", link.linkAndroid)
.put("link_ios", link.linkIos)
.put("link_web", link.linkWeb)
.put("button_text", link.buttonText),
)
}
actions.close?.let { json.put("close", JSONObject().put("button_text", it.buttonText)) }
actions.pushSubscribe?.let {
json.put("system_mobile_push_subscribe", JSONObject().put("button_text", it.buttonText))
}
put("popup_actions", json)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,23 @@ import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.os.SystemClock
import com.rees46.rees46_flutter_sdk.pigeon.FlutterError
import com.rees46.rees46_flutter_sdk.pigeon.InitConfig
import com.rees46.rees46_flutter_sdk.pigeon.ManageSubscriptionParamsWire
import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationFlutterApi
import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationHostApi
import com.rees46.rees46_flutter_sdk.pigeon.PersonalizationPopupFlutterApi
import com.rees46.rees46_flutter_sdk.pigeon.ProfileParamsWire
import com.rees46.rees46_flutter_sdk.pigeon.PurchaseLineItemWire
import com.rees46.rees46_flutter_sdk.pigeon.TrackingItemWire
import com.rees46.rees46_flutter_sdk.pigeon.TrackingSourceWire
import com.google.gson.Gson
import com.personalization.Params
import com.personalization.PopupPresentationListener
import com.personalization.PushEventType
import com.personalization.PushProvider
import com.personalization.Rees46
Expand Down Expand Up @@ -56,6 +60,7 @@ class Rees46FlutterSdkPlugin :
private lateinit var applicationContext: Context
private val coroutineScope = CoroutineScope(Dispatchers.Main + Job())
private var flutterApi: PersonalizationFlutterApi? = null
private var popupApi: PersonalizationPopupFlutterApi? = null
private var activityBinding: ActivityPluginBinding? = null

private val onNewIntentListener =
Expand All @@ -70,11 +75,13 @@ class Rees46FlutterSdkPlugin :
applicationContext = flutterPluginBinding.applicationContext
PersonalizationHostApi.setUp(flutterPluginBinding.binaryMessenger, this)
flutterApi = PersonalizationFlutterApi(flutterPluginBinding.binaryMessenger)
popupApi = PersonalizationPopupFlutterApi(flutterPluginBinding.binaryMessenger)
}

override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
PersonalizationHostApi.setUp(binding.binaryMessenger, null)
flutterApi = null
popupApi = null
coroutineScope.cancel()
}

Expand Down Expand Up @@ -149,7 +156,16 @@ class Rees46FlutterSdkPlugin :
)
// F3: initialize (and register) the instance through the multi-instance
// `Rees46` facade so it is reachable by shopId via Rees46.getInstance.
Rees46.initialize(context = applicationContext, config = shopConfig)
val sdk = Rees46.initialize(context = applicationContext, config = shopConfig)

// Dart draws popups with the UI kit: every popup is kept back from the native SDK
// (null — not shown, not reported, not remembered) and handed over. Dart decides
// whether to show it, and reports it once it is on screen. The listener runs on the
// main thread, where the Pigeon channel has to be called.
sdk.popupPresentationListener = PopupPresentationListener { _, popup ->
runCatching { popupApi?.onPopup(shopId, popup.toJson().toString()) { _ -> } }
null
}

// Persist so the cold-start push provider (Rees46PushInitProvider) can re-register this
// shop on a process FCM spins up before Dart runs — otherwise the registry is empty and
Expand Down Expand Up @@ -539,6 +555,28 @@ class Rees46FlutterSdkPlugin :
}
}

override fun trackPopupShown(popupId: Long, shopId: String?, callback: (Result<Unit>) -> Unit) =
trackingCall(callback, shopId) {
it.popupShown(popupId.toInt(), trackingListener(callback))
}

override fun openNotificationSettings() {
val packageName = applicationContext.packageName
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
} else {
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:$packageName"))
}
val activity = activityBinding?.activity
if (activity == null) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
(activity ?: applicationContext).startActivity(intent)
} catch (e: ActivityNotFoundException) {
android.util.Log.w(Rees46PushNotifier.TAG, "No notification settings screen", e)
}
}

// region stories viewer (UI kit)

override fun getStoriesSeen(shop: String): Map<String, List<String>> =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,18 @@ interface PersonalizationHostApi {
fun trackSetSource(source: TrackingSourceWire, shopId: String?)
/** [customJson] and [recommendedSourceJson] are JSON object strings or null. */
fun trackPurchase(orderId: String, orderPrice: Double, items: List<PurchaseLineItemWire>, deliveryType: String?, deliveryAddress: String?, paymentType: String?, isTaxFree: Boolean, isGiftPackage: Boolean, promocode: String?, orderCash: Double?, orderBonuses: Double?, orderDelivery: Double?, orderDiscount: Double?, channel: String?, customJson: String?, recommendedSourceJson: String?, stream: String?, segment: String?, shopId: String?, callback: (Result<Unit>) -> Unit)
/**
* Reports popup [popupId] as shown (`popup/showed`) — native `tracking.popupShown`
* (Android) / `trackPopupShown` (iOS). The native SDKs never show a popup themselves
* under the plugin, so they never report one either: Dart does, once it is on screen.
*/
fun trackPopupShown(popupId: Long, shopId: String?, callback: (Result<Unit>) -> Unit)
/**
* Opens the system settings where the user turns notifications on for the app: the
* app's notification settings on Android, the app's page in Settings on iOS. What the
* native popups do for their push-subscription button.
*/
fun openNotificationSettings()

companion object {
/** The codec used by PersonalizationHostApi. */
Expand Down Expand Up @@ -1546,6 +1558,79 @@ interface PersonalizationHostApi {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.trackPopupShown$separatedMessageChannelSuffix", codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val popupIdArg = args[0] as Long
val shopIdArg = args[1] as String?
api.trackPopupShown(popupIdArg, shopIdArg) { result: Result<Unit> ->
val error = result.exceptionOrNull()
if (error != null) {
reply.reply(PersonalizationApiPigeonUtils.wrapError(error))
} else {
reply.reply(PersonalizationApiPigeonUtils.wrapResult(null))
}
}
}
} else {
channel.setMessageHandler(null)
}
}
run {
val channel = BasicMessageChannel<Any?>(binaryMessenger, "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationHostApi.openNotificationSettings$separatedMessageChannelSuffix", codec)
if (api != null) {
channel.setMessageHandler { _, reply ->
val wrapped: List<Any?> = try {
api.openNotificationSettings()
listOf(null)
} catch (exception: Throwable) {
PersonalizationApiPigeonUtils.wrapError(exception)
}
reply.reply(wrapped)
}
} else {
channel.setMessageHandler(null)
}
}
}
}
}
/**
* Server popups, handed over instead of being shown natively: the plugin sets the native
* presentation listener (Android) / delegate (iOS), which keeps every popup back and
* forwards it here. Separate from [PersonalizationFlutterApi], which the push dispatcher
* owns.
*
* Generated class from Pigeon that represents Flutter messages that can be called from Kotlin.
*/
class PersonalizationPopupFlutterApi(private val binaryMessenger: BinaryMessenger, private val messageChannelSuffix: String = "") {
companion object {
/** The codec used by PersonalizationPopupFlutterApi. */
val codec: MessageCodec<Any?> by lazy {
PersonalizationApiPigeonCodec()
}
}
/**
* A popup arrived for [shopId]. [popupJson] is the popup as the server sends it:
* `id`, `position`, `delay`, `components` and `popup_actions` (an object).
*/
fun onPopup(shopIdArg: String, popupJsonArg: String, callback: (Result<Unit>) -> Unit)
{
val separatedMessageChannelSuffix = if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else ""
val channelName = "dev.flutter.pigeon.personalization_flutter_sdk.PersonalizationPopupFlutterApi.onPopup$separatedMessageChannelSuffix"
val channel = BasicMessageChannel<Any?>(binaryMessenger, channelName, codec)
channel.send(listOf(shopIdArg, popupJsonArg)) {
if (it is List<*>) {
if (it.size > 1) {
callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?)))
} else {
callback(Result.success(Unit))
}
} else {
callback(Result.failure(PersonalizationApiPigeonUtils.createConnectionError(channelName)))
}
}
}
}
Expand Down
Loading
Loading