This commit is contained in:
2025-07-14 12:15:41 +03:00
parent a64ed080bb
commit 273ac72207
974 changed files with 483955 additions and 14 deletions

View File

@@ -5,6 +5,7 @@ namespace kernel;
use kernel\helpers\Debug;
use kernel\modules\notification\NotificationDispatcher;
use kernel\modules\user\models\User;
use kernel\services\ModuleService;
use kernel\services\ThemeService;
@@ -21,10 +22,14 @@ class App
static User $user;
static NotificationDispatcher $notificationDispatcher;
static array $secure;
public ModuleService $moduleService;
static Hook $hook;
public ThemeService $themeService;
public static Database $db;
@@ -41,6 +46,7 @@ class App
public function load(): static
{
App::$hook = new Hook();
$this->moduleService = new ModuleService();
App::$collector = new CgRouteCollector();
$this->setRouting();
@@ -53,6 +59,7 @@ class App
include KERNEL_DIR . "/routs/admin.php";
include ROOT_DIR . "/rout.php";
$modules_routs = $this->moduleService->getModulesRouts();
$this->moduleService->setModulesHooks();
foreach ($modules_routs as $rout){
include "$rout";
}

View File

@@ -0,0 +1,345 @@
<?php
namespace kernel;
use Illuminate\Database\Eloquent\Collection;
class CollectionTableRenderer
{
protected \Illuminate\Database\Eloquent\Collection $collection;
protected array $columns;
protected array $tableAttributes;
protected array $customColumns = [];
protected array $valueProcessors = [];
protected array $filters = [];
protected bool $filterRowEnabled = false;
protected array $filterRowAttributes = [
'class' => 'filter-row'
];
/**
* Конструктор класса
*
* @param Collection $collection
*/
public function __construct(Collection $collection)
{
$this->collection = $collection;
$this->columns = [];
$this->customColumns = [];
$this->valueProcessors = [];
$this->filters = [];
$this->tableAttributes = [
'class' => 'table table-bordered table-striped',
'id' => 'dataTable'
];
}
/**
* Установка столбцов для отображения
*
* @param array $columns Массив столбцов в формате ['field' => 'Заголовок']
* @return $this
*/
public function setColumns(array $columns): static
{
$this->columns = $columns;
return $this;
}
/**
* Добавление кастомной колонки
*
* @param string $columnName Название колонки (ключ)
* @param string $title Заголовок колонки
* @param callable $callback Функция для генерации содержимого
* @return $this
*/
public function addCustomColumn(string $columnName, string $title, callable $callback): static
{
$this->customColumns[$columnName] = [
'title' => $title,
'callback' => $callback
];
return $this;
}
/**
* Добавление обработчика значения для колонки
*
* @param string $columnName Название колонки
* @param callable $processor Функция обработки значения
* @return $this
*/
public function addValueProcessor(string $columnName, callable $processor): static
{
$this->valueProcessors[$columnName] = $processor;
return $this;
}
/**
* Добавление фильтра для колонки
*
* @param string $columnName Название колонки
* @param string $filterHtml HTML-код фильтра
* @return $this
*/
public function addFilter(string $columnName, string $filterHtml): static
{
$this->filters[$columnName] = $filterHtml;
$this->filterRowEnabled = true;
return $this;
}
/**
* Включение/отключение строки фильтров
*
* @param bool $enabled
* @return $this
*/
public function enableFilterRow(bool $enabled = true): static
{
$this->filterRowEnabled = $enabled;
return $this;
}
/**
* Установка атрибутов строки фильтров
*
* @param array $attributes
* @return $this
*/
public function setFilterRowAttributes(array $attributes): static
{
$this->filterRowAttributes = array_merge($this->filterRowAttributes, $attributes);
return $this;
}
/**
* Установка атрибутов для таблицы
*
* @param array $attributes Массив атрибутов HTML
* @return $this
*/
public function setTableAttributes(array $attributes): static
{
$this->tableAttributes = array_merge($this->tableAttributes, $attributes);
return $this;
}
/**
* Получить HTML-код таблицы (без вывода)
*
* @return string
*/
public function getHtml(): string
{
if (empty($this->columns) && empty($this->customColumns) && $this->collection->isNotEmpty()) {
// Автоматически определяем столбцы на основе первой модели
$firstItem = $this->collection->first();
$this->columns = array_combine(
array_keys($firstItem->toArray()),
array_map('ucfirst', array_keys($firstItem->toArray()))
);
}
$html = '<table ' . $this->buildAttributes($this->tableAttributes) . '>';
$html .= $this->renderHeader();
if ($this->filterRowEnabled) {
$html .= $this->renderFilterRow();
}
$html .= $this->renderBody();
$html .= '</table>';
return $html;
}
/**
* Генерация HTML-таблицы
*
* @return string
*/
public function render(): void
{
echo $this->getHtml();
}
public function fetch(): string
{
return $this->getHtml();
}
/**
* Генерация заголовка таблицы
*
* @return string
*/
protected function renderHeader(): string
{
$html = '<thead><tr>';
// Обычные колонки
foreach ($this->columns as $title) {
$html .= '<th>' . htmlspecialchars($title) . '</th>';
}
// Кастомные колонки
foreach ($this->customColumns as $column) {
$html .= '<th>' . htmlspecialchars($column['title']) . '</th>';
}
$html .= '</tr></thead>';
return $html;
}
/**
* Генерация строки фильтров
*
* @return string
*/
protected function renderFilterRow(): string
{
$html = '<tr ' . $this->buildAttributes($this->filterRowAttributes) . '>';
// Обычные колонки
foreach (array_keys($this->columns) as $field) {
$html .= '<td>';
if (isset($this->filters[$field])) {
$html .= $this->filters[$field];
} else {
$html .= '&nbsp;';
}
$html .= '</td>';
}
// Кастомные колонки
foreach (array_keys($this->customColumns) as $columnName) {
$html .= '<td>';
if (isset($this->filters[$columnName])) {
$html .= $this->filters[$columnName];
} else {
$html .= '&nbsp;';
}
$html .= '</td>';
}
$html .= '</tr>';
return $html;
}
/**
* Генерация тела таблицы
*
* @return string
*/
protected function renderBody(): string
{
$html = '<tbody>';
foreach ($this->collection as $item) {
$html .= '<tr>';
// Обычные колонки
foreach (array_keys($this->columns) as $field) {
$value = $this->getValue($item, $field);
$value = $this->processValue($field, $value, $item);
$html .= '<td>' . $value . '</td>';
}
// Кастомные колонки
foreach ($this->customColumns as $columnName => $column) {
$value = call_user_func($column['callback'], $item, $columnName);
$html .= '<td>' . $value . '</td>';
}
$html .= '</tr>';
}
$html .= '</tbody>';
return $html;
}
/**
* Обработка значения ячейки
*
* @param string $field Название поля
* @param mixed $value Значение
* @param mixed $item Весь элемент коллекции
* @return mixed
*/
protected function processValue(string $field, mixed $value, mixed $item): mixed
{
// Если есть обработчик для этого поля - применяем его
if (isset($this->valueProcessors[$field])) {
$value = call_user_func($this->valueProcessors[$field], $value, $item, $field);
}
// Если значение не прошло обработку - экранируем его
// if (is_string($value)) {
// return htmlspecialchars($value);
// }
return $value;
}
/**
* Получение значения из элемента коллекции
*
* @param mixed $item
* @param string $field
* @return mixed
*/
protected function getValue(mixed $item, string $field): mixed
{
// Поддержка dot-notation для отношений
if (str_contains($field, '.')) {
return data_get($item, $field);
}
// Поддержка accessor'ов модели
if (method_exists($item, 'get' . ucfirst($field) . 'Attribute')) {
return $item->{$field};
}
return $item->{$field} ?? null;
}
/**
* Сборка HTML-атрибутов
*
* @param array $attributes
* @return string
*/
protected function buildAttributes(array $attributes): string
{
$result = [];
foreach ($attributes as $key => $value) {
$result[] = $key . '="' . htmlspecialchars($value) . '"';
}
return implode(' ', $result);
}
/**
* Магический метод для преобразования в строку
*
* @return string
*/
public function __toString()
{
return $this->render();
}
}

41
kernel/Hook.php Normal file
View File

@@ -0,0 +1,41 @@
<?php
namespace kernel;
class Hook
{
protected array $pool;
public function add(string $entity, \Closure $handler): void
{
$this->pool[] = [
'entity' => $entity,
'handler' => $handler,
];
}
public function getHooksByEntity(string $entity): array
{
$hooks = [];
foreach ($this->pool as $item){
if ($item['entity'] === $entity){
$hooks[] = $item;
}
}
return $hooks;
}
public function runHooksByEntity(string $entity, array $params = []): void
{
$response = '';
$hooks = $this->getHooksByEntity($entity);
foreach ($hooks as $hook){
$response .= call_user_func_array($hook['handler'], $params ?? []);
}
echo $response;
}
}

View File

@@ -0,0 +1,163 @@
<?php
namespace kernel\app_modules\user_custom_fields;
use Illuminate\Database\Eloquent\Model;
use itguild\forms\builders\SelectBuilder;
use itguild\forms\builders\TextInputBuilder;
use kernel\app_modules\tag\models\Tag;
use kernel\app_modules\tag\service\TagEntityService;
use kernel\app_modules\user_custom_fields\models\CustomField;
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
use kernel\app_modules\user_custom_fields\services\UserCustomValuesService;
use kernel\EntityRelation;
use kernel\helpers\Debug;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
use kernel\Request;
use kernel\services\MigrationService;
class UserCustomFieldsModule extends Module
{
public MenuService $menuService;
public MigrationService $migrationService;
public function __construct()
{
$this->menuService = new MenuService();
$this->migrationService = new MigrationService();
}
public function init(): void
{
$this->migrationService->runAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");
$this->menuService->createItem([
"label" => "Доп. поля пользователей",
"url" => "/admin/custom_field",
"slug" => "custom_field",
]);
$this->menuService->createItem([
"label" => "Список",
"url" => "/admin/custom_field",
"slug" => "custom_field_list",
"parent_slug" => "custom_field"
]);
$this->menuService->createItem([
"label" => "Значения",
"url" => "/admin/custom_field/user_values",
"slug" => "custom_field_user_values",
"parent_slug" => "custom_field"
]);
EntityRelation::addEntityRelation('user', 'user_custom_fields');
}
/**
* @throws \Exception
*/
public function deactivate(): void
{
$this->migrationService->rollbackAtPath("{KERNEL_APP_MODULES}/user_custom_fields/migrations");
$this->menuService->removeItemBySlug("custom_field_user_values");
$this->menuService->removeItemBySlug("custom_field_list");
$this->menuService->removeItemBySlug("custom_field");
EntityRelation::removePropertyFromEntityRelations('user', 'user_custom_fields');
}
public function formInputs(string $entity, Model $model = null): void
{
$fields = CustomFieldService::getCustomFields();
foreach ($fields as $field) {
/* @var CustomField $field */
if (isset($model->id)) {
$value = UserCustomValuesService::getValueByFieldAndUser($field->id, $model->id);
}
if ($field->type === "string"){
$input = TextInputBuilder::build($field->slug, [
'class' => 'form-control',
'placeholder' => $field->label,
'value' => $value->value ?? '',
]);
}
else {
$options = explode(", ", $field->field_options);
$options = array_combine($options, $options);
$input = SelectBuilder::build($field->slug, [
'class' => 'form-control',
'placeholder' => $field->label,
'value' => $value->value ?? '',
])->setOptions($options);
}
$input->setLabel($field->label);
$input->create()->render();
}
}
public function saveInputs(string $entity, Model $model, Request $request): void
{
$service = new UserCustomValuesService();
$form = new CreateUserCustomValueForm();
$fields = CustomFieldService::getCustomFields();
foreach ($fields as $field){
/* @var CustomField $field */
if (isset($request->data[$field->slug])){
UserCustomValuesService::deleteByUserAndField($model->id, $field->id);
$form->load([
'user_id' => $model->id,
'custom_field_id' => $field->id,
'value' => $request->data[$field->slug]
]);
$service->create($form);
}
}
}
public function getItem(string $entity, string $entity_id): string
{
$fields = UserCustomValuesService::getValuesByUserId($entity_id);
$fieldsArr = [];
foreach ($fields as $field){
/* @var UserCustomValues $field */
$fieldsArr[$field->customField->label] = $field->value;
}
$string = implode(', ', array_map(
function ($key, $value) {
return "$key: $value";
},
array_keys($fieldsArr),
$fieldsArr
));
return $string;
}
public function getItems(string $entity, Model $model): string
{
$fields = UserCustomValuesService::getValuesByUserId($model->id);
$fieldsArr = [];
foreach ($fields as $field){
/* @var UserCustomValues $field */
$fieldsArr[$field->customField->label] = $field->value;
}
$string = implode(', ', array_map(
function ($key, $value) {
return "$key: $value";
},
array_keys($fieldsArr),
$fieldsArr
));
return $string;
}
}

View File

@@ -0,0 +1,140 @@
<?php
namespace kernel\app_modules\user_custom_fields\controllers;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\app_modules\user_custom_fields\models\forms\CreateCustomFieldForm;
use kernel\app_modules\user_custom_fields\models\CustomField;
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
use kernel\app_modules\user_custom_fields\services\UserCustomValuesService;
use kernel\Flash;
use kernel\helpers\Debug;
class UserCustomFieldsController extends AdminController
{
private CustomFieldService $user_custom_fieldsService;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/user_custom_fields/views/";
$this->user_custom_fieldsService = new CustomFieldService();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
#[NoReturn] public function actionAdd(): void
{
$user_custom_fieldsForm = new CreateCustomFieldForm();
$user_custom_fieldsForm->load($_REQUEST);
if ($user_custom_fieldsForm->validate()){
$user_custom_fields = $this->user_custom_fieldsService->create($user_custom_fieldsForm);
if ($user_custom_fields){
$this->redirect("/admin/custom_field/view/" . $user_custom_fields->id);
}
}
Flash::setMessage("error", $user_custom_fieldsForm->getErrorsStr());
$this->redirect("/admin/custom_field/create");
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$user_custom_fields = CustomField::find($id);
if (!$user_custom_fields){
throw new Exception(message: "The user_custom_fields not found");
}
$this->cgView->render("view.php", ['user_custom_fields' => $user_custom_fields]);
}
/**
* @throws Exception
*/
public function actionUpdate($id): void
{
$model = CustomField::find($id);
if (!$model){
throw new Exception(message: "The user_custom_fields not found");
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit($id): void
{
$user_custom_fields = CustomField::find($id);
if (!$user_custom_fields){
throw new Exception(message: "The user_custom_fields not found");
}
$user_custom_fieldsForm = new CreateCustomFieldForm();
$user_custom_fieldsService = new CustomFieldService();
$user_custom_fieldsForm->load($_REQUEST);
if ($user_custom_fieldsForm->validate()) {
$user_custom_fields = $user_custom_fieldsService->update($user_custom_fieldsForm, $user_custom_fields);
if ($user_custom_fields) {
$this->redirect("/admin/custom_field/view/" . $user_custom_fields->id);
}
}
$this->redirect("/admin/custom_field/update/" . $id);
}
#[NoReturn] public function actionDelete($id): void
{
$user_custom_fields = CustomField::find($id)->first();
$user_custom_fields->delete();
$this->redirect("/admin/custom_field/");
}
public function actionUserCustomValuesList($page_number = 1): void
{
$this->cgView->render("values_index.php", ['page_number' => $page_number]);
}
public function actionCreateUserCustomValues(): void
{
$this->cgView->render("values_form.php");
}
#[NoReturn] public function actionAddUserCustomValues(): void
{
$service = new UserCustomValuesService();
$form = new CreateUserCustomValueForm();
$form->load($_REQUEST);
UserCustomValuesService::deleteByUserAndField($form->getItem('user_id'), $form->getItem('custom_field_id'));
if ($form->validate()){
$model = $service->create($form);
if ($model){
$this->redirect("/admin/custom_field/user_values");
}
}
Flash::setMessage("error", $form->getErrorsStr());
$this->redirect("/admin/custom_field/user_values");
}
#[NoReturn] public function actionDeleteUserCustomValues($id): void
{
$user_custom_values = UserCustomValues::find($id)->first();
$user_custom_values->delete();
Flash::setMessage("success", "Запись удалена");
$this->redirect("/admin/custom_field/user_values");
}
}

View File

@@ -0,0 +1,48 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public string $migration;
/**
* Run the migrations.
*/
public function up(): void
{
\kernel\App::$db->schema->create('custom_field', function (Blueprint $table) {
$table->id();
$table->string('slug')->unique(); // Название поля (например, 'phone')
$table->string('type')->default('string'); // Тип поля (string, integer, boolean и т.д.)
$table->string('entity')->nullable(true); // Сущность (user, post и т.д.)
$table->string('label'); // Человекочитаемое название
$table->text('field_options'); // Человекочитаемое название
$table->integer('status')->default(1);
$table->timestamps();
});
\kernel\App::$db->schema->create('user_custom_values', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('custom_field_id');
$table->text('value')->nullable();
$table->timestamps();
// $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
// $table->foreign('custom_field_id')->references('id')->on('custom_field')->onDelete('cascade');
// $table->unique(['user_id', 'custom_field_id']); // Уникальная пара пользователь-поле
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
\kernel\App::$db->schema->dropIfExists('user_custom_values');
\kernel\App::$db->schema->dropIfExists('custom_field');
}
};

View File

@@ -0,0 +1,72 @@
<?php
namespace kernel\app_modules\user_custom_fields\models;
use Illuminate\Database\Eloquent\Model;
// Добавить @property
/**
* @property int $id
* @property int $status
* @property string $slug
* @property string $label
* @property string $type
* @property string $entity
* @property string $field_options
*/
class CustomField extends Model
{
const DISABLE_STATUS = 0;
const ACTIVE_STATUS = 1;
const TYPE_STRING = 'string';
const TYPE_SELECT = 'select';
protected $table = 'custom_field';
protected $fillable = ['slug', 'label', 'type', 'entity', 'field_options', 'status']; // Заполнить массив. Пример: ['label', 'slug', 'status']
public static function labels(): array
{
// Заполнить массив
// Пример: [
// 'label' => 'Заголовок',
// 'entity' => 'Сущность',
// 'slug' => 'Slug',
// 'status' => 'Статус',
// ]
return [
'slug' => 'Slug',
'label' => 'Название',
'type' => 'Тип',
'entity' => 'Сущность',
'field_options' => 'Опции поля',
'status' => 'Статус',
];
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::ACTIVE_STATUS => "Активный",
];
}
/**
* @return string[]
*/
public static function getTypes(): array
{
return [
self::TYPE_STRING => 'Текст',
self::TYPE_SELECT => 'Список',
];
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace kernel\app_modules\user_custom_fields\models;
use Illuminate\Database\Eloquent\Model;
use kernel\modules\user\models\User;
/**
* @property int $id
* @property int $user_id
* @property int $custom_field_id
* @property string $value
* @property string $created_at
* @property string $updated_at
*/
class UserCustomValues extends Model
{
const DISABLE_STATUS = 0;
const ACTIVE_STATUS = 1;
protected $table = 'user_custom_values';
protected $fillable = ['user_id', 'custom_field_id', 'value'];
public static function labels(): array
{
return [
'user_id' => 'ID пользователя',
'custom_field_id' => 'ID кастомного поля',
'value' => 'Значение',
'created_at' => 'Дата создания',
'updated_at' => 'Дата обновления',
];
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::ACTIVE_STATUS => "Активный",
];
}
public function customField(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(CustomField::class);
}
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace kernel\app_modules\user_custom_fields\models\forms;
use kernel\FormModel;
class CreateCustomFieldForm extends FormModel
{
public function rules(): array
{
// Заполнить массив правил
// Пример:
// return [
// 'label' => 'required|min-str-len:5|max-str-len:30',
// 'entity' => 'required',
// 'slug' => '',
// 'status' => ''
// ];
return [
'slug' => 'required|min-str-len:3|max-str-len:30',
'label' => 'required|min-str-len:3|max-str-len:50',
'type' => 'required|min-str-len:3|max-str-len:30',
'entity' => 'required|min-str-len:3|max-str-len:30',
'field_options' => '',
'status' => '',
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace kernel\app_modules\user_custom_fields\models\forms;
use kernel\FormModel;
class CreateUserCustomValueForm extends FormModel
{
public function rules(): array
{
// Заполнить массив правил
// Пример:
// return [
// 'label' => 'required|min-str-len:5|max-str-len:30',
// 'entity' => 'required',
// 'slug' => '',
// 'status' => ''
// ];
return [
'user_id' => 'required|integer|min:1',
'custom_field_id' => 'required|integer|min:1',
'value' => '',
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
use kernel\App;
use kernel\CgRouteCollector;
use Phroute\Phroute\RouteCollector;
App::$collector->group(["prefix" => "admin"], function (CgRouteCollector $router) {
App::$collector->group(["before" => "auth"], function (RouteCollector $router) {
App::$collector->group(["prefix" => "custom_field"], function (CGRouteCollector $router) {
App::$collector->get('/', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionIndex']);
App::$collector->get('/create', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionDelete']);
App::$collector->get('/user_values', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionUserCustomValuesList']);
App::$collector->post('/user_values', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionAddUserCustomValues']);
App::$collector->get('/user_values/create', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionCreateUserCustomValues']);
App::$collector->get('/user_values/delete/{id}', [\app\modules\user_custom_fields\controllers\UserCustomFieldsController::class, 'actionDeleteUserCustomValues']);
});
});
});

View File

@@ -0,0 +1,105 @@
<?php
namespace kernel\app_modules\user_custom_fields\services;
use itguild\forms\builders\SelectBuilder;
use itguild\forms\builders\TextInputBuilder;
use kernel\app_modules\user_custom_fields\models\CustomField;
use kernel\app_modules\user_custom_fields\models\forms\CreateCustomFieldForm;
use kernel\FormModel;
class CustomFieldService
{
public function create(FormModel $form_model): false|CustomField
{
$model = new CustomField();
// Пример заполнения:
$model->slug = $form_model->getItem('slug');
$model->label = $form_model->getItem('label');
$model->type = $form_model->getItem('type');
$model->entity = $form_model->getItem('entity');
$model->field_options = $form_model->getItem('field_options');
$model->status = $form_model->getItem('status');
if ($model->save()) {
return $model;
}
return false;
}
public function update(FormModel $form_model, CustomField $custom_field): false|CustomField
{
// Пример обновления:
$custom_field->slug = $form_model->getItem('slug');
$custom_field->label = $form_model->getItem('label');
$custom_field->type = $form_model->getItem('type');
$custom_field->entity = $form_model->getItem('entity');
$custom_field->field_options = $form_model->getItem('field_options');
$custom_field->status = $form_model->getItem('status');
if ($custom_field->save()) {
return $custom_field;
}
return false;
}
public static function getCustomFields()
{
$model = CustomField::where(['entity' => 'user'])->where(['status' => CustomField::ACTIVE_STATUS])->get();
return $model;
}
public static function getList(): array
{
return CustomField::select('id', 'label')->get()
->pluck('label', 'id')
->toArray();
}
public static function getCustomFieldHtml(CustomField $field, int $userId)
{
$value = UserCustomValuesService::getValueByFieldAndUser($field->id, $userId);
if ($field->type === "string"){
$input = TextInputBuilder::build($field->slug, [
'class' => 'form-control',
'placeholder' => $field->label,
'value' => $value->value ?? '',
]);
}
else {
$options = explode(", ", $field->field_options);
$options = array_combine($options, $options);
$input = SelectBuilder::build($field->slug, [
'class' => 'form-control',
'placeholder' => $field->label,
'value' => $value->value ?? '',
])->setOptions($options);
}
$input->setLabel($field->label);
return $input->create()->fetch();
}
public static function getOrCreateBySlug(string $slug): CustomField
{
$model = CustomField::where('slug', $slug)->first();
if (!$model) {
$form = new CreateCustomFieldForm();
$service = new self();
$form->load([
'slug' => $slug,
'label' => $slug,
'entity' => 'user',
'type' => 'string',
]);
$model = $service->create($form);
}
return $model;
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace kernel\app_modules\user_custom_fields\services;
use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
use kernel\FormModel;
class UserCustomValuesService
{
public function create(FormModel $form_model): false|UserCustomValues
{
$model = new UserCustomValues();
$model->user_id = $form_model->getItem('user_id');
$model->custom_field_id = $form_model->getItem('custom_field_id');
$model->value = $form_model->getItem('value');
if ($model->save()) {
return $model;
}
return false;
}
public function update(FormModel $form_model, UserCustomValues $user_custom_value): false|UserCustomValues
{
$user_custom_value->user_id = $form_model->getItem('user_id');
$user_custom_value->custom_field_id = $form_model->getItem('custom_field_id');
$user_custom_value->value = $form_model->getItem('value');
if ($user_custom_value->save()) {
return $user_custom_value;
}
return false;
}
public static function getValuesByUserId(int $user_id): \Illuminate\Database\Eloquent\Collection
{
return UserCustomValues::with(['customField'])->where(['user_id' => $user_id])->get();
}
public static function getValueByFieldAndUser(int $custom_field_id, int $user_id): UserCustomValues|null
{
return UserCustomValues::where([
'custom_field_id' => $custom_field_id,
'user_id' => $user_id
])->first();
}
public static function deleteByUserAndField(int $user_id, int $custom_field_id): bool
{
$record = self::getValueByFieldAndUser($custom_field_id, $user_id);
if ($record) {
return $record->delete();
}
return false;
}
public static function save(int $userId, string $slug, string $value): UserCustomValues
{
$customField = CustomFieldService::getOrCreateBySlug($slug);
$model = UserCustomValues::where('user_id', $userId)->where('custom_field_id', $customField->id)->first();
if (!$model) {
$service = new self();
$form = new CreateUserCustomValueForm();
$form->load([
'custom_field_id' => $customField->id,
'user_id' => $userId,
'value' => $value,
]);
$model = $service->create($form);
}
return $model;
}
}

View File

@@ -0,0 +1,96 @@
<?php
/**
* @var CustomField $model
*/
use kernel\app_modules\user_custom_fields\models\CustomField;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/custom_field/edit/" . $model->id : "/admin/custom_field", 'multipart/form-data');
// Пример формы:
$form->field(\itguild\forms\inputs\TextInput::class, 'slug', [
'class' => "form-control",
'placeholder' => 'Slug',
'value' => $model->slug ?? ''
])
->setLabel("Slug")
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'label', [
'class' => "form-control",
'placeholder' => 'Название поля',
'value' => $model->label ?? ''
])
->setLabel("Название поля")
->render();
$form->field(\itguild\forms\inputs\Select::class, 'type', [
'class' => "form-control",
'value' => $model->type ?? ''
])
->setLabel("Тип")
->setOptions(CustomField::getTypes())
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'entity', [
'class' => "form-control",
'placeholder' => 'Сущность',
'value' => $model->entity ?? ''
])
->setLabel("Сущность")
->render();
$form->field(\itguild\forms\inputs\TextArea::class, 'field_options', [
'class' => "form-control",
'placeholder' => 'Вариант 1, Вариант2, Вариант 3',
'value' => $model->field_options ?? ''
])
->setLabel("Опции поля (через запятую)")
->render();
$form->field(\itguild\forms\inputs\Select::class, 'status', [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(CustomField::getStatus())
->render();
/*
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel("Пользователи")
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
->render();
*/
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@@ -0,0 +1,78 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
* @var int $page_number
* @var \kernel\CgView $view
*/
use kernel\app_modules\user_custom_fields\models\CustomField;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;
$view->setTitle("Список дополнительных полей");
$view->setMeta([
'description' => 'Список дополнительных полей системы'
]);
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
$table = new ListEloquentTable(new EloquentDataProvider(CustomField::class, [
'currentPage' => $page_number,
'perPage' => 8,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/custom_field"
]));
//$table = new \Itguild\Tables\ListJsonTable(json_encode(
// [
// 'meta' => [
// 'total' => 0,
// 'totalWithFilters' => 0,
// 'columns' => [
// 'title',
// 'slug',
// 'status',
// ],
// 'perPage' => 5,
// 'currentPage' => 1,
// 'baseUrl' => '/admin/some',
// 'params' => [
// 'class' => 'table table-bordered',
// 'border' => 2
// ]
// ],
// 'filters' => [],
// 'data' => [],
// ]
//));
// Пример фильтра
$table->columns([
'slug' => [
'filter' => [
'class' => \Itguild\Tables\Filter\InputTextFilter::class,
'value' => $get['title'] ?? ''
]
],
]);
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/custom_field/create'])->run();
});
$table->addAction(function($row) {
return IconBtnViewWidget::create(['url' => '/admin/custom_field/view/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnEditWidget::create(['url' => '/admin/custom_field/update/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnDeleteWidget::create(['url' => '/admin/custom_field/delete/' . $row['id']])->run();
});
$table->create();
$table->render();

View File

@@ -0,0 +1,72 @@
<?php
/**
* @var \kernel\app_modules\user_custom_fields\models\UserCustomValues $model
*/
use kernel\app_modules\user_custom_fields\models\CustomField;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/custom_field/user_values/edit/" . $model->id : "/admin/custom_field/user_values", 'multipart/form-data');
// Пример формы:
$form->field(\itguild\forms\inputs\Select::class, 'user_id', [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel("Пользователь")
->setOptions(\kernel\modules\user\service\UserService::getList())
->render();
$form->field(\itguild\forms\inputs\Select::class, 'custom_field_id', [
'class' => "form-control",
'value' => $model->custom_field_id ?? ''
])
->setLabel("Поле")
->setOptions(\kernel\app_modules\user_custom_fields\services\CustomFieldService::getList())
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'value', [
'class' => "form-control",
'placeholder' => 'Значение',
'value' => $model->value ?? ''
])
->setLabel("Значение")
->render();
/*
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel("Пользователи")
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
->render();
*/
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@@ -0,0 +1,85 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
* @var int $page_number
* @var \kernel\CgView $view
*/
use kernel\app_modules\user_custom_fields\models\CustomField;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\modules\user\models\User;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;
$view->setTitle("Список значений дополнительных полей");
$view->setMeta([
'description' => 'Список значений дополнительных полей системы'
]);
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
$table = new ListEloquentTable(new EloquentDataProvider(\kernel\app_modules\user_custom_fields\models\UserCustomValues::class, [
'currentPage' => $page_number,
'perPage' => 8,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/custom_field"
]));
//$table = new \Itguild\Tables\ListJsonTable(json_encode(
// [
// 'meta' => [
// 'total' => 0,
// 'totalWithFilters' => 0,
// 'columns' => [
// 'title',
// 'slug',
// 'status',
// ],
// 'perPage' => 5,
// 'currentPage' => 1,
// 'baseUrl' => '/admin/some',
// 'params' => [
// 'class' => 'table table-bordered',
// 'border' => 2
// ]
// ],
// 'filters' => [],
// 'data' => [],
// ]
//));
// Пример фильтра
$table->columns([
'user_id' => [
'value' => function ($data) {
return User::find($data)->username;
},
'filter' => [
'class' => \kernel\filters\BootstrapSelectFilter::class,
'params' => [
'options' => \kernel\modules\user\service\UserService::createUsernameArr(),
'prompt' => 'Не выбрано'
],
'value' => $get['user_id'] ?? '',
],
],
'custom_field_id' => [
'value' => function ($data) {
return CustomField::find($data)->label ?? '';
},
],
]);
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/custom_field/user_values/create'])->run();
});
$table->addAction(function($row) {
return IconBtnDeleteWidget::create(['url' => '/admin/custom_field/user_values/delete/' . $row['id']])->run();
});
$table->create();
$table->render();

View File

@@ -0,0 +1,25 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user_custom_fields
*/
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnListWidget;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($user_custom_fields, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user_custom_fields",
]));
$table->beforePrint(function () use ($user_custom_fields) {
$btn = IconBtnListWidget::create(['url' => '/admin/custom_field'])->run();
$btn .= IconBtnEditWidget::create(['url' => '/admin/custom_field/update/' . $user_custom_fields->id])->run();
$btn .= IconBtnDeleteWidget::create(['url' => '/admin/custom_field/delete/' . $user_custom_fields->id])->run();
return $btn;
});
$table->create();
$table->render();

View File

@@ -0,0 +1,20 @@
<?php
namespace kernel\app_modules\user_custom_fields\widgets;
use kernel\app_modules\user_custom_fields\models\CustomField;
use kernel\app_modules\user_custom_fields\services\CustomFieldService;
use kernel\helpers\Debug;
use kernel\Widget;
class UserCustomFieldsInputsWidget extends Widget
{
public function run()
{
$fields = CustomFieldService::getCustomFields();
Debug::dd($fields);
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace kernel\app_modules\user_stage;
use kernel\helpers\Debug;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
use kernel\services\MigrationService;
class UserStageModule extends Module
{
public MenuService $menuService;
public MigrationService $migrationService;
public function __construct()
{
$this->menuService = new MenuService();
$this->migrationService = new MigrationService();
}
public function init(): void
{
$this->migrationService->runAtPath("{KERNEL_APP_MODULES}/user_stage/migrations");
$this->menuService->createItem([
"label" => "Этапы пользователя",
"url" => "/admin/user_stage",
"slug" => "user_stage",
]);
}
public function deactivate(): void
{
$this->migrationService->rollbackAtPath("{KERNEL_APP_MODULES}/user_stage/migrations");
$this->menuService->removeItemBySlug("user_stage");
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace kernel\app_modules\user_stage\controllers;
use Exception;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\App;
use kernel\app_modules\user_stage\models\forms\CreateUserStageForm;
use kernel\app_modules\user_stage\models\User;
use kernel\app_modules\user_stage\models\UserStage;
use kernel\app_modules\user_stage\notification_messages\UserNewStageNotification;
use kernel\app_modules\user_stage\services\UserStageService;
use kernel\Flash;
class UserStageController extends AdminController
{
private UserStageService $user_stageService;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_APP_MODULES_DIR . "/user_stage/views/";
$this->user_stageService = new UserStageService();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
#[NoReturn] public function actionAdd(): void
{
$user_stageForm = new CreateUserStageForm();
$user_stageForm->load($_REQUEST);
if ($user_stageForm->validate()) {
$user_stage = $this->user_stageService->create($user_stageForm);
if ($user_stage) {
$this->redirect("/admin/user_stage/view/" . $user_stage->id);
}
}
$this->redirect("/admin/user_stage/create");
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
/**
* @throws Exception
*/
public function actionView($id): void
{
$user_stage = UserStage::find($id);
if (!$user_stage) {
throw new Exception(message: "The user_stage not found");
}
$this->cgView->render("view.php", ['user_stage' => $user_stage]);
}
/**
* @throws Exception
*/
public function actionUpdate($id): void
{
$model = UserStage::find($id);
if (!$model) {
throw new Exception(message: "The user_stage not found");
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws Exception
*/
public function actionEdit($id): void
{
$user_stage = UserStage::find($id);
if (!$user_stage) {
throw new Exception(message: "The user_stage not found");
}
$user_stageForm = new CreateUserStageForm();
$user_stageService = new UserStageService();
$user_stageForm->load($_REQUEST);
if ($user_stageForm->validate()) {
$user_stage = $user_stageService->update($user_stageForm, $user_stage);
if ($user_stage) {
$this->redirect("/admin/user_stage/view/" . $user_stage->id);
}
}
$this->redirect("/admin/user_stage/update/" . $id);
}
#[NoReturn] public function actionDelete($id): void
{
$user_stage = UserStage::find($id)->first();
$user_stage->delete();
$this->redirect("/admin/user_stage/");
}
#[NoReturn] public function actionSetStage(int $stage_id, int $stage_status, int $user_id): void
{
$user = User::find($user_id);
$stage = UserStage::find($stage_id);
if ($stage_status === 2) {
$notification = new UserNewStageNotification($stage, $user);
App::$notificationDispatcher->dispatch($notification, $user);
$user->openStage($stage);
}
if ($stage_status === 3) {
$user->completeStage($stage);
}
if ($stage_status === 1) {
$user->closeStage($stage);
}
Flash::setMessage('success', 'Этап изменен');
$this->redirect("/admin/user/view/" . $user_id, 302);
}
}

View File

@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\kernel\App::$db->schema->create('user_stage', function (Blueprint $table) {
$table->id();
$table->string('slug')->nullable(false);
$table->string('title')->nullable(false);
$table->text('description')->nullable(false);
$table->dateTime('start_date')->nullable();
$table->dateTime('end_date')->nullable();
$table->integer('position')->nullable(false)->default(1);
$table->integer('status')->default(1);
$table->text('user_fields')->nullable(true);
$table->timestamps();
});
\kernel\App::$db->schema->create('user_stage_progress', function (Blueprint $table) {
$table->id();
$table->integer('user_id')->nullable(false);
$table->integer('user_stage_id')->nullable(false);
$table->boolean('is_completed')->default(false);
$table->boolean('is_closed')->default(true);
$table->integer('status')->default(1);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
\kernel\App::$db->schema->dropIfExists('user_stage_progress');
\kernel\App::$db->schema->dropIfExists('user_stage');
}
};

View File

@@ -0,0 +1,81 @@
<?php
namespace kernel\app_modules\user_stage\models;
class User extends \kernel\modules\user\models\User
{
public function stageProgress(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(UserStageProgress::class);
}
public function stages()
{
return $this->belongsToMany(UserStage::class, 'user_stage_progress')
->withPivot(['is_completed', 'completed_at', 'is_closed', 'status'])
->withTimestamps();
}
// Метод для отметки этапа как завершенного
public function completeStage(UserStage $stage): void
{
$this->stages()->updateExistingPivot($stage->id, [
'is_completed' => true,
'status' => 3,
'completed_at' => date('Y-m-d H:i')
]);
}
public function openStage(UserStage $stage): void
{
$this->stages()->updateExistingPivot($stage->id, [
'status' => 2,
'is_closed' => 0,
]);
}
public function closeStage(UserStage $stage): void
{
$this->stages()->updateExistingPivot($stage->id, [
'status' => 1,
'is_closed' => 1,
]);
}
// Проверка, завершен ли этап
public function hasCompletedStage(UserStage $stage)
{
return $this->stages()
->where('stage_id', $stage->id)
->where('is_completed', true)
->exists();
}
public function isClosed(UserStage $stage)
{
return $this->stages()
->where('user_stage_id', $stage->id)
->where('is_closed', true)
->exists();
}
public function hasStages(): bool
{
if ($this->stages()) {
return true;
}
return false;
}
// Получение текущего этапа (первый незавершенный)
public function currentStage()
{
return $this->stages()
->where('is_completed', false)
->orderBy('stage_id')
->first();
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace kernel\app_modules\user_stage\models;
use DateTime;
use Illuminate\Database\Eloquent\Model;
// Добавить @property
/**
* @property int $id
* @property int $status
* @property int $position
* @property string $title
* @property string $slug
* @property string $description
* @property string $start_date
* @property string $end_date
* @property string $user_fields
* @property string $dateStartFormatedToForm
* @property string $dateEndFormatedToForm
*/
class UserStage extends Model
{
const DISABLE_STATUS = 0;
const ACTIVE_STATUS = 1;
protected $table = 'user_stage';
protected $fillable = ['title', 'slug', 'description', 'start_date', 'end_date', 'position', 'status', 'user_fields']; // Заполнить массив. Пример: ['label', 'slug', 'status']
public static function labels(): array
{
// Заполнить массив
// Пример: [
// 'label' => 'Заголовок',
// 'entity' => 'Сущность',
// 'slug' => 'Slug',
// 'status' => 'Статус',
// ]
return [
'title' => 'Заголовок',
'slug' => 'Slug',
'description' => 'Описание',
'start_date' => 'Начало',
'end_date' => 'Конец',
'position' => 'Позиция',
'status' => 'Статус',
'user_fields' => 'Поля пользователя',
];
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::ACTIVE_STATUS => "Активный",
];
}
/**
* @throws \Exception
*/
public function getDateStartFormatedToFormAttribute(): string
{
$startDate = new DateTime($this->start_date);
return $startDate->format("Y-m-d");
}
/**
* @throws \Exception
*/
public function getDateEndFormatedToFormAttribute(): string
{
$endDate = new DateTime($this->end_date);
return $endDate->format("Y-m-d");
}
public function userProgress(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(UserStageProgress::class);
}
public function users()
{
return $this->belongsToMany(User::class, 'user_stage_progress')
->withPivot(['is_completed', 'completed_at', 'status', 'is_closed'])
->withTimestamps();
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace kernel\app_modules\user_stage\models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $user_id
* @property int $user_stage_id
* @property int $status
* @property bool $is_completed
* @property bool $is_closed
* @property string $completed_at
*/
class UserStageProgress extends Model
{
protected $table = 'user_stage_progress';
protected $fillable = ['user_id', 'user_stage_id', 'is_completed', 'is_closed', 'completed_at', 'status'];
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
public function stage(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(UserStage::class);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace kernel\app_modules\user_stage\models\forms;
use kernel\FormModel;
class CreateUserStageForm extends FormModel
{
public function rules(): array
{
// Заполнить массив правил
// Пример:
// return [
// 'label' => 'required|min-str-len:5|max-str-len:30',
// 'entity' => 'required',
// 'slug' => '',
// 'status' => ''
// ];
return [
'title' => 'required|min-str-len:5|max-str-len:30',
'slug' => '',
'description' => 'required|min-str-len:5',
'start_date' => '',
'end_date' => '',
'position' => 'required|integer',
'status' => 'integer',
'user_fields' => '',
];
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace kernel\app_modules\user_stage\notification_messages;
use kernel\app_modules\user_stage\models\User;
use kernel\app_modules\user_stage\models\UserStage;
use kernel\CgView;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\user\service\UserService;
class UserNewStageNotification extends NotificationMessage
{
protected UserStage $userStage;
protected User $user;
protected CgView $cgView;
public function __construct(UserStage $userStage, User $user)
{
$this->cgView = new CgView();
$this->cgView->viewPath = ROOT_DIR . $_ENV['EMAIL_VIEWS_PATH'];
$this->userStage = $userStage;
$this->user = $user;
$this->channels = ['email'];
}
public function getMessage(): string
{
return $this->cgView->fetch('user_new_stage.php', [
'user' => $this->user->username,
'stage' => $this->userStage->title,
'url' => $_ENV['APP_URL'],
]);
}
public function getSubject(): string
{
return "Вам открыт новый этап {$this->userStage->title}";
}
public function toArray(): array
{
return array_merge(parent::toArray(), [
'stage_id' => $this->userStage->id,
'stage_title' => $this->userStage->title
]);
}
}

View File

@@ -0,0 +1,21 @@
<?php
use kernel\App;
use kernel\CgRouteCollector;
use Phroute\Phroute\RouteCollector;
App::$collector->group(["prefix" => "admin"], function (CgRouteCollector $router) {
App::$collector->group(["before" => "auth"], function (RouteCollector $router) {
App::$collector->group(["prefix" => "user_stage"], function (CGRouteCollector $router) {
App::$collector->get('/', [\app\modules\user_stage\controllers\UserStageController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\modules\user_stage\controllers\UserStageController::class, 'actionIndex']);
App::$collector->get('/create', [\app\modules\user_stage\controllers\UserStageController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\user_stage\controllers\UserStageController::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\app\modules\user_stage\controllers\UserStageController::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\modules\user_stage\controllers\UserStageController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\modules\user_stage\controllers\UserStageController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\modules\user_stage\controllers\UserStageController::class, 'actionDelete']);
App::$collector->get('/set_stage/{stage_id}/{stage_status}/{user_id}', [\app\modules\user_stage\controllers\UserStageController::class, 'actionSetStage']);
});
});
});

View File

@@ -0,0 +1,88 @@
<?php
namespace kernel\app_modules\user_stage\services;
use kernel\helpers\Debug;
use kernel\app_modules\user_stage\models\UserStage;
use kernel\FormModel;
use kernel\helpers\Slug;
class UserStageService
{
public function create(FormModel $form_model): false|UserStage
{
$model = new UserStage();
// Пример заполнения:
$model->description = $form_model->getItem('description');
$model->start_date = $form_model->getItem('start_date');
$model->end_date = $form_model->getItem('end_date');
$model->title = $form_model->getItem('title');
$model->position = $form_model->getItem('position');
$model->status = $form_model->getItem('status');
$model->user_fields = $form_model->getItem('user_fields');
$model->slug = Slug::createSlug($form_model->getItem('title'), UserStage::class);
if ($model->save()) {
return $model;
}
return false;
}
public function update(FormModel $form_model, UserStage $user_stage): false|UserStage
{
// Пример обновления:
$user_stage->description = $form_model->getItem('description');
$user_stage->start_date = $form_model->getItem('start_date');
$user_stage->end_date = $form_model->getItem('end_date');
$user_stage->title = $form_model->getItem('title');
$user_stage->position = $form_model->getItem('position');
$user_stage->status = $form_model->getItem('status');
$user_stage->user_fields = $form_model->getItem('user_fields');
if ($user_stage->save()) {
return $user_stage;
}
return false;
}
public static function getStageClass(UserStage $stage): string
{
if ($stage->pivot->status === 1){
return "grey_border";
}
elseif ($stage->pivot->status === 2){
return "blue_border";
}
else {
return "green_border";
}
}
public static function getStageStatusText(UserStage $stage): string
{
if ($stage->pivot->status === 1){
return "Не доступен";
}
elseif ($stage->pivot->status === 2){
return "Открыт";
}
else {
return "Завершен";
}
}
public static function getStageStyle(UserStage $stage): string
{
if ($stage->pivot->status === 1){
return "style='background-color: rgba(255, 193, 7, 0.1); color: #ffc107;'";
}
elseif ($stage->pivot->status === 2){
return "style='background-color: rgba(13, 202, 240, 0.1); color: #0dcaf0;'";
}
else {
return "style='background-color: rgba(25, 135, 84, 0.1); color: #198754;'";
}
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* @var UserStage $model
*/
use kernel\app_modules\user_stage\models\UserStage;
$form = new \itguild\forms\ActiveForm();
$form->beginForm(isset($model) ? "/admin/user_stage/edit/" . $model->id : "/admin/user_stage", 'multipart/form-data');
// Пример формы:
$form->field(\itguild\forms\inputs\TextInput::class, 'title', [
'class' => "form-control",
'placeholder' => 'Заголовок',
'value' => $model->title ?? ''
])
->setLabel("Заголовок")
->render();
$form->field(\itguild\forms\inputs\TextArea::class, 'description', [
'class' => "form-control",
'placeholder' => 'Описание',
'value' => $model->description ?? ''
])
->setLabel("Описание")
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'position', [
'class' => "form-control",
'placeholder' => 'Позиция',
'type' => 'number',
'value' => $model->position ?? ''
])
->setLabel("Позиция")
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'start_date', [
'class' => "form-control",
'placeholder' => 'Начало',
'type' => 'date',
'value' => $model->dateStartFormatedToForm ?? ''
])
->setLabel("Начало")
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'end_date', [
'class' => "form-control",
'placeholder' => 'Конец',
'type' => 'date',
'value' => $model->dateEndFormatedToForm ?? ''
])
->setLabel("Конец")
->render();
$form->field(\itguild\forms\inputs\TextArea::class, 'user_fields', [
'class' => "form-control",
'placeholder' => 'Поля пользователя',
'value' => $model->user_fields ?? ''
])
->setLabel("Поля пользователя")
->render();
$form->field(\itguild\forms\inputs\Select::class, 'status', [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(UserStage::getStatus())
->render();
/*
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel("Пользователи")
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
->render();
*/
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@@ -0,0 +1,83 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user_stage
* @var int $page_number
* @var \kernel\CgView $view
*/
use kernel\app_modules\user_stage\models\UserStage;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;
$view->setTitle("Список user_stage");
$view->setMeta([
'description' => 'Список user_stage системы'
]);
//Для использования таблицы с моделью, необходимо создать таблицу в базе данных
$table = new ListEloquentTable(new EloquentDataProvider(UserStage::class, [
'currentPage' => $page_number,
'perPage' => 8,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user_stage"
]));
//$table = new \Itguild\Tables\ListJsonTable(json_encode(
// [
// 'meta' => [
// 'total' => 0,
// 'totalWithFilters' => 0,
// 'columns' => [
// 'title',
// 'slug',
// 'status',
// ],
// 'perPage' => 5,
// 'currentPage' => 1,
// 'baseUrl' => '/admin/some',
// 'params' => [
// 'class' => 'table table-bordered',
// 'border' => 2
// ]
// ],
// 'filters' => [],
// 'data' => [],
// ]
//));
// Пример фильтра
$table->columns([
'title' => [
'filter' => [
'class' => \Itguild\Tables\Filter\InputTextFilter::class,
'value' => $get['title'] ?? ''
]
],
"status" => [
"value" => function ($cell) {
return UserStage::getStatus()[$cell];
}
]
]);
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/user_stage/create'])->run();
});
$table->addAction(function ($row) {
return IconBtnViewWidget::create(['url' => '/admin/user_stage/view/' . $row['id']])->run();
});
$table->addAction(function ($row) {
return IconBtnEditWidget::create(['url' => '/admin/user_stage/update/' . $row['id']])->run();
});
$table->addAction(function ($row) {
return IconBtnDeleteWidget::create(['url' => '/admin/user_stage/delete/' . $row['id']])->run();
});
$table->create();
$table->render();

View File

@@ -0,0 +1,31 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user_stage
*/
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnListWidget;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($user_stage, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user_stage",
]));
$table->beforePrint(function () use ($user_stage) {
$btn = IconBtnListWidget::create(['url' => '/admin/user_stage'])->run();
$btn .= IconBtnEditWidget::create(['url' => '/admin/user_stage/update/' . $user_stage->id])->run();
$btn .= IconBtnDeleteWidget::create(['url' => '/admin/user_stage/delete/' . $user_stage->id])->run();
return $btn;
});
$table->rows([
'status' => (function ($data) {
return \kernel\app_modules\user_stage\models\UserStage::getStatus()[$data];
})
]);
$table->create();
$table->render();

View File

@@ -0,0 +1,42 @@
<?php
namespace kernel\app_themes\svo;
use kernel\modules\menu\service\MenuService;
use kernel\modules\option\service\OptionService;
use kernel\services\MigrationService;
class SvoTheme
{
public MenuService $menuService;
public MigrationService $migrationService;
public OptionService $optionService;
public function __construct()
{
$this->menuService = new MenuService();
$this->migrationService = new MigrationService();
$this->optionService = new OptionService();
}
/**
* @throws \Exception
*/
public function init(): void
{
OptionService::createFromParams('main_news_slider', json_encode(['ids' => []]), 'Слайдер на главной');
$this->menuService->createItem([
"label" => "Настройки темы",
"url" => "/admin/svo-theme/settings",
"slug" => "svo_theme_settings",
]);
}
public function deactivate(): void
{
OptionService::removeOptionByKey('main_news_slider');
$this->menuService->removeItemBySlug("svo_theme_settings");
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace kernel\app_themes\svo\services;
class SvoThemeService
{
}

View File

@@ -49,6 +49,9 @@ class AdminConsoleController extends ConsoleController
$out = $this->migrationService->runAtPath("kernel/modules/secure/migrations");
$this->out->r("create secret_code table", "green");
$out = $this->migrationService->runAtPath("kernel/modules/notification/migrations");
$this->out->r("create notification table", "green");
$this->optionService->createFromParams(
key: "admin_theme_paths",
value: "{\"paths\": [\"{KERNEL_ADMIN_THEMES}\", \"{APP}/admin_themes\"]}",
@@ -170,6 +173,13 @@ class AdminConsoleController extends ConsoleController
]);
$this->out->r("create item menu option", "green");
$this->menuService->createItem([
"label" => "Уведомления",
"url" => "/admin/notification",
"slug" => "notification"
]);
$this->out->r("create notification option", "green");
$user = new CreateUserForm();
$user->load([
'username' => 'admin',

View File

@@ -24,7 +24,7 @@ class SMTP
/**
* @throws Exception
*/
public function send_html(array $params)
public function send_html(array $params): bool
{
if (!isset($params['address'])){
return false;
@@ -35,6 +35,6 @@ class SMTP
$body = $params['body'] ?? 'Нет информации';
$this->mail->msgHTML($body);
$this->mail->send();
return $this->mail->send();
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace kernel\modules\notification;
use kernel\Flash;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\user\models\User;
class NotificationDispatcher
{
protected array $channels = [];
public function addChannel(string $channelName, NotificationChannelInterface $channel): void
{
$this->channels[$channelName] = $channel;
}
public function dispatch(NotificationMessage $notification, User $user): void
{
foreach ($notification->via() as $channelName) {
if (isset($this->channels[$channelName])) {
try {
$this->channels[$channelName]->send($notification, $user);
} catch (\Exception $e) {
Flash::setMessage("error", $e->getMessage());
}
}
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace kernel\modules\notification;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
use kernel\services\MigrationService;
class NotificationModule extends Module
{
public MenuService $menuService;
public MigrationService $migrationService;
public function __construct()
{
$this->menuService = new MenuService();
$this->migrationService = new MigrationService();
}
/**
* @throws \Exception
*/
public function init(): void
{
$this->migrationService->runAtPath("kernel/modules/notification/migrations");
$this->menuService->createItem([
"label" => "Уведомления",
"url" => "/admin/notification",
"slug" => "notification"
]);
}
/**
* @throws \Exception
*/
public function deactivate(): void
{
$this->migrationService->rollbackAtPath("kernel/modules/notification/migrations");
$this->menuService->removeItemBySlug("notification");
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace kernel\modules\notification\channels;
use kernel\Flash;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\notification\models\User;
class DatabaseChannel implements NotificationChannelInterface
{
public function send(NotificationMessage $notification, User $user): bool
{
try {
$user->notifications()->create([
'message' => $notification->getMessage(),
'data' => $notification->toArray()
]);
return true;
} catch (\Exception $e) {
Flash::setMessage("error", $e->getMessage());
return false;
}
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace kernel\modules\notification\channels;
use kernel\helpers\SMTP;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\user\models\User;
use PHPMailer\PHPMailer\Exception;
class EmailChannel implements NotificationChannelInterface
{
/**
* @throws Exception
*/
public function send(NotificationMessage $notification, User $user): bool
{
$smtp = new SMTP();
// Здесь можно использовать Laravel Mail
// \Illuminate\Support\Facades\Mail::to($user->email)
// ->send(new \App\Mail\NotificationMail(
// $notification->getSubject(),
// $notification->getMessage()
// ));
return $smtp->send_html([
'address' => $user->email,
'subject' => $notification->getSubject(),
'body' => $notification->getMessage(),
'from_name' => $_ENV['MAIL_SMTP_USERNAME'],
]);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace kernel\modules\notification\channels;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\user\models\User;
class SmsChannel implements NotificationChannelInterface
{
public function send(NotificationMessage $notification, User $user): bool
{
if (empty($user->phone)) {
return false;
}
// Интеграция с SMS-сервисом
//$smsService = new \App\Services\SmsService();
//return $smsService->send($user->phone, $notification->getMessage());
return true;
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace kernel\modules\notification\channels;
use kernel\Flash;
use kernel\modules\notification\contracts\NotificationChannelInterface;
use kernel\modules\notification\contracts\NotificationMessage;
use kernel\modules\notification\models\User;
class TelegramChannel implements NotificationChannelInterface
{
protected string $botToken;
public function __construct(string $botToken)
{
$this->botToken = $botToken;
}
public function send(NotificationMessage $notification, User $user): bool
{
if (empty($user->telegram_chat_id)) {
return false;
}
$httpClient = new \GuzzleHttp\Client();
try {
$response = $httpClient->post("https://api.telegram.org/bot{$this->botToken}/sendMessage", [
'form_params' => [
'chat_id' => $user->telegram_chat_id,
'text' => $notification->getMessage(),
'parse_mode' => 'HTML'
]
]);
return $response->getStatusCode() === 200;
} catch (\Exception $e) {
Flash::setMessage("error", $e->getMessage());
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace kernel\modules\notification\contracts;
use kernel\modules\notification\models\User;
interface NotificationChannelInterface
{
public function send(NotificationMessage $notification, User $user): bool;
}

View File

@@ -0,0 +1,31 @@
<?php
namespace kernel\modules\notification\contracts;
abstract class NotificationMessage
{
protected array $channels = [];
abstract public function getMessage(): string;
abstract public function getSubject(): string;
public function via(): array
{
return $this->channels;
}
public function addChannel(string $channel): void
{
if (!in_array($channel, $this->channels)) {
$this->channels[] = $channel;
}
}
public function toArray(): array
{
return [
'message' => $this->getMessage(),
'subject' => $this->getSubject(),
];
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace kernel\modules\notification\controllers;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\modules\notification\models\forms\CreateNotificationForm;
use kernel\modules\notification\models\Notification;
use kernel\modules\notification\service\NotificationService;
use kernel\modules\option\models\forms\CreateOptionForm;
class NotificationController extends AdminController
{
private NotificationService $optionService;
public function init(): void
{
parent::init();
$this->cgView->viewPath = KERNEL_MODULES_DIR . '/notification/views/';
$this->optionService = new NotificationService();
}
public function actionCreate(): void
{
$this->cgView->render('form.php');
}
#[NoReturn] public function actionAdd(): void
{
$optionForm = new CreateNotificationForm();
$optionForm->load($_REQUEST);
if ($optionForm->validate()) {
$option = $this->optionService->create($optionForm);
if ($option) {
Flash::setMessage("success", "notification успешно создана.");
$this->redirect('/admin/notification');
}
}
Flash::setMessage("error", $optionForm->getErrorsStr());
$this->redirect('/admin/notification/create');
}
public function actionIndex($page_number = 1): void
{
$this->cgView->render('index.php', ['page_number' => $page_number]);
}
/**
* @throws \Exception
*/
public function actionView(int $id): void
{
$option = Notification::find($id);
if (!$option) {
throw new \Exception('notification not found');
}
$this->cgView->render("view.php", ['option' => $option]);
}
/**
* @throws \Exception
*/
public function actionUpdate(int $id): void
{
$model = Notification::find($id);
if (!$model) {
throw new \Exception('notification not found');
}
$this->cgView->render("form.php", ['model' => $model]);
}
/**
* @throws \Exception
*/
public function actionEdit(int $id): void
{
$option = Notification::find($id);
if (!$option) {
throw new \Exception('Option not found');
}
$optionForm = new CreateOptionForm();
$optionForm->load($_REQUEST);
if ($optionForm->validate()) {
$option = $this->optionService->update($optionForm, $option);
if ($option) {
$this->redirect('/admin/notification/view/' . $option->id);
}
}
$this->redirect('/admin/notification/update/' . $id);
}
#[NoReturn] public function actionDelete(int $id): void
{
Notification::find($id)->delete();
Flash::setMessage("success", "notification успешно удалена.");
$this->redirect('/admin/notification');
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "Notifications",
"version": "0.1",
"author": "ITGuild",
"slug": "notification",
"type": "entity",
"description": "Notifications module",
"module_class": "kernel\\modules\\notification\\NotificationModule",
"module_class_file": "{KERNEL_MODULES}/notification/NotificationModule.php",
"routs": "routs/notification.php",
"migration_path": "migrations",
"dependence": "user,menu"
}

View File

@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
\kernel\App::$db->schema->create('notification', function (Blueprint $table) {
$table->id();
// Связь с пользователем
$table->unsignedBigInteger('user_id');
// Основные данные уведомления
$table->string('type')->index(); // Класс уведомления (например, App\Notifications\OrderCreated)
$table->text('message'); // Текст уведомления
$table->string('subject')->nullable(); // Тема (для email)
$table->json('data')->nullable(); // Дополнительные данные в JSON
// Статус уведомления
$table->boolean('is_read')->default(false);
$table->integer('status')->default(1);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
\kernel\App::$db->schema->dropIfExists('notification');
}
};

View File

@@ -0,0 +1,71 @@
<?php
namespace kernel\modules\notification\models;
use Illuminate\Database\Eloquent\Model;
use kernel\modules\user\models\User;
/**
* @property int $id
* @property int $user_id
* @property bool $is_read
* @property array|string $data
* @property string $type
* @property string $message
* @property string $subject
* @property int $status
*/
class Notification extends Model
{
const DISABLE_STATUS = 0;
const TO_SEND_STATUS = 1;
const SENT_STATUS = 2;
protected $table = 'notification';
protected $fillable = ['user_id', 'message', 'is_read', 'data', 'type', 'subject', 'status'];
protected $casts = [
'is_read' => 'boolean',
'data' => 'array'
];
public static function labels(): array
{
return [
'user_id' => 'Пользователь',
'message' => 'Сообщение',
'subject' => 'Тема',
'is_read' => 'Прочитано',
'data' => 'Данные',
'type' => 'Тип',
'status' => 'Статус'
];
}
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
public function markAsRead(): static
{
$this->update(['is_read' => true]);
return $this;
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::TO_SEND_STATUS => "На отправку",
self::SENT_STATUS => "Отправлено",
];
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace kernel\modules\notification\models;
class User extends \kernel\modules\user\models\User
{
public function notifications(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(Notification::class);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace kernel\modules\notification\models\forms;
use kernel\FormModel;
/**
* @property string $key
* @property string $value
* @property string $label
* @property integer $status
*/
class CreateNotificationForm extends FormModel
{
public function rules(): array
{
return [
'user_id' => 'required|integer',
'message' => 'required',
'is_read' => '',
'data' => '',
'type' => 'required',
'subject' => '',
];
}
}

View File

@@ -0,0 +1,19 @@
<?php
use kernel\App;
use Phroute\Phroute\RouteCollector;
App::$collector->group(["prefix" => "admin"], function (RouteCollector $router) {
App::$collector->group(["before" => "auth"], function (RouteCollector $router) {
App::$collector->group(["prefix" => "notification"], callback: function (RouteCollector $router) {
App::$collector->get('/', [\kernel\modules\notification\controllers\NotificationController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\kernel\modules\notification\controllers\NotificationController::class, 'actionIndex']);
App::$collector->get('/create', [\kernel\modules\notification\controllers\NotificationController::class, 'actionCreate']);
App::$collector->post("/", [\kernel\modules\notification\controllers\NotificationController::class, 'actionAdd']);
App::$collector->get('/view/{id}', [\kernel\modules\notification\controllers\NotificationController::class, 'actionView']);
App::$collector->any('/update/{id}', [\kernel\modules\notification\controllers\NotificationController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\kernel\modules\notification\controllers\NotificationController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\kernel\modules\notification\controllers\NotificationController::class, 'actionDelete']);
});
});
});

View File

@@ -0,0 +1,57 @@
<?php
namespace kernel\modules\notification\service;
use kernel\FormModel;
use kernel\modules\notification\models\Notification;
class NotificationService
{
public function create(FormModel $form_model): false|Notification
{
$model = new Notification();
$model->user_id = $form_model->getItem('user_id');
$model->message = $form_model->getItem('message');
$model->is_read = $form_model->getItem('is_read');
$model->data = $form_model->getItem('data');
$model->type = $form_model->getItem('type');
$model->subject = $form_model->getItem('subject');
$model->status = $form_model->getItem('status');
if ($model->save()) {
return $model;
}
return false;
}
public function update(FormModel $form_model, Notification $notification): false|Notification
{
$notification->user_id = $form_model->getItem('user_id');
$notification->message = $form_model->getItem('message');
$notification->is_read = $form_model->getItem('is_read');
$notification->data = $form_model->getItem('data');
$notification->type = $form_model->getItem('type');
$notification->subject = $form_model->getItem('subject');
$notification->status = $form_model->getItem('status');
if ($notification->save()) {
return $notification;
}
return false;
}
// public function createOptionArr(): array
// {
// foreach (Option::all()->toArray() as $option) {
// $optionArr[$option['id']] = $option['key'];
// }
// if (!empty($optionArr)) {
// return $optionArr;
// }
// return [];
// }
}

View File

@@ -0,0 +1,16 @@
<?php
namespace kernel\modules\option\table\columns;
use Itguild\Tables\ActionColumn\ActionColumn;
class OptionDeleteActionColumn extends ActionColumn
{
protected string $prefix = "/delete/";
public function fetch(): string
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-danger'>Удалить</a> ";
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace kernel\modules\option\table\columns;
use Itguild\Tables\ActionColumn\ActionColumn;
class OptionEditActionColumn extends ActionColumn
{
protected string $prefix = "/update/";
public function fetch(): string
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-success'>Редактировать</a> ";
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace kernel\modules\option\table\columns;
use Itguild\Tables\ActionColumn\ActionColumn;
class OptionViewActionColumn extends ActionColumn
{
protected string $prefix = "/";
public function fetch()
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-primary'>Просмотр</a> ";
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* @var Notification $model
*/
use itguild\forms\ActiveForm;
use kernel\modules\notification\models\Notification;
$form = new ActiveForm();
$form->beginForm(isset($model) ? "/admin/notification/edit/" . $model->id : "/admin/notification");
$form->field(class: \itguild\forms\inputs\Select::class, name: "user_id", params: [
'class' => "form-control",
'value' => $model->user_id ?? ''
])
->setLabel(Notification::labels()['user_id'])
->setOptions(\kernel\modules\user\service\UserService::createUsernameArr())
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'subject', [
'class' => "form-control",
'placeholder' => Notification::labels()['subject'],
'value' => $model->subject ?? ''
])
->setLabel(Notification::labels()['subject'])
->render();
$form->field(\itguild\forms\inputs\TextInput::class, 'type', [
'class' => "form-control",
'placeholder' => Notification::labels()['type'],
'value' => $model->type ?? ''
])
->setLabel(Notification::labels()['type'])
->render();
$form->field(\itguild\forms\inputs\TextArea::class, 'message', [
'class' => "form-control",
'placeholder' => Notification::labels()['message'],
'value' => $model->message ?? ''
])
->setLabel(Notification::labels()['message'])
->render();
$form->field(\itguild\forms\inputs\Checkbox::class, 'is_read', [
'class' => "form-check-input",
'placeholder' => Notification::labels()['is_read'],
'value' => $model->is_read ?? ''
])
->setLabel(Notification::labels()['is_read'])
->render();
$form->field(\itguild\forms\inputs\Select::class, 'status', [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(Notification::getStatus())
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@@ -0,0 +1,44 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $options
* @var int $page_number
*/
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\modules\notification\models\Notification;
use kernel\widgets\IconBtn\IconBtnCreateWidget;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnViewWidget;
$table = new ListEloquentTable(new EloquentDataProvider(Notification::class, [
'current_page' => $page_number,
'per_page' => 5,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/notification",
]));
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/notification/create'])->run();
});
$table->columns([
"status" => [
"value" => function ($cell) {
return Notification::getStatus()[$cell];
}]
]);
$table->addAction(function($row) {
return IconBtnViewWidget::create(['url' => '/admin/notification/view/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnEditWidget::create(['url' => '/admin/Notification/update/' . $row['id']])->run();
});
$table->addAction(function($row) {
return IconBtnDeleteWidget::create(['url' => '/admin/Notification/delete/' . $row['id']])->run();
});
$table->create();
$table->render();

View File

@@ -0,0 +1,32 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $option
*/
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn;
use kernel\widgets\IconBtn\IconBtnDeleteWidget;
use kernel\widgets\IconBtn\IconBtnEditWidget;
use kernel\widgets\IconBtn\IconBtnListWidget;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($option, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/user",
]));
$table->beforePrint(function () use ($option) {
$btn = IconBtnListWidget::create(['url' => '/admin/option'])->run();
$btn .= IconBtnEditWidget::create(['url' => '/admin/option/update/' . $option->id])->run();
$btn .= IconBtnDeleteWidget::create(['url' => '/admin/option/delete/' . $option->id])->run();
return $btn;
});
$table->rows([
'status' => (function ($data) {
return \kernel\modules\option\models\Notification::getStatus()[$data];
})
]);
$table->create();
$table->render();

View File

@@ -8,6 +8,7 @@ use kernel\App;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\Mailing;
use kernel\modules\secure\models\forms\ChangePasswordForm;
use kernel\modules\secure\models\forms\LoginEmailForm;
use kernel\modules\secure\models\forms\LoginForm;
use kernel\modules\secure\models\forms\RegisterForm;
@@ -40,7 +41,7 @@ class SecureController extends AdminController
// $this->cgView->render('login.php');
}
#[NoReturn] public function actionAuth(): void
#[NoReturn] public function actionAuth($basePath = '/admin'): void
{
$loginForm = new LoginForm();
$loginForm->load($_REQUEST);
@@ -51,19 +52,36 @@ class SecureController extends AdminController
else {
$field = "username";
}
$user = $this->userService->getByField($field, $loginForm->getItem("username"));
if (!$user){
Flash::setMessage("error", "User not found.");
$this->redirect("/admin/login", code: 302);
$this->redirect($basePath . "/login", code: 302);
}
if (password_verify($loginForm->getItem("password"), $user->password_hash)) {
setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
$this->redirect("/admin", code: 302);
$this->redirect($basePath . '/', code: 302);
} else {
Flash::setMessage("error", "Username or password incorrect.");
$this->redirect("/admin/login", code: 302);
$this->redirect($basePath . "/login", code: 302);
}
}
#[NoReturn] public function actionChangePassword($basePath = '/admin'): void
{
$changePasswordForm = new ChangePasswordForm();
$changePasswordForm->load($_REQUEST);
$user = UserService::getAuthUser();
if (password_verify($changePasswordForm->getItem("old_password"), $user->password_hash)) {
$user->password_hash = password_hash($changePasswordForm->getItem("new_password"), PASSWORD_DEFAULT);
$user->save();
Flash::setMessage("success", "Пароль успешно изменен.");
$this->redirect($basePath . '', code: 302);
} else {
Flash::setMessage("error", "Username or password incorrect.");
$this->redirect($basePath . "", code: 302);
}
}
@@ -148,25 +166,25 @@ class SecureController extends AdminController
$this->cgView->render('register.php');
}
public function actionRegistration(): void
public function actionRegistration($basePath = '/admin'): void
{
$regForm = new RegisterForm();
$regForm->load($_REQUEST);
if ($this->userService->getByField('username', $regForm->getItem("username"))) {
Flash::setMessage("error", "Username already exists.");
$this->redirect("/admin/register", code: 302);
$this->redirect($basePath . "/register", code: 302);
}
if ($this->userService->getByField('email', $regForm->getItem("email"))) {
Flash::setMessage("error", "Email already exists.");
$this->redirect("/admin/register", code: 302);
$this->redirect($basePath . "/register", code: 302);
}
$user = $this->userService->create($regForm);
if ($user){
setcookie('user_id', $user->id, time()+60*60*24, '/', $_SERVER['SERVER_NAME'], false);
$this->redirect("/admin", code: 302);
$this->redirect($basePath . "/", code: 302);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace kernel\modules\secure\models\forms;
use kernel\FormModel;
class ChangePasswordForm extends FormModel
{
public function rules(): array
{
return [
'old_password' => 'required|min-str-len:6|max-str-len:50',
'new_password' => 'required|min-str-len:6|max-str-len:50',
];
}
}

View File

@@ -7,6 +7,7 @@ use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\EntityRelation;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\modules\user\models\forms\CreateUserForm;
use kernel\modules\user\models\User;
@@ -55,6 +56,7 @@ class UserController extends AdminController
$this->redirect("/admin/user/view/" . $user->id);
}
}
Flash::setMessage("error", $userForm->getErrorsStr());
$this->redirect("/admin/user/create");
}

View File

@@ -2,6 +2,7 @@
namespace kernel\modules\user\service;
use itguild\forms\ActiveForm;
use kernel\FormModel;
use kernel\helpers\Debug;
use kernel\modules\user\models\User;
@@ -122,4 +123,12 @@ class UserService
$user->save();
}
public static function getList(): array
{
return User::select('id', 'username')->get()
->pluck('username', 'id')
->toArray();
}
}

View File

@@ -47,6 +47,8 @@ if (!isset($model)) {
$model = new User();
}
$entityRelations->renderEntityAdditionalPropertyFormBySlug("user", $model);
?>
<div class="row">
<div class="col-sm-2">

View File

@@ -1,7 +1,7 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $user
* @var User $user
*/
use kernel\modules\user\models\User;
@@ -54,4 +54,6 @@ $table->rows([
}
]);
$table->create();
$table->render();
$table->render();
\kernel\App::$hook->runHooksByEntity('user_view', ['user' => $user]);

View File

@@ -278,6 +278,17 @@ class ModuleService
return $routs;
}
public function setModulesHooks(): void
{
$hooks = [];
$modules = $this->getActiveModules();
foreach ($modules as $module) {
if (isset($module['hooks'])) {
include $module['path'] . "/" . $module['hooks'];
}
}
}
/**
* @return array
*/

View File

@@ -59,7 +59,7 @@ $table->columns([
'value' => $get['title'] ?? ''
]
],
]
]);
$table->beforePrint(function () {
return IconBtnCreateWidget::create(['url' => '/admin/{slug}/create'])->run();