Update: 2026-05-08 01:59:25

This commit is contained in:
Hamza-Ayed
2026-05-08 01:59:25 +03:00
parent 7528ec992d
commit 1cd511f12e
9 changed files with 507 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
<?php
/**
* Referral System — Generate & Track Referral Codes
* GET /v1/referral/my-code — Get or generate user's referral code
*/
use App\Core\Database;
use App\Middleware\AuthMiddleware;
$decoded = AuthMiddleware::check();
$db = Database::getInstance();
$userId = $decoded['user_id'];
$tenantId = $decoded['tenant_id'];
try {
// Check if user already has a referral code
$stmt = $db->prepare("SELECT * FROM referral_codes WHERE user_id = ?");
$stmt->execute([$userId]);
$existing = $stmt->fetch();
if ($existing) {
// Get referral stats
$statsStmt = $db->prepare("
SELECT
COUNT(*) as total_referrals,
SUM(CASE WHEN status = 'registered' THEN 1 ELSE 0 END) as registered,
SUM(CASE WHEN status = 'subscribed' THEN 1 ELSE 0 END) as subscribed,
SUM(CASE WHEN reward_claimed = 1 THEN 1 ELSE 0 END) as rewards_claimed
FROM referrals WHERE referrer_id = ?
");
$statsStmt->execute([$userId]);
$stats = $statsStmt->fetch();
// Recent referrals
$recentStmt = $db->prepare("
SELECT r.*, u.name as referred_name
FROM referrals r
LEFT JOIN users u ON r.referred_id = u.id
WHERE r.referrer_id = ?
ORDER BY r.created_at DESC LIMIT 10
");
$recentStmt->execute([$userId]);
$recent = $recentStmt->fetchAll();
// Decrypt names
foreach ($recent as &$ref) {
if (!empty($ref['referred_name'])) {
$dec = \App\Core\Encryption::decrypt($ref['referred_name']);
$ref['referred_name'] = ($dec !== false && $dec !== null) ? $dec : $ref['referred_name'];
}
}
json_success([
'code' => $existing['code'],
'link' => 'https://musadaq.intaleqapp.com/ref/' . $existing['code'],
'created_at' => $existing['created_at'],
'stats' => [
'total' => (int)($stats['total_referrals'] ?? 0),
'registered' => (int)($stats['registered'] ?? 0),
'subscribed' => (int)($stats['subscribed'] ?? 0),
'rewards_claimed' => (int)($stats['rewards_claimed'] ?? 0),
],
'recent' => $recent,
'reward_rules' => [
'per_registration' => '1 شهر مجاني على الباقة الحالية',
'per_subscription' => '2 شهر مجاني + رفع الحد 50 فاتورة',
],
], 'رمز الإحالة الخاص بك');
} else {
// Generate new referral code
$code = 'MSQ-' . strtoupper(substr(md5($userId . time()), 0, 6));
$db->prepare("INSERT INTO referral_codes (id, user_id, tenant_id, code, created_at) VALUES (UUID(), ?, ?, ?, NOW())")
->execute([$userId, $tenantId, $code]);
json_success([
'code' => $code,
'link' => 'https://musadaq.intaleqapp.com/ref/' . $code,
'created_at' => date('Y-m-d H:i:s'),
'stats' => ['total' => 0, 'registered' => 0, 'subscribed' => 0, 'rewards_claimed' => 0],
'recent' => [],
'reward_rules' => [
'per_registration' => '1 شهر مجاني على الباقة الحالية',
'per_subscription' => '2 شهر مجاني + رفع الحد 50 فاتورة',
],
], 'تم إنشاء رمز الإحالة');
}
} catch (\Exception $e) {
error_log("Referral error: " . $e->getMessage());
json_error('حدث خطأ في نظام الإحالة', 500);
}

View File

@@ -23,6 +23,7 @@ import '../../features/onboarding/views/onboarding_view.dart';
import '../../features/tenants/views/tenants_management_view.dart'; import '../../features/tenants/views/tenants_management_view.dart';
import '../../features/reports/views/tax_report_view.dart'; import '../../features/reports/views/tax_report_view.dart';
import '../../features/audit/views/audit_log_view.dart'; import '../../features/audit/views/audit_log_view.dart';
import '../../features/referral/views/referral_view.dart';
part 'app_routes.dart'; part 'app_routes.dart';
@@ -161,5 +162,9 @@ class AppPages {
name: AppRoutes.AUDIT_LOG, name: AppRoutes.AUDIT_LOG,
page: () => const AuditLogView(), page: () => const AuditLogView(),
), ),
GetPage(
name: AppRoutes.REFERRAL,
page: () => const ReferralView(),
),
]; ];
} }

