HEX
Server: nginx/1.18.0
System: Linux test-ipsremont 5.4.0-214-generic #234-Ubuntu SMP Fri Mar 14 23:50:27 UTC 2025 x86_64
User: ips (1000)
PHP: 8.0.30
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/heifetz/heifetz-app/models/Dictionary.php
<?php

namespace Models;

use Core\Models\Acl;
use Core\Models\OldUser;
use Core\Models\RedisCache;
use Exception;
use Helpers\ArrayHelper;
use Models\Repositories\DictionaryRepository;
use Traits\ModelGetQuery;

/**
 * @property int $id
 * @property string $name
 * @property int $deleted
 * @property int $active
 */
class Dictionary extends AbstractModel
{

    use ModelGetQuery;

    /** @deprecated */
    const TABLE_CITIZENSHIP = 'citizenship';
    /** @deprecated */
    const TABLE_FACTORIES = 'factories';
    /** @deprecated */
    const TABLE_FEEDBACK = 'feedback';
    /** @deprecated */
    const TABLE_LEAD_STATUS_REASONS = 'dic_lead_status_reasons';
    /** @deprecated */
    const TABLE_OVERALLS_LIST = 'overalls_list';
    /** @deprecated */
    const TABLE_PROFESSIONS = 'professions';
    /** @deprecated */
    const TABLE_UNIT_CONTRACT_CONTRACTORS = 'unit_contract_contractors';

    /** @deprecated */
    static array $tablesWithBool = [
        DictionaryRepository::TABLE_LEAD_STATUS_REASONS,
        DictionaryRepository::TABLE_PROTOCOL_TYPES,
        DictionaryRepository::TABLE_SUBWAYS,
        DictionaryRepository::TABLE_SALARY_PROJECTS,
    ];

    public static function save($tableName, $dictionaryId, $data)
    {
        if ($tableName == DictionaryRepository::TABLE_SALARY_PROJECTS && !(OldUser::isManager() || OldUser::isSystemManager())) {
            return null;
        }
        UserLogs::logUpdate($tableName, $dictionaryId, 'record', $data);

        return self::$db->update($tableName, $data, ['id' => $dictionaryId]);
    }

    public static function getRules(): array
    {
        return [
            'name' => 'required|size:255',
            'company_id' => 'required|integer',
        ];
    }

    public static function getData()
    {
        $data = [];

        foreach (DictionaryRepository::$tables as $tableName => $tableTitle) {
            $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

            if ($tableName == DictionaryRepository::TABLE_SALARY_PROJECTS) {
                if (OldUser::isManager() || OldUser::isSystemManager()) {
                    $sqlSalaryProject = self::$db->select()->from($tableName)->where('deleted = ?', $isBoolTable ? false : 0);
                    if (!empty($companyId)) {
                        $sqlSalaryProject->where('company_id = ?', $companyId);
                    }
                    $data[] = [
                        'name' => $tableTitle,
                        'alias' => $tableName,
                        'count' => $sqlSalaryProject->totalCount(),
                    ];
                }
                continue;
            }

            if (Acl::isUserAllowed(OldUser::getId(), Acl::PRESENTER_DICTIONARIES, 'all', $tableName)) {
                $sql = self::$db->select()->from($tableName)->where('deleted = ?', $isBoolTable ? false : 0);
                if (!empty($companyId)) {
                    $sql->where('company_id = ?', $companyId);
                }
                $data[] = [
                    'name' => $tableTitle,
                    'alias' => $tableName,
                    'count' => $sql->totalCount(),
                ];
            }
        }

        return $data;
    }

    /**
     * @param $tableName
     * @param $id
     *
     * @return mixed
     *
     * @deprecated Use <Model>::getName
     */
    public static function getName($tableName, $id)
    {
        $isBoolTable = in_array($tableName, self::$tablesWithBool);

        return self::$db->select('name')->from($tableName)
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->where('id = ?', (int) $id)
            ->fetchOne();
    }

    public static function getId($tableName, $name)
    {
        $isBoolTable = in_array($tableName, self::$tablesWithBool);

        return self::$db->select('id')->from($tableName)
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->where('name = ?', $name)
            ->fetchOne();
    }

