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:
Mekan1206
2026-08-15 21:17:31 +05:00
parent c55694ec8c
commit 5c17c35741
23 changed files with 729 additions and 59 deletions

View File

@@ -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 @@ class MessageSent implements ShouldBroadcast
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;

View File

@@ -7,12 +7,16 @@ use App\Http\Controllers\Api\V1\Chat\Requests\ChatContactsRequest;
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 @@ class ChatController extends Controller
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 @@ class ChatController extends Controller
{
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 @@ class ChatController extends Controller
{
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());

View File

@@ -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.');
}
});
}
}

View File

@@ -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,
]);
}
}

View File

@@ -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'),
];
}
}

View File

@@ -16,9 +16,18 @@ class ConversationResource extends JsonResource
? $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)

View File

@@ -12,17 +12,19 @@ use App\Models\Chat\Message;
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 @@ class SupportChatController extends Controller
$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 @@ class SupportChatController extends Controller
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 @@ class SupportChatController extends Controller
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

View File

@@ -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);
}

View File

@@ -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 @@ class Conversation extends Model
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 @@ class Conversation extends Model
->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 @@ class Conversation extends Model
]);
}
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 @@ class Conversation extends Model
{
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');
}
}

View File

@@ -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 @@ class Channel extends Model implements HasMedia, Sortable
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
*/

View File

@@ -8,7 +8,9 @@ use App\Nova\Resource;
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 @@ class Channel extends Resource
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 @@ class Channel extends Resource
NovaSwitcher::make(__('Active'), 'is_visible')
->default(true),
NovaSwitcher::make(__('Chatting'), 'chatting')
->default(false),
MorphMany::make(__('Products'), 'products', Product::class),
];
}

View File

@@ -6,6 +6,7 @@ use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
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 @@ class ChannelFieldsForIndex
Text::make(__('User'), fn ($model) => $model->user?->fullname ?? '-'),
NovaSwitcher::make(__('Chatting'), 'chatting'),
DateTime::make(__('Created at'), 'created_at')
->turkmenDate()
->sortable(),

View File

@@ -4,6 +4,7 @@ namespace App\Policies\Ecommerce\Channel;
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 @@ class ChannelPolicy
*/
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 @@ class ChannelPolicy
*/
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 @@ class ChannelPolicy
*/
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();
}

View File

@@ -204,7 +204,7 @@ class NovaServiceProvider extends NovaApplicationServiceProvider
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),

View File

@@ -5,6 +5,7 @@ namespace App\Support;
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 @@ class ChatSupport
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 @@ class ChatSupport
/**
* @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 @@ class ChatSupport
$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,

View File

@@ -7,8 +7,10 @@ return [
| Support user
|--------------------------------------------------------------------------
|
| Storefront chat always opens a 1:1 conversation with this user. Nova
| staff (admin / manager / direktor) operate this inbox on their behalf.
| Storefront chat can open a 1:1 with this user (Admin) or with a
| channel owner when that channel has chatting enabled. Nova staff
| operate the admin inbox on this user's behalf; vendors see only
| threads where a visitor picked their store.
|
*/

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('channels', function (Blueprint $table) {
$table->boolean('chatting')->default(false)->after('is_visible');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('channels', function (Blueprint $table) {
$table->dropColumn('chatting');
});
}
};

View File

