Enhance chat functionality: add support for vendor-specific chat channels, implement methods for managing conversations with admin and store owners, and improve conversation payload structure. Update middleware and policies for better access control, and refine chat UI to indicate view-only status for store owner replies.
This commit is contained in:
1 parent
c55694ec8c
commit
5c17c35741
23 files changed
+729
-59
No files matched your search
@@ -3,7 +3,9 @@
|
||||
namespace App\Events\Conversation;
|
||||
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
|
||||
use App\Models\Chat\Conversation;
|
||||
use App\Models\Chat\Message;
|
||||
use App\Models\User;
|
||||
use Illuminate\Broadcasting\Channel;
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Broadcasting\PrivateChannel;
|
||||
@@ -20,7 +22,7 @@ class MessageSent implements ShouldBroadcast
|
||||
*/
|
||||
public function __construct(private Message $message)
|
||||
{
|
||||
$this->message->loadMissing('user');
|
||||
$this->message->loadMissing(['user', 'conversation.channel']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,16 +36,20 @@ public function broadcastOn(): array
|
||||
new PrivateChannel('chat.'.$this->message->conversation_id),
|
||||
];
|
||||
|
||||
$supportId = (int) config('chat.support_user_id');
|
||||
$conversation = $this->message->conversation;
|
||||
|
||||
if ($supportId > 0) {
|
||||
$isSupportConversation = $this->message->conversation()
|
||||
->whereHas('users', fn ($query) => $query->where('users.id', $supportId))
|
||||
->exists();
|
||||
if ($conversation instanceof Conversation && $conversation->isSupportThread()) {
|
||||
$channels[] = new PrivateChannel('chat.support');
|
||||
}
|
||||
|
||||
if ($isSupportConversation) {
|
||||
$channels[] = new PrivateChannel('chat.support');
|
||||
}
|
||||
$channel = $conversation?->channel;
|
||||
|
||||
if (
|
||||
$channel
|
||||
&& $channel->channelables_type === User::class
|
||||
&& $channel->channelables_id
|
||||
) {
|
||||
$channels[] = new PrivateChannel('chat.inbox.'.$channel->channelables_id);
|
||||
}
|
||||
|
||||
return $channels;
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatMessagesRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatSendMessageRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatStartRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatStartTargetRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatTargetsRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatChannelTargetResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatUserResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ConversationResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Chat\Conversation;
|
||||
use App\Models\Chat\Message;
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -30,6 +34,59 @@ public function conversations(): JsonResponse
|
||||
return response()->rest(ConversationResource::collection($conversations));
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Admin + chat-enabled stores for the widget picker
|
||||
*/
|
||||
public function targets(ChatTargetsRequest $request): JsonResponse
|
||||
{
|
||||
$viewer = $request->user();
|
||||
$search = $request->q;
|
||||
|
||||
$paginator = Channel::query()
|
||||
->chatTargets($viewer)
|
||||
->with('media')
|
||||
->when($search, fn ($query) => $query->where('name', 'like', '%'.$search.'%'))
|
||||
->ordered()
|
||||
->simplePaginate($request->perPage);
|
||||
|
||||
$paginator->through(fn (Channel $channel) => (new ChatChannelTargetResource($channel))->resolve());
|
||||
|
||||
return response()->json([
|
||||
'message' => 'success',
|
||||
'data' => [
|
||||
'admin' => ChatSupport::adminTarget($viewer),
|
||||
'channels' => $paginator->items(),
|
||||
],
|
||||
'pagination' => [
|
||||
'page' => $paginator->currentPage(),
|
||||
'perPage' => $paginator->perPage(),
|
||||
'count' => $paginator->count(),
|
||||
'first_page_url' => $paginator->url(1),
|
||||
'next_page_url' => $paginator->nextPageUrl(),
|
||||
'prev_page_url' => $paginator->previousPageUrl(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Find or create a conversation with admin or a store
|
||||
*/
|
||||
public function startTarget(ChatStartTargetRequest $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
if ($request->boolean('admin')) {
|
||||
$conversation = Conversation::findOrCreateSupport($request->user());
|
||||
} else {
|
||||
$channel = Channel::query()->findOrFail($request->integer('channel_id'));
|
||||
$conversation = Conversation::findOrCreateForChannel($request->user(), $channel);
|
||||
}
|
||||
|
||||
$conversation->loadForViewer($request->user());
|
||||
|
||||
return response()->rest(new ConversationResource($conversation));
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Existing support conversation (does not create)
|
||||
*/
|
||||
@@ -37,10 +94,14 @@ public function showSupport(Request $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
$conversation = Conversation::findOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
$conversation = Conversation::findSupportFor($request->user());
|
||||
|
||||
if (! $conversation && ChatSupport::userId()) {
|
||||
$conversation = Conversation::findOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
}
|
||||
|
||||
if (! $conversation) {
|
||||
return response()->rest(null);
|
||||
@@ -58,10 +119,7 @@ public function support(Request $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
$conversation = Conversation::findOrCreateOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
$conversation = Conversation::findOrCreateSupport($request->user());
|
||||
|
||||
$conversation->loadForViewer($request->user());
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class ChatStartTargetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'admin' => ['sometimes', 'boolean'],
|
||||
'channel_id' => ['sometimes', 'integer', 'exists:channels,id'],
|
||||
];
|
||||
}
|
||||
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$admin = $this->boolean('admin');
|
||||
$hasChannel = $this->filled('channel_id');
|
||||
|
||||
if ($admin && $hasChannel) {
|
||||
$validator->errors()->add('channel_id', 'Choose either admin or a channel.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $admin && ! $hasChannel) {
|
||||
$validator->errors()->add('admin', 'Choose either admin or a channel.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ChatTargetsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'perPage' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
];
|
||||
}
|
||||
|
||||
protected function passedValidation(): void
|
||||
{
|
||||
$this->merge([
|
||||
'perPage' => $this->perPage ?: 20,
|
||||
'q' => is_string($this->q) ? trim($this->q) : null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ChatChannelTargetResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'slug' => $this->slug,
|
||||
'image' => $this->thumbnail('200x200'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,18 @@ public function toArray(Request $request): array
|
||||
? $this->users->firstWhere('id', '!=', $request->user()?->id)
|
||||
: null;
|
||||
|
||||
$channel = $this->relationLoaded('channel') ? $this->channel : null;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'thread_key' => $this->thread_key,
|
||||
'user' => $this->when($otherUser, fn () => new ChatUserResource($otherUser)),
|
||||
'channel' => $channel ? [
|
||||
'id' => $channel->id,
|
||||
'name' => $channel->name,
|
||||
'slug' => $channel->slug,
|
||||
'image' => $channel->thumbnail('200x200'),
|
||||
] : null,
|
||||
'last_message' => $this->when(
|
||||
$this->relationLoaded('latestMessage') && $this->latestMessage,
|
||||
fn () => new MessageResource($this->latestMessage)
|
||||
|
||||
@@ -12,17 +12,19 @@
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class SupportChatController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
public function index(Request $request): View
|
||||
{
|
||||
if (app()->bound('debugbar')) {
|
||||
app('debugbar')->disable();
|
||||
}
|
||||
|
||||
$key = config('broadcasting.connections.reverb.key');
|
||||
$actor = $request->user();
|
||||
|
||||
return view('nova.chat', [
|
||||
'chatCss' => $this->panelAsset('css/chat.css'),
|
||||
@@ -32,23 +34,30 @@ public function index(): View
|
||||
$this->panelAsset('js/chat.js'),
|
||||
])),
|
||||
'pusher' => $this->chatPusherConfig($key),
|
||||
'inboxChannel' => ChatSupport::isOperator($actor)
|
||||
? 'chat.support'
|
||||
: 'chat.inbox.'.$actor->id,
|
||||
]);
|
||||
}
|
||||
|
||||
public function conversations(): JsonResponse
|
||||
public function conversations(Request $request): JsonResponse
|
||||
{
|
||||
$support = ChatSupport::user();
|
||||
$actor = $request->user();
|
||||
|
||||
$conversations = Conversation::inboxFor($support)
|
||||
->map(fn (Conversation $conversation) => ChatSupport::conversationPayload($conversation, $support, true))
|
||||
$conversations = ChatSupport::isOperator($actor)
|
||||
? Conversation::inboxForStaff()
|
||||
: Conversation::inboxForVendor($actor);
|
||||
|
||||
$payload = $conversations
|
||||
->map(fn (Conversation $conversation) => ChatSupport::conversationPayload($conversation, $actor, true))
|
||||
->values();
|
||||
|
||||
return response()->rest($conversations);
|
||||
return response()->rest($payload);
|
||||
}
|
||||
|
||||
public function messages(ChatMessagesRequest $request, Conversation $conversation): JsonResponse
|
||||
{
|
||||
$this->assertSupportConversation($conversation);
|
||||
$this->assertCanView($request->user(), $conversation);
|
||||
|
||||
$paginator = $conversation->messages()
|
||||
->with('user')
|
||||
@@ -62,10 +71,10 @@ public function messages(ChatMessagesRequest $request, Conversation $conversatio
|
||||
|
||||
public function send(ChatSendMessageRequest $request, Conversation $conversation): JsonResponse
|
||||
{
|
||||
$support = $this->assertSupportConversation($conversation);
|
||||
$sender = $this->assertCanReply($request->user(), $conversation);
|
||||
|
||||
$message = $conversation->messages()->create([
|
||||
'user_id' => $support->id,
|
||||
'user_id' => $sender->id,
|
||||
'body' => $request->validated('body'),
|
||||
]);
|
||||
|
||||
@@ -78,23 +87,39 @@ public function send(ChatSendMessageRequest $request, Conversation $conversation
|
||||
|
||||
public function read(Conversation $conversation): JsonResponse
|
||||
{
|
||||
$support = $this->assertSupportConversation($conversation);
|
||||
$sender = $this->assertCanReply(request()->user(), $conversation);
|
||||
|
||||
$conversation->messages()
|
||||
->where('user_id', '!=', $support->id)
|
||||
->where('user_id', '!=', $sender->id)
|
||||
->whereNull('seen_at')
|
||||
->update(['seen_at' => now()]);
|
||||
|
||||
return response()->rest();
|
||||
}
|
||||
|
||||
private function assertSupportConversation(Conversation $conversation): User
|
||||
private function assertCanView(User $actor, Conversation $conversation): void
|
||||
{
|
||||
$support = ChatSupport::user();
|
||||
if (ChatSupport::isOperator($actor)) {
|
||||
return;
|
||||
}
|
||||
|
||||
abort_unless($conversation->hasParticipant($support), 403);
|
||||
abort_unless($conversation->hasParticipant($actor), 403);
|
||||
$conversation->loadMissing('channel');
|
||||
abort_unless(ChatSupport::ownsChannel($actor, $conversation->channel), 403);
|
||||
}
|
||||
|
||||
return $support;
|
||||
private function assertCanReply(User $actor, Conversation $conversation): User
|
||||
{
|
||||
abort_unless(ChatSupport::canReply($actor, $conversation), 403);
|
||||
|
||||
if (ChatSupport::isOperator($actor)) {
|
||||
$support = ChatSupport::user();
|
||||
abort_unless($conversation->hasParticipant($support), 403);
|
||||
|
||||
return $support;
|
||||
}
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
private function panelAsset(string $relative): string
|
||||
|
||||
@@ -11,7 +11,7 @@ class EnsureChatOperator
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
abort_unless(ChatSupport::isOperator($request->user()), 403);
|
||||
abort_unless(ChatSupport::canAccessPanelChat($request->user()), 403);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
@@ -2,18 +2,39 @@
|
||||
|
||||
namespace App\Models\Chat;
|
||||
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class Conversation extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const THREAD_ADMIN = 'admin';
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'customer_id',
|
||||
'channel_id',
|
||||
'thread_key',
|
||||
];
|
||||
|
||||
public static function threadKeyForChannel(int $channelId): string
|
||||
{
|
||||
return 'channel:'.$channelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a 1:1 conversation between two users.
|
||||
*/
|
||||
@@ -43,13 +64,65 @@ public static function findOrCreateOneToOne(int $userId, int $otherUserId): self
|
||||
return $conversation;
|
||||
}
|
||||
|
||||
public static function findSupportFor(User $customer): ?self
|
||||
{
|
||||
return static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', self::THREAD_ADMIN)
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function findOrCreateSupport(User $customer): self
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($customer), 403);
|
||||
|
||||
$support = ChatSupport::user();
|
||||
|
||||
return static::locateOrCreate($customer, $support, self::THREAD_ADMIN, null);
|
||||
}
|
||||
|
||||
public static function findOrCreateForChannel(User $customer, Channel $channel): self
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($customer), 403);
|
||||
|
||||
$existing = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', static::threadKeyForChannel($channel->id))
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$channel->loadMissing('user');
|
||||
$owner = $channel->user;
|
||||
|
||||
abort_unless(
|
||||
$channel->is_visible
|
||||
&& $channel->chatting
|
||||
&& $channel->channelables_type === User::class
|
||||
&& $owner,
|
||||
422,
|
||||
'This store is not available for chat.'
|
||||
);
|
||||
abort_if((int) $owner->id === (int) $customer->id, 403, 'You cannot chat with your own store.');
|
||||
abort_if(ChatSupport::isSupportUser($owner), 422, 'This store is not available for chat.');
|
||||
|
||||
return static::locateOrCreate(
|
||||
$customer,
|
||||
$owner,
|
||||
static::threadKeyForChannel($channel->id),
|
||||
$channel
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inbox for a participant, newest activity first.
|
||||
*/
|
||||
public static function inboxFor(User $viewer): Collection
|
||||
{
|
||||
return $viewer->conversations()
|
||||
->with(['users', 'latestMessage.user'])
|
||||
->with(['users', 'latestMessage.user', 'channel'])
|
||||
->withCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->where('user_id', '!=', $viewer->id)
|
||||
@@ -60,9 +133,28 @@ public static function inboxFor(User $viewer): Collection
|
||||
->get();
|
||||
}
|
||||
|
||||
public static function inboxForStaff(): Collection
|
||||
{
|
||||
return static::panelInboxQuery()->get();
|
||||
}
|
||||
|
||||
public static function inboxForVendor(User $vendor): Collection
|
||||
{
|
||||
$channelIds = $vendor->channels()->pluck('id');
|
||||
|
||||
if ($channelIds->isEmpty()) {
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
return static::panelInboxQuery()
|
||||
->whereIn('channel_id', $channelIds)
|
||||
->whereHas('users', fn ($query) => $query->where('users.id', $vendor->id))
|
||||
->get();
|
||||
}
|
||||
|
||||
public function loadForViewer(User $viewer): self
|
||||
{
|
||||
return $this->load(['users', 'latestMessage.user'])
|
||||
return $this->load(['users', 'latestMessage.user', 'channel'])
|
||||
->loadCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->where('user_id', '!=', $viewer->id)
|
||||
@@ -70,6 +162,21 @@ public function loadForViewer(User $viewer): self
|
||||
]);
|
||||
}
|
||||
|
||||
public function isSupportThread(): bool
|
||||
{
|
||||
return $this->thread_key === self::THREAD_ADMIN;
|
||||
}
|
||||
|
||||
public function customer(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'customer_id');
|
||||
}
|
||||
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class);
|
||||
@@ -89,4 +196,69 @@ public function hasParticipant(User $user): bool
|
||||
{
|
||||
return $this->users()->where('users.id', $user->id)->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Illuminate\Database\Eloquent\Builder<static>
|
||||
*/
|
||||
private static function panelInboxQuery()
|
||||
{
|
||||
return static::query()
|
||||
->with(['customer', 'channel', 'users', 'latestMessage.user'])
|
||||
->withCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->whereColumn('messages.user_id', 'conversations.customer_id')
|
||||
->whereNull('seen_at'),
|
||||
])
|
||||
->withMax('messages', 'created_at')
|
||||
->orderByDesc('messages_max_created_at');
|
||||
}
|
||||
|
||||
private static function locateOrCreate(User $customer, User $counterpart, string $threadKey, ?Channel $channel): self
|
||||
{
|
||||
$existing = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', $threadKey)
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use ($customer, $counterpart, $threadKey, $channel) {
|
||||
$conversation = static::query()->create([
|
||||
'customer_id' => $customer->id,
|
||||
'channel_id' => $channel?->id,
|
||||
'thread_key' => $threadKey,
|
||||
]);
|
||||
|
||||
$conversation->users()->attach([$customer->id, $counterpart->id]);
|
||||
|
||||
return $conversation;
|
||||
});
|
||||
} catch (QueryException $exception) {
|
||||
if (! static::isUniqueViolation($exception)) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$conversation = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', $threadKey)
|
||||
->first();
|
||||
|
||||
if ($conversation) {
|
||||
return $conversation;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isUniqueViolation(QueryException $exception): bool
|
||||
{
|
||||
$sqlState = (string) $exception->errorInfo[0];
|
||||
|
||||
return in_array($sqlState, ['23000', '23505'], true)
|
||||
|| str_contains(strtolower($exception->getMessage()), 'unique');
|
||||
}
|
||||
}
|
||||
@@ -46,10 +46,22 @@ class Channel extends Model implements HasMedia, Sortable
|
||||
'sort_order',
|
||||
'is_default',
|
||||
'is_visible',
|
||||
'chatting',
|
||||
'channelables_type',
|
||||
'channelables_id',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $casts = [
|
||||
'is_default' => 'boolean',
|
||||
'is_visible' => 'boolean',
|
||||
'chatting' => 'boolean',
|
||||
];
|
||||
|
||||
/**
|
||||
* Sortable attributes
|
||||
*
|
||||
@@ -158,6 +170,26 @@ public function user(): BelongsTo
|
||||
return $this->belongsTo(User::class, 'channelables_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores that visitors may start a chat with.
|
||||
*
|
||||
* @param \Illuminate\Database\Eloquent\Builder<static> $query
|
||||
* @return \Illuminate\Database\Eloquent\Builder<static>
|
||||
*/
|
||||
public function scopeChatTargets($query, ?User $viewer = null)
|
||||
{
|
||||
$supportId = (int) config('chat.support_user_id');
|
||||
|
||||
return $query
|
||||
->where('is_visible', true)
|
||||
->where('chatting', true)
|
||||
->where('channelables_type', User::class)
|
||||
->whereNotNull('channelables_id')
|
||||
->whereHas('user')
|
||||
->when($viewer, fn ($query) => $query->where('channelables_id', '!=', $viewer->id))
|
||||
->when($supportId > 0, fn ($query) => $query->where('channelables_id', '!=', $supportId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Default tmpost inventory
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
use App\Nova\Resources\Ecommerce\Channel\Fields\ChannelFieldsForIndex;
|
||||
use App\Nova\Resources\Ecommerce\Product\Product\Product;
|
||||
use App\Nova\Resources\User\UserSearchResource;
|
||||
use App\Support\ChatSupport;
|
||||
use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Laravel\Nova\Fields\BelongsTo;
|
||||
use Laravel\Nova\Fields\DateTime;
|
||||
use Laravel\Nova\Fields\Hidden;
|
||||
@@ -81,6 +83,49 @@ public function fieldsForIndex(): array
|
||||
return ChannelFieldsForIndex::make();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an "index" query for the given resource.
|
||||
*
|
||||
* @param Builder $query
|
||||
*/
|
||||
public static function indexQuery(NovaRequest $request, $query): Builder
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user && $user->isVendor() && ! ChatSupport::isOperator($user)) {
|
||||
$query->where('channelables_type', User::class)
|
||||
->where('channelables_id', $user->id);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a "detail" query for the given resource.
|
||||
*
|
||||
* @param Builder $query
|
||||
*/
|
||||
public static function detailQuery(NovaRequest $request, $query): Builder
|
||||
{
|
||||
return static::indexQuery($request, parent::detailQuery($request, $query));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fields vendors may change (chatting only).
|
||||
*/
|
||||
public function fieldsForUpdate(NovaRequest $request): array
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user && $user->isVendor() && ! ChatSupport::isOperator($user)) {
|
||||
return [
|
||||
NovaSwitcher::make(__('Chatting'), 'chatting'),
|
||||
];
|
||||
}
|
||||
|
||||
return $this->fields($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the fields displayed by the resource.
|
||||
*/
|
||||
@@ -125,6 +170,9 @@ public function fields(NovaRequest $request): array
|
||||
NovaSwitcher::make(__('Active'), 'is_visible')
|
||||
->default(true),
|
||||
|
||||
NovaSwitcher::make(__('Chatting'), 'chatting')
|
||||
->default(false),
|
||||
|
||||
MorphMany::make(__('Products'), 'products', Product::class),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use Laravel\Nova\Fields\DateTime;
|
||||
use Laravel\Nova\Fields\ID;
|
||||
use Laravel\Nova\Fields\Text;
|
||||
use Trin4ik\NovaSwitcher\NovaSwitcher;
|
||||
|
||||
class ChannelFieldsForIndex
|
||||
{
|
||||
@@ -25,6 +26,8 @@ public static function make(): array
|
||||
|
||||
Text::make(__('User'), fn ($model) => $model->user?->fullname ?? '-'),
|
||||
|
||||
NovaSwitcher::make(__('Chatting'), 'chatting'),
|
||||
|
||||
DateTime::make(__('Created at'), 'created_at')
|
||||
->turkmenDate()
|
||||
->sortable(),
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
|
||||
@@ -28,7 +29,7 @@ public function before(User $user, string $ability): ?Response
|
||||
*/
|
||||
public function viewAny(User $user): Response
|
||||
{
|
||||
if ($user->hasRole(['admin', 'direktor'])) {
|
||||
if ($user->hasRole(['admin', 'direktor']) || $user->isVendor()) {
|
||||
return $this->allow();
|
||||
}
|
||||
|
||||
@@ -40,7 +41,7 @@ public function viewAny(User $user): Response
|
||||
*/
|
||||
public function view(User $user, Channel $channel): Response
|
||||
{
|
||||
if ($user->hasRole(['admin', 'direktor'])) {
|
||||
if ($user->hasRole(['admin', 'direktor']) || ChatSupport::ownsChannel($user, $channel)) {
|
||||
return $this->allow();
|
||||
}
|
||||
|
||||
@@ -64,7 +65,7 @@ public function create(User $user): Response
|
||||
*/
|
||||
public function update(User $user, Channel $channel): Response
|
||||
{
|
||||
if ($user->hasRole(['admin', 'direktor'])) {
|
||||
if ($user->hasRole(['admin', 'direktor']) || ChatSupport::ownsChannel($user, $channel)) {
|
||||
return $this->allow();
|
||||
}
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ public function setupNavigation(): void
|
||||
MenuSection::make(__('Chat'), [
|
||||
MenuItem::externalLink(__('Inbox'), url('/panel/chat')),
|
||||
])->icon('chat-alt-2')
|
||||
->canSee(fn (Request $request) => ChatSupport::isOperator($request->user())),
|
||||
->canSee(fn (Request $request) => ChatSupport::canAccessPanelChat($request->user())),
|
||||
|
||||
MenuSection::make('Hatlar', [
|
||||
MenuItem::resource(ContactUS::class),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatUserResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
|
||||
use App\Models\Chat\Conversation;
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
@@ -46,11 +47,81 @@ public static function isOperator(?User $user): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
return true; // TODO: Remove this
|
||||
|
||||
return $user->isMe() || $user->isAdmin() || $user->isDirektor() || $user->isManager();
|
||||
}
|
||||
|
||||
public static function canAccessPanelChat(?User $user): bool
|
||||
{
|
||||
if ($user === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (static::isOperator($user)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $user->isVendor() && $user->channels()->exists();
|
||||
}
|
||||
|
||||
public static function ownsChannel(?User $user, ?Channel $channel): bool
|
||||
{
|
||||
if ($user === null || $channel === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $channel->channelables_type === User::class
|
||||
&& (int) $channel->channelables_id === (int) $user->id;
|
||||
}
|
||||
|
||||
public static function canReply(?User $user, Conversation $conversation): bool
|
||||
{
|
||||
if ($user === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (static::isOperator($user)) {
|
||||
return $conversation->isSupportThread();
|
||||
}
|
||||
|
||||
if (! $user->isVendor() || ! $conversation->channel_id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$conversation->loadMissing('channel');
|
||||
|
||||
return static::ownsChannel($user, $conversation->channel)
|
||||
&& $conversation->hasParticipant($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{available: bool, name: string|null}
|
||||
*/
|
||||
public static function adminTarget(?User $viewer): array
|
||||
{
|
||||
$id = static::userId();
|
||||
|
||||
if ($id === null || ($viewer && (int) $viewer->id === $id)) {
|
||||
return [
|
||||
'available' => false,
|
||||
'name' => null,
|
||||
];
|
||||
}
|
||||
|
||||
$user = User::query()->find($id);
|
||||
|
||||
if (! $user) {
|
||||
return [
|
||||
'available' => false,
|
||||
'name' => null,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'available' => true,
|
||||
'name' => $user->fullname ?: 'Admin',
|
||||
];
|
||||
}
|
||||
|
||||
public static function conversationIncludesSupport(int $conversationId): bool
|
||||
{
|
||||
$id = static::userId();
|
||||
@@ -68,11 +139,12 @@ public static function conversationIncludesSupport(int $conversationId): bool
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function conversationPayload(Conversation $conversation, User $viewer, bool $includePhone = false): array
|
||||
public static function conversationPayload(Conversation $conversation, User $actor, bool $includePhone = false): array
|
||||
{
|
||||
$conversation->loadMissing(['users', 'latestMessage.user']);
|
||||
$conversation->loadMissing(['users', 'latestMessage.user', 'channel', 'customer']);
|
||||
|
||||
$otherUser = $conversation->users->firstWhere('id', '!=', $viewer->id);
|
||||
$otherUser = $conversation->customer
|
||||
?? $conversation->users->firstWhere('id', '!=', $actor->id);
|
||||
|
||||
$user = $otherUser ? (new ChatUserResource($otherUser))->resolve() : null;
|
||||
|
||||
@@ -80,9 +152,18 @@ public static function conversationPayload(Conversation $conversation, User $vie
|
||||
$user['phone_number'] = $otherUser->phone_number;
|
||||
}
|
||||
|
||||
$channel = $conversation->channel;
|
||||
|
||||
return [
|
||||
'id' => $conversation->id,
|
||||
'thread_key' => $conversation->thread_key,
|
||||
'user' => $user,
|
||||
'channel' => $channel ? [
|
||||
'id' => $channel->id,
|
||||
'name' => $channel->name,
|
||||
'slug' => $channel->slug,
|
||||
] : null,
|
||||
'can_reply' => static::canReply($actor, $conversation),
|
||||
'last_message' => $conversation->latestMessage
|
||||
? (new MessageResource($conversation->latestMessage))->resolve()
|
||||
: null,
|
||||
|
||||
Reference in new issue
Block a user