fix notif 3
This commit is contained in:
@@ -6,7 +6,12 @@ use App\DB\Te\TableEngine;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AppNotification;
|
||||
use App\Models\AppNotificationRead;
|
||||
use App\Models\AppNotificationRecipient;
|
||||
use App\Models\Customer;
|
||||
use App\Services\AppNotificationAudienceService;
|
||||
use App\Services\PriceStreamService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AppNotificationController extends Controller
|
||||
{
|
||||
@@ -15,31 +20,134 @@ class AppNotificationController extends Controller
|
||||
$query = AppNotification::query()->withCount('reads');
|
||||
|
||||
TableEngine::create($query, $request->all())
|
||||
->initSearch(['title', 'body', 'severity'])
|
||||
->initSearch(['title', 'body', 'severity', 'audience_label', 'audience_type'])
|
||||
->select(['*'])
|
||||
->export($query);
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public function audienceOptions()
|
||||
{
|
||||
return response()->json([
|
||||
'segments' => app(AppNotificationAudienceService::class)->segmentOptions(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function searchCustomers(Request $request)
|
||||
{
|
||||
$q = trim((string) $request->get('q', ''));
|
||||
|
||||
$rows = Customer::query()
|
||||
->where('type', 2)
|
||||
->where('is_archive', false)
|
||||
->when($q !== '', function ($query) use ($q) {
|
||||
$query->where(function ($inner) use ($q) {
|
||||
$inner->where('name', 'like', '%' . $q . '%')
|
||||
->orWhere('mobile', 'like', '%' . $q . '%')
|
||||
->orWhere('id', $q);
|
||||
});
|
||||
})
|
||||
->orderByDesc('id')
|
||||
->limit(30)
|
||||
->get(['id', 'name', 'mobile']);
|
||||
|
||||
return response()->json(['customers' => $rows]);
|
||||
}
|
||||
|
||||
public function previewAudience(Request $request)
|
||||
{
|
||||
$audience = app(AppNotificationAudienceService::class);
|
||||
$type = (string) $request->input('audience_type', AppNotificationAudienceService::TYPE_ALL);
|
||||
$segmentKeys = array_values(array_filter((array) $request->input('segment_keys', [])));
|
||||
$customerIds = array_values(array_filter(array_map('intval', (array) $request->input('customer_ids', []))));
|
||||
|
||||
$customers = match ($type) {
|
||||
AppNotificationAudienceService::TYPE_SEGMENT => $audience->resolveSegmentCustomers($segmentKeys),
|
||||
AppNotificationAudienceService::TYPE_CUSTOMERS => $audience->resolveCustomersByIds($customerIds),
|
||||
default => collect(),
|
||||
};
|
||||
|
||||
return response()->json([
|
||||
'count' => $type === AppNotificationAudienceService::TYPE_ALL ? null : $customers->count(),
|
||||
'sample' => $customers->take(20)->values(),
|
||||
'label' => $audience->buildAudienceLabel($type, $segmentKeys, $customers->count()),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$data = $this->validatedPayload($request);
|
||||
$user = auth()->user();
|
||||
$audience = app(AppNotificationAudienceService::class);
|
||||
|
||||
$row = AppNotification::create([
|
||||
...$data,
|
||||
'is_active' => $data['is_active'] ?? true,
|
||||
'created_by' => $user?->id,
|
||||
]);
|
||||
$audienceType = (string) ($data['audience_type'] ?? AppNotificationAudienceService::TYPE_ALL);
|
||||
$segmentKeys = array_values(array_filter((array) ($data['segment_keys'] ?? [])));
|
||||
$customerIds = array_values(array_filter(array_map('intval', (array) ($data['customer_ids'] ?? []))));
|
||||
|
||||
return response()->json($row, 201);
|
||||
$recipients = match ($audienceType) {
|
||||
AppNotificationAudienceService::TYPE_SEGMENT => $audience->resolveSegmentCustomers($segmentKeys),
|
||||
AppNotificationAudienceService::TYPE_CUSTOMERS => $audience->resolveCustomersByIds($customerIds),
|
||||
default => collect(),
|
||||
};
|
||||
|
||||
if ($audienceType === AppNotificationAudienceService::TYPE_SEGMENT && $recipients->isEmpty()) {
|
||||
return response()->json(['message' => 'برای گروه انتخابشده مشتریای یافت نشد.'], 422);
|
||||
}
|
||||
if ($audienceType === AppNotificationAudienceService::TYPE_CUSTOMERS && $recipients->isEmpty()) {
|
||||
return response()->json(['message' => 'حداقل یک مشتری انتخاب کنید.'], 422);
|
||||
}
|
||||
|
||||
$recipientsCount = $audienceType === AppNotificationAudienceService::TYPE_ALL
|
||||
? 0
|
||||
: $recipients->count();
|
||||
|
||||
$row = DB::transaction(function () use ($data, $audience, $audienceType, $segmentKeys, $recipients, $recipientsCount) {
|
||||
$user = auth()->user();
|
||||
|
||||
$row = AppNotification::create([
|
||||
'title' => $data['title'],
|
||||
'body' => $data['body'],
|
||||
'severity' => $data['severity'],
|
||||
'is_active' => $data['is_active'] ?? true,
|
||||
'created_by' => $user?->id,
|
||||
'audience_type' => $audienceType,
|
||||
'segment_keys' => $audienceType === AppNotificationAudienceService::TYPE_SEGMENT ? $segmentKeys : null,
|
||||
'audience_label' => $audience->buildAudienceLabel($audienceType, $segmentKeys, $recipientsCount),
|
||||
'recipients_count' => $recipientsCount,
|
||||
]);
|
||||
|
||||
if ($audienceType !== AppNotificationAudienceService::TYPE_ALL) {
|
||||
$now = now();
|
||||
$chunks = $recipients->pluck('id')->map(fn ($id) => [
|
||||
'notification_id' => $row->id,
|
||||
'customer_id' => (int) $id,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
])->chunk(500);
|
||||
|
||||
foreach ($chunks as $chunk) {
|
||||
AppNotificationRecipient::query()->insert($chunk->values()->all());
|
||||
}
|
||||
}
|
||||
|
||||
return $row;
|
||||
});
|
||||
|
||||
$this->broadcastNotification($row);
|
||||
|
||||
return response()->json($row->fresh(), 201);
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id)
|
||||
{
|
||||
$row = AppNotification::findOrFail($id);
|
||||
$data = $this->validatedPayload($request, true);
|
||||
// مخاطب بعد از ارسال ثابت میماند — فقط محتوا/وضعیت
|
||||
$data = $request->validate([
|
||||
'title' => 'sometimes|required|string|max:191',
|
||||
'body' => 'sometimes|required|string|max:5000',
|
||||
'severity' => 'sometimes|required|in:info,success,warning,danger',
|
||||
'is_active' => 'sometimes|boolean',
|
||||
]);
|
||||
$row->update($data);
|
||||
|
||||
return response()->json(true);
|
||||
@@ -58,12 +166,14 @@ class AppNotificationController extends Controller
|
||||
|
||||
public function destroy(int $id)
|
||||
{
|
||||
AppNotification::findOrFail($id)->delete();
|
||||
$row = AppNotification::findOrFail($id);
|
||||
AppNotificationRecipient::query()->where('notification_id', $id)->delete();
|
||||
$row->delete();
|
||||
|
||||
return response()->json(true);
|
||||
}
|
||||
|
||||
/** لیست مشتریانی که این اعلان را سین کردهاند */
|
||||
/** بازدیدکنندگان (خواندهاند) */
|
||||
public function readers(int $id)
|
||||
{
|
||||
AppNotification::findOrFail($id);
|
||||
@@ -93,15 +203,90 @@ class AppNotificationController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
private function validatedPayload(Request $request, bool $partial = false): array
|
||||
/** گیرندگان هدف (اسنپشات ارسال) */
|
||||
public function recipients(int $id)
|
||||
{
|
||||
$rules = [
|
||||
'title' => ($partial ? 'sometimes|' : '') . 'required|string|max:191',
|
||||
'body' => ($partial ? 'sometimes|' : '') . 'required|string|max:5000',
|
||||
'severity' => ($partial ? 'sometimes|' : '') . 'required|in:info,success,warning,danger',
|
||||
$row = AppNotification::findOrFail($id);
|
||||
|
||||
if ($row->audience_type === AppNotificationAudienceService::TYPE_ALL) {
|
||||
return response()->json([
|
||||
'audience_type' => $row->audience_type,
|
||||
'audience_label' => $row->audience_label ?: 'همه کاربران',
|
||||
'recipients_count' => null,
|
||||
'recipients' => [],
|
||||
'note' => 'این اعلان برای همه کاربران فعال ارسال شده است.',
|
||||
]);
|
||||
}
|
||||
|
||||
$rows = AppNotificationRecipient::query()
|
||||
->where('notification_id', $id)
|
||||
->with(['customer:id,name,fname,lname,mobile'])
|
||||
->orderByDesc('id')
|
||||
->limit(500)
|
||||
->get();
|
||||
|
||||
$recipients = $rows->map(function (AppNotificationRecipient $item) {
|
||||
$customer = $item->customer;
|
||||
$name = trim((string) ($customer?->name ?: trim(($customer?->fname ?? '') . ' ' . ($customer?->lname ?? ''))));
|
||||
|
||||
return [
|
||||
'customer_id' => $item->customer_id,
|
||||
'name' => $name !== '' ? $name : '—',
|
||||
'mobile' => $customer?->mobile,
|
||||
];
|
||||
})->values();
|
||||
|
||||
return response()->json([
|
||||
'audience_type' => $row->audience_type,
|
||||
'audience_label' => $row->audience_label,
|
||||
'recipients_count' => (int) $row->recipients_count,
|
||||
'recipients' => $recipients,
|
||||
]);
|
||||
}
|
||||
|
||||
private function validatedPayload(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'title' => 'required|string|max:191',
|
||||
'body' => 'required|string|max:5000',
|
||||
'severity' => 'required|in:info,success,warning,danger',
|
||||
'is_active' => 'sometimes|boolean',
|
||||
'audience_type' => 'required|in:all,segment,customers',
|
||||
'segment_keys' => 'nullable|array',
|
||||
'segment_keys.*' => 'string',
|
||||
'customer_ids' => 'nullable|array',
|
||||
'customer_ids.*' => 'integer',
|
||||
]);
|
||||
}
|
||||
|
||||
private function broadcastNotification(AppNotification $row): void
|
||||
{
|
||||
if (! $row->is_active) {
|
||||
return;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'id' => $row->id,
|
||||
'title' => $row->title,
|
||||
'body' => $row->body,
|
||||
'severity' => $row->severity,
|
||||
'created_at' => optional($row->created_at)?->toIso8601String(),
|
||||
];
|
||||
|
||||
return $request->validate($rules);
|
||||
$stream = app(PriceStreamService::class);
|
||||
|
||||
if ($row->audience_type === AppNotificationAudienceService::TYPE_ALL) {
|
||||
$stream->publish('app_notification', $payload);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$ids = AppNotificationRecipient::query()
|
||||
->where('notification_id', $row->id)
|
||||
->pluck('customer_id');
|
||||
|
||||
foreach ($ids as $customerId) {
|
||||
$stream->publishForCustomer((int) $customerId, 'app_notification', $payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace App\Http\Controllers\Customer;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AppNotification;
|
||||
use App\Models\AppNotificationRead;
|
||||
use App\Services\AppNotificationAudienceService;
|
||||
use App\Services\ConfigService;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
@@ -18,13 +20,29 @@ class AppNotificationController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
private function visibleQuery(int $customerId): Builder
|
||||
{
|
||||
return AppNotification::query()
|
||||
->where('is_active', true)
|
||||
->where(function (Builder $q) use ($customerId) {
|
||||
$q->where('audience_type', AppNotificationAudienceService::TYPE_ALL)
|
||||
->orWhere(function (Builder $inner) use ($customerId) {
|
||||
$inner->whereIn('audience_type', [
|
||||
AppNotificationAudienceService::TYPE_SEGMENT,
|
||||
AppNotificationAudienceService::TYPE_CUSTOMERS,
|
||||
])->whereHas('recipients', function (Builder $r) use ($customerId) {
|
||||
$r->where('customer_id', $customerId);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$this->assertFeatureEnabled();
|
||||
$customerId = (int) auth()->id();
|
||||
|
||||
$rows = AppNotification::query()
|
||||
->where('is_active', true)
|
||||
$rows = $this->visibleQuery($customerId)
|
||||
->orderByDesc('id')
|
||||
->limit(100)
|
||||
->get(['id', 'title', 'body', 'severity', 'created_at']);
|
||||
@@ -55,13 +73,11 @@ class AppNotificationController extends Controller
|
||||
$this->assertFeatureEnabled();
|
||||
$customerId = (int) auth()->id();
|
||||
|
||||
$total = AppNotification::query()->where('is_active', true)->count();
|
||||
$visibleIds = $this->visibleQuery($customerId)->select('id');
|
||||
$total = (clone $visibleIds)->count();
|
||||
$read = AppNotificationRead::query()
|
||||
->where('customer_id', $customerId)
|
||||
->whereIn(
|
||||
'notification_id',
|
||||
AppNotification::query()->where('is_active', true)->select('id')
|
||||
)
|
||||
->whereIn('notification_id', $visibleIds)
|
||||
->count();
|
||||
|
||||
return response()->json([
|
||||
@@ -74,10 +90,7 @@ class AppNotificationController extends Controller
|
||||
$this->assertFeatureEnabled();
|
||||
$customerId = (int) auth()->id();
|
||||
|
||||
$exists = AppNotification::query()
|
||||
->where('id', $id)
|
||||
->where('is_active', true)
|
||||
->exists();
|
||||
$exists = $this->visibleQuery($customerId)->where('id', $id)->exists();
|
||||
if (! $exists) {
|
||||
throw new NotFoundHttpException('اعلان یافت نشد.');
|
||||
}
|
||||
@@ -100,10 +113,7 @@ class AppNotificationController extends Controller
|
||||
$this->assertFeatureEnabled();
|
||||
$customerId = (int) auth()->id();
|
||||
|
||||
$ids = AppNotification::query()
|
||||
->where('is_active', true)
|
||||
->pluck('id');
|
||||
|
||||
$ids = $this->visibleQuery($customerId)->pluck('id');
|
||||
$now = now();
|
||||
foreach ($ids as $notificationId) {
|
||||
AppNotificationRead::query()->updateOrCreate(
|
||||
|
||||
Reference in New Issue
Block a user