fixed mqtt bugs

This commit is contained in:
mohamadmahdi jebeli 2025-08-09 13:55:20 +03:30
parent 570ff6bb06
commit e4fc94a3e7
4 changed files with 541 additions and 377 deletions

View File

@ -27,7 +27,7 @@ class NotificationModel {
return NotificationModel( return NotificationModel(
id: json['ID'] ?? '', id: json['ID'] ?? '',
description: json['Description'] ?? 'No description available.', description: json['Description'] ?? 'No description available.',
createdAt: DateTime.parse(json['createdAt'] ?? DateTime.now().toIso8601String()), createdAt: DateTime.tryParse(json['createdAt'] ?? '') ?? DateTime.now(),
discountId: json['Discount']?['ID'] ?? '', discountId: json['Discount']?['ID'] ?? '',
discountName: json['Discount']?['Name'] ?? 'Unknown Discount', discountName: json['Discount']?['Name'] ?? 'Unknown Discount',
shopName: json['Discount']?['Shop']?['Name'] ?? 'Unknown Shop', shopName: json['Discount']?['Shop']?['Name'] ?? 'Unknown Shop',

View File

@ -1,15 +1,10 @@
// lib/presentation/pages/offers_page.dart
import 'dart:async'; import 'dart:async';
import 'dart:math' as math; // برای محاسبات ریاضی
import 'package:animations/animations.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
@ -27,8 +22,8 @@ import 'package:proxibuy/presentation/pages/notification_preferences_page.dart';
import 'package:proxibuy/presentation/pages/reserved_list_page.dart'; import 'package:proxibuy/presentation/pages/reserved_list_page.dart';
import 'package:proxibuy/presentation/reservation/cubit/reservation_cubit.dart'; import 'package:proxibuy/presentation/reservation/cubit/reservation_cubit.dart';
import 'package:proxibuy/presentation/widgets/gps_dialog.dart'; import 'package:proxibuy/presentation/widgets/gps_dialog.dart';
import 'package:proxibuy/presentation/widgets/notification_panel.dart';
import 'package:proxibuy/presentation/widgets/notification_permission_dialog.dart'; import 'package:proxibuy/presentation/widgets/notification_permission_dialog.dart';
import 'package:proxibuy/presentation/widgets/notification_panel.dart';
import 'package:proxibuy/services/mqtt_service.dart'; import 'package:proxibuy/services/mqtt_service.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -41,29 +36,24 @@ class OffersPage extends StatefulWidget {
State<OffersPage> createState() => _OffersPageState(); State<OffersPage> createState() => _OffersPageState();
} }
class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateMixin { class _OffersPageState extends State<OffersPage> {
List<String> _selectedCategories = []; List<String> _selectedCategories = [];
StreamSubscription? _locationServiceSubscription; StreamSubscription? _locationServiceSubscription;
StreamSubscription? _mqttMessageSubscription;
StreamSubscription? _connectivitySubscription; StreamSubscription? _connectivitySubscription;
Timer? _locationTimer;
bool _isSubscribedToOffers = false;
bool _isGpsEnabled = false; bool _isGpsEnabled = false;
bool _isConnectedToInternet = true; bool _isConnectedToInternet = true;
bool _isSearchingRandomly = false; // Notifications panel state
final GlobalKey _bellKey = GlobalKey();
bool _showNotificationPanel = false; OverlayEntry? _notifOverlay;
final GlobalKey _notificationIconKey = GlobalKey(); bool _notifVisible = false;
late AnimationController _animationController;
late Animation<double> _animation;
int _notificationCount = 0; int _notificationCount = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 400),
);
_checkInitialConnectivity(); _checkInitialConnectivity();
_initializePage(); _initializePage();
_initConnectivityListener(); _initConnectivityListener();
@ -74,61 +64,13 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
@override @override
void dispose() { void dispose() {
_locationServiceSubscription?.cancel(); _locationServiceSubscription?.cancel();
_mqttMessageSubscription?.cancel();
_locationTimer?.cancel();
_connectivitySubscription?.cancel(); _connectivitySubscription?.cancel();
_animationController.dispose(); _removeNotificationOverlay();
super.dispose(); super.dispose();
} }
void _toggleNotificationPanel() {
setState(() {
_showNotificationPanel = !_showNotificationPanel;
if (_showNotificationPanel) {
_animationController.forward();
} else {
_animationController.reverse();
_fetchNotificationCount();
}
});
}
Future<void> _handleRandomSearch() async {
setState(() => _isSearchingRandomly = true);
const storage = FlutterSecureStorage();
final mqttService = context.read<MqttService>();
final userID = await storage.read(key: 'userID');
if (!mounted) return;
if (userID == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('برای این کار باید وارد حساب کاربری خود شوید.')),
);
setState(() => _isSearchingRandomly = false);
return;
}
if (!mqttService.isConnected) {
final token = await storage.read(key: 'accessToken');
if (token != null) {
await mqttService.connect(token);
} else {
setState(() => _isSearchingRandomly = false);
return;
}
}
final randomTopic = 'user-proxybuy-random/$userID';
mqttService.subscribe(randomTopic);
mqttService.publish('proxybuy-random', {'userID': userID});
Future.delayed(const Duration(seconds: 2), () {
if (mounted) {
setState(() => _isSearchingRandomly = false);
}
});
}
Future<void> _checkInitialConnectivity() async { Future<void> _checkInitialConnectivity() async {
final connectivityResult = await Connectivity().checkConnectivity(); final connectivityResult = await Connectivity().checkConnectivity();
if (!mounted) return; if (!mounted) return;
@ -146,45 +88,36 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
} }
}); });
} }
await _loadPreferences(); await _loadPreferences();
_initLocationListener(); _initLocationListener();
_listenToBackgroundService(); _subscribeToUserOffersOnLoad();
}
void _listenToBackgroundService() {
FlutterBackgroundService().on('update').listen((event) {
if (event == null || event['offers'] == null) return;
final data = event['offers']['data'];
if (data == null || data is! List) {
if (mounted) {
context.read<OffersBloc>().add(const OffersReceivedFromMqtt([]));
}
return;
}
try {
List<OfferModel> offers = data.whereType<Map<String, dynamic>>().map((json) => OfferModel.fromJson(json)).toList();
if (mounted) {
context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers));
}
} catch (e, stackTrace) {
debugPrint("❌ Error parsing offers from Background Service: $e");
debugPrint(stackTrace.toString());
}
});
} }
void _initConnectivityListener() { void _initConnectivityListener() {
_connectivitySubscription = Connectivity().onConnectivityChanged.listen((results) { _connectivitySubscription =
Connectivity().onConnectivityChanged.listen((results) {
final hasConnection = !results.contains(ConnectivityResult.none); final hasConnection = !results.contains(ConnectivityResult.none);
if (mounted && _isConnectedToInternet != hasConnection) { if (mounted && _isConnectedToInternet != hasConnection) {
setState(() => _isConnectedToInternet = hasConnection); setState(() {
_isConnectedToInternet = hasConnection;
});
if (hasConnection) { if (hasConnection) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('اتصال به اینترنت برقرار شد.'), backgroundColor: Colors.green)); ScaffoldMessenger.of(context).showSnackBar(
_fetchNotificationCount(); const SnackBar(
content: Text('اتصال به اینترنت برقرار شد.'),
backgroundColor: Colors.green,
),
);
} else { } else {
context.read<OffersBloc>().add(ClearOffers()); context.read<OffersBloc>().add(ClearOffers());
setState(() => _notificationCount = 0); ScaffoldMessenger.of(context).showSnackBar(
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('اتصال به اینترنت قطع شد.'), backgroundColor: Colors.red)); const SnackBar(
content: Text('اتصال به اینترنت قطع شد.'),
backgroundColor: Colors.red,
),
);
} }
} }
}); });
@ -196,11 +129,21 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
final token = await storage.read(key: 'accessToken'); final token = await storage.read(key: 'accessToken');
if (token == null) return; if (token == null) return;
final dio = Dio(); final dio = Dio();
final response = await dio.get(ApiConfig.baseUrl + ApiConfig.getReservations, options: Options(headers: {'Authorization': 'Bearer $token'})); final response = await dio.get(
ApiConfig.baseUrl + ApiConfig.getReservations,
options: Options(headers: {'Authorization': 'Bearer $token'}),
);
if (response.statusCode == 200 && mounted) { if (response.statusCode == 200 && mounted) {
final List<dynamic> reserves = response.data['reserves']; final List<dynamic> reserves = response.data['reserves'];
final List<String> reservedIds = reserves.map((reserveData) => (reserveData['Discount']['ID'] as String?) ?? '').where((id) => id.isNotEmpty).toList(); final List<String> reservedIds = reserves
.map((reserveData) =>
(reserveData['Discount']['ID'] as String?) ?? '')
.where((id) => id.isNotEmpty)
.toList();
context.read<ReservationCubit>().setReservedIds(reservedIds); context.read<ReservationCubit>().setReservedIds(reservedIds);
} }
} catch (e) { } catch (e) {
@ -208,70 +151,282 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
} }
} }
Future<void> _fetchNotificationCount() async { Future<void> _subscribeToUserOffersOnLoad() async {
if (!_isConnectedToInternet) return; final storage = const FlutterSecureStorage();
try { final userID = await storage.read(key: 'userID');
const storage = FlutterSecureStorage(); if (userID != null && mounted) {
final token = await storage.read(key: 'accessToken'); _subscribeToUserOffers(userID);
if (token == null) return;
final dio = Dio();
final response = await dio.get(
'${ApiConfig.baseUrl}/notify/get',
options: Options(headers: {'Authorization': 'Bearer $token'}),
);
if (response.statusCode == 200 && mounted) {
final List<dynamic> data = response.data['data'];
setState(() {
_notificationCount = data.length;
});
}
} catch (e) {
debugPrint("Error fetching notification count: $e");
} }
} }
void _initLocationListener() { void _initLocationListener() {
_checkInitialGpsStatus(); _checkInitialGpsStatus();
_locationServiceSubscription = Geolocator.getServiceStatusStream().listen((status) { _locationServiceSubscription =
Geolocator.getServiceStatusStream().listen((status) {
final isEnabled = status == ServiceStatus.enabled; final isEnabled = status == ServiceStatus.enabled;
if (mounted && _isGpsEnabled != isEnabled) { if (mounted && _isGpsEnabled != isEnabled) {
setState(() => _isGpsEnabled = isEnabled); setState(() {
if (!isEnabled) context.read<OffersBloc>().add(ClearOffers()); _isGpsEnabled = isEnabled;
});
if (isEnabled) {
_startSendingLocationUpdates();
} else {
debugPrint("❌ Location Service Disabled. Stopping updates.");
_locationTimer?.cancel();
context.read<OffersBloc>().add(ClearOffers());
}
} }
}); });
} }
Future<void> _checkInitialGpsStatus() async { Future<void> _checkInitialGpsStatus() async {
final status = await Geolocator.isLocationServiceEnabled(); final status = await Geolocator.isLocationServiceEnabled();
if (mounted) setState(() => _isGpsEnabled = status); if (mounted) {
setState(() {
_isGpsEnabled = status;
});
if (_isGpsEnabled) {
_startSendingLocationUpdates();
}
}
}
void _startSendingLocationUpdates() {
debugPrint("🚀 Starting periodic location updates.");
_locationTimer?.cancel();
_locationTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
_sendLocationUpdate();
});
_sendLocationUpdate();
}
Future<void> _sendLocationUpdate() async {
if (!_isConnectedToInternet || !_isGpsEnabled) return;
final mqttService = context.read<MqttService>();
if (!mqttService.isConnected) {
debugPrint("⚠️ MQTT not connected in OffersPage. Cannot send location.");
return;
}
try {
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
debugPrint("🚫 Location permission denied by user.");
return;
}
final position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
const storage = FlutterSecureStorage();
final userID = await storage.read(key: 'userID');
if (userID == null) {
debugPrint("⚠️ UserID not found. Cannot send location.");
return;
}
final payload = {
"userID": userID,
"lat": position.latitude,
"lng": position.longitude
};
mqttService.publish("proxybuy/sendGps", payload);
} catch (e) {
debugPrint("❌ Error sending location update in OffersPage: $e");
}
}
void _subscribeToUserOffers(String userID) {
if (_isSubscribedToOffers) return;
final mqttService = context.read<MqttService>();
if (!mqttService.isConnected) {
debugPrint("⚠️ Cannot subscribe. MQTT client is not connected.");
return;
}
final topic = 'user-proxybuy/$userID';
mqttService.subscribe(topic);
_isSubscribedToOffers = true;
_mqttMessageSubscription = mqttService.messages.listen((message) {
final data = message['data'];
if (data == null || data is! List) {
if (mounted) {
context.read<OffersBloc>().add(const OffersReceivedFromMqtt([]));
}
return;
}
try {
List<OfferModel> offers = data
.whereType<Map<String, dynamic>>()
.map((json) => OfferModel.fromJson(json))
.toList();
if (mounted) {
context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers));
}
} catch (e, stackTrace) {
debugPrint("❌ Error parsing offers from MQTT: $e");
debugPrint(stackTrace.toString());
}
});
} }
Future<void> _loadPreferences() async { Future<void> _loadPreferences() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final savedCategories = prefs.getStringList('user_selected_categories') ?? []; final savedCategories =
if (mounted) setState(() => _selectedCategories = savedCategories); prefs.getStringList('user_selected_categories') ?? [];
if (mounted) {
setState(() {
_selectedCategories = savedCategories;
});
}
} }
Future<void> _handleRefresh() { Future<void> _fetchNotificationCount() async {
final completer = Completer<void>(); try {
final service = FlutterBackgroundService(); const storage = FlutterSecureStorage();
final timeout = Timer(const Duration(seconds: 20), () { final token = await storage.read(key: 'accessToken');
if (!completer.isCompleted) { if (token == null) {
completer.completeError('Request timed out.'); if (mounted) setState(() => _notificationCount = 0);
if (mounted) ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Request timed out. Please try again.'))); return;
} }
}); final dio = Dio();
final StreamSubscription<Map<String, dynamic>?> subscription = service.on('update').listen((event) { final response = await dio.get(
if (!completer.isCompleted) completer.complete(); 'https://proxybuy.liara.run/notify/get',
}); options: Options(headers: {'Authorization': 'Bearer $token'}),
completer.future.whenComplete(() { );
subscription.cancel(); if (!mounted) return;
timeout.cancel(); if (response.statusCode == 200) {
}); final List<dynamic> data = response.data['data'] ?? [];
service.invoke('force_refresh'); // Filter only active notifications (Status: true)
return completer.future; final activeNotifications = data.where((item) => item['Status'] == true).toList();
setState(() => _notificationCount = activeNotifications.length);
} else {
setState(() => _notificationCount = 0);
}
} catch (_) {
if (mounted) setState(() => _notificationCount = 0);
}
}
void _showNotificationOverlay() {
if (_notifOverlay != null) return;
final overlay = Overlay.of(context);
final renderBox = _bellKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox == null) return;
final bellSize = renderBox.size;
final bellPosition = renderBox.localToGlobal(Offset.zero);
final screenSize = MediaQuery.of(context).size;
final panelWidth = screenSize.width.clamp(0, 360);
final width = (panelWidth > 320 ? 320.0 : panelWidth - 24).toDouble();
final top = bellPosition.dy + bellSize.height; // stick to icon
final tentativeLeft = bellPosition.dx + bellSize.width - width;
final double left = tentativeLeft.clamp(8.0, screenSize.width - width - 8.0).toDouble();
_notifOverlay = OverlayEntry(
builder: (ctx) {
return Stack(
children: [
// Tap outside to close
Positioned.fill(
child: GestureDetector(
onTap: _hideNotificationOverlay,
behavior: HitTestBehavior.opaque,
child: const SizedBox.shrink(),
),
),
Positioned(
top: top,
left: left,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0.9, end: 1.0),
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutBack,
builder: (context, scale, child) {
// Ensure scale is valid
final validScale = scale.clamp(0.0, 1.0);
return Opacity(
opacity: validScale,
child: Transform.scale(
scale: validScale,
alignment: Alignment.topLeft,
child: Material(
color: Colors.transparent,
child: Container(
width: width,
constraints: const BoxConstraints(
maxHeight: 250,
minWidth: 370,
),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 24,
spreadRadius: 4,
offset: const Offset(0, 8),
),
],
),
child: Directionality(
textDirection: TextDirection.rtl,
child: NotificationPanel(
onClose: _hideNotificationOverlay,
onListChanged: () {
_fetchNotificationCount();
},
),
),
),
),
),
);
},
),
),
],
);
},
);
overlay.insert(_notifOverlay!);
setState(() => _notifVisible = true);
}
void _hideNotificationOverlay() {
_notifOverlay?.remove();
_notifOverlay = null;
if (mounted) setState(() => _notifVisible = false);
}
void _removeNotificationOverlay() {
_notifOverlay?.remove();
_notifOverlay = null;
}
Future<void> _onRefresh() async {
await _sendLocationUpdate();
await _fetchNotificationCount();
await Future.delayed(const Duration(milliseconds: 300));
} }
Widget _buildFavoriteCategoriesSection() { Widget _buildFavoriteCategoriesSection() {
@ -283,20 +438,36 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text('دسته‌بندی‌های مورد علاقه شما', style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold)), const Text(
'دسته‌بندی‌های مورد علاقه شما',
style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold),
),
TextButton( TextButton(
onPressed: () async { onPressed: () async {
final result = await Navigator.of(context).push<bool>(MaterialPageRoute(builder: (context) => const NotificationPreferencesPage(loadFavoritesOnStart: true))); await Navigator.of(context).push<bool>(
MaterialPageRoute(
builder: (context) => const NotificationPreferencesPage(
loadFavoritesOnStart: true,
),
),
);
if (!mounted) return; if (!mounted) return;
context.read<NotificationPreferencesBloc>().add(ResetSubmissionStatus());
await _loadPreferences(); context
if (result == true) _handleRefresh(); .read<NotificationPreferencesBloc>()
.add(ResetSubmissionStatus());
_loadPreferences();
}, },
child: Row( child: Row(
children: [ children: [
SvgPicture.asset(Assets.icons.edit.path), SvgPicture.asset(Assets.icons.edit.path),
const SizedBox(width: 4), const SizedBox(width: 4),
const Text('ویرایش', style: TextStyle(color: AppColors.active)), const Text(
'ویرایش',
style: TextStyle(color: AppColors.active),
),
], ],
), ),
), ),
@ -307,7 +478,10 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
if (_selectedCategories.isEmpty) if (_selectedCategories.isEmpty)
const Padding( const Padding(
padding: EdgeInsets.only(bottom: 8.0), padding: EdgeInsets.only(bottom: 8.0),
child: Text('شما هنوز دسته‌بندی مورد علاقه خود را انتخاب نکرده‌اید.', style: TextStyle(color: Colors.grey)), child: Text(
'شما هنوز دسته‌بندی مورد علاقه خود را انتخاب نکرده‌اید.',
style: TextStyle(color: Colors.grey),
),
) )
else else
Wrap( Wrap(
@ -315,8 +489,14 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
runSpacing: 8.0, runSpacing: 8.0,
children: _selectedCategories.map((category) { children: _selectedCategories.map((category) {
return Container( return Container(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0), padding: const EdgeInsets.symmetric(
decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(20.0)), horizontal: 12.0,
vertical: 6.0,
),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(20.0),
),
child: Text(category), child: Text(category),
); );
}).toList(), }).toList(),
@ -335,31 +515,52 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
backgroundColor: Colors.white, backgroundColor: Colors.white,
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
title: Padding( title: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0), padding: const EdgeInsets.symmetric(
horizontal: 15.0,
vertical: 0.0,
),
child: Assets.icons.logoWithName.svg(height: 40, width: 200), child: Assets.icons.logoWithName.svg(height: 40, width: 200),
), ),
actions: [ actions: [
// Notification bell with badge and overlay trigger
Stack( Stack(
clipBehavior: Clip.none,
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
IconButton( IconButton(
key: _notificationIconKey, key: _bellKey,
onPressed: _toggleNotificationPanel, onPressed: () {
if (_notifVisible) {
_hideNotificationOverlay();
} else {
_fetchNotificationCount();
_showNotificationOverlay();
}
},
icon: Assets.icons.notification.svg(), icon: Assets.icons.notification.svg(),
), ),
if (_notificationCount > 0) if (_notificationCount > 0)
Positioned( Positioned(
top: 0, top: 3,
right: 2, // in RTL, actions are on the left; badge at top-left of icon
child: GestureDetector( right: 7,
onTap: _toggleNotificationPanel, child: Container(
child: Container( padding: const EdgeInsets.all(4),
padding: const EdgeInsets.all(4), decoration: BoxDecoration(
decoration: BoxDecoration(color: Colors.red, shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.5)), color: Colors.red,
constraints: const BoxConstraints(minWidth: 18, minHeight: 18), shape: BoxShape.circle,
child: Padding( border: Border.all(color: Colors.white, width: 1.5),
padding: const EdgeInsets.fromLTRB(2, 4, 2, 2), ),
child: Text('$_notificationCount', style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.bold), textAlign: TextAlign.center), constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
child: Center(
child: Text(
'$_notificationCount',
style: const TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
), ),
), ),
), ),
@ -373,11 +574,13 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
IconButton( IconButton(
onPressed: () => Navigator.of(context).push(PageRouteBuilder( onPressed: () {
pageBuilder: (context, animation, secondaryAnimation) => const ReservedListPage(), Navigator.of(context).push(
transitionsBuilder: (context, animation, secondaryAnimation, child) => MaterialPageRoute(
SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.horizontal, child: child), builder: (_) => const ReservedListPage(),
)), ),
);
},
icon: Assets.icons.scanBarcode.svg(), icon: Assets.icons.scanBarcode.svg(),
), ),
if (reservedCount > 0) if (reservedCount > 0)
@ -385,18 +588,36 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
top: 0, top: 0,
right: 2, right: 2,
child: GestureDetector( child: GestureDetector(
onTap: () => Navigator.of(context).push(PageRouteBuilder( onTap: () {
pageBuilder: (context, animation, secondaryAnimation) => const ReservedListPage(), Navigator.of(context).push(
transitionsBuilder: (context, animation, secondaryAnimation, child) => MaterialPageRoute(
SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.horizontal, child: child), builder: (_) => const ReservedListPage(),
)), ),
);
},
child: Container( child: Container(
padding: const EdgeInsets.all(4), padding: const EdgeInsets.all(4),
decoration: BoxDecoration(color: Colors.green, shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.5)), decoration: BoxDecoration(
constraints: const BoxConstraints(minWidth: 18, minHeight: 18), color: Colors.green,
shape: BoxShape.circle,
border:
Border.all(color: Colors.white, width: 1.5),
),
constraints: const BoxConstraints(
minWidth: 18,
minHeight: 18,
),
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(2, 4, 2, 2), padding: const EdgeInsets.fromLTRB(2, 4, 2, 2),
child: Text('$reservedCount', style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.bold), textAlign: TextAlign.center), child: Text(
'$reservedCount',
style: const TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
), ),
), ),
), ),
@ -408,115 +629,36 @@ class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateM
const SizedBox(width: 8), const SizedBox(width: 8),
], ],
), ),
body: Stack( body: RefreshIndicator(
children: [ onRefresh: _onRefresh,
RefreshIndicator( color: AppColors.active,
onRefresh: _handleRefresh, child: SingleChildScrollView(
child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(),
physics: const AlwaysScrollableScrollPhysics(), child: Column(
child: Column( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: [
children: [ _buildFavoriteCategoriesSection(),
_buildFavoriteCategoriesSection(), OffersView(
OffersView( isGpsEnabled: _isGpsEnabled,
isGpsEnabled: _isGpsEnabled, isConnectedToInternet: _isConnectedToInternet,
isConnectedToInternet: _isConnectedToInternet,
selectedCategories: _selectedCategories,
onRandomSearch: _handleRandomSearch,
isSearchingRandomly: _isSearchingRandomly,
),
],
), ),
), ],
), ),
_buildNotificationOverlay(), ),
],
), ),
), ),
); );
} }
Widget _buildNotificationOverlay() {
if (!_showNotificationPanel && _animationController.isDismissed) {
return const SizedBox.shrink();
}
final RenderBox? renderBox = _notificationIconKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox == null) return const SizedBox.shrink();
final position = renderBox.localToGlobal(Offset.zero);
final size = renderBox.size;
final iconCenter = Offset(position.dx + size.width / 2, position.dy + size.height / 2);
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
final maxRadius = math.sqrt(math.pow(screenWidth, 2) + math.pow(screenHeight, 2));
_animation = Tween<double>(begin: 0.0, end: maxRadius).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInCubic),
);
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Stack(
children: [
if (_showNotificationPanel || !_animationController.isDismissed)
Positioned.fill(
child: GestureDetector(
onTap: _toggleNotificationPanel,
child: Container(
color: Colors.black.withOpacity(0.4 * _animationController.value),
),
),
),
ClipPath(
clipper: CircularRevealClipper(
radius: _animation.value,
center: iconCenter,
),
child: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(top: kToolbarHeight - 40, left: 16, right: 16),
child: Material(
elevation: 12.0,
borderRadius: BorderRadius.circular(16),
child: Container(
height: MediaQuery.of(context).size.height * 0.40,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
),
child: NotificationPanel(
onClose: _toggleNotificationPanel,
),
),
),
),
),
),
],
);
},
);
}
} }
class OffersView extends StatelessWidget { class OffersView extends StatelessWidget {
final bool isGpsEnabled; final bool isGpsEnabled;
final bool isConnectedToInternet; final bool isConnectedToInternet;
final List<String> selectedCategories;
final VoidCallback onRandomSearch;
final bool isSearchingRandomly;
const OffersView({ const OffersView({
super.key, super.key,
required this.isGpsEnabled, required this.isGpsEnabled,
required this.isConnectedToInternet, required this.isConnectedToInternet,
required this.selectedCategories,
required this.onRandomSearch,
required this.isSearchingRandomly,
}); });
@override @override
@ -548,11 +690,7 @@ class OffersView extends StatelessWidget {
} }
if (state is OffersLoadSuccess) { if (state is OffersLoadSuccess) {
final filteredOffers = selectedCategories.isEmpty if (state.offers.isEmpty) {
? state.offers
: state.offers.where((offer) => selectedCategories.contains(offer.category)).toList();
if (filteredOffers.isEmpty) {
return const SizedBox( return const SizedBox(
height: 300, height: 300,
child: Center( child: Center(
@ -567,7 +705,10 @@ class OffersView extends StatelessWidget {
); );
} }
final groupedOffers = groupBy(filteredOffers, (OfferModel offer) => offer.category); final groupedOffers = groupBy(
state.offers,
(OfferModel offer) => offer.category,
);
final categories = groupedOffers.keys.toList(); final categories = groupedOffers.keys.toList();
return ListView.builder( return ListView.builder(
@ -578,10 +719,12 @@ class OffersView extends StatelessWidget {
itemBuilder: (context, index) { itemBuilder: (context, index) {
final category = categories[index]; final category = categories[index];
final offersForCategory = groupedOffers[category]!; final offersForCategory = groupedOffers[category]!;
return CategoryOffersRow(categoryTitle: category, offers: offersForCategory)
.animate() return CategoryOffersRow(
.fade(duration: 500.ms) categoryTitle: category,
.slideY(begin: 0.3, duration: 400.ms, curve: Curves.easeOut); offers: offersForCategory,
).animate().fade(duration: 500.ms).slideY(
begin: 0.3, duration: 400.ms, curve: Curves.easeOut);
}, },
); );
} }
@ -616,33 +759,25 @@ class OffersView extends StatelessWidget {
backgroundColor: AppColors.confirm, backgroundColor: AppColors.confirm,
foregroundColor: Colors.white, foregroundColor: Colors.white,
disabledBackgroundColor: Colors.grey, disabledBackgroundColor: Colors.grey,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 125), padding: const EdgeInsets.symmetric(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)), vertical: 12,
horizontal: 125,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
child: const Text(
'فعال‌سازی GPS',
style: TextStyle(
fontFamily: 'Dana',
fontSize: 16,
fontWeight: FontWeight.normal,
),
), ),
child: const Text('فعال‌سازی GPS', style: TextStyle(fontFamily: 'Dana', fontSize: 16, fontWeight: FontWeight.normal)),
), ),
const SizedBox(height: 15), const SizedBox(height: 15),
InkWell( const Text('جست‌وجوی تصادفی'),
onTap: isSearchingRandomly ? null : onRandomSearch,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: isSearchingRandomly
? const Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('در حال جستجو...'),
SizedBox(width: 8),
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
)
: const Text('جست‌وجوی تصادفی'),
),
),
], ],
), ),
), ),
@ -659,29 +794,18 @@ class OffersView extends StatelessWidget {
children: [ children: [
Icon(Icons.wifi_off_rounded, size: 80, color: Colors.grey[400]), Icon(Icons.wifi_off_rounded, size: 80, color: Colors.grey[400]),
const SizedBox(height: 20), const SizedBox(height: 20),
const Text("اتصال به اینترنت برقرار نیست", style: TextStyle(fontSize: 18, color: Colors.grey)), const Text(
"اتصال به اینترنت برقرار نیست",
style: TextStyle(fontSize: 18, color: Colors.grey),
),
const SizedBox(height: 10), const SizedBox(height: 10),
const Text("لطفاً اتصال خود را بررسی کرده و دوباره تلاش کنید.", style: TextStyle(color: Colors.grey)), const Text(
"لطفاً اتصال خود را بررسی کرده و دوباره تلاش کنید.",
style: TextStyle(color: Colors.grey),
),
], ],
), ),
), ),
); );
} }
} }
class CircularRevealClipper extends CustomClipper<Path> {
final double radius;
final Offset center;
CircularRevealClipper({required this.radius, required this.center});
@override
Path getClip(Size size) {
return Path()..addOval(Rect.fromCircle(center: center, radius: radius));
}
@override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
return true;
}
}

