Newer
Older
<?php
/**
* Copyright Maarch since 2008 under licence GPLv3.
* See LICENCE.txt file at the root folder for more details.
* This file is part of Maarch software.
*
*/
/**
* @brief Resource List Controller
* @author dev@maarch.org
*/
namespace Resource\controllers;
use Attachment\models\AttachmentModel;
use Basket\models\BasketModel;
use Basket\models\GroupBasketModel;
use Basket\models\RedirectBasketModel;
use Folder\models\FolderModel;
use Group\controllers\PrivilegeController;
use Note\models\NoteModel;
use Resource\models\ResourceListModel;
use SrcCore\models\DatabaseModel;
use SrcCore\models\TextFormatModel;
use User\models\UserModel;
class ResourceListController
{
public function get(Request $request, Response $response, array $aArgs)
{
$errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause', 'basket_res_order', 'basket_name', 'basket_id']]);
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
$data['offset'] = (empty($data['offset']) || !is_numeric($data['offset']) ? 0 : (int)$data['offset']);
$data['limit'] = (empty($data['limit']) || !is_numeric($data['limit']) ? 10 : (int)$data['limit']);
$allQueryData = ResourceListController::getResourcesListQueryData(['data' => $data, 'basketClause' => $basket['basket_clause'], 'login' => $user['user_id']]);
if (!empty($allQueryData['order'])) {
$data['order'] = $allQueryData['order'];
'table' => $allQueryData['table'],
'leftJoin' => $allQueryData['leftJoin'],
'where' => $allQueryData['where'],
'data' => $allQueryData['queryData'],
'orderBy' => empty($data['order']) ? [$basket['basket_res_order']] : [$data['order']]
$resIds = ResourceListController::getIdsWithOffsetAndLimit(['resources' => $rawResources, 'offset' => $data['offset'], 'limit' => $data['limit']]);
$defaultAction = [];
$displayFolderTags = false;
$excludeAttachmentTypes = ['converted_pdf', 'print_folder'];
if (!PrivilegeController::hasPrivilege(['privilegeId' => 'view_documents_with_notes', 'userId' => $GLOBALS['id']])) {
$excludeAttachmentTypes[] = 'document_with_notes';
}
$attachments = AttachmentModel::get([
'select' => ['COUNT(res_id)', 'res_id_master'],
'where' => ['res_id_master in (?)', 'status not in (?)', 'attachment_type not in (?)', '((status = ? AND typist = ?) OR status != ?)'],
'data' => [$resIds, ['DEL', 'OBS'], $excludeAttachmentTypes, 'TMP', $GLOBALS['id'], 'TMP'],
'groupBy' => ['res_id_master']
]);
$groupBasket = GroupBasketModel::get(['select' => ['list_display', 'list_event'], 'where' => ['basket_id = ?', 'group_id = ?'], 'data' => [$basket['basket_id'], $group['group_id']]]);
$listDisplay = json_decode($groupBasket[0]['list_display']);
'res_letterbox.res_id', 'res_letterbox.subject', 'res_letterbox.barcode', 'res_letterbox.alt_identifier',
'status.label_status AS "status.label_status"', 'status.img_filename AS "status.img_filename"', 'priorities.color AS "priorities.color"',
'res_letterbox.closing_date', 'res_letterbox.locker_user_id', 'res_letterbox.locker_time', 'res_letterbox.confidentiality'
$tableFunction = ['status', 'priorities'];
$leftJoinFunction = ['res_letterbox.status = status.id', 'res_letterbox.priority = priorities.id'];
if ($value['value'] == 'getPriority') {
$select[] = 'priorities.label AS "priorities.label"';
} elseif ($value['value'] == 'getCategory') {
$select[] = 'res_letterbox.category_id';
} elseif ($value['value'] == 'getDoctype') {
$select[] = 'doctypes.description AS "doctypes.description"';
$tableFunction[] = 'doctypes';
$leftJoinFunction[] = 'res_letterbox.type_id = doctypes.type_id';
} elseif ($value['value'] == 'getCreationAndProcessLimitDates') {
$select[] = 'res_letterbox.creation_date';
$select[] = 'res_letterbox.process_limit_date';
} elseif ($value['value'] == 'getModificationDate') {
$select[] = 'res_letterbox.modification_date';
} elseif ($value['value'] == 'getOpinionLimitDate') {
$select[] = 'res_letterbox.opinion_limit_date';
}
}
$order = 'CASE res_letterbox.res_id ';
foreach ($resIds as $key => $resId) {
$order .= "WHEN {$resId} THEN {$key} ";
}
$order .= 'END';
$resources = ResourceListModel::getOnResource([
'select' => $select,
'table' => $tableFunction,
'leftJoin' => $leftJoinFunction,
'where' => ['res_letterbox.res_id in (?)'],
'data' => [$resIds],
$formattedResources = ResourceListController::getFormattedResources([
'resources' => $resources,
'userId' => $GLOBALS['id'],
'attachments' => $attachments,
'checkLocked' => true,
'listDisplay' => $listDisplay
]);
$defaultAction['component'] = $groupBasket[0]['list_event'];
if (in_array('getFolders', array_column($listDisplay, 'value'))) {
$displayFolderTags = true;
}
return $response->withJson(['resources' => $formattedResources, 'count' => $count, 'basketLabel' => $basket['basket_name'], 'basket_id' => $basket['basket_id'], 'allResources' => $allResources, 'defaultAction' => $defaultAction, 'displayFolderTags' => $displayFolderTags]);
public function getFilters(Request $request, Response $response, array $aArgs)
{
$currentUser = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['id']]);
$errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $currentUser['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
}
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $user['user_id']]);
$filters = ResourceListController::getFormattedFilters(['where' => $where, 'queryData' => $queryData, 'queryParams' => $queryParams]);
public static function getResourcesListQueryData(array $args)
{
ValidatorModel::stringType($args, ['basketClause', 'login']);
ValidatorModel::arrayType($args, ['data']);
$table = [];
$leftJoin = [];
$where = [];
if (!empty($args['basketClause'])) {
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $args['basketClause'], 'login' => $args['login']]);
$where = [$whereClause];
}
$queryData = [];
$order = null;
if (!empty($args['data']['delayed']) && $args['data']['delayed'] == 'true') {
$where[] = 'process_limit_date < CURRENT_TIMESTAMP';
}
if (!empty($args['data']['search']) && mb_strlen($args['data']['search']) >= 2) {

Alex ORLUC
committed
if (preg_match('/^"([^"]+)"$/', $args['data']['search'], $cleanSearch)) {
$where[] = '(alt_identifier like ? OR subject like ?)';
$queryData[] = "{$cleanSearch[1]}";
$queryData[] = "{$cleanSearch[1]}";
} else {
$where[] = '(alt_identifier ilike ? OR translate(subject, \'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ\', \'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyrr\') ilike translate(?, \'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ\', \'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyrr\'))';
$queryData[] = "%{$args['data']['search']}%";
$queryData[] = "%{$args['data']['search']}%";
}
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
}
if (isset($args['data']['priorities'])) {
if (empty($args['data']['priorities'])) {
$where[] = 'priority is null';
} else {
$replace = preg_replace('/(^,)|(,$)/', '', $args['data']['priorities']);
$replace = preg_replace('/(,,)/', ',', $replace);
if ($replace != $args['data']['priorities']) {
$where[] = '(priority is null OR priority in (?))';
} else {
$where[] = 'priority in (?)';
}
$queryData[] = explode(',', $replace);
}
}
if (isset($args['data']['categories'])) {
if (empty($args['data']['categories'])) {
$where[] = 'category_id is null';
} else {
$replace = preg_replace('/(^,)|(,$)/', '', $args['data']['categories']);
$replace = preg_replace('/(,,)/', ',', $replace);
if ($replace != $args['data']['categories']) {
$where[] = '(category_id is null OR category_id in (?))';
} else {
$where[] = 'category_id in (?)';
}
$queryData[] = explode(',', $replace);
}
}
if (!empty($args['data']['statuses'])) {
$where[] = 'status in (?)';
$queryData[] = explode(',', $args['data']['statuses']);
}
if (isset($args['data']['entities'])) {
if (empty($args['data']['entities'])) {
$where[] = 'destination is null';
} else {
$replace = preg_replace('/(^,)|(,$)/', '', $args['data']['entities']);
$replace = preg_replace('/(,,)/', ',', $replace);
if ($replace != $args['data']['entities']) {
$where[] = '(destination is null OR destination in (?))';
} else {
$where[] = 'destination in (?)';
}
$queryData[] = explode(',', $replace);
}
}
if (!empty($args['data']['entitiesChildren'])) {
$entities = explode(',', $args['data']['entitiesChildren']);
$entitiesChildren = [];
foreach ($entities as $entity) {
$children = EntityModel::getEntityChildren(['entityId' => $entity]);
$entitiesChildren = array_merge($entitiesChildren, $children);
}
if (!empty($entitiesChildren)) {
$where[] = 'destination in (?)';
$queryData[] = $entitiesChildren;
}
}
if (!empty($args['data']['order']) && strpos($args['data']['order'], 'alt_identifier') !== false) {
$order = 'order_alphanum(alt_identifier) ' . explode(' ', $args['data']['order'])[1];
}
if (!empty($args['data']['order']) && strpos($args['data']['order'], 'priority') !== false) {
$order = 'priorities.order ' . explode(' ', $args['data']['order'])[1];
$table = ['priorities'];
$leftJoin = ['res_view_letterbox.priority = priorities.id'];
}
return ['table' => $table, 'leftJoin' => $leftJoin, 'where' => $where, 'queryData' => $queryData, 'order' => $order];
}
public function getActions(Request $request, Response $response, array $args)
$errors = ResourceListController::listControl(['groupId' => $args['groupId'], 'userId' => $args['userId'], 'basketId' => $args['basketId'], 'currentUserId' => $GLOBALS['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
}
$basket = BasketModel::getById(['id' => $args['basketId'], 'select' => ['basket_clause', 'basket_res_order', 'basket_name', 'basket_id']]);
$group = GroupModel::getById(['id' => $args['groupId'], 'select' => ['group_id']]);
$queryParams = $request->getQueryParams();
if (!empty($queryParams['resId'])) {
$usedIn = 'used_in_action_page';
} else {
$usedIn = 'used_in_basketlist';
}
'select' => ['id_action', 'default_action_list', 'where_clause'],
'where' => ['basket_id = ?', 'group_id = ?', "{$usedIn} = ?"],
'data' => [$basket['basket_id'], $group['group_id'], 'Y']
$defaultAction = 0;
if ($rawAction['default_action_list'] == 'Y') {
$defaultAction = $rawAction['id_action'];
}
$actionsClauses[$rawAction['id_action']] = $rawAction['where_clause'];
$actions = ActionModel::get(['select' => ['id', 'label_action', 'component'], 'where' => ['id in (?)'], 'data' => [$actions], 'orderBy' => ["id = {$defaultAction} DESC",'label_action']]);
foreach ($actions as $key => $action) {
if (!empty($queryParams['resId'])) {
if (!empty($actionsClauses[$action['id']])) {
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $actionsClauses[$action['id']], 'login' => $GLOBALS['userId']]);
$ressource = ResModel::getOnView(['select' => [1], 'where' => ['res_id = ?', $whereClause], 'data' => [$queryParams['resId']]]);
if (empty($ressource)) {
unset($actions[$key]);
continue;
}
}
$categoriesList = ActionModel::getCategoriesById(['id' => $action['id']]);
if (!empty($categoriesList)) {
$actions[$key]['categories'] = array_column($categoriesList, 'category_id');
} else {
$categories = ResModel::getCategories();
$actions[$key]['categories'] = array_column($categories, 'id');
$actions[$key]['label'] = $action['label_action'];
unset($actions[$key]['label_action']);
}
return $response->withJson(['actions' => array_values($actions)]);
public function setAction(Request $request, Response $response, array $aArgs)
{
$body = $request->getParsedBody();
if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
}
$body['resources'] = array_unique($body['resources']);
$body['resources'] = array_slice($body['resources'], 0, 500);
$errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $GLOBALS['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
}
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause', 'basket_id', 'basket_name']]);
$group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
$actionGroupBasket = ActionGroupBasketModel::get([
'select' => [1],
'where' => ['basket_id = ?', 'group_id = ?', 'id_action = ?'],
'data' => [$basket['basket_id'], $group['group_id'], $aArgs['actionId']]
]);
if (empty($actionGroupBasket)) {
return $response->withStatus(400)->withJson(['errors' => 'Action is not linked to this group basket']);
}
$action = ActionModel::getById(['id' => $aArgs['actionId'], 'select' => ['component']]);
if (empty($action['component'])) {
return $response->withStatus(400)->withJson(['errors' => 'Action component does not exist']);
}
if (!array_key_exists($action['component'], ActionMethodController::COMPONENTS_ACTIONS)) {
return $response->withStatus(400)->withJson(['errors' => 'Action method does not exist']);
}
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $user['user_id']]);
$resources = ResModel::getOnView([
'select' => ['res_id', 'locker_user_id', 'locker_time'],
'where' => [$whereClause, 'res_view_letterbox.res_id in (?)'],
'data' => [$body['resources']]
]);
$resourcesInBasket = [];
foreach ($resources as $resource) {
$resourcesInBasket[] = $resource['res_id'];
}
if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
foreach ($resources as $resource) {
$lock = true;
if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
$lock = false;
} elseif ($resource['locker_user_id'] == $GLOBALS['id']) {
$lock = false;
} elseif (strtotime($resource['locker_time']) < time()) {
$lock = false;
}
if (!$lock) {
$resourcesForAction[] = $resource['res_id'];
if (empty($resourcesForAction)) {
return $response->withJson(['success' => 'No resource to process']);
$body['data'] = empty($body['data']) ? [] : $body['data'];
$body['note'] = empty($body['note']) ? null : $body['note'];
$method = ActionMethodController::COMPONENTS_ACTIONS[$action['component']];
$methodResponse = ActionMethodController::$method(['resId' => $resId, 'data' => $body['data'], 'note' => $body['note']]);
if (empty($methodResponses['errors'])) {
$methodResponses['errors'] = [];
}
$methodResponses['errors'] = array_merge($methodResponses['errors'], $methodResponse['errors']);
if (!empty($methodResponse['data'])) {
if (empty($methodResponses['data'])) {
$methodResponses['data'] = [];
}
$methodResponses['data'] = array_merge($methodResponses['data'], $methodResponse['data']);
$historic = empty($methodResponse['history']) ? '' : $methodResponse['history'];
ActionMethodController::terminateAction(['id' => $aArgs['actionId'], 'resources' => $resourcesForAction, 'basketName' => $basket['basket_name'], 'note' => $body['note'], 'history' => $historic]);
if (!empty($methodResponses)) {
return $response->withJson($methodResponses);
}
public function lock(Request $request, Response $response, array $aArgs)
{
$body = $request->getParsedBody();
if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
}
$body['resources'] = array_slice($body['resources'], 0, 500);
$currentUser = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['id']]);
$errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $currentUser['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
}
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $user['user_id']]);
$resources = ResModel::getOnView([
'select' => ['res_id', 'locker_user_id', 'locker_time'],
'where' => [$whereClause, 'res_view_letterbox.res_id in (?)'],
'data' => [$body['resources']]
]);
$resourcesInBasket = [];
foreach ($resources as $resource) {
$resourcesInBasket[] = $resource['res_id'];
}
if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
}
$locked = 0;
$resourcesToLock = [];
foreach ($resources as $resource) {
$lock = true;
if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
$lock = false;
} elseif ($resource['locker_user_id'] == $currentUser['id']) {
$lock = false;
} elseif (strtotime($resource['locker_time']) < time()) {
$lock = false;
}
if (!$lock) {
$resourcesToLock[] = $resource['res_id'];
} else {
$lockersId[] = $resource['locker_user_id'];
if (!empty($resourcesToLock)) {
ResModel::update([
'set' => ['locker_user_id' => $currentUser['id'], 'locker_time' => 'CURRENT_TIMESTAMP + interval \'1\' MINUTE'],
'where' => ['res_id in (?)'],
'data' => [$resourcesToLock]
]);
}
$lockers = [];
if (!empty($lockersId)) {
$lockersId = array_unique($lockersId);
foreach ($lockersId as $lockerId) {
$lockers[] = UserModel::getLabelledUserById(['id' => $lockerId]);
}
}
return $response->withJson(['lockedResources' => $locked, 'lockers' => $lockers]);
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
public function unlock(Request $request, Response $response, array $aArgs)
{
$body = $request->getParsedBody();
if (!Validator::arrayType()->notEmpty()->validate($body['resources'])) {
return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
}
$body['resources'] = array_slice($body['resources'], 0, 500);
$currentUser = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['id']]);
$errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $currentUser['id']]);
if (!empty($errors['errors'])) {
return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
}
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_clause']]);
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$whereClause = PreparedClauseController::getPreparedClause(['clause' => $basket['basket_clause'], 'login' => $user['user_id']]);
$resources = ResModel::getOnView([
'select' => ['res_id', 'locker_user_id', 'locker_time'],
'where' => [$whereClause, 'res_view_letterbox.res_id in (?)'],
'data' => [$body['resources']]
]);
$resourcesInBasket = [];
foreach ($resources as $resource) {
$resourcesInBasket[] = $resource['res_id'];
}
if (!empty(array_diff($body['resources'], $resourcesInBasket))) {
return $response->withStatus(403)->withJson(['errors' => 'Resources out of perimeter']);
}
$resourcesToUnlock = [];
foreach ($resources as $resource) {
if (!(!empty($resource['locker_user_id']) && $resource['locker_user_id'] != $currentUser['id'] && strtotime($resource['locker_time']) > time())) {
$resourcesToUnlock[] = $resource['res_id'];
}
}
if (!empty($resourcesToUnlock)) {
ResModel::update([
'set' => ['locker_user_id' => null, 'locker_time' => null],
'where' => ['res_id in (?)'],
'data' => [$resourcesToUnlock]
]);
}
return $response->withStatus(204);
}
{
ValidatorModel::notEmpty($aArgs, ['groupId', 'userId', 'basketId', 'currentUserId']);
ValidatorModel::intVal($aArgs, ['groupId', 'userId', 'basketId', 'currentUserId']);
$group = GroupModel::getById(['id' => $aArgs['groupId'], 'select' => ['group_id']]);
$basket = BasketModel::getById(['id' => $aArgs['basketId'], 'select' => ['basket_id', 'basket_clause', 'basket_res_order', 'basket_name']]);
if (empty($group) || empty($basket)) {
return ['errors' => 'Group or basket does not exist', 'code' => 400];
}
if ($aArgs['userId'] == $aArgs['currentUserId']) {
$redirectedBasket = RedirectBasketModel::get([
'select' => [1],
'where' => ['owner_user_id = ?', 'basket_id = ?', 'group_id = ?'],
'data' => [$aArgs['userId'], $basket['basket_id'], $aArgs['groupId']]
]);
if (!empty($redirectedBasket[0])) {
return ['errors' => 'Basket out of perimeter (redirected)', 'code' => 403];
}
} else {
$redirectedBasket = RedirectBasketModel::get([
'select' => ['actual_user_id'],
'where' => ['owner_user_id = ?', 'basket_id = ?', 'group_id = ?'],
'data' => [$aArgs['userId'], $basket['basket_id'], $aArgs['groupId']]
if (empty($redirectedBasket[0]) || $redirectedBasket[0]['actual_user_id'] != $aArgs['currentUserId']) {
return ['errors' => 'Basket out of perimeter', 'code' => 403];
}
}
$user = UserModel::getById(['id' => $aArgs['userId'], 'select' => ['user_id']]);
$groups = UserModel::getGroupsByLogin(['login' => $user['user_id']]);
$groupFound = false;
foreach ($groups as $value) {
if ($value['id'] == $aArgs['groupId']) {
$groupFound = true;
if (!$groupFound) {
return ['errors' => 'Group is not linked to this user', 'code' => 400];
}
$isBasketLinked = GroupBasketModel::get(['select' => [1], 'where' => ['basket_id = ?', 'group_id = ?'], 'data' => [$basket['basket_id'], $group['group_id']]]);
if (empty($isBasketLinked)) {
return ['errors' => 'Group is not linked to this basket', 'code' => 400];
}
private static function getAssignee(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$res = ResModel::getById(['select' => ['destination'], 'resId' => $args['resId']]);
$listInstances = ListInstanceModel::get([
'select' => ['item_id'],
'where' => ['difflist_type = ?', 'res_id = ?', 'item_mode = ?'],
$assignee = '';
if (!empty($listInstances[0])) {
$assignee .= UserModel::getLabelledUserById(['login' => $listInstances[0]['item_id']]);
}
if (!empty($res['destination'])) {
$entityLabel = EntityModel::getByEntityId(['select' => ['entity_label'], 'entityId' => $res['destination']]);
$assignee .= (empty($assignee) ? "({$entityLabel['entity_label']})" : " ({$entityLabel['entity_label']})");
}
private static function getVisaWorkflow(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$listInstances = ListInstanceModel::get([
'select' => ['item_id', 'requested_signature', 'process_date'],
'where' => ['difflist_type = ?', 'res_id = ?'],
'orderBy' => ['listinstance_id']
]);
$users = [];
foreach ($listInstances as $listInstance) {
$users[] = [
'user' => UserModel::getLabelledUserById(['login' => $listInstance['item_id']]),
'mode' => $listInstance['requested_signature'] ? 'sign' : 'visa',
'date' => TextFormatModel::formatDate($listInstance['process_date']),
'current' => empty($listInstance['process_date']) && !$currentFound
if (empty($listInstance['process_date']) && !$currentFound) {
$currentFound = true;
}
private static function getSignatories(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$listInstances = ListInstanceModel::get([
'select' => ['item_id', 'process_date'],
'where' => ['difflist_type = ?', 'res_id = ?' ,'requested_signature = ?'],
'data' => ['VISA_CIRCUIT', $args['resId'], true],
'orderBy' => ['listinstance_id']
]);
$users = [];
foreach ($listInstances as $listInstance) {
$users[] = [
'user' => UserModel::getLabelledUserById(['login' => $listInstance['item_id']]),
'date' => TextFormatModel::formatDate($listInstance['process_date']),
];
}
return $users;
}
private static function getSenders(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$resource = ResModel::getById(['select' => ['category_id', 'address_id', 'exp_user_id', 'dest_user_id', 'is_multicontacts'], 'resId' => $args['resId']]);
if (!empty($resource)) {
if ($resource['category_id'] == 'outgoing') {
$resourcesContacts = ResourceContactModel::getFormattedByResId(['resId' => $args['resId']]);
foreach ($resourcesContacts as $resourcesContact) {
$senders[] = $resourcesContact['restrictedFormat'];
}
} else {
$rawContacts = [];
if ($resource['is_multicontacts'] == 'Y') {
$multiContacts = DatabaseModel::select([
'select' => ['contact_id', 'address_id'],
'table' => ['contacts_res'],
'where' => ['res_id = ?', 'mode = ?'],
]);
foreach ($multiContacts as $multiContact) {
$rawContacts[] = [
'login' => $multiContact['contact_id'],
'address_id' => $multiContact['address_id'],
];
}
} else {
$rawContacts[] = [
'login' => $resource['exp_user_id'],
'address_id' => $resource['address_id'],
];
}
foreach ($rawContacts as $rawContact) {
if (!empty($rawContact['address_id'])) {
$contact = ContactModel::getOnView([
'select' => ['is_corporate_person', 'ca_id', 'society', 'contact_firstname', 'contact_lastname'],
'where' => ['ca_id = ?'],
'data' => [$rawContact['address_id']]
]);
if (isset($contact[0])) {
$contact = AutoCompleteController::getFormattedContact(['contact' => $contact[0]]);
$senders[] = $contact['contact']['contact'];
}
} else {
$senders[] = UserModel::getLabelledUserById(['login' => $rawContact['login']]);
}
}
}
}
return $senders;
}
private static function getRecipients(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$resource = ResModel::getById(['select' => ['category_id', 'address_id', 'exp_user_id', 'dest_user_id', 'is_multicontacts'], 'resId' => $args['resId']]);
if (!empty($resource)) {
if ($resource['category_id'] == 'outgoing') {
if ($resource['is_multicontacts'] == 'Y') {
$multiContacts = DatabaseModel::select([
'select' => ['contact_id', 'address_id'],
'table' => ['contacts_res'],
'where' => ['res_id = ?', 'mode = ?'],
]);
foreach ($multiContacts as $multiContact) {
$rawContacts[] = [
'login' => $multiContact['contact_id'],
'address_id' => $multiContact['address_id'],
];
}
} else {
$rawContacts[] = [
'login' => $resource['dest_user_id'],
'address_id' => $resource['address_id'],
];
}
foreach ($rawContacts as $rawContact) {
if (!empty($rawContact['address_id'])) {
$contact = ContactModel::getOnView([
'select' => ['is_corporate_person', 'ca_id', 'society', 'contact_firstname', 'contact_lastname'],
'where' => ['ca_id = ?'],
'data' => [$rawContact['address_id']]
]);
if (isset($contact[0])) {
$contact = AutoCompleteController::getFormattedContact(['contact' => $contact[0]]);
$recipients[] = $contact['contact']['contact'];
}
} else {
$recipients[] = UserModel::getLabelledUserById(['login' => $rawContact['login']]);
}
}
} else {
$resourcesContacts = ResourceContactModel::getFormattedByResId(['resId' => $args['resId']]);
foreach ($resourcesContacts as $resourcesContact) {
$recipients[] = $resourcesContact['restrictedFormat'];
}
}
}
return $recipients;
}
private static function getParallelOpinionsNumber(array $args)
{
ValidatorModel::notEmpty($args, ['resId']);
ValidatorModel::intVal($args, ['resId']);
$notes = NoteModel::get(['select' => ['count(1)'], 'where' => ['identifier = ?', 'note_text like ?'], 'data' => [$args['resId'], '[avis%']]);
return $notes[0]['count'];
}
private static function getFolders(array $args)
{
ValidatorModel::notEmpty($args, ['resId', 'userId']);
ValidatorModel::intVal($args, ['resId', 'userId']);
$user = UserModel::getById(['id' => $args['userId'], 'select' => ['user_id']]);
$entities = UserModel::getEntitiesByLogin(['login' => $user['user_id']]);
$entities = array_column($entities, 'id');
if (empty($entities)) {
$entities = [0];
}
$folders = FolderModel::getWithEntitiesAndResources([
'select' => ['DISTINCT(folders.id)', 'folders.label'],
'where' => ['res_id = ?', '(user_id = ? OR entity_id in (?))'],
'data' => [$args['resId'], $args['userId'], $entities]
]);
return $folders;
}
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
public static function getIdsWithOffsetAndLimit(array $args)
{
ValidatorModel::arrayType($args, ['resources']);
ValidatorModel::intVal($args, ['offset', 'limit']);
$ids = [];
if (!empty($args['resources'][$args['offset']])) {
$start = $args['offset'];
$i = 0;
while ($i < $args['limit'] && !empty($args['resources'][$start])) {
$ids[] = $args['resources'][$start]['res_id'];
++$start;
++$i;
}
}
return $ids;
}
public static function getFormattedResources(array $args)
{
ValidatorModel::notEmpty($args, ['resources', 'userId']);
ValidatorModel::arrayType($args, ['resources', 'attachments', 'listDisplay']);
ValidatorModel::intVal($args, ['userId']);
ValidatorModel::boolType($args, ['checkLocked']);
$formattedResources = [];
$resources = $args['resources'];
$attachments = $args['attachments'];
$currentUser = UserModel::getById(['id' => $args['userId'], 'select' => ['user_id']]);
foreach ($resources as $key => $resource) {
$formattedResources[$key]['resId'] = $resource['res_id'];
$formattedResources[$key]['chrono'] = $resource['alt_identifier'];
$formattedResources[$key]['barcode'] = $resource['barcode'];
$formattedResources[$key]['subject'] = $resource['subject'];
$formattedResources[$key]['confidentiality'] = $resource['confidentiality'];
$formattedResources[$key]['statusLabel'] = $resource['status.label_status'];
$formattedResources[$key]['statusImage'] = $resource['status.img_filename'];
$formattedResources[$key]['priorityColor'] = $resource['priorities.color'];
$formattedResources[$key]['closing_date'] = $resource['closing_date'];
$formattedResources[$key]['countAttachments'] = 0;
foreach ($attachments as $attachment) {
if ($attachment['res_id_master'] == $resource['res_id']) {
$formattedResources[$key]['countAttachments'] = $attachment['count'];
break;
}
}
$formattedResources[$key]['countNotes'] = NoteModel::countByResId(['resId' => $resource['res_id'], 'login' => $currentUser['user_id'], 'userId' => $args['userId']]);
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
if (!empty($args['checkLocked'])) {
$isLocked = true;
if (empty($resource['locker_user_id'] || empty($resource['locker_time']))) {
$isLocked = false;
} elseif ($resource['locker_user_id'] == $args['userId']) {
$isLocked = false;
} elseif (strtotime($resource['locker_time']) < time()) {
$isLocked = false;
}
if ($isLocked) {
$formattedResources[$key]['locker'] = UserModel::getLabelledUserById(['id' => $resource['locker_user_id']]);
}
$formattedResources[$key]['isLocked'] = $isLocked;
}
if (isset($args['listDisplay'])) {
$display = [];
foreach ($args['listDisplay'] as $value) {
$value = (array)$value;
if ($value['value'] == 'getPriority') {
$value['displayValue'] = $resource['priorities.label'];
$display[] = $value;
} elseif ($value['value'] == 'getCategory') {
$value['displayValue'] = $resource['category_id'];
$display[] = $value;
} elseif ($value['value'] == 'getDoctype') {
$value['displayValue'] = $resource['doctypes.description'];
$display[] = $value;
} elseif ($value['value'] == 'getAssignee') {
$value['displayValue'] = ResourceListController::getAssignee(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getSenders') {
$value['displayValue'] = ResourceListController::getSenders(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getRecipients') {
$value['displayValue'] = ResourceListController::getRecipients(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getVisaWorkflow') {
$value['displayValue'] = ResourceListController::getVisaWorkflow(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getSignatories') {
$value['displayValue'] = ResourceListController::getSignatories(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getParallelOpinionsNumber') {
$value['displayValue'] = ResourceListController::getParallelOpinionsNumber(['resId' => $resource['res_id']]);
$display[] = $value;
} elseif ($value['value'] == 'getCreationAndProcessLimitDates') {
$value['displayValue'] = ['creationDate' => $resource['creation_date'], 'processLimitDate' => $resource['process_limit_date']];
$display[] = $value;
} elseif ($value['value'] == 'getModificationDate') {
$value['displayValue'] = $resource['modification_date'];
$display[] = $value;
} elseif ($value['value'] == 'getOpinionLimitDate') {
$value['displayValue'] = $resource['opinion_limit_date'];
$display[] = $value;
}
}
$formattedResources[$key]['folders'] = ResourceListController::getFolders(['resId' => $resource['res_id'], 'userId' => $args['userId']]);
$formattedResources[$key]['display'] = $display;
}
}
return $formattedResources;
}
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
public static function getFormattedFilters(array $args)
{
ValidatorModel::notEmpty($args, ['where']);
ValidatorModel::arrayType($args, ['where', 'queryData', 'queryParams']);
$data = $args['queryParams'];
$where = $args['where'];
$queryData = $args['queryData'];
if (!empty($data['delayed']) && $data['delayed'] == 'true') {
$where[] = 'process_limit_date < CURRENT_TIMESTAMP';
}
if (!empty($data['search']) && mb_strlen($data['search']) >= 2) {
$where[] = '(alt_identifier ilike ? OR translate(subject, \'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ\', \'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyrr\') ilike translate(?, \'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ\', \'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyrr\'))';
$queryData[] = "%{$data['search']}%";
$queryData[] = "%{$data['search']}%";
}
$wherePriorities = $where;
$whereCategories = $where;
$whereStatuses = $where;
$whereEntities = $where;
$dataPriorities = $queryData;
$dataCategories = $queryData;
$dataStatuses = $queryData;
$dataEntities = $queryData;
if (isset($data['priorities'])) {
if (empty($data['priorities'])) {
$tmpWhere = 'priority is null';
} else {
$replace = preg_replace('/(^,)|(,$)/', '', $data['priorities']);
$replace = preg_replace('/(,,)/', ',', $replace);
if ($replace != $data['priorities']) {
$tmpWhere = '(priority is null OR priority in (?))';
} else {
$tmpWhere = 'priority in (?)';
}
$dataCategories[] = explode(',', $replace);
$dataStatuses[] = explode(',', $replace);