View File

@@ -23,4 +23,5 @@ abstract class AppRoutes {
static const USERS_MANAGEMENT = '/users-management'; static const USERS_MANAGEMENT = '/users-management';
static const TAX_REPORT = '/tax-report'; static const TAX_REPORT = '/tax-report';
static const AUDIT_LOG = '/audit-log'; static const AUDIT_LOG = '/audit-log';
static const REFERRAL = '/referral';
} }

View File

@@ -250,6 +250,14 @@ class DashboardView extends GetView<DashboardController> {
isDark, isDark,
() => Get.toNamed(AppRoutes.AUDIT_LOG), () => Get.toNamed(AppRoutes.AUDIT_LOG),
), ),
const SizedBox(width: 12),
_buildAdminActionCard(
'ادعُ واكسب',
Icons.card_giftcard,
const Color(0xFFD4AF37),
isDark,
() => Get.toNamed(AppRoutes.REFERRAL),
),
], ],
), ),
), ),

View File

@@ -0,0 +1,34 @@
import 'package:get/get.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/logger.dart';
class ReferralController extends GetxController {
var isLoading = true.obs;
var referralData = Rxn<Map<String, dynamic>>();
@override
void onInit() {
super.onInit();
fetchReferralCode();
}
String get code => referralData.value?['code'] ?? '';
String get link => referralData.value?['link'] ?? '';
Map<String, dynamic> get stats => Map<String, dynamic>.from(referralData.value?['stats'] ?? {});
List get recent => referralData.value?['recent'] ?? [];
Map<String, dynamic> get rewardRules => Map<String, dynamic>.from(referralData.value?['reward_rules'] ?? {});
Future<void> fetchReferralCode() async {
try {
isLoading.value = true;
final res = await DioClient().client.get('referral/my-code');
if (res.data['success'] == true) {
referralData.value = Map<String, dynamic>.from(res.data['data']);
}
} catch (e) {
AppLogger.error('Failed to fetch referral code', e);
} finally {
isLoading.value = false;
}
}
}

View File

