Compare commits
28
Commits
da530f6b36
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c34cbb439 | ||
|
|
62249b18b3 | ||
|
|
bd92137fdc | ||
|
|
db9a8e9d7b | ||
|
|
da611b81b6 | ||
|
|
64407d0241 | ||
|
|
c126032cc9 | ||
|
|
c5567413e1 | ||
|
|
aa23e73b34 | ||
|
|
c9f584ce2a | ||
|
|
9248ef775a | ||
|
|
c78f9bc944 | ||
|
|
f4f781b835 | ||
|
|
9fd01d6f78 | ||
|
|
5a9ba0cc23 | ||
|
|
87bc7d9591 | ||
|
|
0cf106994f | ||
|
|
57dd8ee378 | ||
|
|
550ffea5c0 | ||
|
|
5c17c35741 | ||
|
|
c55694ec8c | ||
|
|
ab7cd8160f | ||
|
|
f68db67465 | ||
|
|
3a415edb6e | ||
|
|
cdbad87958 | ||
|
|
3ce4d17b82 | ||
|
|
f33bae8514 | ||
|
|
8080f8ea73 |
No files matched your search
+10
-1
@@ -50,7 +50,10 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
|
||||
# Storefront widget + Nova inbox 1:1 target (users.id)
|
||||
CHAT_SUPPORT_USER_ID=
|
||||
|
||||
# Laravel Reverb (`php artisan reverb:start`)
|
||||
# Laravel Reverb (`php artisan reverb:start` / supervisor).
|
||||
# PHP publishes events to 127.0.0.1:8080 (REVERB_BROADCAST_* / SERVER_PORT).
|
||||
# Browsers use nginx at wss://mm.com.tm/app (VITE_REVERB_*).
|
||||
# Local:
|
||||
REVERB_APP_ID=
|
||||
REVERB_APP_KEY=
|
||||
REVERB_APP_SECRET=
|
||||
@@ -59,6 +62,12 @@ REVERB_PORT=8080
|
||||
REVERB_SCHEME=http
|
||||
REVERB_SERVER_HOST=0.0.0.0
|
||||
REVERB_SERVER_PORT=8080
|
||||
REVERB_BROADCAST_HOST=127.0.0.1
|
||||
REVERB_BROADCAST_PORT=8080
|
||||
REVERB_BROADCAST_SCHEME=http
|
||||
# Production: keep BROADCAST_* and SERVER_* on 127.0.0.1:8080.
|
||||
# Set VITE_REVERB_HOST=mm.com.tm VITE_REVERB_PORT=443 VITE_REVERB_SCHEME=https
|
||||
# on the frontend build. Do not point PHP at mm.com.tm:443.
|
||||
|
||||
VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
|
||||
VITE_REVERB_HOST="${REVERB_HOST}"
|
||||
|
||||
@@ -3,15 +3,17 @@
|
||||
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;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class MessageSent implements ShouldBroadcast
|
||||
class MessageSent implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
@@ -20,7 +22,7 @@ class MessageSent implements ShouldBroadcast
|
||||
*/
|
||||
public function __construct(private Message $message)
|
||||
{
|
||||
$this->message->loadMissing('user');
|
||||
$this->message->loadMissing(['user', 'conversation.channel']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,16 +36,20 @@ public function broadcastOn(): array
|
||||
new PrivateChannel('chat.'.$this->message->conversation_id),
|
||||
];
|
||||
|
||||
$supportId = (int) config('chat.support_user_id');
|
||||
$conversation = $this->message->conversation;
|
||||
|
||||
if ($supportId > 0) {
|
||||
$isSupportConversation = $this->message->conversation()
|
||||
->whereHas('users', fn ($query) => $query->where('users.id', $supportId))
|
||||
->exists();
|
||||
if ($conversation instanceof Conversation && $conversation->isSupportThread()) {
|
||||
$channels[] = new PrivateChannel('chat.support');
|
||||
}
|
||||
|
||||
if ($isSupportConversation) {
|
||||
$channels[] = new PrivateChannel('chat.support');
|
||||
}
|
||||
$channel = $conversation?->channel;
|
||||
|
||||
if (
|
||||
$channel
|
||||
&& $channel->channelables_type === User::class
|
||||
&& $channel->channelables_id
|
||||
) {
|
||||
$channels[] = new PrivateChannel('chat.inbox.'.$channel->channelables_id);
|
||||
}
|
||||
|
||||
return $channels;
|
||||
|
||||
@@ -217,8 +217,6 @@ function mask_phone(string|int|float $phone): string
|
||||
if (! function_exists('tmpostChannel')) {
|
||||
/**
|
||||
* Default channel
|
||||
*
|
||||
* @return App\Models\Shop\Channel
|
||||
*/
|
||||
function tmpostChannel(): Channel
|
||||
{
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatMessagesRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatSendMessageRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatStartRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatStartTargetRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Requests\ChatTargetsRequest;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatChannelTargetResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatUserResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ConversationResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Chat\Conversation;
|
||||
use App\Models\Chat\Message;
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -30,6 +34,59 @@ public function conversations(): JsonResponse
|
||||
return response()->rest(ConversationResource::collection($conversations));
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Admin + chat-enabled stores for the widget picker
|
||||
*/
|
||||
public function targets(ChatTargetsRequest $request): JsonResponse
|
||||
{
|
||||
$viewer = $request->user();
|
||||
$search = $request->q;
|
||||
|
||||
$paginator = Channel::query()
|
||||
->chatTargets($viewer)
|
||||
->with('media')
|
||||
->when($search, fn ($query) => $query->where('name', 'like', '%'.$search.'%'))
|
||||
->ordered()
|
||||
->simplePaginate($request->perPage);
|
||||
|
||||
$paginator->through(fn (Channel $channel) => (new ChatChannelTargetResource($channel))->resolve());
|
||||
|
||||
return response()->json([
|
||||
'message' => 'success',
|
||||
'data' => [
|
||||
'admin' => ChatSupport::adminTarget($viewer),
|
||||
'channels' => $paginator->items(),
|
||||
],
|
||||
'pagination' => [
|
||||
'page' => $paginator->currentPage(),
|
||||
'perPage' => $paginator->perPage(),
|
||||
'count' => $paginator->count(),
|
||||
'first_page_url' => $paginator->url(1),
|
||||
'next_page_url' => $paginator->nextPageUrl(),
|
||||
'prev_page_url' => $paginator->previousPageUrl(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Find or create a conversation with admin or a store
|
||||
*/
|
||||
public function startTarget(ChatStartTargetRequest $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
if ($request->boolean('admin')) {
|
||||
$conversation = Conversation::findOrCreateSupport($request->user());
|
||||
} else {
|
||||
$channel = Channel::query()->findOrFail($request->integer('channel_id'));
|
||||
$conversation = Conversation::findOrCreateForChannel($request->user(), $channel);
|
||||
}
|
||||
|
||||
$conversation->loadForViewer($request->user());
|
||||
|
||||
return response()->rest(new ConversationResource($conversation));
|
||||
}
|
||||
|
||||
/**
|
||||
* (*) Existing support conversation (does not create)
|
||||
*/
|
||||
@@ -37,10 +94,14 @@ public function showSupport(Request $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
$conversation = Conversation::findOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
$conversation = Conversation::findSupportFor($request->user());
|
||||
|
||||
if (! $conversation && ChatSupport::userId()) {
|
||||
$conversation = Conversation::findOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
}
|
||||
|
||||
if (! $conversation) {
|
||||
return response()->rest(null);
|
||||
@@ -58,10 +119,7 @@ public function support(Request $request): JsonResponse
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($request->user()), 403);
|
||||
|
||||
$conversation = Conversation::findOrCreateOneToOne(
|
||||
$request->user()->id,
|
||||
ChatSupport::user()->id
|
||||
);
|
||||
$conversation = Conversation::findOrCreateSupport($request->user());
|
||||
|
||||
$conversation->loadForViewer($request->user());
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class ChatStartTargetRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'admin' => ['sometimes', 'boolean'],
|
||||
'channel_id' => ['sometimes', 'integer', 'exists:channels,id'],
|
||||
];
|
||||
}
|
||||
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$admin = $this->boolean('admin');
|
||||
$hasChannel = $this->filled('channel_id');
|
||||
|
||||
if ($admin && $hasChannel) {
|
||||
$validator->errors()->add('channel_id', 'Choose either admin or a channel.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $admin && ! $hasChannel) {
|
||||
$validator->errors()->add('admin', 'Choose either admin or a channel.');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class ChatTargetsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'q' => ['nullable', 'string', 'max:100'],
|
||||
'perPage' => ['nullable', 'integer', 'min:1', 'max:50'],
|
||||
];
|
||||
}
|
||||
|
||||
protected function passedValidation(): void
|
||||
{
|
||||
$this->merge([
|
||||
'perPage' => $this->perPage ?: 20,
|
||||
'q' => is_string($this->q) ? trim($this->q) : null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Chat\Resources;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ChatChannelTargetResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'slug' => $this->slug,
|
||||
'image' => $this->thumbnail('200x200'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,18 @@ public function toArray(Request $request): array
|
||||
? $this->users->firstWhere('id', '!=', $request->user()?->id)
|
||||
: null;
|
||||
|
||||
$channel = $this->relationLoaded('channel') ? $this->channel : null;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'thread_key' => $this->thread_key,
|
||||
'user' => $this->when($otherUser, fn () => new ChatUserResource($otherUser)),
|
||||
'channel' => $channel ? [
|
||||
'id' => $channel->id,
|
||||
'name' => $channel->name,
|
||||
'slug' => $channel->slug,
|
||||
'image' => $channel->thumbnail('200x200'),
|
||||
] : null,
|
||||
'last_message' => $this->when(
|
||||
$this->relationLoaded('latestMessage') && $this->latestMessage,
|
||||
fn () => new MessageResource($this->latestMessage)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Product\Search;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class ProductMediaResourceJustThumb extends JsonResource
|
||||
{
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'thumbnail' => $this->getUrl('thumb288x431'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Http\Controllers\Api\V1\Product\Search;
|
||||
|
||||
use App\Http\Controllers\Api\V1\Product\Resources\ProductMediaResource;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Ecommerce\Product\Product\Product;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -37,7 +36,7 @@ public function index(Request $request): JsonResponse
|
||||
->where('products.parent_id', null)
|
||||
->where('products.stock', '>', 0);
|
||||
})
|
||||
->limit(40)
|
||||
->limit(12)
|
||||
->get();
|
||||
|
||||
return response()->rest(
|
||||
@@ -52,7 +51,7 @@ public function index(Request $request): JsonResponse
|
||||
'name' => $product->brand?->name,
|
||||
],
|
||||
'thumbnail' => $product->thumbnail(),
|
||||
'media' => ProductMediaResource::collection($product->media),
|
||||
'media' => ProductMediaResourceJustThumb::collection($product->media),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,36 +12,52 @@
|
||||
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', [
|
||||
'pusher' => [
|
||||
'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'),
|
||||
],
|
||||
'chatCss' => $this->panelAsset('css/chat.css'),
|
||||
'chatScripts' => array_values(array_filter([
|
||||
$key ? $this->panelAsset('js/pusher.min.js') : null,
|
||||
$key ? $this->panelAsset('js/echo.iife.js') : null,
|
||||
$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')
|
||||
@@ -55,10 +71,10 @@ public function messages(ChatMessagesRequest $request, Conversation $conversatio
|
||||
|
||||
public function send(ChatSendMessageRequest $request, Conversation $conversation): JsonResponse
|
||||
{
|
||||
$support = $this->assertSupportConversation($conversation);
|
||||
$sender = $this->assertCanReply($request->user(), $conversation);
|
||||
|
||||
$message = $conversation->messages()->create([
|
||||
'user_id' => $support->id,
|
||||
'user_id' => $sender->id,
|
||||
'body' => $request->validated('body'),
|
||||
]);
|
||||
|
||||
@@ -71,22 +87,84 @@ public function send(ChatSendMessageRequest $request, Conversation $conversation
|
||||
|
||||
public function read(Conversation $conversation): JsonResponse
|
||||
{
|
||||
$support = $this->assertSupportConversation($conversation);
|
||||
$actor = request()->user();
|
||||
$this->assertCanView($actor, $conversation);
|
||||
|
||||
$excludeId = ChatSupport::isOperator($actor)
|
||||
? ChatSupport::user()->id
|
||||
: $actor->id;
|
||||
|
||||
$conversation->messages()
|
||||
->where('user_id', '!=', $support->id)
|
||||
->where('user_id', '!=', $excludeId)
|
||||
->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
|
||||
{
|
||||
$path = public_path('assets/panel/'.$relative);
|
||||
|
||||
abort_unless(is_readable($path), 500, "Missing chat asset [{$relative}].");
|
||||
|
||||
return (string) file_get_contents($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Browser websocket host. Reverb itself stays on 127.0.0.1:8080;
|
||||
* production browsers connect through nginx at wss://mm.com.tm/app.
|
||||
*
|
||||
* @return array{key: mixed, host: string, port: int, scheme: string}
|
||||
*/
|
||||
private function chatPusherConfig(mixed $key): array
|
||||
{
|
||||
$requestHost = request()->getHost();
|
||||
$public = ! in_array($requestHost, ['127.0.0.1', 'localhost', '::1', '0.0.0.0'], true);
|
||||
|
||||
if ($public) {
|
||||
$https = request()->secure()
|
||||
|| request()->header('X-Forwarded-Proto') === 'https'
|
||||
|| str_contains($requestHost, '.');
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'host' => $requestHost,
|
||||
'port' => $https ? 443 : 80,
|
||||
'scheme' => $https ? 'https' : 'http',
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'key' => $key,
|
||||
'host' => (string) config('broadcasting.connections.reverb.options.host'),
|
||||
'port' => (int) config('broadcasting.connections.reverb.options.port', 8080),
|
||||
'scheme' => (string) config('broadcasting.connections.reverb.options.scheme', 'http'),
|
||||
];
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -5,8 +5,8 @@
|
||||
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\EnsureChatOperator;
|
||||
use App\Http\Middleware\EnsureUserHasRole;
|
||||
use App\Http\Middleware\PreventRequestsDuringMaintenance;
|
||||
use App\Http\Middleware\RedirectIfAuthenticated;
|
||||
|
||||
@@ -11,7 +11,7 @@ class EnsureChatOperator
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
abort_unless(ChatSupport::isOperator($request->user()), 403);
|
||||
abort_unless(ChatSupport::canAccessPanelChat($request->user()), 403);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
@@ -2,18 +2,40 @@
|
||||
|
||||
namespace App\Models\Chat;
|
||||
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class Conversation extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
public const THREAD_ADMIN = 'admin';
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'customer_id',
|
||||
'channel_id',
|
||||
'thread_key',
|
||||
];
|
||||
|
||||
public static function threadKeyForChannel(int $channelId): string
|
||||
{
|
||||
return 'channel:'.$channelId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a 1:1 conversation between two users.
|
||||
*/
|
||||
@@ -43,13 +65,65 @@ public static function findOrCreateOneToOne(int $userId, int $otherUserId): self
|
||||
return $conversation;
|
||||
}
|
||||
|
||||
public static function findSupportFor(User $customer): ?self
|
||||
{
|
||||
return static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', self::THREAD_ADMIN)
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function findOrCreateSupport(User $customer): self
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($customer), 403);
|
||||
|
||||
$support = ChatSupport::user();
|
||||
|
||||
return static::locateOrCreate($customer, $support, self::THREAD_ADMIN, null);
|
||||
}
|
||||
|
||||
public static function findOrCreateForChannel(User $customer, Channel $channel): self
|
||||
{
|
||||
abort_if(ChatSupport::isSupportUser($customer), 403);
|
||||
|
||||
$existing = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', static::threadKeyForChannel($channel->id))
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$channel->loadMissing('user');
|
||||
$owner = $channel->user;
|
||||
|
||||
abort_unless(
|
||||
$channel->is_visible
|
||||
&& $channel->chatting
|
||||
&& $channel->channelables_type === User::class
|
||||
&& $owner,
|
||||
422,
|
||||
'This store is not available for chat.'
|
||||
);
|
||||
abort_if((int) $owner->id === (int) $customer->id, 403, 'You cannot chat with your own store.');
|
||||
abort_if(ChatSupport::isSupportUser($owner), 422, 'This store is not available for chat.');
|
||||
|
||||
return static::locateOrCreate(
|
||||
$customer,
|
||||
$owner,
|
||||
static::threadKeyForChannel($channel->id),
|
||||
$channel
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inbox for a participant, newest activity first.
|
||||
*/
|
||||
public static function inboxFor(User $viewer): Collection
|
||||
{
|
||||
return $viewer->conversations()
|
||||
->with(['users', 'latestMessage.user'])
|
||||
->with(['users', 'latestMessage.user', 'channel'])
|
||||
->withCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->where('user_id', '!=', $viewer->id)
|
||||
@@ -60,9 +134,28 @@ public static function inboxFor(User $viewer): Collection
|
||||
->get();
|
||||
}
|
||||
|
||||
public static function inboxForStaff(): Collection
|
||||
{
|
||||
return static::panelInboxQuery()->get();
|
||||
}
|
||||
|
||||
public static function inboxForVendor(User $vendor): Collection
|
||||
{
|
||||
$channelIds = $vendor->channels()->pluck('id');
|
||||
|
||||
if ($channelIds->isEmpty()) {
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
return static::panelInboxQuery()
|
||||
->whereIn('channel_id', $channelIds)
|
||||
->whereHas('users', fn ($query) => $query->where('users.id', $vendor->id))
|
||||
->get();
|
||||
}
|
||||
|
||||
public function loadForViewer(User $viewer): self
|
||||
{
|
||||
return $this->load(['users', 'latestMessage.user'])
|
||||
return $this->load(['users', 'latestMessage.user', 'channel'])
|
||||
->loadCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->where('user_id', '!=', $viewer->id)
|
||||
@@ -70,6 +163,21 @@ public function loadForViewer(User $viewer): self
|
||||
]);
|
||||
}
|
||||
|
||||
public function isSupportThread(): bool
|
||||
{
|
||||
return $this->thread_key === self::THREAD_ADMIN;
|
||||
}
|
||||
|
||||
public function customer(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'customer_id');
|
||||
}
|
||||
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class);
|
||||
@@ -89,4 +197,69 @@ public function hasParticipant(User $user): bool
|
||||
{
|
||||
return $this->users()->where('users.id', $user->id)->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<static>
|
||||
*/
|
||||
private static function panelInboxQuery()
|
||||
{
|
||||
return static::query()
|
||||
->with(['customer', 'channel', 'users', 'latestMessage.user'])
|
||||
->withCount([
|
||||
'messages as unread_count' => fn ($query) => $query
|
||||
->whereColumn('messages.user_id', 'conversations.customer_id')
|
||||
->whereNull('seen_at'),
|
||||
])
|
||||
->withMax('messages', 'created_at')
|
||||
->orderByDesc('messages_max_created_at');
|
||||
}
|
||||
|
||||
private static function locateOrCreate(User $customer, User $counterpart, string $threadKey, ?Channel $channel): self
|
||||
{
|
||||
$existing = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', $threadKey)
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
try {
|
||||
return DB::transaction(function () use ($customer, $counterpart, $threadKey, $channel) {
|
||||
$conversation = static::query()->create([
|
||||
'customer_id' => $customer->id,
|
||||
'channel_id' => $channel?->id,
|
||||
'thread_key' => $threadKey,
|
||||
]);
|
||||
|
||||
$conversation->users()->attach([$customer->id, $counterpart->id]);
|
||||
|
||||
return $conversation;
|
||||
});
|
||||
} catch (QueryException $exception) {
|
||||
if (! static::isUniqueViolation($exception)) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$conversation = static::query()
|
||||
->where('customer_id', $customer->id)
|
||||
->where('thread_key', $threadKey)
|
||||
->first();
|
||||
|
||||
if ($conversation) {
|
||||
return $conversation;
|
||||
}
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isUniqueViolation(QueryException $exception): bool
|
||||
{
|
||||
$sqlState = (string) $exception->errorInfo[0];
|
||||
|
||||
return in_array($sqlState, ['23000', '23505'], true)
|
||||
|| str_contains(strtolower($exception->getMessage()), 'unique');
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Models\User;
|
||||
use App\Repositories\Ecommerce\Channel\ChannelRepository;
|
||||
use App\Repositories\System\Cache\CacheRepository;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
@@ -46,10 +47,22 @@ class Channel extends Model implements HasMedia, Sortable
|
||||
'sort_order',
|
||||
'is_default',
|
||||
'is_visible',
|
||||
'chatting',
|
||||
'channelables_type',
|
||||
'channelables_id',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $casts = [
|
||||
'is_default' => 'boolean',
|
||||
'is_visible' => 'boolean',
|
||||
'chatting' => 'boolean',
|
||||
];
|
||||
|
||||
/**
|
||||
* Sortable attributes
|
||||
*
|
||||
@@ -158,6 +171,26 @@ public function user(): BelongsTo
|
||||
return $this->belongsTo(User::class, 'channelables_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores that visitors may start a chat with.
|
||||
*
|
||||
* @param Builder<static> $query
|
||||
* @return Builder<static>
|
||||
*/
|
||||
public function scopeChatTargets($query, ?User $viewer = null)
|
||||
{
|
||||
$supportId = (int) config('chat.support_user_id');
|
||||
|
||||
return $query
|
||||
->where('is_visible', true)
|
||||
->where('chatting', true)
|
||||
->where('channelables_type', User::class)
|
||||
->whereNotNull('channelables_id')
|
||||
->whereHas('user')
|
||||
->when($viewer, fn ($query) => $query->where('channelables_id', '!=', $viewer->id))
|
||||
->when($supportId > 0, fn ($query) => $query->where('channelables_id', '!=', $supportId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Default tmpost inventory
|
||||
*/
|
||||
|
||||
@@ -8,8 +8,12 @@
|
||||
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 Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Nova\Fields\BelongsTo;
|
||||
use Laravel\Nova\Fields\Boolean;
|
||||
use Laravel\Nova\Fields\DateTime;
|
||||
use Laravel\Nova\Fields\Hidden;
|
||||
use Laravel\Nova\Fields\ID;
|
||||
@@ -81,6 +85,33 @@ public function fieldsForIndex(): array
|
||||
return ChannelFieldsForIndex::make();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an "index" query for the given resource.
|
||||
*
|
||||
* @param Builder $query
|
||||
*/
|
||||
public static function indexQuery(NovaRequest $request, $query): Builder
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user && $user->isVendor() && ! ChatSupport::isOperator($user)) {
|
||||
$query->where('channelables_type', User::class)
|
||||
->where('channelables_id', $user->id);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a "detail" query for the given resource.
|
||||
*
|
||||
* @param Builder $query
|
||||
*/
|
||||
public static function detailQuery(NovaRequest $request, $query): Builder
|
||||
{
|
||||
return static::indexQuery($request, parent::detailQuery($request, $query));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the fields displayed by the resource.
|
||||
*/
|
||||
@@ -122,8 +153,16 @@ public function fields(NovaRequest $request): array
|
||||
$model->channelables_id = $request->input('user');
|
||||
}),
|
||||
|
||||
Boolean::make(__('Active'), 'is_visible')
|
||||
->canSee(fn () => Auth::user()->hasRole(['vendor'])),
|
||||
|
||||
NovaSwitcher::make(__('Active'), 'is_visible')
|
||||
->default(true),
|
||||
->default(true)
|
||||
->canSee(fn () => Auth::user()->hasRole(['admin', 'direktor'])),
|
||||
|
||||
NovaSwitcher::make(__('Chatting'), 'chatting')
|
||||
->default(false)
|
||||
->canSee(fn () => Auth::user()->hasRole(['admin', 'direktor'])),
|
||||
|
||||
MorphMany::make(__('Products'), 'products', Product::class),
|
||||
];
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
namespace App\Nova\Resources\Ecommerce\Channel\Fields;
|
||||
|
||||
use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Laravel\Nova\Fields\DateTime;
|
||||
use Laravel\Nova\Fields\ID;
|
||||
use Laravel\Nova\Fields\Text;
|
||||
use Trin4ik\NovaSwitcher\NovaSwitcher;
|
||||
|
||||
class ChannelFieldsForIndex
|
||||
{
|
||||
@@ -25,6 +27,9 @@ public static function make(): array
|
||||
|
||||
Text::make(__('User'), fn ($model) => $model->user?->fullname ?? '-'),
|
||||
|
||||
NovaSwitcher::make(__('Chatting'), 'chatting')
|
||||
->canSee(fn () => Auth::user()->hasRole(['admin', 'direktor'])),
|
||||
|
||||
DateTime::make(__('Created at'), 'created_at')
|
||||
->turkmenDate()
|
||||
->sortable(),
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
|
||||
@@ -28,7 +29,7 @@ public function before(User $user, string $ability): ?Response
|
||||
*/
|
||||
public function viewAny(User $user): Response
|
||||
{
|
||||
if ($user->hasRole(['admin', 'direktor'])) {
|
||||
if ($user->hasRole(['admin', 'direktor']) || $user->isVendor()) {
|
||||
return $this->allow();
|
||||
}
|
||||
|
||||
@@ -40,7 +41,7 @@ public function viewAny(User $user): Response
|
||||
*/
|
||||
public function view(User $user, Channel $channel): Response
|
||||
{
|
||||
if ($user->hasRole(['admin', 'direktor'])) {
|
||||
if ($user->hasRole(['admin', 'direktor']) || ChatSupport::ownsChannel($user, $channel)) {
|
||||
return $this->allow();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
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
|
||||
{
|
||||
@@ -17,9 +15,14 @@ public function boot(): void
|
||||
{
|
||||
Broadcast::routes(['middleware' => ['auth:sanctum']]);
|
||||
|
||||
Broadcast::routes([
|
||||
'prefix' => 'api/v1',
|
||||
'middleware' => ['api', 'api_token', 'auth:sanctum'],
|
||||
]);
|
||||
|
||||
Broadcast::routes([
|
||||
'prefix' => 'panel',
|
||||
'middleware' => ['web', NovaAuthenticate::class, NovaAuthorize::class, EnsureChatOperator::class],
|
||||
'middleware' => ['web', 'auth', EnsureChatOperator::class],
|
||||
]);
|
||||
|
||||
require base_path('routes/channels.php');
|
||||
|
||||
@@ -204,7 +204,7 @@ public function setupNavigation(): void
|
||||
MenuSection::make(__('Chat'), [
|
||||
MenuItem::externalLink(__('Inbox'), url('/panel/chat')),
|
||||
])->icon('chat-alt-2')
|
||||
->canSee(fn (Request $request) => ChatSupport::isOperator($request->user())),
|
||||
->canSee(fn (Request $request) => ChatSupport::canAccessPanelChat($request->user())),
|
||||
|
||||
MenuSection::make('Hatlar', [
|
||||
MenuItem::resource(ContactUS::class),
|
||||
@@ -232,11 +232,11 @@ public function setupNavigation(): void
|
||||
MenuGroup::make(__('App'), [
|
||||
MenuItem::resource(AppVersion::class),
|
||||
])->collapsedByDefault(),
|
||||
])->icon('cog')->collapsedByDefault(),
|
||||
])->canSee(fn () => false)->icon('cog')->collapsedByDefault(),
|
||||
|
||||
MenuSection::make(__('Backups'), [
|
||||
MenuItem::make('Backups')->path('/backups'),
|
||||
])->icon('server')->collapsedByDefault(),
|
||||
])->canSee(fn () => auth()->user()->isAdmin() || auth()->user()->isDirektor())->icon('server')->collapsedByDefault(),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\ChatUserResource;
|
||||
use App\Http\Controllers\Api\V1\Chat\Resources\MessageResource;
|
||||
use App\Models\Chat\Conversation;
|
||||
use App\Models\Ecommerce\Channel\Channel;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
@@ -46,9 +47,85 @@ public static function isOperator(?User $user): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
if (static::isSupportUser($user)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -66,11 +143,12 @@ public static function conversationIncludesSupport(int $conversationId): bool
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function conversationPayload(Conversation $conversation, User $viewer, bool $includePhone = false): array
|
||||
public static function conversationPayload(Conversation $conversation, User $actor, bool $includePhone = false): array
|
||||
{
|
||||
$conversation->loadMissing(['users', 'latestMessage.user']);
|
||||
$conversation->loadMissing(['users', 'latestMessage.user', 'channel', 'customer']);
|
||||
|
||||
$otherUser = $conversation->users->firstWhere('id', '!=', $viewer->id);
|
||||
$otherUser = $conversation->customer
|
||||
?? $conversation->users->firstWhere('id', '!=', $actor->id);
|
||||
|
||||
$user = $otherUser ? (new ChatUserResource($otherUser))->resolve() : null;
|
||||
|
||||
@@ -78,9 +156,18 @@ public static function conversationPayload(Conversation $conversation, User $vie
|
||||
$user['phone_number'] = $otherUser->phone_number;
|
||||
}
|
||||
|
||||
$channel = $conversation->channel;
|
||||
|
||||
return [
|
||||
'id' => $conversation->id,
|
||||
'thread_key' => $conversation->thread_key,
|
||||
'user' => $user,
|
||||
'channel' => $channel ? [
|
||||
'id' => $channel->id,
|
||||
'name' => $channel->name,
|
||||
'slug' => $channel->slug,
|
||||
] : null,
|
||||
'can_reply' => static::canReply($actor, $conversation),
|
||||
'last_message' => $conversation->latestMessage
|
||||
? (new MessageResource($conversation->latestMessage))->resolve()
|
||||
: null,
|
||||
|
||||
@@ -36,10 +36,10 @@
|
||||
'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',
|
||||
'host' => env('REVERB_BROADCAST_HOST', '127.0.0.1'),
|
||||
'port' => (int) env('REVERB_BROADCAST_PORT', env('REVERB_SERVER_PORT', 8080)),
|
||||
'scheme' => env('REVERB_BROADCAST_SCHEME', 'http'),
|
||||
'useTLS' => env('REVERB_BROADCAST_SCHEME', 'http') === 'https',
|
||||
'path' => env('REVERB_SERVER_PATH', ''),
|
||||
],
|
||||
'client_options' => [
|
||||
|
||||
+4
-2
@@ -7,8 +7,10 @@
|
||||
| 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.
|
||||
|
|
||||
*/
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
'except' => [
|
||||
'telescope*',
|
||||
'horizon*',
|
||||
'panel/chat*',
|
||||
],
|
||||
|
||||
/*
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('channels', function (Blueprint $table) {
|
||||
$table->boolean('chatting')->default(false)->after('is_visible');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('channels', function (Blueprint $table) {
|
||||
$table->dropColumn('chatting');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
use App\Support\ChatSupport;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('conversations', function (Blueprint $table) {
|
||||
$table->foreignId('customer_id')->nullable()->after('id')->constrained('users')->nullOnDelete();
|
||||
$table->foreignId('channel_id')->nullable()->after('customer_id')->constrained('channels')->nullOnDelete();
|
||||
$table->string('thread_key')->nullable()->after('channel_id');
|
||||
});
|
||||
|
||||
$supportId = ChatSupport::userId();
|
||||
$claimed = [];
|
||||
|
||||
DB::table('conversations')->orderBy('id')->chunkById(100, function ($rows) use ($supportId, &$claimed) {
|
||||
foreach ($rows as $conversation) {
|
||||
$userIds = DB::table('conversation_user')
|
||||
->where('conversation_id', $conversation->id)
|
||||
->pluck('user_id');
|
||||
|
||||
if ($supportId === null || $userIds->count() !== 2 || ! $userIds->contains($supportId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$customerId = (int) $userIds->first(fn ($id) => (int) $id !== $supportId);
|
||||
$threadKey = 'admin';
|
||||
|
||||
if (isset($claimed[$customerId])) {
|
||||
$threadKey = 'admin-legacy-'.$conversation->id;
|
||||
} else {
|
||||
$claimed[$customerId] = true;
|
||||
}
|
||||
|
||||
DB::table('conversations')->where('id', $conversation->id)->update([
|
||||
'customer_id' => $customerId,
|
||||
'thread_key' => $threadKey,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
Schema::table('conversations', function (Blueprint $table) {
|
||||
$table->unique(['customer_id', 'thread_key']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('conversations', function (Blueprint $table) {
|
||||
$table->dropUnique(['customer_id', 'thread_key']);
|
||||
$table->dropConstrainedForeignId('channel_id');
|
||||
$table->dropConstrainedForeignId('customer_id');
|
||||
$table->dropColumn('thread_key');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
# Laravel Reverb + broadcasting auth for mm.com.tm
|
||||
#
|
||||
# Paste into the existing HTTPS server { } for mm.com.tm.
|
||||
#
|
||||
# 1) Laravel PHP prefixes MUST include `broadcasting`, otherwise
|
||||
# POST /broadcasting/auth is caught by `location /` and proxied to
|
||||
# the SPA on :4173 (404). Keep this in the same regex as api/panel:
|
||||
#
|
||||
# location ~ ^/(api|storage|panel|vendor|nova-api|nova-vendor|sanctum|nova|app-docs|broadcasting) {
|
||||
# try_files $uri $uri/ /index.php?$query_string;
|
||||
# }
|
||||
#
|
||||
# 2) Reverb (supervisor) stays on 127.0.0.1:8080.
|
||||
# Browsers connect to wss://mm.com.tm/app/...
|
||||
# Place `location /app` BEFORE the SPA `location /` catch-all.
|
||||
|
||||
location /app {
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header Scheme $scheme;
|
||||
proxy_set_header SERVER_PORT $server_port;
|
||||
proxy_set_header REMOTE_ADDR $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
|
||||
proxy_connect_timeout 60s;
|
||||
proxy_send_timeout 60s;
|
||||
proxy_read_timeout 86400s;
|
||||
proxy_buffering off;
|
||||
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
}
|
||||
Binary file not shown.
@@ -141,9 +141,23 @@ .mm-chat__item-preview {
|
||||
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 {
|
||||
|
||||
+313
-113
@@ -1,10 +1,13 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
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 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");
|
||||
@@ -18,52 +21,132 @@
|
||||
echo: null,
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// 1. NOTIFICATION MANAGER (Visual Toast UI)
|
||||
// =========================================================================
|
||||
const notifiedIds = new Set();
|
||||
let inboxReady = false;
|
||||
let toastContainer = null;
|
||||
|
||||
function initToastContainer() {
|
||||
if (toastContainer) return;
|
||||
toastContainer = document.createElement("div");
|
||||
toastContainer.className = "mm-chat-toast-container";
|
||||
toastContainer.style.cssText = `
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
width: 90%;
|
||||
max-width: 320px;
|
||||
`;
|
||||
|
||||
const chatPane = messagesEl ? messagesEl.parentElement : document.body;
|
||||
if (chatPane) {
|
||||
if (getComputedStyle(chatPane).position === "static") {
|
||||
chatPane.style.position = "relative";
|
||||
}
|
||||
chatPane.appendChild(toastContainer);
|
||||
}
|
||||
}
|
||||
|
||||
function showNotification(title, text, conversationId) {
|
||||
initToastContainer();
|
||||
const toast = document.createElement("div");
|
||||
toast.style.cssText = `
|
||||
background-color: #1e293b;
|
||||
color: #f8fafc;
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
|
||||
pointer-events: auto;
|
||||
cursor: pointer;
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
transition: all 0.3s ease;
|
||||
border: 1px solid #334155;
|
||||
`;
|
||||
|
||||
toast.innerHTML = `
|
||||
<div style="font-weight: 600; margin-bottom: 2px;">${title}</div>
|
||||
<div style="opacity: 0.8; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${text}</div>
|
||||
`;
|
||||
|
||||
toast.addEventListener("click", () => {
|
||||
if (conversationId) openConversation(conversationId);
|
||||
toast.remove();
|
||||
});
|
||||
|
||||
toastContainer.appendChild(toast);
|
||||
|
||||
// Animate in
|
||||
requestAnimationFrame(() => {
|
||||
toast.style.opacity = "1";
|
||||
toast.style.transform = "translateY(0)";
|
||||
});
|
||||
|
||||
// Auto-remove after 4 seconds
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = "0";
|
||||
toast.style.transform = "translateY(-10px)";
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
function notifyIncoming(message, conversation) {
|
||||
const key = messageKey(message);
|
||||
if (!key || notifiedIds.has(key)) return;
|
||||
notifiedIds.add(key);
|
||||
|
||||
// Skip toast if they are actively looking at this exact chat thread
|
||||
if (state.activeId === message.conversation_id && document.visibilityState === "visible") {
|
||||
return;
|
||||
}
|
||||
|
||||
const senderName = (conversation && conversation.user && conversation.user.name) || "New Message";
|
||||
showNotification(senderName, preview(message.body), message.conversation_id);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 2. CHAT HELPERS & RENDERING
|
||||
// =========================================================================
|
||||
function headers(json) {
|
||||
const next = {
|
||||
Accept: "application/json",
|
||||
"X-CSRF-TOKEN": config.csrf,
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
};
|
||||
|
||||
if (json) {
|
||||
next["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
if (!response.ok) throw new Error("Chat request failed");
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function formatTime(value) {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return "";
|
||||
}
|
||||
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()}`;
|
||||
return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${pad(date.getFullYear())}`;
|
||||
}
|
||||
|
||||
function preview(body) {
|
||||
if (!body) {
|
||||
return "";
|
||||
}
|
||||
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
|
||||
);
|
||||
const total = state.conversations.reduce((sum, conv) => sum + (conv.unread_count || 0), 0);
|
||||
unreadEl.textContent = String(total);
|
||||
unreadEl.hidden = total < 1;
|
||||
}
|
||||
@@ -76,20 +159,22 @@
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "mm-chat__item";
|
||||
if (conversation.id === state.activeId) {
|
||||
button.classList.add("is-active");
|
||||
}
|
||||
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) : "";
|
||||
const subtitle = conversation.channel && conversation.channel.name
|
||||
? conversation.channel.name
|
||||
: (config.strings && config.strings.support) || "Support";
|
||||
|
||||
button.innerHTML = `
|
||||
<div class="mm-chat__item-row">
|
||||
<span class="mm-chat__item-name"></span>
|
||||
<span class="mm-chat__item-time"></span>
|
||||
</div>
|
||||
<div class="mm-chat__item-sub"></div>
|
||||
${phone ? '<div class="mm-chat__item-phone"></div>' : ""}
|
||||
<div class="mm-chat__item-preview"></div>
|
||||
${conversation.unread_count ? '<span class="mm-chat__item-unread"></span>' : ""}
|
||||
@@ -97,27 +182,62 @@
|
||||
|
||||
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)
|
||||
: "";
|
||||
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
|
||||
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);
|
||||
}
|
||||
if (unread) unread.textContent = String(conversation.unread_count);
|
||||
|
||||
button.addEventListener("click", () => openConversation(conversation.id));
|
||||
listEl.appendChild(button);
|
||||
});
|
||||
|
||||
updateUnreadBadge();
|
||||
}
|
||||
|
||||
function isOutgoing(message, conversation) {
|
||||
if (!message) return false;
|
||||
if (message.tempId || String(message.id).startsWith("temp-")) return true;
|
||||
if (message.is_outgoing || message.sender_type === "admin" || message.sender_type === "operator") return true;
|
||||
|
||||
const otherId = conversation && conversation.user && conversation.user.id;
|
||||
return !otherId || message.user?.id !== otherId;
|
||||
if (!otherId) return true;
|
||||
return String(message.user?.id) !== String(otherId);
|
||||
}
|
||||
|
||||
function messageKey(message) {
|
||||
return message && message.id != null ? String(message.id) : "";
|
||||
}
|
||||
|
||||
function normalizeIncoming(payload) {
|
||||
if (!payload || typeof payload !== "object") return payload;
|
||||
if (payload.conversation_id && payload.id) return payload;
|
||||
if (payload.message && payload.message.id) return payload.message;
|
||||
if (payload.data && payload.data.id) return payload.data;
|
||||
return payload;
|
||||
}
|
||||
|
||||
// Double message fix core: explicitly handles temp messages
|
||||
function addOrUpdateMessage(message) {
|
||||
if (!message || !message.id) return false;
|
||||
|
||||
// 1. If it's a real server message, scrub out any optimistic duplicates based on body
|
||||
if (!String(message.id).startsWith("temp-")) {
|
||||
const tempIdx = state.messages.findIndex(m => m.tempId && m.body === message.body);
|
||||
if (tempIdx !== -1) {
|
||||
state.messages.splice(tempIdx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Add or update by ID
|
||||
const existingIdx = state.messages.findIndex(m => String(m.id) === String(message.id));
|
||||
if (existingIdx !== -1) {
|
||||
state.messages[existingIdx] = message;
|
||||
return false;
|
||||
}
|
||||
|
||||
state.messages.push(message);
|
||||
return true;
|
||||
}
|
||||
|
||||
function renderMessages() {
|
||||
@@ -134,14 +254,14 @@
|
||||
|
||||
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"
|
||||
}`;
|
||||
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);
|
||||
@@ -152,20 +272,34 @@
|
||||
|
||||
async function loadInbox() {
|
||||
const payload = await request(config.conversationsUrl, { headers: headers() });
|
||||
const previous = state.conversations;
|
||||
state.conversations = payload.data || [];
|
||||
|
||||
if (inboxReady) {
|
||||
state.conversations.forEach((conversation) => {
|
||||
const prev = previous.find((item) => item.id === conversation.id);
|
||||
const last = conversation.last_message;
|
||||
const lastChanged = Boolean(last) && messageKey(last) !== messageKey(prev && prev.last_message);
|
||||
|
||||
if (lastChanged && !isOutgoing(last, conversation)) {
|
||||
notifyIncoming(last, conversation);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
inboxReady = true;
|
||||
state.conversations.forEach((conversation) => {
|
||||
const key = messageKey(conversation.last_message);
|
||||
if (key) notifiedIds.add(key);
|
||||
});
|
||||
}
|
||||
renderInbox();
|
||||
}
|
||||
|
||||
async function loadMessages(conversationId, reset) {
|
||||
if (state.loadingMessages) {
|
||||
return;
|
||||
}
|
||||
if (state.loadingMessages) return;
|
||||
state.loadingMessages = true;
|
||||
|
||||
const url = reset
|
||||
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
|
||||
: state.nextPageUrl;
|
||||
|
||||
const url = reset ? `${config.messagesUrl}/${conversationId}/messages?perPage=50` : state.nextPageUrl;
|
||||
if (!url) {
|
||||
state.loadingMessages = false;
|
||||
return;
|
||||
@@ -177,159 +311,214 @@
|
||||
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
|
||||
|
||||
if (reset) {
|
||||
state.messages = items;
|
||||
state.messages = [];
|
||||
items.forEach(addOrUpdateMessage);
|
||||
} else {
|
||||
state.messages = items.concat(state.messages);
|
||||
const oldMessages = state.messages;
|
||||
state.messages = [];
|
||||
items.forEach(addOrUpdateMessage);
|
||||
oldMessages.forEach(addOrUpdateMessage);
|
||||
}
|
||||
|
||||
renderMessages();
|
||||
} finally {
|
||||
state.loadingMessages = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function markRead(conversationId) {
|
||||
async function markRead(conversationId, force) {
|
||||
if (!conversationId || conversationId !== state.activeId) return;
|
||||
|
||||
const conversation = state.conversations.find((item) => item.id === conversationId);
|
||||
if (!conversation || (!force && !conversation.unread_count)) 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;
|
||||
}
|
||||
|
||||
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;
|
||||
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);
|
||||
await markRead(conversationId, true);
|
||||
subscribeThread(conversationId);
|
||||
}
|
||||
|
||||
async function sendMessage(event) {
|
||||
event.preventDefault();
|
||||
|
||||
const body = (inputEl.value || "").trim();
|
||||
if (!body || !state.activeId) {
|
||||
return;
|
||||
}
|
||||
const conversation = state.conversations.find((item) => item.id === state.activeId);
|
||||
if (!body || !state.activeId || !conversation || conversation.can_reply === false) return;
|
||||
|
||||
sendEl.disabled = true;
|
||||
inputEl.value = "";
|
||||
|
||||
const tempId = "temp-" + Date.now();
|
||||
const optimisticMsg = {
|
||||
id: tempId,
|
||||
tempId: tempId,
|
||||
conversation_id: state.activeId,
|
||||
body: body,
|
||||
created_at: new Date().toISOString(),
|
||||
sender_type: "admin"
|
||||
};
|
||||
|
||||
addOrUpdateMessage(optimisticMsg);
|
||||
renderMessages();
|
||||
|
||||
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);
|
||||
const payload = await request(`${config.messagesUrl}/${state.activeId}/messages`, {
|
||||
method: "POST",
|
||||
headers: headers(true),
|
||||
body: JSON.stringify({ body }),
|
||||
});
|
||||
|
||||
const serverMsg = payload.data;
|
||||
if (serverMsg && serverMsg.id) {
|
||||
notifiedIds.add(messageKey(serverMsg)); // Prevent self-notifying
|
||||
|
||||
// **CRITICAL FIX**: Explicitly delete the temporary message by its exact tempId
|
||||
state.messages = state.messages.filter(m => m.tempId !== tempId);
|
||||
|
||||
addOrUpdateMessage(serverMsg);
|
||||
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||
renderMessages();
|
||||
}
|
||||
inputEl.value = "";
|
||||
await loadInbox();
|
||||
} catch (err) {
|
||||
// Revert message on network failure
|
||||
state.messages = state.messages.filter(m => m.tempId !== tempId);
|
||||
renderMessages();
|
||||
} finally {
|
||||
sendEl.disabled = false;
|
||||
inputEl.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function upsertIncoming(message) {
|
||||
if (!message || !message.conversation_id) {
|
||||
return;
|
||||
function upsertIncoming(payload) {
|
||||
const message = normalizeIncoming(payload);
|
||||
if (!message || !message.conversation_id) return;
|
||||
|
||||
const conversation = state.conversations.find((item) => item.id === message.conversation_id);
|
||||
|
||||
if (!isOutgoing(message, conversation)) {
|
||||
notifyIncoming(message, conversation);
|
||||
}
|
||||
|
||||
if (state.activeId === message.conversation_id) {
|
||||
if (!state.messages.some((item) => item.id === message.id)) {
|
||||
state.messages.push(message);
|
||||
renderMessages();
|
||||
}
|
||||
markRead(message.conversation_id);
|
||||
addOrUpdateMessage(message);
|
||||
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||
renderMessages();
|
||||
markRead(message.conversation_id, true);
|
||||
}
|
||||
|
||||
loadInbox();
|
||||
}
|
||||
|
||||
function subscribeThread(conversationId) {
|
||||
if (!state.echo) {
|
||||
return;
|
||||
}
|
||||
if (!state.echo) return;
|
||||
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
|
||||
}
|
||||
|
||||
function isLoopbackHost(host) {
|
||||
return !host || host === "127.0.0.1" || host === "localhost" || host === "0.0.0.0" || host === "::1";
|
||||
}
|
||||
|
||||
function echoEndpoint(pusher) {
|
||||
const pageHost = window.location.hostname;
|
||||
if (!isLoopbackHost(pageHost)) {
|
||||
const https = window.location.protocol === "https:";
|
||||
return { host: pageHost, port: https ? 443 : 80, forceTLS: https };
|
||||
}
|
||||
return {
|
||||
host: pusher.host || "127.0.0.1",
|
||||
port: pusher.port || 8080,
|
||||
forceTLS: (pusher.scheme || "http") === "https",
|
||||
};
|
||||
}
|
||||
|
||||
function bootEcho() {
|
||||
const pusher = config.pusher || {};
|
||||
const EchoClass = window.Echo;
|
||||
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) {
|
||||
return;
|
||||
}
|
||||
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) return;
|
||||
|
||||
const scheme = pusher.scheme || "https";
|
||||
const forceTLS = scheme === "https";
|
||||
const endpoint = echoEndpoint(pusher);
|
||||
|
||||
try {
|
||||
state.echo = new EchoClass({
|
||||
broadcaster: "reverb",
|
||||
key: pusher.key,
|
||||
wsHost: pusher.host || undefined,
|
||||
wsPort: pusher.port || undefined,
|
||||
wssPort: pusher.port || undefined,
|
||||
forceTLS,
|
||||
wsHost: endpoint.host,
|
||||
wsPort: endpoint.port,
|
||||
wssPort: endpoint.port,
|
||||
forceTLS: endpoint.forceTLS,
|
||||
enabledTransports: ["ws", "wss"],
|
||||
disableStats: true,
|
||||
cluster: "mt1",
|
||||
authEndpoint: config.broadcastAuth,
|
||||
csrfToken: config.csrf,
|
||||
authEndpoint: config.broadcastAuthPath || config.broadcastAuth || "/panel/broadcasting/auth",
|
||||
auth: {
|
||||
headers: {
|
||||
"X-CSRF-TOKEN": config.csrf,
|
||||
Accept: "application/json",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async function mergeActiveMessages() {
|
||||
if (!state.activeId || state.loadingMessages) {
|
||||
return;
|
||||
}
|
||||
if (!state.activeId || state.loadingMessages) return false;
|
||||
|
||||
const payload = await request(
|
||||
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
|
||||
{ headers: headers() }
|
||||
);
|
||||
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);
|
||||
const isNew = addOrUpdateMessage(message);
|
||||
if (isNew) {
|
||||
added = true;
|
||||
const conversation = state.conversations.find((i) => i.id === state.activeId);
|
||||
if (!isOutgoing(message, conversation)) {
|
||||
notifyIncoming(message, conversation);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (added) {
|
||||
state.messages.sort(
|
||||
(a, b) => new Date(a.created_at) - new Date(b.created_at)
|
||||
);
|
||||
state.messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
|
||||
renderMessages();
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
// Event Listeners
|
||||
formEl.addEventListener("submit", sendMessage);
|
||||
inputEl.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
@@ -347,13 +536,24 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Initialize
|
||||
loadInbox();
|
||||
bootEcho();
|
||||
|
||||
setInterval(() => {
|
||||
loadInbox().then(() => {
|
||||
if (state.activeId) {
|
||||
mergeActiveMessages();
|
||||
loadInbox().then(async () => {
|
||||
if (!state.activeId) return;
|
||||
const added = await mergeActiveMessages();
|
||||
const conversation = state.conversations.find((item) => item.id === state.activeId);
|
||||
if (added || (conversation && conversation.unread_count > 0)) {
|
||||
await markRead(state.activeId, true);
|
||||
}
|
||||
});
|
||||
}, 4000);
|
||||
})();
|
||||
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible" && state.activeId) {
|
||||
markRead(state.activeId);
|
||||
}
|
||||
});
|
||||
})();
|
||||
File diff suppressed because it is too large.
Load diff
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/*!
|
||||
* Pusher JavaScript Library v8.4.0
|
||||
* https://pusher.com/
|
||||
*
|
||||
* Copyright 2020, Pusher
|
||||
* Released under the MIT licence.
|
||||
*/
|
||||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pusher=e():t.Pusher=e()}(window,(function(){return function(t){var e={};function n(i){if(e[i])return e[i].exports;var r=e[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=t,n.c=e,n.d=function(t,e,i){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var r in t)n.d(i,r,function(e){return t[e]}.bind(null,r));return i},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=2)}([function(t,e,n){"use strict";var i,r=this&&this.__extends||(i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)},function(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var s=function(){function t(t){void 0===t&&(t="="),this._paddingCharacter=t}return t.prototype.encodedLength=function(t){return this._paddingCharacter?(t+2)/3*4|0:(8*t+5)/6|0},t.prototype.encode=function(t){for(var e="",n=0;n<t.length-2;n+=3){var i=t[n]<<16|t[n+1]<<8|t[n+2];e+=this._encodeByte(i>>>18&63),e+=this._encodeByte(i>>>12&63),e+=this._encodeByte(i>>>6&63),e+=this._encodeByte(i>>>0&63)}var r=t.length-n;if(r>0){i=t[n]<<16|(2===r?t[n+1]<<8:0);e+=this._encodeByte(i>>>18&63),e+=this._encodeByte(i>>>12&63),e+=2===r?this._encodeByte(i>>>6&63):this._paddingCharacter||"",e+=this._paddingCharacter||""}return e},t.prototype.maxDecodedLength=function(t){return this._paddingCharacter?t/4*3|0:(6*t+7)/8|0},t.prototype.decodedLength=function(t){return this.maxDecodedLength(t.length-this._getPaddingLength(t))},t.prototype.decode=function(t){if(0===t.length)return new Uint8Array(0);for(var e=this._getPaddingLength(t),n=t.length-e,i=new Uint8Array(this.maxDecodedLength(n)),r=0,s=0,o=0,a=0,c=0,h=0,u=0;s<n-4;s+=4)a=this._decodeChar(t.charCodeAt(s+0)),c=this._decodeChar(t.charCodeAt(s+1)),h=this._decodeChar(t.charCodeAt(s+2)),u=this._decodeChar(t.charCodeAt(s+3)),i[r++]=a<<2|c>>>4,i[r++]=c<<4|h>>>2,i[r++]=h<<6|u,o|=256&a,o|=256&c,o|=256&h,o|=256&u;if(s<n-1&&(a=this._decodeChar(t.charCodeAt(s)),c=this._decodeChar(t.charCodeAt(s+1)),i[r++]=a<<2|c>>>4,o|=256&a,o|=256&c),s<n-2&&(h=this._decodeChar(t.charCodeAt(s+2)),i[r++]=c<<4|h>>>2,o|=256&h),s<n-3&&(u=this._decodeChar(t.charCodeAt(s+3)),i[r++]=h<<6|u,o|=256&u),0!==o)throw new Error("Base64Coder: incorrect characters for decoding");return i},t.prototype._encodeByte=function(t){var e=t;return e+=65,e+=25-t>>>8&6,e+=51-t>>>8&-75,e+=61-t>>>8&-15,e+=62-t>>>8&3,String.fromCharCode(e)},t.prototype._decodeChar=function(t){var e=256;return e+=(42-t&t-44)>>>8&-256+t-43+62,e+=(46-t&t-48)>>>8&-256+t-47+63,e+=(47-t&t-58)>>>8&-256+t-48+52,e+=(64-t&t-91)>>>8&-256+t-65+0,e+=(96-t&t-123)>>>8&-256+t-97+26},t.prototype._getPaddingLength=function(t){var e=0;if(this._paddingCharacter){for(var n=t.length-1;n>=0&&t[n]===this._paddingCharacter;n--)e++;if(t.length<4||e>2)throw new Error("Base64Coder: incorrect padding")}return e},t}();e.Coder=s;var o=new s;e.encode=function(t){return o.encode(t)},e.decode=function(t){return o.decode(t)};var a=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return r(e,t),e.prototype._encodeByte=function(t){var e=t;return e+=65,e+=25-t>>>8&6,e+=51-t>>>8&-75,e+=61-t>>>8&-13,e+=62-t>>>8&49,String.fromCharCode(e)},e.prototype._decodeChar=function(t){var e=256;return e+=(44-t&t-46)>>>8&-256+t-45+62,e+=(94-t&t-96)>>>8&-256+t-95+63,e+=(47-t&t-58)>>>8&-256+t-48+52,e+=(64-t&t-91)>>>8&-256+t-65+0,e+=(96-t&t-123)>>>8&-256+t-97+26},e}(s);e.URLSafeCoder=a;var c=new a;e.encodeURLSafe=function(t){return c.encode(t)},e.decodeURLSafe=function(t){return c.decode(t)},e.encodedLength=function(t){return o.encodedLength(t)},e.maxDecodedLength=function(t){return o.maxDecodedLength(t)},e.decodedLength=function(t){return o.decodedLength(t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i="utf8: invalid source encoding";function r(t){for(var e=0,n=0;n<t.length;n++){var i=t.charCodeAt(n);if(i<128)e+=1;else if(i<2048)e+=2;else if(i<55296)e+=3;else{if(!(i<=57343))throw new Error("utf8: invalid string");if(n>=t.length-1)throw new Error("utf8: invalid string");n++,e+=4}}return e}e.encode=function(t){for(var e=newLine truncated
|
||||
//# sourceMappingURL=pusher.min.js.map
|
||||
@@ -6,7 +6,7 @@
|
||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>{{ __('Chat') }} — {{ config('nova.name', config('app.name')) }}</title>
|
||||
<link rel="stylesheet" href="{{ asset('assets/panel/css/chat.css') }}">
|
||||
<style>{!! $chatCss !!}</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="mm-chat" id="mm-chat">
|
||||
@@ -26,6 +26,7 @@
|
||||
<section class="mm-chat__thread">
|
||||
<div class="mm-chat__thread-head" id="mm-chat-thread-head">{{ __('Select a conversation') }}</div>
|
||||
<div class="mm-chat__messages" id="mm-chat-messages"></div>
|
||||
<p class="mm-chat__view-only" id="mm-chat-view-only" hidden>{{ __('View only — the store owner replies here.') }}</p>
|
||||
<form class="mm-chat__composer" id="mm-chat-form" hidden>
|
||||
<textarea
|
||||
id="mm-chat-input"
|
||||
@@ -40,24 +41,27 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<audio id="mm-chat-sound" src="/assets/panel/audio/sound.mp3" preload="auto" playsinline></audio>
|
||||
<script>
|
||||
window.MM_CHAT = {
|
||||
conversationsUrl: @json(url('/panel/chat/conversations')),
|
||||
messagesUrl: @json(url('/panel/chat/conversations')),
|
||||
csrf: @json(csrf_token()),
|
||||
broadcastAuth: @json(url('/panel/broadcasting/auth')),
|
||||
broadcastAuthPath: '/panel/broadcasting/auth',
|
||||
pusher: @json($pusher),
|
||||
inboxChannel: @json($inboxChannel),
|
||||
strings: {
|
||||
select: @json(__('Select a conversation')),
|
||||
noMessages: @json(__('No messages yet.')),
|
||||
you: @json(__('You')),
|
||||
support: @json(__('Support')),
|
||||
viewOnly: @json(__('View only — the store owner replies here.')),
|
||||
},
|
||||
};
|
||||
</script>
|
||||
@if (! empty($pusher['key']))
|
||||
<script src="https://js.pusher.com/8.4.0/pusher.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/laravel-echo@1.16.1/dist/echo.iife.js"></script>
|
||||
@endif
|
||||
<script src="{{ asset('assets/panel/js/chat.js') }}"></script>
|
||||
@foreach ($chatScripts as $script)
|
||||
<script>{!! $script !!}</script>
|
||||
@endforeach
|
||||
</body>
|
||||
</html>
|
||||
@@ -115,6 +115,8 @@
|
||||
|
||||
// Chat...
|
||||
Route::get('chat/conversations', [ChatController::class, 'conversations']);
|
||||
Route::get('chat/targets', [ChatController::class, 'targets']);
|
||||
Route::post('chat/start-target', [ChatController::class, 'startTarget']);
|
||||
Route::get('chat/support', [ChatController::class, 'showSupport']);
|
||||
Route::post('chat/support', [ChatController::class, 'support']);
|
||||
Route::get('chat/contacts', [ChatController::class, 'contacts']);
|
||||
|
||||
+23
-5
@@ -15,7 +15,30 @@
|
||||
|
|
||||
*/
|
||||
|
||||
Broadcast::channel('chat.support', function ($user) {
|
||||
return ChatSupport::isOperator($user);
|
||||
});
|
||||
|
||||
Broadcast::channel('chat.inbox.{userId}', function ($user, $userId) {
|
||||
if (! ctype_digit((string) $userId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) $user->id === (int) $userId
|
||||
&& ChatSupport::canAccessPanelChat($user);
|
||||
});
|
||||
|
||||
Broadcast::channel('chat.{conversationId}', function ($user, $conversationId) {
|
||||
if ($conversationId === 'support') {
|
||||
return ChatSupport::isOperator($user);
|
||||
}
|
||||
|
||||
if (! ctype_digit((string) $conversationId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$conversationId = (int) $conversationId;
|
||||
|
||||
$isParticipant = DB::table('conversation_user')
|
||||
->where('conversation_id', $conversationId)
|
||||
->where('user_id', $user->id)
|
||||
@@ -25,10 +48,5 @@
|
||||
return true;
|
||||
}
|
||||
|
||||
return ChatSupport::isOperator($user)
|
||||
&& ChatSupport::conversationIncludesSupport((int) $conversationId);
|
||||
});
|
||||
|
||||
Broadcast::channel('chat.support', function ($user) {
|
||||
return ChatSupport::isOperator($user);
|
||||
});
|
||||
+1
-3
@@ -4,13 +4,11 @@
|
||||
use App\Http\Controllers\OnlinePaymentController;
|
||||
use App\Http\Middleware\EnsureChatOperator;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Laravel\Nova\Http\Middleware\Authenticate as NovaAuthenticate;
|
||||
use Laravel\Nova\Http\Middleware\Authorize as NovaAuthorize;
|
||||
|
||||
Route::view('/login', 'wip')->name('login');
|
||||
Route::get('api/online-payment-store', [OnlinePaymentController::class, 'index'])->name('online-payment-store');
|
||||
|
||||
Route::middleware([NovaAuthenticate::class, NovaAuthorize::class, EnsureChatOperator::class])
|
||||
Route::middleware(['auth', EnsureChatOperator::class])
|
||||
->prefix('panel/chat')
|
||||
->name('nova.chat.')
|
||||
->group(function () {
|
||||
|
||||
Reference in new issue
Block a user