added migration seeders models and test script

This commit is contained in:
Jürg Hallenbarter
2026-04-29 14:20:41 +02:00
parent b2dab73f17
commit deba81fadb
38 changed files with 3389 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ActivityLogModel extends Model
{
protected $table = 'activity_logs';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'action',
'entity_type',
'entity_id',
'details',
'ip_address',
'user_agent',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'action' => 'required|max_length[255]',
];
// Log an activity
public function logActivity($data)
{
// Disable events to prevent any recursive logging
$this->skipEvents();
if (!isset($data['id'])) {
$data['id'] = $this->generateUuid();
}
if (!isset($data['created_at'])) {
$data['created_at'] = date('Y-m-d H:i:s');
}
$result = $this->insert($data);
// Re-enable events
$this->skipEvents(false);
return $result;
}
// Get logs by user
public function getByUser($userId, $limit = 50)
{
return $this->where('user_id', $userId)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get logs by entity
public function getByEntity($entityType, $entityId, $limit = 50)
{
return $this->where('entity_type', $entityType)
->where('entity_id', $entityId)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get logs by action
public function getByAction($action, $limit = 50)
{
return $this->where('action', $action)
->orderBy('created_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

105
app/Models/AiChatModel.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiChatModel extends Model
{
protected $table = 'ai_chats';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'provider_id',
'model_used',
'system_prompt',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
];
// Get chats by user
public function getByUser($userId, $limit = 50)
{
return $this->where('user_id', $userId)
->orderBy('updated_at', 'DESC')
->limit($limit)
->get()
->getResultArray();
}
// Get chat with message count
public function getWithMessageCount($chatId)
{
$chat = $this->find($chatId);
if ($chat) {
$messageModel = new AiMessageModel();
$chat['message_count'] = $messageModel->where('chat_id', $chatId)->countAllResults();
}
return $chat;
}
// Get all chats by user with message counts
public function getByUserWithMessageCounts($userId)
{
$chats = $this->getByUser($userId);
$messageModel = new AiMessageModel();
foreach ($chats as &$chat) {
$chat['message_count'] = $messageModel->where('chat_id', $chat['id'])->countAllResults();
}
return $chats;
}
// Get chat with provider info
public function getWithProvider($chatId)
{
return $this->select('ai_chats.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'ai_chats.provider_id = ai_providers.id', 'left')
->where('ai_chats.id', $chatId)
->get()
->getRowArray();
}
// Update chat title
public function updateTitle($chatId, $title)
{
return $this->update($chatId, ['title' => $title]);
}
// Create new chat
public function createChat($userId, $data = [])
{
$data['id'] = $this->generateUuid();
$data['user_id'] = $userId;
$data['created_at'] = date('Y-m-d H:i:s');
$data['updated_at'] = date('Y-m-d H:i:s');
return $this->insert($data);
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiMessageModel extends Model
{
protected $table = 'ai_messages';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'chat_id',
'role',
'content',
'tokens_used',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'chat_id' => 'required',
'role' => 'required|in_list[user,assistant,system]',
'content' => 'required',
];
// Get messages by chat
public function getByChat($chatId)
{
return $this->where('chat_id', $chatId)
->orderBy('created_at', 'ASC')
->get()
->getResultArray();
}
// Add message to chat
public function addMessage($chatId, $role, $content, $tokensUsed = null)
{
return $this->insert([
'id' => $this->generateUuid(),
'chat_id' => $chatId,
'role' => $role,
'content' => $content,
'tokens_used' => $tokensUsed,
'created_at' => date('Y-m-d H:i:s'),
]);
}
// Get last message from chat
public function getLastMessage($chatId)
{
return $this->where('chat_id', $chatId)
->orderBy('created_at', 'DESC')
->limit(1)
->get()
->getRowArray();
}
// Delete all messages from chat
public function deleteByChat($chatId)
{
return $this->where('chat_id', $chatId)->delete();
}
// Get total tokens used by chat
public function getTotalTokens($chatId)
{
$result = $this->selectSum('tokens_used')
->where('chat_id', $chatId)
->get()
->getRowArray();
return $result ? (int) $result['tokens_used'] : 0;
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class AiProviderModel extends Model
{
protected $table = 'ai_providers';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'name',
'display_name',
'base_url',
'is_builtin',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'name' => 'required|max_length[100]|is_unique[ai_providers.name]',
'display_name' => 'required|max_length[255]',
];
// Get builtin providers only
public function getBuiltinProviders()
{
return $this->where('is_builtin', true)
->orderBy('name', 'ASC')
->get()
->getResultArray();
}
// Get custom providers only
public function getCustomProviders()
{
return $this->where('is_builtin', false)
->orderBy('name', 'ASC')
->get()
->getResultArray();
}
// Get provider by name
public function getByName($name)
{
return $this->where('name', $name)
->get()
->getRowArray();
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class CategoryModel extends Model
{
use LoggableTrait;
protected $table = 'categories';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'name',
'color',
'favorite',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'user_id' => 'required',
'name' => 'required|max_length[255]',
];
protected function getEntityType(): string
{
return 'category';
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace App\Models;
trait LoggableTrait
{
/**
* Log activity after insert
*/
protected function afterInsert(array $data)
{
try {
$this->logActivity('created', $data);
} catch (\Exception $e) {
// Silently fail to avoid breaking the main operation
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity after update
*/
protected function afterUpdate(array $data)
{
try {
$this->logActivity('updated', $data);
} catch (\Exception $e) {
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity after delete
*/
protected function afterDelete(array $data)
{
try {
$this->logActivity('deleted', $data);
} catch (\Exception $e) {
log_message('error', 'Failed to log activity: ' . $e->getMessage());
}
return $data;
}
/**
* Log activity to activity_logs table
*/
protected function logActivity($action, $data)
{
$activityLogModel = new ActivityLogModel();
$entityType = $this->getEntityType();
$entityId = $data['id'] ?? $data[$this->primaryKey] ?? null;
$userId = $data['user_id'] ?? null;
// Try to get user from session if not in data
if ($userId === null && function_exists('session')) {
$userId = session()->get('user_id');
}
$logData = [
'user_id' => $userId,
'action' => $this->getActionName($action, $entityType),
'entity_type' => $entityType,
'entity_id' => $entityId,
'details' => json_encode($this->getLogDetails($action, $data)),
'ip_address' => $this->getClientIp(),
'user_agent' => $this->getUserAgent(),
];
$activityLogModel->logActivity($logData);
}
/**
* Get entity type based on table name
*/
protected function getEntityType(): string
{
$table = $this->table;
// Remove plural 's' if present
return rtrim($table, 's');
}
/**
* Get formatted action name
*/
protected function getActionName($action, $entityType): string
{
return "{$entityType}_{$action}";
}
/**
* Get log details (can be overridden in models)
*/
protected function getLogDetails($action, $data): array
{
$details = [
'action' => $action,
];
// Add relevant fields based on entity type
if (isset($data['title'])) {
$details['title'] = $data['title'];
}
if (isset($data['name'])) {
$details['name'] = $data['name'];
}
if (isset($data['email'])) {
$details['email'] = $data['email'];
}
return $details;
}
/**
* Get client IP address
*/
protected function getClientIp(): ?string
{
try {
$request = \Config\Services::request();
return $request->getIPAddress();
} catch (\Exception $e) {
return 'CLI';
}
}
/**
* Get user agent
*/
protected function getUserAgent(): ?string
{
try {
$request = \Config\Services::request();
return $request->getUserAgent()->toString();
} catch (\Exception $e) {
return 'CLI/Script';
}
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class MarketplaceThemeModel extends Model
{
protected $table = 'marketplace_themes';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'name',
'display_name',
'description',
'author',
'version',
'thumbnail_url',
'download_url',
'price',
'is_published',
'metadata',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'name' => 'required|max_length[255]|is_unique[marketplace_themes.name]',
'display_name' => 'required|max_length[255]',
'download_url' => 'required',
];
// Get published themes only
public function getPublished()
{
return $this->where('is_published', true)
->orderBy('created_at', 'DESC')
->get()
->getResultArray();
}
// Get free themes
public function getFreeThemes()
{
return $this->where('price', 0)
->where('is_published', true)
->orderBy('created_at', 'DESC')
->get()
->getResultArray();
}
// Get paid themes
public function getPaidThemes()
{
return $this->where('price >', 0)
->where('is_published', true)
->orderBy('price', 'ASC')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
use LoggableTrait;
protected $table = 'projects';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'name',
'description',
'color',
'created_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = null;
protected $validationRules = [
'user_id' => 'required',
'name' => 'required|max_length[255]',
];
protected function getEntityType(): string
{
return 'project';
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class RecurringTaskCategoryModel extends Model
{
protected $table = 'recurring_task_categories';
protected $primaryKey = 'recurring_task_id'; // Composite primary key
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'recurring_task_id',
'category_id',
];
protected $useTimestamps = false;
// Add category to recurring task
public function addCategoryToTask($taskId, $categoryId)
{
return $this->insert([
'recurring_task_id' => $taskId,
'category_id' => $categoryId,
]);
}
// Remove category from recurring task
public function removeCategoryFromTask($taskId, $categoryId)
{
return $this->where('recurring_task_id', $taskId)
->where('category_id', $categoryId)
->delete();
}
// Get categories for a recurring task
public function getCategoriesForTask($taskId)
{
return $this->select('categories.*')
->join('categories', 'recurring_task_categories.category_id = categories.id')
->where('recurring_task_categories.recurring_task_id', $taskId)
->get()
->getResultArray();
}
// Get recurring tasks for a category
public function getTasksForCategory($categoryId)
{
return $this->select('recurring_tasks.*')
->join('recurring_tasks', 'recurring_task_categories.recurring_task_id = recurring_tasks.id')
->where('recurring_task_categories.category_id', $categoryId)
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class RecurringTaskModel extends Model
{
use LoggableTrait;
protected $table = 'recurring_tasks';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'description',
'schedule',
'custom_days',
'favorite',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
'title' => 'required|max_length[255]',
'schedule' => 'required|in_list[daily,weekly,monthly,custom]',
];
protected function getEntityType(): string
{
return 'recurring_task';
}
// Get recurring tasks with categories
public function getWithCategories($taskId = null)
{
$builder = $this->select('recurring_tasks.*, GROUP_CONCAT(categories.name) as category_names')
->join('recurring_task_categories', 'recurring_tasks.id = recurring_task_categories.recurring_task_id', 'left')
->join('categories', 'recurring_task_categories.category_id = categories.id', 'left')
->groupBy('recurring_tasks.id');
if ($taskId) {
$builder->where('recurring_tasks.id', $taskId);
}
return $builder->get()->getResultArray();
}
// Get recurring tasks by user with categories
public function getByUserWithCategories($userId)
{
return $this->select('recurring_tasks.*, GROUP_CONCAT(categories.name) as category_names')
->join('recurring_task_categories', 'recurring_tasks.id = recurring_task_categories.recurring_task_id', 'left')
->join('categories', 'recurring_task_categories.category_id = categories.id', 'left')
->where('recurring_tasks.user_id', $userId)
->groupBy('recurring_tasks.id')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class TodoCategoryModel extends Model
{
protected $table = 'todo_categories';
protected $primaryKey = 'todo_id'; // Composite primary key
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'todo_id',
'category_id',
];
protected $useTimestamps = false;
// Add category to todo
public function addCategoryToTodo($todoId, $categoryId)
{
return $this->insert([
'todo_id' => $todoId,
'category_id' => $categoryId,
]);
}
// Remove category from todo
public function removeCategoryFromTodo($todoId, $categoryId)
{
return $this->where('todo_id', $todoId)
->where('category_id', $categoryId)
->delete();
}
// Get categories for a todo
public function getCategoriesForTodo($todoId)
{
return $this->select('categories.*')
->join('categories', 'todo_categories.category_id = categories.id')
->where('todo_categories.todo_id', $todoId)
->get()
->getResultArray();
}
// Get todos for a category
public function getTodosForCategory($categoryId)
{
return $this->select('todos.*')
->join('todos', 'todo_categories.todo_id = todos.id')
->where('todo_categories.category_id', $categoryId)
->get()
->getResultArray();
}
}

73
app/Models/TodoModel.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class TodoModel extends Model
{
use LoggableTrait;
protected $table = 'todos';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'title',
'description',
'status',
'due_date',
'due_time',
'sync_enabled',
'reminder_enabled',
'recurring_enabled',
'project_id',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'user_id' => 'required',
'title' => 'required|max_length[255]',
'status' => 'permit_empty|in_list[open,in_progress,completed,archived]',
];
protected function getEntityType(): string
{
return 'todo';
}
// Get todos with categories
public function getWithCategories($todoId = null)
{
$builder = $this->select('todos.*, GROUP_CONCAT(categories.name) as category_names')
->join('todo_categories', 'todos.id = todo_categories.todo_id', 'left')
->join('categories', 'todo_categories.category_id = categories.id', 'left')
->groupBy('todos.id');
if ($todoId) {
$builder->where('todos.id', $todoId);
}
return $builder->get()->getResultArray();
}
// Get todos by user with categories
public function getByUserWithCategories($userId)
{
return $this->select('todos.*, GROUP_CONCAT(categories.name) as category_names')
->join('todo_categories', 'todos.id = todo_categories.todo_id', 'left')
->join('categories', 'todo_categories.category_id = categories.id', 'left')
->where('todos.user_id', $userId)
->groupBy('todos.id')
->get()
->getResultArray();
}
}

View File

@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserAiSettingsModel extends Model
{
protected $table = 'user_ai_settings';
protected $primaryKey = 'user_id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'user_id',
'default_provider_id',
'default_model',
'max_tokens',
'temperature',
'updated_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'max_tokens' => 'permit_empty|integer|greater_than[0]',
'temperature' => 'permit_empty|numeric|greater_than_equal_to[0]|less_than_equal_to[2]',
];
// Get or create settings for user
public function getSettings($userId)
{
$settings = $this->find($userId);
if (!$settings) {
// Create default settings
$this->insert([
'user_id' => $userId,
'default_provider_id' => null,
'default_model' => null,
'max_tokens' => 2048,
'temperature' => 0.7,
'updated_at' => date('Y-m-d H:i:s'),
]);
$settings = $this->find($userId);
}
return $settings;
}
// Update settings for user
public function updateSettings($userId, $data)
{
$data['updated_at'] = date('Y-m-d H:i:s');
return $this->update($userId, $data);
}
// Get settings with provider info
public function getSettingsWithProvider($userId)
{
return $this->select('user_ai_settings.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'user_ai_settings.default_provider_id = ai_providers.id', 'left')
->where('user_ai_settings.user_id', $userId)
->get()
->getRowArray();
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserApiKeyModel extends Model
{
protected $table = 'user_api_keys';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'provider_id',
'api_key_encrypted',
'label',
'is_active',
'created_at',
'last_used_at',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'provider_id' => 'required',
'api_key_encrypted' => 'required',
];
// Save or update API key for user and provider
public function saveApiKey($userId, $providerId, $encryptedKey, $label = null)
{
$existing = $this->where('user_id', $userId)
->where('provider_id', $providerId)
->first();
if ($existing) {
return $this->update($existing['id'], [
'api_key_encrypted' => $encryptedKey,
'label' => $label,
'is_active' => true,
'last_used_at' => null,
]);
} else {
return $this->insert([
'id' => $this->generateUuid(),
'user_id' => $userId,
'provider_id' => $providerId,
'api_key_encrypted' => $encryptedKey,
'label' => $label,
'is_active' => true,
'created_at' => date('Y-m-d H:i:s'),
'last_used_at' => null,
]);
}
}
// Get API key for user and provider
public function getApiKey($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->where('is_active', true)
->first();
}
// Get all API keys for user
public function getUserApiKeys($userId)
{
return $this->select('user_api_keys.*, ai_providers.name as provider_name, ai_providers.display_name')
->join('ai_providers', 'user_api_keys.provider_id = ai_providers.id')
->where('user_api_keys.user_id', $userId)
->orderBy('user_api_keys.created_at', 'DESC')
->get()
->getResultArray();
}
// Deactivate API key
public function deactivateApiKey($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->update(['is_active' => false]);
}
// Update last used timestamp
public function updateLastUsed($userId, $providerId)
{
return $this->where('user_id', $userId)
->where('provider_id', $providerId)
->update(['last_used_at' => date('Y-m-d H:i:s')]);
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}

48
app/Models/UserModel.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
use LoggableTrait;
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'email',
'password_hash',
'name',
'avatar_url',
'settings',
'created_at',
'updated_at',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $validationRules = [
'email' => 'required|valid_email|is_unique[users.email]',
'password_hash' => 'required',
];
protected $validationMessages = [
'email' => [
'required' => 'Email is required',
'valid_email' => 'Please enter a valid email address',
'is_unique' => 'This email is already registered',
],
];
protected function getEntityType(): string
{
return 'user';
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserThemeModel extends Model
{
protected $table = 'user_themes';
protected $primaryKey = 'id';
protected $useAutoIncrement = false;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'id',
'user_id',
'theme_id',
'installed_at',
'active',
'custom_settings',
];
protected $useTimestamps = false;
protected $validationRules = [
'user_id' => 'required',
'theme_id' => 'required',
];
// Install theme for user
public function installTheme($userId, $themeId)
{
return $this->insert([
'id' => $this->generateUuid(),
'user_id' => $userId,
'theme_id' => $themeId,
'installed_at' => date('Y-m-d H:i:s'),
'active' => false,
'custom_settings' => json_encode([]),
]);
}
// Uninstall theme for user
public function uninstallTheme($userId, $themeId)
{
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->delete();
}
// Set active theme for user
public function setActiveTheme($userId, $themeId)
{
// Deactivate all themes for user
$this->where('user_id', $userId)->update(['active' => false]);
// Activate the specified theme
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->update(['active' => true]);
}
// Get active theme for user
public function getActiveTheme($userId)
{
return $this->select('user_themes.*, marketplace_themes.*')
->join('marketplace_themes', 'user_themes.theme_id = marketplace_themes.id')
->where('user_themes.user_id', $userId)
->where('user_themes.active', true)
->get()
->getRowArray();
}
// Get all installed themes for user
public function getUserThemes($userId)
{
return $this->select('user_themes.*, marketplace_themes.*')
->join('marketplace_themes', 'user_themes.theme_id = marketplace_themes.id')
->where('user_themes.user_id', $userId)
->orderBy('user_themes.installed_at', 'DESC')
->get()
->getResultArray();
}
// Check if theme is installed for user
public function isInstalled($userId, $themeId)
{
return $this->where('user_id', $userId)
->where('theme_id', $themeId)
->countAllResults() > 0;
}
private function generateUuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}