background-activity #1

Open
Mr.Jebelli wants to merge 6 commits from background-activity into main
10 changed files with 619 additions and 235 deletions
Showing only changes of commit 570ff6bb06 - Show all commits

View File

@ -17,4 +17,6 @@ class AppColors {
static const Color countdownBorderRserve = Color.fromARGB(255, 186, 222, 251); static const Color countdownBorderRserve = Color.fromARGB(255, 186, 222, 251);
static const Color expiryReserve = Color.fromARGB(255, 183, 28, 28); static const Color expiryReserve = Color.fromARGB(255, 183, 28, 28);
static const Color uploadElevated = Color.fromARGB(255, 233, 245, 254); static const Color uploadElevated = Color.fromARGB(255, 233, 245, 254);
static const Color backgroundConfirm = Color.fromARGB(255, 237, 247, 238);
static const Color notifIcon = Color.fromARGB(255, 179, 38, 30);
} }

View File

@ -0,0 +1,37 @@
import 'package:proxibuy/data/models/offer_model.dart';
class NotificationModel {
final String id;
final String description;
final DateTime createdAt;
final String discountId;
final String discountName;
final String shopName;
final bool status;
OfferModel? offer;
NotificationModel({
required this.id,
required this.description,
required this.createdAt,
required this.discountId,
required this.discountName,
required this.shopName,
required this.status,
this.offer,
});
factory NotificationModel.fromJson(Map<String, dynamic> json) {
final bool statusValue = json['Status'] is bool ? json['Status'] : false;
return NotificationModel(
id: json['ID'] ?? '',
description: json['Description'] ?? 'No description available.',
createdAt: DateTime.parse(json['createdAt'] ?? DateTime.now().toIso8601String()),
discountId: json['Discount']?['ID'] ?? '',
discountName: json['Discount']?['Name'] ?? 'Unknown Discount',
shopName: json['Discount']?['Shop']?['Name'] ?? 'Unknown Shop',
status: statusValue,
);
}
}

View File

@ -1,5 +1,3 @@
// lib/presentation/notification_preferences/bloc/notification_preferences_bloc.dart
import 'package:dio/dio.dart'; import 'package:dio/dio.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';

View File

@ -1,4 +1,3 @@
import 'package:flutter/material.dart'; 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';

View File

