@php use App\Models\Customer; use App\Models\Invoice; use App\Models\Lead; use App\Models\Proposal; use App\Models\Estimation; use Carbon\Carbon; use Illuminate\Support\Facades\DB; // ========================================================================= // ROLE-BASED ACCESS CONTROL // ========================================================================= $currentUser = auth('admin')->user(); $isSuperAdmin = $currentUser->hasRole('super-admin'); $currentUserId = $currentUser->id; // Permission checks $canViewAllLeads = $currentUser->can('leads.all-leads.read'); $canViewAllInvoices = $currentUser->can('sales.Invoice.read'); // Staff ID if using staff table (optional - uncomment if needed) // $staffId = $currentUser->staff?->id; // ========================================================================= // Field names for filtering // ========================================================================= $assignedField = 'assigned'; // For leads - who is assigned $invoiceAssignedField = 'assigned_to'; // For invoices - assigned_to $invoiceCreatedField = 'created_by'; // For invoices - created_by // Date Range $fromDate = request('from_date') ? Carbon::parse(request('from_date'))->startOfDay() : Carbon::now()->startOfMonth(); $toDate = request('to_date') ? Carbon::parse(request('to_date'))->endOfDay() : Carbon::now()->endOfDay(); $dateRange = [ 'from' => $fromDate->format('Y-m-d'), 'to' => $toDate->format('Y-m-d'), ]; // Helper function function formatCurrencyDash($amount, $symbol = '₹') { $amount = $amount ?? 0; if ($amount >= 10000000) return $symbol . number_format($amount / 10000000, 2) . ' Cr'; if ($amount >= 100000) return $symbol . number_format($amount / 100000, 2) . ' L'; if ($amount >= 1000) return $symbol . number_format($amount / 1000, 2) . ' K'; return $symbol . number_format($amount, 2); } // ========================================================================= // REVENUE STATS (Filtered based on invoice permission) // ========================================================================= $invoiceBaseQuery = Invoice::query(); if (!$canViewAllInvoices) { $invoiceBaseQuery->where(function($q) use ($currentUserId, $invoiceAssignedField, $invoiceCreatedField) { $q->where($invoiceAssignedField, $currentUserId) ->orWhere($invoiceCreatedField, $currentUserId); }); } $totalRevenue = (clone $invoiceBaseQuery)->where('payment_status', 'paid')->sum('total') ?? 0; $periodRevenue = (clone $invoiceBaseQuery)->where('payment_status', 'paid') ->whereBetween('created_at', [$fromDate, $toDate]) ->sum('total') ?? 0; $periodDays = $fromDate->diffInDays($toDate); $prevFromDate = (clone $fromDate)->subDays($periodDays + 1); $prevToDate = (clone $fromDate)->subDay(); $prevPeriodRevenue = (clone $invoiceBaseQuery)->where('payment_status', 'paid') ->whereBetween('created_at', [$prevFromDate, $prevToDate]) ->sum('total') ?? 0; $revenueGrowth = $prevPeriodRevenue > 0 ? round((($periodRevenue - $prevPeriodRevenue) / $prevPeriodRevenue) * 100, 1) : ($periodRevenue > 0 ? 100 : 0); // ========================================================================= // CUSTOMER STATS (NO FILTERING - Customers are company-wide) // ========================================================================= $totalCustomers = Customer::where('active', 1)->count(); $newCustomers = Customer::whereBetween('created_at', [$fromDate, $toDate])->count(); $companyCustomers = Customer::where('customer_type', 'company')->where('active', 1)->count(); $individualCustomers = Customer::where('customer_type', 'individual')->where('active', 1)->count(); // ========================================================================= // INVOICE STATS (Filtered based on permission) // ========================================================================= $pendingAmount = (clone $invoiceBaseQuery)->whereIn('payment_status', ['unpaid', 'partial'])->sum('amount_due') ?? 0; $pendingCount = (clone $invoiceBaseQuery)->whereIn('payment_status', ['unpaid', 'partial'])->count(); $overdueCount = (clone $invoiceBaseQuery)->where('due_date', '<', Carbon::now())->whereIn('payment_status', ['unpaid', 'partial'])->count(); $overdueAmount = (clone $invoiceBaseQuery)->where('due_date', '<', Carbon::now())->whereIn('payment_status', ['unpaid', 'partial'])->sum('amount_due') ?? 0; $paidCount = (clone $invoiceBaseQuery)->where('payment_status', 'paid')->count(); $partialCount = (clone $invoiceBaseQuery)->where('payment_status', 'partial')->count(); $unpaidCount = (clone $invoiceBaseQuery)->where('payment_status', 'unpaid')->count(); $totalInvoiceCount = (clone $invoiceBaseQuery)->count(); // ========================================================================= // LEAD STATS (Filtered based on permission) // ========================================================================= $leadQuery = Lead::query(); if (!$canViewAllLeads) { // Filter leads by who is assigned to work on them $leadQuery->where($assignedField, $currentUserId); } $openLeads = (clone $leadQuery)->where('lost', 0)->where('junk', 0)->count(); $newLeads = (clone $leadQuery)->whereBetween('created_at', [$fromDate, $toDate])->count(); $totalLeadValue = (clone $leadQuery)->where('lost', 0)->where('junk', 0)->sum('lead_value') ?? 0; $lostLeads = (clone $leadQuery)->where('lost', 1)->count(); $junkLeads = (clone $leadQuery)->where('junk', 1)->count(); $convertedLeads = (clone $leadQuery)->whereBetween('date_converted', [$fromDate, $toDate])->count(); // ========================================================================= // PROPOSAL STATS (NO FILTERING - Company-wide) // ========================================================================= $totalProposals = Proposal::count(); $acceptedProposals = Proposal::where('status', 'accepted')->count(); $draftProposals = Proposal::where('status', 'draft')->count(); $sentProposals = Proposal::where('status', 'sent')->count(); // ========================================================================= // ESTIMATION STATS (NO FILTERING - Company-wide) // ========================================================================= $totalEstimations = Estimation::count(); $approvedEstimations = Estimation::where('status', 'approved')->count(); $draftEstimations = Estimation::where('status', 'draft')->count(); // ========================================================================= // CHART DATA - Revenue Trend (Filtered based on permission) // ========================================================================= $days = $fromDate->diffInDays($toDate); $revenueTrendLabels = []; $revenueTrendValues = []; $revenueChartQuery = (clone $invoiceBaseQuery)->where('payment_status', 'paid') ->whereBetween('created_at', [$fromDate, $toDate]); if ($days <= 31) { $revenueData = (clone $revenueChartQuery) ->selectRaw('DATE(created_at) as date, SUM(total) as total') ->groupByRaw('DATE(created_at)') ->orderByRaw('DATE(created_at)') ->pluck('total', 'date') ->toArray(); $current = clone $fromDate; while ($current <= $toDate) { $dateStr = $current->format('Y-m-d'); $revenueTrendLabels[] = $current->format('d M'); $revenueTrendValues[] = (float)($revenueData[$dateStr] ?? 0); $current->addDay(); } } else { $revenueData = (clone $revenueChartQuery) ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, SUM(total) as total') ->groupByRaw('YEAR(created_at), MONTH(created_at)') ->orderByRaw('YEAR(created_at), MONTH(created_at)') ->get(); foreach ($revenueData as $row) { $revenueTrendLabels[] = Carbon::create($row->year, $row->month, 1)->format('M Y'); $revenueTrendValues[] = (float)$row->total; } } // Chart Data - Invoice Status $invoiceStatusLabels = ['Paid', 'Partial', 'Unpaid', 'Overdue']; $invoiceStatusValues = [$paidCount, $partialCount, $unpaidCount, $overdueCount]; $invoiceStatusColors = ['#10b981', '#f59e0b', '#6b7280', '#ef4444']; // ========================================================================= // CHART DATA - Lead Status (Filtered based on permission) // ========================================================================= $leadStatusQuery = DB::table('leads') ->join('leads_status', 'leads.status', '=', 'leads_status.id') ->where('leads.lost', 0) ->where('leads.junk', 0); if (!$canViewAllLeads) { $leadStatusQuery->where("leads.{$assignedField}", $currentUserId); } $leadStatuses = $leadStatusQuery ->select('leads_status.id', 'leads_status.name', 'leads_status.color', DB::raw('COUNT(*) as count')) ->groupBy('leads_status.id', 'leads_status.name', 'leads_status.color') ->get(); $leadStatusLabels = $leadStatuses->pluck('name')->toArray(); $leadStatusValues = $leadStatuses->pluck('count')->toArray(); $leadStatusColors = $leadStatuses->pluck('color')->map(fn($c) => $c ?? '#3498db')->toArray(); $leadStatusIds = $leadStatuses->pluck('id')->toArray(); if ($lostLeads > 0) { $leadStatusLabels[] = 'Lost'; $leadStatusValues[] = $lostLeads; $leadStatusColors[] = '#e74c3c'; $leadStatusIds[] = 'lost'; } if ($junkLeads > 0) { $leadStatusLabels[] = 'Junk'; $leadStatusValues[] = $junkLeads; $leadStatusColors[] = '#95a5a6'; $leadStatusIds[] = 'junk'; } // ========================================================================= // CHART DATA - Customer Growth (NO FILTERING - Company-wide) // ========================================================================= $customerGrowthLabels = []; $customerGrowthValues = []; for ($i = 5; $i >= 0; $i--) { $date = Carbon::now()->subMonths($i); $customerGrowthLabels[] = $date->format('M Y'); $customerGrowthValues[] = Customer::whereYear('created_at', $date->year)->whereMonth('created_at', $date->month)->count(); } // ========================================================================= // MONTHLY COMPARISON (Leads and Invoices filtered based on permission) // ========================================================================= $currentMonth = Carbon::now(); $lastMonth = Carbon::now()->subMonth(); // Current Month Queries (filtered) $currentMonthLeadQuery = Lead::whereMonth('created_at', $currentMonth->month)->whereYear('created_at', $currentMonth->year); if (!$canViewAllLeads) { $currentMonthLeadQuery->where($assignedField, $currentUserId); } $currentMonthInvoiceQuery = Invoice::whereMonth('created_at', $currentMonth->month)->whereYear('created_at', $currentMonth->year); if (!$canViewAllInvoices) { $currentMonthInvoiceQuery->where(function($q) use ($currentUserId, $invoiceAssignedField, $invoiceCreatedField) { $q->where($invoiceAssignedField, $currentUserId)->orWhere($invoiceCreatedField, $currentUserId); }); } $currentMonthData = [ 'label' => $currentMonth->format('M Y'), 'revenue' => (clone $currentMonthInvoiceQuery)->where('payment_status', 'paid')->sum('total') ?? 0, 'invoices' => (clone $currentMonthInvoiceQuery)->count(), 'customers' => Customer::whereMonth('created_at', $currentMonth->month)->whereYear('created_at', $currentMonth->year)->count(), 'leads' => $currentMonthLeadQuery->count(), ]; // Last Month Queries (filtered) $lastMonthLeadQuery = Lead::whereMonth('created_at', $lastMonth->month)->whereYear('created_at', $lastMonth->year); if (!$canViewAllLeads) { $lastMonthLeadQuery->where($assignedField, $currentUserId); } $lastMonthInvoiceQuery = Invoice::whereMonth('created_at', $lastMonth->month)->whereYear('created_at', $lastMonth->year); if (!$canViewAllInvoices) { $lastMonthInvoiceQuery->where(function($q) use ($currentUserId, $invoiceAssignedField, $invoiceCreatedField) { $q->where($invoiceAssignedField, $currentUserId)->orWhere($invoiceCreatedField, $currentUserId); }); } $lastMonthData = [ 'label' => $lastMonth->format('M Y'), 'revenue' => (clone $lastMonthInvoiceQuery)->where('payment_status', 'paid')->sum('total') ?? 0, 'invoices' => (clone $lastMonthInvoiceQuery)->count(), 'customers' => Customer::whereMonth('created_at', $lastMonth->month)->whereYear('created_at', $lastMonth->year)->count(), 'leads' => $lastMonthLeadQuery->count(), ]; // ========================================================================= // RECENT DATA (Leads and Invoices filtered based on permission) // ========================================================================= $recentLeadsQuery = Lead::with(['leadStatus', 'leadSource'])->where('lost', 0)->where('junk', 0)->latest(); if (!$canViewAllLeads) { $recentLeadsQuery->where($assignedField, $currentUserId); } $recentInvoicesQuery = Invoice::with('customer')->latest(); if (!$canViewAllInvoices) { $recentInvoicesQuery->where(function($q) use ($currentUserId, $invoiceAssignedField, $invoiceCreatedField) { $q->where($invoiceAssignedField, $currentUserId)->orWhere($invoiceCreatedField, $currentUserId); }); } $recentInvoices = $recentInvoicesQuery->take(5)->get(); $recentCustomers = Customer::latest()->take(5)->get(); $recentLeads = $recentLeadsQuery->take(5)->get(); @endphp

