Add customer contact inquiry system, automated receipt emails, admin communication inbox, and customer profile management

This commit is contained in:
2026-11-02 09:56:24 +01:00
parent 387241f971
commit 9fd39bd7d6
28 changed files with 2426 additions and 8 deletions
@@ -0,0 +1,139 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Mail\ContactInquiryReplyMail;
use App\Models\Communication;
use App\Models\CommunicationReply;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\View\View;
class CommunicationController extends Controller
{
/**
* Display a listing of all customer communications / inquiries.
*/
public function index(Request $request): View
{
$query = Communication::with(['user', 'order', 'replies'])->latest();
// Status filter
if ($request->filled('status') && $request->input('status') !== 'all') {
$query->where('status', $request->input('status'));
}
// Search query
if ($request->filled('q')) {
$search = trim($request->input('q'));
$query->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%")
->orWhere('subject', 'like', "%{$search}%")
->orWhere('message', 'like', "%{$search}%");
});
}
$communications = $query->paginate(20)->withQueryString();
$counts = [
'all' => Communication::count(),
'new' => Communication::where('status', 'new')->count(),
'in_progress' => Communication::where('status', 'in_progress')->count(),
'resolved' => Communication::where('status', 'resolved')->count(),
'closed' => Communication::where('status', 'closed')->count(),
];
return view('admin.communications.index', [
'communications' => $communications,
'counts' => $counts,
'currentStatus' => $request->input('status', 'all'),
'search' => $request->input('q', ''),
]);
}
/**
* Display the specified communication thread.
*/
public function show(Communication $communication): View
{
$communication->load(['user.orders', 'order.items', 'replies.user']);
// Mark as in_progress if still new when viewed by admin
if ($communication->status === 'new') {
$communication->update(['status' => 'in_progress']);
}
return view('admin.communications.show', [
'communication' => $communication,
]);
}
/**
* Update the status and/or admin notes for this communication.
*/
public function updateStatus(Request $request, Communication $communication): RedirectResponse
{
$validated = $request->validate([
'status' => 'required|string|in:new,in_progress,resolved,closed',
'admin_notes' => 'nullable|string|max:5000',
]);
$communication->update($validated);
return back()->with('success', 'Status van het bericht is bijgewerkt.');
}
/**
* Send a reply to the customer from the admin dashboard.
*/
public function sendReply(Request $request, Communication $communication): RedirectResponse
{
$validated = $request->validate([
'message' => 'required|string|min:5|max:5000',
], [
'message.required' => 'Vul alstublieft een antwoordbericht in.',
'message.min' => 'Het antwoordbericht moet minimaal 5 tekens bevatten.',
]);
$reply = CommunicationReply::create([
'communication_id' => $communication->id,
'user_id' => Auth::id(),
'is_admin_reply' => true,
'message' => trim($validated['message']),
]);
$communication->update([
'status' => 'resolved',
'last_replied_at' => now(),
]);
// Send email to customer from info@jouwdriedee.nl
try {
Mail::to($communication->email)->send(new ContactInquiryReplyMail($communication, $reply));
} catch (\Throwable $e) {
Log::error('Fout bij verzenden van admin reactie naar klant: '.$e->getMessage(), [
'communication_id' => $communication->id,
'email' => $communication->email,
]);
return back()->with('warning', 'Het antwoord is opgeslagen in de database, maar er trad een fout op bij het verzenden van de e-mail: '.$e->getMessage());
}
return back()->with('success', 'Jouw antwoord is verzonden naar '.$communication->email.' en toegevoegd aan het communicatiedossier.');
}
/**
* Remove the specified communication from storage.
*/
public function destroy(Communication $communication): RedirectResponse
{
$communication->delete();
return redirect()->route('admin.communications.index')->with('success', 'Klantbericht is verwijderd.');
}
}
@@ -0,0 +1,176 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Communication;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\View\View;
class CustomerController extends Controller
{
/**
* Display a listing of registered customers and guest buyers.
*/
public function index(Request $request): View
{
$search = trim($request->input('q', ''));
// Query registered non-admin users
$usersQuery = User::where('is_admin', false);
if ($search !== '') {
$usersQuery->where(function ($q) use ($search) {
$q->where('name', 'like', "%{$search}%")
->orWhere('email', 'like', "%{$search}%");
});
}
$registeredUsers = $usersQuery->withCount(['orders', 'communications'])->latest()->get();
// Also discover guest customers who placed orders or sent inquiries without an account
$registeredEmails = User::pluck('email')->map(fn ($e) => strtolower($e))->toArray();
$guestOrderEmails = Order::whereNull('user_id')
->select('customer_email', 'customer_name', 'customer_phone', 'created_at')
->latest()
->get()
->groupBy(fn ($item) => strtolower($item->customer_email));
$guestInquiryEmails = Communication::whereNull('user_id')
->select('email', 'name', 'phone', 'created_at')
->latest()
->get()
->groupBy(fn ($item) => strtolower($item->email));
$guestCustomers = collect();
$allGuestEmails = $guestOrderEmails->keys()->merge($guestInquiryEmails->keys())->unique();
foreach ($allGuestEmails as $email) {
if (in_array(strtolower($email), $registeredEmails)) {
continue;
}
if ($search !== '' && ! str_contains(strtolower($email), strtolower($search))) {
continue;
}
$orderGroup = $guestOrderEmails->get($email, collect());
$inquiryGroup = $guestInquiryEmails->get($email, collect());
$latestOrder = $orderGroup->first();
$latestInquiry = $inquiryGroup->first();
$name = $latestOrder ? $latestOrder->customer_name : ($latestInquiry ? $latestInquiry->name : 'Gast');
$phone = $latestOrder ? $latestOrder->customer_phone : ($latestInquiry ? $latestInquiry->phone : null);
$createdAt = $latestOrder ? $latestOrder->created_at : ($latestInquiry ? $latestInquiry->created_at : now());
$guestCustomers->push((object) [
'id' => null,
'is_registered' => false,
'name' => $name,
'email' => $email,
'phone' => $phone,
'orders_count' => $orderGroup->count(),
'communications_count' => $inquiryGroup->count(),
'created_at' => $createdAt,
]);
}
// Map registered users into unified customer object
$registeredCustomers = $registeredUsers->map(function ($u) {
return (object) [
'id' => $u->id,
'is_registered' => true,
'name' => $u->name,
'email' => $u->email,
'phone' => null,
'orders_count' => $u->orders_count,
'communications_count' => $u->communications_count,
'created_at' => $u->created_at,
];
});
$allCustomers = $registeredCustomers->concat($guestCustomers)->sortByDesc('created_at')->values();
// Manual pagination for the unified list
$perPage = 20;
$page = LengthAwarePaginator::resolveCurrentPage('page');
$paginatedCustomers = new LengthAwarePaginator(
$allCustomers->forPage($page, $perPage),
$allCustomers->count(),
$perPage,
$page,
['path' => route('admin.customers.index'), 'query' => $request->query()]
);
return view('admin.customers.index', [
'customers' => $paginatedCustomers,
'totalRegistered' => $registeredUsers->count(),
'totalGuests' => $guestCustomers->count(),
'search' => $search,
]);
}
/**
* Display a specific customer's profile, including their full communication dossier and orders.
*/
public function show(string $identifier): View
{
$user = null;
$email = null;
if (is_numeric($identifier)) {
$user = User::find($identifier);
if ($user) {
$email = strtolower($user->email);
}
} else {
$email = strtolower(urldecode($identifier));
$user = User::where('email', $email)->first();
}
if (! $user && ! $email) {
abort(404, 'Klant niet gevonden.');
}
// Fetch all communications for this customer (by user_id OR by email)
$communicationsQuery = Communication::with(['replies', 'order'])->latest();
if ($user) {
$communicationsQuery->where(function ($q) use ($user, $email) {
$q->where('user_id', $user->id)
->orWhere('email', $email);
});
} else {
$communicationsQuery->where('email', $email);
}
$communications = $communicationsQuery->get();
// Fetch all orders for this customer (by user_id OR by email)
$ordersQuery = Order::with('items')->latest();
if ($user) {
$ordersQuery->where(function ($q) use ($user, $email) {
$q->where('user_id', $user->id)
->orWhere('customer_email', $email);
});
} else {
$ordersQuery->where('customer_email', $email);
}
$orders = $ordersQuery->get();
$customerName = $user ? $user->name : ($orders->first()?->customer_name ?? $communications->first()?->name ?? 'Klant');
$customerPhone = $orders->first()?->customer_phone ?? $communications->first()?->phone ?? null;
$totalSpent = $orders->sum('total');
return view('admin.customers.show', [
'user' => $user,
'email' => $email,
'customerName' => $customerName,
'customerPhone' => $customerPhone,
'totalSpent' => $totalSpent,
'communications' => $communications,
'orders' => $orders,
]);
}
}