diff --git a/.env.example b/.env.example index aefbb2f..9cce79d 100644 --- a/.env.example +++ b/.env.example @@ -18,8 +18,8 @@ DB_DATABASE=postshop DB_USERNAME=root DB_PASSWORD= -# Use `pusher` (Pusher Cloud or Soketi) for live chat. `log` is fine locally without websockets. -BROADCAST_DRIVER=log +# Use `reverb` for live chat (`php artisan reverb:start`). `log` is fine without websockets. +BROADCAST_DRIVER=reverb CACHE_DRIVER=file FILESYSTEM_DISK=local QUEUE_CONNECTION=sync @@ -47,17 +47,20 @@ AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false -# Required when BROADCAST_DRIVER=pusher (Pusher Cloud, or Soketi using the pusher driver) -PUSHER_APP_ID= -PUSHER_APP_KEY= -PUSHER_APP_SECRET= -PUSHER_HOST= -PUSHER_PORT=443 -PUSHER_SCHEME=https -PUSHER_APP_CLUSTER=mt1 +# Storefront widget + Nova inbox 1:1 target (users.id) +CHAT_SUPPORT_USER_ID= -VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}" -VITE_PUSHER_HOST="${PUSHER_HOST}" -VITE_PUSHER_PORT="${PUSHER_PORT}" -VITE_PUSHER_SCHEME="${PUSHER_SCHEME}" -VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" +# Laravel Reverb (`php artisan reverb:start`) +REVERB_APP_ID= +REVERB_APP_KEY= +REVERB_APP_SECRET= +REVERB_HOST=127.0.0.1 +REVERB_PORT=8080 +REVERB_SCHEME=http +REVERB_SERVER_HOST=0.0.0.0 +REVERB_SERVER_PORT=8080 + +VITE_REVERB_APP_KEY="${REVERB_APP_KEY}" +VITE_REVERB_HOST="${REVERB_HOST}" +VITE_REVERB_PORT="${REVERB_PORT}" +VITE_REVERB_SCHEME="${REVERB_SCHEME}" diff --git a/app/Events/Conversation/MessageSent.php b/app/Events/Conversation/MessageSent.php index 466c164..5e54084 100644 --- a/app/Events/Conversation/MessageSent.php +++ b/app/Events/Conversation/MessageSent.php @@ -30,9 +30,23 @@ class MessageSent implements ShouldBroadcast */ public function broadcastOn(): array { - return [ + $channels = [ new PrivateChannel('chat.'.$this->message->conversation_id), ]; + + $supportId = (int) config('chat.support_user_id'); + + if ($supportId > 0) { + $isSupportConversation = $this->message->conversation() + ->whereHas('users', fn ($query) => $query->where('users.id', $supportId)) + ->exists(); + + if ($isSupportConversation) { + $channels[] = new PrivateChannel('chat.support'); + } + } + + return $channels; } public function broadcastAs(): string diff --git a/app/Http/Controllers/Api/V1/Chat/ChatController.php b/app/Http/Controllers/Api/V1/Chat/ChatController.php index 9532a43..f3d2d55 100644 --- a/app/Http/Controllers/Api/V1/Chat/ChatController.php +++ b/app/Http/Controllers/Api/V1/Chat/ChatController.php @@ -14,7 +14,9 @@ use App\Http\Controllers\Controller; use App\Models\Chat\Conversation; use App\Models\Chat\Message; use App\Models\User; +use App\Support\ChatSupport; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; class ChatController extends Controller { @@ -23,26 +25,56 @@ class ChatController extends Controller */ public function conversations(): JsonResponse { - $conversations = auth()->user() - ->conversations() - ->with(['users', 'latestMessage.user']) - ->withCount([ - 'messages as unread_count' => fn ($query) => $query - ->where('user_id', '!=', auth()->id()) - ->whereNull('seen_at'), - ]) - ->withMax('messages', 'created_at') - ->orderByDesc('messages_max_created_at') - ->get(); + $conversations = Conversation::inboxFor(auth()->user()); return response()->rest(ConversationResource::collection($conversations)); } + /** + * (*) Existing support conversation (does not create) + */ + public function showSupport(Request $request): JsonResponse + { + abort_if(ChatSupport::isSupportUser($request->user()), 403); + + $conversation = Conversation::findOneToOne( + $request->user()->id, + ChatSupport::user()->id + ); + + if (! $conversation) { + return response()->rest(null); + } + + $conversation->loadForViewer($request->user()); + + return response()->rest(new ConversationResource($conversation)); + } + + /** + * (*) Find or create the 1:1 support conversation + */ + public function support(Request $request): JsonResponse + { + abort_if(ChatSupport::isSupportUser($request->user()), 403); + + $conversation = Conversation::findOrCreateOneToOne( + $request->user()->id, + ChatSupport::user()->id + ); + + $conversation->loadForViewer($request->user()); + + return response()->rest(new ConversationResource($conversation)); + } + /** * (*) Searchable chat contacts */ public function contacts(ChatContactsRequest $request): JsonResponse { + abort_unless(ChatSupport::isOperator($request->user()), 403); + $paginator = User::query() ->select(['id', 'first_name', 'last_name']) ->where('id', '!=', $request->user()->id) @@ -66,17 +98,14 @@ class ChatController extends Controller */ public function start(ChatStartRequest $request): JsonResponse { + abort_unless(ChatSupport::isOperator($request->user()), 403); + $conversation = Conversation::findOrCreateOneToOne( $request->user()->id, $request->integer('user_id') ); - $conversation->load(['users', 'latestMessage.user']) - ->loadCount([ - 'messages as unread_count' => fn ($query) => $query - ->where('user_id', '!=', $request->user()->id) - ->whereNull('seen_at'), - ]); + $conversation->loadForViewer($request->user()); return response()->rest(new ConversationResource($conversation)); } diff --git a/app/Http/Controllers/Nova/SupportChatController.php b/app/Http/Controllers/Nova/SupportChatController.php new file mode 100644 index 0000000..fe35878 --- /dev/null +++ b/app/Http/Controllers/Nova/SupportChatController.php @@ -0,0 +1,92 @@ + [ + 'key' => config('broadcasting.connections.reverb.key'), + 'host' => config('broadcasting.connections.reverb.options.host'), + 'port' => (int) config('broadcasting.connections.reverb.options.port', 8080), + 'scheme' => config('broadcasting.connections.reverb.options.scheme', 'http'), + ], + ]); + } + + public function conversations(): JsonResponse + { + $support = ChatSupport::user(); + + $conversations = Conversation::inboxFor($support) + ->map(fn (Conversation $conversation) => ChatSupport::conversationPayload($conversation, $support, true)) + ->values(); + + return response()->rest($conversations); + } + + public function messages(ChatMessagesRequest $request, Conversation $conversation): JsonResponse + { + $this->assertSupportConversation($conversation); + + $paginator = $conversation->messages() + ->with('user') + ->latest() + ->simplePaginate($request->perPage); + + $paginator->through(fn (Message $message) => (new MessageResource($message))->resolve()); + + return response()->rest_paginate($paginator); + } + + public function send(ChatSendMessageRequest $request, Conversation $conversation): JsonResponse + { + $support = $this->assertSupportConversation($conversation); + + $message = $conversation->messages()->create([ + 'user_id' => $support->id, + 'body' => $request->validated('body'), + ]); + + $message->load('user'); + + broadcast(new MessageSent($message))->toOthers(); + + return response()->rest(new MessageResource($message), 201); + } + + public function read(Conversation $conversation): JsonResponse + { + $support = $this->assertSupportConversation($conversation); + + $conversation->messages() + ->where('user_id', '!=', $support->id) + ->whereNull('seen_at') + ->update(['seen_at' => now()]); + + return response()->rest(); + } + + private function assertSupportConversation(Conversation $conversation): User + { + $support = ChatSupport::user(); + + abort_unless($conversation->hasParticipant($support), 403); + + return $support; + } +} diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index ff56f0d..8ca3451 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -5,6 +5,7 @@ namespace App\Http; use App\Http\Middleware\Authenticate; use App\Http\Middleware\CheckApiToken; use App\Http\Middleware\CheckIfUserIsBanned; +use App\Http\Middleware\EnsureChatOperator; use App\Http\Middleware\EncryptCookies; use App\Http\Middleware\EnsureUserHasRole; use App\Http\Middleware\PreventRequestsDuringMaintenance; @@ -93,5 +94,6 @@ class Kernel extends HttpKernel 'set_lang' => SetLanguage::class, 'banned' => CheckIfUserIsBanned::class, 'role' => EnsureUserHasRole::class, + 'chat.operator' => EnsureChatOperator::class, ]; } diff --git a/app/Http/Middleware/EnsureChatOperator.php b/app/Http/Middleware/EnsureChatOperator.php new file mode 100644 index 0000000..f703903 --- /dev/null +++ b/app/Http/Middleware/EnsureChatOperator.php @@ -0,0 +1,18 @@ +user()), 403); + + return $next($request); + } +} diff --git a/app/Models/Chat/Conversation.php b/app/Models/Chat/Conversation.php index 815a262..5e0cecb 100644 --- a/app/Models/Chat/Conversation.php +++ b/app/Models/Chat/Conversation.php @@ -3,6 +3,7 @@ namespace App\Models\Chat; use App\Models\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; @@ -14,15 +15,23 @@ class Conversation extends Model use HasFactory; /** - * Find or create a 1:1 conversation between two users. + * Find a 1:1 conversation between two users. */ - public static function findOrCreateOneToOne(int $userId, int $otherUserId): self + public static function findOneToOne(int $userId, int $otherUserId): ?self { - $conversation = static::query() + return static::query() ->whereHas('users', fn ($query) => $query->where('users.id', $userId)) ->whereHas('users', fn ($query) => $query->where('users.id', $otherUserId)) ->has('users', '=', 2) ->first(); + } + + /** + * Find or create a 1:1 conversation between two users. + */ + public static function findOrCreateOneToOne(int $userId, int $otherUserId): self + { + $conversation = static::findOneToOne($userId, $otherUserId); if ($conversation) { return $conversation; @@ -34,6 +43,33 @@ class Conversation extends Model return $conversation; } + /** + * Inbox for a participant, newest activity first. + */ + public static function inboxFor(User $viewer): Collection + { + return $viewer->conversations() + ->with(['users', 'latestMessage.user']) + ->withCount([ + 'messages as unread_count' => fn ($query) => $query + ->where('user_id', '!=', $viewer->id) + ->whereNull('seen_at'), + ]) + ->withMax('messages', 'created_at') + ->orderByDesc('messages_max_created_at') + ->get(); + } + + public function loadForViewer(User $viewer): self + { + return $this->load(['users', 'latestMessage.user']) + ->loadCount([ + 'messages as unread_count' => fn ($query) => $query + ->where('user_id', '!=', $viewer->id) + ->whereNull('seen_at'), + ]); + } + public function users(): BelongsToMany { return $this->belongsToMany(User::class); diff --git a/app/Providers/BroadcastServiceProvider.php b/app/Providers/BroadcastServiceProvider.php index f264152..5add828 100644 --- a/app/Providers/BroadcastServiceProvider.php +++ b/app/Providers/BroadcastServiceProvider.php @@ -2,8 +2,11 @@ namespace App\Providers; +use App\Http\Middleware\EnsureChatOperator; use Illuminate\Support\Facades\Broadcast; use Illuminate\Support\ServiceProvider; +use Laravel\Nova\Http\Middleware\Authenticate as NovaAuthenticate; +use Laravel\Nova\Http\Middleware\Authorize as NovaAuthorize; class BroadcastServiceProvider extends ServiceProvider { @@ -14,6 +17,11 @@ class BroadcastServiceProvider extends ServiceProvider { Broadcast::routes(['middleware' => ['auth:sanctum']]); + Broadcast::routes([ + 'prefix' => 'panel', + 'middleware' => ['web', NovaAuthenticate::class, NovaAuthorize::class, EnsureChatOperator::class], + ]); + require base_path('routes/channels.php'); } } diff --git a/app/Providers/NovaServiceProvider.php b/app/Providers/NovaServiceProvider.php index b46691b..742da34 100644 --- a/app/Providers/NovaServiceProvider.php +++ b/app/Providers/NovaServiceProvider.php @@ -36,6 +36,7 @@ use App\Nova\Resources\System\VersionManagement\AppVersion; use App\Nova\Seller\Seller; use App\Nova\User; use App\Repositories\Nova\NovaRepo; +use App\Support\ChatSupport; use Eolica\NovaLocaleSwitcher\LocaleSwitcher; use Illuminate\Http\Request; use Illuminate\Support\Facades\Gate; @@ -200,6 +201,11 @@ class NovaServiceProvider extends NovaApplicationServiceProvider MenuItem::resource(Coupon::class), ])->icon('presentation-chart-bar')->collapsedByDefault(), + MenuSection::make(__('Chat'), [ + MenuItem::externalLink(__('Inbox'), url('/panel/chat')), + ])->icon('chat-alt-2') + ->canSee(fn (Request $request) => ChatSupport::isOperator($request->user())), + MenuSection::make('Hatlar', [ MenuItem::resource(ContactUS::class), ])->icon('inbox-in')->collapsedByDefault(), diff --git a/app/Support/ChatSupport.php b/app/Support/ChatSupport.php new file mode 100644 index 0000000..ef3fa54 --- /dev/null +++ b/app/Support/ChatSupport.php @@ -0,0 +1,92 @@ + 0 ? $id : null; + } + + public static function user(): User + { + $id = static::userId(); + + abort_unless($id, 422, 'Chat support user is not configured.'); + + $user = User::query()->find($id); + + abort_unless($user, 422, 'Chat support user was not found.'); + + return $user; + } + + public static function isSupportUser(?User $user): bool + { + $id = static::userId(); + + return $user !== null && $id !== null && (int) $user->id === $id; + } + + /** + * Nova staff who may operate the support inbox (vendors excluded). + */ + public static function isOperator(?User $user): bool + { + if ($user === null) { + return false; + } + + return $user->isMe() || $user->isAdmin() || $user->isDirektor() || $user->isManager(); + } + + public static function conversationIncludesSupport(int $conversationId): bool + { + $id = static::userId(); + + if ($id === null) { + return false; + } + + return DB::table('conversation_user') + ->where('conversation_id', $conversationId) + ->where('user_id', $id) + ->exists(); + } + + /** + * @return array + */ + public static function conversationPayload(Conversation $conversation, User $viewer, bool $includePhone = false): array + { + $conversation->loadMissing(['users', 'latestMessage.user']); + + $otherUser = $conversation->users->firstWhere('id', '!=', $viewer->id); + + $user = $otherUser ? (new ChatUserResource($otherUser))->resolve() : null; + + if ($includePhone && $otherUser && is_array($user)) { + $user['phone_number'] = $otherUser->phone_number; + } + + return [ + 'id' => $conversation->id, + 'user' => $user, + 'last_message' => $conversation->latestMessage + ? (new MessageResource($conversation->latestMessage))->resolve() + : null, + 'unread_count' => (int) ($conversation->unread_count ?? 0), + 'created_at' => $conversation->created_at, + 'updated_at' => $conversation->updated_at, + ]; + } +} diff --git a/composer.json b/composer.json index 25ed6f8..f3029ad 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,7 @@ "guzzlehttp/guzzle": "^7.2", "laravel/framework": "^10.10", "laravel/nova": "*", + "laravel/reverb": "^1.11", "laravel/sanctum": "^3.2", "laravel/tinker": "^2.8", "maatwebsite/excel": "^3.1", diff --git a/composer.lock b/composer.lock index 149354a..b2aa891 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3758ca8376a4ceb686f0265581777fd8", + "content-hash": "6c8f85c880987851c5a8908689974f71", "packages": [ { "name": "blendbyte/nova-attach-many", @@ -239,6 +239,136 @@ ], "time": "2023-12-11T17:09:12+00:00" }, + { + "name": "clue/redis-protocol", + "version": "v0.3.2", + "source": { + "type": "git", + "url": "https://github.com/clue/redis-protocol.git", + "reference": "6f565332f5531b7722d1e9c445314b91862f6d6c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/redis-protocol/zipball/6f565332f5531b7722d1e9c445314b91862f6d6c", + "reference": "6f565332f5531b7722d1e9c445314b91862f6d6c", + "shasum": "" + }, + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "psr-4": { + "Clue\\Redis\\Protocol\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@lueck.tv" + } + ], + "description": "A streaming Redis protocol (RESP) parser and serializer written in pure PHP.", + "homepage": "https://github.com/clue/redis-protocol", + "keywords": [ + "parser", + "protocol", + "redis", + "resp", + "serializer", + "streaming" + ], + "support": { + "issues": "https://github.com/clue/redis-protocol/issues", + "source": "https://github.com/clue/redis-protocol/tree/v0.3.2" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "time": "2024-08-07T11:06:28+00:00" + }, + { + "name": "clue/redis-react", + "version": "v2.8.0", + "source": { + "type": "git", + "url": "https://github.com/clue/reactphp-redis.git", + "reference": "84569198dfd5564977d2ae6a32de4beb5a24bdca" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/reactphp-redis/zipball/84569198dfd5564977d2ae6a32de4beb5a24bdca", + "reference": "84569198dfd5564977d2ae6a32de4beb5a24bdca", + "shasum": "" + }, + "require": { + "clue/redis-protocol": "^0.3.2", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.0 || ^1.1", + "react/promise-timer": "^1.11", + "react/socket": "^1.16" + }, + "require-dev": { + "clue/block-react": "^1.5", + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "psr-4": { + "Clue\\React\\Redis\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "Async Redis client implementation, built on top of ReactPHP.", + "homepage": "https://github.com/clue/reactphp-redis", + "keywords": [ + "async", + "client", + "database", + "reactphp", + "redis" + ], + "support": { + "issues": "https://github.com/clue/reactphp-redis/issues", + "source": "https://github.com/clue/reactphp-redis/tree/v2.8.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "time": "2025-01-03T16:18:33+00:00" + }, { "name": "composer/pcre", "version": "3.3.2", @@ -1330,6 +1460,53 @@ }, "time": "2024-03-18T11:24:55+00:00" }, + { + "name": "evenement/evenement", + "version": "v3.0.2", + "source": { + "type": "git", + "url": "https://github.com/igorw/evenement.git", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/igorw/evenement/zipball/0a16b0d71ab13284339abb99d9d2bd813640efbc", + "reference": "0a16b0d71ab13284339abb99d9d2bd813640efbc", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^9 || ^6" + }, + "type": "library", + "autoload": { + "psr-4": { + "Evenement\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https://github.com/igorw/evenement/issues", + "source": "https://github.com/igorw/evenement/tree/v3.0.2" + }, + "time": "2023-08-08T05:53:35+00:00" + }, { "name": "ezyang/htmlpurifier", "version": "v4.19.0", @@ -2526,6 +2703,85 @@ }, "time": "2024-08-12T22:06:33+00:00" }, + { + "name": "laravel/reverb", + "version": "v1.11.1", + "source": { + "type": "git", + "url": "https://github.com/laravel/reverb.git", + "reference": "52ce5fd88cd1d7eacfdcf6b91cea4704cc546f27" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/reverb/zipball/52ce5fd88cd1d7eacfdcf6b91cea4704cc546f27", + "reference": "52ce5fd88cd1d7eacfdcf6b91cea4704cc546f27", + "shasum": "" + }, + "require": { + "clue/redis-react": "^2.6", + "guzzlehttp/psr7": "^2.6", + "illuminate/console": "^10.47|^11.0|^12.0|^13.0", + "illuminate/contracts": "^10.47|^11.0|^12.0|^13.0", + "illuminate/http": "^10.47|^11.0|^12.0|^13.0", + "illuminate/support": "^10.47|^11.0|^12.0|^13.0", + "laravel/prompts": "^0.1.15|^0.2.0|^0.3.0", + "php": "^8.2", + "pusher/pusher-php-server": "^7.2", + "ratchet/rfc6455": "^0.4", + "react/promise-timer": "^1.10", + "react/socket": "^1.14", + "symfony/console": "^6.0|^7.0|^8.0", + "symfony/http-foundation": "^6.3|^7.0|^8.0" + }, + "require-dev": { + "orchestra/testbench": "^8.36|^9.15|^10.8|^11.0", + "pestphp/pest": "^2.0|^3.0|^4.0", + "phpstan/phpstan": "^1.10", + "ratchet/pawl": "^0.4.1", + "react/async": "^4.2", + "react/http": "^1.9" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Reverb\\ApplicationManagerServiceProvider", + "Laravel\\Reverb\\ReverbServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Laravel\\Reverb\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Joe Dixon", + "email": "joe@laravel.com" + } + ], + "description": "Laravel Reverb provides a real-time WebSocket communication backend for Laravel applications.", + "keywords": [ + "WebSockets", + "laravel", + "real-time", + "websocket" + ], + "support": { + "issues": "https://github.com/laravel/reverb/issues", + "source": "https://github.com/laravel/reverb/tree/v1.11.1" + }, + "time": "2026-08-06T14:48:58+00:00" + }, { "name": "laravel/sanctum", "version": "v3.3.3", @@ -6061,6 +6317,595 @@ ], "time": "2026-03-24T09:13:16+00:00" }, + { + "name": "ratchet/rfc6455", + "version": "v0.4.1", + "source": { + "type": "git", + "url": "https://github.com/ratchetphp/RFC6455.git", + "reference": "9b05f371219cbaf9748b505f139617dd0715592b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ratchetphp/RFC6455/zipball/9b05f371219cbaf9748b505f139617dd0715592b", + "reference": "9b05f371219cbaf9748b505f139617dd0715592b", + "shasum": "" + }, + "require": { + "php": ">=7.4", + "psr/http-factory-implementation": "^1.0", + "symfony/polyfill-php80": "^1.15" + }, + "require-dev": { + "guzzlehttp/psr7": "^2.7", + "phpunit/phpunit": "^9.5", + "react/socket": "^1.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Ratchet\\RFC6455\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "role": "Developer" + }, + { + "name": "Matt Bonneau", + "role": "Developer" + } + ], + "description": "RFC6455 WebSocket protocol handler", + "homepage": "http://socketo.me", + "keywords": [ + "WebSockets", + "rfc6455", + "websocket" + ], + "support": { + "chat": "https://gitter.im/reactphp/reactphp", + "issues": "https://github.com/ratchetphp/RFC6455/issues", + "source": "https://github.com/ratchetphp/RFC6455/tree/v0.4.1" + }, + "time": "2026-06-06T14:34:23+00:00" + }, + { + "name": "react/cache", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/cache.git", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/cache/zipball/d47c472b64aa5608225f47965a484b75c7817d5b", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/cache/issues", + "source": "https://github.com/reactphp/cache/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2022-11-30T15:59:55+00:00" + }, + { + "name": "react/dns", + "version": "v1.14.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/dns.git", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/dns/zipball/7562c05391f42701c1fccf189c8225fece1cd7c3", + "reference": "7562c05391f42701c1fccf189c8225fece1cd7c3", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3 || ^2", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Dns\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/dns/issues", + "source": "https://github.com/reactphp/dns/tree/v1.14.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-18T19:34:28+00:00" + }, + { + "name": "react/event-loop", + "version": "v1.6.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/event-loop.git", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/event-loop/zipball/ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "reference": "ba276bda6083df7e0050fd9b33f66ad7a4ac747a", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https://github.com/reactphp/event-loop/issues", + "source": "https://github.com/reactphp/event-loop/tree/v1.6.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-17T20:46:25+00:00" + }, + { + "name": "react/promise", + "version": "v3.3.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise.git", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise/zipball/23444f53a813a3296c1368bb104793ce8d88f04a", + "reference": "23444f53a813a3296c1368bb104793ce8d88f04a", + "shasum": "" + }, + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan/phpstan": "1.12.28 || 1.4.10", + "phpunit/phpunit": "^9.6 || ^7.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "React\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https://github.com/reactphp/promise/issues", + "source": "https://github.com/reactphp/promise/tree/v3.3.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-08-19T18:57:03+00:00" + }, + { + "name": "react/promise-timer", + "version": "v1.11.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise-timer.git", + "reference": "4f70306ed66b8b44768941ca7f142092600fafc1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise-timer/zipball/4f70306ed66b8b44768941ca7f142092600fafc1", + "reference": "4f70306ed66b8b44768941ca7f142092600fafc1", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.7.0 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "React\\Promise\\Timer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A trivial implementation of timeouts for Promises, built on top of ReactPHP.", + "homepage": "https://github.com/reactphp/promise-timer", + "keywords": [ + "async", + "event-loop", + "promise", + "reactphp", + "timeout", + "timer" + ], + "support": { + "issues": "https://github.com/reactphp/promise-timer/issues", + "source": "https://github.com/reactphp/promise-timer/tree/v1.11.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2024-06-04T14:27:45+00:00" + }, + { + "name": "react/socket", + "version": "v1.17.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/socket.git", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/socket/zipball/ef5b17b81f6f60504c539313f94f2d826c5faa08", + "reference": "ef5b17b81f6f60504c539313f94f2d826c5faa08", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/dns": "^1.13", + "react/event-loop": "^1.2", + "react/promise": "^3.2 || ^2.6 || ^1.2.1", + "react/stream": "^1.4" + }, + "require-dev": { + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36", + "react/async": "^4.3 || ^3.3 || ^2", + "react/promise-stream": "^1.4", + "react/promise-timer": "^1.11" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Socket\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https://github.com/reactphp/socket/issues", + "source": "https://github.com/reactphp/socket/tree/v1.17.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2025-11-19T20:47:34+00:00" + }, + { + "name": "react/stream", + "version": "v1.4.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/stream.git", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/stream/zipball/1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "reference": "1e5b0acb8fe55143b5b426817155190eb6f5b18d", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react/event-loop": "^1.2" + }, + "require-dev": { + "clue/stream-filter": "~1.2", + "phpunit/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "type": "library", + "autoload": { + "psr-4": { + "React\\Stream\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https://github.com/reactphp/stream/issues", + "source": "https://github.com/reactphp/stream/tree/v1.4.0" + }, + "funding": [ + { + "url": "https://opencollective.com/reactphp", + "type": "open_collective" + } + ], + "time": "2024-06-11T12:45:25+00:00" + }, { "name": "shuvroroy/nova-tabs", "version": "v1.1.1", diff --git a/config/broadcasting.php b/config/broadcasting.php index 2410485..797f5dc 100644 --- a/config/broadcasting.php +++ b/config/broadcasting.php @@ -11,7 +11,7 @@ return [ | framework when an event needs to be broadcast. You may set this to | any of the connections defined in the "connections" array below. | - | Supported: "pusher", "ably", "redis", "log", "null" + | Supported: "reverb", "pusher", "ably", "redis", "log", "null" | */ @@ -30,6 +30,23 @@ return [ 'connections' => [ + 'reverb' => [ + 'driver' => 'reverb', + 'key' => env('REVERB_APP_KEY'), + 'secret' => env('REVERB_APP_SECRET'), + 'app_id' => env('REVERB_APP_ID'), + 'options' => [ + 'host' => env('REVERB_HOST'), + 'port' => env('REVERB_PORT', 443), + 'scheme' => env('REVERB_SCHEME', 'https'), + 'useTLS' => env('REVERB_SCHEME', 'https') === 'https', + 'path' => env('REVERB_SERVER_PATH', ''), + ], + 'client_options' => [ + // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html + ], + ], + 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), diff --git a/config/chat.php b/config/chat.php new file mode 100644 index 0000000..a7a3a76 --- /dev/null +++ b/config/chat.php @@ -0,0 +1,17 @@ + (int) env('CHAT_SUPPORT_USER_ID', 0), + +]; diff --git a/config/reverb.php b/config/reverb.php new file mode 100644 index 0000000..91f3880 --- /dev/null +++ b/config/reverb.php @@ -0,0 +1,102 @@ + env('REVERB_SERVER', 'reverb'), + + /* + |-------------------------------------------------------------------------- + | Reverb Servers + |-------------------------------------------------------------------------- + | + | Here you may define details for each of the supported Reverb servers. + | Each server has its own configuration options that are defined in + | the array below. You should ensure all the options are present. + | + */ + + 'servers' => [ + + 'reverb' => [ + 'host' => env('REVERB_SERVER_HOST', '0.0.0.0'), + 'port' => env('REVERB_SERVER_PORT', 8080), + 'path' => env('REVERB_SERVER_PATH', ''), + 'hostname' => env('REVERB_HOST'), + 'options' => [ + 'tls' => [], + ], + 'max_request_size' => env('REVERB_MAX_REQUEST_SIZE', 10_000), + 'scaling' => [ + 'enabled' => env('REVERB_SCALING_ENABLED', false), + 'channel' => env('REVERB_SCALING_CHANNEL', 'reverb'), + 'server' => [ + 'url' => env('REDIS_URL'), + 'host' => env('REDIS_HOST', '127.0.0.1'), + 'port' => env('REDIS_PORT', '6379'), + 'username' => env('REDIS_USERNAME'), + 'password' => env('REDIS_PASSWORD'), + 'database' => env('REDIS_DB', '0'), + 'timeout' => env('REDIS_TIMEOUT', 60), + ], + ], + 'pulse_ingest_interval' => env('REVERB_PULSE_INGEST_INTERVAL', 15), + 'telescope_ingest_interval' => env('REVERB_TELESCOPE_INGEST_INTERVAL', 15), + ], + + ], + + /* + |-------------------------------------------------------------------------- + | Reverb Applications + |-------------------------------------------------------------------------- + | + | Here you may define how Reverb applications are managed. If you choose + | to use the "config" provider, you may define an array of apps which + | your server will support, including their connection credentials. + | + */ + + 'apps' => [ + + 'provider' => 'config', + + 'apps' => [ + [ + 'key' => env('REVERB_APP_KEY'), + 'secret' => env('REVERB_APP_SECRET'), + 'app_id' => env('REVERB_APP_ID'), + 'options' => [ + 'host' => env('REVERB_HOST'), + 'port' => env('REVERB_PORT', 443), + 'scheme' => env('REVERB_SCHEME', 'https'), + 'useTLS' => env('REVERB_SCHEME', 'https') === 'https', + ], + 'allowed_origins' => ['*'], + 'ping_interval' => env('REVERB_APP_PING_INTERVAL', 60), + 'activity_timeout' => env('REVERB_APP_ACTIVITY_TIMEOUT', 30), + 'max_connections' => env('REVERB_APP_MAX_CONNECTIONS'), + 'max_message_size' => env('REVERB_APP_MAX_MESSAGE_SIZE', 10_000), + 'accept_client_events_from' => env('REVERB_APP_ACCEPT_CLIENT_EVENTS_FROM', 'members'), + 'rate_limiting' => [ + 'enabled' => env('REVERB_APP_RATE_LIMITING_ENABLED', false), + 'max_attempts' => env('REVERB_APP_RATE_LIMIT_MAX_ATTEMPTS', 60), + 'decay_seconds' => env('REVERB_APP_RATE_LIMIT_DECAY_SECONDS', 60), + 'terminate_on_limit' => env('REVERB_APP_RATE_LIMIT_TERMINATE', false), + ], + ], + ], + + ], + +]; diff --git a/public/assets/panel/css/chat.css b/public/assets/panel/css/chat.css new file mode 100644 index 0000000..28c9cfc --- /dev/null +++ b/public/assets/panel/css/chat.css @@ -0,0 +1,256 @@ +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body { + margin: 0; + height: 100%; + font-family: Nunito, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + background: #0f172a; + color: #0f172a; +} + +.mm-chat { + display: flex; + flex-direction: column; + height: 100%; + min-height: 100vh; +} + +.mm-chat__top { + display: flex; + align-items: center; + gap: 16px; + padding: 12px 20px; + background: #1e293b; + color: #f8fafc; + flex-shrink: 0; +} + +.mm-chat__top h1 { + margin: 0; + font-size: 18px; + font-weight: 700; +} + +.mm-chat__back { + color: #cbd5e1; + text-decoration: none; + font-size: 13px; +} + +.mm-chat__back:hover { + color: #fff; +} + +.mm-chat__badge { + margin-left: auto; + min-width: 22px; + height: 22px; + padding: 0 7px; + border-radius: 999px; + background: #d32824; + color: #fff; + font-size: 12px; + line-height: 22px; + text-align: center; + font-weight: 700; +} + +.mm-chat__shell { + display: grid; + grid-template-columns: 320px 1fr; + flex: 1; + min-height: 0; + background: #e2e8f0; +} + +.mm-chat__inbox { + display: flex; + flex-direction: column; + background: #fff; + border-right: 1px solid #e2e8f0; + min-height: 0; +} + +.mm-chat__inbox-head { + padding: 14px 16px; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: #64748b; + border-bottom: 1px solid #e2e8f0; +} + +.mm-chat__list { + overflow-y: auto; + flex: 1; +} + +.mm-chat__empty { + margin: 24px 16px; + color: #94a3b8; + font-size: 13px; +} + +.mm-chat__item { + display: block; + width: 100%; + text-align: left; + border: 0; + border-bottom: 1px solid #f1f5f9; + background: #fff; + padding: 12px 16px; + cursor: pointer; +} + +.mm-chat__item:hover, +.mm-chat__item.is-active { + background: #f8fafc; +} + +.mm-chat__item-row { + display: flex; + justify-content: space-between; + gap: 8px; + align-items: center; +} + +.mm-chat__item-name { + font-weight: 700; + font-size: 14px; + color: #0f172a; +} + +.mm-chat__item-time { + font-size: 11px; + color: #94a3b8; + white-space: nowrap; +} + +.mm-chat__item-preview { + margin-top: 4px; + font-size: 13px; + color: #64748b; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.mm-chat__item-phone { + font-size: 12px; + color: #94a3b8; +} + +.mm-chat__item-unread { + display: inline-flex; + min-width: 18px; + height: 18px; + margin-top: 6px; + padding: 0 6px; + border-radius: 999px; + background: #d32824; + color: #fff; + font-size: 11px; + font-weight: 700; + align-items: center; + justify-content: center; +} + +.mm-chat__thread { + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; +} + +.mm-chat__thread-head { + padding: 14px 20px; + background: #fff; + border-bottom: 1px solid #e2e8f0; + font-weight: 700; + font-size: 15px; +} + +.mm-chat__messages { + flex: 1; + overflow-y: auto; + padding: 20px; + display: flex; + flex-direction: column; + gap: 10px; +} + +.mm-chat__bubble { + max-width: 72%; + padding: 10px 12px; + border-radius: 14px; + font-size: 14px; + line-height: 1.45; + white-space: pre-wrap; + word-break: break-word; +} + +.mm-chat__bubble--in { + align-self: flex-start; + background: #fff; + color: #0f172a; +} + +.mm-chat__bubble--out { + align-self: flex-end; + background: #d32824; + color: #fff; +} + +.mm-chat__meta { + display: block; + margin-top: 4px; + font-size: 11px; + opacity: 0.7; +} + +.mm-chat__composer { + display: flex; + gap: 10px; + padding: 12px 16px; + background: #fff; + border-top: 1px solid #e2e8f0; +} + +.mm-chat__composer textarea { + flex: 1; + resize: none; + border: 1px solid #cbd5e1; + border-radius: 10px; + padding: 10px 12px; + font: inherit; + min-height: 44px; + max-height: 140px; +} + +.mm-chat__composer button { + border: 0; + border-radius: 10px; + background: #d32824; + color: #fff; + font-weight: 700; + padding: 0 18px; + cursor: pointer; +} + +.mm-chat__composer button:disabled { + opacity: 0.55; + cursor: not-allowed; +} + +@media (max-width: 800px) { + .mm-chat__shell { + grid-template-columns: 1fr; + grid-template-rows: 40% 1fr; + } +} diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js new file mode 100644 index 0000000..1f61026 --- /dev/null +++ b/public/assets/panel/js/chat.js @@ -0,0 +1,359 @@ +(function () { + const config = window.MM_CHAT || {}; + const listEl = document.getElementById("mm-chat-list"); + const emptyInboxEl = document.getElementById("mm-chat-empty-inbox"); + const messagesEl = document.getElementById("mm-chat-messages"); + const headEl = document.getElementById("mm-chat-thread-head"); + const formEl = document.getElementById("mm-chat-form"); + const inputEl = document.getElementById("mm-chat-input"); + const sendEl = document.getElementById("mm-chat-send"); + const unreadEl = document.getElementById("mm-chat-unread"); + + const state = { + conversations: [], + activeId: null, + messages: [], + nextPageUrl: null, + loadingMessages: false, + echo: null, + }; + + function headers(json) { + const next = { + Accept: "application/json", + "X-CSRF-TOKEN": config.csrf, + "X-Requested-With": "XMLHttpRequest", + }; + + if (json) { + next["Content-Type"] = "application/json"; + } + + return next; + } + + async function request(url, options) { + const response = await fetch(url, options); + if (!response.ok) { + throw new Error("Chat request failed"); + } + return response.json(); + } + + function formatTime(value) { + if (!value) { + return ""; + } + const date = new Date(value); + if (Number.isNaN(date.getTime())) { + return ""; + } + const pad = (n) => String(n).padStart(2, "0"); + return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`; + } + + function preview(body) { + if (!body) { + return ""; + } + return body.length > 80 ? `${body.slice(0, 80)}…` : body; + } + + function updateUnreadBadge() { + const total = state.conversations.reduce( + (sum, conversation) => sum + (conversation.unread_count || 0), + 0 + ); + unreadEl.textContent = String(total); + unreadEl.hidden = total < 1; + } + + function renderInbox() { + listEl.innerHTML = ""; + emptyInboxEl.hidden = state.conversations.length > 0; + + state.conversations.forEach((conversation) => { + const button = document.createElement("button"); + button.type = "button"; + button.className = "mm-chat__item"; + if (conversation.id === state.activeId) { + button.classList.add("is-active"); + } + + const name = (conversation.user && conversation.user.name) || `#${conversation.id}`; + const phone = conversation.user && conversation.user.phone_number; + const last = conversation.last_message; + const time = last ? formatTime(last.created_at) : ""; + + button.innerHTML = ` +
+ + +
+ ${phone ? '
' : ""} +
+ ${conversation.unread_count ? '' : ""} + `; + + button.querySelector(".mm-chat__item-name").textContent = name; + button.querySelector(".mm-chat__item-time").textContent = time; + if (phone) { + button.querySelector(".mm-chat__item-phone").textContent = String(phone); + } + button.querySelector(".mm-chat__item-preview").textContent = last + ? preview(last.body) + : ""; + const unread = button.querySelector(".mm-chat__item-unread"); + if (unread) { + unread.textContent = String(conversation.unread_count); + } + + button.addEventListener("click", () => openConversation(conversation.id)); + listEl.appendChild(button); + }); + + updateUnreadBadge(); + } + + function isOutgoing(message, conversation) { + const otherId = conversation && conversation.user && conversation.user.id; + return !otherId || message.user?.id !== otherId; + } + + function renderMessages() { + const conversation = state.conversations.find((item) => item.id === state.activeId); + messagesEl.innerHTML = ""; + + if (!state.messages.length) { + const empty = document.createElement("p"); + empty.className = "mm-chat__empty"; + empty.textContent = config.strings.noMessages; + messagesEl.appendChild(empty); + return; + } + + state.messages.forEach((message) => { + const bubble = document.createElement("div"); + bubble.className = `mm-chat__bubble ${ + isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in" + }`; + const body = document.createElement("div"); + body.textContent = message.body; + const meta = document.createElement("span"); + meta.className = "mm-chat__meta"; + meta.textContent = formatTime(message.created_at); + bubble.appendChild(body); + bubble.appendChild(meta); + messagesEl.appendChild(bubble); + }); + + messagesEl.scrollTop = messagesEl.scrollHeight; + } + + async function loadInbox() { + const payload = await request(config.conversationsUrl, { headers: headers() }); + state.conversations = payload.data || []; + renderInbox(); + } + + async function loadMessages(conversationId, reset) { + if (state.loadingMessages) { + return; + } + state.loadingMessages = true; + + const url = reset + ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` + : state.nextPageUrl; + + if (!url) { + state.loadingMessages = false; + return; + } + + try { + const payload = await request(url, { headers: headers() }); + const items = (payload.data || []).slice().reverse(); + state.nextPageUrl = payload.pagination && payload.pagination.next_page_url; + + if (reset) { + state.messages = items; + } else { + state.messages = items.concat(state.messages); + } + + renderMessages(); + } finally { + state.loadingMessages = false; + } + } + + async function markRead(conversationId) { + 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(); + } + } + + async function openConversation(conversationId) { + state.activeId = conversationId; + 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; + renderInbox(); + await loadMessages(conversationId, true); + await markRead(conversationId); + subscribeThread(conversationId); + } + + async function sendMessage(event) { + event.preventDefault(); + const body = (inputEl.value || "").trim(); + if (!body || !state.activeId) { + return; + } + + sendEl.disabled = true; + try { + const payload = await request( + `${config.messagesUrl}/${state.activeId}/messages`, + { + method: "POST", + headers: headers(true), + body: JSON.stringify({ body }), + } + ); + const message = payload.data; + if (message && !state.messages.some((item) => item.id === message.id)) { + state.messages.push(message); + renderMessages(); + } + inputEl.value = ""; + await loadInbox(); + } finally { + sendEl.disabled = false; + inputEl.focus(); + } + } + + function upsertIncoming(message) { + if (!message || !message.conversation_id) { + return; + } + + if (state.activeId === message.conversation_id) { + if (!state.messages.some((item) => item.id === message.id)) { + state.messages.push(message); + renderMessages(); + } + markRead(message.conversation_id); + } + + loadInbox(); + } + + function subscribeThread(conversationId) { + if (!state.echo) { + return; + } + state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming); + } + + function bootEcho() { + const pusher = config.pusher || {}; + const EchoClass = window.Echo; + if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) { + return; + } + + const scheme = pusher.scheme || "https"; + const forceTLS = scheme === "https"; + + try { + state.echo = new EchoClass({ + broadcaster: "reverb", + key: pusher.key, + wsHost: pusher.host || undefined, + wsPort: pusher.port || undefined, + wssPort: pusher.port || undefined, + forceTLS, + enabledTransports: ["ws", "wss"], + disableStats: true, + cluster: "mt1", + authEndpoint: config.broadcastAuth, + auth: { + headers: { + "X-CSRF-TOKEN": config.csrf, + Accept: "application/json", + }, + }, + }); + + state.echo.private("chat.support").listen(".message.sent", upsertIncoming); + } catch (err) { + state.echo = null; + } + } + + async function mergeActiveMessages() { + if (!state.activeId || state.loadingMessages) { + return; + } + + const payload = await request( + `${config.messagesUrl}/${state.activeId}/messages?perPage=50`, + { headers: headers() } + ); + const items = (payload.data || []).slice().reverse(); + const known = new Set(state.messages.map((item) => item.id)); + let added = false; + + items.forEach((message) => { + if (!known.has(message.id)) { + state.messages.push(message); + added = true; + } + }); + + if (added) { + state.messages.sort( + (a, b) => new Date(a.created_at) - new Date(b.created_at) + ); + renderMessages(); + } + } + + formEl.addEventListener("submit", sendMessage); + inputEl.addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + formEl.requestSubmit(); + } + }); + + messagesEl.addEventListener("scroll", () => { + if (messagesEl.scrollTop < 40 && state.nextPageUrl && state.activeId) { + const previousHeight = messagesEl.scrollHeight; + loadMessages(state.activeId, false).then(() => { + messagesEl.scrollTop = messagesEl.scrollHeight - previousHeight; + }); + } + }); + + loadInbox(); + bootEcho(); + setInterval(() => { + loadInbox().then(() => { + if (state.activeId) { + mergeActiveMessages(); + } + }); + }, 4000); +})(); diff --git a/resources/views/nova/chat.blade.php b/resources/views/nova/chat.blade.php new file mode 100644 index 0000000..5a34337 --- /dev/null +++ b/resources/views/nova/chat.blade.php @@ -0,0 +1,63 @@ + + + + + + + + {{ __('Chat') }} — {{ config('nova.name', config('app.name')) }} + + + +
+
+ {{ __('Back to panel') }} +

{{ __('Chat') }}

+ +
+ +
+ + +
+
{{ __('Select a conversation') }}
+
+ +
+
+
+ + + @if (! empty($pusher['key'])) + + + @endif + + + diff --git a/routes/api/v1/v1-api.php b/routes/api/v1/v1-api.php index 732839d..dbe0302 100644 --- a/routes/api/v1/v1-api.php +++ b/routes/api/v1/v1-api.php @@ -115,6 +115,8 @@ Route::middleware(['auth:sanctum', 'banned'])->group(function () { // Chat... Route::get('chat/conversations', [ChatController::class, 'conversations']); + Route::get('chat/support', [ChatController::class, 'showSupport']); + Route::post('chat/support', [ChatController::class, 'support']); Route::get('chat/contacts', [ChatController::class, 'contacts']); Route::post('chat/start', [ChatController::class, 'start']); Route::get('chat/conversations/{conversation}/messages', [ChatController::class, 'messages'])->where(['conversation' => '[0-9]+']); diff --git a/routes/channels.php b/routes/channels.php index fa3421a..265099e 100644 --- a/routes/channels.php +++ b/routes/channels.php @@ -1,5 +1,6 @@ where('conversation_id', $conversationId) ->where('user_id', $user->id) ->exists(); + + if ($isParticipant) { + return true; + } + + return ChatSupport::isOperator($user) + && ChatSupport::conversationIncludesSupport((int) $conversationId); +}); + +Broadcast::channel('chat.support', function ($user) { + return ChatSupport::isOperator($user); }); diff --git a/routes/web.php b/routes/web.php index 7e78e99..ba67c6a 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,7 +1,28 @@ name('login'); Route::get('api/online-payment-store', [OnlinePaymentController::class, 'index'])->name('online-payment-store'); + +Route::middleware([NovaAuthenticate::class, NovaAuthorize::class, EnsureChatOperator::class]) + ->prefix('panel/chat') + ->name('nova.chat.') + ->group(function () { + Route::get('/', [SupportChatController::class, 'index'])->name('index'); + Route::get('/conversations', [SupportChatController::class, 'conversations'])->name('conversations'); + Route::get('/conversations/{conversation}/messages', [SupportChatController::class, 'messages']) + ->whereNumber('conversation') + ->name('messages'); + Route::post('/conversations/{conversation}/messages', [SupportChatController::class, 'send']) + ->whereNumber('conversation') + ->name('send'); + Route::post('/conversations/{conversation}/read', [SupportChatController::class, 'read']) + ->whereNumber('conversation') + ->name('read'); + });