@ -1,5 +1,8 @@
// 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';
@ -24,7 +27,9 @@ 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/services/mqtt_service.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
class OffersPage extends StatefulWidget { class OffersPage extends StatefulWidget {
@ -36,35 +41,99 @@ class OffersPage extends StatefulWidget {
State<OffersPage> createState() => _OffersPageState(); State<OffersPage> createState() => _OffersPageState();
} }
class _OffersPageState extends State<OffersPage> { class _OffersPageState extends State<OffersPage> with SingleTickerProviderStateMixin {
List<String> _selectedCategories = []; List<String> _selectedCategories = [];
StreamSubscription? _locationServiceSubscription; StreamSubscription? _locationServiceSubscription;
StreamSubscription? _connectivitySubscription; StreamSubscription? _connectivitySubscription;
bool _isGpsEnabled = false; bool _isGpsEnabled = false;
bool _isConnectedToInternet = true; bool _isConnectedToInternet = true;
bool _isSearchingRandomly = false;
bool _showNotificationPanel = false;
final GlobalKey _notificationIconKey = GlobalKey();
late AnimationController _animationController;
late Animation<double> _animation;
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();
_fetchInitialReservations(); _fetchInitialReservations();
_fetchNotificationCount();
} }
@override @override
void dispose() { void dispose() {
_locationServiceSubscription?.cancel(); _locationServiceSubscription?.cancel();
_connectivitySubscription?.cancel(); _connectivitySubscription?.cancel();
_animationController.dispose();
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;
setState(() { setState(() {
_isConnectedToInternet = _isConnectedToInternet = !connectivityResult.contains(ConnectivityResult.none);
!connectivityResult.contains(ConnectivityResult.none);
}); });
} }
@ -85,7 +154,6 @@ class _OffersPageState extends State<OffersPage> {
void _listenToBackgroundService() { void _listenToBackgroundService() {
FlutterBackgroundService().on('update').listen((event) { FlutterBackgroundService().on('update').listen((event) {
if (event == null || event['offers'] == null) return; if (event == null || event['offers'] == null) return;
final data = event['offers']['data']; final data = event['offers']['data'];
if (data == null || data is! List) { if (data == null || data is! List) {
if (mounted) { if (mounted) {
@ -93,13 +161,8 @@ class _OffersPageState extends State<OffersPage> {
} }
return; return;
} }
try { try {
List<OfferModel> offers = data List<OfferModel> offers = data.whereType<Map<String, dynamic>>().map((json) => OfferModel.fromJson(json)).toList();
.whereType<Map<String, dynamic>>()
.map((json) => OfferModel.fromJson(json))
.toList();
if (mounted) { if (mounted) {
context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers)); context.read<OffersBloc>().add(OffersReceivedFromMqtt(offers));
} }
@ -111,29 +174,17 @@ class _OffersPageState extends State<OffersPage> {
} }
void _initConnectivityListener() { void _initConnectivityListener() {
_connectivitySubscription = _connectivitySubscription = Connectivity().onConnectivityChanged.listen((results) {
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(() { setState(() => _isConnectedToInternet = hasConnection);
_isConnectedToInternet = hasConnection;
});
if (hasConnection) { if (hasConnection) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('اتصال به اینترنت برقرار شد.'), backgroundColor: Colors.green));
const SnackBar( _fetchNotificationCount();
content: Text('اتصال به اینترنت برقرار شد.'),
backgroundColor: Colors.green,
),
);
} else { } else {
context.read<OffersBloc>().add(ClearOffers()); context.read<OffersBloc>().add(ClearOffers());
ScaffoldMessenger.of(context).showSnackBar( setState(() => _notificationCount = 0);
const SnackBar( ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('اتصال به اینترنت قطع شد.'), backgroundColor: Colors.red));
content: Text('اتصال به اینترنت قطع شد.'),
backgroundColor: Colors.red,
),
);
} }
} }
}); });
@ -145,21 +196,11 @@ class _OffersPageState extends State<OffersPage> {
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( final response = await dio.get(ApiConfig.baseUrl + ApiConfig.getReservations, options: Options(headers: {'Authorization': 'Bearer $token'}));
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 final List<String> reservedIds = reserves.map((reserveData) => (reserveData['Discount']['ID'] as String?) ?? '').where((id) => id.isNotEmpty).toList();
.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) {
@ -167,73 +208,69 @@ class _OffersPageState extends State<OffersPage> {
} }
} }
Future<void> _fetchNotificationCount() async {
if (!_isConnectedToInternet) return;
try {
const storage = FlutterSecureStorage();
final token = await storage.read(key: 'accessToken');
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 = _locationServiceSubscription = Geolocator.getServiceStatusStream().listen((status) {
Geolocator.getServiceStatusStream().listen((status) {
final isEnabled = status == ServiceStatus.enabled; final isEnabled = status == ServiceStatus.enabled;
if (mounted && _isGpsEnabled != isEnabled) { if (mounted && _isGpsEnabled != isEnabled) {
setState(() { setState(() => _isGpsEnabled = isEnabled);
_isGpsEnabled = isEnabled; if (!isEnabled) context.read<OffersBloc>().add(ClearOffers());
});
if (!isEnabled) {
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) { if (mounted) setState(() => _isGpsEnabled = status);
setState(() {
_isGpsEnabled = status;
});
}
} }
Future<void> _loadPreferences() async { Future<void> _loadPreferences() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final savedCategories = final savedCategories = prefs.getStringList('user_selected_categories') ?? [];
prefs.getStringList('user_selected_categories') ?? []; if (mounted) setState(() => _selectedCategories = savedCategories);
if (mounted) {
setState(() {
_selectedCategories = savedCategories;
});
}
} }
Future<void> _handleRefresh() { Future<void> _handleRefresh() {
final completer = Completer<void>(); final completer = Completer<void>();
final service = FlutterBackgroundService(); final service = FlutterBackgroundService();
final timeout = Timer(const Duration(seconds: 20), () { final timeout = Timer(const Duration(seconds: 20), () {
if (!completer.isCompleted) { if (!completer.isCompleted) {
completer.completeError('Request timed out.'); completer.completeError('Request timed out.');
if (mounted) { if (mounted) ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Request timed out. Please try again.')));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Request timed out. Please try again.')),
);
}
} }
}); });
final StreamSubscription<Map<String, dynamic>?> subscription = service.on('update').listen((event) {
final StreamSubscription<Map<String, dynamic>?> subscription = if (!completer.isCompleted) completer.complete();
service.on('update').listen((event) {
if (!completer.isCompleted) {
completer.complete();
}
}); });
completer.future.whenComplete(() { completer.future.whenComplete(() {
subscription.cancel(); subscription.cancel();
timeout.cancel(); timeout.cancel();
}); });
service.invoke('force_refresh'); service.invoke('force_refresh');
return completer.future; return completer.future;
} }
@ -246,40 +283,20 @@ class _OffersPageState extends State<OffersPage> {
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
const Text( const Text('دسته‌بندی‌های مورد علاقه شما', style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold)),
'دسته‌بندی‌های مورد علاقه شما',
style: TextStyle(fontSize: 19, fontWeight: FontWeight.bold),
),
TextButton( TextButton(
onPressed: () async { onPressed: () async {
final result = await Navigator.of(context).push<bool>( final result = await Navigator.of(context).push<bool>(MaterialPageRoute(builder: (context) => const NotificationPreferencesPage(loadFavoritesOnStart: true)));
MaterialPageRoute(
builder: (context) => const NotificationPreferencesPage(
loadFavoritesOnStart: true,
),
),
);
if (!mounted) return; if (!mounted) return;
context.read<NotificationPreferencesBloc>().add(ResetSubmissionStatus());
context
.read<NotificationPreferencesBloc>()
.add(ResetSubmissionStatus());
await _loadPreferences(); await _loadPreferences();
if (result == true) _handleRefresh();
if (result == true) {
_handleRefresh();
}
}, },
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( const Text('ویرایش', style: TextStyle(color: AppColors.active)),
'ویرایش',
style: TextStyle(color: AppColors.active),
),
], ],
), ),
), ),
@ -290,10 +307,7 @@ class _OffersPageState extends State<OffersPage> {
if (_selectedCategories.isEmpty) if (_selectedCategories.isEmpty)
const Padding( const Padding(
padding: EdgeInsets.only(bottom: 8.0), padding: EdgeInsets.only(bottom: 8.0),
child: Text( child: Text('شما هنوز دسته‌بندی مورد علاقه خود را انتخاب نکرده‌اید.', style: TextStyle(color: Colors.grey)),
'شما هنوز دسته‌بندی مورد علاقه خود را انتخاب نکرده‌اید.',
style: TextStyle(color: Colors.grey),
),
) )
else else
Wrap( Wrap(
@ -301,14 +315,8 @@ class _OffersPageState extends State<OffersPage> {
runSpacing: 8.0, runSpacing: 8.0,
children: _selectedCategories.map((category) { children: _selectedCategories.map((category) {
return Container( return Container(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
horizontal: 12.0, decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(20.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(),
@ -327,15 +335,37 @@ class _OffersPageState extends State<OffersPage> {
backgroundColor: Colors.white, backgroundColor: Colors.white,
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
title: Padding( title: Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
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: [
Stack(
alignment: Alignment.center,
children: [
IconButton( IconButton(
onPressed: () {}, icon: Assets.icons.notification.svg()), key: _notificationIconKey,
onPressed: _toggleNotificationPanel,
icon: Assets.icons.notification.svg(),
),
if (_notificationCount > 0)
Positioned(
top: 0,
right: 2,
child: GestureDetector(
onTap: _toggleNotificationPanel,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(color: Colors.red, shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.5)),
constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
child: Padding(
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),
),
),
),
),
],
),
BlocBuilder<ReservationCubit, ReservationState>( BlocBuilder<ReservationCubit, ReservationState>(
builder: (context, state) { builder: (context, state) {
final reservedCount = state.reservedProductIds.length; final reservedCount = state.reservedProductIds.length;
@ -343,13 +373,11 @@ class _OffersPageState extends State<OffersPage> {
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
IconButton( IconButton(
onPressed: () { onPressed: () => Navigator.of(context).push(PageRouteBuilder(
Navigator.of(context).push( pageBuilder: (context, animation, secondaryAnimation) => const ReservedListPage(),
MaterialPageRoute( transitionsBuilder: (context, animation, secondaryAnimation, child) =>
builder: (_) => const ReservedListPage(), SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.horizontal, child: child),
), )),
);
},
icon: Assets.icons.scanBarcode.svg(), icon: Assets.icons.scanBarcode.svg(),
), ),
if (reservedCount > 0) if (reservedCount > 0)
@ -357,36 +385,18 @@ class _OffersPageState extends State<OffersPage> {
top: 0, top: 0,
right: 2, right: 2,
child: GestureDetector( child: GestureDetector(
onTap: () { onTap: () => Navigator.of(context).push(PageRouteBuilder(
Navigator.of(context).push( pageBuilder: (context, animation, secondaryAnimation) => const ReservedListPage(),
MaterialPageRoute( transitionsBuilder: (context, animation, secondaryAnimation, child) =>
builder: (_) => const ReservedListPage(), SharedAxisTransition(animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.horizontal, child: child),
), )),
);
},
child: Container( child: Container(
padding: const EdgeInsets.all(4), padding: const EdgeInsets.all(4),
decoration: BoxDecoration( decoration: BoxDecoration(color: Colors.green, shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 1.5)),
color: Colors.green, constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
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( child: Text('$reservedCount', style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.bold), textAlign: TextAlign.center),
'$reservedCount',
style: const TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
), ),
), ),
), ),
@ -398,7 +408,9 @@ class _OffersPageState extends State<OffersPage> {
const SizedBox(width: 8), const SizedBox(width: 8),
], ],
), ),
body: RefreshIndicator( body: Stack(
children: [
RefreshIndicator(
onRefresh: _handleRefresh, onRefresh: _handleRefresh,
child: SingleChildScrollView( child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
@ -410,12 +422,83 @@ class _OffersPageState extends State<OffersPage> {
isGpsEnabled: _isGpsEnabled, isGpsEnabled: _isGpsEnabled,
isConnectedToInternet: _isConnectedToInternet, isConnectedToInternet: _isConnectedToInternet,
selectedCategories: _selectedCategories, 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,
),
),
),
),
),
),
],
);
},
); );
} }
} }
@ -424,12 +507,16 @@ class OffersView extends StatelessWidget {
final bool isGpsEnabled; final bool isGpsEnabled;
final bool isConnectedToInternet; final bool isConnectedToInternet;
final List<String> selectedCategories; 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.selectedCategories,
required this.onRandomSearch,
required this.isSearchingRandomly,
}); });
@override @override
@ -463,9 +550,7 @@ class OffersView extends StatelessWidget {
if (state is OffersLoadSuccess) { if (state is OffersLoadSuccess) {
final filteredOffers = selectedCategories.isEmpty final filteredOffers = selectedCategories.isEmpty
? state.offers ? state.offers
: state.offers : state.offers.where((offer) => selectedCategories.contains(offer.category)).toList();
.where((offer) => selectedCategories.contains(offer.category))
.toList();
if (filteredOffers.isEmpty) { if (filteredOffers.isEmpty) {
return const SizedBox( return const SizedBox(
@ -482,10 +567,7 @@ class OffersView extends StatelessWidget {
); );
} }
final groupedOffers = groupBy( final groupedOffers = groupBy(filteredOffers, (OfferModel offer) => offer.category);
filteredOffers,
(OfferModel offer) => offer.category,
);
final categories = groupedOffers.keys.toList(); final categories = groupedOffers.keys.toList();
return ListView.builder( return ListView.builder(
@ -496,12 +578,10 @@ 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)
return CategoryOffersRow( .animate()
categoryTitle: category, .fade(duration: 500.ms)
offers: offersForCategory, .slideY(begin: 0.3, duration: 400.ms, curve: Curves.easeOut);
).animate().fade(duration: 500.ms).slideY(
begin: 0.3, duration: 400.ms, curve: Curves.easeOut);
}, },
); );
} }
@ -536,25 +616,33 @@ 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( padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 125),
vertical: 12, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
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),
const Text('جست‌وجوی تصادفی'), InkWell(
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('جست‌وجوی تصادفی'),
),
),
], ],
), ),
), ),
@ -571,18 +659,29 @@ 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( const Text("اتصال به اینترنت برقرار نیست", style: TextStyle(fontSize: 18, color: Colors.grey)),
"اتصال به اینترنت برقرار نیست",
style: TextStyle(fontSize: 18, color: Colors.grey),
),
const SizedBox(height: 10), const SizedBox(height: 10),
const Text( const Text("لطفاً اتصال خود را بررسی کرده و دوباره تلاش کنید.", style: TextStyle(color: Colors.grey)),
"لطفاً اتصال خود را بررسی کرده و دوباره تلاش کنید.",
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

@ -198,19 +198,15 @@ class _ProductDetailViewState extends State<ProductDetailView> {
} }
Future<List<CommentModel>> _fetchComments() async { Future<List<CommentModel>> _fetchComments() async {
// 1. توکن را از حافظه امن بخوان
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
final token = await storage.read(key: 'accessToken'); final token = await storage.read(key: 'accessToken');
// 2. اگر توکن وجود نداشت، خطا برگردان
// هرچند کاربر لاگین نکرده معمولا به این صفحه دسترسی ندارد
if (token == null) { if (token == null) {
throw Exception('Authentication token not found!'); throw Exception('Authentication token not found!');
} }
try { try {
final dio = Dio(); final dio = Dio();
// 3. هدر Authorization را به درخواست اضافه کن
final response = await dio.get( final response = await dio.get(
ApiConfig.baseUrl + ApiConfig.getComments + widget.offer.id, ApiConfig.baseUrl + ApiConfig.getComments + widget.offer.id,
options: Options(headers: {'Authorization': 'Bearer $token'}), options: Options(headers: {'Authorization': 'Bearer $token'}),
@ -220,11 +216,9 @@ class _ProductDetailViewState extends State<ProductDetailView> {
final List<dynamic> commentsJson = response.data['data']['comments']; final List<dynamic> commentsJson = response.data['data']['comments'];
return commentsJson.map((json) => CommentModel.fromJson(json)).toList(); return commentsJson.map((json) => CommentModel.fromJson(json)).toList();
} else { } else {
// خطاهای دیگر سرور
throw Exception('Failed to load comments with status code: ${response.statusCode}'); throw Exception('Failed to load comments with status code: ${response.statusCode}');
} }
} on DioException catch (e) { } on DioException catch (e) {
// چاپ خطای کامل Dio برای دیباگ بهتر
debugPrint("DioException fetching comments: $e"); debugPrint("DioException fetching comments: $e");
if (e.response != null) { if (e.response != null) {
debugPrint("Response data: ${e.response?.data}"); debugPrint("Response data: ${e.response?.data}");
@ -235,7 +229,6 @@ class _ProductDetailViewState extends State<ProductDetailView> {
throw Exception('An unknown error occurred: $e'); throw Exception('An unknown error occurred: $e');
} }
} }
// ############ END: FIX SECTION ############
void _launchMaps(double lat, double lon, String title) { void _launchMaps(double lat, double lon, String title) {
MapsLauncher.launchCoordinates(lat, lon, title); MapsLauncher.launchCoordinates(lat, lon, title);
@ -408,19 +401,6 @@ class _ProductDetailViewState extends State<ProductDetailView> {
), ),
); );
}, },
child: Container(
width: 90,
height: 90,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey.shade400, width: 1.5),
),
child: Padding(
padding: const EdgeInsets.all(9.0),
child: SvgPicture.asset(Assets.icons.addImg.path),
),
),
); );
} }
@ -686,7 +666,7 @@ class _ProductDetailViewState extends State<ProductDetailView> {
slideDirection: SlideDirection.up, slideDirection: SlideDirection.up,
separator: ':', separator: ':',
style: const TextStyle( style: const TextStyle(
fontSize: 50, fontSize: 45,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: AppColors.countdown, color: AppColors.countdown,
), ),
@ -720,12 +700,7 @@ class _ProductDetailViewState extends State<ProductDetailView> {
return Center(child: Text('خطا در بارگذاری نظرات. لطفاً صفحه را رفرش کنید.')); return Center(child: Text('خطا در بارگذاری نظرات. لطفاً صفحه را رفرش کنید.'));
} }
if (!snapshot.hasData || snapshot.data!.isEmpty) { if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center( return SizedBox();
child: Padding(
padding: EdgeInsets.symmetric(vertical: 32.0),
child: Text('هنوز نظری برای این تخفیف ثبت نشده است.'),
),
);
} }
return CommentsSection(comments: snapshot.data!); return CommentsSection(comments: snapshot.data!);
}, },

