Deploy: 2026-05-25 00:29:42

This commit is contained in:
Hamza-Ayed
2026-05-25 00:29:42 +03:00
parent b20f457eaf
commit 7359206eb3
14 changed files with 1126 additions and 213 deletions

View File

@@ -42,4 +42,13 @@ class ApiConstants {
// English: The endpoint to approve a pending company subscription.
// Arabic: نقطة النهاية للموافقة على اشتراك معلق للشركة.
static const String approveBillingEndpoint = '/admin/companies/approve-billing';
// English: The endpoint to list connected Meta sessions.
static const String metaSessionsEndpoint = '/meta/sessions';
// English: The endpoint to connect a new Meta channel session.
static const String metaConnectEndpoint = '/meta/sessions/connect';
// English: The endpoint to disconnect a Meta channel session.
static const String metaDisconnectEndpoint = '/meta/sessions';
}

View File

@@ -176,4 +176,52 @@ class ApiService {
}),
);
}
// English: Fetch Meta sessions connection status.
Future<http.Response> getMetaSessions(String token) async {
final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaSessionsEndpoint}');
return await _client.get(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
},
);
}
// English: Connect a new Facebook page or Instagram channel.
Future<http.Response> connectMetaSession(String token, String channelType, String pageId, String pageName, String pageAccessToken) async {
final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaConnectEndpoint}');
return await _client.post(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
},
body: jsonEncode({
'channel_type': channelType,
'page_id': pageId,
'page_name': pageName,
'page_access_token': pageAccessToken,
}),
);
}
// English: Disconnect a Meta page or Instagram channel.
Future<http.Response> disconnectMetaSession(String token, int sessionId) async {
final url = Uri.parse('${ApiConstants.baseUrl}${ApiConstants.metaDisconnectEndpoint}');
return await _client.delete(
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
},
body: jsonEncode({
'session_id': sessionId,
}),
);
}
}

View File

@@ -6,6 +6,7 @@ import 'models/contact_model.dart';
import 'models/plan_model.dart';
import 'models/super_admin_stats_model.dart';
import 'models/whatsapp_status_model.dart';
import 'models/meta_session_model.dart';
class DashboardRepository {
final ApiService _apiService = ApiService();
@@ -157,4 +158,42 @@ class DashboardRepository {
throw Exception(error);
}
}
// English: Load connected Meta sessions.
Future<List<MetaSessionModel>> getMetaSessions() async {
final token = await _getToken();
final response = await _apiService.getMetaSessions(token);
if (response.statusCode == 200) {
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
final list = decoded['data'] as List<dynamic>? ?? [];
return list.map((item) => MetaSessionModel.fromJson(item as Map<String, dynamic>)).toList();
} else {
throw Exception('فشل في جلب جلسات ميتا المتصلة');
}
}
// English: Connect a new Facebook Page or Instagram channel.
Future<void> connectMetaSession(String channelType, String pageId, String pageName, String pageAccessToken) async {
final token = await _getToken();
final response = await _apiService.connectMetaSession(token, channelType, pageId, pageName, pageAccessToken);
if (response.statusCode != 200) {
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
final error = decoded['message'] as String? ?? 'فشل في ربط القناة';
throw Exception(error);
}
}
// English: Disconnect a Meta page or Instagram channel.
Future<void> disconnectMetaSession(int sessionId) async {
final token = await _getToken();
final response = await _apiService.disconnectMetaSession(token, sessionId);
if (response.statusCode != 200) {
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
final error = decoded['message'] as String? ?? 'فشل في قطع اتصال القناة';
throw Exception(error);
}
}
}

View File

