Joywork/ajax/getObjectClients.php
2026-05-22 21:21:54 +03:00

264 lines
10 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
header('Content-Type: application/json');
$response = [
'success' => false,
'message' => 'Unauthorized',
'data' => [],
'hidden_objects' => []
];
if ($_SESSION['id'] && isset($_GET['object_ids'])) {
$currentUserId = $_SESSION['id'];
$userSql = "SELECT agency, users_admin, id_manager, company_id FROM users WHERE id = $currentUserId LIMIT 1";
$userResult = mysql_query($userSql);
$userData = mysql_fetch_assoc($userResult);
$currentCompanyID = $userData['company_id'];
$isAdmin = ($userData['agency'] == 1 || $userData['users_admin'] == 1);
$permSql = "SELECT menu_all_clients, menu_all_clients_edit FROM user_permissions
WHERE user_id = $currentUserId LIMIT 1";
$permResult = mysql_query($permSql);
$permData = mysql_fetch_assoc($permResult);
$depClass = new Department();
$dep_user = $depClass->getDepartment((int)$_SESSION['id']);
$canViewAll = ($isAdmin || $permData['menu_all_clients'] == 1 || $dep_user['role'] == 'admin_department');
$canEditAll = ($isAdmin || $permData['menu_all_clients_edit'] == 1 || $dep_user['role'] == 'admin_department');
$objectIds = array_filter(
array_map('intval', explode(',', $_GET['object_ids'])),
function($id) { return $id > 0; }
);
if (empty($objectIds)) {
$response['message'] = 'No valid object IDs provided';
echo json_encode($response);
exit;
}
$objectIdsStr = implode(',', $objectIds);
$validObjectIds = [];
if ($currentCompanyID) {
$agencyUsersSql = "SELECT id FROM users WHERE company_id = " . (int)$currentCompanyID;
$agencyUsersRes = mysql_query($agencyUsersSql);
$agencyUserIDs = [];
while ($row = mysql_fetch_assoc($agencyUsersRes)) {
$agencyUserIDs[] = (int)$row['id'];
}
if (!empty($agencyUserIDs)) {
$agencyUserIDsStr = implode(',', $agencyUserIDs);
$validObjectsSql = "
SELECT id
FROM objects
WHERE id IN ($objectIdsStr)
AND id_add_user IN ($agencyUserIDsStr)
";
$validRes = mysql_query($validObjectsSql);
while ($row = mysql_fetch_assoc($validRes)) {
$validObjectIds[] = (int)$row['id'];
}
}
}
if (empty($validObjectIds)) {
$fallbackSql = "SELECT o.id, o.id_add_user, u.id_manager FROM objects o JOIN users u ON u.id = o.id_add_user WHERE o.id IN ($objectIdsStr)";
$fallbackRes = mysql_query($fallbackSql);
while ($row = mysql_fetch_assoc($fallbackRes)) {
if ($row['id_add_user'] == $currentUserId || $row['id_manager'] == $currentUserId) {
$validObjectIds[] = (int)$row['id'];
}
}
}
if (empty($validObjectIds)) {
$response['success'] = true;
$response['message'] = 'Нет доступных объектов в вашем агентстве';
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
}
$objectIds = $validObjectIds;
$objectIdsStr = implode(',', $objectIds);
//$objectsSql = "SELECT id, id_add_user FROM objects WHERE id IN ($objectIdsStr)";
$objectsSql = "SELECT o.id, o.id_add_user, u.id_manager FROM objects o JOIN users u ON u.id = o.id_add_user WHERE o.id IN ($objectIdsStr);";
$objectsResult = mysql_query($objectsSql);
$objectsOwnersManager = [];
$objectsOwners = [];
while ($row = mysql_fetch_assoc($objectsResult)) {
$objectsOwners[$row['id']] = $row['id_add_user'];
$objectsOwnersManager[$row['id']] = $row['id_manager'];
}
$userOwnedObjects = [];
foreach ($objectsOwners as $objectId => $ownerId) {
if ($ownerId == $currentUserId || (isset($objectsOwnersManager[$objectId]) && $objectsOwnersManager[$objectId] == $currentUserId)) {
$userOwnedObjects[] = $objectId;
}
}
$applyFilter = (isset($_SESSION['agency_id']) && $_SESSION['agency_id'] == 19794 && !$isAdmin && $permData['menu_all_clients'] == 1);
$filteredObjectIds = $objectIds;
if ($applyFilter) {
$filteredObjectIds = [];
// Объекты с Юр.лицо = Да
$sqlLegalYes = "SELECT DISTINCT object_id FROM object_data WHERE field_id = 445 AND value = '[\"1\"]' AND object_id IN ($objectIdsStr)";
$resultLegalYes = mysql_query($sqlLegalYes);
while ($row = mysql_fetch_assoc($resultLegalYes)) {
$filteredObjectIds[] = $row['object_id'];
}
// Объекты с Юр.лицо = Нет и Эксклюзив = Нет
$sqlLegalNoExclusiveNo = "
SELECT DISTINCT od1.object_id
FROM object_data od1
JOIN object_data od2 ON od1.object_id = od2.object_id
WHERE od1.field_id = 445 AND od1.value = '[\"2\"]'
AND od2.field_id = 482 AND od2.value = '[\"2\"]'
AND od1.object_id IN ($objectIdsStr)";
$resultLegalNoExclusiveNo = mysql_query($sqlLegalNoExclusiveNo);
while ($row = mysql_fetch_assoc($resultLegalNoExclusiveNo)) {
$filteredObjectIds[] = $row['object_id'];
}
$filteredObjectIds = array_merge($filteredObjectIds, $userOwnedObjects);
$filteredObjectIds = array_unique($filteredObjectIds);
$response['hidden_objects'] = array_values(array_diff($objectIds, $filteredObjectIds));
if (empty($filteredObjectIds)) {
$response['success'] = true;
$response['message'] = 'No objects match the condition';
echo json_encode($response);
exit;
}
$objectIdsStr = implode(',', $filteredObjectIds);
}
$sql = "SELECT object_id, client_id FROM client_objects WHERE object_id IN ($objectIdsStr)";
$result = mysql_query($sql);
$clientIds = [];
$objectClientsMap = [];
while ($row = mysql_fetch_assoc($result)) {
$objectId = $row['object_id'];
$clientId = $row['client_id'];
// Проверяем права на просмотр для каждого объекта
$isOwner = (isset($objectsOwners[$objectId]) && ($objectsOwners[$objectId] == $currentUserId || $objectsOwnersManager[$objectId] == $currentUserId));
$hasAccess = $canViewAll || $isOwner;
if ($hasAccess) {
if (!isset($objectClientsMap[$objectId])) {
$objectClientsMap[$objectId] = [];
}
$objectClientsMap[$objectId][] = $clientId;
$clientIds[] = $clientId;
}
}
if (!empty($clientIds)) {
$clientIds = array_unique($clientIds);
$clientIdsStr = implode(',', $clientIds);
$sqlClients = "SELECT id, fio, email, phone, id_agent, who_work FROM clients WHERE id IN ($clientIdsStr)";
$resultClients = mysql_query($sqlClients);
$clientsMap = [];
if (is_null($userData['company_id'])) {
$allowedUserIds = [$currentUserId];
if (!empty($userData['id_manager']) && $userData['id_manager'] != 0) {
$allowedUserIds[] = (int)$userData['id_manager'];
}
while ($resultClient = mysql_fetch_assoc($resultClients)) {
if (in_array($resultClient['who_work'], $allowedUserIds) || in_array($resultClient['id_agent'], $allowedUserIds)) {
$clientsMap[$resultClient['id']] = $resultClient;
}
}
} else {
$companyId = isset($_SESSION['agency_id']) ? (int)$_SESSION['agency_id'] : 0;
if ($companyId > 0) {
$agencyUsersSql = "SELECT id FROM users WHERE company_id = $companyId";
$agencyUsersResult = mysql_query($agencyUsersSql);
$agencyUserIds = [];
while ($row = mysql_fetch_assoc($agencyUsersResult)) {
$agencyUserIds[] = $row['id'];
}
} else {
$agencyUserIds = [$currentUserId];
}
$agencyUserIdsStr = implode(',', array_unique($agencyUserIds));
while ($client = mysql_fetch_assoc($resultClients)) {
$belongsToCompany = $isAdmin
|| in_array($client['who_work'], $agencyUserIds)
|| ($client['who_work'] == 0 && in_array($client['id_agent'], $agencyUserIds));
if ($belongsToCompany) {
$clientsMap[$client['id']] = $client;
}
}
}
foreach ($objectClientsMap as $objectId => $clientIdsForObject) {
if ($applyFilter && !in_array($objectId, $filteredObjectIds) && !in_array($objectId, $userOwnedObjects)) {
continue;
}
$clientsForObject = [];
$objectOwnerId = isset($objectsOwners[$objectId]) ? $objectsOwners[$objectId] : 0;
foreach ($clientIdsForObject as $clientId) {
if (isset($clientsMap[$clientId])) {
$client = $clientsMap[$clientId];
$canEdit = $canEditAll || $client['who_work'] == $currentUserId || $objectOwnerId == $currentUserId;
$clientItem = array(
'id' => $client['id'],
'fio' => $client['fio'],
'email' => $client['email'],
'phone' => $client['phone'],
'can_edit' => $canEdit
);
mask_client_contacts_inplace($clientItem);
$clientsForObject[] = $clientItem;
}
}
if (!empty($clientsForObject)) {
$response['data'][] = [
'object_id' => $objectId,
'clients' => $clientsForObject,
'clients_count' => count($clientsForObject)
];
}
}
$response['success'] = true;
$response['message'] = '';
} else {
$response['message'] = 'Клиентов не найдено';
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;