chartboard/app/Models/DashboardModel.php
2026-03-30 09:51:33 +05:30

90 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
class DashboardModel extends Model
{
protected $table = 'dashboards';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = true;
protected $protectFields = true;
protected $allowedFields = [
'workspace_id',
'name',
'description',
'slug',
'layout_config',
'filters_config',
'refresh_interval',
'theme',
'is_public',
'public_token',
'public_password',
'public_expires_at',
'is_pinned',
'created_by',
];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
'workspace_id' => 'required|integer',
'name' => 'required|min_length[2]|max_length[200]',
'slug' => 'required|min_length[1]|max_length[220]',
'theme' => 'permit_empty|in_list[light,dark,system]',
];
public function forWorkspace(int $workspaceId): array
{
return $this->select('dashboards.*')
->select('(SELECT COUNT(*) FROM dashboard_widgets WHERE dashboard_widgets.dashboard_id = dashboards.id) AS widget_count', false)
->where('dashboards.workspace_id', $workspaceId)
->orderBy('dashboards.is_pinned', 'DESC')
->orderBy('dashboards.updated_at', 'DESC')
->findAll();
}
public function findForWorkspace(int $id, int $workspaceId): ?array
{
$row = $this->where('workspace_id', $workspaceId)->find($id);
return $row ?: null;
}
public function generateUniqueSlug(int $workspaceId, string $name): string
{
$slug = url_title($name, '-', true);
if ($slug === '') {
$slug = 'dashboard';
}
$base = $slug;
$n = 2;
while ($this->where('workspace_id', $workspaceId)->where('slug', $slug)->first()) {
$slug = $base . '-' . $n;
$n++;
}
return $slug;
}
/**
* URL-safe random token for public sharing (future use).
*/
public function generatePublicToken(): string
{
return bin2hex(random_bytes(24));
}
}