64 lines
2.3 KiB
Dart
64 lines
2.3 KiB
Dart
import 'dart:convert';
|
|
import 'package:workmanager/workmanager.dart';
|
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:odoo_rpc/odoo_rpc.dart';
|
|
|
|
@pragma('vm:entry-point')
|
|
void callbackDispatcher() {
|
|
Workmanager().executeTask((task, inputData) async {
|
|
try {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final url = prefs.getString('odoo_url');
|
|
final sessionStr = prefs.getString('odoo_session');
|
|
final lastNotificationId = prefs.getInt('last_notification_id') ?? 0;
|
|
|
|
if (url == null || sessionStr == null) {
|
|
return Future.value(true); // Cannot fetch if not logged in
|
|
}
|
|
|
|
final sessionArgs = json.decode(sessionStr);
|
|
final session = OdooSession.fromJson(sessionArgs);
|
|
final client = OdooClient(url, sessionId: session);
|
|
|
|
final response = await client.callRPC(
|
|
'/api/loyalty/fetch_notifications',
|
|
'call',
|
|
{'last_id': lastNotificationId}
|
|
);
|
|
|
|
if (response != null && response['status'] == 'success') {
|
|
final notifications = response['data'] as List;
|
|
if (notifications.isNotEmpty) {
|
|
int highestId = lastNotificationId;
|
|
|
|
final flnp = FlutterLocalNotificationsPlugin();
|
|
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
|
const initSettings = InitializationSettings(android: androidSettings);
|
|
await flnp.initialize(settings: initSettings);
|
|
|
|
for (final notif in notifications) {
|
|
final int notifId = notif['id'];
|
|
if (notifId > highestId) highestId = notifId;
|
|
|
|
const androidConfig = AndroidNotificationDetails(
|
|
'loyalty_channel', 'Promos',
|
|
importance: Importance.max, priority: Priority.high
|
|
);
|
|
await flnp.show(
|
|
id: notifId,
|
|
title: notif['title'],
|
|
body: notif['body'],
|
|
notificationDetails: const NotificationDetails(android: androidConfig)
|
|
);
|
|
}
|
|
await prefs.setInt('last_notification_id', highestId);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
print('Background Fetch Error: $e');
|
|
}
|
|
return Future.value(true);
|
|
});
|
|
}
|