1
0

Обновление бека+фронт

MVP версия - которая уже готова к работе
This commit is contained in:
2026-01-12 01:11:32 +07:00
parent a9c146b192
commit 456876f837
16 changed files with 894 additions and 75 deletions

View File

@@ -0,0 +1,248 @@
<?php
class Task extends BaseEntity {
protected $db_name = 'cards_task';
// Свойства задачи
public $id;
public $id_department;
public $id_label;
public $order;
public $column_id;
public $date;
public $id_account;
public $title;
public $descript;
public $descript_full;
// Валидация данных
protected function validate() {
static::$error_message = [];
if (!$this->id) {
$this->addError('id', 'ID задачи не указан');
}
if (!$this->title) {
$this->addError('title', 'Название не может быть пустым');
}
return $this->getErrors();
}
// Валидация данных (для create)
protected function validateCreate() {
static::$error_message = [];
if (!$this->title) {
$this->addError('title', 'Название не может быть пустым');
}
if (!$this->column_id) {
$this->addError('column_id', 'Колонка не указана');
}
if (!$this->id_department) {
$this->addError('id_department', 'Департамент не указан');
}
return $this->getErrors();
}
// Создание задачи (с файлами)
public function create($files = []) {
// Валидация
if ($errors = $this->validateCreate()) {
return $errors;
}
// Вставляем в базу
Database::insert($this->db_name, [
'id_department' => $this->id_department,
'id_label' => $this->id_label,
'order' => $this->order ?? 0,
'column_id' => $this->column_id,
'date' => $this->date ?: null,
'id_account' => $this->id_account,
'title' => $this->title,
'descript' => $this->descript ?: null,
'descript_full' => $this->descript_full ?: null,
'date_create' => date('Y-m-d H:i:s'),
'file_img' => '[]'
]);
// Получаем ID созданной задачи
$this->id = Database::id();
// Загружаем файлы если есть
$uploaded_files = [];
if (!empty($files)) {
foreach ($files as $file) {
$result = TaskImage::upload($this->id, $file['data'], $file['name']);
if ($result['success']) {
$uploaded_files[] = $result['file'];
}
}
}
return [
'success' => true,
'id' => $this->id,
'files' => $uploaded_files
];
}
// Обновление задачи
public function update() {
// Валидация
if ($errors = $this->validate()) {
return $errors;
}
// Проверка что задача существует
$task = Database::get($this->db_name, ['id'], ['id' => $this->id]);
if (!$task) {
$this->addError('task', 'Задача не найдена');
return $this->getErrors();
}
// Обновляем в БД
Database::update($this->db_name, [
'id_department' => $this->id_department,
'id_label' => $this->id_label,
'order' => $this->order,
'column_id' => $this->column_id,
'date' => $this->date ?: null,
'id_account' => $this->id_account,
'title' => $this->title,
'descript' => $this->descript ?: null,
'descript_full' => $this->descript_full ?: null
], [
'id' => $this->id
]);
return ['success' => true];
}
// Удаление задачи
public static function delete($id) {
// Проверка что задача существует
self::check_task($id);
// Удаляем папку с файлами если есть
$upload_dir = __DIR__ . '/../../../public/img/task/' . $id;
if (is_dir($upload_dir)) {
$files = glob($upload_dir . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
rmdir($upload_dir);
}
// Удаляем из базы
Database::delete('cards_task', ['id' => $id]);
return ['success' => true];
}
// Изменение порядка и колонки задачи (с пересчётом order)
public static function updateOrder($id, $column_id, $to_index) {
// Проверка что задача существует
self::check_task($id);
// Получаем все карточки целевой колонки (кроме перемещаемой)
$cards = Database::select('cards_task', ['id', 'order'], [
'column_id' => $column_id,
'id[!]' => $id,
'ORDER' => ['order' => 'ASC']
]) ?? [];
// Вставляем перемещаемую карточку в нужную позицию
array_splice($cards, $to_index, 0, [['id' => $id]]);
// Пересчитываем order для всех карточек
foreach ($cards as $index => $card) {
Database::update('cards_task', [
'order' => $index,
'column_id' => $column_id
], [
'id' => $card['id']
]);
}
return ['success' => true];
}
// Получение всех задач
public function getAll() {
$tasks = Database::select($this->db_name, [
'id',
'id_department',
'id_label',
'id_account',
'order',
'column_id',
'date',
'date_create',
'file_img',
'title',
'descript',
'descript_full'
]);
// Декодируем JSON и получаем avatar_url из accounts
return array_map(function($task) {
$task['file_img'] = json_decode($task['file_img'], true) ?? [];
// Получаем avatar_url из accounts по id_account
if ($task['id_account']) {
$account = Database::get('accounts', ['avatar_url'], ['id' => $task['id_account']]);
$task['avatar_img'] = $account['avatar_url'] ?? null;
} else {
$task['avatar_img'] = null;
}
return $task;
}, $tasks);
}
// Получение всех колонок
public function getColumns() {
return Database::select('columns', [
'id',
'name_columns',
'color'
]);
}
// Получение всех департаментов
public function getDepartments() {
return Database::select('departments', [
'id',
'name_departments',
'color'
]);
}
// Получение всех меток
public function getLabels() {
return Database::select('labels', [
'id',
'name_labels',
'icon',
'color'
]);
}
// Проверка и получение задачи (при ошибке — сразу ответ и exit)
public static function check_task($task_id) {
$task = Database::get('cards_task', '*', ['id' => $task_id]);
if (!$task_id || !$task) {
RestApi::response(['success' => false, 'errors' => ['task' => 'Задача не найдена']], 400);
}
return $task;
}
}
?>