@@ -0,0 +1,306 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../controllers/referral_controller.dart';
import '../../../core/utils/app_snackbar.dart';
class ReferralView extends StatelessWidget {
const ReferralView({super.key});
@override
Widget build(BuildContext context) {
final controller = Get.put(ReferralController());
final isDark = Theme.of(context).brightness == Brightness.dark;
return Scaffold(
backgroundColor: isDark ? const Color(0xFF121212) : const Color(0xFFF5F7FA),
appBar: AppBar(
title: const Text('ادعُ واكسب', style: TextStyle(fontWeight: FontWeight.bold)),
centerTitle: true,
backgroundColor: const Color(0xFF0F4C81),
foregroundColor: Colors.white,
),
body: Obx(() {
if (controller.isLoading.value) {
return const Center(child: CircularProgressIndicator(color: Color(0xFF0F4C81)));
}
return SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
children: [
// Hero Banner
_buildHeroBanner(controller, isDark),
const SizedBox(height: 20),
// Stats Cards
_buildStatsRow(controller.stats, isDark),
const SizedBox(height: 20),
// Rewards Info
_buildRewardsCard(controller.rewardRules, isDark),
const SizedBox(height: 20),
// How it works
_buildHowItWorks(isDark),
const SizedBox(height: 20),
// Recent referrals
if (controller.recent.isNotEmpty) ...[
_buildRecentReferrals(controller.recent, isDark),
],
const SizedBox(height: 40),
],
),
);
}),
);
}
Widget _buildHeroBanner(ReferralController controller, bool isDark) {
return Container(
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF0F4C81), Color(0xFF1A6BB5), Color(0xFF2980B9)],
begin: Alignment.topLeft, end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(color: const Color(0xFF0F4C81).withValues(alpha: 0.3), blurRadius: 15, offset: const Offset(0, 6)),
],
),
child: Column(
children: [
const Icon(Icons.card_giftcard, size: 48, color: Color(0xFFD4AF37)),
const SizedBox(height: 12),
const Text(
'ادعُ صديقك واحصل على\nشهر مجاني!',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white, height: 1.4),
),
const SizedBox(height: 16),
// Code display
Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
controller.code,
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 3, fontFamily: 'monospace'),
),
const SizedBox(width: 12),
GestureDetector(
onTap: () {
Clipboard.setData(ClipboardData(text: controller.code));
AppSnackbar.showSuccess('تم النسخ', 'تم نسخ رمز الإحالة');
},
child: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: const Color(0xFFD4AF37),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.copy, size: 18, color: Colors.white),
),
),
],
),
),
const SizedBox(height: 12),
// Share link button
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
Clipboard.setData(ClipboardData(text: controller.link));
AppSnackbar.showSuccess('تم النسخ', 'تم نسخ رابط الإحالة');
},
icon: const Icon(Icons.share, size: 18),
label: const Text('نسخ رابط الدعوة', style: TextStyle(fontWeight: FontWeight.bold)),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFD4AF37),
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
),
],
),
);
}
Widget _buildStatsRow(Map<String, dynamic> stats, bool isDark) {
return Row(
children: [
Expanded(child: _statCard('الدعوات', '${stats['total'] ?? 0}', Icons.people_alt, const Color(0xFF3B82F6), isDark)),
const SizedBox(width: 10),
Expanded(child: _statCard('مسجّلين', '${stats['registered'] ?? 0}', Icons.person_add, const Color(0xFF10B981), isDark)),
const SizedBox(width: 10),
Expanded(child: _statCard('مشتركين', '${stats['subscribed'] ?? 0}', Icons.workspace_premium, const Color(0xFFD4AF37), isDark)),
],
);
}
Widget _statCard(String label, String value, IconData icon, Color color, bool isDark) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
),
child: Column(
children: [
Icon(icon, size: 22, color: color),
const SizedBox(height: 8),
Text(value, style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: isDark ? Colors.white : Colors.black87, fontFamily: 'monospace')),
const SizedBox(height: 4),
Text(label, style: TextStyle(fontSize: 11, color: isDark ? Colors.white38 : Colors.grey)),
],
),
);
}
Widget _buildRewardsCard(Map<String, dynamic> rules, bool isDark) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFD4AF37).withValues(alpha: 0.3)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Row(
children: [
Icon(Icons.emoji_events, color: Color(0xFFD4AF37), size: 22),
SizedBox(width: 8),
Text('المكافآت', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
],
),
const SizedBox(height: 14),
_rewardRow('عند تسجيل صديقك', rules['per_registration'] ?? '', Icons.person_add, const Color(0xFF10B981), isDark),
const SizedBox(height: 10),
_rewardRow('عند اشتراكه', rules['per_subscription'] ?? '', Icons.workspace_premium, const Color(0xFFD4AF37), isDark),
],
),
);
}
Widget _rewardRow(String trigger, String reward, IconData icon, Color color, bool isDark) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.06),
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Icon(icon, size: 20, color: color),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(trigger, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: isDark ? Colors.white70 : Colors.black87)),
Text(reward, style: TextStyle(fontSize: 12, color: color, fontWeight: FontWeight.bold)),
],
),
),
],
),
);
}
Widget _buildHowItWorks(bool isDark) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('كيف يعمل؟', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: isDark ? Colors.white : Colors.black87)),
const SizedBox(height: 14),
_stepItem('1', 'شارك رمز الإحالة مع زميلك', Icons.share, const Color(0xFF3B82F6), isDark),
const SizedBox(height: 10),
_stepItem('2', 'يسجّل في مُصادَق بالرمز', Icons.person_add, const Color(0xFF6366F1), isDark),
const SizedBox(height: 10),
_stepItem('3', 'كلاكما يحصل على المكافأة!', Icons.celebration, const Color(0xFFD4AF37), isDark),
],
),
);
}
Widget _stepItem(String num, String text, IconData icon, Color color, bool isDark) {
return Row(
children: [
Container(
width: 32, height: 32,
decoration: BoxDecoration(
color: color.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
),
child: Center(child: Text(num, style: TextStyle(fontWeight: FontWeight.w900, color: color, fontSize: 14))),
),
const SizedBox(width: 12),
Icon(icon, size: 18, color: color),
const SizedBox(width: 8),
Expanded(child: Text(text, style: TextStyle(fontSize: 13, color: isDark ? Colors.white70 : Colors.black87))),
],
);
}
Widget _buildRecentReferrals(List recent, bool isDark) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('آخر الإحالات', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: isDark ? Colors.white : Colors.black87)),
const SizedBox(height: 12),
...recent.map((r) {
final status = r['status'] ?? 'clicked';
final statusColor = status == 'subscribed' ? const Color(0xFFD4AF37) : status == 'registered' ? const Color(0xFF10B981) : Colors.grey;
final statusLabel = status == 'subscribed' ? 'مشترك' : status == 'registered' ? 'مسجّل' : 'ضغط الرابط';
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
children: [
CircleAvatar(radius: 16, backgroundColor: statusColor.withValues(alpha: 0.1), child: Icon(Icons.person, size: 16, color: statusColor)),
const SizedBox(width: 10),
Expanded(child: Text(r['referred_name'] ?? 'مستخدم', style: TextStyle(fontSize: 14, color: isDark ? Colors.white : Colors.black87))),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(color: statusColor.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(6)),
child: Text(statusLabel, style: TextStyle(fontSize: 11, color: statusColor, fontWeight: FontWeight.w600)),
),
],
),
);
}),
],
),
);
}
}

