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,
|
||||
Reference in New Issue
Block a user