@@ -0,0 +1,68 @@
<?php
use App\Support\ChatSupport;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('conversations', function (Blueprint $table) {
$table->foreignId('customer_id')->nullable()->after('id')->constrained('users')->nullOnDelete();
$table->foreignId('channel_id')->nullable()->after('customer_id')->constrained('channels')->nullOnDelete();
$table->string('thread_key')->nullable()->after('channel_id');
});
$supportId = ChatSupport::userId();
$claimed = [];
DB::table('conversations')->orderBy('id')->chunkById(100, function ($rows) use ($supportId, &$claimed) {
foreach ($rows as $conversation) {
$userIds = DB::table('conversation_user')
->where('conversation_id', $conversation->id)
->pluck('user_id');
if ($supportId === null || $userIds->count() !== 2 || ! $userIds->contains($supportId)) {
continue;
}
$customerId = (int) $userIds->first(fn ($id) => (int) $id !== $supportId);
$threadKey = 'admin';
if (isset($claimed[$customerId])) {
$threadKey = 'admin-legacy-'.$conversation->id;
} else {
$claimed[$customerId] = true;
}
DB::table('conversations')->where('id', $conversation->id)->update([
'customer_id' => $customerId,
'thread_key' => $threadKey,
]);
}
});
Schema::table('conversations', function (Blueprint $table) {
$table->unique(['customer_id', 'thread_key']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('conversations', function (Blueprint $table) {
$table->dropUnique(['customer_id', 'thread_key']);
$table->dropConstrainedForeignId('channel_id');
$table->dropConstrainedForeignId('customer_id');
$table->dropColumn('thread_key');
});
}
};

View File

@@ -141,9 +141,23 @@ body {
text-overflow: ellipsis;
}
.mm-chat__item-phone {
font-size: 12px;
color: #94a3b8;
.mm-chat__item-sub {
margin-top: 2px;
font-size: 11px;
font-weight: 600;
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.mm-chat__view-only {
margin: 0;
padding: 12px 16px;
background: #fff;
border-top: 1px solid #e2e8f0;
color: #64748b;
font-size: 13px;
text-align: center;
}
.mm-chat__item-unread {

View File

@@ -5,6 +5,7 @@
const messagesEl = document.getElementById("mm-chat-messages");
const headEl = document.getElementById("mm-chat-thread-head");
const formEl = document.getElementById("mm-chat-form");
const viewOnlyEl = document.getElementById("mm-chat-view-only");
const inputEl = document.getElementById("mm-chat-input");
const sendEl = document.getElementById("mm-chat-send");
const unreadEl = document.getElementById("mm-chat-unread");
@@ -84,12 +85,16 @@
const phone = conversation.user && conversation.user.phone_number;
const last = conversation.last_message;
const time = last ? formatTime(last.created_at) : "";
const subtitle = conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
button.innerHTML = `
<div class="mm-chat__item-row">
<span class="mm-chat__item-name"></span>
<span class="mm-chat__item-time"></span>
</div>
<div class="mm-chat__item-sub"></div>
${phone ? '<div class="mm-chat__item-phone"></div>' : ""}
<div class="mm-chat__item-preview"></div>
${conversation.unread_count ? '<span class="mm-chat__item-unread"></span>' : ""}
@@ -97,6 +102,7 @@
button.querySelector(".mm-chat__item-name").textContent = name;
button.querySelector(".mm-chat__item-time").textContent = time;
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
if (phone) {
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
}
@@ -189,14 +195,24 @@
}
async function markRead(conversationId) {
const conversation = state.conversations.find((item) => item.id === conversationId);
if (!conversation || conversation.can_reply === false) {
return;
}
await request(`${config.messagesUrl}/${conversationId}/read`, {
method: "POST",
headers: headers(true),
});
const conversation = state.conversations.find((item) => item.id === conversationId);
if (conversation) {
conversation.unread_count = 0;
renderInbox();
conversation.unread_count = 0;
renderInbox();
}
function setComposer(conversation) {
const canReply = Boolean(conversation && conversation.can_reply);
formEl.hidden = !canReply;
if (viewOnlyEl) {
viewOnlyEl.hidden = canReply || !conversation;
}
}
@@ -205,8 +221,11 @@
const conversation = state.conversations.find((item) => item.id === conversationId);
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
const phone = conversation && conversation.user && conversation.user.phone_number;
headEl.textContent = phone ? `${name} · ${phone}` : name;
formEl.hidden = false;
const subtitle = conversation && conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
setComposer(conversation);
renderInbox();
await loadMessages(conversationId, true);
await markRead(conversationId);
@@ -216,7 +235,8 @@
async function sendMessage(event) {
event.preventDefault();
const body = (inputEl.value || "").trim();
if (!body || !state.activeId) {
const conversation = state.conversations.find((item) => item.id === state.activeId);
if (!body || !state.activeId || !conversation || conversation.can_reply === false) {
return;
}
@@ -317,7 +337,7 @@
},
});
state.echo.private("chat.support").listen(".message.sent", upsertIncoming);
state.echo.private(config.inboxChannel || "chat.support").listen(".message.sent", upsertIncoming);
} catch (err) {
state.echo = null;
}

View File

@@ -26,6 +26,7 @@
<section class="mm-chat__thread">
<div class="mm-chat__thread-head" id="mm-chat-thread-head">{{ __('Select a conversation') }}</div>
<div class="mm-chat__messages" id="mm-chat-messages"></div>
<p class="mm-chat__view-only" id="mm-chat-view-only" hidden>{{ __('View only — the store owner replies here.') }}</p>
<form class="mm-chat__composer" id="mm-chat-form" hidden>
<textarea
id="mm-chat-input"
@@ -47,10 +48,13 @@
csrf: @json(csrf_token()),
broadcastAuth: @json(url('/panel/broadcasting/auth')),
pusher: @json($pusher),
inboxChannel: @json($inboxChannel),
strings: {
select: @json(__('Select a conversation')),
noMessages: @json(__('No messages yet.')),
you: @json(__('You')),
support: @json(__('Support')),
viewOnly: @json(__('View only — the store owner replies here.')),
},
};
</script>

View File

@@ -115,6 +115,8 @@ Route::middleware(['auth:sanctum', 'banned'])->group(function () {
// Chat...
Route::get('chat/conversations', [ChatController::class, 'conversations']);
Route::get('chat/targets', [ChatController::class, 'targets']);
Route::post('chat/start-target', [ChatController::class, 'startTarget']);
Route::get('chat/support', [ChatController::class, 'showSupport']);
Route::post('chat/support', [ChatController::class, 'support']);
Route::get('chat/contacts', [ChatController::class, 'contacts']);

View File

@@ -19,6 +19,15 @@ Broadcast::channel('chat.support', function ($user) {
return ChatSupport::isOperator($user);
});
Broadcast::channel('chat.inbox.{userId}', function ($user, $userId) {
if (! ctype_digit((string) $userId)) {
return false;
}
return (int) $user->id === (int) $userId
&& ChatSupport::canAccessPanelChat($user);
});
Broadcast::channel('chat.{conversationId}', function ($user, $conversationId) {
if (! ctype_digit((string) $conversationId)) {
return false;
@@ -35,6 +44,5 @@ Broadcast::channel('chat.{conversationId}', function ($user, $conversationId) {
return true;
}
return ChatSupport::isOperator($user)
&& ChatSupport::conversationIncludesSupport($conversationId);
return ChatSupport::isOperator($user);
});