Deploy: 2026-05-24 23:27:32
This commit is contained in:
66
mobile/lib/features/auth/data/auth_repository.dart
Normal file
66
mobile/lib/features/auth/data/auth_repository.dart
Normal file
@@ -0,0 +1,66 @@
|
||||
import 'dart:convert';
|
||||
import '../../../core/services/api_service.dart';
|
||||
import '../../../core/services/secure_storage_service.dart';
|
||||
import 'models/user_model.dart';
|
||||
|
||||
class AuthRepository {
|
||||
final ApiService _apiService = ApiService();
|
||||
final SecureStorageService _secureStorage = SecureStorageService();
|
||||
|
||||
// English: Perform login by email/password, verify response status, and save JWT token.
|
||||
// Arabic: إجراء تسجيل الدخول عن طريق البريد الإلكتروني وكلمة المرور، والتحقق من حالة الاستجابة، وحفظ رمز التحقق.
|
||||
Future<UserModel> login(String email, String password) async {
|
||||
final response = await _apiService.login(email, password);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final token = data['token'] as String;
|
||||
final userJson = data['user'] as Map<String, dynamic>;
|
||||
|
||||
// English: Store JWT token securely using secure storage.
|
||||
// Arabic: تخزين رمز التحقق بشكل آمن باستخدام التخزين الآمن.
|
||||
await _secureStorage.writeToken(token);
|
||||
|
||||
return UserModel.fromJson(userJson);
|
||||
} else {
|
||||
// English: Handle server error messages securely.
|
||||
// Arabic: معالجة رسائل خطأ الخادم بشكل آمن.
|
||||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final errorMessage = data['error'] as String? ?? 'Failed to authenticate';
|
||||
throw Exception(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
// English: Check if a valid JWT token exists and fetch the authenticated user data.
|
||||
// Arabic: التحقق من وجود رمز تحقق صالح وجلب بيانات المستخدم المصادق عليه.
|
||||
Future<UserModel?> getCachedUser() async {
|
||||
final token = await _secureStorage.readToken();
|
||||
if (token == null || token.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await _apiService.getMe(token);
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final userJson = data['user'] as Map<String, dynamic>;
|
||||
return UserModel.fromJson(userJson);
|
||||
} else {
|
||||
// English: Token is likely invalid or expired, clear it.
|
||||
// Arabic: من المحتمل أن يكون الرمز غير صالح أو منتهي الصلاحية، قم بمسحه.
|
||||
await _secureStorage.deleteToken();
|
||||
return null;
|
||||
}
|
||||
} catch (_) {
|
||||
// English: Return null if offline or server is unreachable.
|
||||
// Arabic: إرجاع قيمة فارغة إذا كان الجهاز غير متصل أو تعذر الوصول إلى الخادم.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// English: Clear stored JWT credentials.
|
||||
// Arabic: مسح بيانات اعتماد رمز التحقق المخزنة.
|
||||
Future<void> logout() async {
|
||||
await _secureStorage.deleteToken();
|
||||
}
|
||||
}
|
||||
77
mobile/lib/features/auth/data/models/user_model.dart
Normal file
77
mobile/lib/features/auth/data/models/user_model.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class UserModel extends Equatable {
|
||||
// English: Unique identifier for the user.
|
||||
// Arabic: المعرف الفريد للمستخدم.
|
||||
final int id;
|
||||
|
||||
// English: The ID of the company this user belongs to.
|
||||
// Arabic: معرف الشركة التي ينتمي إليها هذا المستخدم.
|
||||
final int companyId;
|
||||
|
||||
// English: The name of the user.
|
||||
// Arabic: اسم المستخدم.
|
||||
final String name;
|
||||
|
||||
// English: The email address of the user.
|
||||
// Arabic: البريد الإلكتروني للمستخدم.
|
||||
final String email;
|
||||
|
||||
// English: The system role assigned to the user (e.g. admin, staff).
|
||||
// Arabic: دور النظام المعين للمستخدم (مثل مشرف، موظف).
|
||||
final String role;
|
||||
|
||||
// English: Indicator if the user is a super admin (company ID 1).
|
||||
// Arabic: مؤشر ما إذا كان المستخدم مشرفاً عاماً (معرف الشركة 1).
|
||||
final bool isSuperAdmin;
|
||||
|
||||
const UserModel({
|
||||
required this.id,
|
||||
required this.companyId,
|
||||
required this.name,
|
||||
required this.email,
|
||||
required this.role,
|
||||
required this.isSuperAdmin,
|
||||
});
|
||||
|
||||
// English: Factory constructor to create a UserModel instance from JSON mapping.
|
||||
// Arabic: منشئ المصنع لإنشاء نسخة نموذج المستخدم من خريطة جيسون.
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) {
|
||||
// English: Safely parse isSuperAdmin from dynamic input (boolean or integer).
|
||||
// Arabic: تحليل آمن لمؤشر المشرف العام من المدخلات الديناميكية (بولين أو عدد صحيح).
|
||||
final rawSuperAdmin = json['is_super_admin'];
|
||||
bool isSuper = false;
|
||||
if (rawSuperAdmin is bool) {
|
||||
isSuper = rawSuperAdmin;
|
||||
} else if (rawSuperAdmin is int) {
|
||||
isSuper = rawSuperAdmin == 1;
|
||||
} else if (rawSuperAdmin is String) {
|
||||
isSuper = rawSuperAdmin == '1' || rawSuperAdmin.toLowerCase() == 'true';
|
||||
}
|
||||
|
||||
return UserModel(
|
||||
id: json['id'] as int? ?? 0,
|
||||
companyId: json['company_id'] as int? ?? 0,
|
||||
name: json['name'] as String? ?? '',
|
||||
email: json['email'] as String? ?? '',
|
||||
role: json['role'] as String? ?? '',
|
||||
isSuperAdmin: isSuper,
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert UserModel instance to JSON map for local caching.
|
||||
// Arabic: تحويل نسخة نموذج المستخدم إلى خريطة جيسون للتخزين المؤقت المحلي.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'company_id': companyId,
|
||||
'name': name,
|
||||
'email': email,
|
||||
'role': role,
|
||||
'is_super_admin': isSuperAdmin,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, companyId, name, email, role, isSuperAdmin];
|
||||
}
|
||||
81
mobile/lib/features/auth/presentation/cubit/auth_cubit.dart
Normal file
81
mobile/lib/features/auth/presentation/cubit/auth_cubit.dart
Normal file
@@ -0,0 +1,81 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/auth_repository.dart';
|
||||
import 'auth_state.dart';
|
||||
|
||||
// English: AuthCubit manages authentication states.
|
||||
// Arabic: يدير ملف الكيوبيت حالات المصادقة للمستخدمين.
|
||||
//
|
||||
// English: In GetX, you would use a GetxController and update observable variables.
|
||||
// Arabic: في غيت إكس، كنت ستستخدم وحدة التحكم وتحدث المتغيرات المرصودة.
|
||||
//
|
||||
// English: In Bloc/Cubit, you inherit from Cubit and emit new immutable states.
|
||||
// Arabic: في بلوك أو كيوبيت، ترث من الكيوبيت وترسل حالات غير قابلة للتعديل.
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final AuthRepository _authRepository;
|
||||
|
||||
// English: Constructor initializing the Cubit with the AuthInitial state.
|
||||
// Arabic: منشئ يقوم بتهيئة الكيوبيت بالحالة الأولية.
|
||||
AuthCubit(this._authRepository) : super(const AuthInitial());
|
||||
|
||||
// English: Check if the user is already authenticated on app launch.
|
||||
// Arabic: التحقق مما إذا كان المستخدم مصدقًا عليه بالفعل عند تشغيل التطبيق.
|
||||
Future<void> checkAuthStatus() async {
|
||||
// English: Emit loading state while reading storage.
|
||||
// Arabic: إرسال حالة التحميل أثناء قراءة وحدة التخزين.
|
||||
emit(const AuthLoading());
|
||||
|
||||
try {
|
||||
final user = await _authRepository.getCachedUser();
|
||||
if (user != null) {
|
||||
// English: Emit Authenticated state if user exists.
|
||||
// Arabic: إرسال حالة مصادق عليه إذا كان المستخدم موجودًا.
|
||||
emit(Authenticated(user));
|
||||
} else {
|
||||
// English: Emit Unauthenticated if no cached token is found.
|
||||
// Arabic: إرسال حالة غير مصادق عليه في حال لم يتم العثور على رمز مخزن مؤقتًا.
|
||||
emit(const Unauthenticated());
|
||||
}
|
||||
} catch (e) {
|
||||
// English: Fail check, treat as unauthenticated.
|
||||
// Arabic: فشل التحقق، يتم اعتباره غير مصادق عليه.
|
||||
emit(const Unauthenticated());
|
||||
}
|
||||
}
|
||||
|
||||
// English: Perform login request using email and password.
|
||||
// Arabic: إجراء طلب تسجيل الدخول باستخدام البريد الإلكتروني وكلمة المرور.
|
||||
Future<void> login(String email, String password) async {
|
||||
// English: Validate input locally before hitting the server.
|
||||
// Arabic: التحقق من صحة المدخلات محليًا قبل الاتصال بالخادم.
|
||||
if (email.isEmpty || password.isEmpty) {
|
||||
emit(const AuthFailure('الرجاء إدخال جميع الحقول بشكل صحيح'));
|
||||
return;
|
||||
}
|
||||
|
||||
emit(const AuthLoading());
|
||||
|
||||
try {
|
||||
final user = await _authRepository.login(email, password);
|
||||
|
||||
// English: Emit Authenticated state with user profile on success.
|
||||
// Arabic: إرسال حالة مصادق عليه مع ملف تعريف المستخدم عند النجاح.
|
||||
emit(Authenticated(user));
|
||||
} catch (e) {
|
||||
// English: Clean the error message to display to the user.
|
||||
// Arabic: تنظيف رسالة الخطأ لعرضها على المستخدم.
|
||||
final cleanError = e.toString().replaceAll('Exception: ', '');
|
||||
emit(AuthFailure(cleanError));
|
||||
}
|
||||
}
|
||||
|
||||
// English: Clear user token and log out.
|
||||
// Arabic: مسح رمز المستخدم وتسجيل الخروج.
|
||||
Future<void> logout() async {
|
||||
emit(const AuthLoading());
|
||||
await _authRepository.logout();
|
||||
|
||||
// English: Emit Unauthenticated state to return user to login screen.
|
||||
// Arabic: إرسال حالة غير مصادق عليه لإرجاع المستخدم إلى شاشة تسجيل الدخول.
|
||||
emit(const Unauthenticated());
|
||||
}
|
||||
}
|
||||
49
mobile/lib/features/auth/presentation/cubit/auth_state.dart
Normal file
49
mobile/lib/features/auth/presentation/cubit/auth_state.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../data/models/user_model.dart';
|
||||
|
||||
abstract class AuthState extends Equatable {
|
||||
const AuthState();
|
||||
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
// English: Initial state when the app is checking for existing authentication tokens.
|
||||
// Arabic: الحالة الأولية عندما يقوم التطبيق بالتحقق من وجود رموز مصادقة حالية.
|
||||
class AuthInitial extends AuthState {
|
||||
const AuthInitial();
|
||||
}
|
||||
|
||||
// English: Loading state shown during credential verification or API login request.
|
||||
// Arabic: حالة التحميل المعروضة أثناء التحقق من بيانات الاعتماد أو طلب تسجيل الدخول.
|
||||
class AuthLoading extends AuthState {
|
||||
const AuthLoading();
|
||||
}
|
||||
|
||||
// English: State emitted when the user successfully authenticates. Contains user details.
|
||||
// Arabic: الحالة المرسلة عندما ينجح المستخدم في المصادقة. تحتوي على تفاصيل المستخدم.
|
||||
class Authenticated extends AuthState {
|
||||
final UserModel user;
|
||||
|
||||
const Authenticated(this.user);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [user];
|
||||
}
|
||||
|
||||
// English: State emitted when the user is not authenticated or has logged out.
|
||||
// Arabic: الحالة المرسلة عندما لا يكون المستخدم مصدقًا أو قد سجل خروجه.
|
||||
class Unauthenticated extends AuthState {
|
||||
const Unauthenticated();
|
||||
}
|
||||
|
||||
// English: Failure state containing the error message in case authentication fails.
|
||||
// Arabic: حالة الفشل التي تحتوي على رسالة الخطأ في حالة فشل المصادقة.
|
||||
class AuthFailure extends AuthState {
|
||||
final String errorMessage;
|
||||
|
||||
const AuthFailure(this.errorMessage);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [errorMessage];
|
||||
}
|
||||
243
mobile/lib/features/auth/presentation/screens/login_screen.dart
Normal file
243
mobile/lib/features/auth/presentation/screens/login_screen.dart
Normal file
@@ -0,0 +1,243 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../cubit/auth_cubit.dart';
|
||||
import '../cubit/auth_state.dart';
|
||||
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> {
|
||||
// English: Form key to manage state and invoke validation.
|
||||
// Arabic: مفتاح النموذج لإدارة الحالة واستدعاء التحقق من الصحة.
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
bool _isPasswordVisible = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// English: We use a dark, premium theme with purple/blue gradients.
|
||||
// Arabic: نحن نستخدم سمة داكنة ومميزة مع تدرجات أرجوانية وزرقاء.
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFF0F0C20), Color(0xFF15102A), Color(0xFF0A0814)],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: BlocConsumer<AuthCubit, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthFailure) {
|
||||
// English: Show failure message as SnackBar when state is AuthFailure.
|
||||
// Arabic: عرض رسالة الفشل كشريط وجبة خفيفة عندما تكون الحالة فشل المصادقة.
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
state.errorMessage,
|
||||
style: const TextStyle(color: Colors.white, fontFamily: 'Outfit'),
|
||||
),
|
||||
backgroundColor: Colors.redAccent,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
// English: Logo placeholder with dynamic design.
|
||||
// Arabic: رمز شعار تجريبي بتصميم ديناميكي.
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: Colors.deepPurple.withOpacity(0.2),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.security,
|
||||
size: 64,
|
||||
color: Colors.purpleAccent,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const Text(
|
||||
'نـبـيـه',
|
||||
style: TextStyle(
|
||||
fontSize: 36,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
letterSpacing: 2,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'تسجيل الدخول للمشرفين والعملاء',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.white.withOpacity(0.6),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// English: Email text input with custom borders and icons.
|
||||
// Arabic: إدخال نص البريد الإلكتروني مع حدود وأيقونات مخصصة.
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'البريد الإلكتروني',
|
||||
labelStyle: TextStyle(color: Colors.white.withOpacity(0.6)),
|
||||
prefixIcon: const Icon(Icons.email_outlined, color: Colors.purpleAccent),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.05),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Colors.purpleAccent, width: 2),
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'الرجاء إدخال البريد الإلكتروني';
|
||||
}
|
||||
if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
|
||||
return 'الرجاء إدخال بريد إلكتروني صالح';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// English: Password text input with visibility toggle.
|
||||
// Arabic: إدخال نص كلمة المرور مع إمكانية التبديل بين إظهارها وإخفائها.
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: !_isPasswordVisible,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'كلمة المرور',
|
||||
labelStyle: TextStyle(color: Colors.white.withOpacity(0.6)),
|
||||
prefixIcon: const Icon(Icons.lock_outline, color: Colors.purpleAccent),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
|
||||
color: Colors.white.withOpacity(0.6),
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isPasswordVisible = !_isPasswordVisible;
|
||||
});
|
||||
},
|
||||
),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.05),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Colors.purpleAccent, width: 2),
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'الرجاء إدخال كلمة المرور';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// English: Submit button. Shows progress bar during login request.
|
||||
// Arabic: زر الإرسال. يعرض شريط تقدم تحميل البيانات أثناء المصادقة.
|
||||
if (state is AuthLoading)
|
||||
const CircularProgressIndicator(color: Colors.purpleAccent)
|
||||
else
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
// English: Dispatch login method to AuthCubit.
|
||||
// Arabic: استدعاء دالة تسجيل الدخول إلى الكيوبيت.
|
||||
context.read<AuthCubit>().login(
|
||||
_emailController.text.trim(),
|
||||
_passwordController.text,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
colors: [Colors.purpleAccent, Colors.deepPurpleAccent],
|
||||
begin: Alignment.centerLeft,
|
||||
end: Alignment.centerRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.purpleAccent.withOpacity(0.3),
|
||||
blurRadius: 12,
|
||||
offset: const Offset(0, 4),
|
||||
)
|
||||
],
|
||||
),
|
||||
child: const Center(
|
||||
child: Text(
|
||||
'تسجيل الدخول',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
160
mobile/lib/features/dashboard/data/dashboard_repository.dart
Normal file
160
mobile/lib/features/dashboard/data/dashboard_repository.dart
Normal file
@@ -0,0 +1,160 @@
|
||||
import 'dart:convert';
|
||||
import '../../../core/services/api_service.dart';
|
||||
import '../../../core/services/secure_storage_service.dart';
|
||||
import 'models/chatbot_rule_model.dart';
|
||||
import 'models/contact_model.dart';
|
||||
import 'models/plan_model.dart';
|
||||
import 'models/super_admin_stats_model.dart';
|
||||
import 'models/whatsapp_status_model.dart';
|
||||
|
||||
class DashboardRepository {
|
||||
final ApiService _apiService = ApiService();
|
||||
final SecureStorageService _secureStorage = SecureStorageService();
|
||||
|
||||
// English: Helper to retrieve token from secure storage. Throws exception if token is missing.
|
||||
// Arabic: دالة مساعدة لاسترداد الرمز من التخزين الآمن. تطلق استثناء إذا كان الرمز مفقودًا.
|
||||
Future<String> _getToken() async {
|
||||
final token = await _secureStorage.readToken();
|
||||
if (token == null || token.isEmpty) {
|
||||
throw Exception('أنت غير مصرح لك بالوصول، يرجى إعادة تسجيل الدخول');
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
// English: Load the active WhatsApp connection session status.
|
||||
// Arabic: تحميل حالة اتصال جلسة الواتساب النشطة.
|
||||
Future<WhatsAppStatusModel?> getWhatsAppStatus() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.getWhatsAppStatus(token);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final statusData = decoded['data'] as Map<String, dynamic>?;
|
||||
if (statusData == null) return null;
|
||||
return WhatsAppStatusModel.fromJson(statusData);
|
||||
} else {
|
||||
throw Exception('فشل في جلب حالة الواتساب');
|
||||
}
|
||||
}
|
||||
|
||||
// English: Load available subscription plans.
|
||||
// Arabic: تحميل باقات الاشتراك المتاحة.
|
||||
Future<List<PlanModel>> getPlans() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.getPlans(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) => PlanModel.fromJson(item as Map<String, dynamic>)).toList();
|
||||
} else {
|
||||
throw Exception('فشل في جلب الباقات المتاحة');
|
||||
}
|
||||
}
|
||||
|
||||
// English: Load CRM contacts directory.
|
||||
// Arabic: تحميل دليل جهات اتصال إدارة العملاء.
|
||||
Future<List<ContactModel>> getContacts() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.getContacts(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) => ContactModel.fromJson(item as Map<String, dynamic>)).toList();
|
||||
} else {
|
||||
throw Exception('فشل في جلب جهات الاتصال');
|
||||
}
|
||||
}
|
||||
|
||||
// English: Create a new contact inside remote CRM directory.
|
||||
// Arabic: إنشاء جهة اتصال جديدة داخل دليل إدارة العملاء البعيد.
|
||||
Future<void> addContact(String name, String phone) async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.addContact(token, name, phone);
|
||||
|
||||
if (response.statusCode == 201 || response.statusCode == 200) {
|
||||
return;
|
||||
} else if (response.statusCode == 409) {
|
||||
throw Exception('رقم الهاتف هذا مسجل بالفعل في جهات الاتصال الخاصة بك');
|
||||
} else {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final error = decoded['message'] as String? ?? 'فشل في إضافة جهة الاتصال';
|
||||
throw Exception(error);
|
||||
}
|
||||
}
|
||||
|
||||
// English: Load chatbot auto-reply rules.
|
||||
// Arabic: تحميل قواعد الرد الآلي لروبوت الدردشة.
|
||||
Future<List<ChatbotRuleModel>> getChatbotRules() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.getChatbotRules(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) => ChatbotRuleModel.fromJson(item as Map<String, dynamic>)).toList();
|
||||
} else {
|
||||
throw Exception('فشل في جلب قواعد الرد الآلي');
|
||||
}
|
||||
}
|
||||
|
||||
// English: Load platform statistics (Super Admin only).
|
||||
// Arabic: تحميل إحصائيات المنصة (للمشرف العام فقط).
|
||||
Future<SuperAdminStatsModel> getAdminStats() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.getAdminStats(token);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final statsData = decoded['data'] as Map<String, dynamic>?;
|
||||
if (statsData == null) {
|
||||
throw Exception('البيانات غير صالحة');
|
||||
}
|
||||
return SuperAdminStatsModel.fromJson(decoded['data'] as Map<String, dynamic>);
|
||||
} else {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final error = decoded['error'] as String? ?? 'فشل في جلب إحصائيات المشرف العام';
|
||||
throw Exception(error);
|
||||
}
|
||||
}
|
||||
|
||||
// English: Request a new WhatsApp QR connection.
|
||||
// Arabic: طلب اتصال واتساب جديد برمز استجابة سريع.
|
||||
Future<void> requestWhatsAppQr() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.requestWhatsAppQr(token);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final error = decoded['message'] as String? ?? 'فشل في طلب رمز الاستجابة السريعة';
|
||||
throw Exception(error);
|
||||
}
|
||||
}
|
||||
|
||||
// English: Disconnect the active WhatsApp connection.
|
||||
// Arabic: قطع اتصال الواتساب النشط.
|
||||
Future<void> disconnectWhatsApp() async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.disconnectWhatsApp(token);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final error = decoded['message'] as String? ?? 'فشل في قطع الاتصال';
|
||||
throw Exception(error);
|
||||
}
|
||||
}
|
||||
|
||||
// English: Approve a pending company subscription.
|
||||
// Arabic: الموافقة على اشتراك شركة معلق.
|
||||
Future<void> approveBilling(int companyId) async {
|
||||
final token = await _getToken();
|
||||
final response = await _apiService.approveBilling(token, companyId);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final error = decoded['error'] as String? ?? 'فشل في الموافقة على الاشتراك';
|
||||
throw Exception(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class ChatbotRuleModel extends Equatable {
|
||||
// English: Unique identifier for the rule.
|
||||
// Arabic: المعرف الفريد للقاعدة.
|
||||
final int id;
|
||||
|
||||
// English: The ID of the company this rule belongs to.
|
||||
// Arabic: معرف الشركة التي تنتمي إليها هذه القاعدة.
|
||||
final int companyId;
|
||||
|
||||
// English: The session ID this rule is bound to.
|
||||
// Arabic: معرف الجلسة المرتبطة بها هذه القاعدة.
|
||||
final int? sessionId;
|
||||
|
||||
// English: Trigger type (keyword, gemini_ai).
|
||||
// Arabic: نوع المشغل (كلمة مفتاحية، ذكاء اصطناعي).
|
||||
final String triggerType;
|
||||
|
||||
// English: The comma-separated static reply keywords.
|
||||
// Arabic: الكلمات المفتاحية للردود الثابتة مفصولة بفاصلة.
|
||||
final String? keyword;
|
||||
|
||||
// English: Predefined reply content or Gemini prompt instructions.
|
||||
// Arabic: محتوى الرد المحدد مسبقاً أو تعليمات موجه الذكاء الاصطناعي.
|
||||
final String? aiPrompt;
|
||||
|
||||
// English: Active state flag.
|
||||
// Arabic: علم الحالة النشطة.
|
||||
final bool isActive;
|
||||
|
||||
const ChatbotRuleModel({
|
||||
required this.id,
|
||||
required this.companyId,
|
||||
this.sessionId,
|
||||
required this.triggerType,
|
||||
this.keyword,
|
||||
this.aiPrompt,
|
||||
required this.isActive,
|
||||
});
|
||||
|
||||
// English: Factory constructor to parse ChatbotRuleModel from JSON data map.
|
||||
// Arabic: منشئ المصنع لتحليل نموذج قاعدة الرد الآلي من خريطة بيانات جيسون.
|
||||
factory ChatbotRuleModel.fromJson(Map<String, dynamic> json) {
|
||||
return ChatbotRuleModel(
|
||||
id: json['id'] as int? ?? 0,
|
||||
companyId: json['company_id'] as int? ?? 0,
|
||||
sessionId: json['session_id'] as int?,
|
||||
triggerType: json['trigger_type'] as String? ?? 'keyword',
|
||||
keyword: json['keyword'] as String?,
|
||||
aiPrompt: json['ai_prompt'] as String?,
|
||||
isActive: (json['is_active'] as int? ?? 0) == 1,
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert model to JSON map.
|
||||
// Arabic: تحويل النموذج إلى خريطة جيسون.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'company_id': companyId,
|
||||
'session_id': sessionId,
|
||||
'trigger_type': triggerType,
|
||||
'keyword': keyword,
|
||||
'ai_prompt': aiPrompt,
|
||||
'is_active': isActive ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, companyId, sessionId, triggerType, keyword, aiPrompt, isActive];
|
||||
}
|
||||
58
mobile/lib/features/dashboard/data/models/contact_model.dart
Normal file
58
mobile/lib/features/dashboard/data/models/contact_model.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class ContactModel extends Equatable {
|
||||
// English: Unique identifier for the contact.
|
||||
// Arabic: المعرف الفريد لجهة الاتصال.
|
||||
final int id;
|
||||
|
||||
// English: Name of the contact.
|
||||
// Arabic: اسم جهة الاتصال.
|
||||
final String name;
|
||||
|
||||
// English: Phone number.
|
||||
// Arabic: رقم الهاتف.
|
||||
final String phone;
|
||||
|
||||
// English: Optional email address.
|
||||
// Arabic: البريد الإلكتروني الاختياري.
|
||||
final String? email;
|
||||
|
||||
// English: Optional descriptive notes.
|
||||
// Arabic: ملاحظات وصفية اختيارية.
|
||||
final String? notes;
|
||||
|
||||
const ContactModel({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.phone,
|
||||
this.email,
|
||||
this.notes,
|
||||
});
|
||||
|
||||
// English: Factory constructor to parse ContactModel from JSON map.
|
||||
// Arabic: منشئ المصنع لتحليل نموذج جهة الاتصال من خريطة جيسون.
|
||||
factory ContactModel.fromJson(Map<String, dynamic> json) {
|
||||
return ContactModel(
|
||||
id: json['id'] as int? ?? 0,
|
||||
name: json['name'] as String? ?? '',
|
||||
phone: json['phone'] as String? ?? '',
|
||||
email: json['email'] as String?,
|
||||
notes: json['notes'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert model to JSON map.
|
||||
// Arabic: تحويل النموذج إلى خريطة جيسون.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'phone': phone,
|
||||
'email': email,
|
||||
'notes': notes,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name, phone, email, notes];
|
||||
}
|
||||
44
mobile/lib/features/dashboard/data/models/plan_model.dart
Normal file
44
mobile/lib/features/dashboard/data/models/plan_model.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class PlanModel extends Equatable {
|
||||
// English: Unique plan identifier.
|
||||
// Arabic: المعرف الفريد للباقة.
|
||||
final int id;
|
||||
|
||||
// English: Name of the plan (e.g. Free Trial, Pro, Enterprise).
|
||||
// Arabic: اسم الباقة (مثل التجريبية، الاحترافية، الشركات).
|
||||
final String name;
|
||||
|
||||
// English: Monthly price of the plan.
|
||||
// Arabic: السعر الشهري للباقة.
|
||||
final double price;
|
||||
|
||||
const PlanModel({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.price,
|
||||
});
|
||||
|
||||
// English: Factory constructor to parse PlanModel from JSON data map.
|
||||
// Arabic: منشئ المصنع لتحليل نموذج الباقة من خريطة بيانات جيسون.
|
||||
factory PlanModel.fromJson(Map<String, dynamic> json) {
|
||||
return PlanModel(
|
||||
id: json['id'] as int? ?? 0,
|
||||
name: json['name'] as String? ?? 'Nabeh Plan',
|
||||
price: (json['price'] as num?)?.toDouble() ?? 0.0,
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert model to JSON map.
|
||||
// Arabic: تحويل النموذج إلى خريطة جيسون.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'price': price,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name, price];
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class SuperAdminStatsModel extends Equatable {
|
||||
// English: Overall platform stats.
|
||||
// Arabic: إحصائيات المنصة الإجمالية.
|
||||
final int totalCompanies;
|
||||
final int totalSessions;
|
||||
final int connectedSessions;
|
||||
|
||||
// English: Lists of active companies, pending billing approvals, and subscription plans.
|
||||
// Arabic: قوائم بالشركات النشطة، وموافقات الفواتير المعلقة، وباقات الاشتراك المتاحة.
|
||||
final List<dynamic> companies;
|
||||
final List<dynamic> pendingApprovals;
|
||||
final List<dynamic> plans;
|
||||
|
||||
const SuperAdminStatsModel({
|
||||
required this.totalCompanies,
|
||||
required this.totalSessions,
|
||||
required this.connectedSessions,
|
||||
required this.companies,
|
||||
required this.pendingApprovals,
|
||||
required this.plans,
|
||||
});
|
||||
|
||||
// English: Factory constructor to parse SuperAdminStatsModel from JSON data map.
|
||||
// Arabic: منشئ المصنع لتحليل نموذج إحصائيات المشرف العام من خريطة بيانات جيسون.
|
||||
factory SuperAdminStatsModel.fromJson(Map<String, dynamic> json) {
|
||||
final stats = json['stats'] as Map<String, dynamic>? ?? {};
|
||||
return SuperAdminStatsModel(
|
||||
totalCompanies: stats['total_companies'] as int? ?? 0,
|
||||
totalSessions: stats['total_sessions'] as int? ?? 0,
|
||||
connectedSessions: stats['connected_sessions'] as int? ?? 0,
|
||||
companies: json['companies'] as List<dynamic>? ?? [],
|
||||
pendingApprovals: json['pending_approvals'] as List<dynamic>? ?? [],
|
||||
plans: json['plans'] as List<dynamic>? ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert model to JSON map.
|
||||
// Arabic: تحويل النموذج إلى خريطة جيسون.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'stats': {
|
||||
'total_companies': totalCompanies,
|
||||
'total_sessions': totalSessions,
|
||||
'connected_sessions': connectedSessions,
|
||||
},
|
||||
'companies': companies,
|
||||
'pending_approvals': pendingApprovals,
|
||||
'plans': plans,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [totalCompanies, totalSessions, connectedSessions, companies, pendingApprovals, plans];
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
class WhatsAppStatusModel extends Equatable {
|
||||
// English: Unique session identifier in database.
|
||||
// Arabic: معرف الجلسة الفريد في قاعدة البيانات.
|
||||
final int id;
|
||||
|
||||
// English: Name of the session (e.g. support, sales).
|
||||
// Arabic: اسم الجلسة (مثل الدعم، المبيعات).
|
||||
final String name;
|
||||
|
||||
// English: Unique session key sent to Baileys Node.js gateway.
|
||||
// Arabic: مفتاح الجلسة الفريد المرسل إلى بوابة الجيسون الخاصة بالواتساب.
|
||||
final String sessionKey;
|
||||
|
||||
// English: Current connection status (waiting_qr, connected, disconnected).
|
||||
// Arabic: حالة الاتصال الحالية (بانتظار رمز الاستجابة، متصل، غير متصل).
|
||||
final String status;
|
||||
|
||||
// English: Base64 or text QR code from Baileys if waiting for scan.
|
||||
// Arabic: رمز الاستجابة السريعة (QR) من البوابة إذا كان بانتظار المسح.
|
||||
final String? qrCode;
|
||||
|
||||
// English: Linked phone number on success connection.
|
||||
// Arabic: رقم الهاتف المرتبط بالجلسة عند الاتصال بنجاح.
|
||||
final String? phone;
|
||||
|
||||
const WhatsAppStatusModel({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.sessionKey,
|
||||
required this.status,
|
||||
this.qrCode,
|
||||
this.phone,
|
||||
});
|
||||
|
||||
// English: Factory constructor to parse WhatsApp status session model from JSON.
|
||||
// Arabic: منشئ المصنع لتحليل نموذج حالة جلسة الواتساب من استجابة جيسون.
|
||||
factory WhatsAppStatusModel.fromJson(Map<String, dynamic> json) {
|
||||
return WhatsAppStatusModel(
|
||||
id: json['id'] as int? ?? 0,
|
||||
name: json['name'] as String? ?? 'WhatsApp Team',
|
||||
sessionKey: json['session_key'] as String? ?? '',
|
||||
status: json['status'] as String? ?? 'disconnected',
|
||||
qrCode: json['qr_code'] as String?,
|
||||
phone: json['phone'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
// English: Convert model to JSON payload.
|
||||
// Arabic: تحويل النموذج إلى حمولة جيسون.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'session_key': sessionKey,
|
||||
'status': status,
|
||||
'qr_code': qrCode,
|
||||
'phone': phone,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name, sessionKey, status, qrCode, phone];
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/dashboard_repository.dart';
|
||||
import 'dashboard_state.dart';
|
||||
|
||||
// English: DashboardCubit manages the active tab and data fetching.
|
||||
// Arabic: يدير ملف الكيوبيت الباب النشط وجلب البيانات المخصصة له.
|
||||
//
|
||||
// English: In the web client, AlpineJS switches active tabs and calls fetch functions.
|
||||
// Arabic: في عميل الويب، تبدل مكتبة ألبين الباب النشط وتستدعي دوال الجلب.
|
||||
//
|
||||
// English: Here, this Cubit replicates that behavior by capturing changes and emitting updated states.
|
||||
// Arabic: هنا، يكرر هذا الكيوبيت هذا السلوك من خلال رصد التغييرات وإرسال حالات محدثة.
|
||||
class DashboardCubit extends Cubit<DashboardState> {
|
||||
final DashboardRepository _repository;
|
||||
|
||||
DashboardCubit(this._repository)
|
||||
: super(const DashboardState(
|
||||
activeTab: DashboardTab.whatsapp,
|
||||
isLoading: false,
|
||||
));
|
||||
|
||||
// English: Switch the active dashboard view and fetch the required API data.
|
||||
// Arabic: تبديل عرض لوحة التحكم النشط وجلب بيانات واجهة برمجة التطبيقات المطلوبة.
|
||||
Future<void> changeTab(DashboardTab tab) async {
|
||||
// English: Update tab state first to give instant visual feedback in UI.
|
||||
// Arabic: تحديث حالة الباب أولاً لتقديم استجابة مرئية فورية في الواجهة.
|
||||
emit(state.copyWith(activeTab: tab, isLoading: true));
|
||||
|
||||
try {
|
||||
switch (tab) {
|
||||
case DashboardTab.whatsapp:
|
||||
final status = await _repository.getWhatsAppStatus();
|
||||
emit(state.copyWith(whatsappStatus: status, isLoading: false));
|
||||
break;
|
||||
case DashboardTab.billing:
|
||||
final plans = await _repository.getPlans();
|
||||
emit(state.copyWith(plans: plans, isLoading: false));
|
||||
break;
|
||||
case DashboardTab.contacts:
|
||||
final contacts = await _repository.getContacts();
|
||||
emit(state.copyWith(contacts: contacts, isLoading: false));
|
||||
break;
|
||||
case DashboardTab.chatbot:
|
||||
final rules = await _repository.getChatbotRules();
|
||||
emit(state.copyWith(chatbotRules: rules, isLoading: false));
|
||||
break;
|
||||
case DashboardTab.superAdmin:
|
||||
final adminStats = await _repository.getAdminStats();
|
||||
emit(state.copyWith(superAdminStats: adminStats, isLoading: false));
|
||||
break;
|
||||
default:
|
||||
// English: Placeholder views do not hit any backend API.
|
||||
// Arabic: شاشات الحجز المؤقتة لا تتصل بأي واجهة برمجة تطبيقات.
|
||||
emit(state.copyWith(isLoading: false));
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
final cleanMsg = e.toString().replaceAll('Exception: ', '');
|
||||
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
|
||||
}
|
||||
}
|
||||
|
||||
// English: Action trigger to reload current active tab data.
|
||||
// Arabic: مشغل الإجراء لإعادة تحميل بيانات الباب النشط الحالي.
|
||||
Future<void> refreshCurrentTab() async {
|
||||
await changeTab(state.activeTab);
|
||||
}
|
||||
|
||||
// English: Add a new contact and automatically reload the updated contacts list.
|
||||
// Arabic: إضافة جهة اتصال جديدة وإعادة تحميل قائمة جهات الاتصال المحدثة تلقائياً.
|
||||
Future<bool> addContact(String name, String phone) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
await _repository.addContact(name, phone);
|
||||
final contacts = await _repository.getContacts();
|
||||
emit(state.copyWith(contacts: contacts, isLoading: false));
|
||||
return true;
|
||||
} catch (e) {
|
||||
final cleanMsg = e.toString().replaceAll('Exception: ', '');
|
||||
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// English: Request a new WhatsApp QR connection session and refresh status.
|
||||
// Arabic: طلب جلسة اتصال واتساب جديدة برمز استجابة سريع وتحديث الحالة.
|
||||
Future<void> requestWhatsAppQr() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
await _repository.requestWhatsAppQr();
|
||||
final status = await _repository.getWhatsAppStatus();
|
||||
emit(state.copyWith(whatsappStatus: status, isLoading: false));
|
||||
} catch (e) {
|
||||
final cleanMsg = e.toString().replaceAll('Exception: ', '');
|
||||
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
|
||||
}
|
||||
}
|
||||
|
||||
// English: Disconnect active WhatsApp connection and refresh status.
|
||||
// Arabic: قطع اتصال الواتساب النشط وتحديث الحالة.
|
||||
Future<void> disconnectWhatsApp() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
await _repository.disconnectWhatsApp();
|
||||
final status = await _repository.getWhatsAppStatus();
|
||||
emit(state.copyWith(whatsappStatus: status, isLoading: false));
|
||||
} catch (e) {
|
||||
final cleanMsg = e.toString().replaceAll('Exception: ', '');
|
||||
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
|
||||
}
|
||||
}
|
||||
|
||||
// English: Approve a pending company subscription billing and reload admin stats.
|
||||
// Arabic: الموافقة على اشتراك شركة معلق وإعادة تحميل إحصائيات المدير العام.
|
||||
Future<void> approveBilling(int companyId) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
await _repository.approveBilling(companyId);
|
||||
final stats = await _repository.getAdminStats();
|
||||
emit(state.copyWith(superAdminStats: stats, isLoading: false));
|
||||
} catch (e) {
|
||||
final cleanMsg = e.toString().replaceAll('Exception: ', '');
|
||||
emit(state.copyWith(errorMessage: cleanMsg, isLoading: false));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../data/models/chatbot_rule_model.dart';
|
||||
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';
|
||||
|
||||
// English: Enum representing the 9 tabs in the Nabeh web/mobile dashboard.
|
||||
// Arabic: قائمة تعداد تمثل الأبواب التسعة في لوحة تحكم نبيه على الويب والهاتف.
|
||||
enum DashboardTab {
|
||||
superAdmin,
|
||||
whatsapp,
|
||||
billing,
|
||||
contacts,
|
||||
templates,
|
||||
campaigns,
|
||||
chatbot,
|
||||
integrations,
|
||||
staff
|
||||
}
|
||||
|
||||
class DashboardState extends Equatable {
|
||||
// English: The currently selected tab in navigation.
|
||||
// Arabic: الباب المحدد حالياً في التنقل.
|
||||
final DashboardTab activeTab;
|
||||
|
||||
// English: Indicator if data is being retrieved from backend.
|
||||
// Arabic: مؤشر ما إذا كان يتم استرداد البيانات من الواجهة الخلفية.
|
||||
final bool isLoading;
|
||||
|
||||
// English: Error message if API requests fail.
|
||||
// Arabic: رسالة الخطأ إذا فشلت طلبات واجهة برمجة التطبيقات.
|
||||
final String? errorMessage;
|
||||
|
||||
// English: Feature data models parsed from network API responses.
|
||||
// Arabic: نماذج بيانات الميزات التي تم تحليلها من استجابات الشبكة.
|
||||
final WhatsAppStatusModel? whatsappStatus;
|
||||
final List<PlanModel> plans;
|
||||
final List<ContactModel> contacts;
|
||||
final List<ChatbotRuleModel> chatbotRules;
|
||||
final SuperAdminStatsModel? superAdminStats;
|
||||
|
||||
const DashboardState({
|
||||
required this.activeTab,
|
||||
required this.isLoading,
|
||||
this.errorMessage,
|
||||
this.whatsappStatus,
|
||||
this.plans = const [],
|
||||
this.contacts = const [],
|
||||
this.chatbotRules = const [],
|
||||
this.superAdminStats,
|
||||
});
|
||||
|
||||
// English: Helper copyWith constructor to copy immutable state data safely.
|
||||
// Arabic: منشئ مساعد لنسخ بيانات الحالة الثابتة بشكل آمن.
|
||||
DashboardState copyWith({
|
||||
DashboardTab? activeTab,
|
||||
bool? isLoading,
|
||||
String? errorMessage,
|
||||
WhatsAppStatusModel? whatsappStatus,
|
||||
List<PlanModel>? plans,
|
||||
List<ContactModel>? contacts,
|
||||
List<ChatbotRuleModel>? chatbotRules,
|
||||
SuperAdminStatsModel? superAdminStats,
|
||||
}) {
|
||||
return DashboardState(
|
||||
activeTab: activeTab ?? this.activeTab,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
errorMessage: errorMessage, // Reset if null
|
||||
whatsappStatus: whatsappStatus ?? this.whatsappStatus,
|
||||
plans: plans ?? this.plans,
|
||||
contacts: contacts ?? this.contacts,
|
||||
chatbotRules: chatbotRules ?? this.chatbotRules,
|
||||
superAdminStats: superAdminStats ?? this.superAdminStats,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
activeTab,
|
||||
isLoading,
|
||||
errorMessage,
|
||||
whatsappStatus,
|
||||
plans,
|
||||
contacts,
|
||||
chatbotRules,
|
||||
superAdminStats,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../cubit/dashboard_cubit.dart';
|
||||
import '../cubit/dashboard_state.dart';
|
||||
|
||||
class AddContactScreen extends StatefulWidget {
|
||||
const AddContactScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AddContactScreen> createState() => _AddContactScreenState();
|
||||
}
|
||||
|
||||
class _AddContactScreenState extends State<AddContactScreen> {
|
||||
// English: Form key to execute field validations.
|
||||
// Arabic: مفتاح النموذج لتنفيذ عمليات التحقق من صحة الحقول.
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
final _nameController = TextEditingController();
|
||||
final _phoneController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_phoneController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF0F0C20),
|
||||
appBar: AppBar(
|
||||
backgroundColor: const Color(0xFF15102A),
|
||||
elevation: 0,
|
||||
title: const Text(
|
||||
'إضافة جهة اتصال جديدة',
|
||||
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
body: BlocConsumer<DashboardCubit, DashboardState>(
|
||||
listener: (context, state) {
|
||||
if (state.errorMessage != null) {
|
||||
// English: Show API failure messages as SnackBar alert.
|
||||
// Arabic: عرض رسائل فشل واجهة برمجة التطبيقات كشريط تنبيه.
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
state.errorMessage!,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
backgroundColor: Colors.redAccent,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'تفاصيل جهة الاتصال',
|
||||
style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// English: Input field for contact name.
|
||||
// Arabic: حقل إدخال اسم جهة الاتصال.
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'الاسم الكامل',
|
||||
labelStyle: TextStyle(color: Colors.white.withOpacity(0.6)),
|
||||
prefixIcon: const Icon(Icons.person_outline, color: Colors.purpleAccent),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.05),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Colors.purpleAccent, width: 2),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'الرجاء إدخال اسم جهة الاتصال';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// English: Input field for phone number.
|
||||
// Arabic: حقل إدخال رقم الهاتف.
|
||||
TextFormField(
|
||||
controller: _phoneController,
|
||||
keyboardType: TextInputType.phone,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'رقم الهاتف (مع رمز الدولة)',
|
||||
labelStyle: TextStyle(color: Colors.white.withOpacity(0.6)),
|
||||
prefixIcon: const Icon(Icons.phone_outlined, color: Colors.purpleAccent),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.05),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: Colors.white.withOpacity(0.1)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Colors.purpleAccent, width: 2),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.trim().isEmpty) {
|
||||
return 'الرجاء إدخال رقم الهاتف';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// English: Save button. Shows progress bar or calls Cubit and Pops on success.
|
||||
// Arabic: زر الحفظ. يعرض شريط تقدم التحميل أو يستدعي الكيوبيت ويغلق الصفحة عند النجاح.
|
||||
if (state.isLoading)
|
||||
const Center(child: CircularProgressIndicator(color: Colors.purpleAccent))
|
||||
else
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.purpleAccent,
|
||||
minimumSize: const Size(double.infinity, 56),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
onPressed: () async {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
// English: Dispatch addContact action to DashboardCubit.
|
||||
// Arabic: استدعاء إجراء إضافة جهة اتصال في الكيوبيت.
|
||||
final success = await context.read<DashboardCubit>().addContact(
|
||||
_nameController.text.trim(),
|
||||
_phoneController.text.trim(),
|
||||
);
|
||||
if (success && mounted) {
|
||||
// English: Use Navigator.pop to return to previous contacts screen.
|
||||
// Arabic: استخدام ميزة الموجه لإغلاق الشاشة والرجوع لقائمة جهات الاتصال.
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
},
|
||||
child: const Text(
|
||||
'حفظ جهة الاتصال',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../auth/data/models/user_model.dart';
|
||||
import '../../../auth/presentation/cubit/auth_cubit.dart';
|
||||
import '../../data/dashboard_repository.dart';
|
||||
import '../cubit/dashboard_cubit.dart';
|
||||
import '../cubit/dashboard_state.dart';
|
||||
import '../widgets/billing_view.dart';
|
||||
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';
|
||||
|
||||
class DashboardScreen extends StatelessWidget {
|
||||
final UserModel user;
|
||||
|
||||
const DashboardScreen({super.key, required this.user});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// English: Wrap dashboard view in a local BlocProvider to manage dashboard tab states.
|
||||
// Arabic: تغليف واجهة لوحة التحكم في موفر كتلة محلي لإدارة حالات تبويبات لوحة التحكم.
|
||||
return BlocProvider<DashboardCubit>(
|
||||
create: (context) {
|
||||
final cubit = DashboardCubit(DashboardRepository());
|
||||
// English: Load WhatsApp status as the default view on launch.
|
||||
// Arabic: تحميل حالة الواتساب كعرض افتراضي عند بدء التشغيل.
|
||||
cubit.changeTab(DashboardTab.whatsapp);
|
||||
return cubit;
|
||||
},
|
||||
child: BlocBuilder<DashboardCubit, DashboardState>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF0F0C20),
|
||||
appBar: AppBar(
|
||||
backgroundColor: const Color(0xFF15102A),
|
||||
elevation: 0,
|
||||
title: Text(
|
||||
_getAppBarTitle(state.activeTab),
|
||||
style: const TextStyle(
|
||||
color: Colors.white, fontWeight: FontWeight.bold),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, color: Colors.purpleAccent),
|
||||
tooltip: 'تحديث البيانات',
|
||||
onPressed: () {
|
||||
context.read<DashboardCubit>().refreshCurrentTab();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
// English: Slide drawer menu offering navigation to all 9 dashboard tabs.
|
||||
// Arabic: قائمة درج جانبية توفر التنقل إلى جميع أبواب لوحة التحكم التسعة.
|
||||
drawer: Drawer(
|
||||
backgroundColor: const Color(0xFF15102A),
|
||||
child: Column(
|
||||
children: [
|
||||
UserAccountsDrawerHeader(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFF281C5C), Color(0xFF15102A)],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
currentAccountPicture: CircleAvatar(
|
||||
backgroundColor: Colors.purpleAccent.withOpacity(0.2),
|
||||
child: const Icon(Icons.person,
|
||||
color: Colors.purpleAccent, size: 40),
|
||||
),
|
||||
accountName: Text(
|
||||
user.name,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold, fontSize: 16),
|
||||
),
|
||||
accountEmail: Text(
|
||||
user.isSuperAdmin
|
||||
? '👑 المشرف العام للمنصة'
|
||||
: '🏢 مدير الشركة',
|
||||
style: const TextStyle(
|
||||
color: Colors.purpleAccent, fontSize: 13),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: [
|
||||
// English: Show Super Admin tab only if current user is_super_admin is true.
|
||||
// Arabic: عرض تبويب المشرف العام فقط إذا كان المستخدم الحالي مشرفاً عاماً.
|
||||
if (user.isSuperAdmin)
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'👑 لوحة المشرف العام',
|
||||
DashboardTab.superAdmin,
|
||||
state.activeTab,
|
||||
Icons.admin_panel_settings,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'📱 اتصال الواتساب',
|
||||
DashboardTab.whatsapp,
|
||||
state.activeTab,
|
||||
Icons.phone_android,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'💳 الباقات والاشتراكات',
|
||||
DashboardTab.billing,
|
||||
state.activeTab,
|
||||
Icons.credit_card,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'👥 دليل جهات الاتصال',
|
||||
DashboardTab.contacts,
|
||||
state.activeTab,
|
||||
Icons.contacts_outlined,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'📝 قوالب الرسائل',
|
||||
DashboardTab.templates,
|
||||
state.activeTab,
|
||||
Icons.message_outlined,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'📣 الحملات التسويقية',
|
||||
DashboardTab.campaigns,
|
||||
state.activeTab,
|
||||
Icons.campaign_outlined,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'🤖 قواعد الرد الآلي',
|
||||
DashboardTab.chatbot,
|
||||
state.activeTab,
|
||||
Icons.android_outlined,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'🔌 التكاملات والربط',
|
||||
DashboardTab.integrations,
|
||||
state.activeTab,
|
||||
Icons.integration_instructions_outlined,
|
||||
),
|
||||
_buildDrawerItem(
|
||||
context,
|
||||
'👤 الموظفين والدعم',
|
||||
DashboardTab.staff,
|
||||
state.activeTab,
|
||||
Icons.people_outline,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(color: Colors.white10),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.logout, color: Colors.redAccent),
|
||||
title: const Text('تسجيل الخروج',
|
||||
style: TextStyle(color: Colors.redAccent)),
|
||||
onTap: () {
|
||||
context.read<AuthCubit>().logout();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: state.isLoading
|
||||
? const Center(
|
||||
child:
|
||||
CircularProgressIndicator(color: Colors.purpleAccent))
|
||||
: state.errorMessage != null
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Text(
|
||||
state.errorMessage!,
|
||||
style: const TextStyle(
|
||||
color: Colors.redAccent, fontSize: 14),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
)
|
||||
: SingleChildScrollView(
|
||||
child: _renderActiveTabContent(context, state),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDrawerItem(
|
||||
BuildContext context,
|
||||
String title,
|
||||
DashboardTab tab,
|
||||
DashboardTab activeTab,
|
||||
IconData icon,
|
||||
) {
|
||||
final isSelected = tab == activeTab;
|
||||
return ListTile(
|
||||
leading:
|
||||
Icon(icon, color: isSelected ? Colors.purpleAccent : Colors.white60),
|
||||
title: Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
color: isSelected ? Colors.purpleAccent : Colors.white,
|
||||
fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
|
||||
),
|
||||
),
|
||||
selected: isSelected,
|
||||
selectedTileColor: Colors.purpleAccent.withOpacity(0.05),
|
||||
onTap: () {
|
||||
// English: Close drawer and switch tab.
|
||||
// Arabic: إغلاق درج القائمة الجانبية وتبديل التبويب.
|
||||
Navigator.pop(context);
|
||||
context.read<DashboardCubit>().changeTab(tab);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _getAppBarTitle(DashboardTab tab) {
|
||||
switch (tab) {
|
||||
case DashboardTab.superAdmin:
|
||||
return 'المشرف العام - نبيه';
|
||||
case DashboardTab.whatsapp:
|
||||
return 'اتصال الواتساب';
|
||||
case DashboardTab.billing:
|
||||
return 'الباقات والاشتراكات';
|
||||
case DashboardTab.contacts:
|
||||
return 'دليل جهات الاتصال';
|
||||
case DashboardTab.templates:
|
||||
return 'قوالب الرسائل';
|
||||
case DashboardTab.campaigns:
|
||||
return 'الحملات التسويقية';
|
||||
case DashboardTab.chatbot:
|
||||
return 'قواعد الرد الآلي';
|
||||
case DashboardTab.integrations:
|
||||
return 'التكاملات والربط';
|
||||
case DashboardTab.staff:
|
||||
return 'الموظفين والدعم';
|
||||
}
|
||||
}
|
||||
|
||||
Widget _renderActiveTabContent(BuildContext context, DashboardState state) {
|
||||
switch (state.activeTab) {
|
||||
case DashboardTab.superAdmin:
|
||||
return SuperAdminView(stats: state.superAdminStats);
|
||||
case DashboardTab.whatsapp:
|
||||
return WhatsAppView(
|
||||
status: state.whatsappStatus,
|
||||
onRefresh: () => context.read<DashboardCubit>().refreshCurrentTab(),
|
||||
);
|
||||
case DashboardTab.billing:
|
||||
return BillingView(plans: state.plans);
|
||||
case DashboardTab.contacts:
|
||||
return ContactsView(contacts: state.contacts);
|
||||
case DashboardTab.chatbot:
|
||||
return ChatbotView(rules: state.chatbotRules);
|
||||
case DashboardTab.templates:
|
||||
return const SimplePlaceholderView(
|
||||
title: 'قوالب الرسائل',
|
||||
description:
|
||||
'ميزة تصميم قوالب رسائل الواتساب الديناميكية تحت التطوير.',
|
||||
icon: Icons.message,
|
||||
);
|
||||
case DashboardTab.campaigns:
|
||||
return const SimplePlaceholderView(
|
||||
title: 'الحملات التسويقية',
|
||||
description:
|
||||
'ميزة إرسال وإدارة الحملات البريدية والجماعية تحت التطوير.',
|
||||
icon: Icons.campaign,
|
||||
);
|
||||
case DashboardTab.integrations:
|
||||
return const SimplePlaceholderView(
|
||||
title: 'التكاملات والربط',
|
||||
description: 'ربط البوابة مع منصات سلة وووردبريس عبر واجهات البرمجة.',
|
||||
icon: Icons.integration_instructions,
|
||||
);
|
||||
case DashboardTab.staff:
|
||||
return const SimplePlaceholderView(
|
||||
title: 'الموظفين والدعم',
|
||||
description:
|
||||
'إضافة وإدارة حسابات الموظفين والعملاء لتوزيع المحادثات.',
|
||||
icon: Icons.people_outline,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../data/models/plan_model.dart';
|
||||
|
||||
class BillingView extends StatelessWidget {
|
||||
final List<PlanModel> plans;
|
||||
|
||||
const BillingView({
|
||||
super.key,
|
||||
required this.plans,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
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: Render list of subscription plan cards.
|
||||
// Arabic: عرض قائمة ببطاقات خطط الاشتراك المتاحة.
|
||||
if (plans.isEmpty)
|
||||
const Center(
|
||||
child: Text(
|
||||
'لا توجد باقات متاحة حالياً.',
|
||||
style: TextStyle(color: Colors.white70),
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: plans.length,
|
||||
itemBuilder: (context, index) {
|
||||
final plan = plans[index];
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
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: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
plan.name,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
const Text(
|
||||
'الدفع شهرياً - إلغاء في أي وقت',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
'\$${plan.price.toStringAsFixed(2)}',
|
||||
style: const TextStyle(
|
||||
color: Colors.purpleAccent,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
const Text(
|
||||
'/شهرياً',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../data/models/chatbot_rule_model.dart';
|
||||
|
||||
class ChatbotView extends StatelessWidget {
|
||||
final List<ChatbotRuleModel> rules;
|
||||
|
||||
const ChatbotView({
|
||||
super.key,
|
||||
required this.rules,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
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: Render list of chatbot rule cards.
|
||||
// Arabic: عرض قائمة ببطاقات قواعد روبوت الدردشة المكونة.
|
||||
if (rules.isEmpty)
|
||||
const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 40.0),
|
||||
child: Text(
|
||||
'لم يتم تكوين قواعد رد آلي بعد.',
|
||||
style: TextStyle(color: Colors.white70),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: rules.length,
|
||||
itemBuilder: (context, index) {
|
||||
final rule = rules[index];
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
padding: const EdgeInsets.all(16),
|
||||
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: [
|
||||
_buildTriggerBadge(rule.triggerType),
|
||||
_buildStatusBadge(rule.isActive),
|
||||
],
|
||||
),
|
||||
const Divider(color: Colors.white10, height: 24),
|
||||
if (rule.triggerType == 'keyword' && rule.keyword != null) ...[
|
||||
const Text(
|
||||
'الكلمة المفتاحية للمشغل:',
|
||||
style: TextStyle(color: Colors.white70, fontSize: 12),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
rule.keyword!,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
const Text(
|
||||
'رد الروبوت أو تعليمات موجه الذكاء الاصطناعي (AI Prompt):',
|
||||
style: TextStyle(color: Colors.white70, fontSize: 12),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
rule.aiPrompt ?? 'لا توجد تعليمات',
|
||||
style: TextStyle(color: Colors.white.withOpacity(0.8), fontSize: 13, height: 1.4),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTriggerBadge(String type) {
|
||||
final isAi = type == 'gemini_ai';
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isAi ? Colors.purpleAccent.withOpacity(0.2) : Colors.blue.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: isAi ? Colors.purpleAccent : Colors.blue),
|
||||
),
|
||||
child: Text(
|
||||
isAi ? '🧠 ذكاء اصطناعي (Gemini)' : '⌨️ كلمات مفتاحية',
|
||||
style: TextStyle(color: isAi ? Colors.purpleAccent : Colors.blue, fontSize: 11, fontWeight: FontWeight.bold),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusBadge(bool isActive) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: isActive ? Colors.green.withOpacity(0.2) : Colors.grey.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: isActive ? Colors.green : Colors.grey),
|
||||
),
|
||||
child: Text(
|
||||
isActive ? 'نشط' : 'غير نشط',
|
||||
style: TextStyle(color: isActive ? Colors.green : Colors.grey, fontSize: 10, fontWeight: FontWeight.bold),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/models/contact_model.dart';
|
||||
import '../cubit/dashboard_cubit.dart';
|
||||
import '../screens/add_contact_screen.dart';
|
||||
|
||||
class ContactsView extends StatelessWidget {
|
||||
final List<ContactModel> contacts;
|
||||
|
||||
const ContactsView({
|
||||
super.key,
|
||||
required this.contacts,
|
||||
});
|
||||
|
||||
// English: Show alert confirmation dialog before navigating.
|
||||
// Arabic: عرض مربع حوار تأكيدي قبل الانتقال إلى الشاشة التالية.
|
||||
void _showNavigationDialog(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: () {
|
||||
// English: Pop dialog window first.
|
||||
// Arabic: إغلاق مربع الحوار أولاً.
|
||||
Navigator.pop(dialogContext);
|
||||
|
||||
// English: Push AddContactScreen, sharing the existing Cubit instance.
|
||||
// Arabic: الانتقال إلى شاشة إضافة جهة اتصال ومشاركة نفس الكيوبيت الحالي.
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => BlocProvider.value(
|
||||
value: context.read<DashboardCubit>(),
|
||||
child: const AddContactScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: const Text('نعم، انتقل', style: TextStyle(color: Colors.purpleAccent)),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const Text(
|
||||
'👥 دليل جهات الاتصال',
|
||||
style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.purpleAccent,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
icon: const Icon(Icons.add, color: Colors.white, size: 16),
|
||||
label: const Text(
|
||||
'إضافة جهة',
|
||||
style: TextStyle(color: Colors.white, fontSize: 12),
|
||||
),
|
||||
onPressed: () => _showNavigationDialog(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'عرض وإدارة دليل العملاء والجهات التي تواصلت مع النظام الآلي.',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 13),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// English: Render list of parsed contacts in custom list view.
|
||||
// Arabic: عرض قائمة بجهات الاتصال المحللة في طريقة عرض القائمة المخصصة.
|
||||
if (contacts.isEmpty)
|
||||
const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 40.0),
|
||||
child: Text(
|
||||
'دليل جهات الاتصال فارغ حالياً.',
|
||||
style: TextStyle(color: Colors.white70),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: contacts.length,
|
||||
itemBuilder: (context, index) {
|
||||
final contact = contacts[index];
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF15102A),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.05)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: Colors.purpleAccent.withOpacity(0.1),
|
||||
),
|
||||
child: const Icon(Icons.person, color: Colors.purpleAccent),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
contact.name,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
contact.phone,
|
||||
style: const TextStyle(color: Colors.purpleAccent, fontSize: 13),
|
||||
),
|
||||
if (contact.notes != null && contact.notes!.isNotEmpty) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
contact.notes!,
|
||||
style: TextStyle(color: Colors.white.withOpacity(0.5), fontSize: 12),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class SimplePlaceholderView extends StatelessWidget {
|
||||
final String title;
|
||||
final String description;
|
||||
final IconData icon;
|
||||
|
||||
const SimplePlaceholderView({
|
||||
super.key,
|
||||
required this.title,
|
||||
required this.description,
|
||||
required this.icon,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// English: Placeholders mimic undeveloped features in standard premium dark cards.
|
||||
// Arabic: تحاكي شاشات الحجز الميزات التي لم يتم تطويرها في بطاقات داكنة مميزة قياسية.
|
||||
return Center(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(20),
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF15102A),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.05)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 64, color: Colors.purpleAccent),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
description,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.6),
|
||||
fontSize: 14,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../data/models/super_admin_stats_model.dart';
|
||||
import '../cubit/dashboard_cubit.dart';
|
||||
|
||||
class SuperAdminView extends StatelessWidget {
|
||||
final SuperAdminStatsModel? stats;
|
||||
|
||||
const SuperAdminView({
|
||||
super.key,
|
||||
required this.stats,
|
||||
});
|
||||
|
||||
// English: Show a confirmation dialog before approving company billing subscription.
|
||||
// Arabic: عرض مربع حوار تأكيدي للموافقة على ترقية الفوترة والاشتراك.
|
||||
void _showApproveDialog(BuildContext context, int companyId, String companyName) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (dialogContext) {
|
||||
return AlertDialog(
|
||||
backgroundColor: const Color(0xFF15102A),
|
||||
title: const Text('الموافقة على الاشتراك', style: TextStyle(color: Colors.white)),
|
||||
content: Text(
|
||||
'هل أنت متأكد من تفعيل اشتراك شركة "$companyName"؟ سيتم ترقية حسابهم على الفور.',
|
||||
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);
|
||||
// English: Dispatch approveBilling command to DashboardCubit.
|
||||
// Arabic: استدعاء أمر الموافقة على الاشتراك في الكيوبيت.
|
||||
context.read<DashboardCubit>().approveBilling(companyId);
|
||||
},
|
||||
child: const Text('نعم، وافق', style: TextStyle(color: Colors.green)),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final model = stats;
|
||||
|
||||
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),
|
||||
if (model == null)
|
||||
const Center(
|
||||
child: Text(
|
||||
'فشل تحميل إحصائيات المشرف العام.',
|
||||
style: TextStyle(color: Colors.white70),
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
// English: Stats widgets mirroring the web interface dashboard indicators.
|
||||
// Arabic: أدوات إحصائية تحاكي مؤشرات لوحة معلومات واجهة الويب.
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
'الشركات المسجلة',
|
||||
model.totalCompanies.toString(),
|
||||
Icons.business,
|
||||
Colors.purpleAccent,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
'جلسات الواتساب',
|
||||
'${model.connectedSessions}/${model.totalSessions}',
|
||||
Icons.phone_android,
|
||||
Colors.green,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
|
||||
// English: Display pending billing approval requests.
|
||||
// Arabic: عرض طلبات الموافقة على ترقية الباقات المعلقة.
|
||||
const Text(
|
||||
'طلبات الترقية المعلقة للموافقة',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (model.pendingApprovals.isEmpty)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.02),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.white12),
|
||||
),
|
||||
child: const Center(
|
||||
child: Text(
|
||||
'لا توجد طلبات ترقية معلقة حالياً.',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 13),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: model.pendingApprovals.length,
|
||||
itemBuilder: (context, index) {
|
||||
final company =
|
||||
model.pendingApprovals[index] as Map<String, dynamic>;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF1E1446),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Colors.purpleAccent.withOpacity(0.3)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
company['name'] as String? ?? 'شركة غير معروفة',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'الباقة المطلوبة: ${company['plan_name'] ?? 'لا يوجد'}',
|
||||
style: const TextStyle(
|
||||
color: Colors.purpleAccent, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.green,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: const Text('موافقة',
|
||||
style: TextStyle(fontSize: 12)),
|
||||
onPressed: () {
|
||||
_showApproveDialog(
|
||||
context,
|
||||
company['id'] as int? ?? 0,
|
||||
company['name'] as String? ?? 'الشركة',
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
|
||||
// English: Display list of SaaS Companies.
|
||||
// Arabic: عرض قائمة الشركات المسجلة وتفاصيل استخداماتها.
|
||||
const Text(
|
||||
'الشركات والعملاء المشتركين',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ListView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: model.companies.length,
|
||||
itemBuilder: (context, index) {
|
||||
final company = model.companies[index] as Map<String, dynamic>;
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 16),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF15102A),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.05)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
company['name'] as String? ?? 'شركة',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
_buildSubBadge(
|
||||
company['sub_status'] as String? ?? 'expired',
|
||||
company['plan_name'] as String?),
|
||||
],
|
||||
),
|
||||
const Divider(color: Colors.white10, height: 24),
|
||||
_buildDetailRow('الجلسات النشطة',
|
||||
'${company['active_sessions'] ?? 0}/${company['sessions_count'] ?? 0}'),
|
||||
const SizedBox(height: 8),
|
||||
// English: Display SaaS resource usages metrics (Requests, Voice, OCR).
|
||||
// Arabic: عرض مقاييس استخدام موارد النظام (الطلبات، الصوت، تحليل الصور).
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
_buildUsageText('الطلبات',
|
||||
(company['request_usage'] ?? 0).toString()),
|
||||
_buildUsageText('الصوت',
|
||||
(company['voice_usage'] ?? 0).toString()),
|
||||
_buildUsageText(
|
||||
'OCR', (company['ocr_usage'] ?? 0).toString()),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMetricCard(
|
||||
String title, String value, IconData icon, Color color) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
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: [
|
||||
Icon(icon, color: color, size: 24),
|
||||
const SizedBox(height: 12),
|
||||
Text(title,
|
||||
style: const TextStyle(color: Colors.white60, fontSize: 12)),
|
||||
const SizedBox(height: 4),
|
||||
Text(value,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSubBadge(String status, String? planName) {
|
||||
final name = planName ?? 'لا توجد باقة';
|
||||
Color color = Colors.grey;
|
||||
if (status == 'active') {
|
||||
color = Colors.green;
|
||||
} else if (status == 'trialing') {
|
||||
color = Colors.blue;
|
||||
}
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: color),
|
||||
),
|
||||
child: Text(
|
||||
name,
|
||||
style:
|
||||
TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.bold),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailRow(String label, String value) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(label,
|
||||
style: const TextStyle(color: Colors.white60, fontSize: 13)),
|
||||
Text(value,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUsageText(String label, String value) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label,
|
||||
style: const TextStyle(color: Colors.white54, fontSize: 11)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value,
|
||||
style: const TextStyle(
|
||||
color: Colors.purpleAccent,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user