Files
backend-mm/app/Models/Chat/Conversation.php

265 lines
7.7 KiB
PHP

<?php
namespace App\Models\Chat;
use App\Models\Ecommerce\Channel\Channel;
use App\Models\User;
use App\Support\ChatSupport;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
class Conversation extends Model
{
use HasFactory;
public const THREAD_ADMIN = 'admin';
/**
* @var array<int, string>
*/
protected $fillable = [
'customer_id',
'channel_id',
'thread_key',
];
public static function threadKeyForChannel(int $channelId): string
{
return 'channel:'.$channelId;
}
/**
* Find a 1:1 conversation between two users.
*/
public static function findOneToOne(int $userId, int $otherUserId): ?self
{
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;
}
$conversation = static::create();
$conversation->users()->attach([$userId, $otherUserId]);
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', 'channel'])
->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 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', 'channel'])
->loadCount([
'messages as unread_count' => fn ($query) => $query
->where('user_id', '!=', $viewer->id)
->whereNull('seen_at'),
]);
}
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);
}
public function messages(): HasMany
{
return $this->hasMany(Message::class);
}
public function latestMessage(): HasOne
{
return $this->hasOne(Message::class)->latestOfMany();
}
public function hasParticipant(User $user): bool
{
return $this->users()->where('users.id', $user->id)->exists();
}
/**
* @return \Illuminate\Database\Eloquent\Builder<static>
*/
private static function panelInboxQuery()
{
return static::query()
->with(['customer', 'channel', 'users', 'latestMessage.user'])
->withCount([
'messages as unread_count' => fn ($query) => $query
->whereColumn('messages.user_id', 'conversations.customer_id')
->whereNull('seen_at'),
])
->withMax('messages', 'created_at')
->orderByDesc('messages_max_created_at');
}
private static function locateOrCreate(User $customer, User $counterpart, string $threadKey, ?Channel $channel): self
{
$existing = static::query()
->where('customer_id', $customer->id)
->where('thread_key', $threadKey)
->first();
if ($existing) {
return $existing;
}
try {
return DB::transaction(function () use ($customer, $counterpart, $threadKey, $channel) {
$conversation = static::query()->create([
'customer_id' => $customer->id,
'channel_id' => $channel?->id,
'thread_key' => $threadKey,
]);
$conversation->users()->attach([$customer->id, $counterpart->id]);
return $conversation;
});
} catch (QueryException $exception) {
if (! static::isUniqueViolation($exception)) {
throw $exception;
}
$conversation = static::query()
->where('customer_id', $customer->id)
->where('thread_key', $threadKey)
->first();
if ($conversation) {
return $conversation;
}
throw $exception;
}
}
private static function isUniqueViolation(QueryException $exception): bool
{
$sqlState = (string) $exception->errorInfo[0];
return in_array($sqlState, ['23000', '23505'], true)
|| str_contains(strtolower($exception->getMessage()), 'unique');
}
}