Dashboard

@if(!$canViewAllLeads) My Leads @endif @if(!$canViewAllInvoices) My Invoices @endif
{{-- Date Range Filter --}}
Reset
{{-- Welcome Section --}}

Welcome back, {{ $currentUser->name ?? 'Admin' }}! 👋

Showing data from {{ Carbon::parse($dateRange['from'])->format('d M Y') }} to {{ Carbon::parse($dateRange['to'])->format('d M Y') }}

{{-- Main Stats Grid --}}
{{-- Revenue Card --}}
@if($revenueGrowth >= 0) ↑ {{ $revenueGrowth }}% @else ↓ {{ abs($revenueGrowth) }}% @endif

Period Revenue

{{ formatCurrencyDash($periodRevenue) }}

Total: {{ formatCurrencyDash($totalRevenue) }}

{{-- Customers Card --}}
+{{ $newCustomers }} new

Total Customers

{{ number_format($totalCustomers) }}

{{ $companyCustomers }} Companies • {{ $individualCustomers }} Individuals

{{-- Pending Invoices Card --}}
{{ $pendingCount }} pending

Pending Amount

{{ formatCurrencyDash($pendingAmount) }}

{{ $overdueCount }} overdue ({{ formatCurrencyDash($overdueAmount) }})

{{-- Leads Card - CLICKABLE --}}
+{{ $newLeads }} new