@@ -0,0 +1,48 @@
// English: Model representing a connected Meta session (Facebook Page or Instagram Business Profile)
class MetaSessionModel {
final int id;
final int companyId;
final String channelType;
final String pageId;
final String pageName;
final String status;
final String? createdAt;
final String? updatedAt;
MetaSessionModel({
required this.id,
required this.companyId,
required this.channelType,
required this.pageId,
required this.pageName,
required this.status,
this.createdAt,
this.updatedAt,
});
factory MetaSessionModel.fromJson(Map<String, dynamic> json) {
return MetaSessionModel(
id: json['id'] as int,
companyId: json['company_id'] as int,
channelType: json['channel_type'] as String,
pageId: json['page_id'] as String,
pageName: json['page_name'] as String,
status: json['status'] as String,
createdAt: json['created_at'] as String?,
updatedAt: json['updated_at'] as String?,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'company_id': companyId,
'channel_type': channelType,
'page_id': pageId,
'page_name': pageName,
'status': status,
'created_at': createdAt,
'updated_at': updatedAt,
};
}
}

View File

@@ -30,7 +30,12 @@ class DashboardCubit extends Cubit<DashboardState> {
switch (tab) {
case DashboardTab.whatsapp:
final status = await _repository.getWhatsAppStatus();
emit(state.copyWith(whatsappStatus: status, isLoading: false));
final meta = await _repository.getMetaSessions();
emit(state.copyWith(
whatsappStatus: status,
metaSessions: meta,
isLoading: false,
));
break;
case DashboardTab.billing:
final plans = await _repository.getPlans();
@@ -123,4 +128,30 @@ class DashboardCubit extends Cubit<DashboardState> {
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
}
}
// English: Connect a Facebook Page or Instagram channel and refresh sessions.
Future<void> connectMetaSession(String channelType, String pageId, String pageName, String pageAccessToken) async {
emit(state.copyWith(isLoading: true));
try {
await _repository.connectMetaSession(channelType, pageId, pageName, pageAccessToken);
final meta = await _repository.getMetaSessions();
emit(state.copyWith(metaSessions: meta, isLoading: false));
} catch (e) {
final cleanMsg = e.toString().replaceAll('Exception: ', '');
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
}
}
// English: Disconnect a Meta page/profile connection and refresh sessions.
Future<void> disconnectMetaSession(int sessionId) async {
emit(state.copyWith(isLoading: true));
try {
await _repository.disconnectMetaSession(sessionId);
final meta = await _repository.getMetaSessions();
emit(state.copyWith(metaSessions: meta, isLoading: false));
} catch (e) {
final cleanMsg = e.toString().replaceAll('Exception: ', '');
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
}
}
}

View File