View File

@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:proxibuy/core/config/api_config.dart';
import 'package:proxibuy/core/config/app_colors.dart'; import 'package:proxibuy/core/config/app_colors.dart';
import 'package:proxibuy/data/models/notification_model.dart'; import 'package:proxibuy/data/models/notification_model.dart';
import 'package:proxibuy/presentation/offer/bloc/offer_bloc.dart'; import 'package:proxibuy/presentation/offer/bloc/offer_bloc.dart';
@ -12,8 +11,9 @@ import 'package:proxibuy/presentation/pages/product_detail_page.dart';
class NotificationPanel extends StatefulWidget { class NotificationPanel extends StatefulWidget {
final VoidCallback onClose; final VoidCallback onClose;
final VoidCallback? onListChanged;
const NotificationPanel({super.key, required this.onClose}); const NotificationPanel({super.key, required this.onClose, this.onListChanged});
@override @override
State<NotificationPanel> createState() => _NotificationPanelState(); State<NotificationPanel> createState() => _NotificationPanelState();
@ -40,27 +40,32 @@ class _NotificationPanelState extends State<NotificationPanel> {
_isLoading = false; _isLoading = false;
_errorMessage = 'برای مشاهده اعلان‌ها، لطفا ابتدا وارد شوید.'; _errorMessage = 'برای مشاهده اعلان‌ها، لطفا ابتدا وارد شوید.';
}); });
widget.onListChanged?.call();
} }
return; return;
} }
try { try {
final response = await _dio.get( final response = await _dio.get(
'${ApiConfig.baseUrl}/notify/get', 'https://proxybuy.liara.run/notify/get',
options: Options(headers: {'Authorization': 'Bearer $token'}), options: Options(headers: {'Authorization': 'Bearer $token'}),
); );
if (response.statusCode == 200 && mounted) { if (response.statusCode == 200 && mounted) {
final List<dynamic> data = response.data['data']; final List<dynamic> data = response.data['data'] ?? [];
setState(() { setState(() {
_notifications = data.map((json) => NotificationModel.fromJson(json)).toList(); _notifications = data.map((json) => NotificationModel.fromJson(json)).toList();
_isLoading = false; _isLoading = false;
}); });
} else { widget.onListChanged?.call();
setState(() { } else if (response.statusCode == 201) {
_isLoading = false; if (mounted) {
_errorMessage = 'خطا در دریافت اطلاعات.'; setState(() {
}); _isLoading = false;
_errorMessage = 'اعلانی وجود ندارد';
});
widget.onListChanged?.call();
}
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
@ -68,6 +73,7 @@ class _NotificationPanelState extends State<NotificationPanel> {
_isLoading = false; _isLoading = false;
_errorMessage = 'اتصال به سرور برقرار نشد.'; _errorMessage = 'اتصال به سرور برقرار نشد.';
}); });
widget.onListChanged?.call();
} }
} }
} }
@ -83,7 +89,7 @@ class _NotificationPanelState extends State<NotificationPanel> {
try { try {
final response = await _dio.get( final response = await _dio.get(
'${ApiConfig.baseUrl}/notify/ignore/$notificationId', 'https://proxybuy.liara.run/notify/ignore/$notificationId',
options: Options(headers: {'Authorization': 'Bearer $token'}), options: Options(headers: {'Authorization': 'Bearer $token'}),
); );
@ -91,17 +97,20 @@ class _NotificationPanelState extends State<NotificationPanel> {
setState(() { setState(() {
_notifications.removeWhere((n) => n.id == notificationId); _notifications.removeWhere((n) => n.id == notificationId);
}); });
widget.onListChanged?.call();
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( if (mounted) {
SnackBar(content: Text(response.data['message'] ?? 'خطا در حذف اعلان.')), ScaffoldMessenger.of(context).showSnackBar(
); SnackBar(content: Text(response.data?['message'] ?? 'خطا در حذف اعلان.')),
);
}
} }
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('خطا در ارتباط با سرور.')), const SnackBar(content: Text('خطا در ارتباط با سرور.')),
); );
print(e.toString()); debugPrint('Error ignoring notification: $e');
} }
} }
} }
@ -174,7 +183,7 @@ class _NotificationPanelState extends State<NotificationPanel> {
return const Center( return const Center(
child: Padding( child: Padding(
padding: EdgeInsets.all(16.0), padding: EdgeInsets.all(16.0),
child: Text('هیچ اعلانی برای نمایش وجود ندارد.', textAlign: TextAlign.center), child: Text('اعلانی وجود ندارد.', textAlign: TextAlign.center),
), ),
); );
} }

