1
0
Files
TaskBoard/backend/app/class/enity/class_task.php
Falknat 2d27abc48a Добавление логики
1. Получения конфигурациия с бека
2. Время закрытия задачи
3. Изменение фронта под новую локигу конфигурации
4. Обновление структуры бд
2026-01-13 09:11:56 +07:00

311 lines
10 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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 $date_closed;
public $id_account;
public $title;
public $descript;
public $descript_full;
public $archive;
// Валидация данных
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,
'archive' => 0,
'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', 'column_id'], ['id' => $this->id]);
if (!$task) {
$this->addError('task', 'Задача не найдена');
return $this->getErrors();
}
$old_column_id = (int)$task['column_id'];
$new_column_id = (int)$this->column_id;
// Формируем данные для обновления
$update_data = [
'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
];
// Обновляем date_closed при смене колонки
if ($new_column_id === COLUMN_DONE_ID && $old_column_id !== COLUMN_DONE_ID) {
$update_data['date_closed'] = date('Y-m-d H:i:s');
} elseif ($old_column_id === COLUMN_DONE_ID && $new_column_id !== COLUMN_DONE_ID) {
$update_data['date_closed'] = null;
}
// Обновляем в БД
Database::update($this->db_name, $update_data, [
'id' => $this->id
]);
return ['success' => true];
}
// Удаление задачи
public static function delete($id) {
// Проверка что задача существует
self::check_task($id);
// Удаляем папку с файлами если есть
$upload_dir = __DIR__ . '/../../../public/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) {
// Проверка что задача существует
$task = self::check_task($id);
$old_column_id = (int)$task['column_id'];
$new_column_id = (int)$column_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) {
$update_data = [
'order' => $index,
'column_id' => $column_id
];
// Только для перемещаемой карточки обновляем date_closed
if ($card['id'] == $id) {
// Перемещаем В колонку "Готово" — устанавливаем дату закрытия
if ($new_column_id === COLUMN_DONE_ID && $old_column_id !== COLUMN_DONE_ID) {
$update_data['date_closed'] = date('Y-m-d H:i:s');
}
// Перемещаем ИЗ колонки "Готово" — обнуляем дату
elseif ($old_column_id === COLUMN_DONE_ID && $new_column_id !== COLUMN_DONE_ID) {
$update_data['date_closed'] = null;
}
}
Database::update('cards_task', $update_data, [
'id' => $card['id']
]);
}
return ['success' => true];
}
// Получение всех задач
// $archive: 0 = неархивные, 1 = архивные, null = все
public function getAll($archive = 0) {
$where = [];
if ($archive !== null) {
$where['archive'] = $archive ? 1 : 0;
}
$tasks = Database::select($this->db_name, [
'id',
'id_department',
'id_label',
'id_account',
'order',
'column_id',
'date',
'date_create',
'date_closed',
'file_img',
'title',
'descript',
'descript_full',
'archive'
], $where);
// Декодируем 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;
}
// Установка статуса архивации задачи (только для задач в колонке "Готово")
public static function setArchive($id, $archive = 1) {
// Проверка что задача существует
$task = self::check_task($id);
// Архивировать можно только задачи в колонке "Готово"
if ($archive && (int)$task['column_id'] !== COLUMN_DONE_ID) {
RestApi::response([
'success' => false,
'errors' => ['column' => 'Архивировать можно только задачи из колонки "Готово"']
], 400);
}
// Обновляем archive
Database::update('cards_task', [
'archive' => $archive ? 1 : 0
], [
'id' => $id
]);
return ['success' => true, 'archive' => $archive ? 1 : 0];
}
}
?>