View File

@ -0,0 +1,253 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.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/data/models/notification_model.dart';
import 'package:proxibuy/presentation/offer/bloc/offer_bloc.dart';
import 'package:proxibuy/presentation/offer/bloc/offer_state.dart';
import 'package:proxibuy/presentation/pages/product_detail_page.dart';
class NotificationPanel extends StatefulWidget {
final VoidCallback onClose;
const NotificationPanel({super.key, required this.onClose});
@override
State<NotificationPanel> createState() => _NotificationPanelState();
}
class _NotificationPanelState extends State<NotificationPanel> {
List<NotificationModel> _notifications = [];
bool _isLoading = true;
String _errorMessage = '';
final Dio _dio = Dio();
final FlutterSecureStorage _storage = const FlutterSecureStorage();
@override
void initState() {
super.initState();
_fetchNotifications();
}
Future<void> _fetchNotifications() async {
final token = await _storage.read(key: 'accessToken');
if (token == null) {
if (mounted) {
setState(() {
_isLoading = false;
_errorMessage = 'برای مشاهده اعلان‌ها، لطفا ابتدا وارد شوید.';
});
}
return;
}
try {
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(() {
_notifications = data.map((json) => NotificationModel.fromJson(json)).toList();
_isLoading = false;
});
} else {
setState(() {
_isLoading = false;
_errorMessage = 'خطا در دریافت اطلاعات.';
});
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
_errorMessage = 'اتصال به سرور برقرار نشد.';
});
}
}
}
Future<void> _ignoreNotification(String notificationId) async {
final token = await _storage.read(key: 'accessToken');
if (token == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('خطا: شما وارد حساب کاربری نشده‌اید.')),
);
return;
}
try {
final response = await _dio.get(
'${ApiConfig.baseUrl}/notify/ignore/$notificationId',
options: Options(headers: {'Authorization': 'Bearer $token'}),
);
if (response.statusCode == 200 && mounted) {
setState(() {
_notifications.removeWhere((n) => n.id == notificationId);
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(response.data['message'] ?? 'خطا در حذف اعلان.')),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('خطا در ارتباط با سرور.')),
);
print(e.toString());
}
}
}
String _formatTimeAgo(DateTime dateTime) {
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inSeconds < 60) {
return 'همین الان';
} else if (difference.inMinutes < 60) {
return '${difference.inMinutes} دقیقه قبل';
} else if (difference.inHours < 24) {
return '${difference.inHours} ساعت قبل';
} else if (difference.inDays < 7) {
return '${difference.inDays} روز قبل';
} else {
return DateFormat('yyyy/MM/dd', 'fa').format(dateTime);
}
}
void _navigateToOffer(NotificationModel notification) {
if (!notification.status) return;
final offersState = context.read<OffersBloc>().state;
if (offersState is OffersLoadSuccess) {
try {
final offer = offersState.offers.firstWhere((o) => o.id == notification.discountId);
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => ProductDetailPage(offer: offer),
),
);
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('این تخفیف در حال حاضر در دسترس نیست.')),
);
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('اطلاعات تخفیف‌ها هنوز بارگذاری نشده است.')),
);
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: _buildBody(),
),
],
);
}
Widget _buildBody() {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(_errorMessage, textAlign: TextAlign.center),
),
);
}
if (_notifications.isEmpty) {
return const Center(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Text('هیچ اعلانی برای نمایش وجود ندارد.', textAlign: TextAlign.center),
),
);
}
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 0.0),
itemCount: _notifications.length,
itemBuilder: (context, index) {
return _buildNotificationCard(_notifications[index]);
},
);
}
Widget _buildNotificationCard(NotificationModel notification) {
final bool isExpired = !notification.status;
final Color textColor = isExpired ? Colors.grey.shade600 : Colors.black;
return Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
notification.description,
style: TextStyle(fontSize: 15, height: 1.6, color: textColor),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_formatTimeAgo(notification.createdAt.toLocal()),
style: TextStyle(color: Colors.grey.shade600, fontSize: 12),
),
if (isExpired)
ElevatedButton(
onPressed: null,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey.shade300,
foregroundColor: Colors.grey.shade700,
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
padding: const EdgeInsets.symmetric(horizontal: 16),
),
child: const Text('تخفیف تمام شد'),
)
else
Row(
children: [
TextButton(
onPressed: () => _ignoreNotification(notification.id),
style: TextButton.styleFrom(foregroundColor: Colors.red.shade700),
child: const Text('بیخیال'),
),
const SizedBox(width: 4),
ElevatedButton(
onPressed: () => _navigateToOffer(notification),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.backgroundConfirm,
foregroundColor: AppColors.selectedImg,
side: BorderSide(color: Colors.green.shade200),
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
padding: const EdgeInsets.symmetric(horizontal: 16),
),
child: const Text('بزن بریم'),
),
],
),
],
),
],
),
);
}
}