View File

@ -1,5 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
import 'dart:math'; import 'dart:math';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
@ -8,25 +9,22 @@ import 'package:mqtt_client/mqtt_server_client.dart';
class MqttService { class MqttService {
MqttServerClient? client; MqttServerClient? client;
final String server = '5.75.197.180'; final String server = '62.60.214.99';
final int port = 1883; final int port = 1883;
final StreamController<Map<String, dynamic>> _messageStreamController =
StreamController.broadcast();
final StreamController<Map<String, dynamic>> _messageStreamController = StreamController.broadcast();
Stream<Map<String, dynamic>> get messages => _messageStreamController.stream; Stream<Map<String, dynamic>> get messages => _messageStreamController.stream;
Completer<Map<String, dynamic>>? _firstMessageCompleter; bool get isConnected {
return client?.connectionStatus?.state == MqttConnectionState.connected;
bool get isConnected => client?.connectionStatus?.state == MqttConnectionState.connected;
Future<Map<String, dynamic>> awaitFirstMessage() {
_firstMessageCompleter = Completer<Map<String, dynamic>>();
return _firstMessageCompleter!.future;
} }
Future<void> connect(String token) async { Future<void> connect(String token) async {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
final userID = await storage.read(key: 'userID'); final userID = await storage.read(key: 'userID');
final String clientId = userID ?? 'proxibuy'; final String clientId = userID??
'nest-' + Random().nextInt(0xFFFFFF).toRadixString(16).padLeft(6, '0');
final String username = 'ignored'; final String username = 'ignored';
final String password = token; final String password = token;
@ -36,6 +34,10 @@ class MqttService {
client!.autoReconnect = true; client!.autoReconnect = true;
client!.setProtocolV311(); client!.setProtocolV311();
debugPrint('--- [MQTT] Attempting to connect...');
debugPrint('--- [MQTT] Server: $server:$port');
debugPrint('--- [MQTT] ClientID: $clientId');
final connMessage = MqttConnectMessage() final connMessage = MqttConnectMessage()
.withClientIdentifier(clientId) .withClientIdentifier(clientId)
.startClean() .startClean()
@ -47,57 +49,86 @@ class MqttService {
debugPrint('✅ [MQTT] Connected successfully.'); debugPrint('✅ [MQTT] Connected successfully.');
client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) { client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage; final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
final String payload = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
final String payload =
MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
debugPrint('<<<<< [MQTT] Received Data <<<<<');
debugPrint('<<<<< [MQTT] Topic: ${c[0].topic}');
debugPrint('<<<<< [MQTT] Payload as String: $payload');
debugPrint('<<<<< ======================== <<<<<');
try { try {
final Map<String, dynamic> jsonPayload = json.decode(payload); final Map<String, dynamic> jsonPayload = json.decode(payload);
_messageStreamController.add(jsonPayload);
if (!_messageStreamController.isClosed) {
_messageStreamController.add(jsonPayload);
}
if (_firstMessageCompleter != null && !_firstMessageCompleter!.isCompleted) {
_firstMessageCompleter!.complete(jsonPayload);
}
} catch (e) { } catch (e) {
debugPrint("❌ [MQTT] Error decoding JSON: $e"); debugPrint("❌ [MQTT] Error decoding received JSON: $e");
if (_firstMessageCompleter != null && !_firstMessageCompleter!.isCompleted) {
_firstMessageCompleter!.completeError(e);
}
} }
}); });
}; };
client!.onDisconnected = () => debugPrint('❌ [MQTT] Disconnected.'); client!.onDisconnected = () {
client!.onSubscribed = (String topic) => debugPrint('✅ [MQTT] Subscribed to topic: $topic'); debugPrint('❌ [MQTT] Disconnected.');
};
client!.onAutoReconnect = () {
debugPrint('↪️ [MQTT] Auto-reconnecting...');
};
client!.onAutoReconnected = () {
debugPrint('✅ [MQTT] Auto-reconnected successfully.');
};
client!.onSubscribed = (String topic) {
debugPrint('✅ [MQTT] Subscribed to topic: $topic');
};
client!.pongCallback = () {
debugPrint('🏓 [MQTT] Ping response received');
};
try { try {
await client!.connect(); await client!.connect();
} on NoConnectionException catch (e) {
debugPrint('❌ [MQTT] Connection failed - No Connection Exception: $e');
client?.disconnect();
} on SocketException catch (e) {
debugPrint('❌ [MQTT] Connection failed - Socket Exception: $e');
client?.disconnect();
} catch (e) { } catch (e) {
debugPrint('❌ [MQTT] Connection failed: $e'); debugPrint('❌ [MQTT] Connection failed - General Exception: $e');
client?.disconnect(); client?.disconnect();
if (_firstMessageCompleter != null && !_firstMessageCompleter!.isCompleted) {
_firstMessageCompleter!.completeError(e);
}
} }
} }
void subscribe(String topic) { void subscribe(String topic) {
if (isConnected) { if (isConnected) {
client?.subscribe(topic, MqttQos.atLeastOnce); client?.subscribe(topic, MqttQos.atLeastOnce);
} else {
debugPrint("⚠️ [MQTT] Cannot subscribe. Client is not connected.");
} }
} }
void publish(String topic, Map<String, dynamic> message) { void publish(String topic, Map<String, dynamic> message) {
if (isConnected) { if (isConnected) {
final builder = MqttClientPayloadBuilder(); final builder = MqttClientPayloadBuilder();
builder.addString(json.encode(message)); final payloadString = json.encode(message);
builder.addString(payloadString);
debugPrint('>>>>> [MQTT] Publishing Data >>>>>');
debugPrint('>>>>> [MQTT] Topic: $topic');
debugPrint('>>>>> [MQTT] Payload: $payloadString');
debugPrint('>>>>> ======================= >>>>>');
client?.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!); client?.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
} else {
debugPrint("⚠️ [MQTT] Cannot publish. Client is not connected.");
} }
} }
void dispose() { void dispose() {
client?.disconnect(); debugPrint("--- [MQTT] Disposing MQTT Service.");
_messageStreamController.close(); _messageStreamController.close();
client?.disconnect();
} }
} }