@@ -4,6 +4,7 @@ import '../../data/models/contact_model.dart';
import '../../data/models/plan_model.dart';
import '../../data/models/super_admin_stats_model.dart';
import '../../data/models/whatsapp_status_model.dart';
import '../../data/models/meta_session_model.dart';
// English: Enum representing the 9 tabs in the Nabeh web/mobile dashboard.
// Arabic: قائمة تعداد تمثل الأبواب التسعة في لوحة تحكم نبيه على الويب والهاتف.
@@ -39,6 +40,7 @@ class DashboardState extends Equatable {
final List<ContactModel> contacts;
final List<ChatbotRuleModel> chatbotRules;
final SuperAdminStatsModel? superAdminStats;
final List<MetaSessionModel> metaSessions;
const DashboardState({
required this.activeTab,
@@ -49,6 +51,7 @@ class DashboardState extends Equatable {
this.contacts = const [],
this.chatbotRules = const [],
this.superAdminStats,
this.metaSessions = const [],
});
// English: Helper copyWith constructor to copy immutable state data safely.
@@ -62,6 +65,7 @@ class DashboardState extends Equatable {
List<ContactModel>? contacts,
List<ChatbotRuleModel>? chatbotRules,
SuperAdminStatsModel? superAdminStats,
List<MetaSessionModel>? metaSessions,
}) {
return DashboardState(
activeTab: activeTab ?? this.activeTab,
@@ -72,6 +76,7 @@ class DashboardState extends Equatable {
contacts: contacts ?? this.contacts,
chatbotRules: chatbotRules ?? this.chatbotRules,
superAdminStats: superAdminStats ?? this.superAdminStats,
metaSessions: metaSessions ?? this.metaSessions,
);
}
@@ -85,5 +90,6 @@ class DashboardState extends Equatable {
contacts,
chatbotRules,
superAdminStats,
metaSessions,
];
}

View File

@@ -10,7 +10,7 @@ import '../widgets/chatbot_view.dart';
import '../widgets/contacts_view.dart';
import '../widgets/simple_placeholder_view.dart';
import '../widgets/super_admin_view.dart';
import '../widgets/whatsapp_view.dart';
import '../widgets/channels_view.dart';
class DashboardScreen extends StatelessWidget {
final UserModel user;
@@ -99,10 +99,10 @@ class DashboardScreen extends StatelessWidget {
),
_buildDrawerItem(
context,
'📱 اتصال الواتساب',
'📱 قنوات الاتصال',
DashboardTab.whatsapp,
state.activeTab,
Icons.phone_android,
Icons.contact_mail_outlined,
),
_buildDrawerItem(
context,
@@ -228,7 +228,7 @@ class DashboardScreen extends StatelessWidget {
case DashboardTab.superAdmin:
return 'المشرف العام - نبيه';
case DashboardTab.whatsapp:
return 'اتصال الواتساب';
return 'قنوات الاتصال';
case DashboardTab.billing:
return 'الباقات والاشتراكات';
case DashboardTab.contacts:
@@ -251,8 +251,9 @@ class DashboardScreen extends StatelessWidget {
case DashboardTab.superAdmin:
return SuperAdminView(stats: state.superAdminStats);
case DashboardTab.whatsapp:
return WhatsAppView(
status: state.whatsappStatus,
return ChannelsView(
whatsappStatus: state.whatsappStatus,
metaSessions: state.metaSessions,
onRefresh: () => context.read<DashboardCubit>().refreshCurrentTab(),
);
case DashboardTab.billing:

View File

@@ -0,0 +1,466 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/whatsapp_status_model.dart';
import '../../data/models/meta_session_model.dart';
import '../cubit/dashboard_cubit.dart';
class ChannelsView extends StatefulWidget {
final WhatsAppStatusModel? whatsappStatus;
final List<MetaSessionModel> metaSessions;
final VoidCallback onRefresh;
const ChannelsView({
super.key,
required this.whatsappStatus,
required this.metaSessions,
required this.onRefresh,
});
@override
State<ChannelsView> createState() => _ChannelsViewState();
}
class _ChannelsViewState extends State<ChannelsView> with SingleTickerProviderStateMixin {
late TabController _tabController;
@override
void initState() {
_tabController = TabController(length: 3, vsync: this);
super.initState();
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
// English: Open confirmation dialog to disconnect WhatsApp.
void _showWhatsAppDisconnectDialog(BuildContext context) {
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: const Text('قطع اتصال الواتساب', style: TextStyle(color: Colors.white)),
content: const Text(
'هل أنت متأكد من رغبتك في قطع اتصال الواتساب؟ سيؤدي ذلك إلى تعطيل الردود التلقائية لعملاء الواتساب.',
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().disconnectWhatsApp();
},
child: const Text('نعم، اقطع الاتصال', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
// English: Open confirmation dialog to disconnect a Meta session.
void _showMetaDisconnectDialog(BuildContext context, MetaSessionModel session) {
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: Text(
session.channelType == 'messenger' ? 'قطع اتصال ماسنجر' : 'قطع اتصال إنستغرام',
style: const TextStyle(color: Colors.white),
),
content: Text(
'هل أنت متأكد من رغبتك في قطع الاتصال عن ${session.pageName}؟',
style: const TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().disconnectMetaSession(session.id);
},
child: const Text('نعم، اقطع الاتصال', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
// English: Show connect dialog for Facebook Page or Instagram Business Account.
void _showConnectMetaDialog(BuildContext context, String type) {
final pageNameController = TextEditingController();
final pageIdController = TextEditingController();
final tokenController = TextEditingController();
final formKey = GlobalKey<FormState>();
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: Text(
type == 'messenger' ? 'ربط صفحة فيسبوك' : 'ربط حساب إنستغرام',
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
content: Form(
key: formKey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: pageNameController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: type == 'messenger' ? 'اسم الصفحة' : 'اسم الحساب',
labelStyle: const TextStyle(color: Colors.white60),
enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال الاسم' : null,
),
const SizedBox(height: 12),
TextFormField(
controller: pageIdController,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
labelText: type == 'messenger' ? 'معرّف الصفحة (Page ID)' : 'معرّف الحساب (Account ID)',
labelStyle: const TextStyle(color: Colors.white60),
enabledBorder: const UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال المعرّف' : null,
),
const SizedBox(height: 12),
TextFormField(
controller: tokenController,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
labelText: 'رمز الوصول للصفحة (Access Token)',
labelStyle: TextStyle(color: Colors.white60),
enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.white30)),
),
validator: (v) => (v == null || v.isEmpty) ? 'الرجاء إدخال رمز الوصول' : null,
),
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.purpleAccent),
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.pop(dialogContext);
context.read<DashboardCubit>().connectMetaSession(
type,
pageIdController.text.trim(),
pageNameController.text.trim(),
tokenController.text.trim(),
);
}
},
child: const Text('ربط وتفعيل'),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// English: Channel selector TabBar.
Container(
color: const Color(0xFF15102A),
child: TabBar(
controller: _tabController,
indicatorColor: Colors.purpleAccent,
labelColor: Colors.purpleAccent,
unselectedLabelColor: Colors.white60,
tabs: const [
Tab(icon: Icon(Icons.phone_android), text: 'واتساب'),
Tab(icon: Icon(Icons.facebook), text: 'فيسبوك ماسنجر'),
Tab(icon: Icon(Icons.camera_alt), text: 'إنستغرام'),
],
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: TabBarView(
controller: _tabController,
children: [
_buildWhatsAppTab(),
_buildMetaTab('messenger'),
_buildMetaTab('instagram'),
],
),
),
],
);
}
Widget _buildWhatsAppTab() {
final session = widget.whatsappStatus;
return SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'📱 إعدادات اتصال الواتساب',
style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
const Text(
'اربط حسابك مع بوابة واتساب لتفعيل الردود التلقائية وروبوت خدمة العملاء.',
style: TextStyle(color: Colors.white60, fontSize: 12),
),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF15102A),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.05)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('حالة الجلسة الحالية', style: TextStyle(color: Colors.white70, fontSize: 14)),
_buildWhatsAppStatusBadge(session?.status ?? 'disconnected'),
],
),
const Divider(color: Colors.white10, height: 24),
_buildDetailsRow('اسم الجلسة', session?.name ?? 'WhatsApp Team'),
_buildDetailsRow('مفتاح التعريف', session?.sessionKey ?? 'لا يوجد'),
if (session?.phone != null) _buildDetailsRow('رقم الهاتف المرتبط', session!.phone!),
const SizedBox(height: 20),
if (session == null || session.status == 'disconnected') ...[
const Text(
'⚠️ الحساب غير متصل. يرجى توليد رمز الاستجابة السريعة ومسحه ضوئياً لتفعيل الخدمة.',
style: TextStyle(color: Colors.orangeAccent, fontSize: 12),
),
const SizedBox(height: 20),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purpleAccent,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.qr_code_scanner),
label: const Text('توليد رمز الاستجابة QR'),
onPressed: () {
context.read<DashboardCubit>().requestWhatsAppQr();
},
),
] else if (session.status == 'waiting_qr') ...[
const Text(
'🔍 رمز الاستجابة جاهز. افتح الواتساب واختر الأجهزة المرتبطة لمسح الرمز:',
style: TextStyle(color: Colors.yellowAccent, fontSize: 12),
),
const SizedBox(height: 20),
Center(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.qr_code_2, size: 180, color: Colors.black),
),
),
const SizedBox(height: 20),
] else if (session.status == 'connected') ...[
const Text(
'✅ الحساب متصل وجاهز للعمل. الردود التلقائية وروبوت خدمة العملاء نشطان.',
style: TextStyle(color: Colors.greenAccent, fontSize: 12),
),
const SizedBox(height: 20),
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.redAccent,
side: const BorderSide(color: Colors.redAccent),
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.link_off),
label: const Text('قطع الاتصال'),
onPressed: () => _showWhatsAppDisconnectDialog(context),
),
],
],
),
),
],
),
);
}
Widget _buildMetaTab(String type) {
final filtered = widget.metaSessions.where((s) => s.channelType == type).toList();
final title = (type == 'messenger') ? 'فيسبوك ماسنجر' : 'إنستغرام الأعمال';
final desc = (type == 'messenger')
? 'اربط صفحات فيسبوك الخاصة بك لتفعيل الرد الآلي والمحادثات مع العملاء.'
: 'اربط حسابات إنستغرام للأعمال لتفعيل روبوت المحادثة المخصص.';
return SingleChildScrollView(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'💬 إعدادات $title',
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
Text(
desc,
style: const TextStyle(color: Colors.white60, fontSize: 12),
),
],
),
],
),
const SizedBox(height: 20),
if (filtered.isEmpty) ...[
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: const Color(0xFF15102A),
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
Icon(type == 'messenger' ? Icons.facebook : Icons.camera_alt, size: 48, color: Colors.white30),
const SizedBox(height: 12),
const Text('لا توجد قنوات مرتبطة حالياً', style: TextStyle(color: Colors.white70, fontSize: 14)),
const SizedBox(height: 16),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purpleAccent,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
icon: const Icon(Icons.add),
label: Text('ربط قناة $title new'),
onPressed: () => _showConnectMetaDialog(context, type),
),
],
),
),
] else ...[
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: filtered.length,
itemBuilder: (context, index) {
final item = filtered[index];
return Card(
color: const Color(0xFF15102A),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
margin: const EdgeInsets.only(bottom: 12),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.purpleAccent.withOpacity(0.1),
child: Icon(type == 'messenger' ? Icons.messenger_outline : Icons.camera_alt, color: Colors.purpleAccent),
),
title: Text(item.pageName, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
subtitle: Text('ID: ${item.pageId}', style: const TextStyle(color: Colors.white60, fontSize: 12)),
trailing: IconButton(
icon: const Icon(Icons.delete_outline, color: Colors.redAccent),
onPressed: () => _showMetaDisconnectDialog(context, item),
),
),
);
},
),
const SizedBox(height: 16),
Center(
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.purpleAccent,
side: const BorderSide(color: Colors.purpleAccent),
),
icon: const Icon(Icons.add),
label: const Text('ربط صفحة إضافية'),
onPressed: () => _showConnectMetaDialog(context, type),
),
),
],
],
),
);
}
Widget _buildDetailsRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(color: Colors.white70, fontSize: 13)),
Text(value, style: const TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.bold)),
],
),
);
}
Widget _buildWhatsAppStatusBadge(String status) {
Color color;
String text;
switch (status) {
case 'connected':
color = Colors.green;
text = 'متصل';
break;
case 'waiting_qr':
color = Colors.orange;
text = 'بانتظار المسح';
break;
case 'connecting':
color = Colors.blue;
text = 'جاري الاتصال';
break;
default:
color = Colors.red;
text = 'غير متصل';
break;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: color),
),
child: Text(text, style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.bold)),
);
}
}