    /**
     * @param string $tableName
     * @param int $id
     * @param bool $showDeleted
     *
     * @return object|null|AbstractDictionary
     *
     * @deprecated use AbstractDictionary::get()
     */
    public static function get(string $tableName, int $id, bool $showDeleted = false)
    {
        $sql = self::$db->select()->from($tableName)->where('id = ?', $id);
        $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

        if (!$showDeleted) {
            $sql->where('deleted = ?', $isBoolTable ? $showDeleted : (int) $showDeleted);
        }

        return $sql->company()->fetchRow();
    }

    /**
     * TODO active используется только для предприятия надо переделать это
     *
     * @param string $tableName
     * @param bool $activeOnly
     * @param bool $showDeleted
     * @param null|string $keyByField
     *
     * @return Dictionary[]|object[]
     */
    public static function getTableData(string $tableName, bool $activeOnly = false, bool $showDeleted = false, ?string $keyByField = null): array
    {
        $sql = self::$db->select()->from($tableName)->company();

        $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

        if ($activeOnly) {
            $sql->where('active = ?', $isBoolTable ? true : 1);
        }

        if (!$showDeleted) {
            $sql->where('deleted = ?', $isBoolTable ? false : 0);
        }

        $tableData = $sql->order('name', 'ASC')->fetchAll();

        if (isset($keyByField)) {
            $tableData = ArrayHelper::keyByField($tableData, $keyByField);
        }

        return $tableData;
    }

    public static function getByIds($tableName, $ids, $activeOnly = false, $showDeleted = false, $keyByField = null)
    {
        if (empty($ids)) {
            return [];
        }

        $isBoolTable = in_array($tableName, self::$tablesWithBool);

        $sql = self::$db->select()->from($tableName)->company()
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->whereIn('id', $ids)
            ->order('name', 'ASC');

        if ($activeOnly) {
            $sql->where('active = ?', $isBoolTable ? true : 1);
        }

        if (!$showDeleted) {
            $sql->where('deleted = ?', $isBoolTable ? false : 0);
        }

        $tableData = $sql->fetchAll();

        if (isset($keyByField)) {
            $tableData = ArrayHelper::keyByField($tableData, $keyByField);
        }

        return $tableData;
    }

    public static function getTableDataIds(string $tableName, bool $activeOnly = false): array
    {
        $isBoolTable = in_array($tableName, self::$tablesWithBool);
        $sql = self::$db->select('id')->from($tableName)->company()
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->order('name', 'ASC');

        if ($activeOnly) {
            $sql->where('active = ?', $isBoolTable ? true : 1);
        }

        return $sql->fetchCol();
    }

    public static function isExists(string $tableName, string $word, bool $deleted = false, int $dictionaryId = null): bool
    {
        $sql = self::$db->select('id')->from($tableName)->where('LOWER(name) = ?', mb_strtolower($word));
        if (!$deleted) {
            $isBoolTable = in_array($tableName, self::$tablesWithBool);
            $sql->where('deleted = ?', $isBoolTable ? false : 0);
        }
        if (!empty($dictionaryId)) {
            $sql->where('id != ?', $dictionaryId);
        }

        return (bool) $sql->totalCount('id');
    }

    public static function add(string $tableName, string $word, $key = null): int
    {
        $data = [$word];
        $columns = ['name'];
        if (!empty($key)) {
            $data[] = $key;
            $columns[] = 'key';
        }
        $dictionaryId = self::$db->insert($tableName, $columns, [$data]);

        $cache = RedisCache::create();
        $cache->delete($cache->keys($tableName . '*'));

        UserLogs::logCreate($tableName, $dictionaryId, $word);

        return $dictionaryId;
    }

    public static function remove(string $tableName, int $dictionaryId): int
    {
        $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

        $data = ['deleted' => $isBoolTable ? true : 1];
        switch ($tableName) {
            // Если предприятие удаляется — увольняем всех работников.
            case DictionaryRepository::TABLE_FACTORIES:
                Factories::freeFromFactory($dictionaryId);
                $data['active'] = $isBoolTable ? false : 0;
                break;
        }

        $cache = RedisCache::create();
        $cache->delete($cache->keys($tableName . '*'));

        UserLogs::logDelete($tableName, $dictionaryId);

        return self::save($tableName, $dictionaryId, $data);
    }

