diff --git a/CHANGELOG.md b/CHANGELOG.md index c3ac52e..76081f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog All notable changes to this project will be documented in this file. +## [0.6.0] - 2023-06-16 +### Added +- new methods for `Content` module +- added predefined `Events` + +### Fixed +- apiKey terminology + +### Removed +- old `Content` module methods got deprecated + ## [0.5.0] - 2023-05-10 ### Added - `Promotions` module diff --git a/README.md b/README.md index 07e3c8c..8a5766c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Synerise Flutter SDK (synerise-flutter-sdk) (0.5.0) +# Synerise Flutter SDK (synerise-flutter-sdk) (0.6.0) [![Platform](https://img.shields.io/badge/platform-iOS-orange.svg)](https://github.com/synerise/ios-sdk) [![Platform](https://img.shields.io/badge/platform-Android-orange.svg)](https://github.com/synerise/android-sdk) @@ -45,7 +45,7 @@ This will add a line like this to your package's pubspec.yaml (and run an implic ``` dependencies: - synerise_flutter_sdk: ^0.5.0 + synerise_flutter_sdk: ^0.6.0 ``` Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more. diff --git a/android/build.gradle b/android/build.gradle index d3949ac..1f5561c 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -41,5 +41,5 @@ repositories { } dependencies { - implementation 'com.synerise.sdk:synerise-mobile-sdk:5.3.0' + implementation 'com.synerise.sdk:synerise-mobile-sdk:5.5.0' } \ No newline at end of file diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseConnector.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseConnector.java index 98adde0..ef9356b 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseConnector.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseConnector.java @@ -4,7 +4,6 @@ import android.app.Application; import android.content.Context; import android.content.pm.ApplicationInfo; -import android.util.Log; import androidx.annotation.NonNull; diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseMethodChannel.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseMethodChannel.java index c9d0af8..905eef1 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseMethodChannel.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseMethodChannel.java @@ -1,13 +1,12 @@ package com.synerise.synerise_flutter_sdk; - import io.flutter.embedding.engine.FlutterEngine; import io.flutter.plugin.common.MethodChannel; public class SyneriseMethodChannel { - public static MethodChannel methodChannel; + public static MethodChannel methodChannel; - public static void configureChannel(FlutterEngine flutterEngine) { - methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "synerise_dart_channel"); - } + public static void configureChannel(FlutterEngine flutterEngine) { + methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "synerise_dart_channel"); + } } diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseModule.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseModule.java index bfef8bf..0525015 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseModule.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/SyneriseModule.java @@ -1,6 +1,7 @@ package com.synerise.synerise_flutter_sdk; import com.synerise.sdk.error.ApiError; + import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel.Result; diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseClient.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseClient.java index 1adc7d6..78e62ee 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseClient.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseClient.java @@ -20,8 +20,6 @@ import com.synerise.sdk.error.ApiError; import com.synerise.synerise_flutter_sdk.SyneriseModule; -import org.json.JSONObject; - import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseContent.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseContent.java index 06e8f2b..c4cf15d 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseContent.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseContent.java @@ -6,8 +6,11 @@ import com.synerise.sdk.content.model.DocumentsApiQuery; import com.synerise.sdk.content.model.DocumentsApiQueryType; import com.synerise.sdk.content.model.ScreenViewResponse; +import com.synerise.sdk.content.model.document.Document; +import com.synerise.sdk.content.model.recommendation.FiltersJoinerRule; import com.synerise.sdk.content.model.recommendation.RecommendationRequestBody; import com.synerise.sdk.content.model.recommendation.RecommendationResponse; +import com.synerise.sdk.content.model.screenview.ScreenView; import com.synerise.sdk.content.widgets.dataModel.Recommendation; import com.synerise.sdk.core.net.IDataApiCall; import com.synerise.synerise_flutter_sdk.SyneriseModule; @@ -15,7 +18,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -35,6 +37,8 @@ public class SyneriseContent implements SyneriseModule { private final String ISO8601_FORMAT = "yyyy-MM-dd'T'kk:mm:ss.SSS'Z'"; private IDataApiCall getRecommendationsApiCall; private IDataApiCall getScreenViewApiCall; + private IDataApiCall generateScreenViewApiCall; + private IDataApiCall generateDocumentApiCall; private Gson gson = new Gson(); public SyneriseContent() { @@ -45,17 +49,26 @@ public void handleMethodCall(MethodCall call, MethodChannel.Result result, Strin switch (calledMethod) { case "getDocument": - getDocument(call,result); + getDocument(call, result); return; case "getDocuments": - getDocuments(call,result); + getDocuments(call, result); return; case "getRecommendations": - getRecommendations(call,result); + getRecommendations(call, result); return; case "getScreenView": getScreenView(result); return; + case "getRecommendationsV2": + getRecommendationsV2(call, result); + return; + case "generateDocument": + generateDocument(call, result); + return; + case "generateScreenView": + generateScreenView(call, result); + return; } } @@ -151,13 +164,106 @@ public void getScreenView(MethodChannel.Result result) { }, apiError -> SyneriseModule.executeFailureResult(apiError, result)); } - private ArrayList> recommendationToArrayList(List array) { + public void getRecommendationsV2(MethodCall call, MethodChannel.Result result) { + Map recommendationOptions = (Map) call.arguments; + String productID = null; + String slugName = null; + if (call.arguments != null) { + productID = (String) recommendationOptions.get("productID"); + slugName = (String) recommendationOptions.get("slug"); + } + if (getRecommendationsApiCall != null) getRecommendationsApiCall.cancel(); + + RecommendationRequestBody recommendationRequestBody = new RecommendationRequestBody(); + recommendationRequestBody.setProductId(productID); + recommendationRequestBody.setItemsIds(recommendationOptions.get("productIDs") != null ? (ArrayList) recommendationOptions.get("productIDs") : null); + recommendationRequestBody.setItemsExcluded((ArrayList) recommendationOptions.get("itemsExcluded")); + recommendationRequestBody.setAdditionalFilters((String) recommendationOptions.get("additionalFilters")); + if (recommendationOptions.get("filtersJoiner") != null) { + recommendationRequestBody.setFiltersJoiner(getFiltersJoinerRuleFromString((String) recommendationOptions.get("filtersJoiner"))); + } + if (recommendationOptions.get("elasticFiltersJoiner") != null) { + recommendationRequestBody.setElasticFiltersJoiner(getFiltersJoinerRuleFromString((String) recommendationOptions.get("elasticFiltersJoiner"))); + } + recommendationRequestBody.setAdditionalElasticFilters((String) recommendationOptions.get("additionalElasticFilters")); + recommendationRequestBody.setDisplayAttributes((ArrayList) recommendationOptions.get("displayAttributes")); + recommendationRequestBody.setIncludeContextItems((boolean) recommendationOptions.get("includeContextItems")); + + Map recommendationMap = new HashMap<>(); + + getRecommendationsApiCall = Content.getRecommendationsV2(slugName, recommendationRequestBody); + getRecommendationsApiCall.execute(responseBody -> { + recommendationMap.put("name", responseBody.getName()); + recommendationMap.put("correlationID", responseBody.getCorrelationId()); + recommendationMap.put("campaignHash", responseBody.getCampaignHash()); + recommendationMap.put("campaignID", responseBody.getCampaignId()); + recommendationMap.put("schema", responseBody.getSchema()); + recommendationMap.put("slug", responseBody.getSlug()); + recommendationMap.put("uuid", responseBody.getUuid()); + recommendationMap.put("items", recommendationToArrayList(responseBody.getRecommendations())); + SyneriseModule.executeSuccessResult(recommendationMap, result); + }, apiError -> SyneriseModule.executeFailureResult(apiError, result)); + } + + public void generateDocument(MethodCall call, MethodChannel.Result result) { + String slug = (String) call.arguments; + Map documentMap = new HashMap<>(); + if (generateDocumentApiCall != null) generateDocumentApiCall.cancel(); + generateDocumentApiCall = Content.generateDocument(slug); + generateDocumentApiCall.execute(document -> { + if (document.getContent() instanceof String) { + try { + HashMap contentMap = new Gson().fromJson((String) document.getContent(), HashMap.class); + documentMap.put("content", contentMap); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + documentMap.put("content", document.getContent()); + } + documentMap.put("identifier", document.getUuid()); + documentMap.put("slug", document.getSlug()); + documentMap.put("schema", document.getSchema()); + SyneriseModule.executeSuccessResult(documentMap, result); + }, apiError -> SyneriseModule.executeFailureResult(apiError, result)); + } + + public void generateScreenView(MethodCall call, MethodChannel.Result result) { + String slug = (String) call.arguments; + Map screenViewMap = new HashMap<>(); + if (generateScreenViewApiCall != null) generateScreenViewApiCall.cancel(); + generateScreenViewApiCall = Content.generateScreenView(slug); + generateScreenViewApiCall.execute(screenView -> { + screenViewMap.put("audience", screenViewAudienceToWritableMap(screenView.getAudience())); + screenViewMap.put("identifier", screenView.getId()); + screenViewMap.put("hashString", screenView.getHash()); + screenViewMap.put("path", screenView.getPath()); + screenViewMap.put("name", screenView.getName()); + screenViewMap.put("priority", screenView.getPriority()); + screenViewMap.put("data", screenViewDataMapper(screenView.getData())); + try { + Date createdAtDate = new SimpleDateFormat(ISO8601_FORMAT, Locale.getDefault()).parse(screenView.getCreatedAt()); + Date updatedAtDate = new SimpleDateFormat(ISO8601_FORMAT, Locale.getDefault()).parse(screenView.getUpdatedAt()); + if (createdAtDate != null) { + screenViewMap.put("createdAt", createdAtDate.getTime()); + } + if (updatedAtDate != null) { + screenViewMap.put("updatedAt", updatedAtDate.getTime()); + } + } catch (ParseException e) { + e.printStackTrace(); + } + SyneriseModule.executeSuccessResult(screenViewMap, result); + }, apiError -> SyneriseModule.executeFailureResult(apiError, result)); + } + + private ArrayList> recommendationToArrayList(List array) { ArrayList> arrayList = new ArrayList(); for (int i = 0; i < array.size(); i++) { Recommendation recommendation = array.get(i); Map recommendationMap = new HashMap<>(); - Map feed = recommendation.getFeed(); + Map feed = recommendation.getFeed(); recommendationMap.put("itemID", recommendation.getItemId()); recommendationMap.put("attributes", feed); arrayList.add(recommendationMap); @@ -183,6 +289,15 @@ private Map audienceToWritableMap(Audience audience) { return audienceMap; } + private Map screenViewAudienceToWritableMap(com.synerise.sdk.content.model.screenview.Audience audience) { + Map audienceMap = new HashMap<>(); + List segmentsList = audience.getSegments(); + audienceMap.put("query", audience.getQuery()); + audienceMap.put("targetType", audience.getTargetType()); + audienceMap.put("segments", segmentsList != null ? listOfStringsToArrayList(segmentsList) : null); + return audienceMap; + } + private Map screenViewDataMapper(Object data) { Map screenViewData = (Map) data; String jsonObject = gson.toJson(data); @@ -194,6 +309,19 @@ private Map screenViewDataMapper(Object data) { return screenViewData; } + private FiltersJoinerRule getFiltersJoinerRuleFromString(String filtersJoiner) { + switch (filtersJoiner) { + case "and": + return FiltersJoinerRule.AND; + case "or": + return FiltersJoinerRule.OR; + case "replace": + return FiltersJoinerRule.REPLACE; + default: + return null; + } + } + public static SyneriseContent getInstance() { if (instance == null) { instance = new SyneriseContent(); diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInitializer.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInitializer.java index f110968..10cbb68 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInitializer.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInitializer.java @@ -39,9 +39,9 @@ public void initSynerise(Application app, MethodCall call, MethodChannel.Result Map dataFull = (Map) call.arguments; Map data = (Map) dataFull.get("initializationParameters"); Synerise.Builder.with(app, data.get("clientApiKey").toString(), SyneriseConnector.getApplicationName(app)) - .baseUrl(data.containsKey("baseUrl") ? data.get("baseUrl").toString() : null) - .syneriseDebugMode(data.containsKey("debugModeEnabled") ? (boolean) data.get("debugModeEnabled") : null) - .crashHandlingEnabled(data.containsKey("crashHandlingEnabled") ? (boolean) data.get("crashHandlingEnabled") : null) + .baseUrl(data.containsKey("baseUrl") ? (String) data.get("baseUrl") : null) + .syneriseDebugMode(data.containsKey("debugModeEnabled") ? (boolean) data.get("debugModeEnabled") : false) + .crashHandlingEnabled(data.containsKey("crashHandlingEnabled") ? (boolean) data.get("crashHandlingEnabled") : false) .hostApplicationType(HostApplicationType.FLUTTER) .pushRegistrationRequired(SyneriseNotifications.getPushNotificationsListener()) .build(); diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInjector.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInjector.java index 73ea569..caac144 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInjector.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseInjector.java @@ -2,7 +2,6 @@ import android.os.Handler; import android.os.Looper; -import android.util.Log; import com.synerise.sdk.error.ApiError; import com.synerise.sdk.injector.Injector; @@ -66,7 +65,7 @@ public void onHandledOpenUrl(InAppMessageData inAppMessageData) { public void onHandledOpenDeepLink(InAppMessageData inAppMessageData) { Map data = createMapFromInAppMessageData(inAppMessageData); data.put("deepLink", inAppMessageData.getDeepLink()); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorInAppMessageListener#onDeepLink",data); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorInAppMessageListener#onDeepLink", data); } @Override @@ -79,7 +78,7 @@ public void onCustomAction(String identifier, HashMap params, In Map data = createMapFromInAppMessageData(inAppMessageData); data.put("name", identifier); data.put("parameters", params); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorInAppMessageListener#onCustomAction",data); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorInAppMessageListener#onCustomAction", data); } }); } @@ -101,7 +100,7 @@ public void onPresented() { @Override public void onClosed() { Map map = new HashMap<>(); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorBannerListener#onHide",map); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorBannerListener#onHide", map); super.onClosed(); } }); @@ -136,28 +135,28 @@ public static void registerWalkthroughListener() { @Override public void onLoadingError(ApiError error) { Map map = new HashMap<>(); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onLoadingError",map); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onLoadingError", map); super.onLoadingError(error); } @Override public void onLoaded(WalkthroughResponse walkthrough) { Map map = new HashMap<>(); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onLoad",map); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onLoad", map); super.onLoaded(walkthrough); } @Override public void onPresented() { Map map = new HashMap<>(); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onPresent",map); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onPresent", map); super.onPresented(); } @Override public void onClosed() { Map map = new HashMap<>(); - SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onHide",map); + SyneriseMethodChannel.methodChannel.invokeMethod("Injector#InjectorWalkthroughListener#onHide", map); super.onClosed(); } }); diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseNotifications.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseNotifications.java index c5f27c9..ff4808b 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseNotifications.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseNotifications.java @@ -1,7 +1,5 @@ package com.synerise.synerise_flutter_sdk.modules; -import android.util.Log; - import com.synerise.sdk.client.Client; import com.synerise.sdk.core.listeners.DataActionListener; import com.synerise.sdk.core.listeners.OnRegisterForPushListener; @@ -31,7 +29,7 @@ public void handleMethodCall(MethodCall call, MethodChannel.Result result, Strin registerForNotifications(call, result); return; case "handleNotification": - handleNotification(call,result); + handleNotification(call, result); return; } } @@ -56,7 +54,7 @@ private void handleNotification(MethodCall call, MethodChannel.Result result) { public static OnRegisterForPushListener getPushNotificationsListener() { Map map = new HashMap<>(); - registerNativeForPushListener = () -> SyneriseMethodChannel.methodChannel.invokeMethod("Notifications#NotificationsListener#onRegistrationRequired",map); + registerNativeForPushListener = () -> SyneriseMethodChannel.methodChannel.invokeMethod("Notifications#NotificationsListener#onRegistrationRequired", map); return registerNativeForPushListener; - } + } } diff --git a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseTracker.java b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseTracker.java index 6338eec..4d7bb7d 100644 --- a/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseTracker.java +++ b/android/src/main/java/com/synerise/synerise_flutter_sdk/modules/SyneriseTracker.java @@ -42,15 +42,14 @@ private void setCustomEmail(MethodCall call) { } private void send(MethodCall call) { - String type = call.argument("type"); String action = call.argument("action"); String label = call.argument("label"); HashMap hashMapParams = call.argument("params"); TrackerParams params = new TrackerParams.Builder() .addAll(hashMapParams) .build(); - if (type != null && action != null && label != null) { - CustomEvent event = new CustomEvent(type, action, label, params); + if (action != null && label != null) { + CustomEvent event = new CustomEvent(action, label, params); Tracker.send(event); } } diff --git a/example/android/app/google-services.json b/example/android/app/google-services.json index 658cf19..9e26dfe 100644 --- a/example/android/app/google-services.json +++ b/example/android/app/google-services.json @@ -1,3 +1 @@ -{ - googlefiletemplate, PUT YOUR GOOGLE-SERVICES.JSON CONTENT HERE -} +{} \ No newline at end of file diff --git a/example/lib/main.dart b/example/lib/main.dart index 9ec59b9..63c1d92 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -13,7 +13,6 @@ import 'dart:developer' as developer; import 'views/promotions/promotions_methods_view.dart'; - String? firebaseToken; class InitialView extends StatefulWidget { @@ -34,10 +33,7 @@ class _InitialViewState extends State { Future initializeSynerise() async { Synerise.settings.injector.automatic = true; Synerise.initializer() - .withClientApiKey("YOUR_CLIENT_API_KEY") - .withBaseUrl("https://api.snrapi.com") - .withDebugModeEnabled(true) - .init(); + .withClientApiKey("YOUR_PROFILE_API_KEY").withBaseUrl("https://api.snrapi.com").withDebugModeEnabled(true).init(); Synerise.injector.listener((listener) { listener.onOpenUrl = (url) { @@ -49,36 +45,20 @@ class _InitialViewState extends State { }); Synerise.injector.bannerListener((listener) { - listener.onPresent = () { - - }; - listener.onHide = () { - - }; + listener.onPresent = () {}; + listener.onHide = () {}; }); Synerise.injector.walkthroughListener((listener) { - listener.onLoad = () { - - }; - listener.onLoadingError = () { - - }; - listener.onPresent = () { - - }; - listener.onHide = () { - - }; + listener.onLoad = () {}; + listener.onLoadingError = () {}; + listener.onPresent = () {}; + listener.onHide = () {}; }); Synerise.injector.inAppMessageListener((listener) { - listener.onOpenUrl = (data, url) { - - }; - listener.onDeepLink = (data, deepLink) { - - }; + listener.onOpenUrl = (data, url) {}; + listener.onDeepLink = (data, deepLink) {}; listener.onPresent = (data) { Utils.displaySimpleAlert(data.campaignHash, context); @@ -88,9 +68,7 @@ class _InitialViewState extends State { Utils.displaySimpleAlert(data.campaignHash, context); }; - listener.onCustomAction = (data, name, parameters) { - - }; + listener.onCustomAction = (data, name, parameters) {}; }); } @@ -109,13 +87,9 @@ class _InitialViewState extends State { provisional: false, sound: true, ); - FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( - alert: true, - sound: true, - badge: true - ); + FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(alert: true, sound: true, badge: true); FirebaseMessaging.onBackgroundMessage(backgroundHandlerForFCM); - + FirebaseMessaging.instance.onTokenRefresh.listen((event) { FirebaseMessaging.instance.getToken().then((value) { if (value != null) { @@ -135,7 +109,9 @@ class _InitialViewState extends State { } }); - FirebaseMessaging.onMessage.listen((RemoteMessage message,) { + FirebaseMessaging.onMessage.listen(( + RemoteMessage message, + ) { Synerise.notifications.handleNotification(message.toMap()); }); @@ -144,14 +120,12 @@ class _InitialViewState extends State { }); Synerise.notifications.listener((listener) { - listener.onRegistrationRequired = () { - Synerise.notifications.registerForNotifications(firebaseToken!, true); - }; + listener.onRegistrationRequired = () { + Synerise.notifications.registerForNotifications(firebaseToken!, true); + }; }); } - - @override Widget build(BuildContext context) { return MaterialApp( @@ -281,16 +255,16 @@ class MyApp extends StatelessWidget { } @pragma('vm:entry-point') - Future backgroundHandlerForFCM(RemoteMessage message) async { +Future backgroundHandlerForFCM(RemoteMessage message) async { await Firebase.initializeApp(); await Synerise.initializer() - .withClientApiKey("YOUR_CLIENT_API_KEY") - .withBaseUrl("https://api.snrapi.com") - .withDebugModeEnabled(true) - .init(); + .withClientApiKey("YOUR_PROFILE_API_KEY") + .withBaseUrl("https://api.snrapi.com") + .withDebugModeEnabled(true) + .init(); // If you're going to use other Firebase services in the background, such as Firestore, // make sure you call `initializeApp` before using other Firebase services. // ignore: unused_local_variable bool isPushSynerise = await Synerise.notifications.handleNotification(message.toMap()); developer.log('flutter', name: 'onMessage background'); -} +} diff --git a/example/lib/views/client/register_account.dart b/example/lib/views/client/register_account.dart index dfb26fe..d3bcf89 100644 --- a/example/lib/views/client/register_account.dart +++ b/example/lib/views/client/register_account.dart @@ -39,9 +39,7 @@ class _RegisterAccountState extends State with AutomaticKeepAli ButtonBar( children: [ ElevatedButton.icon( - onPressed: () => _registerAccountCall( - emailController.text, - passwordController.text), + onPressed: () => _registerAccountCall(emailController.text, passwordController.text), icon: const Icon(Icons.arrow_forward), label: const Text('Register')), ], @@ -51,11 +49,8 @@ class _RegisterAccountState extends State with AutomaticKeepAli )); } - Future _registerAccountCall( - email, password) async { - ClientAccountRegisterContext clientAccountRegisterContext = ClientAccountRegisterContext( - email: email, - password: password); + Future _registerAccountCall(email, password) async { + ClientAccountRegisterContext clientAccountRegisterContext = ClientAccountRegisterContext(email: email, password: password); await Synerise.client.registerAccount(clientAccountRegisterContext).catchError((error) { showDialog( diff --git a/example/lib/views/content/content_methods_view.dart b/example/lib/views/content/content_methods_view.dart index 6576b87..92ba10e 100644 --- a/example/lib/views/content/content_methods_view.dart +++ b/example/lib/views/content/content_methods_view.dart @@ -12,17 +12,15 @@ class ContentMethodsView extends StatefulWidget { class _ContentMethodsViewState extends State with AutomaticKeepAliveClientMixin { final slugController = TextEditingController(); - final getDocumentForm = GlobalKey(); + final generateDocumentForm = GlobalKey(); - final getDocumentsForm = GlobalKey(); - final typeController = TextEditingController(); - final typeValueController = TextEditingController(); - final versionController = TextEditingController(); - - final getRecommendationsForm = GlobalKey(); + final getRecommendationsV2Form = GlobalKey(); final slugRecoController = TextEditingController(); final productIDController = TextEditingController(); + final feedSlugController = TextEditingController(); + final generateScreenViewForm = GlobalKey(); + _tempFormBody() { return SingleChildScrollView( scrollDirection: Axis.vertical, @@ -30,12 +28,12 @@ class _ContentMethodsViewState extends State with AutomaticK crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ - //getDocument + //generateDocument Form( - key: getDocumentForm, + key: generateDocumentForm, child: Column( children: [ - const Padding(padding: EdgeInsets.all(15), child: Text("getDocument Test")), + const Padding(padding: EdgeInsets.all(15), child: Text("generateDocument Test")), SizedBox( width: 350, child: TextFormField( @@ -44,7 +42,7 @@ class _ContentMethodsViewState extends State with AutomaticK keyboardType: TextInputType.text, )), ElevatedButton.icon( - onPressed: () => _getDocumentCall(slugController.text), + onPressed: () => _generateDocumentCall(slugController.text), icon: const Icon(Icons.file_copy_outlined), label: const Text('getDocument')), ], @@ -53,86 +51,67 @@ class _ContentMethodsViewState extends State with AutomaticK thickness: 1, color: Colors.grey, ), - //getDocuments + //getRecommendations Form( - key: getDocumentsForm, + key: getRecommendationsV2Form, child: Column( children: [ - const Padding(padding: EdgeInsets.all(15), child: Text("getDocuments Test")), - SizedBox( - width: 350, - child: TextFormField( - enabled: false, - controller: typeController, - decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "type"), - keyboardType: TextInputType.text, - )), + const Padding(padding: EdgeInsets.all(15), child: Text("getRecommendationsV2 Test")), SizedBox( width: 350, child: TextFormField( - controller: typeValueController, - decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "typeValue"), + controller: slugRecoController, + decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "slug"), keyboardType: TextInputType.text, )), SizedBox( width: 350, child: TextFormField( - controller: versionController, - decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "version"), + controller: productIDController, + decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "productID"), keyboardType: TextInputType.text, )), ElevatedButton.icon( - onPressed: () => _getDocumentsCall(typeValueController.text, versionController.text), - icon: const Icon(Icons.list_alt), - label: const Text('getDocuments')), + onPressed: () => _getRecommendationsV2Call(slugRecoController.text, productIDController.text), + icon: const Icon(Icons.recommend_outlined), + label: const Text('getRecommendationsV2')), ], )), const Divider( thickness: 1, color: Colors.grey, ), - //getRecommendations + //generateScreenView Form( - key: getRecommendationsForm, + key: generateScreenViewForm, child: Column( children: [ - const Padding(padding: EdgeInsets.all(15), child: Text("getRecommendations Test")), - SizedBox( - width: 350, - child: TextFormField( - controller: slugRecoController, - decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "slug"), - keyboardType: TextInputType.text, - )), + const Padding(padding: EdgeInsets.all(15), child: Text("generateScreenView Test")), SizedBox( width: 350, child: TextFormField( - controller: productIDController, - decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "productID"), + controller: feedSlugController, + decoration: const InputDecoration(border: OutlineInputBorder(), labelText: "feedSlug"), keyboardType: TextInputType.text, )), ElevatedButton.icon( - onPressed: () => _getRecommendationsCall(slugRecoController.text, productIDController.text), - icon: const Icon(Icons.recommend_outlined), - label: const Text('getRecommendations')), + onPressed: () => _generateScreenViewCall(feedSlugController.text), + icon: const Icon(Icons.fit_screen), + label: const Text('generateScreenView')), ], )), const Divider( thickness: 1, color: Colors.grey, ), - //getScreenView - const Padding(padding: EdgeInsets.all(15), child: Text("getScreenView Test")), - ElevatedButton.icon( - onPressed: () => _getScreenViewCall(), icon: const Icon(Icons.fit_screen), label: const Text('getScreenView')), ], )); } - Future _getDocumentCall(String slug) async { + Future _generateDocumentCall(String slug) async { String slugName = slug; - Map documentMap = await Synerise.content.getDocument(slugName).catchError((error) { + Document document = await Synerise.content.generateDocument(slugName).catchError((error) { String errorMessage = Utils.handlePlatformException(error); Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); throw Exception(errorMessage); @@ -145,7 +124,7 @@ class _ContentMethodsViewState extends State with AutomaticK content: SingleChildScrollView( child: Column(children: [ const Text( - 'Document Map', + 'Document Identifier', style: TextStyle(fontStyle: FontStyle.italic), ), Container( @@ -153,47 +132,19 @@ class _ContentMethodsViewState extends State with AutomaticK margin: const EdgeInsets.all(5.0), padding: const EdgeInsets.all(5), decoration: BoxDecoration(border: Border.all(width: 0.5, color: Colors.black)), - child: Text(documentMap.toString(), textScaleFactor: 0.5)) + child: Text(document.identifier.toString(), textScaleFactor: 0.5)) ]))); }); } - Future _getDocumentsCall(String typeValue, String? version) async { - DocumentsApiQueryType documentsApiQueryType = DocumentsApiQueryType.schema; - DocumentsApiQuery documentsApiQuery = - DocumentsApiQuery(typeValue: typeValue, version: version != "" ? version : null, type: documentsApiQueryType); - List> documentsList = await Synerise.content.getDocuments(documentsApiQuery).catchError((error) { - String errorMessage = Utils.handlePlatformException(error); - Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); - throw Exception(errorMessage); - }); - if (!mounted) return; - showDialog( - context: context, - builder: (context) { - return AlertDialog( - content: SingleChildScrollView( - child: Column(children: [ - const Text( - 'Documents Map', - style: TextStyle(fontStyle: FontStyle.italic), - ), - Container( - width: double.infinity, - margin: const EdgeInsets.all(5.0), - padding: const EdgeInsets.all(5), - decoration: BoxDecoration(border: Border.all(width: 0.5, color: Colors.black)), - child: Text(documentsList.toString(), textScaleFactor: 0.5)) - ]))); - }); - } - - Future _getRecommendationsCall(String slugReco, String productRecoID) async { - String productID = productRecoID; + Future _getRecommendationsV2Call(String slugReco, String productID) async { + String productId = productID; String slug = slugReco; - RecommendationOptions recommendationOptions = RecommendationOptions(slug: slug, productID: productID); - - RecommendationResponse recommendationResponse = await Synerise.content.getRecommendations(recommendationOptions).catchError((error) { + RecommendationOptions recommendationOptions = RecommendationOptions( + slug: slug, + productID: productId); + + RecommendationResponse recommendationResponse = await Synerise.content.getRecommendationsV2(recommendationOptions).catchError((error) { String errorMessage = Utils.handlePlatformException(error); Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); throw Exception(errorMessage); @@ -214,13 +165,14 @@ class _ContentMethodsViewState extends State with AutomaticK margin: const EdgeInsets.all(5.0), padding: const EdgeInsets.all(5), decoration: BoxDecoration(border: Border.all(width: 0.5, color: Colors.black)), - child: Text(recommendationResponse.asMap().toString(), textScaleFactor: 0.5)) + child: Text(recommendationResponse.items.toString(), textScaleFactor: 0.5)) ]))); }); } - Future _getScreenViewCall() async { - ScreenViewResponse screenViewResponse = await Synerise.content.getScreenView().catchError((error) { + Future _generateScreenViewCall(String feedSlug) async { + String slug = feedSlug; + ScreenView screenViewResponse = await Synerise.content.generateScreenView(slug).catchError((error) { String errorMessage = Utils.handlePlatformException(error); Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); throw Exception(errorMessage); @@ -233,7 +185,7 @@ class _ContentMethodsViewState extends State with AutomaticK content: SingleChildScrollView( child: Column(children: [ const Text( - 'ScreenView Map', + 'ScreenView Data', style: TextStyle(fontStyle: FontStyle.italic), ), Container( @@ -241,7 +193,7 @@ class _ContentMethodsViewState extends State with AutomaticK margin: const EdgeInsets.all(5.0), padding: const EdgeInsets.all(5), decoration: BoxDecoration(border: Border.all(width: 0.5, color: Colors.black)), - child: Text(screenViewResponse.asMap().toString(), textScaleFactor: 0.5)) + child: Text(screenViewResponse.data.toString(), textScaleFactor: 0.5)) ]))); }); } diff --git a/example/lib/views/promotions/promotions_methods_view.dart b/example/lib/views/promotions/promotions_methods_view.dart index 768048d..735c78c 100644 --- a/example/lib/views/promotions/promotions_methods_view.dart +++ b/example/lib/views/promotions/promotions_methods_view.dart @@ -172,7 +172,9 @@ class _PromotionsMethodsViewState extends State with Auto Future _getPromotionsCall() async { List promotionsStatusList = [PromotionStatus.active]; List promotionTypeList = [PromotionType.general]; - List apiQuerySortingList = [ApiQuerySorting(property: "", order: ApiQuerySortingOrder.ascending)]; + List apiQuerySortingList = [ + ApiQuerySorting(property: PromotionSortingKey.expireAt, order: ApiQuerySortingOrder.ascending) + ]; PromotionsApiQuery promotionsApiQuery = PromotionsApiQuery( statuses: promotionsStatusList, types: promotionTypeList, sorting: apiQuerySortingList, limit: 10, page: 10, includeMeta: true); PromotionResponse promotionResponse = await Synerise.promotions.getPromotions(promotionsApiQuery).catchError((error) { @@ -276,9 +278,7 @@ class _PromotionsMethodsViewState extends State with Auto } Future _deactivatePromotionByUUIDCall(String uuid) async { - await Synerise.promotions - .deactivatePromotionByUUID(uuid) - .catchError((error) { + await Synerise.promotions.deactivatePromotionByUUID(uuid).catchError((error) { String errorMessage = Utils.handlePlatformException(error); Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); throw Exception(errorMessage); @@ -288,9 +288,7 @@ class _PromotionsMethodsViewState extends State with Auto } Future _deactivatePromotionByCodeCall(String code) async { - await Synerise.promotions - .deactivatePromotionByCode(code) - .catchError((error) { + await Synerise.promotions.deactivatePromotionByCode(code).catchError((error) { String errorMessage = Utils.handlePlatformException(error); Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context); throw Exception(errorMessage); diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 62ee99b..4ebf3e8 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,6 +1,6 @@ name: synerise_flutter_sdk_example description: Demonstrates how to use the synerise_flutter_sdk plugin. -version: 0.5.0 +version: 0.6.0 # The following line prevents the package from being accidentally published to # pub.dev using `flutter pub publish`. This is preferred for private packages. diff --git a/ios/Classes/Modules/FContent.m b/ios/Classes/Modules/FContent.m index e386f24..828aa59 100644 --- a/ios/Classes/Modules/FContent.m +++ b/ios/Classes/Modules/FContent.m @@ -27,6 +27,12 @@ - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result c [self getRecommendations:call result:result]; } else if ([calledMethod isEqualToString:@"getScreenView"]) { [self getScreenView:call result:result]; + } else if ([calledMethod isEqualToString:@"getRecommendationsV2"]) { + [self getRecommendationsV2:call result:result]; + } else if ([calledMethod isEqualToString:@"generateDocument"]) { + [self generateDocument:call result:result]; + } else if ([calledMethod isEqualToString:@"generateScreenView"]) { + [self generateScreenView:call result:result]; } } @@ -92,6 +98,49 @@ - (void)getScreenView:(FlutterMethodCall *)call result:(FlutterResult)result { }]; } +- (void)getRecommendationsV2:(FlutterMethodCall *)call result:(FlutterResult)result { + NSDictionary *dictionary = call.arguments; + + SNRRecommendationOptions *recommendationOptions = [self modelRecommendationOptionsWithDictionary:dictionary]; + if (recommendationOptions == nil) { + result([self defaultFlutterError]); + return; + } + + [SNRContent getRecommendationsV2:recommendationOptions success:^(SNRRecommendationResponse *recommendationResponse) { + NSDictionary *recommendationResponseDictionary = [self dictionaryWithRecommendationResponse:recommendationResponse]; + if (recommendationResponseDictionary != nil) { + result(recommendationResponseDictionary); + } else { + result([self defaultFlutterError]); + } + } failure:^(NSError *error) { + result([self makeFlutterErrorWithError:error]); + }]; +} + +- (void)generateDocument:(FlutterMethodCall *)call result:(FlutterResult)result { + NSString *slug = call.arguments; + + [SNRContent generateDocument:slug success:^(SNRDocument *document) { + NSDictionary *documentDictionary = [self dictionaryWithDocument:document]; + result (documentDictionary); + } failure:^(NSError *error) { + result([self makeFlutterErrorWithError:error]); + }]; +} + +- (void)generateScreenView:(FlutterMethodCall *)call result:(FlutterResult)result { + NSString *slug = call.arguments; + + [SNRContent generateScreenView:slug success:^(SNRScreenView *screenView) { + NSDictionary *screenViewDictionary = [self dictionaryWithScreenView:screenView]; + result (screenViewDictionary); + } failure:^(NSError *error) { + result([self makeFlutterErrorWithError:error]); + }]; +} + #pragma mark - SDK Mapping - (SNRDocumentsApiQuery *)modelDocumentsApiQueryWithDictionary:(NSDictionary *)dictionary { @@ -113,14 +162,34 @@ - (SNRDocumentsApiQuery *)modelDocumentsApiQueryWithDictionary:(NSDictionary *)d - (SNRRecommendationOptions *)modelRecommendationOptionsWithDictionary:(NSDictionary *)dictionary { NSString *slug = [dictionary getStringForKey:@"slug"]; SNRRecommendationOptions *model = [[SNRRecommendationOptions alloc] initWithSlug:slug]; - + if (dictionary != nil) { model.productID = [dictionary getStringForKey:@"productID"]; + model.productIDs = [dictionary getArrayForKey:@"productIDs"]; + model.itemsExcluded = [dictionary getArrayForKey:@"itemsExcluded"]; + model.additionalFilters = [dictionary getStringForKey:@"additionalFilters"]; + model.filtersJoiner = ([self modelFiltersJoiner:[dictionary getStringForKey:@"filtersJoiner"]]); + model.additionalElasticFilters = [dictionary getStringForKey:@"additionalElasticFilters"]; + model.elasticFiltersJoiner = ([self modelFiltersJoiner:[dictionary getStringForKey:@"elasticFiltersJoiner"]]); + model.displayAttribute = [dictionary getArrayForKey:@"displayAttribute"]; + model.includeContextItems = [dictionary getBoolForKey:@"includeContextItems"]; } return model; } +- (SNRRecommendationFiltersJoinerRule)modelFiltersJoiner:(NSString *)string { + if ([string isEqualToString:@"and"]) { + return SNRRecommendationFiltersJoinerRuleAnd; + } else if ([string isEqualToString:@"or"]) { + return SNRRecommendationFiltersJoinerRuleOr; + } else if ([string isEqualToString:@"replace"]) { + return SNRRecommendationFiltersJoinerRuleReplace; + } else { + return -1; + } +} + #pragma mark - Dart Mapping - (nullable NSDictionary *)dictionaryWithRecommendationResponse:(SNRRecommendationResponse *)model { @@ -130,9 +199,11 @@ - (nullable NSDictionary *)dictionaryWithRecommendationResponse:(SNRRecommendati [dictionary setString:model.name forKey:@"name"]; [dictionary setString:model.campaignHash forKey:@"campaignHash"]; [dictionary setString:model.campaignID forKey:@"campaignID"]; + [dictionary setString:model.correlationID forKey:@"correlationID"]; [dictionary setString:model.schema forKey:@"schema"]; [dictionary setString:model.UUID forKey:@"uuid"]; [dictionary setString:model.slug forKey:@"slug"]; + NSMutableArray *recommendationsArray = [@[] mutableCopy]; for (SNRRecommendation *recommendationModel in model.items) { [recommendationsArray addObject:[self dictionaryWithRecommendation:recommendationModel]]; @@ -200,6 +271,52 @@ - (nullable NSDictionary *)dictionaryWithScreenViewAudience:(SNRScreenViewAudien return nil; } +- (nullable NSDictionary *)dictionaryWithDocument:(SNRDocument *)model { + if (model != nil) { + NSMutableDictionary *dictionary = [@{} mutableCopy]; + + [dictionary setString:model.identifier forKey:@"identifier"]; + [dictionary setString:model.slug forKey:@"slug"]; + [dictionary setString:model.schema forKey:@"schema"]; + [dictionary setDictionary:model.content forKey:@"content"]; + + return dictionary; + } + return nil; +} + +- (nullable NSDictionary *)dictionaryWithScreenView:(SNRScreenView *)model { + if (model != nil) { + NSMutableDictionary *dictionary = [@{} mutableCopy]; + [dictionary setString:model.identifier forKey:@"identifier"]; + [dictionary setString:model.name forKey:@"name"]; + [dictionary setString:model.hashString forKey:@"hashString"]; + [dictionary setString:model.path forKey:@"path"]; + [dictionary setInteger:model.priority forKey:@"priority"]; + [dictionary setDictionary:[self dictionaryWithScreenViewAudienceInfo:model.audience] forKey:@"audience"]; + [dictionary setGenericObject:model.data forKey:@"data"]; + [dictionary setDate:model.createdAt forKey:@"createdAt"]; + [dictionary setDate:model.updatedAt forKey:@"updatedAt"]; + + return dictionary; + } + return nil; +} + +- (nullable NSDictionary *)dictionaryWithScreenViewAudienceInfo:(SNRScreenViewAudienceInfo *)model { + if (model != nil) { + NSMutableDictionary *dictionary = [@{} mutableCopy]; + + [dictionary setArray:model.segments forKey:@"segments"]; + [dictionary setString:model.query forKey:@"query"]; + [dictionary setString:model.targetType forKey:@"targetType"]; + + return dictionary; + } + + return nil; +} + @end NS_ASSUME_NONNULL_END diff --git a/ios/Classes/Modules/FTracker.m b/ios/Classes/Modules/FTracker.m index 129f422..ef5c0f7 100644 --- a/ios/Classes/Modules/FTracker.m +++ b/ios/Classes/Modules/FTracker.m @@ -76,7 +76,7 @@ - (void)flush:(FlutterMethodCall *)call result:(FlutterResult)result { - (SNRCustomEvent *)eventWithDictionary:(NSDictionary *)dictionary { NSString *label = [dictionary getStringForKey:@"label"]; NSString *action = [dictionary getStringForKey:@"action"]; - NSDictionary *parameters = [dictionary getDictionaryForKey:@"parameters"]; + NSDictionary *parameters = [dictionary getDictionaryForKey:@"params"]; if (label != nil && action != nil) { SNRTrackerParams *params = [SNRTrackerParams makeWithBuilder:^(SNRTrackerParamsBuilder *builder) { diff --git a/ios/synerise_flutter_sdk.podspec b/ios/synerise_flutter_sdk.podspec index 1952d32..1845690 100644 --- a/ios/synerise_flutter_sdk.podspec +++ b/ios/synerise_flutter_sdk.podspec @@ -3,7 +3,7 @@ # Run `pod lib lint synerise_flutter_sdk.podspec` to validate before publishing. # -SYNERISE_SDK_FRAMEWORK_VERSION = '4.12.1' +SYNERISE_SDK_FRAMEWORK_VERSION = '4.13.1' Pod::Spec.new do |s| s.name = 'synerise_flutter_sdk' diff --git a/lib/enums/client/client_sex.dart b/lib/enums/client/client_sex.dart index 7eb71bf..ef8af1d 100644 --- a/lib/enums/client/client_sex.dart +++ b/lib/enums/client/client_sex.dart @@ -1,3 +1,6 @@ +/// This is defining an enumeration type called `ClientSex` with four possible values: `notSpecified`, +/// `male`, `female`, and `other`. Each value is assigned a string representation that corresponds to +/// the value's name in all caps. enum ClientSex { notSpecified('NOT_SPECIFIED'), male('MALE'), @@ -8,10 +11,12 @@ enum ClientSex { final String clientSex; + /// The function returns the client's sex as a string. String getSexAsString() { return clientSex; } - + + /// This function returns a ClientSex enum value based on a given string input. static ClientSex getClientSexFromString(String string) { if (string == 'NOT_SPECIFIED') { return ClientSex.notSpecified; diff --git a/lib/enums/client/identity_provider.dart b/lib/enums/client/identity_provider.dart index 1f2e7c0..6f8a708 100644 --- a/lib/enums/client/identity_provider.dart +++ b/lib/enums/client/identity_provider.dart @@ -1,3 +1,5 @@ +/// This is defining an enumeration called `IdentityProvider` with five possible values: `synerise`, +/// `facebook`, `google`, `oauth`, and `unknown`. Each value is associated with a string representation. enum IdentityProvider { synerise('SYNERISE'), facebook('FACEBOOK'), @@ -9,10 +11,12 @@ enum IdentityProvider { final String identityPrvovider; + /// This function returns the identity provider as a string. String getIdentityProviderAsString() { return identityPrvovider; } + /// This function returns an identity provider as a string based on a given input string. static String getIdentityProviderFromString(String string) { if (string == synerise.identityPrvovider) { return synerise.identityPrvovider; diff --git a/lib/enums/client/token_origin.dart b/lib/enums/client/token_origin.dart index 564d230..c2dfc18 100644 --- a/lib/enums/client/token_origin.dart +++ b/lib/enums/client/token_origin.dart @@ -1,3 +1,6 @@ +/// This is defining an enumeration type called `TokenOrigin` with five possible values: `synerise`, +/// `facebook`, `google`, `oauth`, and `unknown`. Each value is associated with a string representation +/// (`'SYNERISE'`, `'FACEBOOK'`, `'GOOGLE'`, `'OAUTH'`, and `'UNKNOWN'`, respectively). enum TokenOrigin { synerise('SYNERISE'), facebook('FACEBOOK'), @@ -9,6 +12,7 @@ enum TokenOrigin { final String tokenOrigin; + /// This is a factory method that returns a TokenOrigin object based on a given string value. factory TokenOrigin.fromString(String string) { return values.byName(string.toLowerCase()); } diff --git a/lib/enums/content/documents_api_query_type.dart b/lib/enums/content/documents_api_query_type.dart index b9309ab..d522ac5 100644 --- a/lib/enums/content/documents_api_query_type.dart +++ b/lib/enums/content/documents_api_query_type.dart @@ -1,3 +1,5 @@ +/// This code defines an enumeration called `DocumentsApiQueryType`. +/// The value is initialized with the string `'by-schema'`. enum DocumentsApiQueryType { schema('by-schema'); @@ -5,6 +7,7 @@ enum DocumentsApiQueryType { final String documentApiQueryType; + /// This function returns the document API query type as a string. String? getDocumentsApiQueryTypeAsString() { return documentApiQueryType; } diff --git a/lib/enums/promotions/promotion_discount_mode.dart b/lib/enums/promotions/promotion_discount_mode.dart index a7e9662..f0a66e8 100644 --- a/lib/enums/promotions/promotion_discount_mode.dart +++ b/lib/enums/promotions/promotion_discount_mode.dart @@ -1,3 +1,7 @@ +/// This is defining an enumeration called `PromotionDiscountMode` with two possible values: +/// `staticMode` and `stepMode`. Each value is associated with a string value (`'STATIC'` and `'STEP'`, +/// respectively). The `getPromotionDiscountModeFromString` method is used to convert a string value to the +/// corresponding enum value. enum PromotionDiscountMode { staticMode('STATIC'), stepMode('STEP'); @@ -6,6 +10,11 @@ enum PromotionDiscountMode { final String promotionDiscountMode; + /// `static PromotionDiscountMode getPromotionDiscountModeFromString(String string)` is a static + /// method that takes a string as input and returns the corresponding `PromotionDiscountMode` enum + /// value. It checks if the input string matches either `'STATIC'` or `'STEP'`, and returns the + /// corresponding enum value (`staticMode` or `stepMode`). If the input string does not match either + /// of these values, it returns the default value of `staticMode`. static PromotionDiscountMode getPromotionDiscountModeFromString(String string) { if (string == 'STATIC') { return PromotionDiscountMode.staticMode; diff --git a/lib/enums/promotions/promotion_discount_type.dart b/lib/enums/promotions/promotion_discount_type.dart index 02c9caa..0ec8bdc 100644 --- a/lib/enums/promotions/promotion_discount_type.dart +++ b/lib/enums/promotions/promotion_discount_type.dart @@ -1,3 +1,8 @@ +/// This is defining an enumeration type called `PromotionDiscountType` with seven possible values: +/// `none`, `percent`, `amount`, `twoForOne`, `points`, `multibuy`, and `exactPrice`. Each value is +/// associated with a string literal that represents the value in a human-readable format. The +/// `getPromotionDiscountTypeFromString` method is used to convert a string to the corresponding +/// `PromotionDiscountType` value. enum PromotionDiscountType { none('NONE'), percent('PERCENT'), @@ -11,6 +16,13 @@ enum PromotionDiscountType { final String promotionDiscountType; + /// This function returns a PromotionDiscountType enum value based on a given string input. + /// + /// Args: + /// string (String): A string value representing a promotion discount type. + /// + /// Returns: + /// This method returns a value of the enum type `PromotionDiscountType`. static PromotionDiscountType getPromotionDiscountTypeFromString(String string) { if (string == 'NONE') { return PromotionDiscountType.none; diff --git a/lib/enums/promotions/promotion_discount_usage_trigger.dart b/lib/enums/promotions/promotion_discount_usage_trigger.dart index 6b758c2..b7c4fc0 100644 --- a/lib/enums/promotions/promotion_discount_usage_trigger.dart +++ b/lib/enums/promotions/promotion_discount_usage_trigger.dart @@ -1,3 +1,9 @@ +/// This is defining an enum called `PromotionDiscountUsageTrigger` with two possible +/// values: `transaction` and `redeem`. Each value is associated with a string value (`'TRANSACTION'` +/// and `'REDEEM'` respectively). The enum also has a constructor that takes a string parameter and a +/// method `getPromotionDiscountUsageTriggerFromString` that returns the corresponding enum value based +/// on a given string input. There is also a method `promotionDiscountUsageTriggerAsString` that returns +/// the string value associated with the enum value. enum PromotionDiscountUsageTrigger { transaction('TRANSACTION'), redeem('REDEEM'); @@ -6,6 +12,16 @@ enum PromotionDiscountUsageTrigger { final String promotionDiscountUsageTrigger; + /// The function returns a PromotionDiscountUsageTrigger enum value based on a given string input. + /// + /// Args: + /// string (String): A string value that represents a promotion discount usage trigger. + /// + /// Returns: + /// The method is returning a value of the enum type `PromotionDiscountUsageTrigger`. The value + /// returned depends on the input string parameter. If the string is equal to 'TRANSACTION', the + /// method returns the enum value `transaction`. If the string is equal to 'REDEEM', the method + /// returns the enum value `redeem`. If the string is anything else, the method returns the enum value static PromotionDiscountUsageTrigger getPromotionDiscountUsageTriggerFromString(String string) { if (string == 'TRANSACTION') { return PromotionDiscountUsageTrigger.transaction; @@ -16,6 +32,11 @@ enum PromotionDiscountUsageTrigger { } } + /// This function returns a string representation of a promotion discount usage trigger. + /// + /// Returns: + /// The method `promotionDiscountUsageTriggerAsString()` is returning the value of the variable + /// `promotionDiscountUsageTrigger` as a string. String promotionDiscountUsageTriggerAsString() { return promotionDiscountUsageTrigger; } diff --git a/lib/enums/promotions/promotion_identifier_key.dart b/lib/enums/promotions/promotion_identifier_key.dart index 46102e5..b5f3cb7 100644 --- a/lib/enums/promotions/promotion_identifier_key.dart +++ b/lib/enums/promotions/promotion_identifier_key.dart @@ -1,3 +1,7 @@ +/// This is defining an enumeration called `PromotionIdentifierKey` with two possible values: `uuid` and +/// `code`. Each value is associated with a string value (`'UUID'` and `'CODE'` respectively). The +/// `const PromotionIdentifierKey(this.promotionIdentifierKey)` constructor is used to initialize the +/// `promotionIdentifierKey` field with the string value associated with each enumeration value. enum PromotionIdentifierKey { uuid('UUID'), code('CODE'); @@ -6,6 +10,17 @@ enum PromotionIdentifierKey { final String promotionIdentifierKey; + /// The function returns a PromotionIdentifierKey based on a given string input. + /// + /// Args: + /// string (String): A string value that represents the type of promotion identifier key. It can be + /// either "UUID" or "CODE". + /// + /// Returns: + /// The function `getPromotionIdentifierKeyFromString` returns a value of the + /// `PromotionIdentifierKey` enum type. The returned value depends on the input string: if the string + /// is "UUID", the function returns the `uuid` value of the enum, if the string is "CODE", the + /// function returns the `code` value of the enum, and if the string is anything else, the static PromotionIdentifierKey getPromotionIdentifierKeyFromString(String string) { if (string == 'UUID') { return PromotionIdentifierKey.uuid; @@ -16,6 +31,10 @@ enum PromotionIdentifierKey { } } + /// This function returns the promotion identifier key as a string. + /// + /// Returns: + /// The method is returning the value of the variable `promotionIdentifierKey` as a string. String promotionIdentifierKeyAsString() { return promotionIdentifierKey; } diff --git a/lib/enums/promotions/promotion_image_type.dart b/lib/enums/promotions/promotion_image_type.dart index 124b46f..622a4d9 100644 --- a/lib/enums/promotions/promotion_image_type.dart +++ b/lib/enums/promotions/promotion_image_type.dart @@ -1,3 +1,10 @@ +/// This is a enum that defines four possible values for a promotion image type: "image", +/// "thumbnail", "large", and "UNKNOWN". Each value is assigned a string representation and a +/// constructor that takes a string argument. The enum also includes a static method +/// `getPromotionImageTypeFromString` that takes a string argument and returns the corresponding enum +/// value, or "UNKNOWN" if the string does not match any of the defined values. Finally, the enum +/// includes a method `promotionImageTypeAsString` that returns the string representation of the enum +/// value. enum PromotionImageType { image('image'), thumbnail('thumbnail'), @@ -8,6 +15,13 @@ enum PromotionImageType { final String promotionImageType; + /// This function returns a PromotionImageType enum value based on a given string input. + /// + /// Args: + /// string (String): A string that represents the promotion image type. + /// + /// Returns: + /// The method is returning a value of the enum type `PromotionImageType`. static PromotionImageType getPromotionImageTypeFromString(String string) { if (string == PromotionImageType.image.promotionImageType) { return PromotionImageType.image; @@ -22,6 +36,10 @@ enum PromotionImageType { } } + /// This function returns a string representation of a promotion image type. + /// + /// Returns: + /// The method is returning the value of the variable `promotionImageType` as a string. String promotionImageTypeAsString() { return promotionImageType; } diff --git a/lib/enums/promotions/promotion_item_scope.dart b/lib/enums/promotions/promotion_item_scope.dart index f07b717..5b75897 100644 --- a/lib/enums/promotions/promotion_item_scope.dart +++ b/lib/enums/promotions/promotion_item_scope.dart @@ -1,3 +1,6 @@ +/// This code is defining an enumeration type called `PromotionItemScope` with two possible values: +/// `lineItem` and `basket`. Each value is associated with a string value (`'LINE_ITEM'` and `'BASKET'`, +/// respectively) that represents the promotion item scope. enum PromotionItemScope { lineItem('LINE_ITEM'), basket('BASKET'); @@ -6,6 +9,16 @@ enum PromotionItemScope { final String promotionItemScope; + /// The function returns a PromotionItemScope enum value based on a string input. + /// + /// Args: + /// string (String): A string representing the promotion item scope. + /// + /// Returns: + /// The method is returning a value of the enumeration type `PromotionItemScope`. The specific value + /// being returned depends on the input string. If the input string matches the `promotionItemScope` + /// value of the `lineItem` or `basket` enum values, then the corresponding enum value is returned. + /// Otherwise, the default value of `lineItem` is returned. static PromotionItemScope getPromotionItemScopeFromString(String string) { if (string == PromotionItemScope.lineItem.promotionItemScope) { return PromotionItemScope.lineItem; @@ -16,6 +29,11 @@ enum PromotionItemScope { } } + /// This function returns the promotion item scope as a string. + /// + /// Returns: + /// The method `promotionItemScopeAsString()` is returning the value of the variable + /// `promotionItemScope` as a string. String promotionItemScopeAsString() { return promotionItemScope; } diff --git a/lib/enums/promotions/promotion_sorting_key.dart b/lib/enums/promotions/promotion_sorting_key.dart new file mode 100644 index 0000000..2ebeabd --- /dev/null +++ b/lib/enums/promotions/promotion_sorting_key.dart @@ -0,0 +1,11 @@ +class PromotionSortingKey { + static const String expireAt = "expireAt"; + static const String createdAt = "createdAt"; + static const String lastingAt = "lastingAt"; + static const String requireRedeemedPoints = "requireRedeemedPoints"; + static const String updatedAt = "updatedAt"; + static const String type = "type"; + static const String priority = "priority"; + + PromotionSortingKey._(); +} diff --git a/lib/enums/promotions/promotion_status.dart b/lib/enums/promotions/promotion_status.dart index 1a7f5af..83e8109 100644 --- a/lib/enums/promotions/promotion_status.dart +++ b/lib/enums/promotions/promotion_status.dart @@ -1,3 +1,6 @@ +/// This is defining an enumeration called `PromotionStatus` with four possible values: `none`, +/// `active`, `assigned`, and `redeemed`. Each value is associated with a string representation +/// (`'NONE'`, `'ACTIVE'`, `'ASSIGNED'`, and `'REDEEMED'`, respectively). enum PromotionStatus { none('NONE'), active('ACTIVE'), @@ -8,6 +11,17 @@ enum PromotionStatus { final String promotionStatus; + /// The function returns a PromotionStatus enum value based on a given string input. + /// + /// Args: + /// string (String): A string value that represents the promotion status. It can be one of the + /// following values: 'ACTIVE', 'ASSIGNED', or 'REDEEMED'. If the string value is not one of these, + /// the function returns PromotionStatus.none. + /// + /// Returns: + /// a value of the `PromotionStatus` enum type based on the input string. If the input string + /// matches one of the defined enum values (`ACTIVE`, `ASSIGNED`, or `REDEEMED`), the corresponding + /// enum value is returned. Otherwise, the `none` value of the `PromotionStatus` enum is returned. static PromotionStatus getPromotionStatusFromString(String string) { if (string == 'ACTIVE') { return PromotionStatus.active; @@ -20,6 +34,10 @@ enum PromotionStatus { } } + /// This function returns the promotion status as a string. + /// + /// Returns: + /// The method is returning the value of the variable `promotionStatus` as a string. String promotionStatusAsString() { return promotionStatus; } diff --git a/lib/enums/promotions/promotion_type.dart b/lib/enums/promotions/promotion_type.dart index c1e3437..394fbdc 100644 --- a/lib/enums/promotions/promotion_type.dart +++ b/lib/enums/promotions/promotion_type.dart @@ -1,3 +1,10 @@ +/// This is an enum called `PromotionType` that defines five possible values: `unknown`, +/// `membersOnly`, `custom`, `general`, and `handbill`. Each value is associated with a string +/// representation. The enum also has a constructor that takes a string argument and a method +/// `getPromotionTypeFromString` that returns a `PromotionType` value based on a given string input. If +/// the input string matches one of the defined enum values, then the corresponding enum value is +/// returned. Otherwise, the value `unknown` is returned. The enum also has a method +/// `promotionTypeAsString` that returns the string representation of the enum value. enum PromotionType { unknown('UNKNOWN'), membersOnly('MEMBERS_ONLY'), @@ -9,6 +16,16 @@ enum PromotionType { final String promotionType; + /// This function returns a PromotionType enum value based on a given string input. + /// + /// Args: + /// string (String): A string value that represents a promotion type. + /// + /// Returns: + /// This function returns a value of the enum type `PromotionType`. The specific value returned + /// depends on the input string. If the input string matches one of the defined enum values + /// (`membersOnly`, `custom`, `general`, `handbill`), then the corresponding enum value is returned. + /// Otherwise, the value `unknown` is returned. static PromotionType getPromotionTypeFromString(String string) { if (string == 'MEMBERS_ONLY') { return PromotionType.membersOnly; @@ -23,6 +40,10 @@ enum PromotionType { } } + /// This function returns the promotion type as a string. + /// + /// Returns: + /// The method is returning the value of the variable `promotionType` as a string. String promotionTypeAsString() { return promotionType; } diff --git a/lib/enums/vouchers/voucher_code_status.dart b/lib/enums/vouchers/voucher_code_status.dart index a226307..d3d4e89 100644 --- a/lib/enums/vouchers/voucher_code_status.dart +++ b/lib/enums/vouchers/voucher_code_status.dart @@ -1,3 +1,6 @@ +/// This is defining an enumeration type called `VoucherCodeStatus` with four possible values: +/// `unassigned`, `assigned`, `redeemed`, and `canceled`. Each value is associated with a string +/// representation (`'UNASSIGNED'`, `'ASSIGNED'`, `'REDEEMED'`, and `'CANCELED'`, respectively). enum VoucherCodeStatus { unassigned('UNASSIGNED'), assigned('ASSIGNED'), @@ -8,6 +11,17 @@ enum VoucherCodeStatus { final String voucherCodeStatus; + /// The function converts a string to a corresponding VoucherCodeStatus enum value. + /// + /// Args: + /// string (String): A string representing the status of a voucher code. It can be one of the + /// following values: 'UNASSIGNED', 'ASSIGNED', 'REDEEMED', or 'CANCELED'. + /// + /// Returns: + /// This function returns a value of the `VoucherCodeStatus` enum type based on the input string. If + /// the input string matches one of the defined enum values, the corresponding enum value is returned. + /// If the input string does not match any of the defined enum values, the default value of + /// `VoucherCodeStatus.unassigned` is returned. static VoucherCodeStatus getVoucherCodeStatusFromString(String string) { if (string == 'UNASSIGNED') { return VoucherCodeStatus.unassigned; @@ -22,6 +36,10 @@ enum VoucherCodeStatus { } } + /// This function returns the voucher code status as a string. + /// + /// Returns: + /// The method is returning the value of the variable `voucherCodeStatus` as a string. String voucherCodeStatusAsString() { return voucherCodeStatus; } diff --git a/lib/events/auth/logged_in_event.dart b/lib/events/auth/logged_in_event.dart new file mode 100644 index 0000000..fc60cdb --- /dev/null +++ b/lib/events/auth/logged_in_event.dart @@ -0,0 +1,7 @@ +import '../custom_event.dart'; + +/// The class represents an event of signing in user with a label, event type, and optional +/// parameters. +class LoggedInEvent extends CustomEvent { + LoggedInEvent(String label, Map? parameters) : super(label, 'client.login', parameters); +} diff --git a/lib/events/auth/logged_out_event.dart b/lib/events/auth/logged_out_event.dart new file mode 100644 index 0000000..ef7e7d3 --- /dev/null +++ b/lib/events/auth/logged_out_event.dart @@ -0,0 +1,7 @@ +import '../custom_event.dart'; + +/// The `LoggedOutEvent` class represents an event of signing out of a client with a label and +/// optional parameters. +class LoggedOutEvent extends CustomEvent { + LoggedOutEvent(String label, Map? parameters) : super(label, 'client.logout', parameters); +} diff --git a/lib/events/auth/registered_event.dart b/lib/events/auth/registered_event.dart new file mode 100644 index 0000000..8744102 --- /dev/null +++ b/lib/events/auth/registered_event.dart @@ -0,0 +1,7 @@ +import '../custom_event.dart'; + +/// The RegisteredEvent is an event of client registration with a label, +/// parameters, and a specific type of 'client.register'. +class RegisteredEvent extends CustomEvent { + RegisteredEvent(String label, Map? parameters) : super(label, 'client.register', parameters); +} diff --git a/lib/events/cart/cart_event.dart b/lib/events/cart/cart_event.dart new file mode 100644 index 0000000..a663971 --- /dev/null +++ b/lib/events/cart/cart_event.dart @@ -0,0 +1,69 @@ +import '../../model/tracker/unit_price.dart'; +import '../custom_event.dart'; + +/// The class defines constant strings for various parameters used in a cart event. +abstract class CartEventParameters { + static const String sku = 'sku'; + static const String name = 'name'; + static const String category = 'category'; + static const String categories = 'categories'; + static const String offline = 'offline'; + static const String regularUnitPrice = 'regularUnitPrice'; + static const String finalUnitPrice = 'finalUnitPrice'; + static const String discountedUnitPrice = 'discountedUnitPrice'; + static const String url = 'url'; + static const String producer = 'producer'; + static const String quantity = 'quantity'; + + CartEventParameters._(); +} + +/// The abstract class CartEvent defines a custom event with parameters for a shopping cart action. +abstract class CartEvent extends CustomEvent { + CartEvent(String label, String action, String sku, UnitPrice finalPrice, int quantity, Map? parameters) + : super(label, action, parameters) { + this.parameters[CartEventParameters.sku] = sku; + this.parameters[CartEventParameters.quantity] = quantity; + this.parameters[CartEventParameters.finalUnitPrice] = finalPrice.asMap(); + } + + /// This function sets the name parameter in a cart object. + void setName(String name) { + parameters[CartEventParameters.name] = name; + } + + /// This function sets the category parameter for a cart event. + void setCategory(String category) { + parameters[CartEventParameters.category] = category; + } + + /// This function sets the categories parameter in a cart event. + void setCategories(List categories) { + parameters[CartEventParameters.categories] = categories; + } + + /// The function sets the offline parameter in the CartEventParameters map to a boolean value. + void setOffline(bool offline) { + parameters[CartEventParameters.offline] = offline; + } + + /// This function sets the regular unit price for a cart event. + void setRegularPrice(UnitPrice regularPrice) { + parameters[CartEventParameters.regularUnitPrice] = regularPrice.asMap(); + } + + /// This function sets the discounted unit price for a cart event. + void setDiscountedPrice(UnitPrice discountedPrice) { + parameters[CartEventParameters.discountedUnitPrice] = discountedPrice.asMap(); + } + + /// This function sets a URL parameter in a cart event. + void setUrl(String url) { + parameters[CartEventParameters.url] = url; + } + + /// This function sets the producer parameter in a cart event. + void setProducer(String producer) { + parameters[CartEventParameters.producer] = producer; + } +} diff --git a/lib/events/cart/product_added_to_cart_event.dart b/lib/events/cart/product_added_to_cart_event.dart new file mode 100644 index 0000000..bea94f7 --- /dev/null +++ b/lib/events/cart/product_added_to_cart_event.dart @@ -0,0 +1,8 @@ +import '../../model/tracker/unit_price.dart'; +import 'cart_event.dart'; + +/// The class represents an event of adding a product to a cart with relevant information. +class ProductAddedToCartEvent extends CartEvent { + ProductAddedToCartEvent(String label, String sku, UnitPrice finalPrice, int quantity, Map? parameters) + : super(label, 'product.addToCart', sku, finalPrice, quantity, parameters); +} diff --git a/lib/events/cart/product_removed_from_cart_event.dart b/lib/events/cart/product_removed_from_cart_event.dart new file mode 100644 index 0000000..d149931 --- /dev/null +++ b/lib/events/cart/product_removed_from_cart_event.dart @@ -0,0 +1,9 @@ +import '../../model/tracker/unit_price.dart'; +import 'cart_event.dart'; + +/// The ProductRemovedFromCartEvent class represents an event where a +/// product is removed from the cart. +class ProductRemovedFromCartEvent extends CartEvent { + ProductRemovedFromCartEvent(String label, String sku, UnitPrice finalPrice, int quantity, Map? parameters) + : super(label, 'product.removeFromCart', sku, finalPrice, quantity, parameters); +} diff --git a/lib/events/custom_event.dart b/lib/events/custom_event.dart new file mode 100644 index 0000000..bcd5ba2 --- /dev/null +++ b/lib/events/custom_event.dart @@ -0,0 +1,7 @@ +import 'event.dart'; + +/// The CustomEvent class extends the Event class and defines a custom event type with a label, action, +/// and parameters. +class CustomEvent extends Event { + CustomEvent(String label, String action, Map? parameters) : super(label, action, parameters ?? {}); +} diff --git a/lib/events/event.dart b/lib/events/event.dart new file mode 100644 index 0000000..33e46e2 --- /dev/null +++ b/lib/events/event.dart @@ -0,0 +1,12 @@ +/// The class "Event" defines a custom event with a type, label, action, and parameters, and provides +/// a method to convert it to a map. +abstract class Event { + final String _label; + final String _action; + Map parameters; + + Event(this._label, this._action, this.parameters); + + /// The function returns a map with the values of type, label, action, and parameters. + Map asMap() => {'label': _label, 'action': _action, 'params': parameters}; +} diff --git a/lib/events/other/appeared_in_location_event.dart b/lib/events/other/appeared_in_location_event.dart new file mode 100644 index 0000000..2a0f251 --- /dev/null +++ b/lib/events/other/appeared_in_location_event.dart @@ -0,0 +1,23 @@ +import '../custom_event.dart'; + +/// The class defines two constant strings representing latitude and longitude parameters for an event. +abstract class AppearedInLocationEventParameters { + static const String lat = 'lat'; + static const String lon = 'lon'; + + AppearedInLocationEventParameters._(); +} + +/// The AppearedInLocationEvent class represents an event where a client has appeared in a specific +/// location, with latitude and longitude parameters. +class AppearedInLocationEvent extends CustomEvent { + AppearedInLocationEvent( + String label, + double lat, + double lon, + Map? parameters, + ) : super(label, 'client.location', parameters) { + this.parameters[AppearedInLocationEventParameters.lat] = lat; + this.parameters[AppearedInLocationEventParameters.lon] = lon; + } +} diff --git a/lib/events/other/hit_timer_event.dart b/lib/events/other/hit_timer_event.dart new file mode 100644 index 0000000..ea619d8 --- /dev/null +++ b/lib/events/other/hit_timer_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The HitTimerEvent class is an event that represents a hit timer event with a label and +/// optional parameters. +class HitTimerEvent extends CustomEvent { + HitTimerEvent( + String label, + Map? parameters, + ) : super(label, 'client.hitTimer', parameters); +} diff --git a/lib/events/other/searched_event.dart b/lib/events/other/searched_event.dart new file mode 100644 index 0000000..fb69b48 --- /dev/null +++ b/lib/events/other/searched_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The `SearchedEvent` class is a custom event that represents a search action with a label and +/// optional parameters. +class SearchedEvent extends CustomEvent { + SearchedEvent( + String label, + Map? parameters, + ) : super(label, 'client.search', parameters); +} diff --git a/lib/events/other/shared_event.dart b/lib/events/other/shared_event.dart new file mode 100644 index 0000000..9fc775a --- /dev/null +++ b/lib/events/other/shared_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The SharedEvent represents a shared event with a label and +/// optional parameters. +class SharedEvent extends CustomEvent { + SharedEvent( + String label, + Map? parameters, + ) : super(label, 'client.shared', parameters); +} diff --git a/lib/events/other/visited_screen_event.dart b/lib/events/other/visited_screen_event.dart new file mode 100644 index 0000000..bf0eed8 --- /dev/null +++ b/lib/events/other/visited_screen_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The VisitedScreenEvent class is an event that represents a screen view with a label and +/// optional parameters. +class VisitedScreenEvent extends CustomEvent { + VisitedScreenEvent( + String label, + Map? parameters, + ) : super(label, 'screen.view', parameters); +} diff --git a/lib/events/product/product_added_to_favorites_event.dart b/lib/events/product/product_added_to_favorites_event.dart new file mode 100644 index 0000000..51d470c --- /dev/null +++ b/lib/events/product/product_added_to_favorites_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// ProductAddedToFavoritesEvent represents an event of adding a product to favorites with a label and +/// optional parameters. +class ProductAddedToFavoritesEvent extends CustomEvent { + ProductAddedToFavoritesEvent( + String label, + Map? parameters, + ) : super(label, 'product.addToFavorite', parameters); +} diff --git a/lib/events/product/product_viewed_event.dart b/lib/events/product/product_viewed_event.dart new file mode 100644 index 0000000..c3d23f2 --- /dev/null +++ b/lib/events/product/product_viewed_event.dart @@ -0,0 +1,35 @@ +import '../custom_event.dart'; + +/// The class defines constant strings for the parameters of a product viewed event. +abstract class ProductViewedEventParameters { + static const String productId = 'productId'; + static const String name = 'name'; + static const String category = 'category'; + static const String url = 'url'; + + ProductViewedEventParameters._(); +} + +/// The ProductViewedEvent class represents an event where a product has been viewed, with specific +/// parameters such as the product ID and name. +class ProductViewedEvent extends CustomEvent { + ProductViewedEvent( + String label, + String productId, + String name, + Map? parameters, + ) : super(label, 'product.view', parameters) { + this.parameters[ProductViewedEventParameters.productId] = productId; + this.parameters[ProductViewedEventParameters.name] = name; + } + + /// This function sets the category parameter for a ProductViewedEvent in Dart.= + void setCategory(String category) { + parameters[ProductViewedEventParameters.category] = category; + } + + /// This function sets the URL parameter for a ProductViewedEvent. + void setUrl(String url) { + parameters[ProductViewedEventParameters.url] = url; + } +} diff --git a/lib/events/push/push_cancelled_event.dart b/lib/events/push/push_cancelled_event.dart new file mode 100644 index 0000000..9dc64bc --- /dev/null +++ b/lib/events/push/push_cancelled_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The PushCancelledEvent class is a custom event that represents the cancellation of a push +/// notification. +class PushCancelledEvent extends CustomEvent { + PushCancelledEvent( + String label, + Map? parameters, + ) : super(label, 'push.cancel', parameters); +} diff --git a/lib/events/push/push_clicked_event.dart b/lib/events/push/push_clicked_event.dart new file mode 100644 index 0000000..c6c544f --- /dev/null +++ b/lib/events/push/push_clicked_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The PushClickedEvent class is a custom event that represents a push notification click with a label +/// and optional parameters. +class PushClickedEvent extends CustomEvent { + PushClickedEvent( + String label, + Map? parameters, + ) : super(label, 'push.click', parameters); +} diff --git a/lib/events/push/push_viewed_event.dart b/lib/events/push/push_viewed_event.dart new file mode 100644 index 0000000..88bca23 --- /dev/null +++ b/lib/events/push/push_viewed_event.dart @@ -0,0 +1,10 @@ +import '../custom_event.dart'; + +/// The PushViewedEvent class is a custom event that represents a push notification being viewed, with a +/// label and optional parameters. +class PushViewedEvent extends CustomEvent { + PushViewedEvent( + String label, + Map? parameters, + ) : super(label, 'push.view', parameters); +} diff --git a/lib/events/recommendation/recommendation_click_event.dart b/lib/events/recommendation/recommendation_click_event.dart new file mode 100644 index 0000000..aa03fe3 --- /dev/null +++ b/lib/events/recommendation/recommendation_click_event.dart @@ -0,0 +1,35 @@ +import 'recommendation_event.dart'; + +/// The class defines static constants for parameters used in a recommendation click event. +abstract class RecommendationClickEventParameters { + static const String productId = 'productId'; + static const String name = 'name'; + static const String category = 'category'; + static const String campaignHash = 'campaignHash'; + static const String campaignId = 'campaignId'; + static const String url = 'url'; + + RecommendationClickEventParameters._(); +} + +/// The class represents a recommendation click event with specific parameters. +abstract class RecommendationClickEvent extends RecommendationEvent { + RecommendationClickEvent(String label, String action, String productId, String productName, String campaignId, String campaignHash, + Map? parameters) + : super(label, 'recommendation.click', parameters) { + this.parameters[RecommendationClickEventParameters.productId] = productId; + this.parameters[RecommendationClickEventParameters.name] = productName; + this.parameters[RecommendationClickEventParameters.campaignId] = campaignId; + this.parameters[RecommendationClickEventParameters.campaignHash] = campaignHash; + } + + /// This function sets the category parameter for a recommendation click event. + void setCategory(String category) { + parameters[RecommendationClickEventParameters.category] = category; + } + + /// The function sets a URL parameter in a recommendation click event. + void setUrl(String url) { + parameters[RecommendationClickEventParameters.url] = url; + } +} diff --git a/lib/events/recommendation/recommendation_event.dart b/lib/events/recommendation/recommendation_event.dart new file mode 100644 index 0000000..8c379d1 --- /dev/null +++ b/lib/events/recommendation/recommendation_event.dart @@ -0,0 +1,7 @@ +import '../custom_event.dart'; + +/// The class `RecommendationEvent` extends `CustomEvent` and creates a new event for recommendations +/// with a label, action, and parameters. +class RecommendationEvent extends CustomEvent { + RecommendationEvent(super.label, super.action, super.parameters); +} diff --git a/lib/events/recommendation/recommendation_seen_event.dart b/lib/events/recommendation/recommendation_seen_event.dart new file mode 100644 index 0000000..cafa297 --- /dev/null +++ b/lib/events/recommendation/recommendation_seen_event.dart @@ -0,0 +1,36 @@ +import 'recommendation_event.dart'; + +/// The class defines static constants for parameters related to a recommendation seen event. +abstract class RecommendationSeenEventParameters { + static const String productId = 'productId'; + static const String name = 'name'; + static const String category = 'category'; + static const String campaignHash = 'campaignHash'; + static const String campaignId = 'campaignId'; + static const String url = 'url'; + + RecommendationSeenEventParameters._(); +} + +/// This is a recommendation seen event with parameters such as product ID, +/// product name, campaign ID, and campaign hash. +abstract class RecommendationSeenEvent extends RecommendationEvent { + RecommendationSeenEvent(String label, String action, String productId, String productName, String campaignId, String campaignHash, + Map? parameters) + : super(label, 'recommendation.seen', parameters) { + this.parameters[RecommendationSeenEventParameters.productId] = productId; + this.parameters[RecommendationSeenEventParameters.name] = productName; + this.parameters[RecommendationSeenEventParameters.campaignId] = campaignId; + this.parameters[RecommendationSeenEventParameters.campaignHash] = campaignHash; + } + + /// This function sets the category parameter for a recommendation seen event. + void setCategory(String category) { + parameters[RecommendationSeenEventParameters.category] = category; + } + + /// This function sets a URL parameter in a map called "parameters". + void setUrl(String url) { + parameters[RecommendationSeenEventParameters.url] = url; + } +} diff --git a/lib/events/recommendation/recommendation_view_event.dart b/lib/events/recommendation/recommendation_view_event.dart new file mode 100644 index 0000000..032765e --- /dev/null +++ b/lib/events/recommendation/recommendation_view_event.dart @@ -0,0 +1,33 @@ +import 'recommendation_event.dart'; + +/// The class defines static constants for parameters used in recommendation views. +abstract class RecommendationViewParameters { + static const String items = 'items'; + static const String category = 'category'; + static const String campaignHash = 'campaignHash'; + static const String campaignId = 'campaignId'; + static const String url = 'url'; + static const String correlationId = 'correlationId'; + + RecommendationViewParameters._(); +} + +/// The class RecommendationViewEvent is used to create an event with specific parameters for tracking +/// recommendation views. +class RecommendationViewEvent extends RecommendationEvent { + RecommendationViewEvent(String label, String action, List? items, String campaignId, String campaignHash, String correlationId, + Map? parameters) + : super(label, 'recommendation.view', parameters) { + if (items != null) { + this.parameters[RecommendationViewParameters.items] = items; + } + this.parameters[RecommendationViewParameters.correlationId] = campaignId; + this.parameters[RecommendationViewParameters.correlationId] = campaignHash; + this.parameters[RecommendationViewParameters.correlationId] = correlationId; + } + + /// The function sets a list of items as a parameter in a recommendation view. + void setItems(List items) { + parameters[RecommendationViewParameters.items] = items; + } +} diff --git a/lib/main/dependencies.dart b/lib/main/dependencies.dart index 394c833..d450b23 100644 --- a/lib/main/dependencies.dart +++ b/lib/main/dependencies.dart @@ -1,6 +1,8 @@ import 'package:flutter/services.dart'; +/// The class Dependencies contains two static constants representing MethodChannels for the Synerise +/// Flutter SDK and its background operations. class Dependencies { static const methodChannel = MethodChannel('synerise_flutter_sdk'); static const backgroundMethodChannel = MethodChannel('synerise_flutter_sdk_background'); -} \ No newline at end of file +} diff --git a/lib/main/index.dart b/lib/main/index.dart index e44365c..7b06e56 100644 --- a/lib/main/index.dart +++ b/lib/main/index.dart @@ -1,3 +1,5 @@ +/// This code exports various classes and enums from the Synerise Flutter SDK. It allows the application developer +/// to access the objects from the Synerise SDK without the importing them. // CONFIG export 'package:synerise_flutter_sdk/main/dependencies.dart'; @@ -27,13 +29,12 @@ export 'package:synerise_flutter_sdk/enums/client/identity_provider.dart'; export 'package:synerise_flutter_sdk/enums/client/token_origin.dart'; // CONTENT -export 'package:synerise_flutter_sdk/model/content/documents_api_query.dart'; export 'package:synerise_flutter_sdk/model/content/recommendation_options.dart'; export 'package:synerise_flutter_sdk/model/content/recommendation.dart'; -export 'package:synerise_flutter_sdk/model/content/screen_view_audience.dart'; export 'package:synerise_flutter_sdk/model/content/recommendation_response.dart'; -export 'package:synerise_flutter_sdk/enums/content/documents_api_query_type.dart'; -export 'package:synerise_flutter_sdk/model/content/screen_view_response.dart'; +export 'package:synerise_flutter_sdk/model/content/document.dart'; +export 'package:synerise_flutter_sdk/model/content/screen_view_audience_info.dart'; +export 'package:synerise_flutter_sdk/model/content/screen_view.dart'; // PROMOTIONS export 'package:synerise_flutter_sdk/model/promotions/promotion.dart'; @@ -51,6 +52,7 @@ export 'package:synerise_flutter_sdk/enums/promotions/promotion_identifier_key.d export 'package:synerise_flutter_sdk/enums/promotions/promotion_item_scope.dart'; export 'package:synerise_flutter_sdk/enums/promotions/promotion_status.dart'; export 'package:synerise_flutter_sdk/enums/promotions/promotion_type.dart'; +export 'package:synerise_flutter_sdk/enums/promotions/promotion_sorting_key.dart'; // VOUCHERS export 'package:synerise_flutter_sdk/model/vouchers/assign_voucher_data.dart'; @@ -63,8 +65,29 @@ export 'package:synerise_flutter_sdk/enums/vouchers/voucher_code_status.dart'; export 'package:synerise_flutter_sdk/model/in_app/in_app_message_data.dart'; // TRACKER -export 'package:synerise_flutter_sdk/model/tracker/event.dart'; -export 'package:synerise_flutter_sdk/model/tracker/custom_event.dart'; +export 'package:synerise_flutter_sdk/events/event.dart'; +export 'package:synerise_flutter_sdk/events/custom_event.dart'; +export 'package:synerise_flutter_sdk/events/cart/cart_event.dart'; +export 'package:synerise_flutter_sdk/model/tracker/unit_price.dart'; +export 'package:synerise_flutter_sdk/events/cart/product_added_to_cart_event.dart'; +export 'package:synerise_flutter_sdk/events/cart/product_removed_from_cart_event.dart'; +export 'package:synerise_flutter_sdk/events/auth/logged_in_event.dart'; +export 'package:synerise_flutter_sdk/events/auth/logged_out_event.dart'; +export 'package:synerise_flutter_sdk/events/auth/registered_event.dart'; +export 'package:synerise_flutter_sdk/events/other/appeared_in_location_event.dart'; +export 'package:synerise_flutter_sdk/events/other/hit_timer_event.dart'; +export 'package:synerise_flutter_sdk/events/other/searched_event.dart'; +export 'package:synerise_flutter_sdk/events/other/shared_event.dart'; +export 'package:synerise_flutter_sdk/events/other/visited_screen_event.dart'; +export 'package:synerise_flutter_sdk/events/product/product_added_to_favorites_event.dart'; +export 'package:synerise_flutter_sdk/events/product/product_viewed_event.dart'; +export 'package:synerise_flutter_sdk/events/push/push_cancelled_event.dart'; +export 'package:synerise_flutter_sdk/events/push/push_clicked_event.dart'; +export 'package:synerise_flutter_sdk/events/push/push_viewed_event.dart'; +export 'package:synerise_flutter_sdk/events/recommendation/recommendation_click_event.dart'; +export 'package:synerise_flutter_sdk/events/recommendation/recommendation_event.dart'; +export 'package:synerise_flutter_sdk/events/recommendation/recommendation_seen_event.dart'; +export 'package:synerise_flutter_sdk/events/recommendation/recommendation_view_event.dart'; //BASE API QUERY export 'package:synerise_flutter_sdk/model/base_api_query.dart'; diff --git a/lib/main/synerise_initializer.dart b/lib/main/synerise_initializer.dart index 1d18d4d..36d486c 100644 --- a/lib/main/synerise_initializer.dart +++ b/lib/main/synerise_initializer.dart @@ -1,7 +1,6 @@ import 'package:flutter/services.dart'; import 'dependencies.dart'; - class SyneriseInitializer { MethodChannel methodChannel = Dependencies.methodChannel; @@ -14,30 +13,57 @@ class SyneriseInitializer { SyneriseInitializer(); + /// This function sets a completion handler function that takes a boolean parameter. void setCompletionHandler(Function(bool) completionHandler) { this.completionHandler = completionHandler; } + /// The function sets the client API key and returns the SyneriseInitializer object. + /// + /// Args: + /// clientApiKey (String): The clientApiKey parameter is a string that represents the API key of the + /// Synerise client. This key is used to authenticate and authorize the client's access to the + /// Synerise platform. SyneriseInitializer withClientApiKey(String clientApiKey) { _clientApiKey = clientApiKey; return this; } + /// The function sets the base URL for the SyneriseInitializer and returns the instance. + /// + /// Args: + /// baseUrl (String): The `baseUrl` parameter is a string that represents the base URL of the + /// Synerise API. It is used to initialize the Synerise SDK with the correct API endpoint. SyneriseInitializer withBaseUrl(String baseUrl) { _baseUrl = baseUrl; return this; } + /// This function sets the debug mode for the SyneriseInitializer and returns the instance. + /// + /// Args: + /// debugModeEnabled (bool): A boolean parameter that determines whether debug mode is enabled or + /// not. Debug mode is a feature that allows developers to debug and troubleshoot their code by providing + /// additional information and logging. SyneriseInitializer withDebugModeEnabled(bool debugModeEnabled) { _debugModeEnabled = debugModeEnabled; return this; } + /// This function sets the value of a boolean variable for enabling or disabling crash handling and + /// returns an instance of the SyneriseInitializer class. + /// + /// Args: + /// crashHandlingEnabled (bool): A boolean parameter that determines whether or not crash handling + /// is enabled in the SyneriseInitializer. If set to true, the SyneriseInitializer will handle any + /// crashes that occur during runtime. SyneriseInitializer withCrashHandlingEnabled(bool crashHandlingEnabled) { _crashHandlingEnabled = crashHandlingEnabled; return this; } + /// This function initializes a Synerise SDK instance with specified parameters and invokes a + /// completion handler. Future init() async { if (completionHandler != null) { completionHandler!(false); @@ -58,4 +84,4 @@ class SyneriseInitializer { return result; } -} \ No newline at end of file +} diff --git a/lib/model/base_api_query.dart b/lib/model/base_api_query.dart index 514d37e..b31cba4 100644 --- a/lib/model/base_api_query.dart +++ b/lib/model/base_api_query.dart @@ -1,3 +1,6 @@ +/// This is an enumeration in Dart that defines two values: `ascending` and `descending`. Each value has +/// a corresponding `apiQuerySortingOrder` string value ('asc' for `ascending` and 'desc' for +/// `descending`). enum ApiQuerySortingOrder { ascending('asc'), descending('desc'); @@ -6,11 +9,14 @@ enum ApiQuerySortingOrder { final String apiQuerySortingOrder; + /// This function returns a string representing the sorting order for an API query. String apiQuerySortingOrderAsString() { return apiQuerySortingOrder; } } +/// The `ApiQuerySorting` class represents a sorting query for an API with a specified property and +/// order. class ApiQuerySorting { String property; ApiQuerySortingOrder order; @@ -20,12 +26,11 @@ class ApiQuerySorting { required this.order, }); - Map asMap() => { - 'property': property, - 'order': order.apiQuerySortingOrderAsString() - }; + /// This function returns a map with the property and order values as key-value pairs. + Map asMap() => {'property': property, 'order': order.apiQuerySortingOrderAsString()}; } +/// The class represents a base API query with properties for limit, page, sorting, and includeMeta. class BaseApiQuery { int limit = 100; int page = 1; diff --git a/lib/model/client/client_account_information.dart b/lib/model/client/client_account_information.dart index be47fe0..cd07764 100644 --- a/lib/model/client/client_account_information.dart +++ b/lib/model/client/client_account_information.dart @@ -2,6 +2,8 @@ import '../../enums/client/client_sex.dart'; import '../../utils/synerise_utils.dart'; import 'client_agreements.dart'; +/// The class represents client account information with various properties such as email, phone, name, +/// address, and agreements. class ClientAccountInformation { final int clientId; final String email; @@ -55,6 +57,8 @@ class ClientAccountInformation { this.attributes, required this.tags}); + /// This is a named constructor in the `ClientAccountInformation` class that takes a `Map` as input + /// and creates a new instance of `ClientAccountInformation` with the values extracted from the map. ClientAccountInformation.fromMap(Map map) : this( clientId: map['clientId'], diff --git a/lib/model/client/client_account_register_context.dart b/lib/model/client/client_account_register_context.dart index 083d2ed..9a988c8 100644 --- a/lib/model/client/client_account_register_context.dart +++ b/lib/model/client/client_account_register_context.dart @@ -1,6 +1,8 @@ import '../../enums/client/client_sex.dart'; import 'client_agreements.dart'; +/// The `ClientAccountRegisterContext` class represents the context for registering a client account, +/// including personal information, agreements, and attributes. class ClientAccountRegisterContext { String email; String password; @@ -37,26 +39,33 @@ class ClientAccountRegisterContext { this.agreements, this.attributes}); + /// `ClientAccountRegisterContext.fromMap(Map map)` is a constructor that takes a `Map` as an argument + /// and creates a new instance of `ClientAccountRegisterContext` using the values from the `Map`. ClientAccountRegisterContext.fromMap(Map map) : this( - email: map['email'], - password: map['password'], - firstName: map['firstName'], - lastName: map['lastName'], - sex: map['sex'], - phone: map['phone'], - company: map['company'], - address: map['address'], - city: map['city'], - zipcode: map['zipcode'], - countrycode: map['countrycode'], - province: map['province'], - uuid: map['uuid'], - customId: map['customId'], - agreements: map['agreements'], + email: map['email'], + password: map['password'], + firstName: map['firstName'], + lastName: map['lastName'], + sex: map['sex'] != null ? ClientSex.getClientSexFromString(map['sex']) : null, + phone: map['phone'], + company: map['company'], + address: map['address'], + city: map['city'], + zipcode: map['zipcode'], + countrycode: map['countrycode'], + province: map['province'], + uuid: map['uuid'], + customId: map['customId'], + agreements: map['agreements'] != null ? ClientAgreements.fromMap(map['agreements']) : null, attributes: map['attributes'] != null ? Map.from(map['attributes']) : null, ); + /// `Map asMap()` is a method that returns a `Map` representation of the + /// `ClientAccountRegisterContext` object. It includes all the properties of the object as key-value + /// pairs in the returned `Map`. If a property is null, it will not be included in the returned `Map`. + /// The `agreements` property is converted to a `Map` using its own `asMap()` method, and the + /// `attributes` property is included as is. Map asMap() => { 'email': email, 'password': password, diff --git a/lib/model/client/client_account_update_context.dart b/lib/model/client/client_account_update_context.dart index d4ea9b6..fbff8f0 100644 --- a/lib/model/client/client_account_update_context.dart +++ b/lib/model/client/client_account_update_context.dart @@ -1,6 +1,8 @@ import '../../enums/client/client_sex.dart'; import 'client_agreements.dart'; +/// The `ClientAccountUpdateContext` class represents the context for updating a client's account +/// information, including personal details, agreements, and custom attributes. class ClientAccountUpdateContext { String? email; String? password; @@ -37,6 +39,9 @@ class ClientAccountUpdateContext { this.agreements, this.attributes}); + /// `Map asMap()` is a method that returns a `Map` object containing all the properties of the + /// `ClientAccountUpdateContext` instance. The keys of the map correspond to the property names, and + /// the values correspond to the property values. Map asMap() => { 'email': email, 'password': password, diff --git a/lib/model/client/client_agreements.dart b/lib/model/client/client_agreements.dart index 521697b..3b3a419 100644 --- a/lib/model/client/client_agreements.dart +++ b/lib/model/client/client_agreements.dart @@ -1,3 +1,6 @@ +/// The `ClientAgreements` class represents a client's agreements for email, SMS, push notifications, +/// Bluetooth, RFID, and Wi-Fi, and includes methods for setting and getting these agreements, as well +/// as a constructor for creating objects from a `Map`. class ClientAgreements { bool? email; bool? sms; @@ -56,8 +59,12 @@ class ClientAgreements { return wifi; } + /// `ClientAgreements.fromMap(Map map)` is a constructor that takes a `Map` as an argument and + /// initializes a new `ClientAgreements` object with the values from the `Map`. ClientAgreements.fromMap(Map map) : this(email: map['email'], sms: map['sms'], push: map['push'], bluetooth: map['bluetooth'], rfid: map['rfid'], wifi: map['wifi']); + /// This function returns a map containing email, sms, push, bluetooth, rfid, and wifi as keys and + /// their corresponding values. Map asMap() => {'email': email, 'sms': sms, 'push': push, 'bluetooth': bluetooth, 'rfid': rfid, 'wifi': wifi}; } diff --git a/lib/model/client/client_auth_context.dart b/lib/model/client/client_auth_context.dart index 5d746ce..9d1d1c3 100644 --- a/lib/model/client/client_auth_context.dart +++ b/lib/model/client/client_auth_context.dart @@ -1,5 +1,7 @@ import 'client_agreements.dart'; +/// The `ClientAuthContext` class represents the authentication context of a client, including their ID, +/// agreements, and attributes. class ClientAuthContext { String? authId; ClientAgreements? agreements; @@ -7,11 +9,13 @@ class ClientAuthContext { ClientAuthContext({this.authId, this.agreements, this.attributes}); + /// `ClientAuthContext.fromMap(Map map)` is a constructor that takes a `Map` as an argument and + /// creates a new instance of `ClientAuthContext` using the values from the `Map`. ClientAuthContext.fromMap(Map map) : this( authId: map['authID'], - agreements: map['agreements'], + agreements: map['agreements'] != null ? ClientAgreements.fromMap(map['agreements']) : null, attributes: map['attributes'] != null ? Map.from(map['attributes']) : null); - + Map asMap() => {'authID': authId, 'agreements': agreements?.asMap(), 'attributes': attributes}; } diff --git a/lib/model/client/token.dart b/lib/model/client/token.dart index 1082836..1542120 100644 --- a/lib/model/client/token.dart +++ b/lib/model/client/token.dart @@ -1,6 +1,7 @@ import '../../enums/client/token_origin.dart'; import '../../utils/synerise_utils.dart'; +/// The Token class represents a token with a string value, origin information, and an expiration date. class Token { final String tokenString; final TokenOrigin origin; @@ -8,9 +9,12 @@ class Token { Token({required this.tokenString, required this.origin, required this.expirationDate}); - Token.fromMap(Map map): this( - tokenString: map['tokenString'], - origin: TokenOrigin.fromString(map['origin']), - expirationDate: SyneriseUtils.formatIntToDateTime(map['expirationDate']) - ); + /// `Token.fromMap(Map map)` is a named constructor that creates a new instance of the `Token` class + /// from a `Map` object. It takes a `Map` object as an argument and uses its values to initialize the + /// properties of the `Token` object. + Token.fromMap(Map map) + : this( + tokenString: map['tokenString'], + origin: TokenOrigin.fromString(map['origin']), + expirationDate: SyneriseUtils.formatIntToDateTime(map['expirationDate'])); } diff --git a/lib/model/content/document.dart b/lib/model/content/document.dart new file mode 100644 index 0000000..d70aac0 --- /dev/null +++ b/lib/model/content/document.dart @@ -0,0 +1,33 @@ +/// The `Document` class represents a document with an identifier, slug, schema, and optional content +/// stored as a map. +class Document { + final String identifier; + final String slug; + final String schema; + final Map? content; + + Document._({ + required this.identifier, + required this.slug, + required this.schema, + this.content, + }); + + /// `Document.fromMap(Map map)` is a constructor that takes a `Map` as an argument and creates a new + /// `Document` object from it. + Document.fromMap(Map map) + : this._( + identifier: map['identifier'], + slug: map['slug'], + schema: map['schema'], + content: map['content'] != null ? Map.from(map['content']) : null, + ); + + /// The function returns a map containing the identifier, slug, schema, and content properties. + Map asMap() => { + 'identifier': identifier, + 'slug': slug, + 'schema': schema, + 'content': content, + }; +} diff --git a/lib/model/content/documents_api_query.dart b/lib/model/content/documents_api_query.dart index bc58cf2..178c388 100644 --- a/lib/model/content/documents_api_query.dart +++ b/lib/model/content/documents_api_query.dart @@ -1,5 +1,7 @@ import '../../enums/content/documents_api_query_type.dart'; +/// The DocumentsApiQuery class represents a query for a document API with a type, type value, and +/// optional version. class DocumentsApiQuery { DocumentsApiQueryType type; String typeValue; @@ -11,7 +13,10 @@ class DocumentsApiQuery { this.version, }); + /// This is a constructor that creates a new instance of the `DocumentsApiQuery` class from a `Map` + /// object. DocumentsApiQuery.fromMap(Map map) : this(type: map['type'], typeValue: map['typeValue'], version: map['version']); + /// The function returns a map with the type, type value, and version as key-value pairs. Map asMap() => {'type': type.getDocumentsApiQueryTypeAsString(), 'typeValue': typeValue, 'version': version}; } diff --git a/lib/model/content/recommendation.dart b/lib/model/content/recommendation.dart index 4955f12..9e0d4bc 100644 --- a/lib/model/content/recommendation.dart +++ b/lib/model/content/recommendation.dart @@ -1,3 +1,5 @@ +/// The class Recommendation represents a recommendation with attributes and an item ID, and can be +/// converted to and from a map. class Recommendation { final Map attributes; final String itemID; @@ -7,12 +9,15 @@ class Recommendation { required this.itemID, }); + /// This is a named constructor in the `Recommendation` class that takes a `Map` as input and creates + /// a new instance of the `Recommendation` class using the values from the input `Map`. Recommendation.fromMap(Map map) : this._( attributes: Map.from(map['attributes']), itemID: map['itemID'], ); + /// The function returns a map with 'attributes' and 'itemID' keys and their corresponding values. Map asMap() => { 'attributes': attributes, 'itemID': itemID, diff --git a/lib/model/content/recommendation_options.dart b/lib/model/content/recommendation_options.dart index ae9d6cb..36f3cf9 100644 --- a/lib/model/content/recommendation_options.dart +++ b/lib/model/content/recommendation_options.dart @@ -1,20 +1,70 @@ +/// The `enum RecommendationFiltersJoinerRule` is defining a set of possible values for a recommendation +/// filter joiner rule. It has three possible values: `and`, `or`, and `replace`. +enum RecommendationFiltersJoinerRule { + and('and'), + or('or'), + replace('replace'); + + const RecommendationFiltersJoinerRule(this.recommendationFiltersJoinerRule); + + final String recommendationFiltersJoinerRule; + + static RecommendationFiltersJoinerRule? getRecommendationFiltersJoinerRuleFromString(String string) { + if (string == 'and') { + return RecommendationFiltersJoinerRule.and; + } else if (string == 'or') { + return RecommendationFiltersJoinerRule.or; + } else if (string == 'replace') { + return RecommendationFiltersJoinerRule.replace; + } else { + return null; + } + } + + String recommendationFiltersJoinerRuleAsString() { + return recommendationFiltersJoinerRule; + } +} + +/// The class "RecommendationOptions" contains various properties for configuring recommendations, such +/// as product IDs, filters, and display attributes. class RecommendationOptions { String slug; String? productID; + List? productIDs; + List? itemsExcluded; + String? additionalFilters; + RecommendationFiltersJoinerRule? filtersJoiner; + String? additionalElasticFilters; + RecommendationFiltersJoinerRule? elasticFiltersJoiner; + List? displayAttribute; + bool? includeContextItems; RecommendationOptions({ required this.slug, this.productID, + this.productIDs, + this.itemsExcluded, + this.additionalFilters, + this.filtersJoiner, + this.additionalElasticFilters, + this.elasticFiltersJoiner, + this.displayAttribute, + this.includeContextItems = false, }); - RecommendationOptions.fromMap(Map map) - : this( - slug: map['slug'], - productID: map['productID'], - ); - + /// `Map asMap()` is a method that returns a `Map` object containing the properties of the + /// `RecommendationOptions` class as key-value pairs. Map asMap() => { 'slug': slug, 'productID': productID, + 'productIDs': productIDs, + 'itemsExcluded': itemsExcluded, + 'additionalFilters': additionalFilters, + 'filtersJoiner': filtersJoiner?.recommendationFiltersJoinerRuleAsString(), + 'additionalElasticFilters': additionalElasticFilters, + 'elasticFiltersJoiner': elasticFiltersJoiner?.recommendationFiltersJoinerRuleAsString(), + 'displayAttribute': displayAttribute, + 'includeContextItems': includeContextItems, }; } diff --git a/lib/model/content/recommendation_response.dart b/lib/model/content/recommendation_response.dart index 1ed4e01..9e7b38b 100644 --- a/lib/model/content/recommendation_response.dart +++ b/lib/model/content/recommendation_response.dart @@ -1,38 +1,44 @@ import 'recommendation.dart'; +/// The code defines a Dart class for a recommendation response and includes a function to convert a +/// list of objects to a list of recommendations. class RecommendationResponse { + final String name; final String campaignHash; final String campaignID; + final String correlationID; final String schema; final String slug; final String uuid; - final String name; final List items; RecommendationResponse._( - {required this.campaignHash, + {required this.name, + required this.campaignHash, required this.campaignID, + required this.correlationID, required this.schema, required this.slug, required this.uuid, - required this.items, - required this.name}); + required this.items}); + /// This is a named constructor in the `RecommendationResponse` class that takes a `Map` as input and + /// initializes the properties of a `RecommendationResponse` object. RecommendationResponse.fromMap(Map map) : this._( - campaignHash: map['campaignHash'], - campaignID: map['campaignID'], - schema: map['schema'], - slug: map['slug'], - uuid: map['uuid'], - items: _convertObjectListToRecoList(map['items']), - name: map['name']); - - Map asMap() => - {'campaignHash': campaignHash, 'campaignID': campaignID, 'schema': schema, 'slug': slug, 'uuid': uuid, 'items': items, 'name': name}; + name: map['name'], + campaignHash: map['campaignHash'], + campaignID: map['campaignID'], + correlationID: map['correlationID'], + schema: map['schema'], + slug: map['slug'], + uuid: map['uuid'], + items: _convertObjectListToRecoList(map['items']), + ); } +/// This function converts a list of objects to a list of Recommendation objects. List _convertObjectListToRecoList(List list) { List recommendationList = []; for (var recoObject in list) { diff --git a/lib/model/content/screen_view.dart b/lib/model/content/screen_view.dart new file mode 100644 index 0000000..00df6cd --- /dev/null +++ b/lib/model/content/screen_view.dart @@ -0,0 +1,44 @@ +import '../../utils/synerise_utils.dart'; +import 'screen_view_audience_info.dart'; + +/// The ScreenView class represents a screen view with various properties such as identifier, name, +/// hashString, path, priority, audience information, data, createdAt and updatedAt timestamps. +class ScreenView { + final String identifier; + final String name; + final String hashString; + final String path; + final int priority; + + final ScreenViewAudienceInfo? audience; + final Map? data; + + final DateTime createdAt; + final DateTime updatedAt; + + ScreenView._( + {required this.identifier, + required this.name, + required this.hashString, + required this.path, + required this.priority, + this.audience, + this.data, + required this.updatedAt, + required this.createdAt}); + + /// `ScreenView.fromMap(Map map)` is a named constructor that takes a `Map` as an argument and creates + /// a new `ScreenView` object from the data in the map. + ScreenView.fromMap(Map map) + : this._( + name: map['name'], + identifier: map['identifier'], + hashString: map['hashString'], + path: map['path'], + priority: map['priority'], + audience: map['audience'] != null ? ScreenViewAudienceInfo.fromMap(map['audience']) : null, + data: map['data'] != null ? Map.from(map['data']) : null, + updatedAt: SyneriseUtils.formatIntToDateTime(map['updatedAt']), + createdAt: SyneriseUtils.formatIntToDateTime(map['createdAt']), + ); +} diff --git a/lib/model/content/screen_view_audience.dart b/lib/model/content/screen_view_audience.dart index fe0c8c2..a2c5b12 100644 --- a/lib/model/content/screen_view_audience.dart +++ b/lib/model/content/screen_view_audience.dart @@ -1,3 +1,5 @@ +/// The ScreenViewAudience class represents an audience for a screen view with a query and a list of +/// IDs. class ScreenViewAudience { final String? query; final List? ids; @@ -7,12 +9,15 @@ class ScreenViewAudience { this.ids, }); + /// `ScreenViewAudience.fromMap(Map map)` is a constructor that takes a `Map` as input and creates a + /// new instance of `ScreenViewAudience` based on the values in the `Map`. ScreenViewAudience.fromMap(Map map) : this._( query: map['query'], ids: map['IDs'] != null ? List.from(map['IDs']) : null, ); + /// The function returns a map with 'query' and 'IDs' keys and their corresponding values. Map asMap() => { 'query': query, 'IDs': ids, diff --git a/lib/model/content/screen_view_audience_info.dart b/lib/model/content/screen_view_audience_info.dart new file mode 100644 index 0000000..8b251bb --- /dev/null +++ b/lib/model/content/screen_view_audience_info.dart @@ -0,0 +1,17 @@ +/// The ScreenViewAudienceInfo class represents information about the audience of a screen view, +/// including segments, query, and target type. +class ScreenViewAudienceInfo { + final List? segments; + final String? query; + final String? targetType; + + ScreenViewAudienceInfo._({this.segments, this.query, this.targetType}); + + /// `ScreenViewAudienceInfo.fromMap(Map map)` is a constructor that takes a `Map` as input and creates a + /// new instance of `ScreenViewAudienceInfo` based on the values in the `Map`. + ScreenViewAudienceInfo.fromMap(Map map) + : this._( + segments: map['segments'] != null ? List.from(map['segments']) : null, + query: map['query'], + targetType: map['targetType']); +} diff --git a/lib/model/content/screen_view_response.dart b/lib/model/content/screen_view_response.dart index 4cabcf5..db1a7ad 100644 --- a/lib/model/content/screen_view_response.dart +++ b/lib/model/content/screen_view_response.dart @@ -1,16 +1,18 @@ import '../../utils/synerise_utils.dart'; import 'screen_view_audience.dart'; +/// The `ScreenViewResponse` class represents a response object containing information about a screen +/// view, including its audience, identifier, name, path, priority, version, and data. class ScreenViewResponse { final ScreenViewAudience audience; - + final String identifier; final String hashString; final String name; final String path; final int priority; final String? descriptionText; - + final Map data; final String version; @@ -35,6 +37,8 @@ class ScreenViewResponse { this.descriptionText, this.deletedAt}); + /// `ScreenViewResponse.fromMap(Map map)` is a named constructor that takes a `Map` as an argument and + /// creates a new instance of `ScreenViewResponse` using the values from the `Map`. ScreenViewResponse.fromMap(Map map) : this._( audience: ScreenViewAudience.fromMap(map['audience']), @@ -51,6 +55,7 @@ class ScreenViewResponse { descriptionText: map['descriptionText'], deletedAt: map['deletedAt'] != null ? SyneriseUtils.formatIntToDateTime(map['deletedAt']) : null); + /// The function returns a map containing various properties of an object. Map asMap() => { 'audience': audience, 'createdAt': createdAt, diff --git a/lib/model/in_app/in_app_message_data.dart b/lib/model/in_app/in_app_message_data.dart index 8b5dc14..fa66bf3 100644 --- a/lib/model/in_app/in_app_message_data.dart +++ b/lib/model/in_app/in_app_message_data.dart @@ -1,3 +1,5 @@ +/// The InAppMessageData class represents data for an in-app message campaign, including campaign hash, +/// variant identifier, additional parameters, and a flag for testing. class InAppMessageData { String campaignHash; String variantIdentifier; @@ -5,6 +7,8 @@ class InAppMessageData { bool isTest; InAppMessageData(this.campaignHash, this.variantIdentifier, this.additionalParameters, this.isTest); - + + /// This is a constructor named `fromMap` that takes a `Map` as an argument and creates a new instance + /// of the `InAppMessageData` class using the values from the map. InAppMessageData.fromMap(Map map) : this(map['campaignHash'], map['variantIdentifier'], map['additionalParameters'], map['isTest']); -} \ No newline at end of file +} diff --git a/lib/model/promotions/promotion.dart b/lib/model/promotions/promotion.dart index f490887..050cc3f 100644 --- a/lib/model/promotions/promotion.dart +++ b/lib/model/promotions/promotion.dart @@ -1,5 +1,4 @@ -import 'package:synerise_flutter_sdk/model/promotions/promotion_image.dart'; - +import '../../model/promotions/promotion_image.dart'; import '../../enums/promotions/promotion_discount_mode.dart'; import '../../enums/promotions/promotion_discount_type.dart'; import '../../enums/promotions/promotion_item_scope.dart'; @@ -9,6 +8,8 @@ import '../../utils/synerise_utils.dart'; import 'promotion_details.dart'; import 'promotion_discount_mode_details.dart'; +/// The Promotion class represents a promotional offer with various properties such as discount type, +/// redemption limits, and expiration dates. class Promotion { String uuid; String code; @@ -46,7 +47,7 @@ class Promotion { int? lastingTime; String? displayFrom; String? displayTo; - + Map? params; List? catalogIndexItems; List? tags; @@ -89,6 +90,10 @@ class Promotion { this.tags, }); + /// `Promotion.fromMap(Map map)` is a factory constructor that creates a new instance of the + /// `Promotion` class from a `Map` object. It takes a `Map` object as an argument and uses the values + /// from the map to initialize the properties of the `Promotion` object. It returns a new instance of + /// the `Promotion` class with the properties set to the values from the `Map`. Promotion.fromMap(Map map) : this._( uuid: map['uuid'], @@ -129,6 +134,7 @@ class Promotion { tags: map['tags'] != null ? List.from(map['tags']) : null); } +/// This function converts a list of objects to a list of PromotionImage objects. List _convertObjectListToPromotionImageList(List list) { List promotionImageList = []; for (var promotionImageMap in list) { diff --git a/lib/model/promotions/promotion_details.dart b/lib/model/promotions/promotion_details.dart index 909c845..a315a2c 100644 --- a/lib/model/promotions/promotion_details.dart +++ b/lib/model/promotions/promotion_details.dart @@ -1,13 +1,19 @@ import 'promotion_discount_type_details.dart'; +/// The `PromotionDetails` class represents details of a promotion, including the discount type, and +/// provides methods for converting to and from a `Map`. class PromotionDetails { PromotionDiscountTypeDetails? discountType; PromotionDetails({this.discountType}); + /// `PromotionDetails.fromMap(Map map)` is a constructor that takes a `Map` as input and creates a new + /// `PromotionDetails` object from it. PromotionDetails.fromMap(Map map) : discountType = map['discountType'] != null ? PromotionDiscountTypeDetails.fromMap(map['discountType']) : null; + /// The function returns a map with the value of 'discountType' converted to a map using the 'asMap' + /// function. Map asMap() => { 'discountType': discountType?.asMap(), }; diff --git a/lib/model/promotions/promotion_discount_mode_details.dart b/lib/model/promotions/promotion_discount_mode_details.dart index 100c102..3f1c1a3 100644 --- a/lib/model/promotions/promotion_discount_mode_details.dart +++ b/lib/model/promotions/promotion_discount_mode_details.dart @@ -1,6 +1,8 @@ import '../../enums/promotions/promotion_discount_usage_trigger.dart'; import 'promotion_discount_step.dart'; +/// The class `PromotionDiscountModeDetails` contains information about the discount steps and usage +/// trigger for a promotion. class PromotionDiscountModeDetails { List discountSteps; PromotionDiscountUsageTrigger discountUsageTrigger; @@ -10,14 +12,18 @@ class PromotionDiscountModeDetails { required this.discountUsageTrigger, }); + /// `PromotionDiscountModeDetails.fromMap(Map map)` is a constructor that takes a `Map` as an argument + /// and initializes a `PromotionDiscountModeDetails` object with the values from the `Map`. PromotionDiscountModeDetails.fromMap(Map map) : this( discountSteps: _convertObjectListToPromotionDiscountStep(map['discountSteps']), discountUsageTrigger: PromotionDiscountUsageTrigger.getPromotionDiscountUsageTriggerFromString(map['discountUsageTrigger'])); + /// The function returns a map with the values of 'discountSteps' and 'discountUsageTrigger'. Map asMap() => {'discountSteps': discountSteps, 'discountUsageTrigger': discountUsageTrigger}; } +/// This function converts a list of objects to a list of PromotionDiscountStep objects. List _convertObjectListToPromotionDiscountStep(List list) { List promotionDiscountStepList = []; for (var discountSteps in list) { diff --git a/lib/model/promotions/promotion_discount_step.dart b/lib/model/promotions/promotion_discount_step.dart index ada5f7a..58d8e9f 100644 --- a/lib/model/promotions/promotion_discount_step.dart +++ b/lib/model/promotions/promotion_discount_step.dart @@ -1,3 +1,5 @@ +/// The `PromotionDiscountStep` class represents a step in a promotion that includes a discount value +/// and a usage threshold. class PromotionDiscountStep { int discountValue; int usageThreshold; @@ -7,10 +9,13 @@ class PromotionDiscountStep { required this.usageThreshold, }); + /// `PromotionDiscountStep.fromMap(Map map)` is a constructor that takes a `Map` as an argument and + /// initializes a new `PromotionDiscountStep` object with the values from the map. PromotionDiscountStep.fromMap(Map map) : discountValue = map['discountValue'], usageThreshold = map['usageThreshold']; + /// The function returns a map with the values of discountValue and usageThreshold. Map asMap() => { 'discountValue': discountValue, 'usageThreshold': usageThreshold, diff --git a/lib/model/promotions/promotion_discount_type_details.dart b/lib/model/promotions/promotion_discount_type_details.dart index 22aefbc..ddf153a 100644 --- a/lib/model/promotions/promotion_discount_type_details.dart +++ b/lib/model/promotions/promotion_discount_type_details.dart @@ -1,3 +1,5 @@ +/// The `PromotionDiscountTypeDetails` class represents details about a promotion discount type and +/// includes methods for creating an instance from a `Map` and converting it to a `Map`. class PromotionDiscountTypeDetails { String name; bool outerScope; @@ -11,6 +13,8 @@ class PromotionDiscountTypeDetails { required this.discountedItemsCount, }); + /// `PromotionDiscountTypeDetails.fromMap(Map map)` is a constructor that takes a `Map` as an argument + /// and creates a new instance of `PromotionDiscountTypeDetails` using the values from the `Map`. PromotionDiscountTypeDetails.fromMap(Map map) : this( name: map['name'], @@ -19,6 +23,8 @@ class PromotionDiscountTypeDetails { discountedItemsCount: map['discountedItemsCount'], ); + /// The function returns a map containing the values of name, outerScope, requiredItemsCount, and + /// discountedItemsCount. Map asMap() => { 'name': name, 'outerScope': outerScope, diff --git a/lib/model/promotions/promotion_identifier.dart b/lib/model/promotions/promotion_identifier.dart index 279a9cd..98957e6 100644 --- a/lib/model/promotions/promotion_identifier.dart +++ b/lib/model/promotions/promotion_identifier.dart @@ -1,17 +1,22 @@ import '../../enums/promotions/promotion_identifier_key.dart'; +/// The PromotionIdentifier class represents a key-value pair object used to identify a promotion, with methods +/// for converting to and from a map. class PromotionIdentifier { PromotionIdentifierKey key; String value; PromotionIdentifier({required this.key, required this.value}); + /// `PromotionIdentifier.fromMap(Map map)` is a constructor that takes a `Map` as an argument and + /// creates a new `PromotionIdentifier` object from it. PromotionIdentifier.fromMap(Map map) : this( key: PromotionIdentifierKey.getPromotionIdentifierKeyFromString(map['key']), value: map['value'], ); + /// The function returns a map with a key and value based on the promotion identifier key and value. Map asMap() => { 'key': key.promotionIdentifierKeyAsString(), 'value': value, diff --git a/lib/model/promotions/promotion_image.dart b/lib/model/promotions/promotion_image.dart index 79dc1b4..9069ec2 100644 --- a/lib/model/promotions/promotion_image.dart +++ b/lib/model/promotions/promotion_image.dart @@ -1,5 +1,6 @@ import '../../enums/promotions/promotion_image_type.dart'; +/// The PromotionImage class represents an image used for promotions and includes a URL and type. class PromotionImage { String url; PromotionImageType type; @@ -9,10 +10,13 @@ class PromotionImage { required this.type, }); + /// `PromotionImage.fromMap(Map map)` is a constructor that takes a `Map` as an argument and + /// initializes a `PromotionImage` object with the values from the map. PromotionImage.fromMap(Map map) : url = map['url'], type = PromotionImageType.getPromotionImageTypeFromString(map['type']); + /// The function returns a map with the URL and type of a promotion image. Map asMap() => { 'url': url, 'type': type.promotionImageTypeAsString(), diff --git a/lib/model/promotions/promotion_response.dart b/lib/model/promotions/promotion_response.dart index c31fee8..54be059 100644 --- a/lib/model/promotions/promotion_response.dart +++ b/lib/model/promotions/promotion_response.dart @@ -1,5 +1,7 @@ import 'promotion.dart'; +/// The code defines a Dart class for a promotion response and includes a private constructor and a +/// function to convert a list of objects to a list of promotions. class PromotionResponse { final int? totalCount; final int? totalPages; @@ -8,10 +10,10 @@ class PromotionResponse { final int? code; final List items; - PromotionResponse._( - {this.totalCount, this.totalPages, this.page, this.limit, this.code, - required this.items}); + PromotionResponse._({this.totalCount, this.totalPages, this.page, this.limit, this.code, required this.items}); + /// `PromotionResponse.fromMap(Map map)` is a factory constructor that takes in a `Map` object and + /// returns a new instance of the `PromotionResponse` class. PromotionResponse.fromMap(Map map) : this._( totalCount: map['totalCount'], @@ -22,6 +24,7 @@ class PromotionResponse { items: _convertObjectListToPromotion(map['items'])); } +/// This function converts a list of objects to a list of Promotion objects. List _convertObjectListToPromotion(List list) { List promotionList = []; for (var promotionMap in list) { diff --git a/lib/model/promotions/promotions_api_query.dart b/lib/model/promotions/promotions_api_query.dart index 45b87bd..770da00 100644 --- a/lib/model/promotions/promotions_api_query.dart +++ b/lib/model/promotions/promotions_api_query.dart @@ -1,8 +1,9 @@ -import 'package:synerise_flutter_sdk/model/base_api_query.dart'; - +import '../../model/base_api_query.dart'; import '../../enums/promotions/promotion_status.dart'; import '../../enums/promotions/promotion_type.dart'; +/// The `PromotionsApiQuery` class is a subclass of `BaseApiQuery` that allows for filtering promotions +/// by status and type. class PromotionsApiQuery extends BaseApiQuery { List statuses = []; List types = []; @@ -15,6 +16,8 @@ class PromotionsApiQuery extends BaseApiQuery { required super.page, required super.includeMeta}); + /// This is a named constructor in the `PromotionsApiQuery` class that allows creating an instance of + /// the class from a `Map` object. PromotionsApiQuery.fromMap(Map map) : this( statuses: map['statuses'], @@ -24,6 +27,8 @@ class PromotionsApiQuery extends BaseApiQuery { page: map['page'], includeMeta: map['includeMeta']); + /// The function returns a map containing serialized lists of statuses, types, and sorting, as well as + /// limit, page, and includeMeta values. Map asMap() => { 'statuses': _serializeStatusesList(statuses), 'types': _serializeTypesList(types), @@ -34,6 +39,8 @@ class PromotionsApiQuery extends BaseApiQuery { }; } +/// This function serializes a list of PromotionStatus objects into a list of their corresponding string +/// representations. List _serializeStatusesList(List list) { List formattedList = []; for (PromotionStatus promotionStatus in list) { @@ -43,6 +50,8 @@ List _serializeStatusesList(List list) { return formattedList; } +/// This function serializes a list of PromotionType objects into a list of their corresponding string +/// representations. List _serializeTypesList(List list) { List formattedList = []; for (PromotionType promotionType in list) { @@ -52,6 +61,7 @@ List _serializeTypesList(List list) { return formattedList; } +/// This function serializes a list of ApiQuerySorting objects into a list of maps. List> _serializeSortingList(List list) { List> formattedList = >[]; for (ApiQuerySorting apiQuerySorting in list) { diff --git a/lib/model/tracker/custom_event.dart b/lib/model/tracker/custom_event.dart deleted file mode 100644 index 8f63252..0000000 --- a/lib/model/tracker/custom_event.dart +++ /dev/null @@ -1,9 +0,0 @@ -import 'event.dart'; - -class CustomEvent extends Event { - -static const customType = 'custom'; - - CustomEvent(String label, String action, Map parameters): - super(customType, label, action, parameters); -} \ No newline at end of file diff --git a/lib/model/tracker/event.dart b/lib/model/tracker/event.dart deleted file mode 100644 index 006250b..0000000 --- a/lib/model/tracker/event.dart +++ /dev/null @@ -1,11 +0,0 @@ -abstract class Event { - -String type; -String label; -String action; -Map parameters; - -Event(this.type, this.label, this.action, this.parameters); - -Map asMap() => {'type': type, 'label': label, 'action': action, 'params': parameters}; -} \ No newline at end of file diff --git a/lib/model/tracker/unit_price.dart b/lib/model/tracker/unit_price.dart new file mode 100644 index 0000000..79b8de0 --- /dev/null +++ b/lib/model/tracker/unit_price.dart @@ -0,0 +1,10 @@ +/// The `UnitPrice` class represents a unit price with an amount and currency, and has a method to +/// convert it to a map. +class UnitPrice { + int amount; + String currency; + + UnitPrice(this.amount, this.currency); + + Map asMap() => {'amount': amount, 'currency': currency}; +} diff --git a/lib/model/vouchers/assign_voucher_data.dart b/lib/model/vouchers/assign_voucher_data.dart index 6c45448..15870c4 100644 --- a/lib/model/vouchers/assign_voucher_data.dart +++ b/lib/model/vouchers/assign_voucher_data.dart @@ -1,5 +1,7 @@ import '../../utils/synerise_utils.dart'; +/// The AssignVoucherData class represents data related to a voucher, including its code, expiration +/// date, redemption date, and creation/update timestamps. class AssignVoucherData { String code; DateTime? expireIn; @@ -17,6 +19,9 @@ class AssignVoucherData { required this.updatedAt, }); + /// `AssignVoucherData.fromMap(Map map)` is a named constructor that creates an instance of the + /// `AssignVoucherData` class from a `Map` object. It takes a `Map` object as an argument and uses its + /// values to initialize the properties of the `AssignVoucherData` object. AssignVoucherData.fromMap(Map map) : this( code: map['code'], @@ -26,6 +31,7 @@ class AssignVoucherData { createdAt: SyneriseUtils.formatIntToDateTime(map['createdAt']! * 1000), updatedAt: SyneriseUtils.formatIntToDateTime(map['updatedAt']! * 1000)); + /// This function returns a map containing various properties of an object, including timestamps. Map asMap() => { 'code': code, 'expireIn': expireIn?.millisecondsSinceEpoch, diff --git a/lib/model/vouchers/assign_voucher_response.dart b/lib/model/vouchers/assign_voucher_response.dart index aca1608..d65ef4e 100644 --- a/lib/model/vouchers/assign_voucher_response.dart +++ b/lib/model/vouchers/assign_voucher_response.dart @@ -1,5 +1,7 @@ import 'assign_voucher_data.dart'; +/// The AssignVoucherResponse class represents a response object with a message and optional data, which +/// can be initialized from a map. class AssignVoucherResponse { final String message; final AssignVoucherData? data; @@ -9,5 +11,13 @@ class AssignVoucherResponse { this.data, }); + /// `AssignVoucherResponse.fromMap(Map map) : this(message: map['message'], data: + /// AssignVoucherData.fromMap(map['data']));` is a constructor that takes a map as input and + /// initializes an `AssignVoucherResponse` object with the values extracted from the map. It uses the + /// `message` key from the map to initialize the `message` field of the `AssignVoucherResponse` + /// object, and it uses the `data` key from the map to initialize the `data` field of the + /// `AssignVoucherResponse` object by calling the `AssignVoucherData.fromMap` constructor with the + /// value associated with the `data` key. The `fromMap` constructor is a common pattern in Dart for + /// initializing objects from maps, which is often used when parsing JSON data. AssignVoucherResponse.fromMap(Map map) : this(message: map['message'], data: AssignVoucherData.fromMap(map['data'])); } diff --git a/lib/model/vouchers/voucher_codes_data.dart b/lib/model/vouchers/voucher_codes_data.dart index 64c6099..d0b5adf 100644 --- a/lib/model/vouchers/voucher_codes_data.dart +++ b/lib/model/vouchers/voucher_codes_data.dart @@ -1,6 +1,8 @@ import '../../enums/vouchers/voucher_code_status.dart'; import '../../utils/synerise_utils.dart'; +/// The `VoucherCodesData` class represents voucher codes data and includes a constructor that takes a +/// `Map` as an argument to create a new instance of the class. class VoucherCodesData { String code; VoucherCodeStatus status; @@ -26,6 +28,13 @@ class VoucherCodesData { required this.updatedAt, }); + /// `VoucherCodesData.fromMap(Map map)` is a constructor that takes a `Map` as an argument and creates + /// a new instance of `VoucherCodesData` using the values from the `Map`. The `this()` syntax is used + /// to call the main constructor of `VoucherCodesData` and pass in the values extracted from the + /// `Map`. The values are extracted from the `Map` using the keys `code`, `status`, `clientId`, + /// `clientUuid`, `poolUuid`, `expireIn`, `redeemAt`, `assignedAt`, `createdAt`, and `updatedAt`. Some + /// of these values are formatted using the `SyneriseUtils.formatIntToDateTime()` method before being + /// passed to the constructor. VoucherCodesData.fromMap(Map map) : this( code: map['code'], diff --git a/lib/model/vouchers/voucher_codes_response.dart b/lib/model/vouchers/voucher_codes_response.dart index 9cee51b..eaa9392 100644 --- a/lib/model/vouchers/voucher_codes_response.dart +++ b/lib/model/vouchers/voucher_codes_response.dart @@ -1,16 +1,45 @@ import 'voucher_codes_data.dart'; +/// The above code defines a Dart class and a private function to convert a list of data objects to a +/// list of voucher codes data objects. +/// +/// Args: +/// list (List): The list parameter is a List of Object type, which is being passed as an +/// argument to the _convertDataListToVoucherCodesData function. This list is expected to contain maps +/// that represent voucher codes data. The function iterates over each map in the list, converts it to a +/// Voucher +/// +/// Returns: +/// The code is defining a class `VoucherCodesResponse` with a constructor that takes a required list +/// of `VoucherCodesData` objects. It also defines a named constructor `fromMap` that takes a `Map` +/// object and returns a `VoucherCodesResponse` object with the `data` field populated by calling +/// `_convertDataListToVoucherCodesData` function on the `data class VoucherCodesResponse { final List data; VoucherCodesResponse({required this.data}); + /// `VoucherCodesResponse.fromMap(Map map)` is a named constructor that takes a `Map` object as an + /// argument. It then creates a new instance of the `VoucherCodesResponse` class by calling the + /// default constructor `this(data: ...)`, passing in a list of `VoucherCodesData` objects. The list + /// is obtained by calling the private `_convertDataListToVoucherCodesData` function on the `data` + /// field of the input `Map` object. This named constructor is used to create a `VoucherCodesResponse` + /// object from a `Map` object, which is a common format for data exchange in many programming + /// languages. VoucherCodesResponse.fromMap(Map map) : this( data: _convertDataListToVoucherCodesData(map['data']), ); } +/// This function converts a list of objects to a list of VoucherCodesData objects. +/// +/// Args: +/// list (List): The parameter `list` is a list of objects that needs to be converted to a +/// list of `VoucherCodesData` objects. +/// +/// Returns: +/// a list of `VoucherCodesData` objects. List _convertDataListToVoucherCodesData(List list) { List voucherCodesDataList = []; for (var voucherCodesDataMap in list) { diff --git a/lib/modules/base/base_module.dart b/lib/modules/base/base_module.dart index 49309b5..14bce5a 100644 --- a/lib/modules/base/base_module.dart +++ b/lib/modules/base/base_module.dart @@ -1,3 +1,5 @@ +/// The class "BaseModule" has methods for initialization and a boolean variable to track if it has been +/// initialized. class BaseModule { bool isInitialized = false; diff --git a/lib/modules/base/base_module_method_channel.dart b/lib/modules/base/base_module_method_channel.dart index b0450da..0a5b93e 100644 --- a/lib/modules/base/base_module_method_channel.dart +++ b/lib/modules/base/base_module_method_channel.dart @@ -1,5 +1,7 @@ import '../../main/dependencies.dart'; +/// The class `BaseMethodChannel` contains instances of method channels for regular and background +/// communication in Dart. class BaseMethodChannel { final methodChannel = Dependencies.methodChannel; final backgroundMethodChannel = Dependencies.backgroundMethodChannel; diff --git a/lib/modules/client/client_impl.dart b/lib/modules/client/client_impl.dart index eafc3af..a1e767d 100644 --- a/lib/modules/client/client_impl.dart +++ b/lib/modules/client/client_impl.dart @@ -11,74 +11,148 @@ class ClientImpl extends BaseModule { final ClientMethods _methods = ClientMethods(); ClientImpl(); + /// This function registers a client account asynchronously using the provided context. + /// + /// Args: + /// clientAccountRegisterContext (ClientAccountRegisterContext): It is an object of type + /// ClientAccountRegisterContext that contains the necessary information to register a client account. Future registerAccount(ClientAccountRegisterContext clientAccountRegisterContext) async { return _methods.registerAccount(clientAccountRegisterContext); } + /// This function confirms a user's account using a token. + /// + /// Args: + /// token (String): The "token" parameter is a string that represents a unique identifier for a user + /// account confirmation. Future confirmAccount(String token) async { return _methods.confirmAccount(token); } + /// This function activates a user account using their email address. + /// + /// Args: + /// email (String): The email parameter is a string that represents the email address of the user + /// whose account needs to be activated. Future activateAccount(String email) async { return _methods.activateAccount(email); } + /// This function takes an email and password as parameters and signs in the + /// user using those credentials. + /// + /// Args: + /// email (String): A string representing the email address of the user trying to sign in. + /// password (String): The password parameter is a string that represents the user's password. Future signIn(String email, String password) async { return _methods.signIn(email, password); } + /// This function authenticates a client using an identity provider, clientAuthContext and a token string. + /// + /// Args: + /// clientAuthContext (ClientAuthContext): An object that contains information about the client's + /// authentication context. + /// identityProvider (IdentityProvider): The `identityProvider` parameter is an object that + /// represents the identity provider used for authentication. + /// tokenString (String): The `tokenString` parameter is a string that represents an authentication + /// token. Future authenticate(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString) async { return _methods.authenticate(clientAuthContext, identityProvider, tokenString); } + /// This function returns a boolean value indicating whether the user is signed in or not. Future isSignedIn() async { return _methods.isSignedIn(); } + /// This function signs the user out of the current session. Future signOut() async { return _methods.signOut(); } + /// This function destroys a session asynchronously. Future destroySession() async { return _methods.destroySession(); } + /// This function retrieves a token. Future retrieveToken() async { return _methods.retrieveToken(); } + /// This function refreshes user token. Future refreshToken() async { return _methods.refreshToken(); } + /// This function returns a user's UUID string. Future getUUID() async { return _methods.getUUID(); } + /// This function regenerates a UUID. Future regenerateUUID() async { return _methods.regenerateUUID(); } + /// This function returns a Future object containing the client account information. Future getAccount() async { return _methods.getAccount(); } + /// This function updates a client account using the provided context. + /// + /// Args: + /// clientAccountUpdateContext (ClientAccountUpdateContext): It is an object of type + /// ClientAccountUpdateContext that contains the information needed to update a client's account. This + /// object may include fields such as the client's name, email, phone number, address, and any other + /// relevant information that needs to be updated. Future updateAccount(ClientAccountUpdateContext clientAccountUpdateContext) async { return _methods.updateAccount(clientAccountUpdateContext); } + /// This function requests a password reset for a given email address. + /// + /// Args: + /// email (String): The email parameter is a string that represents the email address of the user + /// who wants to reset their password. Future requestPasswordReset(String email) async { return _methods.requestPasswordReset(email); } + /// This function confirms a password reset using a token and a new password. + /// + /// Args: + /// token (String): The token is a unique string that is generated when a user requests to reset their + /// password. This token is used to verify the user's identity when they reset their password. + /// password (String): The password parameter is a string that represents the new password that the + /// user wants to set for their account after resetting their password. Future confirmPasswordReset(String token, String password) async { return _methods.confirmPasswordReset(token, password); } + /// This function changes the user's password by calling a private method with the old and new + /// passwords as parameters. + /// + /// Args: + /// oldPassword (String): The old password is a string parameter that represents the user's current + /// password. It is used to verify the user's identity before allowing them to change their password. + /// password (String): The new password that the user wants to set. Future changePassword(String oldPassword, String password) async { return _methods.changePassword(oldPassword, password); } + /// This function deletes an account using client authentication factor, identity provider, and + /// optional authentication ID. + /// + /// Args: + /// clientAuthFactor (String): It is a string parameter that represents the authentication factor of + /// the client. + /// identityProvider (IdentityProvider): The `identityProvider` parameter is an object of type + /// `IdentityProvider` which represents the identity provider used for authentication. + /// authId (String): The authId parameter is an optional string that represents the unique + /// identifier of the authenticated user whose account is to be deleted. Future deleteAccount(String clientAuthFactor, IdentityProvider identityProvider, String? authId) async { return _methods.deleteAccount(clientAuthFactor, identityProvider, authId); } diff --git a/lib/modules/client/client_methods.dart b/lib/modules/client/client_methods.dart index 3e2dd81..db020dd 100644 --- a/lib/modules/client/client_methods.dart +++ b/lib/modules/client/client_methods.dart @@ -1,5 +1,3 @@ - - import '../../enums/client/identity_provider.dart'; import '../../model/client/client_account_information.dart'; import '../../model/client/client_account_register_context.dart'; diff --git a/lib/modules/content/content_impl.dart b/lib/modules/content/content_impl.dart index edf811d..da344fe 100644 --- a/lib/modules/content/content_impl.dart +++ b/lib/modules/content/content_impl.dart @@ -1,6 +1,8 @@ +import '../../model/content/document.dart'; import '../../model/content/documents_api_query.dart'; import '../../model/content/recommendation_options.dart'; import '../../model/content/recommendation_response.dart'; +import '../../model/content/screen_view.dart'; import '../../model/content/screen_view_response.dart'; import '../base/base_module.dart'; import 'content_methods.dart'; @@ -9,19 +11,63 @@ class ContentImpl extends BaseModule { final ContentMethods _methods = ContentMethods(); ContentImpl(); + /// (DEPRECATED) Please use generateDocument instead. + /// This method generates the document that is defined for the provided slug. + /// + /// Args: + /// slugName (String): The parameter `slugName` is a string that represents the + /// name of a document slug that is being requested. + @Deprecated('Deprecated in version 0.6.0') Future> getDocument(String slugName) async { return _methods.getDocument(slugName); } + /// This function generates a document based on a given slug. + /// + /// Args: + /// slug (String): The parameter "slug" represents a unique identifier + /// for a specific document. + Future generateDocument(String slug) async { + return _methods.generateDocument(slug); + } + + /// (DEPRECATED) Please use generateDocument instead. + /// This method generates documents that are defined for parameters provided in the query object. + /// + /// Args: + /// documentsApiQueryModel (DocumentsApiQuery): An object for configuration of the query parameters + @Deprecated('Deprecated in version 0.6.0') Future>> getDocuments(DocumentsApiQuery documentsApiQueryModel) async { return _methods.getDocuments(documentsApiQueryModel); } + /// (DEPRECATED) Please use getRecommendationsV2 instead. + /// This method generates recommendations that are defined for the options provided. + /// + /// Args: + /// recommendationOptions (RecommendationOptions): Object for configuration of the options parameters. + @Deprecated('Deprecated in version 0.6.0') Future getRecommendations(RecommendationOptions recommendationOptions) async { return _methods.getRecommendations(recommendationOptions); } + /// This method generates recommendations that are defined for the options provided. + /// + /// Args: + /// recommendationOptions (RecommendationOptions): Object for configuration of the options parameters. + Future getRecommendationsV2(RecommendationOptions recommendationOptions) async { + return _methods.getRecommendationsV2(recommendationOptions); + } + + /// (DEPRECATED) Please use generateScreenView instead. + /// This method generates the customer’s highest-priority screen view campaign. + @Deprecated('Deprecated in version 0.6.0') Future getScreenView() async { return _methods.getScreenView(); } + + /// This function generates a screen view for a given feed slug. + Future generateScreenView(String feedSlug) async { + return _methods.generateScreenView(feedSlug); + } } diff --git a/lib/modules/content/content_methods.dart b/lib/modules/content/content_methods.dart index a72ba16..5a37ee5 100644 --- a/lib/modules/content/content_methods.dart +++ b/lib/modules/content/content_methods.dart @@ -1,16 +1,24 @@ +import '../../model/content/document.dart'; import '../../model/content/documents_api_query.dart'; import '../../model/content/recommendation_options.dart'; import '../../model/content/recommendation_response.dart'; +import '../../model/content/screen_view.dart'; import '../../model/content/screen_view_response.dart'; import '../base/base_module_method_channel.dart'; class ContentMethods extends BaseMethodChannel { Future> getDocument(String slugName) async { - var documentRsponse = await methodChannel.invokeMethod("Content/getDocument", slugName); - Map documentMap = Map.from(documentRsponse); + var documentResponseMap = await methodChannel.invokeMethod("Content/getDocument", slugName); + Map documentMap = Map.from(documentResponseMap); return documentMap; } + Future generateDocument(String slug) async { + var documentResponseMap = await methodChannel.invokeMethod("Content/generateDocument", slug); + Document document = Document.fromMap(documentResponseMap); + return document; + } + Future>> getDocuments(DocumentsApiQuery documentsApiQueryModel) async { var documentsResponse = await methodChannel.invokeMethod("Content/getDocuments", documentsApiQueryModel.asMap()); List> documentsRawList = List>.from(documentsResponse); @@ -23,14 +31,26 @@ class ContentMethods extends BaseMethodChannel { } Future getRecommendations(RecommendationOptions recommendationOptions) async { - var recommendationsResponse = await methodChannel.invokeMethod("Content/getRecommendations", recommendationOptions.asMap()); - RecommendationResponse recommendationsMap = RecommendationResponse.fromMap(recommendationsResponse); - return recommendationsMap; + var recommendationsResponseMap = await methodChannel.invokeMethod("Content/getRecommendations", recommendationOptions.asMap()); + RecommendationResponse recommendationResponse = RecommendationResponse.fromMap(recommendationsResponseMap); + return recommendationResponse; + } + + Future getRecommendationsV2(RecommendationOptions recommendationOptions) async { + var recommendationResponseMap = await methodChannel.invokeMethod("Content/getRecommendationsV2", recommendationOptions.asMap()); + RecommendationResponse recommendationResponse = RecommendationResponse.fromMap(recommendationResponseMap); + return recommendationResponse; } Future getScreenView() async { - var screenViewResponse = await methodChannel.invokeMethod("Content/getScreenView"); - ScreenViewResponse screenViewMap = ScreenViewResponse.fromMap(screenViewResponse); - return screenViewMap; + var screenViewResponseMap = await methodChannel.invokeMethod("Content/getScreenView"); + ScreenViewResponse screenViewResponse = ScreenViewResponse.fromMap(screenViewResponseMap); + return screenViewResponse; + } + + Future generateScreenView(String feedSlug) async { + var screenViewMap = await methodChannel.invokeMethod("Content/generateScreenView", feedSlug); + ScreenView screenViewResponse = ScreenView.fromMap(screenViewMap); + return screenViewResponse; } } diff --git a/lib/modules/injector/injector_impl.dart b/lib/modules/injector/injector_impl.dart index 05c0177..49dd823 100644 --- a/lib/modules/injector/injector_impl.dart +++ b/lib/modules/injector/injector_impl.dart @@ -57,26 +57,32 @@ class InjectorImpl extends BaseModule { final InjectorWalkthroughListener _walkthroughListener = InjectorWalkthroughListener(); final InjectorInAppMessageListener _inAppMessageListener = InjectorInAppMessageListener(); + /// This function handles method calls for listeners related to opening URLs and deep links. void listener(InjectorListenerFunction listenerFunction) { listenerFunction(_listener); } + /// This function handles banner listener methods by calling the appropriate listener method based on + /// the method name. void bannerListener(InjectorBannerListenerFunction listenerFunction) { listenerFunction(_bannerListener); } + /// This function handles different listener methods for a walkthrough feature in a Dart application. void walkthroughListener(InjectorWalkthroughListenerFunction listenerFunction) { listenerFunction(_walkthroughListener); } - + + /// This function handles different listener methods for in-app messages in Dart. void inAppMessageListener(InjectorInAppMessageListenerFunction listenerFunction) { listenerFunction(_inAppMessageListener); } + /// This function handles different types of listeners based on the method call received. void handleMethod(MethodCall call) async { var methodPath = call.method.split('#'); var listenerName = methodPath[1]; - + if (listenerName == 'InjectorListener') { _handleListenerMethod(call); return; @@ -132,7 +138,7 @@ class InjectorImpl extends BaseModule { var methodPath = call.method.split('#'); var listenerName = methodPath[1]; var listenerMethodName = methodPath[2]; - + if (listenerMethodName == 'onPresent') { if (_bannerListener.onPresent != null) { _bannerListener.onPresent!(); @@ -200,7 +206,7 @@ class InjectorImpl extends BaseModule { String campaignHash = inAppMessageDataArguments['campaignHash']; String variantIdentifier = inAppMessageDataArguments['variantIdentifier']; Map additionalParamaters = Map.from(inAppMessageDataArguments['additionalParameters']); - bool isTest = inAppMessageDataArguments['isTest']; + bool isTest = inAppMessageDataArguments['isTest']; InAppMessageData data = InAppMessageData(campaignHash, variantIdentifier, additionalParamaters, isTest); if (listenerMethodName == 'onPresent') { @@ -258,4 +264,4 @@ class InjectorImpl extends BaseModule { Future isLoadedWalkthroughUnique() async { return _methods.isLoadedWalkthroughUnique(); } -} \ No newline at end of file +} diff --git a/lib/modules/notifications/notifications_impl.dart b/lib/modules/notifications/notifications_impl.dart index 6580836..380e790 100644 --- a/lib/modules/notifications/notifications_impl.dart +++ b/lib/modules/notifications/notifications_impl.dart @@ -17,15 +17,19 @@ class NotificationsImpl extends BaseModule { final NotificationsListener _listener = NotificationsListener(); + /// This function takes a listener function as a parameter and calls it with a private listener + /// function. void listener(NotificationsListenerFunction listenerFunction) { listenerFunction(_listener); } + /// This function handles a specific method call and invokes a listener method if it matches certain + /// criteria. void handleMethod(MethodCall call) { var methodPath = call.method.split('#'); var listenerName = methodPath[1]; var listenerMethodName = methodPath[2]; - + if (listenerName == 'NotificationsListener' && listenerMethodName == 'onRegistrationRequired') { if (_listener.onRegistrationRequired != null) { _listener.onRegistrationRequired!(); @@ -33,14 +37,35 @@ class NotificationsImpl extends BaseModule { } } + /// This function registers a device for notifications with a given registration token and mobile + /// agreement. + /// + /// Args: + /// registrationToken (String): The registration token is a unique identifier that is generated by + /// the device when a user installs an app that uses Firebase Cloud Messaging (FCM) for push + /// notifications. This token is used to identify the device and send push notifications to it. + /// mobileAgreement (bool): mobileAgreement is a boolean parameter that indicates whether the user + /// has agreed to receive notifications on their mobile device. void registerForNotifications(String registrationToken, bool mobileAgreement) { _methods.registerForNotifications(registrationToken, mobileAgreement); } + /// This function handles a notification and returns a boolean value indicating whether the + /// notification was successfully handled. + /// + /// Args: + /// notification (Map): The parameter "notification" is a Map object that contains data related to a + /// notification. It could include information such as the title and body of the notification, the + /// sender of the notification, and any additional data that was included with the notification. Future handleNotification(Map notification) async { return _methods.handleNotification(notification); } + /// This function handles a notification click and returns a boolean value. + /// + /// Args: + /// notification (Map): The parameter "notification" is a Map object that contains the data of a + /// notification that was received by the app. Future handleNotificationClick(Map notification) async { return _methods.handleNotificationClick(notification); } diff --git a/lib/modules/notifications/notifications_methods.dart b/lib/modules/notifications/notifications_methods.dart index 474191a..2796f04 100644 --- a/lib/modules/notifications/notifications_methods.dart +++ b/lib/modules/notifications/notifications_methods.dart @@ -2,21 +2,15 @@ import '../base/base_module_method_channel.dart'; class NotificationsMethods extends BaseMethodChannel { void registerForNotifications(String registrationToken, bool mobileAgreement) { - methodChannel.invokeMethod('Notifications/registerForNotifications', { - "registrationToken": registrationToken, - "mobileAgreement": mobileAgreement - }); + methodChannel.invokeMethod( + 'Notifications/registerForNotifications', {"registrationToken": registrationToken, "mobileAgreement": mobileAgreement}); } Future handleNotification(Map notification) async { - return await backgroundMethodChannel.invokeMethod('Notifications/handleNotification', { - 'notification': notification - }); + return await backgroundMethodChannel.invokeMethod('Notifications/handleNotification', {'notification': notification}); } Future handleNotificationClick(Map notification) async { - return await backgroundMethodChannel.invokeMethod('Notifications/handleNotificationClick', { - 'notification': notification - }); + return await backgroundMethodChannel.invokeMethod('Notifications/handleNotificationClick', {'notification': notification}); } -} \ No newline at end of file +} diff --git a/lib/modules/promotions/promotions_impl.dart b/lib/modules/promotions/promotions_impl.dart index 5a7fe51..4cfcfd4 100644 --- a/lib/modules/promotions/promotions_impl.dart +++ b/lib/modules/promotions/promotions_impl.dart @@ -11,54 +11,117 @@ class PromotionsImpl extends BaseModule { final PromotionsMethods _methods = PromotionsMethods(); PromotionsImpl(); + /// This method retrieves all available promotions that are defined for a customer. Future getAllPromotions() async { return _methods.getAllPromotions(); } + /// This method retrieves promotions that match the parameters defined in an API query. + /// + /// Args: + /// promotionsApiQuery (PromotionsApiQuery): It is an object of type PromotionsApiQuery which + /// contains the query parameters for the promotions API. Future getPromotions(PromotionsApiQuery promotionsApiQuery) async { return _methods.getPromotions(promotionsApiQuery); } + /// This function retrieves a Promotion object by its UUID. + /// + /// Args: + /// uuid (String): The "uuid" parameter is a string that represents a unique identifier for a + /// promotion. Future getPromotionByUUID(String uuid) async { return _methods.getPromotionByUUID(uuid); } + /// This function returns a promotion object by its code. + /// + /// Args: + /// code (String): The parameter "code" is a string that represents the code of a promotion. Future getPromotionByCode(String code) async { return _methods.getPromotionByCode(code); } + /// This function activates a promotion by its UUID. + /// + /// Args: + /// uuid (String): The "uuid" parameter is a String that represents a unique identifier for a + /// promotion. Future activatePromotionByUUID(String uuid) async { return _methods.activatePromotionByUUID(uuid); } + /// This function activates a promotion by a given code. + /// + /// Args: + /// code (String): The parameter "code" is a String that represents the promotion code that needs to + /// be activated. Future activatePromotionByCode(String code) async { return _methods.activatePromotionByCode(code); } + /// This function deactivates a promotion by its UUID. + /// + /// Args: + /// uuid (String): The "uuid" parameter is a String that represents the unique identifier of a + /// promotion that needs to be deactivated. Future deactivatePromotionByUUID(String uuid) async { return _methods.deactivatePromotionByUUID(uuid); } + /// This function deactivates a promotion by its code. + /// + /// Args: + /// code (String): The "code" parameter is a string that represents the code of the promotion that + /// needs to be deactivated. Future deactivatePromotionByCode(String code) async { return _methods.deactivatePromotionByCode(code); } + /// This method activates promotions with a code or with UUID in a batch. + /// + /// Args: + /// promotionsToActivate (List): A list of PromotionIdentifier objects + /// representing the promotions that need to be activated. Future activatePromotionsBatch(List promotionsToActivate) async { return _methods.activatePromotionsBatch(promotionsToActivate); } + /// This method deactivates promotions with a code or with UUID in a batch. + /// + /// Args: + /// promotionsToDeactivate (List): promotionsToDeactivate is a List of + /// PromotionIdentifier objects that contains the promotions that need to be deactivated. The method + /// deactivatePromotionsBatch() takes this list as a parameter and deactivates all the promotions in + /// the list. Future deactivatePromotionsBatch(List promotionsToDeactivate) async { return _methods.deactivatePromotionsBatch(promotionsToDeactivate); } + /// This method retrieves an assigned voucher code or assigns a voucher from a pool identified + /// by UUID to the customer. + /// + /// Once a voucher is assigned using this method, the same voucher is returned for the customer + /// every time the method is called. + /// + /// Args: + /// poolUuid (String): The `poolUuid` parameter is a unique identifier for a voucher pool. It is + /// used to retrieve or assign a voucher from/to the specified pool. Future getOrAssignVoucher(String poolUuid) async { return _methods.getOrAssignVoucher(poolUuid); } + /// This method assigns a voucher from a pool identified by UUID to the customer. Every request + /// returns a different code until the pool is empty. + /// + /// Args: + /// poolUuid (String): The parameter `poolUuid` is a unique identifier for a voucher pool. It is + /// used to assign a voucher code from the specified pool to a user. Future assignVoucherCode(String poolUuid) async { return _methods.assignVoucherCode(poolUuid); } + /// This method retrieves voucher codes for a customer. Future getAssignedVoucherCodes() async { return _methods.getAssignedVoucherCodes(); } diff --git a/lib/modules/promotions/promotions_methods.dart b/lib/modules/promotions/promotions_methods.dart index afd8fea..da7b579 100644 --- a/lib/modules/promotions/promotions_methods.dart +++ b/lib/modules/promotions/promotions_methods.dart @@ -1,5 +1,4 @@ -import 'package:synerise_flutter_sdk/model/vouchers/voucher_codes_response.dart'; - +import '../../model/vouchers/voucher_codes_response.dart'; import '../../model/promotions/promotion.dart'; import '../../model/promotions/promotion_identifier.dart'; import '../../model/promotions/promotion_response.dart'; diff --git a/lib/modules/settings/settings_impl.dart b/lib/modules/settings/settings_impl.dart index 0140852..a1230ee 100644 --- a/lib/modules/settings/settings_impl.dart +++ b/lib/modules/settings/settings_impl.dart @@ -128,9 +128,30 @@ class SettingsImpl extends BaseModule { await _refreshAllSettings(); } + /// This function retrieves a function based on a given key and platform, with optional default + /// values. + /// + /// Args: + /// key (String): A string representing the key of the setting to be retrieved. + /// isSupportedPlatform: A boolean value indicating whether the current platform is supported. If it + /// is set to false, the function will return the default value for the platform (androidDefault for + /// Android, iosDefault for iOS). If it is set to null or true, the function will proceed to retrieve + /// the value for the given key + /// androidDefault (dynamic): The default value to be returned if the platform is Android and the + /// requested key is not found in the settings. + /// iosDefault (dynamic): The default value to be returned if the platform is iOS and the requested + /// key is not found in the settings. + /// + /// Returns: + /// either the value associated with the given key in the settings map, or null if the key is not + /// found. If the function is called before initialization or on an unsupported platform, it throws a + /// PlatformException. If the function is called on a supported platform but the key is not found in + /// the settings map, it returns the default value provided for that platform (androidDefault for + /// Android, ios dynamic _getFunction(String key, [isSupportedPlatform, dynamic androidDefault, dynamic iosDefault]) { if (isInitialized == false) { - throw PlatformException(message: 'Synerise is not initialized. Access to reading settings is possible when Synerise is initialized.', code: '-1'); + throw PlatformException( + message: 'Synerise is not initialized. Access to reading settings is possible when Synerise is initialized.', code: '-1'); } if (isSupportedPlatform != null && isSupportedPlatform == false) { @@ -148,6 +169,18 @@ class SettingsImpl extends BaseModule { return _getOne(key); } + /// This function sets a value for a given key, but only if the platform is supported. + /// + /// Args: + /// key (String): A string representing the key of the function to be set or overridden. + /// value (dynamic): The value to be set for the given key. + /// isSupportedPlatform: isSupportedPlatform is an optional boolean parameter that determines + /// whether the platform is supported or not. + /// + /// Returns: + /// If the `isSupportedPlatform` parameter is not provided or is `true`, then nothing is being + /// returned. If `isSupportedPlatform` is `false`, then the function returns without executing the + /// rest of the code. void _setFunction(String key, dynamic value, [isSupportedPlatform]) { if (isSupportedPlatform != null && isSupportedPlatform == false) { return; @@ -157,6 +190,7 @@ class SettingsImpl extends BaseModule { _setOne(key, value); } + /// This function refreshes all settings by overriding them with values obtained from a method call. Future _refreshAllSettings() async { return _methods.getAllSettings().then((settings) { _overrideOne(SettingsKeys.sdkEnabled, settings[SettingsKeys.sdkEnabled]); @@ -187,6 +221,17 @@ class SettingsImpl extends BaseModule { await _methods.setOne(key, value); } + /// This function retrieves a value from a settings map and returns it if it matches the specified + /// type, otherwise it returns null. + /// + /// Args: + /// key (String): The key is a string parameter that represents the key of the value to be retrieved + /// from the settingsValues map. + /// + /// Returns: + /// either the value associated with the given key in the `settingsValues` map, or `null` if the key + /// is not found or the value is not of type `T`. The return type of the function is `dynamic`, which + /// means it can return any type of value. dynamic _getOne(String key) { dynamic value = settingsValues[key]; @@ -201,6 +246,12 @@ class SettingsImpl extends BaseModule { return value; } + /// This function overrides a value in a settings map if the new value is not null and is of the same + /// type as the original value. + /// + /// Args: + /// key (String): A string representing the key of the setting value to be overridden or removed. + /// value (dynamic): The value that needs to be stored or removed in the settingsValues map. void _overrideOne(String key, dynamic value) { if (value == null) { settingsValues.remove(key); diff --git a/lib/modules/settings/settings_methods.dart b/lib/modules/settings/settings_methods.dart index d29ab06..c4254d6 100644 --- a/lib/modules/settings/settings_methods.dart +++ b/lib/modules/settings/settings_methods.dart @@ -1,7 +1,6 @@ import '../base/base_module_method_channel.dart'; class SettingsMethods extends BaseMethodChannel { - Future> getAllSettings() async { final result = await methodChannel.invokeMethod("Settings/getAllSettings"); Map data = Map.from(result); @@ -9,13 +8,10 @@ class SettingsMethods extends BaseMethodChannel { } Future setOne(String key, dynamic value) async { - await methodChannel.invokeMethod("Settings/setOne", { - 'key': key, - 'value': value - }); + await methodChannel.invokeMethod("Settings/setOne", {'key': key, 'value': value}); } Future setMany(Map settings) async { await methodChannel.invokeMethod("Settings/setMany", settings); } -} \ No newline at end of file +} diff --git a/lib/modules/synerise_dart_method_channel.dart b/lib/modules/synerise_dart_method_channel.dart index cb16427..a2f3abf 100644 --- a/lib/modules/synerise_dart_method_channel.dart +++ b/lib/modules/synerise_dart_method_channel.dart @@ -2,17 +2,30 @@ import 'package:flutter/services.dart'; import '../synerise.dart'; class SyneriseDartMethodChannel { - static const channelName = "synerise_dart_channel"; // this channel name needs to match the one in Native method channel + ///This variable is used to identify the method channel that is being set up and configured in the + /// `configureChannel()` function. The same value is also used in the platform-specific code to + /// establish communication with the Flutter app through this method channel. + /// + /// This channel name needs to match the one in Native method channel. + static const channelName = "synerise_dart_channel"; late MethodChannel methodChannel; static final SyneriseDartMethodChannel instance = SyneriseDartMethodChannel._init(); SyneriseDartMethodChannel._init(); + /// This function configures a method channel and sets a method call handler. void configureChannel() { methodChannel = const MethodChannel(channelName); methodChannel.setMethodCallHandler(methodHandler); } + /// This function handles method calls for different modules based on the method name. + /// + /// Args: + /// call (MethodCall): The parameter `call` is of type `MethodCall`, which is a class from the + /// Flutter framework's `flutter/services.dart` library. It represents a method call from a + /// platform-specific code to the Flutter app. It contains information such as the method name, + /// arguments, and argument types. Future methodHandler(MethodCall call) async { var modulePath = call.method.split('#'); // ignore: unnecessary_type_check diff --git a/lib/modules/tracker/tracker_impl.dart b/lib/modules/tracker/tracker_impl.dart index 44130b0..02e57fd 100644 --- a/lib/modules/tracker/tracker_impl.dart +++ b/lib/modules/tracker/tracker_impl.dart @@ -1,4 +1,4 @@ -import '../../model/tracker/event.dart'; +import '../../events/event.dart'; import '../base/base_module.dart'; import 'tracker_methods.dart'; @@ -6,19 +6,36 @@ class TrackerImpl extends BaseModule { final TrackerMethods _methods = TrackerMethods(); TrackerImpl(); + /// This method sets a custom identifier in the parameters of every event. You can pass a custom + /// identifier to match your customers in our database. + /// + /// Args: + /// customIdentifier (String): customIdentifier is a String parameter that represents a unique + /// customer's custom identifier. void setCustomIdentifier(String customIdentifier) { _methods.setCustomIdentifier(customIdentifier); } + /// This method sets a custom email in the parameters of every event. You can pass a custom email to + /// match your customers in our database. + /// + /// Args: + /// customEmail (String): customEmail is a variable of type String that represents the email address + /// that the user wants to set as their custom email. void setCustomEmail(String customEmail) { _methods.setCustomEmail(customEmail); } + /// This method sends an event. + /// + /// Args: + /// event (Event): Event object void send(Event event) { _methods.send(event); } + /// This method forces sending the events from the queue to the server. void flush() { _methods.flush(); } -} \ No newline at end of file +} diff --git a/lib/modules/tracker/tracker_methods.dart b/lib/modules/tracker/tracker_methods.dart index b655745..c32243f 100644 --- a/lib/modules/tracker/tracker_methods.dart +++ b/lib/modules/tracker/tracker_methods.dart @@ -1,14 +1,13 @@ -import '../../model/tracker/event.dart'; +import '../../events/event.dart'; import '../base/base_module_method_channel.dart'; class TrackerMethods extends BaseMethodChannel { - void setCustomIdentifier(String customIdentifier) { - methodChannel.invokeMethod('Tracker/setCustomIdentifier', {"customIdentifier" : customIdentifier}); + methodChannel.invokeMethod('Tracker/setCustomIdentifier', {"customIdentifier": customIdentifier}); } void setCustomEmail(String customEmail) { - methodChannel.invokeMethod('Tracker/setCustomEmail', {"customEmail" : customEmail}); + methodChannel.invokeMethod('Tracker/setCustomEmail', {"customEmail": customEmail}); } void send(Event event) { @@ -18,4 +17,4 @@ class TrackerMethods extends BaseMethodChannel { void flush() { methodChannel.invokeMethod('Tracker/flush'); } -} \ No newline at end of file +} diff --git a/lib/synerise.dart b/lib/synerise.dart index 046a07e..2aeeb7b 100644 --- a/lib/synerise.dart +++ b/lib/synerise.dart @@ -13,6 +13,8 @@ class Synerise { static InjectorImpl injector = InjectorImpl(); static PromotionsImpl promotions = PromotionsImpl(); + /// This function returns a SyneriseInitializer object with a completion handler that initializes + /// Synerise and configures the SyneriseDartMethodChannel instance. static SyneriseInitializer initializer() { final initializer = SyneriseInitializer(); initializer.setCompletionHandler((initialized) { diff --git a/lib/utils/synerise_utils.dart b/lib/utils/synerise_utils.dart index 5efcb06..086a6b3 100644 --- a/lib/utils/synerise_utils.dart +++ b/lib/utils/synerise_utils.dart @@ -1,4 +1,13 @@ class SyneriseUtils { + /// This function converts a timestamp in milliseconds to a DateTime object in UTC format. + /// + /// Args: + /// timestampInMiliseconds (int): timestampInMiliseconds is an integer value representing the number + /// of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 UTC). + /// + /// Returns: + /// The function `formatIntToDateTime` returns a `DateTime` object that represents the date and time + /// corresponding to the input `timestampInMiliseconds`. static DateTime formatIntToDateTime(int timestampInMiliseconds) { DateTime dateTime; dateTime = DateTime.fromMillisecondsSinceEpoch(timestampInMiliseconds, isUtc: true); diff --git a/pubspec.yaml b/pubspec.yaml index 308d61b..5a4ac90 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,10 @@ name: synerise_flutter_sdk -description: Synerise Flutter SDK -version: 0.5.0 -homepage: +description: >- + Flutter plugin for Synerise SDK +version: 0.6.0 +homepage: https://synerise.com +documentation: https://help.synerise.com/developers/mobile-sdk/ +repository: https://github.com/Synerise/synerise-flutter-sdk environment: sdk: '>=2.18.2 <3.0.0'