108 lines
3.0 KiB
PHP
108 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Admin;
|
|
|
|
use App\DB\Te\TableEngine;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\AppNotification;
|
|
use App\Models\AppNotificationRead;
|
|
use Illuminate\Http\Request;
|
|
|
|
class AppNotificationController extends Controller
|
|
{
|
|
public function table(Request $request)
|
|
{
|
|
$query = AppNotification::query()->withCount('reads');
|
|
|
|
TableEngine::create($query, $request->all())
|
|
->initSearch(['title', 'body', 'severity'])
|
|
->select(['*'])
|
|
->export($query);
|
|
|
|
return $query;
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$data = $this->validatedPayload($request);
|
|
$user = auth()->user();
|
|
|
|
$row = AppNotification::create([
|
|
...$data,
|
|
'is_active' => $data['is_active'] ?? true,
|
|
'created_by' => $user?->id,
|
|
]);
|
|
|
|
return response()->json($row, 201);
|
|
}
|
|
|
|
public function update(Request $request, int $id)
|
|
{
|
|
$row = AppNotification::findOrFail($id);
|
|
$data = $this->validatedPayload($request, true);
|
|
$row->update($data);
|
|
|
|
return response()->json(true);
|
|
}
|
|
|
|
public function toggleActive(int $id)
|
|
{
|
|
$row = AppNotification::findOrFail($id);
|
|
$row->is_active = ! $row->is_active;
|
|
$row->save();
|
|
|
|
return response()->json([
|
|
'is_active' => (bool) $row->is_active,
|
|
]);
|
|
}
|
|
|
|
public function destroy(int $id)
|
|
{
|
|
AppNotification::findOrFail($id)->delete();
|
|
|
|
return response()->json(true);
|
|
}
|
|
|
|
/** لیست مشتریانی که این اعلان را سین کردهاند */
|
|
public function readers(int $id)
|
|
{
|
|
AppNotification::findOrFail($id);
|
|
|
|
$rows = AppNotificationRead::query()
|
|
->where('notification_id', $id)
|
|
->with(['customer:id,name,fname,lname,mobile'])
|
|
->orderByDesc('read_at')
|
|
->orderByDesc('id')
|
|
->get();
|
|
|
|
$readers = $rows->map(function (AppNotificationRead $read) {
|
|
$customer = $read->customer;
|
|
$name = trim((string) ($customer?->name ?: trim(($customer?->fname ?? '') . ' ' . ($customer?->lname ?? ''))));
|
|
|
|
return [
|
|
'customer_id' => $read->customer_id,
|
|
'name' => $name !== '' ? $name : '—',
|
|
'mobile' => $customer?->mobile,
|
|
'read_at' => $read->read_at,
|
|
];
|
|
})->values();
|
|
|
|
return response()->json([
|
|
'reads_count' => $readers->count(),
|
|
'readers' => $readers,
|
|
]);
|
|
}
|
|
|
|
private function validatedPayload(Request $request, bool $partial = false): array
|
|
{
|
|
$rules = [
|
|
'title' => ($partial ? 'sometimes|' : '') . 'required|string|max:191',
|
|
'body' => ($partial ? 'sometimes|' : '') . 'required|string|max:5000',
|
|
'severity' => ($partial ? 'sometimes|' : '') . 'required|in:info,success,warning,danger',
|
|
'is_active' => 'sometimes|boolean',
|
|
];
|
|
|
|
return $request->validate($rules);
|
|
}
|
|
}
|