diff --git a/app/Events/Conversation/MessageSent.php b/app/Events/Conversation/MessageSent.php index 5e54084..950484d 100644 --- a/app/Events/Conversation/MessageSent.php +++ b/app/Events/Conversation/MessageSent.php @@ -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; diff --git a/app/Http/Controllers/Api/V1/Chat/ChatController.php b/app/Http/Controllers/Api/V1/Chat/ChatController.php index f3d2d55..dd1f783 100644 --- a/app/Http/Controllers/Api/V1/Chat/ChatController.php +++ b/app/Http/Controllers/Api/V1/Chat/ChatController.php @@ -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()); diff --git a/app/Http/Controllers/Api/V1/Chat/Requests/ChatStartTargetRequest.php b/app/Http/Controllers/Api/V1/Chat/Requests/ChatStartTargetRequest.php new file mode 100644 index 0000000..e8e93cc --- /dev/null +++ b/app/Http/Controllers/Api/V1/Chat/Requests/ChatStartTargetRequest.php @@ -0,0 +1,39 @@ +|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.'); + } + }); + } +} diff --git a/app/Http/Controllers/Api/V1/Chat/Requests/ChatTargetsRequest.php b/app/Http/Controllers/Api/V1/Chat/Requests/ChatTargetsRequest.php new file mode 100644 index 0000000..912856d --- /dev/null +++ b/app/Http/Controllers/Api/V1/Chat/Requests/ChatTargetsRequest.php @@ -0,0 +1,28 @@ +|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, + ]); + } +} diff --git a/app/Http/Controllers/Api/V1/Chat/Resources/ChatChannelTargetResource.php b/app/Http/Controllers/Api/V1/Chat/Resources/ChatChannelTargetResource.php new file mode 100644 index 0000000..7934d0a --- /dev/null +++ b/app/Http/Controllers/Api/V1/Chat/Resources/ChatChannelTargetResource.php @@ -0,0 +1,22 @@ + + */ + public function toArray(Request $request): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'slug' => $this->slug, + 'image' => $this->thumbnail('200x200'), + ]; + } +} diff --git a/app/Http/Controllers/Api/V1/Chat/Resources/ConversationResource.php b/app/Http/Controllers/Api/V1/Chat/Resources/ConversationResource.php index 93b948d..5e12219 100644 --- a/app/Http/Controllers/Api/V1/Chat/Resources/ConversationResource.php +++ b/app/Http/Controllers/Api/V1/Chat/Resources/ConversationResource.php @@ -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) diff --git a/app/Http/Controllers/Nova/SupportChatController.php b/app/Http/Controllers/Nova/SupportChatController.php index 5b31899..d8d8397 100644 --- a/app/Http/Controllers/Nova/SupportChatController.php +++ b/app/Http/Controllers/Nova/SupportChatController.php @@ -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 diff --git a/app/Http/Middleware/EnsureChatOperator.php b/app/Http/Middleware/EnsureChatOperator.php index f703903..7a48a11 100644 --- a/app/Http/Middleware/EnsureChatOperator.php +++ b/app/Http/Middleware/EnsureChatOperator.php @@ -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); } diff --git a/app/Models/Chat/Conversation.php b/app/Models/Chat/Conversation.php index 5e0cecb..e1dcf98 100644 --- a/app/Models/Chat/Conversation.php +++ b/app/Models/Chat/Conversation.php @@ -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 + */ + 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 + */ + 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'); + } } diff --git a/app/Models/Ecommerce/Channel/Channel.php b/app/Models/Ecommerce/Channel/Channel.php index 9df6c80..42d07ca 100644 --- a/app/Models/Ecommerce/Channel/Channel.php +++ b/app/Models/Ecommerce/Channel/Channel.php @@ -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 + */ + 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 $query + * @return \Illuminate\Database\Eloquent\Builder + */ + 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 */ diff --git a/app/Nova/Resources/Ecommerce/Channel/Channel.php b/app/Nova/Resources/Ecommerce/Channel/Channel.php index 667ceb3..bf6b51b 100644 --- a/app/Nova/Resources/Ecommerce/Channel/Channel.php +++ b/app/Nova/Resources/Ecommerce/Channel/Channel.php @@ -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), ]; } diff --git a/app/Nova/Resources/Ecommerce/Channel/Fields/ChannelFieldsForIndex.php b/app/Nova/Resources/Ecommerce/Channel/Fields/ChannelFieldsForIndex.php index 3208928..0d8578b 100644 --- a/app/Nova/Resources/Ecommerce/Channel/Fields/ChannelFieldsForIndex.php +++ b/app/Nova/Resources/Ecommerce/Channel/Fields/ChannelFieldsForIndex.php @@ -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(), diff --git a/app/Policies/Ecommerce/Channel/ChannelPolicy.php b/app/Policies/Ecommerce/Channel/ChannelPolicy.php index 82d8c09..8b73e6a 100644 --- a/app/Policies/Ecommerce/Channel/ChannelPolicy.php +++ b/app/Policies/Ecommerce/Channel/ChannelPolicy.php @@ -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(); } diff --git a/app/Providers/NovaServiceProvider.php b/app/Providers/NovaServiceProvider.php index 742da34..328541a 100644 --- a/app/Providers/NovaServiceProvider.php +++ b/app/Providers/NovaServiceProvider.php @@ -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), diff --git a/app/Support/ChatSupport.php b/app/Support/ChatSupport.php index 1ac8f2b..3ca4153 100644 --- a/app/Support/ChatSupport.php +++ b/app/Support/ChatSupport.php @@ -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 */ - 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, diff --git a/config/chat.php b/config/chat.php index a7a3a76..332b9a6 100644 --- a/config/chat.php +++ b/config/chat.php @@ -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. | */ diff --git a/database/migrations/2026_08_15_210000_add_chatting_to_channels_table.php b/database/migrations/2026_08_15_210000_add_chatting_to_channels_table.php new file mode 100644 index 0000000..81b418f --- /dev/null +++ b/database/migrations/2026_08_15_210000_add_chatting_to_channels_table.php @@ -0,0 +1,28 @@ +boolean('chatting')->default(false)->after('is_visible'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('channels', function (Blueprint $table) { + $table->dropColumn('chatting'); + }); + } +}; diff --git a/database/migrations/2026_08_15_210100_add_targeting_to_conversations_table.php b/database/migrations/2026_08_15_210100_add_targeting_to_conversations_table.php new file mode 100644 index 0000000..1d6b487 --- /dev/null +++ b/database/migrations/2026_08_15_210100_add_targeting_to_conversations_table.php @@ -0,0 +1,68 @@ +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'); + }); + } +}; diff --git a/public/assets/panel/css/chat.css b/public/assets/panel/css/chat.css index 28c9cfc..ae0084d 100644 --- a/public/assets/panel/css/chat.css +++ b/public/assets/panel/css/chat.css @@ -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 { diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js index 20d925d..5f668be 100644 --- a/public/assets/panel/js/chat.js +++ b/public/assets/panel/js/chat.js @@ -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 = `
+
${phone ? '
' : ""}
${conversation.unread_count ? '' : ""} @@ -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; } diff --git a/resources/views/nova/chat.blade.php b/resources/views/nova/chat.blade.php index 981b32b..a222910 100644 --- a/resources/views/nova/chat.blade.php +++ b/resources/views/nova/chat.blade.php @@ -26,6 +26,7 @@
{{ __('Select a conversation') }}
+