View File

@@ -42,6 +42,7 @@ $routes = [
'v1/audit-log' => ['GET', 'audit/index.php'], 'v1/audit-log' => ['GET', 'audit/index.php'],
'v1/notifications' => ['GET', 'notifications/index.php'], 'v1/notifications' => ['GET', 'notifications/index.php'],
'v1/notifications/read' => ['POST', 'notifications/read.php'], 'v1/notifications/read' => ['POST', 'notifications/read.php'],
'v1/referral/my-code' => ['GET', 'referral/my_code.php'],
'v1/companies/stats' => ['GET', 'companies/stats.php'], 'v1/companies/stats' => ['GET', 'companies/stats.php'],
'v1/companies/connect' => ['POST', 'companies/connect_jofotara.php'], 'v1/companies/connect' => ['POST', 'companies/connect_jofotara.php'],
'v1/dashboard/stats' => ['GET', 'dashboard/stats.php'], 'v1/dashboard/stats' => ['GET', 'dashboard/stats.php'],

View File

@@ -0,0 +1,28 @@
-- Referral System Tables
CREATE TABLE IF NOT EXISTS referral_codes (
id CHAR(36) PRIMARY KEY,
user_id CHAR(36) NOT NULL,
tenant_id CHAR(36) NOT NULL,
code VARCHAR(20) NOT NULL UNIQUE,
is_active TINYINT(1) DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user (user_id),
INDEX idx_code (code),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS referrals (
id CHAR(36) PRIMARY KEY,
referrer_id CHAR(36) NOT NULL,
referred_id CHAR(36) NULL,
referral_code VARCHAR(20) NOT NULL,
status ENUM('clicked', 'registered', 'subscribed') DEFAULT 'clicked',
reward_claimed TINYINT(1) DEFAULT 0,
reward_type VARCHAR(50) NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
converted_at TIMESTAMP NULL,
INDEX idx_referrer (referrer_id),
INDEX idx_code (referral_code),
FOREIGN KEY (referrer_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@@ -0,0 +1,32 @@
-- Restore original Musadaq subscription pricing
-- Premium pricing justified by AI extraction + JoFotara + mobile app
UPDATE subscription_plans SET
name_ar = 'مجانية', name_en = 'Free',
max_companies = 1, max_invoices_month = 15, max_users = 1,
price_jod = 0.00, jofotara_enabled = 1
WHERE id = 'free';
UPDATE subscription_plans SET
name_ar = 'أساسية', name_en = 'Basic',
max_companies = 3, max_invoices_month = 100, max_users = 3,
price_jod = 15.00, jofotara_enabled = 1
WHERE id = 'basic';
UPDATE subscription_plans SET
name_ar = 'مكتبية', name_en = 'Office',
max_companies = 10, max_invoices_month = 500, max_users = 10,
price_jod = 45.00, jofotara_enabled = 1
WHERE id = 'office';
UPDATE subscription_plans SET
name_ar = 'احترافية', name_en = 'Pro',
max_companies = 25, max_invoices_month = 2000, max_users = 25,
price_jod = 99.00, jofotara_enabled = 1
WHERE id = 'pro';
UPDATE subscription_plans SET
name_ar = 'مؤسسية', name_en = 'Enterprise',
max_companies = 999, max_invoices_month = 99999, max_users = 999,
price_jod = 249.00, jofotara_enabled = 1
WHERE id = 'enterprise';