big restructure
This commit is contained in:
140
lib/Repository/Access/PermissionRepository.php
Normal file
140
lib/Repository/Access/PermissionRepository.php
Normal file
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository\Access;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class PermissionRepository
|
||||
{
|
||||
public static function list(): array
|
||||
{
|
||||
$rows = DB::select('select id, `key`, description, active, is_system, created from permissions order by `key` asc');
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['permissions'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function listActive(): array
|
||||
{
|
||||
$rows = DB::select(
|
||||
'select id, `key`, description, active, is_system, created from permissions where active = 1 order by `key` asc'
|
||||
);
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['permissions'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$allowedOrder = [
|
||||
'key' => '`key`',
|
||||
'description' => 'description',
|
||||
'active' => 'active',
|
||||
'created' => 'created',
|
||||
];
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, array_keys($allowedOrder), 'key', 'asc');
|
||||
$orderBy = $allowedOrder[$order] ?? $allowedOrder['key'];
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
RepoQuery::addLikeFilter($where, $params, ['permissions.`key`', 'permissions.description'], $search);
|
||||
$activeValue = array_key_exists('active', $options) ? $options['active'] : null;
|
||||
RepoQuery::addEnumFilter($where, $params, $activeValue, [
|
||||
['aliases' => ['1', 'true', 'active'], 'sql' => 'permissions.active = 1'],
|
||||
['aliases' => ['0', 'false', 'inactive'], 'sql' => 'permissions.active = 0'],
|
||||
]);
|
||||
$whereSql = $where ? ' where ' . implode(' and ', $where) : '';
|
||||
|
||||
$total = DB::selectValue('select count(*) from permissions' . $whereSql, ...$params);
|
||||
$query = 'select id, `key`, description, active, is_system, created from permissions' . $whereSql .
|
||||
' order by ' . $orderBy . ' ' . $dir . ' limit ? offset ?';
|
||||
$queryParams = array_merge($params, [(string) $limit, (string) $offset]);
|
||||
$rows = DB::select($query, ...$queryParams);
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['permissions'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return ['data' => $list, 'total' => (int) $total];
|
||||
}
|
||||
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, `key`, description, active, is_system, created from permissions where id = ? limit 1',
|
||||
(string) $id
|
||||
);
|
||||
$data = $row['permissions'] ?? $row;
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
public static function findByKey(string $key): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, `key`, description, active, is_system, created from permissions where `key` = ? limit 1',
|
||||
$key
|
||||
);
|
||||
$data = $row['permissions'] ?? $row;
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
public static function create(array $data): ?int
|
||||
{
|
||||
$key = trim((string) ($data['key'] ?? ''));
|
||||
$desc = trim((string) ($data['description'] ?? ''));
|
||||
$active = (int) ($data['active'] ?? 1);
|
||||
$isSystem = (int) ($data['is_system'] ?? 0);
|
||||
$result = DB::insert(
|
||||
'insert into permissions (`key`, description, active, is_system, created) values (?,?,?,?,NOW())',
|
||||
$key,
|
||||
$desc !== '' ? $desc : null,
|
||||
(string) $active,
|
||||
(string) $isSystem
|
||||
);
|
||||
return $result ? (int) $result : null;
|
||||
}
|
||||
|
||||
public static function update(int $id, array $data): bool
|
||||
{
|
||||
$key = trim((string) ($data['key'] ?? ''));
|
||||
$desc = trim((string) ($data['description'] ?? ''));
|
||||
$active = (int) ($data['active'] ?? 1);
|
||||
$isSystem = (int) ($data['is_system'] ?? 0);
|
||||
$result = DB::update(
|
||||
'update permissions set `key` = ?, description = ?, active = ?, is_system = ? where id = ?',
|
||||
$key,
|
||||
$desc !== '' ? $desc : null,
|
||||
(string) $active,
|
||||
(string) $isSystem,
|
||||
(string) $id
|
||||
);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function delete(int $id): bool
|
||||
{
|
||||
$result = DB::delete('delete from permissions where id = ?', (string) $id);
|
||||
return (bool) $result;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Access;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -79,7 +79,9 @@ class RolePermissionRepository
|
||||
return [];
|
||||
}
|
||||
$rows = DB::select(
|
||||
'select p.`key` as `key` from role_permissions rp join permissions p on p.id = rp.permission_id ' .
|
||||
'select p.`key` as `key` from role_permissions rp ' .
|
||||
'join roles r on r.id = rp.role_id and r.active = 1 ' .
|
||||
'join permissions p on p.id = rp.permission_id and p.active = 1 ' .
|
||||
'where rp.role_id in (???)',
|
||||
array_map('strval', $ids)
|
||||
);
|
||||
@@ -106,8 +108,8 @@ class RolePermissionRepository
|
||||
}
|
||||
$rows = DB::select(
|
||||
'select rp.permission_id as permission_id, p.`key` as `key`, p.description as `description`, r.description as role ' .
|
||||
'from role_permissions rp join permissions p on p.id = rp.permission_id ' .
|
||||
'join roles r on r.id = rp.role_id where rp.role_id in (???) ' .
|
||||
'from role_permissions rp join permissions p on p.id = rp.permission_id and p.active = 1 ' .
|
||||
'join roles r on r.id = rp.role_id and r.active = 1 where rp.role_id in (???) ' .
|
||||
'order by p.`key` asc, r.description asc',
|
||||
array_map('strval', $ids)
|
||||
);
|
||||
@@ -1,8 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Access;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class RoleRepository
|
||||
{
|
||||
@@ -32,7 +33,15 @@ class RoleRepository
|
||||
public static function list(): array
|
||||
{
|
||||
$rows = DB::select(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from roles order by id desc'
|
||||
'select id, uuid, description, code, active, created_by, modified_by, created, modified from roles order by id desc'
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
|
||||
public static function listActive(): array
|
||||
{
|
||||
$rows = DB::select(
|
||||
'select id, uuid, description, code, active, created_by, modified_by, created, modified from roles where active = 1 order by description asc'
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
@@ -53,45 +62,43 @@ class RoleRepository
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
public static function listActiveIds(): array
|
||||
{
|
||||
$rows = DB::select('select id from roles where active = 1');
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$ids = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['roles'] ?? $row;
|
||||
if (is_array($data) && isset($data['id'])) {
|
||||
$ids[] = (int) $data['id'];
|
||||
}
|
||||
}
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
if ($limit < 1) {
|
||||
$limit = 10;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$order = (string) ($options['order'] ?? 'id');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'desc'));
|
||||
$allowedOrder = ['id', 'uuid', 'description', 'created', 'modified'];
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = 'id';
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = 'desc';
|
||||
}
|
||||
$allowedOrder = ['id', 'uuid', 'description', 'code', 'active', 'created', 'modified'];
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder);
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
$where[] = '(description like ? or uuid like ?)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
RepoQuery::addLikeFilter($where, $params, ['description', 'uuid', 'code'], $search);
|
||||
$activeValue = array_key_exists('active', $options) ? $options['active'] : null;
|
||||
RepoQuery::addEnumFilter($where, $params, $activeValue, [
|
||||
['aliases' => ['1', 'true', 'active'], 'sql' => 'roles.active = 1'],
|
||||
['aliases' => ['0', 'false', 'inactive'], 'sql' => 'roles.active = 0'],
|
||||
]);
|
||||
|
||||
$whereSql = $where ? (' where ' . implode(' and ', $where)) : '';
|
||||
$count = DB::selectValue('select count(*) from roles' . $whereSql, ...$params);
|
||||
$total = $count ? (int) $count : 0;
|
||||
|
||||
$query = 'select id, uuid, description, created_by, modified_by, created, modified from roles' .
|
||||
$query = 'select id, uuid, description, code, active, created_by, modified_by, created, modified from roles' .
|
||||
$whereSql .
|
||||
sprintf(' order by `%s` %s limit ? offset ?', $order, $dir);
|
||||
|
||||
@@ -107,7 +114,7 @@ class RoleRepository
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from roles where id = ? limit 1',
|
||||
'select id, uuid, description, code, active, created_by, modified_by, created, modified from roles where id = ? limit 1',
|
||||
(string) $id
|
||||
);
|
||||
return self::unwrap($row);
|
||||
@@ -116,12 +123,26 @@ class RoleRepository
|
||||
public static function findByUuid(string $uuid): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from roles where uuid = ? limit 1',
|
||||
'select id, uuid, description, code, active, created_by, modified_by, created, modified from roles where uuid = ? limit 1',
|
||||
$uuid
|
||||
);
|
||||
return self::unwrap($row);
|
||||
}
|
||||
|
||||
public static function existsByCode(string $code, int $excludeId = 0): bool
|
||||
{
|
||||
$code = trim($code);
|
||||
if ($code === '') {
|
||||
return false;
|
||||
}
|
||||
if ($excludeId > 0) {
|
||||
$count = DB::selectValue('select count(*) from roles where code = ? and id != ?', $code, (string) $excludeId);
|
||||
} else {
|
||||
$count = DB::selectValue('select count(*) from roles where code = ?', $code);
|
||||
}
|
||||
return $count ? ((int) $count > 0) : false;
|
||||
}
|
||||
|
||||
private static function uuidV4(): string
|
||||
{
|
||||
$data = random_bytes(16);
|
||||
@@ -133,9 +154,11 @@ class RoleRepository
|
||||
public static function create(array $data)
|
||||
{
|
||||
return DB::insert(
|
||||
'insert into roles (uuid, description, created_by, created) values (?,?,?,NOW())',
|
||||
'insert into roles (uuid, description, code, active, created_by, created) values (?,?,?,?,?,NOW())',
|
||||
$data['uuid'] ?? self::uuidV4(),
|
||||
$data['description'],
|
||||
$data['code'] ?? null,
|
||||
$data['active'] ?? 1,
|
||||
$data['created_by'] ?? null
|
||||
);
|
||||
}
|
||||
@@ -144,6 +167,8 @@ class RoleRepository
|
||||
{
|
||||
$fields = [
|
||||
'description' => $data['description'],
|
||||
'code' => $data['code'] ?? null,
|
||||
'active' => $data['active'] ?? 1,
|
||||
];
|
||||
if (array_key_exists('modified_by', $data)) {
|
||||
$fields['modified_by'] = $data['modified_by'];
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Access;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Auth;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Auth;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
class PasswordResetRepository
|
||||
{
|
||||
private static function unwrapList($rows): array
|
||||
{
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['password_resets'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function create(int $userId, string $codeHash, string $expiresAt): ?int
|
||||
{
|
||||
$id = DB::insert(
|
||||
@@ -68,4 +83,22 @@ class PasswordResetRepository
|
||||
);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function listByUserId(int $userId, int $limit = 20): array
|
||||
{
|
||||
if ($userId <= 0) {
|
||||
return [];
|
||||
}
|
||||
if ($limit < 1) {
|
||||
$limit = 20;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
$rows = DB::select(
|
||||
'select id, user_id, expires_at, attempts, used_at, created from password_resets where user_id = ? order by id desc limit ?',
|
||||
(string) $userId,
|
||||
(string) $limit
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
}
|
||||
102
lib/Repository/Auth/RememberTokenRepository.php
Normal file
102
lib/Repository/Auth/RememberTokenRepository.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository\Auth;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
class RememberTokenRepository
|
||||
{
|
||||
private static function unwrapList($rows): array
|
||||
{
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['user_remember_tokens'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function create(int $userId, string $selector, string $tokenHash, string $expiresAt): ?int
|
||||
{
|
||||
$id = DB::insert(
|
||||
'insert into user_remember_tokens (user_id, selector, token_hash, expires_at, created) values (?,?,?,?,NOW())',
|
||||
(string) $userId,
|
||||
$selector,
|
||||
$tokenHash,
|
||||
$expiresAt
|
||||
);
|
||||
return $id ? (int) $id : null;
|
||||
}
|
||||
|
||||
public static function findBySelector(string $selector): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, user_id, selector, token_hash, expires_at, expired_by_admin_at, last_used from user_remember_tokens where selector = ? limit 1',
|
||||
$selector
|
||||
);
|
||||
if (!$row || !isset($row['user_remember_tokens'])) {
|
||||
return null;
|
||||
}
|
||||
return $row['user_remember_tokens'];
|
||||
}
|
||||
|
||||
public static function updateToken(int $id, string $tokenHash, string $expiresAt): bool
|
||||
{
|
||||
$result = DB::update(
|
||||
'update user_remember_tokens set token_hash = ?, expires_at = ?, expired_by_admin_at = NULL, last_used = NOW() where id = ?',
|
||||
$tokenHash,
|
||||
$expiresAt,
|
||||
(string) $id
|
||||
);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function expireAllByAdmin(): int
|
||||
{
|
||||
$result = DB::update(
|
||||
'update user_remember_tokens set expires_at = NOW(), expired_by_admin_at = NOW() where expires_at > NOW()'
|
||||
);
|
||||
return $result !== false ? (int) $result : 0;
|
||||
}
|
||||
|
||||
public static function deleteById(int $id): bool
|
||||
{
|
||||
$result = DB::delete('delete from user_remember_tokens where id = ?', (string) $id);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function deleteByUserId(int $userId): bool
|
||||
{
|
||||
$result = DB::delete('delete from user_remember_tokens where user_id = ?', (string) $userId);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function listByUserId(int $userId, int $limit = 20): array
|
||||
{
|
||||
if ($userId <= 0) {
|
||||
return [];
|
||||
}
|
||||
if ($limit < 1) {
|
||||
$limit = 20;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
$rows = DB::select(
|
||||
'select id, user_id, selector, expires_at, expired_by_admin_at, last_used, created from user_remember_tokens where user_id = ? order by id desc limit ?',
|
||||
(string) $userId,
|
||||
(string) $limit
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
|
||||
public static function countActive(): int
|
||||
{
|
||||
$count = DB::selectValue('select count(*) from user_remember_tokens where expires_at > NOW()');
|
||||
return $count ? (int) $count : 0;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Content;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Content;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Mail;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class MailLogRepository
|
||||
{
|
||||
@@ -65,46 +66,19 @@ class MailLogRepository
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
if ($limit < 1) {
|
||||
$limit = 10;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$order = (string) ($options['order'] ?? 'created_at');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'desc'));
|
||||
$status = trim((string) ($options['status'] ?? ''));
|
||||
$createdFrom = trim((string) ($options['created_from'] ?? ''));
|
||||
$createdTo = trim((string) ($options['created_to'] ?? ''));
|
||||
|
||||
$allowedOrder = ['id', 'created_at', 'sent_at', 'to_email', 'subject', 'status'];
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = 'created_at';
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = 'desc';
|
||||
}
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder, 'created_at', 'desc');
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
$where[] = '(to_email like ? or subject like ? or template like ?)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
if ($status !== '') {
|
||||
$where[] = 'status = ?';
|
||||
$params[] = $status;
|
||||
}
|
||||
RepoQuery::addLikeFilter($where, $params, ['to_email', 'subject', 'template'], $search);
|
||||
RepoQuery::addEqualsFilter($where, $params, $status, 'status = ?');
|
||||
if ($createdFrom !== '') {
|
||||
$where[] = 'created_at >= ?';
|
||||
$params[] = $createdFrom . ' 00:00:00';
|
||||
@@ -1,8 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Org;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class DepartmentRepository
|
||||
{
|
||||
@@ -32,7 +33,7 @@ class DepartmentRepository
|
||||
public static function list(): array
|
||||
{
|
||||
$rows = DB::select(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from departments order by id desc'
|
||||
'select id, uuid, description, code, cost_center, active, created_by, modified_by, created, modified from departments order by id desc'
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
@@ -62,10 +63,10 @@ class DepartmentRepository
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($tenantIds), '?'));
|
||||
$rows = DB::select(
|
||||
'select departments.id, departments.uuid, departments.description, departments.created_by, departments.modified_by, departments.created, departments.modified ' .
|
||||
'select departments.id, departments.uuid, departments.description, departments.code, departments.cost_center, departments.active, departments.created_by, departments.modified_by, departments.created, departments.modified ' .
|
||||
'from departments departments join tenant_departments td on td.department_id = departments.id ' .
|
||||
'where td.tenant_id in (' . $placeholders . ') ' .
|
||||
'group by departments.id, departments.uuid, departments.description, departments.created_by, departments.modified_by, departments.created, departments.modified ' .
|
||||
'where departments.active = 1 and td.tenant_id in (' . $placeholders . ') ' .
|
||||
'group by departments.id, departments.uuid, departments.description, departments.code, departments.cost_center, departments.active, departments.created_by, departments.modified_by, departments.created, departments.modified ' .
|
||||
'order by departments.description asc',
|
||||
...array_map('strval', $tenantIds)
|
||||
);
|
||||
@@ -81,7 +82,7 @@ class DepartmentRepository
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($departmentIds), '?'));
|
||||
$rows = DB::select(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from departments where id in (' . $placeholders . ') order by description asc',
|
||||
'select id, uuid, description, code, cost_center, active, created_by, modified_by, created, modified from departments where active = 1 and id in (' . $placeholders . ') order by description asc',
|
||||
...array_map('strval', $departmentIds)
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
@@ -89,42 +90,31 @@ class DepartmentRepository
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
if ($limit < 1) {
|
||||
$limit = 10;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$tenant = trim((string) ($options['tenant'] ?? ''));
|
||||
$order = (string) ($options['order'] ?? 'id');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'desc'));
|
||||
$allowedOrder = ['id', 'uuid', 'description', 'created', 'modified'];
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = 'id';
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = 'desc';
|
||||
}
|
||||
$allowedOrder = ['id', 'uuid', 'description', 'code', 'cost_center', 'active', 'created', 'modified'];
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder);
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
$where[] = '(description like ? or uuid like ?)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
if ($tenant !== '') {
|
||||
$where[] = "exists (select 1 from tenant_departments td join tenants t on t.id = td.tenant_id and t.status = 'active' where td.department_id = departments.id and t.uuid = ?)";
|
||||
$params[] = $tenant;
|
||||
}
|
||||
RepoQuery::addLikeFilter(
|
||||
$where,
|
||||
$params,
|
||||
['description', 'uuid', 'code', 'cost_center'],
|
||||
$search
|
||||
);
|
||||
$activeValue = array_key_exists('active', $options) ? $options['active'] : null;
|
||||
RepoQuery::addEnumFilter($where, $params, $activeValue, [
|
||||
['aliases' => ['1', 'true', 'active'], 'sql' => 'departments.active = 1'],
|
||||
['aliases' => ['0', 'false', 'inactive'], 'sql' => 'departments.active = 0'],
|
||||
]);
|
||||
RepoQuery::addEqualsFilter(
|
||||
$where,
|
||||
$params,
|
||||
$tenant,
|
||||
"exists (select 1 from tenant_departments td join tenants t on t.id = td.tenant_id and t.status = 'active' where td.department_id = departments.id and t.uuid = ?)"
|
||||
);
|
||||
if (!empty($options['tenantUserId'])) {
|
||||
$tenantUserId = (int) $options['tenantUserId'];
|
||||
if ($tenantUserId > 0) {
|
||||
@@ -168,7 +158,7 @@ class DepartmentRepository
|
||||
$count = DB::selectValue('select count(*) from departments' . $whereSql, ...$params);
|
||||
$total = $count ? (int) $count : 0;
|
||||
|
||||
$query = 'select id, uuid, description, created_by, modified_by, created, modified from departments' .
|
||||
$query = 'select id, uuid, description, code, cost_center, active, created_by, modified_by, created, modified from departments' .
|
||||
$whereSql .
|
||||
sprintf(' order by `%s` %s limit ? offset ?', $order, $dir);
|
||||
|
||||
@@ -244,7 +234,7 @@ class DepartmentRepository
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from departments where id = ? limit 1',
|
||||
'select id, uuid, description, code, cost_center, active, created_by, modified_by, created, modified from departments where id = ? limit 1',
|
||||
(string) $id
|
||||
);
|
||||
return self::unwrap($row);
|
||||
@@ -253,12 +243,26 @@ class DepartmentRepository
|
||||
public static function findByUuid(string $uuid): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, description, created_by, modified_by, created, modified from departments where uuid = ? limit 1',
|
||||
'select id, uuid, description, code, cost_center, active, created_by, modified_by, created, modified from departments where uuid = ? limit 1',
|
||||
$uuid
|
||||
);
|
||||
return self::unwrap($row);
|
||||
}
|
||||
|
||||
public static function existsByCode(string $code, int $excludeId = 0): bool
|
||||
{
|
||||
$code = trim($code);
|
||||
if ($code === '') {
|
||||
return false;
|
||||
}
|
||||
if ($excludeId > 0) {
|
||||
$count = DB::selectValue('select count(*) from departments where code = ? and id != ?', $code, (string) $excludeId);
|
||||
} else {
|
||||
$count = DB::selectValue('select count(*) from departments where code = ?', $code);
|
||||
}
|
||||
return (int) $count > 0;
|
||||
}
|
||||
|
||||
private static function uuidV4(): string
|
||||
{
|
||||
$data = random_bytes(16);
|
||||
@@ -270,9 +274,12 @@ class DepartmentRepository
|
||||
public static function create(array $data)
|
||||
{
|
||||
return DB::insert(
|
||||
'insert into departments (uuid, description, created_by, created) values (?,?,?,NOW())',
|
||||
'insert into departments (uuid, description, code, cost_center, active, created_by, created) values (?,?,?,?,?,?,NOW())',
|
||||
$data['uuid'] ?? self::uuidV4(),
|
||||
$data['description'],
|
||||
$data['code'] ?? null,
|
||||
$data['cost_center'] ?? null,
|
||||
$data['active'] ?? 1,
|
||||
$data['created_by'] ?? null
|
||||
);
|
||||
}
|
||||
@@ -281,6 +288,9 @@ class DepartmentRepository
|
||||
{
|
||||
$fields = [
|
||||
'description' => $data['description'],
|
||||
'code' => $data['code'] ?? null,
|
||||
'cost_center' => $data['cost_center'] ?? null,
|
||||
'active' => $data['active'] ?? 1,
|
||||
];
|
||||
if (array_key_exists('modified_by', $data)) {
|
||||
$fields['modified_by'] = $data['modified_by'];
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Org;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
class PermissionRepository
|
||||
{
|
||||
public static function list(): array
|
||||
{
|
||||
$rows = DB::select('select id, `key`, description, created from permissions order by `key` asc');
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['permissions'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$order = (string) ($options['order'] ?? 'key');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'asc')) === 'desc' ? 'desc' : 'asc';
|
||||
|
||||
$allowedOrder = ['key' => '`key`', 'description' => 'description', 'created' => 'created'];
|
||||
$orderBy = $allowedOrder[$order] ?? $allowedOrder['key'];
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$where[] = '(permissions.`key` like ? or permissions.description like ?)';
|
||||
$params[] = '%' . $search . '%';
|
||||
$params[] = '%' . $search . '%';
|
||||
}
|
||||
$whereSql = $where ? ' where ' . implode(' and ', $where) : '';
|
||||
|
||||
$total = DB::selectValue('select count(*) from permissions' . $whereSql, ...$params);
|
||||
$query = 'select id, `key`, description, created from permissions' . $whereSql .
|
||||
' order by ' . $orderBy . ' ' . $dir . ' limit ? offset ?';
|
||||
$queryParams = array_merge($params, [(string) $limit, (string) $offset]);
|
||||
$rows = DB::select($query, ...$queryParams);
|
||||
$list = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['permissions'] ?? $row;
|
||||
if (is_array($data)) {
|
||||
$list[] = $data;
|
||||
}
|
||||
}
|
||||
return ['data' => $list, 'total' => (int) $total];
|
||||
}
|
||||
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$row = DB::selectOne('select id, `key`, description, created from permissions where id = ? limit 1', (string) $id);
|
||||
$data = $row['permissions'] ?? $row;
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
public static function findByKey(string $key): ?array
|
||||
{
|
||||
$row = DB::selectOne('select id, `key`, description, created from permissions where `key` = ? limit 1', $key);
|
||||
$data = $row['permissions'] ?? $row;
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
|
||||
public static function create(array $data): ?int
|
||||
{
|
||||
$key = trim((string) ($data['key'] ?? ''));
|
||||
$desc = trim((string) ($data['description'] ?? ''));
|
||||
$result = DB::insert(
|
||||
'insert into permissions (`key`, description, created) values (?,?,NOW())',
|
||||
$key,
|
||||
$desc !== '' ? $desc : null
|
||||
);
|
||||
return $result ? (int) $result : null;
|
||||
}
|
||||
|
||||
public static function update(int $id, array $data): bool
|
||||
{
|
||||
$key = trim((string) ($data['key'] ?? ''));
|
||||
$desc = trim((string) ($data['description'] ?? ''));
|
||||
$result = DB::update(
|
||||
'update permissions set `key` = ?, description = ? where id = ?',
|
||||
$key,
|
||||
$desc !== '' ? $desc : null,
|
||||
(string) $id
|
||||
);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function delete(int $id): bool
|
||||
{
|
||||
$result = DB::delete('delete from permissions where id = ?', (string) $id);
|
||||
return (bool) $result;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
class RememberTokenRepository
|
||||
{
|
||||
public static function create(int $userId, string $selector, string $tokenHash, string $expiresAt): ?int
|
||||
{
|
||||
$id = DB::insert(
|
||||
'insert into user_remember_tokens (user_id, selector, token_hash, expires_at, created) values (?,?,?,?,NOW())',
|
||||
(string) $userId,
|
||||
$selector,
|
||||
$tokenHash,
|
||||
$expiresAt
|
||||
);
|
||||
return $id ? (int) $id : null;
|
||||
}
|
||||
|
||||
public static function findBySelector(string $selector): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, user_id, selector, token_hash, expires_at, last_used from user_remember_tokens where selector = ? limit 1',
|
||||
$selector
|
||||
);
|
||||
if (!$row || !isset($row['user_remember_tokens'])) {
|
||||
return null;
|
||||
}
|
||||
return $row['user_remember_tokens'];
|
||||
}
|
||||
|
||||
public static function updateToken(int $id, string $tokenHash, string $expiresAt): bool
|
||||
{
|
||||
$result = DB::update(
|
||||
'update user_remember_tokens set token_hash = ?, expires_at = ?, last_used = NOW() where id = ?',
|
||||
$tokenHash,
|
||||
$expiresAt,
|
||||
(string) $id
|
||||
);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function deleteById(int $id): bool
|
||||
{
|
||||
$result = DB::delete('delete from user_remember_tokens where id = ?', (string) $id);
|
||||
return $result !== false;
|
||||
}
|
||||
|
||||
public static function deleteByUserId(int $userId): bool
|
||||
{
|
||||
$result = DB::delete('delete from user_remember_tokens where user_id = ?', (string) $userId);
|
||||
return $result !== false;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Settings;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
120
lib/Repository/Support/RepoQuery.php
Normal file
120
lib/Repository/Support/RepoQuery.php
Normal file
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository\Support;
|
||||
|
||||
class RepoQuery
|
||||
{
|
||||
private static function normalizeLikeValue(string $value): string
|
||||
{
|
||||
$value = trim($value);
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
$value = str_replace('\\', '\\\\', $value);
|
||||
$value = str_replace('_', '\\_', $value);
|
||||
$value = str_replace('*', '%', $value);
|
||||
if (!str_starts_with($value, '%')) {
|
||||
$value = '%' . $value;
|
||||
}
|
||||
if (!str_ends_with($value, '%')) {
|
||||
$value = $value . '%';
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
public static function sanitizeLimitOffset(
|
||||
array $options,
|
||||
int $defaultLimit = 10,
|
||||
int $minLimit = 1,
|
||||
int $maxLimit = 100,
|
||||
int $defaultOffset = 0
|
||||
): array {
|
||||
$limit = (int) ($options['limit'] ?? $defaultLimit);
|
||||
if ($limit < $minLimit) {
|
||||
$limit = $defaultLimit;
|
||||
} elseif ($limit > $maxLimit) {
|
||||
$limit = $maxLimit;
|
||||
}
|
||||
|
||||
$offset = (int) ($options['offset'] ?? $defaultOffset);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
return [$limit, $offset];
|
||||
}
|
||||
|
||||
public static function sanitizeOrder(
|
||||
array $options,
|
||||
array $allowedOrder,
|
||||
string $defaultOrder = 'id',
|
||||
string $defaultDir = 'desc'
|
||||
): array {
|
||||
$order = (string) ($options['order'] ?? $defaultOrder);
|
||||
$dir = strtolower((string) ($options['dir'] ?? $defaultDir));
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = $defaultOrder;
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = $defaultDir;
|
||||
}
|
||||
return [$order, $dir];
|
||||
}
|
||||
|
||||
public static function addLikeFilter(array &$where, array &$params, array $fields, string $value): void
|
||||
{
|
||||
$like = self::normalizeLikeValue($value);
|
||||
if ($like === '') {
|
||||
return;
|
||||
}
|
||||
$clauses = [];
|
||||
foreach ($fields as $field) {
|
||||
$clauses[] = $field . " like ? escape '\\\\'";
|
||||
$params[] = $like;
|
||||
}
|
||||
if ($clauses) {
|
||||
$where[] = '(' . implode(' or ', $clauses) . ')';
|
||||
}
|
||||
}
|
||||
|
||||
public static function addEnumFilter(array &$where, array &$params, $value, array $map): void
|
||||
{
|
||||
if ($value === null) {
|
||||
return;
|
||||
}
|
||||
$normalized = strtolower(trim((string) $value));
|
||||
if ($normalized === '' || $normalized === 'all') {
|
||||
return;
|
||||
}
|
||||
foreach ($map as $entry) {
|
||||
$aliases = $entry['aliases'] ?? [];
|
||||
$aliases = array_map('strtolower', $aliases);
|
||||
if (!in_array($normalized, $aliases, true)) {
|
||||
continue;
|
||||
}
|
||||
$sql = (string) ($entry['sql'] ?? '');
|
||||
if ($sql === '') {
|
||||
return;
|
||||
}
|
||||
$where[] = $sql;
|
||||
$paramsToAdd = $entry['params'] ?? [];
|
||||
foreach ($paramsToAdd as $param) {
|
||||
$params[] = $param;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public static function addEqualsFilter(array &$where, array &$params, $value, string $sql, bool $allowEmpty = false): void
|
||||
{
|
||||
// Use for simple "= ?" filters; skip when empty to keep WHERE clean.
|
||||
if ($value === null) {
|
||||
return;
|
||||
}
|
||||
$normalized = trim((string) $value);
|
||||
if ($normalized === '' && !$allowEmpty) {
|
||||
return;
|
||||
}
|
||||
$where[] = $sql;
|
||||
$params[] = $normalized;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Tenant;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -47,6 +47,39 @@ class TenantDepartmentRepository
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
public static function listDepartmentMapByTenantIds(array $tenantIds): array
|
||||
{
|
||||
$tenantIds = array_values(array_unique(array_map('intval', $tenantIds)));
|
||||
$tenantIds = array_filter($tenantIds, static fn ($id) => $id > 0);
|
||||
if (!$tenantIds) {
|
||||
return [];
|
||||
}
|
||||
$placeholders = implode(',', array_fill(0, count($tenantIds), '?'));
|
||||
$rows = DB::select(
|
||||
'select tenant_id, department_id from tenant_departments where tenant_id in (' . $placeholders . ')',
|
||||
...array_map('strval', $tenantIds)
|
||||
);
|
||||
if (!is_array($rows)) {
|
||||
return [];
|
||||
}
|
||||
$map = [];
|
||||
foreach ($rows as $row) {
|
||||
$data = $row['tenant_departments'] ?? $row;
|
||||
if (is_array($data) && isset($data['tenant_id'], $data['department_id'])) {
|
||||
$tenantId = (int) $data['tenant_id'];
|
||||
$departmentId = (int) $data['department_id'];
|
||||
if ($tenantId > 0 && $departmentId > 0) {
|
||||
$map[$tenantId] ??= [];
|
||||
$map[$tenantId][] = $departmentId;
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($map as $tenantId => $items) {
|
||||
$map[$tenantId] = array_values(array_unique($items));
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
public static function replaceForDepartment(int $departmentId, array $tenantIds): bool
|
||||
{
|
||||
DB::delete('delete from tenant_departments where department_id = ?', (string) $departmentId);
|
||||
@@ -1,8 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Tenant;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class TenantRepository
|
||||
{
|
||||
@@ -83,37 +84,14 @@ class TenantRepository
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
if ($limit < 1) {
|
||||
$limit = 10;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$order = (string) ($options['order'] ?? 'id');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'desc'));
|
||||
$allowedOrder = ['id', 'uuid', 'description', 'created', 'modified'];
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = 'id';
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = 'desc';
|
||||
}
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder);
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
$where[] = '(description like ? or uuid like ?)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
RepoQuery::addLikeFilter($where, $params, ['description', 'uuid'], $search);
|
||||
if (!empty($options['tenantUserId'])) {
|
||||
$tenantUserId = (int) $options['tenantUserId'];
|
||||
if ($tenantUserId > 0) {
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\Tenant;
|
||||
|
||||
use MintyPHP\DB;
|
||||
|
||||
@@ -1,11 +1,247 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Repository;
|
||||
namespace MintyPHP\Repository\User;
|
||||
|
||||
use MintyPHP\DB;
|
||||
use MintyPHP\Repository\Support\RepoQuery;
|
||||
|
||||
class UserRepository
|
||||
{
|
||||
private static function buildUserFilters(array $options): array
|
||||
{
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$active = $options['active'] ?? null;
|
||||
$createdFrom = trim((string) ($options['created_from'] ?? ''));
|
||||
$createdTo = trim((string) ($options['created_to'] ?? ''));
|
||||
$tenant = trim((string) ($options['tenant'] ?? ''));
|
||||
$tenantUuids = array_filter(array_map('trim', explode(',', (string) ($options['tenants'] ?? ''))));
|
||||
$roleIds = self::normalizeIdList($options['roles'] ?? []);
|
||||
$departmentIds = self::normalizeIdList($options['departments'] ?? []);
|
||||
$emailVerified = $options['email_verified'] ?? null;
|
||||
$loginStatus = $options['login_status'] ?? null;
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
|
||||
RepoQuery::addLikeFilter(
|
||||
$where,
|
||||
$params,
|
||||
['users.first_name', 'users.last_name', 'users.email'],
|
||||
$search
|
||||
);
|
||||
RepoQuery::addEnumFilter($where, $params, $active, [
|
||||
['aliases' => ['1', 'true', 'active'], 'sql' => 'users.active = ?', 'params' => ['1']],
|
||||
['aliases' => ['0', 'false', 'inactive'], 'sql' => 'users.active = ?', 'params' => ['0']],
|
||||
]);
|
||||
|
||||
if ($createdFrom !== '') {
|
||||
$where[] = 'users.created >= ?';
|
||||
$params[] = $createdFrom . ' 00:00:00';
|
||||
}
|
||||
if ($createdTo !== '') {
|
||||
$where[] = 'users.created <= ?';
|
||||
$params[] = $createdTo . ' 23:59:59';
|
||||
}
|
||||
if ($tenantUuids) {
|
||||
$where[] = 'exists (select 1 from user_tenants ut2 join tenants t2 on t2.id = ut2.tenant_id where ut2.user_id = users.id and t2.uuid in (???))';
|
||||
$params[] = array_values($tenantUuids);
|
||||
} else {
|
||||
RepoQuery::addEqualsFilter(
|
||||
$where,
|
||||
$params,
|
||||
$tenant,
|
||||
'exists (select 1 from user_tenants ut2 join tenants t2 on t2.id = ut2.tenant_id where ut2.user_id = users.id and t2.uuid = ?)'
|
||||
);
|
||||
}
|
||||
if ($roleIds) {
|
||||
$where[] = 'exists (select 1 from user_roles ur2 where ur2.user_id = users.id and ur2.role_id in (???))';
|
||||
$params[] = array_map('strval', $roleIds);
|
||||
}
|
||||
if ($departmentIds) {
|
||||
$where[] = 'exists (select 1 from user_departments ud2 where ud2.user_id = users.id and ud2.department_id in (???))';
|
||||
$params[] = array_map('strval', $departmentIds);
|
||||
}
|
||||
RepoQuery::addEnumFilter($where, $params, $emailVerified, [
|
||||
['aliases' => ['1', 'true', 'verified', 'yes'], 'sql' => 'users.email_verified_at is not null'],
|
||||
['aliases' => ['0', 'false', 'unverified', 'no'], 'sql' => 'users.email_verified_at is null'],
|
||||
]);
|
||||
RepoQuery::addEnumFilter($where, $params, $loginStatus, [
|
||||
['aliases' => ['never', 'none', 'no'], 'sql' => 'users.last_login_at is null'],
|
||||
['aliases' => ['ever', 'logged', 'yes'], 'sql' => 'users.last_login_at is not null'],
|
||||
]);
|
||||
if (!empty($options['tenantUserId'])) {
|
||||
$tenantUserId = (int) $options['tenantUserId'];
|
||||
if ($tenantUserId > 0) {
|
||||
if (defined('TENANT_SCOPE_STRICT') && TENANT_SCOPE_STRICT) {
|
||||
$where[] = 'exists (select 1 from user_tenants ut join user_tenants ut2 on ut2.tenant_id = ut.tenant_id ' .
|
||||
"join tenants t on t.id = ut.tenant_id and t.status = 'active' " .
|
||||
'where ut2.user_id = ? and ut.user_id = users.id)';
|
||||
$params[] = (string) $tenantUserId;
|
||||
} else {
|
||||
$where[] = '(not exists (select 1 from user_tenants ut where ut.user_id = users.id) ' .
|
||||
'or exists (select 1 from user_tenants ut join user_tenants ut2 on ut2.tenant_id = ut.tenant_id ' .
|
||||
"join tenants t on t.id = ut.tenant_id and t.status = 'active' " .
|
||||
'where ut2.user_id = ? and ut.user_id = users.id))';
|
||||
$params[] = (string) $tenantUserId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$whereSql = $where ? (' where ' . implode(' and ', $where)) : '';
|
||||
return [$whereSql, $params];
|
||||
}
|
||||
|
||||
private static function buildListQuery(string $whereSql, string $order, string $dir): string
|
||||
{
|
||||
return 'select users.id, users.uuid, users.first_name, users.last_name, users.display_name, users.email, users.profile_description, users.job_title, users.phone, users.mobile, users.short_dial, users.address, users.postal_code, users.city, users.country, users.region, users.hire_date, users.theme, users.primary_tenant_id, users.created_by, users.modified_by, users.created, users.modified, users.last_login_at, users.active, ' .
|
||||
'pt.description as primary_tenant_label ' .
|
||||
"from users left join tenants pt on pt.id = users.primary_tenant_id and pt.status = 'active'" .
|
||||
$whereSql .
|
||||
sprintf(' order by `users`.`%s` %s limit ? offset ?', $order, $dir);
|
||||
}
|
||||
|
||||
private static function extractIds(array $list): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($list as $user) {
|
||||
if (isset($user['id'])) {
|
||||
$ids[] = (int) $user['id'];
|
||||
}
|
||||
}
|
||||
return $ids;
|
||||
}
|
||||
|
||||
private static function collectLabels(array $rows, string $userKey, string $labelKey): array
|
||||
{
|
||||
$labelsByUser = [];
|
||||
foreach ($rows as $row) {
|
||||
$userId = 0;
|
||||
$label = '';
|
||||
if (isset($row[$userKey]) && is_array($row[$userKey])) {
|
||||
$userId = (int) ($row[$userKey]['user_id'] ?? 0);
|
||||
}
|
||||
if (isset($row[$labelKey]) && is_array($row[$labelKey])) {
|
||||
$label = (string) ($row[$labelKey]['description'] ?? '');
|
||||
}
|
||||
if ($userId === 0 || $label === '') {
|
||||
foreach ($row as $value) {
|
||||
if (!is_array($value)) {
|
||||
continue;
|
||||
}
|
||||
if ($userId === 0 && isset($value['user_id'])) {
|
||||
$userId = (int) $value['user_id'];
|
||||
}
|
||||
if ($label === '' && isset($value['description'])) {
|
||||
$label = (string) $value['description'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($userId === 0 && isset($row['user_id'])) {
|
||||
$userId = (int) $row['user_id'];
|
||||
}
|
||||
if ($label === '' && isset($row['description'])) {
|
||||
$label = (string) $row['description'];
|
||||
}
|
||||
if ($userId > 0 && $label !== '') {
|
||||
$labelsByUser[$userId] ??= [];
|
||||
$labelsByUser[$userId][] = $label;
|
||||
}
|
||||
}
|
||||
return $labelsByUser;
|
||||
}
|
||||
|
||||
private static function hydrateUserLabels(array $list, array $options): array
|
||||
{
|
||||
$ids = self::extractIds($list);
|
||||
if (!$ids) {
|
||||
return $list;
|
||||
}
|
||||
|
||||
$scopeToActiveTenants = !empty($options['tenantUserId']);
|
||||
$tenantLabelJoin = $scopeToActiveTenants
|
||||
? "join tenants t on t.id = ut.tenant_id and t.status = 'active' "
|
||||
: 'join tenants t on t.id = ut.tenant_id ';
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
|
||||
$labelRows = DB::select(
|
||||
'select ut.user_id as user_id, t.id as tenant_id, t.description as description from user_tenants ut ' . $tenantLabelJoin .
|
||||
'where ut.user_id in (' . $placeholders . ') order by t.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
$roleLabelRows = DB::select(
|
||||
'select ur.user_id as user_id, r.description as description from user_roles ur join roles r on r.id = ur.role_id and r.active = 1 ' .
|
||||
'where ur.user_id in (' . $placeholders . ') order by r.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
$departmentLabelRows = DB::select(
|
||||
'select ud.user_id as user_id, d.description as description from user_departments ud join departments d on d.id = ud.department_id and d.active = 1 ' .
|
||||
'where ud.user_id in (' . $placeholders . ') order by d.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
|
||||
$tenantMapByUser = [];
|
||||
foreach ($labelRows as $row) {
|
||||
$userId = 0;
|
||||
$tenantId = 0;
|
||||
$label = '';
|
||||
if (isset($row['ut']) && is_array($row['ut'])) {
|
||||
$userId = (int) ($row['ut']['user_id'] ?? 0);
|
||||
}
|
||||
if (isset($row['t']) && is_array($row['t'])) {
|
||||
$tenantId = (int) ($row['t']['tenant_id'] ?? 0);
|
||||
$label = (string) ($row['t']['description'] ?? '');
|
||||
}
|
||||
if ($userId === 0 || $tenantId === 0 || $label === '') {
|
||||
foreach ($row as $value) {
|
||||
if (!is_array($value)) {
|
||||
continue;
|
||||
}
|
||||
if ($userId === 0 && isset($value['user_id'])) {
|
||||
$userId = (int) $value['user_id'];
|
||||
}
|
||||
if ($tenantId === 0 && isset($value['tenant_id'])) {
|
||||
$tenantId = (int) $value['tenant_id'];
|
||||
}
|
||||
if ($label === '' && isset($value['description'])) {
|
||||
$label = (string) $value['description'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($userId === 0 && isset($row['user_id'])) {
|
||||
$userId = (int) $row['user_id'];
|
||||
}
|
||||
if ($tenantId === 0 && isset($row['tenant_id'])) {
|
||||
$tenantId = (int) $row['tenant_id'];
|
||||
}
|
||||
if ($label === '' && isset($row['description'])) {
|
||||
$label = (string) $row['description'];
|
||||
}
|
||||
if ($userId > 0 && $tenantId > 0 && $label !== '') {
|
||||
$tenantMapByUser[$userId] ??= [];
|
||||
$tenantMapByUser[$userId][$tenantId] = $label;
|
||||
}
|
||||
}
|
||||
$tenantLabelsByUser = [];
|
||||
foreach ($tenantMapByUser as $userId => $map) {
|
||||
$tenantLabelsByUser[$userId] = array_values($map);
|
||||
}
|
||||
$roleLabelsByUser = self::collectLabels($roleLabelRows, 'ur', 'r');
|
||||
$departmentLabelsByUser = self::collectLabels($departmentLabelRows, 'ud', 'd');
|
||||
|
||||
foreach ($list as &$user) {
|
||||
$userId = (int) ($user['id'] ?? 0);
|
||||
$primaryId = (int) ($user['primary_tenant_id'] ?? 0);
|
||||
$user['tenant_labels'] = $tenantLabelsByUser[$userId] ?? [];
|
||||
if ($primaryId > 0 && isset($tenantMapByUser[$userId][$primaryId])) {
|
||||
$user['primary_tenant_label'] = $tenantMapByUser[$userId][$primaryId];
|
||||
}
|
||||
$user['role_labels'] = $roleLabelsByUser[$userId] ?? [];
|
||||
$user['department_labels'] = $departmentLabelsByUser[$userId] ?? [];
|
||||
}
|
||||
unset($user);
|
||||
|
||||
return $list;
|
||||
}
|
||||
private static function unwrap(?array $row): ?array
|
||||
{
|
||||
if (!$row) {
|
||||
@@ -44,262 +280,35 @@ class UserRepository
|
||||
public static function list(): array
|
||||
{
|
||||
$rows = DB::select(
|
||||
'select id, uuid, first_name, last_name, email, profile_description, job_title, phone, mobile, short_dial, theme, primary_tenant_id, created_by, modified_by, created, modified, active from users order by id desc'
|
||||
'select id, uuid, first_name, last_name, display_name, email, profile_description, job_title, phone, mobile, short_dial, theme, primary_tenant_id, created_by, modified_by, created, modified, active from users order by id desc'
|
||||
);
|
||||
return self::unwrapList($rows);
|
||||
}
|
||||
|
||||
public static function updateLastLogin(int $userId): void
|
||||
{
|
||||
if ($userId <= 0) {
|
||||
return;
|
||||
}
|
||||
DB::query('update users set last_login_at = UTC_TIMESTAMP() where id = ?', (string) $userId);
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
$limit = (int) ($options['limit'] ?? 10);
|
||||
if ($limit < 1) {
|
||||
$limit = 10;
|
||||
} elseif ($limit > 100) {
|
||||
$limit = 100;
|
||||
}
|
||||
$allowedOrder = ['id', 'uuid', 'first_name', 'last_name', 'email', 'created', 'modified', 'active', 'last_login_at'];
|
||||
[$limit, $offset] = RepoQuery::sanitizeLimitOffset($options);
|
||||
[$order, $dir] = RepoQuery::sanitizeOrder($options, $allowedOrder);
|
||||
[$whereSql, $params] = self::buildUserFilters($options);
|
||||
|
||||
$offset = (int) ($options['offset'] ?? 0);
|
||||
if ($offset < 0) {
|
||||
$offset = 0;
|
||||
}
|
||||
|
||||
$search = trim((string) ($options['search'] ?? ''));
|
||||
$active = $options['active'] ?? null;
|
||||
$createdFrom = trim((string) ($options['created_from'] ?? ''));
|
||||
$createdTo = trim((string) ($options['created_to'] ?? ''));
|
||||
$tenant = trim((string) ($options['tenant'] ?? ''));
|
||||
$tenantUuids = array_filter(array_map('trim', explode(',', (string) ($options['tenants'] ?? ''))));
|
||||
$roleIds = self::normalizeIdList($options['roles'] ?? []);
|
||||
$departmentIds = self::normalizeIdList($options['departments'] ?? []);
|
||||
$emailVerified = $options['email_verified'] ?? null;
|
||||
$order = (string) ($options['order'] ?? 'id');
|
||||
$dir = strtolower((string) ($options['dir'] ?? 'desc'));
|
||||
$allowedOrder = ['id', 'uuid', 'first_name', 'last_name', 'email', 'created', 'modified', 'active'];
|
||||
if (!in_array($order, $allowedOrder, true)) {
|
||||
$order = 'id';
|
||||
}
|
||||
if (!in_array($dir, ['asc', 'desc'], true)) {
|
||||
$dir = 'desc';
|
||||
}
|
||||
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($search !== '') {
|
||||
$like = '%' . $search . '%';
|
||||
$where[] = '(users.first_name like ? or users.last_name like ? or users.email like ?)';
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
$params[] = $like;
|
||||
}
|
||||
|
||||
$activeFilter = null;
|
||||
if ($active !== null && $active !== '' && $active !== 'all') {
|
||||
$activeValue = strtolower((string) $active);
|
||||
if (in_array($activeValue, ['1', 'true', 'active'], true)) {
|
||||
$activeFilter = 1;
|
||||
} elseif (in_array($activeValue, ['0', 'false', 'inactive'], true)) {
|
||||
$activeFilter = 0;
|
||||
}
|
||||
}
|
||||
if ($activeFilter !== null) {
|
||||
$where[] = 'users.active = ?';
|
||||
$params[] = (string) $activeFilter;
|
||||
}
|
||||
|
||||
if ($createdFrom !== '') {
|
||||
$where[] = 'users.created >= ?';
|
||||
$params[] = $createdFrom . ' 00:00:00';
|
||||
}
|
||||
if ($createdTo !== '') {
|
||||
$where[] = 'users.created <= ?';
|
||||
$params[] = $createdTo . ' 23:59:59';
|
||||
}
|
||||
if ($tenantUuids) {
|
||||
$where[] = 'exists (select 1 from user_tenants ut2 join tenants t2 on t2.id = ut2.tenant_id where ut2.user_id = users.id and t2.uuid in (???))';
|
||||
$params[] = array_values($tenantUuids);
|
||||
} elseif ($tenant !== '') {
|
||||
$where[] = 'exists (select 1 from user_tenants ut2 join tenants t2 on t2.id = ut2.tenant_id where ut2.user_id = users.id and t2.uuid = ?)';
|
||||
$params[] = $tenant;
|
||||
}
|
||||
if ($roleIds) {
|
||||
$where[] = 'exists (select 1 from user_roles ur2 where ur2.user_id = users.id and ur2.role_id in (???))';
|
||||
$params[] = array_map('strval', $roleIds);
|
||||
}
|
||||
if ($departmentIds) {
|
||||
$where[] = 'exists (select 1 from user_departments ud2 where ud2.user_id = users.id and ud2.department_id in (???))';
|
||||
$params[] = array_map('strval', $departmentIds);
|
||||
}
|
||||
if ($emailVerified !== null && $emailVerified !== '' && $emailVerified !== 'all') {
|
||||
$emailVerifiedValue = strtolower((string) $emailVerified);
|
||||
if (in_array($emailVerifiedValue, ['1', 'true', 'verified', 'yes'], true)) {
|
||||
$where[] = 'users.email_verified_at is not null';
|
||||
} elseif (in_array($emailVerifiedValue, ['0', 'false', 'unverified', 'no'], true)) {
|
||||
$where[] = 'users.email_verified_at is null';
|
||||
}
|
||||
}
|
||||
if (!empty($options['tenantUserId'])) {
|
||||
$tenantUserId = (int) $options['tenantUserId'];
|
||||
if ($tenantUserId > 0) {
|
||||
if (defined('TENANT_SCOPE_STRICT') && TENANT_SCOPE_STRICT) {
|
||||
$where[] = 'exists (select 1 from user_tenants ut join user_tenants ut2 on ut2.tenant_id = ut.tenant_id ' .
|
||||
"join tenants t on t.id = ut.tenant_id and t.status = 'active' " .
|
||||
'where ut2.user_id = ? and ut.user_id = users.id)';
|
||||
$params[] = (string) $tenantUserId;
|
||||
} else {
|
||||
$where[] = '(not exists (select 1 from user_tenants ut where ut.user_id = users.id) ' .
|
||||
'or exists (select 1 from user_tenants ut join user_tenants ut2 on ut2.tenant_id = ut.tenant_id ' .
|
||||
"join tenants t on t.id = ut.tenant_id and t.status = 'active' " .
|
||||
'where ut2.user_id = ? and ut.user_id = users.id))';
|
||||
$params[] = (string) $tenantUserId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$whereSql = $where ? (' where ' . implode(' and ', $where)) : '';
|
||||
$count = DB::selectValue('select count(*) from users' . $whereSql, ...$params);
|
||||
$total = $count ? (int) $count : 0;
|
||||
|
||||
$query = 'select users.id, users.uuid, users.first_name, users.last_name, users.email, users.profile_description, users.job_title, users.phone, users.mobile, users.short_dial, users.address, users.postal_code, users.city, users.country, users.region, users.hire_date, users.theme, users.primary_tenant_id, users.created_by, users.modified_by, users.created, users.modified, users.active, ' .
|
||||
'pt.description as primary_tenant_label ' .
|
||||
"from users left join tenants pt on pt.id = users.primary_tenant_id and pt.status = 'active'" .
|
||||
$whereSql .
|
||||
sprintf(' order by `users`.`%s` %s limit ? offset ?', $order, $dir);
|
||||
|
||||
$query = self::buildListQuery($whereSql, $order, $dir);
|
||||
$queryParams = array_merge($params, [(string) $limit, (string) $offset]);
|
||||
$rows = call_user_func_array(['MintyPHP\\DB', 'select'], array_merge([$query], $queryParams));
|
||||
|
||||
$list = self::unwrapList($rows);
|
||||
$labelRows = [];
|
||||
$tenantMapByUser = [];
|
||||
$roleLabelRows = [];
|
||||
$departmentLabelRows = [];
|
||||
|
||||
$ids = [];
|
||||
foreach ($list as $user) {
|
||||
if (isset($user['id'])) {
|
||||
$ids[] = (int) $user['id'];
|
||||
}
|
||||
}
|
||||
if ($ids) {
|
||||
$scopeToActiveTenants = !empty($options['tenantUserId']);
|
||||
$tenantLabelJoin = $scopeToActiveTenants
|
||||
? "join tenants t on t.id = ut.tenant_id and t.status = 'active' "
|
||||
: 'join tenants t on t.id = ut.tenant_id ';
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$labelRows = DB::select(
|
||||
'select ut.user_id as user_id, t.id as tenant_id, t.description as description from user_tenants ut ' . $tenantLabelJoin .
|
||||
'where ut.user_id in (' . $placeholders . ') order by t.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
$roleLabelRows = DB::select(
|
||||
'select ur.user_id as user_id, r.description as description from user_roles ur join roles r on r.id = ur.role_id ' .
|
||||
'where ur.user_id in (' . $placeholders . ') order by r.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
$departmentLabelRows = DB::select(
|
||||
'select ud.user_id as user_id, d.description as description from user_departments ud join departments d on d.id = ud.department_id ' .
|
||||
'where ud.user_id in (' . $placeholders . ') order by d.description asc',
|
||||
...array_map('strval', $ids)
|
||||
);
|
||||
|
||||
$collectLabels = static function (array $rows, string $userKey, string $labelKey): array {
|
||||
$labelsByUser = [];
|
||||
foreach ($rows as $row) {
|
||||
$userId = 0;
|
||||
$label = '';
|
||||
if (isset($row[$userKey]) && is_array($row[$userKey])) {
|
||||
$userId = (int) ($row[$userKey]['user_id'] ?? 0);
|
||||
}
|
||||
if (isset($row[$labelKey]) && is_array($row[$labelKey])) {
|
||||
$label = (string) ($row[$labelKey]['description'] ?? '');
|
||||
}
|
||||
if ($userId === 0 || $label === '') {
|
||||
foreach ($row as $value) {
|
||||
if (!is_array($value)) {
|
||||
continue;
|
||||
}
|
||||
if ($userId === 0 && isset($value['user_id'])) {
|
||||
$userId = (int) $value['user_id'];
|
||||
}
|
||||
if ($label === '' && isset($value['description'])) {
|
||||
$label = (string) $value['description'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($userId === 0 && isset($row['user_id'])) {
|
||||
$userId = (int) $row['user_id'];
|
||||
}
|
||||
if ($label === '' && isset($row['description'])) {
|
||||
$label = (string) $row['description'];
|
||||
}
|
||||
if ($userId > 0 && $label !== '') {
|
||||
$labelsByUser[$userId] ??= [];
|
||||
$labelsByUser[$userId][] = $label;
|
||||
}
|
||||
}
|
||||
return $labelsByUser;
|
||||
};
|
||||
|
||||
foreach ($labelRows as $row) {
|
||||
$userId = 0;
|
||||
$tenantId = 0;
|
||||
$label = '';
|
||||
if (isset($row['ut']) && is_array($row['ut'])) {
|
||||
$userId = (int) ($row['ut']['user_id'] ?? 0);
|
||||
}
|
||||
if (isset($row['t']) && is_array($row['t'])) {
|
||||
$tenantId = (int) ($row['t']['tenant_id'] ?? 0);
|
||||
$label = (string) ($row['t']['description'] ?? '');
|
||||
}
|
||||
if ($userId === 0 || $tenantId === 0 || $label === '') {
|
||||
foreach ($row as $value) {
|
||||
if (!is_array($value)) {
|
||||
continue;
|
||||
}
|
||||
if ($userId === 0 && isset($value['user_id'])) {
|
||||
$userId = (int) $value['user_id'];
|
||||
}
|
||||
if ($tenantId === 0 && isset($value['tenant_id'])) {
|
||||
$tenantId = (int) $value['tenant_id'];
|
||||
}
|
||||
if ($label === '' && isset($value['description'])) {
|
||||
$label = (string) $value['description'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($userId === 0 && isset($row['user_id'])) {
|
||||
$userId = (int) $row['user_id'];
|
||||
}
|
||||
if ($tenantId === 0 && isset($row['tenant_id'])) {
|
||||
$tenantId = (int) $row['tenant_id'];
|
||||
}
|
||||
if ($label === '' && isset($row['description'])) {
|
||||
$label = (string) $row['description'];
|
||||
}
|
||||
if ($userId > 0 && $tenantId > 0 && $label !== '') {
|
||||
$tenantMapByUser[$userId] ??= [];
|
||||
$tenantMapByUser[$userId][$tenantId] = $label;
|
||||
}
|
||||
}
|
||||
$tenantLabelsByUser = [];
|
||||
foreach ($tenantMapByUser as $userId => $map) {
|
||||
$tenantLabelsByUser[$userId] = array_values($map);
|
||||
}
|
||||
$roleLabelsByUser = $collectLabels($roleLabelRows, 'ur', 'r');
|
||||
$departmentLabelsByUser = $collectLabels($departmentLabelRows, 'ud', 'd');
|
||||
|
||||
foreach ($list as &$user) {
|
||||
$userId = (int) ($user['id'] ?? 0);
|
||||
$primaryId = (int) ($user['primary_tenant_id'] ?? 0);
|
||||
$user['tenant_labels'] = $tenantLabelsByUser[$userId] ?? [];
|
||||
if ($primaryId > 0 && isset($tenantMapByUser[$userId][$primaryId])) {
|
||||
$user['primary_tenant_label'] = $tenantMapByUser[$userId][$primaryId];
|
||||
}
|
||||
$user['role_labels'] = $roleLabelsByUser[$userId] ?? [];
|
||||
$user['department_labels'] = $departmentLabelsByUser[$userId] ?? [];
|
||||
}
|
||||
unset($user);
|
||||
}
|
||||
$list = self::hydrateUserLabels($list, $options);
|
||||
|
||||
$result = [
|
||||
'total' => $total,
|
||||
@@ -311,7 +320,7 @@ class UserRepository
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, first_name, last_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active from users where id = ? limit 1',
|
||||
'select id, uuid, first_name, last_name, display_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active from users where id = ? limit 1',
|
||||
(string) $id
|
||||
);
|
||||
return self::unwrap($row);
|
||||
@@ -320,7 +329,7 @@ class UserRepository
|
||||
public static function findByUuid(string $uuid): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, first_name, last_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active, active_changed_at, active_changed_by from users where uuid = ? limit 1',
|
||||
'select id, uuid, first_name, last_name, display_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active, active_changed_at, active_changed_by from users where uuid = ? limit 1',
|
||||
$uuid
|
||||
);
|
||||
return self::unwrap($row);
|
||||
@@ -329,12 +338,23 @@ class UserRepository
|
||||
public static function findByEmail(string $email): ?array
|
||||
{
|
||||
$row = DB::selectOne(
|
||||
'select id, uuid, first_name, last_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active, active_changed_at, active_changed_by from users where email = ? limit 1',
|
||||
'select id, uuid, first_name, last_name, display_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, email_verified_at, email_verified_at, password, locale, totp_secret, theme, primary_tenant_id, created_by, modified_by, created, modified, active, active_changed_at, active_changed_by from users where email = ? limit 1',
|
||||
$email
|
||||
);
|
||||
return self::unwrap($row);
|
||||
}
|
||||
|
||||
private static function buildDisplayName(array $data): string
|
||||
{
|
||||
$first = trim((string) ($data['first_name'] ?? ''));
|
||||
$last = trim((string) ($data['last_name'] ?? ''));
|
||||
$name = trim($first . ' ' . $last);
|
||||
if ($name === '') {
|
||||
$name = trim((string) ($data['email'] ?? ''));
|
||||
}
|
||||
return $name;
|
||||
}
|
||||
|
||||
private static function uuidV4(): string
|
||||
{
|
||||
$data = random_bytes(16);
|
||||
@@ -347,10 +367,11 @@ class UserRepository
|
||||
{
|
||||
$hash = password_hash($data['password'], PASSWORD_DEFAULT);
|
||||
return DB::insert(
|
||||
'insert into users (uuid, first_name, last_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, password, locale, totp_secret, theme, primary_tenant_id, current_tenant_id, created_by, created, active, active_changed_at, active_changed_by) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?)',
|
||||
'insert into users (uuid, first_name, last_name, display_name, email, profile_description, job_title, phone, mobile, short_dial, address, postal_code, city, country, region, hire_date, password, locale, totp_secret, theme, primary_tenant_id, current_tenant_id, created_by, created, active, active_changed_at, active_changed_by) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?)',
|
||||
$data['uuid'] ?? self::uuidV4(),
|
||||
$data['first_name'],
|
||||
$data['last_name'],
|
||||
self::buildDisplayName($data),
|
||||
$data['email'],
|
||||
$data['profile_description'] ?? null,
|
||||
$data['job_title'] ?? null,
|
||||
@@ -381,6 +402,7 @@ class UserRepository
|
||||
$fields = [
|
||||
'first_name' => $data['first_name'],
|
||||
'last_name' => $data['last_name'],
|
||||
'display_name' => self::buildDisplayName($data),
|
||||
'email' => $data['email'],
|
||||
'profile_description' => $data['profile_description'] ?? null,
|
||||
'job_title' => $data['job_title'] ?? null,
|
||||
@@ -1,16 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Access;
|
||||
|
||||
use MintyPHP\Repository\RolePermissionRepository;
|
||||
use MintyPHP\Repository\UserRoleRepository;
|
||||
use MintyPHP\Repository\PermissionRepository;
|
||||
use MintyPHP\Repository\Access\RolePermissionRepository;
|
||||
use MintyPHP\Repository\Access\UserRoleRepository;
|
||||
use MintyPHP\Repository\Access\PermissionRepository;
|
||||
|
||||
class PermissionService
|
||||
{
|
||||
public const USERS_CREATE = 'users.create';
|
||||
public const USERS_DELETE = 'users.delete';
|
||||
public const USERS_VIEW = 'users.view';
|
||||
public const USERS_VIEW_META = 'users.view_meta';
|
||||
public const USERS_VIEW_AUDIT = 'users.view_audit';
|
||||
public const USERS_UPDATE = 'users.update';
|
||||
public const USERS_SELF_UPDATE = 'users.self_update';
|
||||
public const USERS_UPDATE_ASSIGNMENTS = 'users.update_assignments';
|
||||
@@ -96,6 +98,11 @@ class PermissionService
|
||||
return PermissionRepository::list();
|
||||
}
|
||||
|
||||
public static function listActive(): array
|
||||
{
|
||||
return PermissionRepository::listActive();
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
return PermissionRepository::listPaged($options);
|
||||
@@ -152,6 +159,9 @@ class PermissionService
|
||||
if (!$permission) {
|
||||
return ['ok' => false, 'status' => 404, 'error' => 'not_found'];
|
||||
}
|
||||
if ((int) ($permission['is_system'] ?? 0) === 1) {
|
||||
return ['ok' => false, 'status' => 403, 'error' => 'system_permission_protected'];
|
||||
}
|
||||
$deleted = PermissionRepository::delete($id);
|
||||
if (!$deleted) {
|
||||
return ['ok' => false, 'status' => 500, 'error' => 'delete_failed'];
|
||||
@@ -164,6 +174,8 @@ class PermissionService
|
||||
return [
|
||||
'key' => trim((string) ($input['key'] ?? '')),
|
||||
'description' => trim((string) ($input['description'] ?? '')),
|
||||
'active' => self::normalizeActive($input['active'] ?? 1),
|
||||
'is_system' => self::normalizeFlag($input['is_system'] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -177,4 +189,25 @@ class PermissionService
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
private static function normalizeActive($value): int
|
||||
{
|
||||
$value = strtolower(trim((string) $value));
|
||||
if (in_array($value, ['0', 'false', 'inactive'], true)) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static function normalizeFlag($value): int
|
||||
{
|
||||
if (is_bool($value)) {
|
||||
return $value ? 1 : 0;
|
||||
}
|
||||
$value = strtolower(trim((string) $value));
|
||||
if (in_array($value, ['1', 'true', 'yes', 'on'], true)) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Access;
|
||||
|
||||
use MintyPHP\Repository\RoleRepository;
|
||||
use MintyPHP\Service\SettingService;
|
||||
use MintyPHP\Repository\Access\RoleRepository;
|
||||
use MintyPHP\Service\Settings\SettingService;
|
||||
|
||||
class RoleService
|
||||
{
|
||||
@@ -12,6 +12,11 @@ class RoleService
|
||||
return RoleRepository::list();
|
||||
}
|
||||
|
||||
public static function listActive(): array
|
||||
{
|
||||
return RoleRepository::listActive();
|
||||
}
|
||||
|
||||
public static function listPaged(array $options): array
|
||||
{
|
||||
return RoleRepository::listPaged($options);
|
||||
@@ -30,7 +35,7 @@ class RoleService
|
||||
public static function createFromAdmin(array $input, int $currentUserId = 0): array
|
||||
{
|
||||
$form = self::sanitizeBase($input);
|
||||
$errors = self::validateBase($form);
|
||||
$errors = self::validateBase($form, 0);
|
||||
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors, 'form' => $form];
|
||||
@@ -38,6 +43,8 @@ class RoleService
|
||||
|
||||
$createdId = RoleRepository::create([
|
||||
'description' => $form['description'],
|
||||
'code' => $form['code'] ?: null,
|
||||
'active' => $form['active'],
|
||||
'created_by' => $currentUserId > 0 ? $currentUserId : null,
|
||||
]);
|
||||
|
||||
@@ -56,7 +63,7 @@ class RoleService
|
||||
public static function updateFromAdmin(int $roleId, array $input, int $currentUserId = 0): array
|
||||
{
|
||||
$form = self::sanitizeBase($input);
|
||||
$errors = self::validateBase($form);
|
||||
$errors = self::validateBase($form, $roleId);
|
||||
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors, 'form' => $form];
|
||||
@@ -64,6 +71,8 @@ class RoleService
|
||||
|
||||
$updated = RoleRepository::update($roleId, [
|
||||
'description' => $form['description'],
|
||||
'code' => $form['code'] ?: null,
|
||||
'active' => $form['active'],
|
||||
'modified_by' => $currentUserId > 0 ? $currentUserId : null,
|
||||
]);
|
||||
|
||||
@@ -102,15 +111,30 @@ class RoleService
|
||||
{
|
||||
return [
|
||||
'description' => trim((string) ($input['description'] ?? '')),
|
||||
'code' => trim((string) ($input['code'] ?? '')),
|
||||
'active' => self::normalizeActive($input['active'] ?? 1),
|
||||
];
|
||||
}
|
||||
|
||||
private static function validateBase(array $form): array
|
||||
private static function validateBase(array $form, int $excludeId): array
|
||||
{
|
||||
$errors = [];
|
||||
if ($form['description'] === '') {
|
||||
$errors[] = t('Description cannot be empty');
|
||||
}
|
||||
$code = $form['code'] ?? '';
|
||||
if ($code !== '' && RoleRepository::existsByCode($code, $excludeId)) {
|
||||
$errors[] = t('Role code already exists');
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
private static function normalizeActive($value): int
|
||||
{
|
||||
$value = strtolower(trim((string) $value));
|
||||
if (in_array($value, ['0', 'false', 'inactive'], true)) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Auth;
|
||||
|
||||
use MintyPHP\Auth;
|
||||
use MintyPHP\Router;
|
||||
use MintyPHP\Support\Flash;
|
||||
use MintyPHP\Service\UserService;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\RememberMeService;
|
||||
use MintyPHP\Service\EmailVerificationService;
|
||||
use MintyPHP\Repository\UserRepository;
|
||||
use MintyPHP\Service\User\UserService;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
use MintyPHP\Service\Auth\RememberMeService;
|
||||
use MintyPHP\Service\Auth\EmailVerificationService;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
|
||||
class AuthService
|
||||
{
|
||||
@@ -60,6 +60,7 @@ class AuthService
|
||||
'flash_key' => 'login_no_active_tenant',
|
||||
];
|
||||
}
|
||||
UserRepository::updateLastLogin($userId);
|
||||
}
|
||||
|
||||
return ['ok' => true];
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Auth;
|
||||
|
||||
use MintyPHP\Repository\EmailVerificationRepository;
|
||||
use MintyPHP\Repository\UserRepository;
|
||||
use MintyPHP\Repository\Auth\EmailVerificationRepository;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
use MintyPHP\I18n;
|
||||
use MintyPHP\Http\Request;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Auth;
|
||||
|
||||
use MintyPHP\Repository\PasswordResetRepository;
|
||||
use MintyPHP\Repository\UserRepository;
|
||||
use MintyPHP\Repository\Auth\PasswordResetRepository;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
use MintyPHP\I18n;
|
||||
use MintyPHP\Http\Request;
|
||||
use MintyPHP\Service\RememberMeService;
|
||||
use MintyPHP\Service\Auth\RememberMeService;
|
||||
|
||||
class PasswordResetService
|
||||
{
|
||||
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Auth;
|
||||
|
||||
use MintyPHP\Session;
|
||||
use MintyPHP\Repository\RememberTokenRepository;
|
||||
use MintyPHP\Repository\UserRepository;
|
||||
use MintyPHP\Repository\Auth\RememberTokenRepository;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
use MintyPHP\I18n;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\AuthService;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
use MintyPHP\Service\Auth\AuthService;
|
||||
|
||||
class RememberMeService
|
||||
{
|
||||
@@ -83,6 +83,9 @@ class RememberMeService
|
||||
if ($userId > 0) {
|
||||
PermissionService::getUserPermissions($userId, true);
|
||||
AuthService::loadTenantDataIntoSession($userId);
|
||||
if (empty($_SESSION['no_active_tenant'])) {
|
||||
UserRepository::updateLastLogin($userId);
|
||||
}
|
||||
}
|
||||
|
||||
$newToken = bin2hex(random_bytes(32));
|
||||
@@ -115,6 +118,11 @@ class RememberMeService
|
||||
RememberTokenRepository::deleteByUserId($userId);
|
||||
}
|
||||
|
||||
public static function expireAllTokensByAdmin(): int
|
||||
{
|
||||
return RememberTokenRepository::expireAllByAdmin();
|
||||
}
|
||||
|
||||
private static function setCookie(string $selector, string $token): void
|
||||
{
|
||||
$value = $selector . ':' . $token;
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Branding;
|
||||
|
||||
class BrandingFaviconService
|
||||
{
|
||||
@@ -19,7 +19,7 @@ class BrandingFaviconService
|
||||
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
||||
return rtrim(APP_STORAGE_PATH, '/');
|
||||
}
|
||||
return rtrim(dirname(__DIR__, 2) . '/storage', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
||||
}
|
||||
|
||||
public static function storageDir(): string
|
||||
@@ -29,7 +29,7 @@ class BrandingFaviconService
|
||||
|
||||
public static function publicDir(): string
|
||||
{
|
||||
return rtrim(dirname(__DIR__, 2) . '/web/favicon', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/web/favicon', '/');
|
||||
}
|
||||
|
||||
public static function hasFavicon(): bool
|
||||
@@ -195,8 +195,8 @@ class BrandingFaviconService
|
||||
}
|
||||
|
||||
$title = null;
|
||||
if (class_exists('MintyPHP\\Service\\SettingService')) {
|
||||
$title = \MintyPHP\Service\SettingService::getAppTitle();
|
||||
if (class_exists('MintyPHP\\Service\\Settings\\SettingService')) {
|
||||
$title = \MintyPHP\Service\Settings\SettingService::getAppTitle();
|
||||
}
|
||||
if ($title === null || $title === '') {
|
||||
$title = defined('APP_NAME') ? APP_NAME : 'IMVS';
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Branding;
|
||||
|
||||
class BrandingLogoService
|
||||
{
|
||||
@@ -13,7 +13,7 @@ class BrandingLogoService
|
||||
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
||||
return rtrim(APP_STORAGE_PATH, '/');
|
||||
}
|
||||
return rtrim(dirname(__DIR__, 2) . '/storage', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
||||
}
|
||||
|
||||
public static function brandingDir(): string
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Content;
|
||||
|
||||
use MintyPHP\Repository\PageRepository;
|
||||
use MintyPHP\Repository\PageContentRepository;
|
||||
use MintyPHP\Repository\Content\PageRepository;
|
||||
use MintyPHP\Repository\Content\PageContentRepository;
|
||||
use MintyPHP\I18n;
|
||||
|
||||
class PageService
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Mail;
|
||||
|
||||
use MintyPHP\Repository\MailLogRepository;
|
||||
use MintyPHP\Repository\Mail\MailLogRepository;
|
||||
|
||||
class MailLogService
|
||||
{
|
||||
@@ -1,10 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Mail;
|
||||
|
||||
use MintyPHP\Repository\MailLogRepository;
|
||||
use MintyPHP\Repository\Mail\MailLogRepository;
|
||||
use MintyPHP\I18n;
|
||||
use MintyPHP\Service\SettingService;
|
||||
use MintyPHP\Service\Settings\SettingService;
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception as MailerException;
|
||||
|
||||
@@ -69,7 +69,7 @@ class MailService
|
||||
|
||||
private static function renderTemplate(string $template, array $vars, string $locale): array
|
||||
{
|
||||
$base = dirname(__DIR__, 2) . '/templates/emails';
|
||||
$base = dirname(__DIR__, 3) . '/templates/emails';
|
||||
$htmlPath = $base . '/' . $locale . '/' . $template . '.html';
|
||||
$textPath = $base . '/' . $locale . '/' . $template . '.txt';
|
||||
$htmlHeaderPath = $base . '/' . $locale . '/partials/header.html';
|
||||
@@ -1,12 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Org;
|
||||
|
||||
use MintyPHP\Repository\DepartmentRepository;
|
||||
use MintyPHP\Repository\TenantDepartmentRepository;
|
||||
use MintyPHP\Repository\UserDepartmentRepository;
|
||||
use MintyPHP\Service\SettingService;
|
||||
use MintyPHP\Service\TenantScopeService;
|
||||
use MintyPHP\Repository\Org\DepartmentRepository;
|
||||
use MintyPHP\Repository\Tenant\TenantDepartmentRepository;
|
||||
use MintyPHP\Repository\Org\UserDepartmentRepository;
|
||||
use MintyPHP\Service\Settings\SettingService;
|
||||
use MintyPHP\Service\Tenant\TenantScopeService;
|
||||
|
||||
class DepartmentService
|
||||
{
|
||||
@@ -71,13 +71,17 @@ class DepartmentService
|
||||
{
|
||||
$form = self::sanitizeBase($input);
|
||||
$errors = self::validateBase($form);
|
||||
$warnings = self::warningsForCode($form, 0);
|
||||
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors, 'form' => $form];
|
||||
return ['ok' => false, 'errors' => $errors, 'warnings' => $warnings, 'form' => $form];
|
||||
}
|
||||
|
||||
$createdId = DepartmentRepository::create([
|
||||
'description' => $form['description'],
|
||||
'code' => $form['code'] ?: null,
|
||||
'cost_center' => $form['cost_center'] ?: null,
|
||||
'active' => $form['active'],
|
||||
'created_by' => $currentUserId > 0 ? $currentUserId : null,
|
||||
]);
|
||||
|
||||
@@ -90,20 +94,24 @@ class DepartmentService
|
||||
if (!empty($input['is_default']) && $createdId) {
|
||||
SettingService::setDefaultDepartmentId((int) $createdId);
|
||||
}
|
||||
return ['ok' => true, 'form' => $form, 'uuid' => $uuid, 'id' => (int) $createdId];
|
||||
return ['ok' => true, 'form' => $form, 'warnings' => $warnings, 'uuid' => $uuid, 'id' => (int) $createdId];
|
||||
}
|
||||
|
||||
public static function updateFromAdmin(int $departmentId, array $input, int $currentUserId = 0): array
|
||||
{
|
||||
$form = self::sanitizeBase($input);
|
||||
$errors = self::validateBase($form);
|
||||
$warnings = self::warningsForCode($form, $departmentId);
|
||||
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors, 'form' => $form];
|
||||
return ['ok' => false, 'errors' => $errors, 'warnings' => $warnings, 'form' => $form];
|
||||
}
|
||||
|
||||
$updated = DepartmentRepository::update($departmentId, [
|
||||
'description' => $form['description'],
|
||||
'code' => $form['code'] ?: null,
|
||||
'cost_center' => $form['cost_center'] ?: null,
|
||||
'active' => $form['active'],
|
||||
'modified_by' => $currentUserId > 0 ? $currentUserId : null,
|
||||
]);
|
||||
|
||||
@@ -111,7 +119,7 @@ class DepartmentService
|
||||
return ['ok' => false, 'errors' => [t('Department can not be updated')], 'form' => $form];
|
||||
}
|
||||
|
||||
return ['ok' => true, 'form' => $form];
|
||||
return ['ok' => true, 'form' => $form, 'warnings' => $warnings];
|
||||
}
|
||||
|
||||
public static function syncTenants(int $departmentId, array $tenantIds): int
|
||||
@@ -147,6 +155,9 @@ class DepartmentService
|
||||
{
|
||||
return [
|
||||
'description' => trim((string) ($input['description'] ?? '')),
|
||||
'code' => trim((string) ($input['code'] ?? '')),
|
||||
'cost_center' => trim((string) ($input['cost_center'] ?? '')),
|
||||
'active' => self::normalizeActive($input['active'] ?? 1),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -158,4 +169,23 @@ class DepartmentService
|
||||
}
|
||||
return $errors;
|
||||
}
|
||||
|
||||
private static function warningsForCode(array $form, int $excludeId): array
|
||||
{
|
||||
$warnings = [];
|
||||
$code = $form['code'] ?? '';
|
||||
if ($code !== '' && DepartmentRepository::existsByCode($code, $excludeId)) {
|
||||
$warnings[] = t('Department code already exists');
|
||||
}
|
||||
return $warnings;
|
||||
}
|
||||
|
||||
private static function normalizeActive($value): int
|
||||
{
|
||||
$value = strtolower(trim((string) $value));
|
||||
if (in_array($value, ['0', 'false', 'inactive'], true)) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Settings;
|
||||
|
||||
use MintyPHP\Repository\SettingRepository;
|
||||
use MintyPHP\Repository\TenantRepository;
|
||||
use MintyPHP\Repository\RoleRepository;
|
||||
use MintyPHP\Repository\DepartmentRepository;
|
||||
use MintyPHP\Repository\Settings\SettingRepository;
|
||||
use MintyPHP\Repository\Tenant\TenantRepository;
|
||||
use MintyPHP\Repository\Access\RoleRepository;
|
||||
use MintyPHP\Repository\Org\DepartmentRepository;
|
||||
|
||||
class SettingService
|
||||
{
|
||||
@@ -16,6 +16,7 @@ class SettingService
|
||||
public const APP_LOCALE_KEY = 'app_locale';
|
||||
public const APP_THEME_KEY = 'app_theme';
|
||||
public const APP_THEME_USER_KEY = 'app_theme_user';
|
||||
public const APP_REGISTRATION_KEY = 'app_registration';
|
||||
public const APP_PRIMARY_COLOR_KEY = 'app_primary_color';
|
||||
public const SMTP_HOST_KEY = 'smtp_host';
|
||||
public const SMTP_PORT_KEY = 'smtp_port';
|
||||
@@ -149,7 +150,7 @@ class SettingService
|
||||
{
|
||||
$value = SettingRepository::getValue(self::APP_THEME_KEY);
|
||||
$value = $value !== null ? strtolower(trim((string) $value)) : '';
|
||||
if (!in_array($value, ['light', 'dark'], true)) {
|
||||
if (!in_array($value, self::allowedThemes(), true)) {
|
||||
return null;
|
||||
}
|
||||
return $value;
|
||||
@@ -158,7 +159,7 @@ class SettingService
|
||||
public static function setAppTheme(?string $theme, ?string $description = null): bool
|
||||
{
|
||||
$value = $theme !== null ? strtolower(trim((string) $theme)) : '';
|
||||
if ($value === '' || !in_array($value, ['light', 'dark'], true)) {
|
||||
if ($value === '' || !in_array($value, self::allowedThemes(), true)) {
|
||||
$value = null;
|
||||
}
|
||||
$desc = $description ?? 'setting.app_theme';
|
||||
@@ -181,6 +182,43 @@ class SettingService
|
||||
return SettingRepository::set(self::APP_THEME_USER_KEY, $value, $desc);
|
||||
}
|
||||
|
||||
private static function allowedThemes(): array
|
||||
{
|
||||
$file = dirname(__DIR__, 3) . '/config/themes.php';
|
||||
if (!is_file($file)) {
|
||||
return ['light', 'dark'];
|
||||
}
|
||||
$themes = include $file;
|
||||
if (!is_array($themes)) {
|
||||
return ['light', 'dark'];
|
||||
}
|
||||
$keys = [];
|
||||
foreach ($themes as $key => $label) {
|
||||
$key = strtolower(trim((string) $key));
|
||||
$label = trim((string) $label);
|
||||
if ($key !== '' && $label !== '') {
|
||||
$keys[] = $key;
|
||||
}
|
||||
}
|
||||
return $keys ?: ['light', 'dark'];
|
||||
}
|
||||
|
||||
public static function isRegistrationEnabled(): bool
|
||||
{
|
||||
$value = SettingRepository::getValue(self::APP_REGISTRATION_KEY);
|
||||
if ($value === null || $value === '') {
|
||||
return true;
|
||||
}
|
||||
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
public static function setRegistrationEnabled(bool $allowed, ?string $description = null): bool
|
||||
{
|
||||
$value = $allowed ? '1' : '0';
|
||||
$desc = $description ?? 'setting.app_registration';
|
||||
return SettingRepository::set(self::APP_REGISTRATION_KEY, $value, $desc);
|
||||
}
|
||||
|
||||
public static function getAppPrimaryColor(): ?string
|
||||
{
|
||||
$value = SettingRepository::getValue(self::APP_PRIMARY_COLOR_KEY);
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Tenant;
|
||||
|
||||
class TenantAvatarService
|
||||
{
|
||||
@@ -18,7 +18,7 @@ class TenantAvatarService
|
||||
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
||||
return rtrim(APP_STORAGE_PATH, '/');
|
||||
}
|
||||
return rtrim(dirname(__DIR__, 2) . '/storage', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
||||
}
|
||||
|
||||
public static function tenantDir(string $uuid): string
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Tenant;
|
||||
|
||||
class TenantFaviconService
|
||||
{
|
||||
@@ -24,7 +24,7 @@ class TenantFaviconService
|
||||
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
||||
return rtrim(APP_STORAGE_PATH, '/');
|
||||
}
|
||||
return rtrim(dirname(__DIR__, 2) . '/storage', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
||||
}
|
||||
|
||||
public static function storageDir(string $uuid): string
|
||||
@@ -34,7 +34,7 @@ class TenantFaviconService
|
||||
|
||||
public static function publicDir(string $uuid): string
|
||||
{
|
||||
return rtrim(dirname(__DIR__, 2) . '/web/favicon/tenants/' . $uuid, '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/web/favicon/tenants/' . $uuid . '/favicon', '/');
|
||||
}
|
||||
|
||||
public static function hasFavicon(string $uuid): bool
|
||||
@@ -1,11 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Tenant;
|
||||
|
||||
use MintyPHP\Repository\TenantDepartmentRepository;
|
||||
use MintyPHP\Repository\UserTenantRepository;
|
||||
use MintyPHP\Repository\TenantRepository;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Repository\Tenant\TenantDepartmentRepository;
|
||||
use MintyPHP\Repository\Tenant\UserTenantRepository;
|
||||
use MintyPHP\Repository\Tenant\TenantRepository;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
|
||||
class TenantScopeService
|
||||
{
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\Tenant;
|
||||
|
||||
use MintyPHP\Repository\TenantRepository;
|
||||
use MintyPHP\Service\SettingService;
|
||||
use MintyPHP\Repository\Tenant\TenantRepository;
|
||||
use MintyPHP\Service\Settings\SettingService;
|
||||
|
||||
class TenantService
|
||||
{
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\User;
|
||||
|
||||
class UserAvatarService
|
||||
{
|
||||
@@ -18,7 +18,7 @@ class UserAvatarService
|
||||
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
||||
return rtrim(APP_STORAGE_PATH, '/');
|
||||
}
|
||||
return rtrim(dirname(__DIR__, 2) . '/storage', '/');
|
||||
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
||||
}
|
||||
|
||||
public static function userDir(string $uuid): string
|
||||
@@ -1,18 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Service;
|
||||
namespace MintyPHP\Service\User;
|
||||
|
||||
use MintyPHP\I18n;
|
||||
use MintyPHP\Repository\DepartmentRepository;
|
||||
use MintyPHP\Repository\RoleRepository;
|
||||
use MintyPHP\Repository\TenantRepository;
|
||||
use MintyPHP\Repository\UserRepository;
|
||||
use MintyPHP\Repository\UserDepartmentRepository;
|
||||
use MintyPHP\Repository\UserRoleRepository;
|
||||
use MintyPHP\Repository\UserTenantRepository;
|
||||
use MintyPHP\Repository\TenantDepartmentRepository;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\TenantScopeService;
|
||||
use MintyPHP\Repository\Org\DepartmentRepository;
|
||||
use MintyPHP\Repository\Access\RoleRepository;
|
||||
use MintyPHP\Repository\Tenant\TenantRepository;
|
||||
use MintyPHP\Repository\User\UserRepository;
|
||||
use MintyPHP\Repository\Org\UserDepartmentRepository;
|
||||
use MintyPHP\Repository\Access\UserRoleRepository;
|
||||
use MintyPHP\Repository\Tenant\UserTenantRepository;
|
||||
use MintyPHP\Repository\Tenant\TenantDepartmentRepository;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
use MintyPHP\Service\Tenant\TenantScopeService;
|
||||
|
||||
class UserService
|
||||
{
|
||||
@@ -447,7 +447,7 @@ class UserService
|
||||
{
|
||||
$ids = array_values(array_unique(array_map('intval', $roleIds)));
|
||||
$ids = array_filter($ids, static fn ($id) => $id > 0);
|
||||
$validIds = RoleRepository::listIds();
|
||||
$validIds = RoleRepository::listActiveIds();
|
||||
if ($validIds) {
|
||||
$validMap = array_fill_keys($validIds, true);
|
||||
$ids = array_values(array_filter($ids, static fn ($id) => isset($validMap[$id])));
|
||||
@@ -520,8 +520,9 @@ class UserService
|
||||
private static function normalizeTheme($value): string
|
||||
{
|
||||
$theme = strtolower(trim((string) $value));
|
||||
if (!in_array($theme, ['dark', 'light'], true)) {
|
||||
return 'light';
|
||||
$themes = function_exists('appThemes') ? appThemes() : ['light' => 'Light', 'dark' => 'Dark'];
|
||||
if ($theme === '' || !isset($themes[$theme])) {
|
||||
return function_exists('appDefaultTheme') ? appDefaultTheme() : 'light';
|
||||
}
|
||||
return $theme;
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
use MintyPHP\Router;
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\TenantService;
|
||||
use MintyPHP\Service\AuthService;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
use MintyPHP\Service\Tenant\TenantService;
|
||||
use MintyPHP\Service\Auth\AuthService;
|
||||
use MintyPHP\Http\Request;
|
||||
|
||||
class Guard
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace MintyPHP\Support;
|
||||
|
||||
use MintyPHP\Service\PermissionService;
|
||||
use MintyPHP\Service\UserAvatarService;
|
||||
use MintyPHP\Service\Access\PermissionService;
|
||||
use MintyPHP\Service\User\UserAvatarService;
|
||||
|
||||
class SearchConfig
|
||||
{
|
||||
@@ -17,97 +17,125 @@ class SearchConfig
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
private static function normalizeLikeQuery(string $query): string
|
||||
{
|
||||
$query = trim($query);
|
||||
if ($query === '') {
|
||||
return '';
|
||||
}
|
||||
$query = str_replace('\\', '\\\\', $query);
|
||||
$query = str_replace('_', '\\_', $query);
|
||||
$query = str_replace('*', '%', $query);
|
||||
if (!str_starts_with($query, '%')) {
|
||||
$query = '%' . $query;
|
||||
}
|
||||
if (!str_ends_with($query, '%')) {
|
||||
$query = $query . '%';
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
public static function normalizeScoreQuery(string $query): string
|
||||
{
|
||||
$query = trim($query);
|
||||
if ($query == '') {
|
||||
return '';
|
||||
}
|
||||
return str_replace(['*', '%', '_'], '', $query);
|
||||
}
|
||||
|
||||
public static function resources(string $query, string $locale): array
|
||||
{
|
||||
$like = '%' . $query . '%';
|
||||
$like = self::normalizeLikeQuery($query);
|
||||
|
||||
return [
|
||||
[
|
||||
'key' => 'address-book',
|
||||
'label' => t('Address book'),
|
||||
'permission' => PermissionService::ADDRESS_BOOK_VIEW,
|
||||
'countSql' => 'select count(*) from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}}',
|
||||
'countSql' => "select count(*) from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}}",
|
||||
'countParams' => [$like, $like, $like],
|
||||
'previewSql' => 'select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name limit ?',
|
||||
'previewSql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name limit ?",
|
||||
'previewParams' => [$like, $like, $like],
|
||||
'resultSql' => 'select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name',
|
||||
'resultSql' => "select uuid, first_name, last_name, email from users where active = 1 and (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name",
|
||||
'resultParams' => [$like, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'users',
|
||||
'label' => t('Users'),
|
||||
'permission' => PermissionService::USERS_VIEW,
|
||||
'countSql' => 'select count(*) from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}}',
|
||||
'countSql' => "select count(*) from users where (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}}",
|
||||
'countParams' => [$like, $like, $like],
|
||||
'previewSql' => 'select uuid, first_name, last_name, email from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name limit ?',
|
||||
'previewSql' => "select uuid, first_name, last_name, email from users where (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name limit ?",
|
||||
'previewParams' => [$like, $like, $like],
|
||||
'resultSql' => 'select uuid, first_name, last_name, email from users where (first_name like ? or last_name like ? or email like ?) {{tenantFilter}} order by last_name, first_name',
|
||||
'resultSql' => "select uuid, first_name, last_name, email from users where (first_name like ? escape '\\\\' or last_name like ? escape '\\\\' or email like ? escape '\\\\') {{tenantFilter}} order by last_name, first_name",
|
||||
'resultParams' => [$like, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'tenants',
|
||||
'label' => t('Tenants'),
|
||||
'permission' => PermissionService::TENANTS_VIEW,
|
||||
'countSql' => 'select count(*) from tenants where description like ? {{tenantFilter}}',
|
||||
'countSql' => "select count(*) from tenants where description like ? escape '\\\\' {{tenantFilter}}",
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from tenants where description like ? {{tenantFilter}} order by description limit ?',
|
||||
'previewSql' => "select uuid, description from tenants where description like ? escape '\\\\' {{tenantFilter}} order by description limit ?",
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from tenants where description like ? {{tenantFilter}} order by description',
|
||||
'resultSql' => "select uuid, description from tenants where description like ? escape '\\\\' {{tenantFilter}} order by description",
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'departments',
|
||||
'label' => t('Departments'),
|
||||
'permission' => PermissionService::DEPARTMENTS_VIEW,
|
||||
'countSql' => 'select count(*) from departments where description like ? {{tenantFilter}}',
|
||||
'countSql' => "select count(*) from departments where description like ? escape '\\\\' {{tenantFilter}}",
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from departments where description like ? {{tenantFilter}} order by description limit ?',
|
||||
'previewSql' => "select uuid, description from departments where description like ? escape '\\\\' {{tenantFilter}} order by description limit ?",
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from departments where description like ? {{tenantFilter}} order by description',
|
||||
'resultSql' => "select uuid, description from departments where description like ? escape '\\\\' {{tenantFilter}} order by description",
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'roles',
|
||||
'label' => t('Roles'),
|
||||
'permission' => PermissionService::ROLES_VIEW,
|
||||
'countSql' => 'select count(*) from roles where description like ?',
|
||||
'countSql' => "select count(*) from roles where active = 1 and description like ? escape '\\\\'",
|
||||
'countParams' => [$like],
|
||||
'previewSql' => 'select uuid, description from roles where description like ? order by description limit ?',
|
||||
'previewSql' => "select uuid, description from roles where active = 1 and description like ? escape '\\\\' order by description limit ?",
|
||||
'previewParams' => [$like],
|
||||
'resultSql' => 'select uuid, description from roles where description like ? order by description',
|
||||
'resultSql' => "select uuid, description from roles where active = 1 and description like ? escape '\\\\' order by description",
|
||||
'resultParams' => [$like],
|
||||
],
|
||||
[
|
||||
'key' => 'permissions',
|
||||
'label' => t('Permissions'),
|
||||
'permission' => PermissionService::PERMISSIONS_VIEW,
|
||||
'countSql' => 'select count(*) from permissions where `key` like ? or description like ?',
|
||||
'countSql' => "select count(*) from permissions where active = 1 and (`key` like ? escape '\\\\' or description like ? escape '\\\\')",
|
||||
'countParams' => [$like, $like],
|
||||
'previewSql' => 'select id, description, `key` from permissions where `key` like ? or description like ? order by `key` limit ?',
|
||||
'previewSql' => "select id, description, `key` from permissions where active = 1 and (`key` like ? escape '\\\\' or description like ? escape '\\\\') order by `key` limit ?",
|
||||
'previewParams' => [$like, $like],
|
||||
'resultSql' => 'select id, description, `key` from permissions where `key` like ? or description like ? order by `key`',
|
||||
'resultSql' => "select id, description, `key` from permissions where active = 1 and (`key` like ? escape '\\\\' or description like ? escape '\\\\') order by `key`",
|
||||
'resultParams' => [$like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'pages',
|
||||
'label' => t('Pages'),
|
||||
'permission' => '',
|
||||
'countSql' => 'select count(*) from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ?',
|
||||
'countSql' => "select count(*) from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? escape '\\\\' or pc.content like ? escape '\\\\'",
|
||||
'countParams' => [$locale, $like, $like],
|
||||
'previewSql' => 'select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ? order by p.slug limit ?',
|
||||
'previewSql' => "select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? escape '\\\\' or pc.content like ? escape '\\\\' order by p.slug limit ?",
|
||||
'previewParams' => [$locale, $like, $like],
|
||||
'resultSql' => 'select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? or pc.content like ? order by p.slug',
|
||||
'resultSql' => "select p.slug from pages p join page_contents pc on pc.page_id = p.id and pc.locale = ? where p.slug like ? escape '\\\\' or pc.content like ? escape '\\\\' order by p.slug",
|
||||
'resultParams' => [$locale, $like, $like],
|
||||
],
|
||||
[
|
||||
'key' => 'settings',
|
||||
'label' => t('Settings'),
|
||||
'permission' => PermissionService::SETTINGS_VIEW,
|
||||
'countSql' => 'select count(*) from settings where `key` like ? or value like ?',
|
||||
'countSql' => "select count(*) from settings where `key` like ? escape '\\\\' or value like ? escape '\\\\'",
|
||||
'countParams' => [$like, $like],
|
||||
'previewSql' => null,
|
||||
'previewParams' => [],
|
||||
'resultSql' => 'select `key`, value from settings where `key` like ? or value like ? order by `key`',
|
||||
'resultSql' => "select `key`, value from settings where `key` like ? escape '\\\\' or value like ? escape '\\\\' order by `key`",
|
||||
'resultParams' => [$like, $like],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -14,6 +14,8 @@ class Tile
|
||||
'iconBg' => null,
|
||||
'iconColor' => null,
|
||||
'class' => '',
|
||||
'tooltip' => '',
|
||||
'tooltipPos' => 'top',
|
||||
];
|
||||
|
||||
$data = array_merge($defaults, $options);
|
||||
|
||||
@@ -10,6 +10,23 @@ function asset(string $path): string
|
||||
return \MintyPHP\Router::getBaseUrl() . ltrim($path, '/');
|
||||
}
|
||||
|
||||
function templatePath(string $path): string
|
||||
{
|
||||
return dirname(__DIR__, 3) . '/templates/' . ltrim($path, '/');
|
||||
}
|
||||
|
||||
function assetVersion(string $path): string
|
||||
{
|
||||
$path = ltrim($path, '/');
|
||||
$file = dirname(__DIR__, 3) . '/web/' . $path;
|
||||
$url = asset($path);
|
||||
$version = @filemtime($file);
|
||||
if ($version === false) {
|
||||
return $url;
|
||||
}
|
||||
return $url . '?v=' . $version;
|
||||
}
|
||||
|
||||
function localeBase(): string
|
||||
{
|
||||
$locale = \MintyPHP\I18n::$locale ?? \MintyPHP\I18n::$defaultLocale;
|
||||
@@ -58,6 +75,16 @@ function appUrl(string $path = ''): string
|
||||
return $base . '/' . $path;
|
||||
}
|
||||
|
||||
function currentUserDisplayName(): string
|
||||
{
|
||||
$user = $_SESSION['user'] ?? [];
|
||||
$name = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
|
||||
if ($name !== '') {
|
||||
return $name;
|
||||
}
|
||||
return trim((string) ($user['email'] ?? ''));
|
||||
}
|
||||
|
||||
function appLogoUrlAbsolute(int $size = 128): string
|
||||
{
|
||||
$url = appLogoUrl($size);
|
||||
@@ -79,6 +106,36 @@ function appSetting(string $key): ?string
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
function appThemes(): array
|
||||
{
|
||||
$file = dirname(__DIR__, 3) . '/config/themes.php';
|
||||
if (!is_file($file)) {
|
||||
return [
|
||||
'light' => 'Light',
|
||||
'dark' => 'Dark',
|
||||
];
|
||||
}
|
||||
$themes = include $file;
|
||||
if (!is_array($themes)) {
|
||||
return [
|
||||
'light' => 'Light',
|
||||
'dark' => 'Dark',
|
||||
];
|
||||
}
|
||||
$clean = [];
|
||||
foreach ($themes as $key => $label) {
|
||||
$key = strtolower(trim((string) $key));
|
||||
$label = trim((string) $label);
|
||||
if ($key !== '' && $label !== '') {
|
||||
$clean[$key] = $label;
|
||||
}
|
||||
}
|
||||
return $clean ?: [
|
||||
'light' => 'Light',
|
||||
'dark' => 'Dark',
|
||||
];
|
||||
}
|
||||
|
||||
function appDefaultLocale(): ?string
|
||||
{
|
||||
$locale = appSetting('app_locale');
|
||||
@@ -94,13 +151,29 @@ function appDefaultLocale(): ?string
|
||||
|
||||
function appDefaultTheme(): string
|
||||
{
|
||||
$themes = appThemes();
|
||||
$setting = appSetting('app_theme');
|
||||
if (in_array($setting, ['light', 'dark'], true)) {
|
||||
if ($setting !== null && isset($themes[$setting])) {
|
||||
return $setting;
|
||||
}
|
||||
$envTheme = getenv('APP_THEME') ?: 'light';
|
||||
$envTheme = strtolower(trim((string) $envTheme));
|
||||
return in_array($envTheme, ['light', 'dark'], true) ? $envTheme : 'light';
|
||||
return isset($themes[$envTheme]) ? $envTheme : 'light';
|
||||
}
|
||||
|
||||
function currentTheme(): string
|
||||
{
|
||||
$themes = appThemes();
|
||||
$theme = appDefaultTheme();
|
||||
if (!allowUserTheme()) {
|
||||
return $theme;
|
||||
}
|
||||
$user = $_SESSION['user'] ?? [];
|
||||
$userTheme = strtolower(trim((string) ($user['theme'] ?? '')));
|
||||
if ($userTheme !== '' && isset($themes[$userTheme])) {
|
||||
return $userTheme;
|
||||
}
|
||||
return $theme;
|
||||
}
|
||||
|
||||
function allowUserTheme(): bool
|
||||
@@ -112,6 +185,15 @@ function allowUserTheme(): bool
|
||||
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
function allowRegistration(): bool
|
||||
{
|
||||
$value = appSetting('app_registration');
|
||||
if ($value === null || $value === '') {
|
||||
return true;
|
||||
}
|
||||
return in_array(strtolower($value), ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
function appPrimaryColor(): ?string
|
||||
{
|
||||
$tenantColor = $_SESSION['current_tenant']['primary_color'] ?? null;
|
||||
@@ -147,26 +229,40 @@ function appPrimaryCssVars(): string
|
||||
$g = hexdec(substr($hex, 2, 2)) / 255;
|
||||
$b = hexdec(substr($hex, 4, 2)) / 255;
|
||||
|
||||
$monoThreshold = 0.000001;
|
||||
if (abs($r - $g) < $monoThreshold && abs($g - $b) < $monoThreshold) {
|
||||
$l = round($r * 100, 2) . '%';
|
||||
return "--app-primary-h-base: 0; --app-primary-s-base: 0%; --app-primary-l-base: {$l}; --app-primary-h-light: 0; --app-primary-s-light: 0%; --app-primary-l-light: {$l};";
|
||||
}
|
||||
|
||||
$max = max($r, $g, $b);
|
||||
$min = min($r, $g, $b);
|
||||
$delta = $max - $min;
|
||||
|
||||
if ($delta == 0.0) {
|
||||
$l = round((($max + $min) / 2) * 100, 2) . '%';
|
||||
return "--app-primary-h-base: 0; --app-primary-s-base: 0%; --app-primary-l-base: {$l}; --app-primary-h-light: 0; --app-primary-s-light: 0%; --app-primary-l-light: {$l};";
|
||||
}
|
||||
|
||||
$h = 0.0;
|
||||
if ($delta !== 0.0) {
|
||||
if ($max === $r) {
|
||||
$h = 60 * fmod((($g - $b) / $delta), 6);
|
||||
} elseif ($max === $g) {
|
||||
$h = 60 * ((($b - $r) / $delta) + 2);
|
||||
} else {
|
||||
$h = 60 * ((($r - $g) / $delta) + 4);
|
||||
}
|
||||
if ($max === $r) {
|
||||
$h = 60 * fmod((($g - $b) / $delta), 6);
|
||||
} elseif ($max === $g) {
|
||||
$h = 60 * ((($b - $r) / $delta) + 2);
|
||||
} else {
|
||||
$h = 60 * ((($r - $g) / $delta) + 4);
|
||||
}
|
||||
if ($h < 0) {
|
||||
$h += 360;
|
||||
}
|
||||
|
||||
$l = ($max + $min) / 2;
|
||||
$s = $delta === 0.0 ? 0.0 : $delta / (1 - abs(2 * $l - 1));
|
||||
$denominator = 1 - abs(2 * $l - 1);
|
||||
if ($delta === 0.0 || $denominator == 0.0) {
|
||||
$s = 0.0;
|
||||
} else {
|
||||
$s = $delta / $denominator;
|
||||
}
|
||||
|
||||
$h = round($h, 2);
|
||||
$s = round($s * 100, 2) . '%';
|
||||
@@ -177,7 +273,7 @@ function appPrimaryCssVars(): string
|
||||
|
||||
function appLogoUrl(?int $size = null): string
|
||||
{
|
||||
if (class_exists('MintyPHP\\Service\\BrandingLogoService') && \MintyPHP\Service\BrandingLogoService::hasLogo()) {
|
||||
if (class_exists('MintyPHP\\Service\\Branding\\BrandingLogoService') && \MintyPHP\Service\Branding\BrandingLogoService::hasLogo()) {
|
||||
$query = $size ? '?size=' . (int) $size : '';
|
||||
return lurl('branding/logo' . $query);
|
||||
}
|
||||
@@ -187,9 +283,9 @@ function appLogoUrl(?int $size = null): string
|
||||
function appFaviconUrl(string $file): string
|
||||
{
|
||||
$tenantUuid = $_SESSION['current_tenant']['uuid'] ?? '';
|
||||
if ($tenantUuid !== '' && class_exists('MintyPHP\\Service\\TenantFaviconService')) {
|
||||
if (\MintyPHP\Service\TenantFaviconService::hasFavicon($tenantUuid)) {
|
||||
return asset('favicon/tenants/' . $tenantUuid . '/' . ltrim($file, '/'));
|
||||
if ($tenantUuid !== '' && class_exists('MintyPHP\\Service\\Tenant\\TenantFaviconService')) {
|
||||
if (\MintyPHP\Service\Tenant\TenantFaviconService::hasFavicon($tenantUuid)) {
|
||||
return asset('favicon/tenants/' . $tenantUuid . '/favicon/' . ltrim($file, '/'));
|
||||
}
|
||||
}
|
||||
return asset('favicon/' . ltrim($file, '/'));
|
||||
|
||||
@@ -13,12 +13,12 @@ function can(string $permissionKey): bool
|
||||
if ($userId <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (!class_exists('MintyPHP\\Service\\PermissionService')) {
|
||||
if (!class_exists('MintyPHP\\Service\\Access\\PermissionService')) {
|
||||
return false;
|
||||
}
|
||||
$keys = \MintyPHP\Service\PermissionService::getCachedPermissions($userId);
|
||||
$keys = \MintyPHP\Service\Access\PermissionService::getCachedPermissions($userId);
|
||||
if (!$keys) {
|
||||
$keys = \MintyPHP\Service\PermissionService::getUserPermissions($userId);
|
||||
$keys = \MintyPHP\Service\Access\PermissionService::getUserPermissions($userId);
|
||||
if (!$keys) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user