{{ $canViewAllLeads ? 'Open Leads' : 'My Open Leads' }}

{{ number_format($openLeads) }}

Pipeline: {{ formatCurrencyDash($totalLeadValue) }}

{{-- Charts Row --}}
{{-- Revenue Trend Chart --}}

📈 Revenue Trend

{{-- Invoice Status Pie Chart --}}

📊 Invoice Status

{{-- Second Charts Row --}}
{{-- Lead Status Pie Chart - CLICKABLE --}}

🎯 {{ $canViewAllLeads ? 'Lead Status Distribution' : 'My Lead Status' }}

View all

Click on any segment to filter leads by status

{{-- Customer Growth Chart --}}

👥 Customer Growth (Last 6 Months)

{{-- Monthly Comparison Report --}}

📊 Monthly Comparison Report

{{-- Revenue Comparison --}}

Revenue

{{ $currentMonthData['label'] }}

₹{{ number_format($currentMonthData['revenue'], 2) }}

{{ $lastMonthData['label'] }}

₹{{ number_format($lastMonthData['revenue'], 2) }}

{{-- Invoices Comparison --}}

Invoices Created

{{ $currentMonthData['label'] }}

{{ $currentMonthData['invoices'] }}

{{ $lastMonthData['label'] }}

{{ $lastMonthData['invoices'] }}

