Deploy: 2026-05-21 15:33:14
This commit is contained in:
89
backend/app/Models/WhatsAppSession.php
Normal file
89
backend/app/Models/WhatsAppSession.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\Security;
|
||||
|
||||
/**
|
||||
* WhatsAppSession Model
|
||||
* Handles the whatsapp_sessions table with encryption for phone and QR code.
|
||||
*/
|
||||
class WhatsAppSession extends BaseModel
|
||||
{
|
||||
protected string $table = 'whatsapp_sessions';
|
||||
|
||||
/**
|
||||
* Get the session for a specific company
|
||||
*/
|
||||
public function findByCompany(int $companyId)
|
||||
{
|
||||
$session = $this->db->query(
|
||||
"SELECT * FROM {$this->table} WHERE company_id = ? LIMIT 1",
|
||||
[$companyId]
|
||||
)->fetch();
|
||||
|
||||
if ($session) {
|
||||
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
|
||||
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
|
||||
}
|
||||
|
||||
return $session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a session by session_key (used by webhooks)
|
||||
*/
|
||||
public function findBySessionKey(string $sessionKey)
|
||||
{
|
||||
$session = $this->db->query(
|
||||
"SELECT * FROM {$this->table} WHERE session_key = ? LIMIT 1",
|
||||
[$sessionKey]
|
||||
)->fetch();
|
||||
|
||||
if ($session) {
|
||||
$session['phone'] = $session['phone'] ? Security::decrypt($session['phone']) : null;
|
||||
$session['qr_code'] = $session['qr_code'] ? Security::decrypt($session['qr_code']) : null;
|
||||
}
|
||||
|
||||
return $session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or retrieve a new session for a company
|
||||
*/
|
||||
public function findOrCreate(int $companyId, string $name = 'Main WhatsApp')
|
||||
{
|
||||
$session = $this->findByCompany($companyId);
|
||||
if ($session) {
|
||||
return $session;
|
||||
}
|
||||
|
||||
$sessionKey = 'cmp_' . $companyId . '_' . bin2hex(random_bytes(4));
|
||||
|
||||
$id = $this->create([
|
||||
'company_id' => $companyId,
|
||||
'name' => $name,
|
||||
'session_key' => $sessionKey,
|
||||
'status' => 'disconnected'
|
||||
]);
|
||||
|
||||
return $this->findByCompany($companyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update session state securely
|
||||
*/
|
||||
public function updateState(int $id, array $data)
|
||||
{
|
||||
if (isset($data['phone'])) {
|
||||
$data['phone_hash'] = Security::blindIndex($data['phone']);
|
||||
$data['phone'] = Security::encrypt($data['phone']);
|
||||
}
|
||||
|
||||
if (isset($data['qr_code'])) {
|
||||
$data['qr_code'] = Security::encrypt($data['qr_code']);
|
||||
}
|
||||
|
||||
return $this->update($id, $data);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user