<?php
namespace Fusion\KPI;
use \Bitrix\Main\SystemException;
use \Bitrix\Main\ErrorCollection;
use \Bitrix\Main\Error;
class Map
{
/**
* Ошибки в работе класса
*
* @var \Bitrix\Main\ErrorCollection
*/
protected $errors;
/**
* Массив полей текущего объекта
*
* @var []
*/
protected $fields = [];
/**
* Идентификатор текущей карты
*
* @var integer
*/
private $_id;
/**
* Коллекция разделов текущей карты
*
* @var \Fusion\KPI\Section[]
*/
private $_sectionCollection = [];
/**
* Роли пользователя
* @todo убрать
* @var array
*/
private $_userRole = [];
/**
* Конструктор класса
* Загружает значение полей
*
* @param int $id
*/
public function __construct($id)
{
$this->errors = new ErrorCollection();
if (!empty($id)) {
$this->_id = $id;
$this->_getFields();
} else {
ErrorManager::addError($this->errors, 'Не указан id карты');
}
}
/**
* Магический метод
*
* @param string $key
* @return \Fusion\KPI\Section[]|\Fusion\KPI\[]|var|NULL
*/
public function __get($key)
{
if ($key == 'sectionCollection') {
if (empty($this->_sectionCollection)) {
$this->_loadSectionCollection();
}
return $this->_sectionCollection['data'];
}
$key = strtoupper($key);
if (array_key_exists($key, $this->fields)) {
return $this->fields[$key];
}
return null;
}
/**
*
* @return integer
*/
public function getId()
{
return $this->_id;
}
/**
* Создаёт разделы карты определённые типом карты
*
* @return boolean
*/
public function setSections($periods = null)
{
$objectTypePeiodRelations = Orm\TypePeriodTable::GetList([
'filter' => [
'TYPE_ID' => $this->type_id
],
'select' => [
'PERIOD_ID'
]
]);
$sectionFields = [
'MAP_ID' => $this->getId()
];
foreach ($objectTypePeiodRelations as $typePeiodRelations) {
if($periods !== null)
{
if(!in_array($typePeiodRelations['PERIOD_ID'], $periods))
{
continue;
}
}
$sectionFields['PERIOD_ID'] = $typePeiodRelations['PERIOD_ID'];
$addSectionResult = Section::create($sectionFields);
if ($addSectionResult->isSuccess()) {
$objectSection = new Section($addSectionResult->getid());
if (! $objectSection->hasErrors()) {
$this->_loadSectionCollection();
} else {
$this->errors = $objectSection->getErrors();
return false;
}
} else {
ErrorManager::addResultError($this->errors, $addSectionResult);
return false;
}
}
return true;
}
/**
* Смена статуса карты
*
* @param string $staus
* @return boolean
*/
public function setStatus($status = null)
{
if (empty($status)) {
ErrorManager::addError($this->errors, 'Статус не указан');
return false;
}
if ($status == $this->status) {
return true;
}
$arFields = [
'STATUS' => $status,
'DATE_UPDATE' => new \Bitrix\Main\Type\DateTime(),
'UPDATE_BY' => Config::getUser()->getId()
];
$result = Orm\MapTable::update($this->getId(), $arFields);
if ($result->isSuccess()) {
return true;
} else {
ErrorManager::addResultError($this->errors, $result);
return false;
}
}
/**
* Метод обновляет мета-данные по карте
*
* @author Andrey Nikolaev
* @param int $userId
* @return boolean
*/
public function touchBy($userId = 0)
{
$userId = empty($userId) ? Config::getUser()->getId() : $userId;
$arFields = [
'DATE_UPDATE' => new \Bitrix\Main\Type\DateTime(),
'UPDATE_BY' => $userId
];
$result = Orm\MapTable::update($this->getId(), $arFields);
if (! $result->isSuccess()) {
ErrorManager::addResultError($this->errors, $result);
return false;
}
return true;
}
/**
* Удаление карты и относящихся к ней разделов
*
* @return boolean
*/
public function Delete()
{
foreach ($this->sectionCollection as $objectSection) {
if (! $objectSection->Delete()) {
$this->errors = $objectSection->getErrors();
return false;
}
}
$result = Orm\MapTable::delete($this->getId());
if ($result->isSuccess()) {
$objDinamicPermission = \Fusion\KPI\Orm\Map\RoleDinamicTable::GetList(['filter' => ['MAP_ID' => $this->getId()]]);
while ($record = $objDinamicPermission->fetch())
{
\Fusion\KPI\Orm\Map\RoleDinamicTable::Delete($record['ID']);
}
return true;
} else {
ErrorManager::addResultError($this->errors, $result);
return false;
}
}
/**
* Проверка прав доступа
*
* @param string $action
* @return boolean
*/
public function checkAccess($action)
{
// @todo проверить action
$method = "can$action";
$modelAccess = new Access\Map($this->status, $this->type_code, $this->entity, $this->getId());
return $modelAccess->$method();
}
/**
* Возвращает коллекцию ошибок класса
*
* @return object \Bitrix\Main\ErrorCollection
*/
public function getErrors()
{
return $this->errors;
}
/**
* Возвращает true, если есть ошибки обработки
*
* @return boolean
*/
public function hasErrors()
{
return ! $this->errors->isEmpty();
}
/**
* Создание карты
*
* @param array $params
* @return \Bitrix\Main\Entity\Result
*/
public static function create($params)
{
$arFields = [
'YEAR' => $params['YEAR'],
'RESPONSIBLE_ID' => $params['RESPONSIBLE_ID'],
'STATUS' => $params['STATUS'],
'TYPE_ID' => Orm\Map\TypeTable::getTypeByCode($params['TYPE_CODE']),
'PLANED_DATE_APPROVE' => $params['PLANED_DATE_APPROVE'],
'ENTITY' => $params['ENTITY']
];
return Orm\MapTable::add($arFields);
}
/**
* Метод возвращает коллекцию карт
*
* @param array $filter
* @param integer $offset
* @param integer $limit
* @return \Fusion\KPI\Map[]
*/
public static function getCollection($filter = [], $offset = 0, $limit = 0, $checkPermittion = true)
{
if($checkPermittion === true)
{
$modelAccess = new Access\Map();
$accesFilter = $modelAccess->getFilter($filter['TYPE_ID']);
if (!empty($filter)) {
$filter = [
[
'LOGIC' => 'AND',
$filter,
$accesFilter
]
];
}
else
{
$filter = $accesFilter;
}
}
$arReturn = [];
$objectMap = Orm\MapTable::GetList([
'order' => [
'ID' => 'ASC'
],
'filter' => $filter,
'count_total' => true,
'offset' => $offset,
'limit' => $limit,
'select' => [
'ID'
]
]);
foreach ($objectMap as $map) {
$arReturn[] = new Map($map['ID']);
}
return [
'data' => $arReturn,
'count' => $objectMap->getCount()
];
}
/**
* Подгружаем поля
*
* @return boolean
*/
private function _getFields()
{
$object = Orm\MapTable::GetList([
'filter' => [
'ID' => $this->getId()
],
'select' => [
'ID',
'YEAR',
'RESPONSIBLE_ID',
'STATUS',
'TYPE_ID',
'TYPE_CODE' => 'TYPE.CODE',
'TYPE_NAME' => 'TYPE.NAME',
'PLANED_DATE_APPROVE',
'DATE_CREATE',
'DATE_UPDATE',
'DATE_APPROVE',
'UPDATE_BY',
'ENTITY'
]
]);
$fields = $object->fetch();
if (!empty($fields)) {
$this->fields = $fields;
return true;
} else {
ErrorManager::addError($this->errors, 'Карта с таким id не найдена');
return false;
}
}
/**
* Загржает коллекцию разделов
*/
private function _loadSectionCollection()
{
$this->_sectionCollection = Section::getCollection([
'MAP_ID' => $this->getId()
]);
}
}