{{-- Customers Comparison --}}

New Customers

{{ $currentMonthData['label'] }}

{{ $currentMonthData['customers'] }}

{{ $lastMonthData['label'] }}

{{ $lastMonthData['customers'] }}

{{-- Leads Comparison --}}

New Leads

{{ $currentMonthData['label'] }}

{{ $currentMonthData['leads'] }}

{{ $lastMonthData['label'] }}

{{ $lastMonthData['leads'] }}

{{-- Quick Stats Cards --}}
{{-- Proposals --}}
📄
Proposals
Total {{ $totalProposals }}
Accepted {{ $acceptedProposals }}
Pending {{ $draftProposals + $sentProposals }}
{{-- Estimations --}}
📋
Estimations
Total {{ $totalEstimations }}
Approved {{ $approvedEstimations }}
Draft {{ $draftEstimations }}
{{-- Invoices Summary --}}
{{ $canViewAllInvoices ? 'Invoices' : 'My Invoices' }}
Total {{ $totalInvoiceCount }}
Paid {{ $paidCount }}
Overdue {{ $overdueCount }}
{{-- Lead Pipeline --}}
📈
{{ $canViewAllLeads ? 'Lead Pipeline' : 'My Pipeline' }}
Value {{ formatCurrencyDash($totalLeadValue) }}
Converted {{ $convertedLeads }}
Lost {{ $lostLeads }}
{{-- Recent Data Tables --}}
{{-- Recent Invoices --}}

{{ $canViewAllInvoices ? 'Recent Invoices' : 'My Recent Invoices' }}

View all →
@if($recentInvoices->count() > 0) @foreach($recentInvoices as $invoice) @endforeach

{{ $invoice->invoice_number }}

{{ $invoice->customer->name ?? $invoice->customer->company ?? 'N/A' }}

{{ formatCurrencyDash($invoice->total) }}

@if($invoice->payment_status === 'paid') Paid @elseif($invoice->payment_status === 'partial') Partial @elseif($invoice->due_date && $invoice->due_date < now()) Overdue @else {{ ucfirst($invoice->payment_status) }} @endif
@else

No invoices yet

@endif
{{-- Recent Customers --}}

Recent Customers

View all →
@if($recentCustomers->count() > 0) @foreach($recentCustomers as $customer) @endforeach
{{ strtoupper(substr($customer->name ?? 'C', 0, 1)) }}

{{ $customer->display_name }}

{{ $customer->email ?? '-' }}

@if($customer->customer_type === 'company') Company @else Individual @endif
@else

No customers yet

@endif
{{-- Recent Leads - CLICKABLE ROWS --}}

{{ $canViewAllLeads ? 'Recent Leads' : 'My Recent Leads' }}

View all →
@if($recentLeads->count() > 0) @foreach($recentLeads as $lead) @endforeach

{{ $lead->name }}

{{ $lead->company ?? $lead->email ?? '-' }}

{{ formatCurrencyDash($lead->lead_value ?? 0) }}

{{ $lead->leadStatus->name ?? '-' }}
@else

No leads yet

@endif
{{-- Chart.js --}}