View File

@@ -1,206 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/models/whatsapp_status_model.dart';
import '../cubit/dashboard_cubit.dart';
class WhatsAppView extends StatelessWidget {
final WhatsAppStatusModel? status;
final VoidCallback onRefresh;
const WhatsAppView({
super.key,
required this.status,
required this.onRefresh,
});
// English: Show a confirmation dialog before disconnecting.
// Arabic: عرض مربع حوار تأكيدي قبل قطع الاتصال لتجنب الإجراء المفاجئ.
void _showDisconnectDialog(BuildContext context) {
showDialog(
context: context,
builder: (dialogContext) {
return AlertDialog(
backgroundColor: const Color(0xFF15102A),
title: const Text('قطع اتصال الواتساب', style: TextStyle(color: Colors.white)),
content: const Text(
'هل أنت متأكد من رغبتك في قطع الاتصال؟ سيؤدي ذلك إلى تعطيل روبوت خدمة العملاء والردود التلقائية.',
style: TextStyle(color: Colors.white70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('إلغاء', style: TextStyle(color: Colors.white60)),
),
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
// English: Dispatch disconnectWhatsApp command to DashboardCubit.
// Arabic: استدعاء أمر قطع اتصال الواتساب في الكيوبيت.
context.read<DashboardCubit>().disconnectWhatsApp();
},
child: const Text('نعم، اقطع الاتصال', style: TextStyle(color: Colors.redAccent)),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
final session = status;
return Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'📱 إعدادات اتصال الواتساب',
style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'اربط حسابك مع بوابة واتساب التابعة لنظام نبيه لتفعيل الردود التلقائية والتحقق.',
style: TextStyle(color: Colors.white60, fontSize: 13),
),
const SizedBox(height: 24),
// English: Display WhatsApp connection card containing session and status.
// Arabic: عرض بطاقة اتصال الواتساب التي تحتوي على الجلسة والحالة.
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF15102A),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withOpacity(0.05)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'حالة الجلسة الحالية',
style: TextStyle(color: Colors.white70, fontSize: 14),
),
_buildStatusBadge(session?.status ?? 'disconnected'),
],
),
const Divider(color: Colors.white10, height: 24),
_buildRow('اسم الجلسة', session?.name ?? 'WhatsApp Team'),
_buildRow('مفتاح التعريف', session?.sessionKey ?? 'لا يوجد'),
if (session?.phone != null) _buildRow('رقم الهاتف المرتبط', session!.phone!),
const SizedBox(height: 24),
// English: Render different elements depending on connection status.
// Arabic: عرض عناصر مختلفة حسب حالة الاتصال.
if (session == null || session.status == 'disconnected') ...[
const Text(
'⚠️ الحساب غير متصل. يرجى توليد رمز الاستجابة السريعة (QR Code) ومسحه ضوئياً لتفعيل الاتصال.',
style: TextStyle(color: Colors.orangeAccent, fontSize: 13),
),
const SizedBox(height: 20),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purpleAccent,
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
icon: const Icon(Icons.qr_code_scanner),
label: const Text('توليد رمز الاستجابة QR'),
onPressed: () {
// English: Dispatch requestWhatsAppQr command to DashboardCubit.
// Arabic: استدعاء أمر طلب رمز الاستجابة في الكيوبيت.
context.read<DashboardCubit>().requestWhatsAppQr();
},
),
] else if (session.status == 'waiting_qr') ...[
const Text(
'🔍 رمز الاستجابة جاهز للمسح. يرجى فتح الواتساب في هاتفك واختيار "الأجهزة المرتبطة" ثم مسح الرمز أدناه:',
style: TextStyle(color: Colors.yellowAccent, fontSize: 13),
),
const SizedBox(height: 20),
Center(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.qr_code_2, size: 200, color: Colors.black),
),
),
const SizedBox(height: 20),
] else if (session.status == 'connected') ...[
const Text(
'✅ الحساب متصل وجاهز للعمل. الردود التلقائية وروبوت خدمة العملاء نشطان الآن.',
style: TextStyle(color: Colors.greenAccent, fontSize: 13),
),
const SizedBox(height: 20),
OutlinedButton.icon(
style: OutlinedButton.styleFrom(
foregroundColor: Colors.redAccent,
side: const BorderSide(color: Colors.redAccent),
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 24),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
icon: const Icon(Icons.link_off),
label: const Text('قطع الاتصال'),
onPressed: () => _showDisconnectDialog(context),
),
],
],
),
),
],
),
);
}
Widget _buildRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(color: Colors.white70, fontSize: 13)),
Text(value, style: const TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.bold)),
],
),
);
}
Widget _buildStatusBadge(String status) {
Color color;
String text;
switch (status) {
case 'connected':
color = Colors.green;
text = 'متصل';
break;
case 'waiting_qr':
color = Colors.orange;
text = 'بانتظار المسح';
break;
case 'connecting':
color = Colors.blue;
text = 'جاري الاتصال';
break;
default:
color = Colors.red;
text = 'غير متصل';
break;
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.2),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: color),
),
child: Text(text, style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.bold)),
);
}
}