    public static function recover($tableName, $dictionaryId)
    {
        $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

        return self::save($tableName, $dictionaryId, ['deleted' => $isBoolTable ? false : 0]);
    }

    public static function updateRow($tableName, $dictionaryId, $value, $pid = null, $externalId = null, $key = null)
    {
        $values = ['name' => $value];

        if (!is_null($pid) && trim($pid) !== '') {
            if ($dictionaryId === $pid) {
                return false;
            }
            $values['pid'] = $pid;
        }

        if (!empty($externalId) && in_array($tableName, [Dictionary::TABLE_FACTORIES, Dictionary::TABLE_PROFESSIONS, Dictionary::TABLE_UNIT_CONTRACT_CONTRACTORS])) {
            $values['external_id'] = $externalId;
        }
        if (DictionaryRepository::dictionaryHasKey($tableName)) {
            $values['key'] = $key;
        }

        return self::save($tableName, $dictionaryId, $values);
    }

    public static function updateState($tableName, $dictionaryId, $state)
    {
        $isBoolTable = in_array($tableName, DictionaryRepository::$tablesWithBool);

        return self::save($tableName, $dictionaryId, ['active' => $isBoolTable ? boolval($state) : intval($state)]);
    }

    public static function markInactive($list)
    {
        if (is_array($list)) {
            foreach ($list as &$record) {
                if (!$record->active) {
                    $record->name .= ' 🔴';
                }
            }
        }

        return $list;
    }

    /**
     * @param $tableName
     * @param $id
     *
     * @return bool
     *
     * @deprecated Factories::hasChildren()
     */
    public static function hasChildren($tableName, $id)
    {
        $isBoolTable = in_array($tableName, self::$tablesWithBool);

        return (bool) self::$db->select('COUNT(id)')->from($tableName)
            ->where('pid = ?', $id)
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->where('active = ?', $isBoolTable ? true : 1)
            ->fetchOne();
    }

    /**
     * @param $tableName
     * @param $ids
     * @param bool $recursive
     *
     * @return array
     *
     * @deprecated Factories::getChildrenIds()
     */
    public static function getChildrenIds($tableName, $ids, $recursive = false)
    {
        if (0 == $ids) {
            return [];
        }

        if (empty($ids)) {
            throw new Exception('Некорректный параметр $ids');
        }

        $ids = is_array($ids) ? $ids : [$ids];
        $isBoolTable = in_array($tableName, self::$tablesWithBool);

        if ($recursive) {
            $dictionary = self::getTableData($tableName, false, true);

            $count = count($ids);
            do {
                $oldCount = $count;
                array_map(
                    function ($item) use (&$ids) {
                        if (in_array($item->pid, $ids)) {
                            $ids[] = $item->id;
                        }
                    },
                    $dictionary
                );
                $ids = array_unique($ids);
                $count = count($ids);
            } while ($oldCount != $count);
        }

        return self::$db->select('id')->from($tableName)
            ->where('pid IN (?)', $ids)
            ->where('deleted = ?', $isBoolTable ? false : 0)
            ->where('active = ?', $isBoolTable ? true : 1)
            ->fetchCol();
    }

    /** @deprecated */
    public static function getRootIds($tableName, array $ids)
    {
        $result = [];
        foreach ($ids as $id) {
            $item = self::get($tableName, $id);
            if ($item->pid == 0) {
                $result[] = $item->id;
            } else {
                $result[] = $item->pid;
            }
        }

        return array_unique($result);
    }

    /** @deprecated */
    public static function getRoot($tableName, array $ids)
    {
        $result = [];
        foreach ($ids as $id) {
            $item = self::get($tableName, $id);
            if (empty($item)) {
                continue;
            }
            if ($item->pid == 0) {
                $result[$item->id] = $item;
            } else {
                $result[$item->pid] = self::get($tableName, $item->pid);
            }
        }

        return $result;
    }

    public static function isKeyExist(string $tableName, string $key, int $companyId, int $dictionaryId = null): bool
    {
        $sql = self::$db->select('id')->from($tableName)->where('key = ?', $key)->where('company_id = ?', $companyId);
        if (!empty($dictionaryId)) {
            $sql->where('id != ?', $dictionaryId);
        }

        return (bool) $sql->totalCount('id');
    }

}