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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ await sdk.tracking.purchase(
deliveryAddress: 'Tverskaya 1, Moscow',
paymentType: 'card',
isTaxFree: false,
isGiftPackage: true,
promocode: 'WINTER20',
orderCash: 100.0,
orderBonuses: 49.8,
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.37.0"
val rees46AndroidSdkVersion = "v2.38.0"
add("rees46Implementation", "com.github.rees46:android-sdk:$rees46AndroidSdkVersion")

// Used directly by the push presenter (NotificationCompat / ContextCompat). The native SDK
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@ import com.personalization.SDK
import com.personalization.api.OnApiCallbackListener
import com.personalization.sdk.data.models.params.UserBasicParams
import com.rees46.rees46_flutter_sdk.pigeon.FlutterError
import com.rees46.rees46_flutter_sdk.pigeon.PurchaseLineItemWire
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

/**
* Builds tracking JSON and posts via [SDK.sendAsync] for published `rees46-sdk` artifacts that do not
* expose `SDK.trackEvent` / `SDK.trackPurchase` (wire format aligned with personalization-sdk
* `TrackEventManagerImpl` and `PurchaseTrackingJsonBuilder`).
* Builds custom-event JSON and posts via [SDK.sendAsync] for published `rees46-sdk` artifacts that do
* not expose `SDK.trackEvent` (wire format aligned with personalization-sdk `TrackEventManagerImpl`).
*
* Purchases do not go through here: the plugin hands them to `sdk.tracking.purchase`, so the wire
* format, the validation and the reserved-key rules live in the native SDK alone.
*/
internal object FlutterTrackingBridge {
private const val CUSTOM_PUSH_PATH = "push/custom"
private const val PURCHASE_PUSH_PATH = "push"

private const val TRACK_EVENT_CLIENT_ERROR_CODE = -1
private const val TRACK_PURCHASE_CLIENT_ERROR_CODE = -2

private const val KEY_EVENT = "event"
private const val KEY_TIME = "time"
Expand Down Expand Up @@ -51,56 +50,6 @@ internal object FlutterTrackingBridge {
add(KEY_CODE)
}

private object PurchaseWireKeys {
const val EVENT = "event"
const val PURCHASE_EVENT_VALUE = "purchase"
const val ITEMS = "items"
const val ID = "id"
const val AMOUNT = "amount"
const val PRICE = "price"
const val LINE_ID = "line_id"
const val FASHION_SIZE = "fashion_size"
const val ORDER_ID = "order_id"
const val ORDER_PRICE = "order_price"
const val DELIVERY_TYPE = "delivery_type"
const val DELIVERY_ADDRESS = "delivery_address"
const val PAYMENT_TYPE = "payment_type"
const val TAX_FREE = "tax_free"
const val PROMOCODE = "promocode"
const val ORDER_CASH = "order_cash"
const val ORDER_BONUSES = "order_bonuses"
const val ORDER_DELIVERY = "order_delivery"
const val ORDER_DISCOUNT = "order_discount"
const val CHANNEL = "channel"
const val CUSTOM = "custom"
const val RECOMMENDED_SOURCE = "recommended_source"
const val RECOMMENDED_BY = "recommended_by"
const val RECOMMENDED_CODE = "recommended_code"
}

private val RESERVED_PURCHASE_CUSTOM_KEYS: Set<String> =
RESERVED_CUSTOM_EVENT_KEYS +
setOf(
PurchaseWireKeys.EVENT,
PurchaseWireKeys.ITEMS,
PurchaseWireKeys.ORDER_ID,
PurchaseWireKeys.ORDER_PRICE,
PurchaseWireKeys.DELIVERY_TYPE,
PurchaseWireKeys.DELIVERY_ADDRESS,
PurchaseWireKeys.PAYMENT_TYPE,
PurchaseWireKeys.TAX_FREE,
PurchaseWireKeys.PROMOCODE,
PurchaseWireKeys.ORDER_CASH,
PurchaseWireKeys.ORDER_BONUSES,
PurchaseWireKeys.ORDER_DELIVERY,
PurchaseWireKeys.ORDER_DISCOUNT,
PurchaseWireKeys.CHANNEL,
PurchaseWireKeys.CUSTOM,
PurchaseWireKeys.RECOMMENDED_SOURCE,
PurchaseWireKeys.RECOMMENDED_BY,
PurchaseWireKeys.RECOMMENDED_CODE,
)

fun postTrackEvent(
sdk: SDK,
event: String,
Expand Down Expand Up @@ -170,237 +119,6 @@ internal object FlutterTrackingBridge {
)
}

fun postTrackPurchase(
sdk: SDK,
orderId: String,
orderPrice: Double,
items: List<PurchaseLineItemWire>,
deliveryType: String?,
deliveryAddress: String?,
paymentType: String?,
isTaxFree: Boolean,
promocode: String?,
orderCash: Double?,
orderBonuses: Double?,
orderDelivery: Double?,
orderDiscount: Double?,
channel: String?,
custom: Map<String, Any?>?,
recommendedSource: JSONObject?,
stream: String?,
segment: String?,
callback: (Result<Unit>) -> Unit,
) {
val buildResult = buildPurchaseJsonOrError(
orderId = orderId,
orderPrice = orderPrice,
items = items,
deliveryType = deliveryType,
deliveryAddress = deliveryAddress,
paymentType = paymentType,
isTaxFree = isTaxFree,
promocode = promocode,
orderCash = orderCash,
orderBonuses = orderBonuses,
orderDelivery = orderDelivery,
orderDiscount = orderDiscount,
channel = channel,
custom = custom,
recommendedSource = recommendedSource,
stream = stream,
segment = segment,
)
if (buildResult.isFailure) {
callback(
Result.failure(
FlutterError(
"track_purchase_failed",
buildResult.exceptionOrNull()?.message ?: "validation failed",
mapOf("code" to TRACK_PURCHASE_CLIENT_ERROR_CODE),
),
),
)
return
}
val body = buildResult.getOrNull()!!

@Suppress("DEPRECATION")
sdk.sendAsync(
PURCHASE_PUSH_PATH,
body,
object : OnApiCallbackListener() {
override fun onSuccess(response: JSONObject?) {
callback(Result.success(Unit))
}

override fun onError(code: Int, msg: String?) {
val message = listOfNotNull(code.toString(), msg).joinToString(": ")
callback(Result.failure(FlutterError("track_purchase_failed", message, null)))
}
},
)
}

private fun buildPurchaseJsonOrError(
orderId: String,
orderPrice: Double,
items: List<PurchaseLineItemWire>,
deliveryType: String?,
deliveryAddress: String?,
paymentType: String?,
isTaxFree: Boolean,
promocode: String?,
orderCash: Double?,
orderBonuses: Double?,
orderDelivery: Double?,
orderDiscount: Double?,
channel: String?,
custom: Map<String, Any?>?,
recommendedSource: JSONObject?,
stream: String?,
segment: String?,
): Result<JSONObject> {
if (orderId.isBlank()) {
return Result.failure(IllegalArgumentException("trackPurchase: orderId must be non-empty"))
}
if (items.isEmpty()) {
return Result.failure(IllegalArgumentException("trackPurchase: items must not be empty"))
}
for (item in items) {
if (item.id.isBlank()) {
return Result.failure(IllegalArgumentException("trackPurchase: each item.id must be non-empty"))
}
if (item.amount <= 0) {
return Result.failure(IllegalArgumentException("trackPurchase: each item.amount must be > 0"))
}
if (!item.price.isFinite()) {
return Result.failure(IllegalArgumentException("trackPurchase: each item.price must be a finite number"))
}
}
if (!orderPrice.isFinite()) {
return Result.failure(IllegalArgumentException("trackPurchase: orderPrice must be a finite number"))
}

val effectiveCustom = effectiveCustomFields(custom)
if (effectiveCustom.isNotEmpty()) {
val collisions = effectiveCustom.keys.intersect(RESERVED_PURCHASE_CUSTOM_KEYS)
if (collisions.isNotEmpty()) {
return Result.failure(
IllegalArgumentException(
"trackPurchase: custom contains reserved keys: ${collisions.toSortedSet().joinToString(", ")}",
),
)
}
}

return try {
Result.success(
buildPurchaseJson(
orderId = orderId,
orderPrice = orderPrice,
items = items,
deliveryType = deliveryType,
deliveryAddress = deliveryAddress,
paymentType = paymentType,
isTaxFree = isTaxFree,
promocode = promocode,
orderCash = orderCash,
orderBonuses = orderBonuses,
orderDelivery = orderDelivery,
orderDiscount = orderDiscount,
channel = channel,
effectiveCustom = effectiveCustom,
recommendedSource = recommendedSource,
stream = stream,
segment = segment,
),
)
} catch (e: JSONException) {
Result.failure(IllegalArgumentException("trackPurchase: failed to build JSON: ${e.message}", e))
}
}

private fun buildPurchaseJson(
orderId: String,
orderPrice: Double,
items: List<PurchaseLineItemWire>,
deliveryType: String?,
deliveryAddress: String?,
paymentType: String?,
isTaxFree: Boolean,
promocode: String?,
orderCash: Double?,
orderBonuses: Double?,
orderDelivery: Double?,
orderDiscount: Double?,
channel: String?,
effectiveCustom: Map<String, Any>,
recommendedSource: JSONObject?,
stream: String?,
segment: String?,
): JSONObject {
val root = JSONObject()
root.put(PurchaseWireKeys.EVENT, PurchaseWireKeys.PURCHASE_EVENT_VALUE)
root.put(PurchaseWireKeys.ORDER_ID, orderId)
root.put(PurchaseWireKeys.ORDER_PRICE, orderPrice)

val itemsArray = JSONArray()
for (item in items) {
val row = JSONObject()
row.put(PurchaseWireKeys.ID, item.id)
row.put(PurchaseWireKeys.AMOUNT, item.amount)
row.put(PurchaseWireKeys.PRICE, item.price)
item.lineId?.takeIf { it.isNotBlank() }?.let { row.put(PurchaseWireKeys.LINE_ID, it) }
item.fashionSize?.takeIf { it.isNotBlank() }?.let {
row.put(PurchaseWireKeys.FASHION_SIZE, it)
}
itemsArray.put(row)
}
root.put(PurchaseWireKeys.ITEMS, itemsArray)

deliveryType?.takeIf { it.isNotBlank() }?.let {
root.put(PurchaseWireKeys.DELIVERY_TYPE, it)
}
deliveryAddress?.takeIf { it.isNotBlank() }?.let {
root.put(PurchaseWireKeys.DELIVERY_ADDRESS, it)
}
paymentType?.takeIf { it.isNotBlank() }?.let {
root.put(PurchaseWireKeys.PAYMENT_TYPE, it)
}
if (isTaxFree) {
root.put(PurchaseWireKeys.TAX_FREE, true)
}
promocode?.takeIf { it.isNotBlank() }?.let {
root.put(PurchaseWireKeys.PROMOCODE, it)
}
orderCash?.let { root.put(PurchaseWireKeys.ORDER_CASH, it) }
orderBonuses?.let { root.put(PurchaseWireKeys.ORDER_BONUSES, it) }
orderDelivery?.let { root.put(PurchaseWireKeys.ORDER_DELIVERY, it) }
orderDiscount?.let { root.put(PurchaseWireKeys.ORDER_DISCOUNT, it) }
channel?.takeIf { it.isNotBlank() }?.let {
root.put(PurchaseWireKeys.CHANNEL, it)
}

if (effectiveCustom.isNotEmpty()) {
val customJson = JSONObject()
for ((key, value) in effectiveCustom) {
putJsonValue(customJson, key, value)
}
root.put(PurchaseWireKeys.CUSTOM, customJson)
}

recommendedSource?.let { root.put(PurchaseWireKeys.RECOMMENDED_SOURCE, it) }

stream?.takeIf { it.isNotBlank() }?.let {
root.put(UserBasicParams.STREAM, it)
}
segment?.takeIf { it.isNotBlank() }?.let {
root.put(UserBasicParams.SEGMENT, it)
}

return root
}

private fun effectiveCustomFields(map: Map<String, Any?>?): Map<String, Any> {
if (map.isNullOrEmpty()) return emptyMap()
val out = LinkedHashMap<String, Any>()
Expand Down
Loading
Loading