View File

@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
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:mqtt_client/mqtt_client.dart'; import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart'; import 'package:mqtt_client/mqtt_server_client.dart';
@ -23,7 +24,9 @@ class MqttService {
} }
Future<void> connect(String token) async { Future<void> connect(String token) async {
final String clientId = 'nest-' + Random().nextInt(0xFFFFFF).toRadixString(16).padLeft(6, '0'); const storage = FlutterSecureStorage();
final userID = await storage.read(key: 'userID');
final String clientId = userID ?? 'proxibuy';
final String username = 'ignored'; final String username = 'ignored';
final String password = token; final String password = token;

View File

@ -33,6 +33,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.4.5" version: "7.4.5"
animations:
dependency: "direct main"
description:
name: animations
sha256: d3d6dcfb218225bbe68e87ccf6378bbb2e32a94900722c5f81611dad089911cb
url: "https://pub.dev"
source: hosted
version: "2.0.11"
archive: archive:
dependency: transitive dependency: transitive
description: description:
@ -1445,6 +1453,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.0" version: "3.0.0"
skeletons:
dependency: "direct main"
description:
name: skeletons
sha256: "5b2d08ae7f908ee1f7007ca99f8dcebb4bfc1d3cb2143dec8d112a5be5a45c8f"
url: "https://pub.dev"
source: hosted
version: "0.0.3"
sky_engine: sky_engine:
dependency: transitive dependency: transitive
description: flutter description: flutter

View File

@ -69,6 +69,8 @@ dependencies:
firebase_messaging: ^15.2.10 firebase_messaging: ^15.2.10
firebase_crashlytics: ^4.3.10 firebase_crashlytics: ^4.3.10
flutter_rating_bar: ^4.0.1 flutter_rating_bar: ^4.0.1
animations: ^2.0.11
skeletons: ^0.0.3
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: