retrieveCurrentUserInfoFromFile(8); // Фёдор Коробков log_event_creation('DEBUG', "Пользователь инициализирован: " . $current_user->user_name); // Получаем проект через webservices чтобы узнать владельца $projectWsId = vtws_getWebserviceEntityId('Project', $projectId); $project = vtws_retrieve($projectWsId, $current_user); log_event_creation('DEBUG', "Проект получен: " . $project['projectname']); log_event_creation('DEBUG', "Владелец проекта: " . $project['assigned_user_id']); // Форматируем дату и время для CRM $formattedDate = formatDateForCRM($eventDate); $formattedTime = formatTimeForCRM($eventTime); // Формируем описание события $description = "Автоматически созданное событие из судебного дела\n\n"; if (!empty($location)) { $description .= "Место: $location\n"; } if (!empty($result)) { $description .= "Результат: $result\n"; } if (!empty($basis)) { $description .= "Основание: $basis\n"; } if (!empty($note)) { $description .= "Примечание: $note\n"; } if (!empty($publicationDate)) { $description .= "Дата размещения: $publicationDate\n"; } // Создаем событие через webservices $eventData = [ 'subject' => $eventName, 'date_start' => $formattedDate, 'time_start' => $formattedTime, 'due_date' => $formattedDate, 'time_end' => date('H:i:s', strtotime($formattedTime) + 3600), // +1 час 'assigned_user_id' => $project['assigned_user_id'], 'activitytype' => 'Meeting', // Тип события 'eventstatus' => 'Planned', // Статус 'location' => $location, 'description' => $description, 'visibility' => 'Public' ]; log_event_creation('DEBUG', "Данные для создания события: " . json_encode($eventData, JSON_UNESCAPED_UNICODE)); // Создаем событие $createdEvent = vtws_create('Calendar', $eventData, $current_user); log_event_creation('SUCCESS', "Событие создано: " . $createdEvent['id']); // Связываем событие с проектом через vtiger_seactivityrel list(, $eventNumericId) = explode('x', $createdEvent['id']); $adb = PearDatabase::getInstance(); $query = "INSERT INTO vtiger_seactivityrel (crmid, activityid) VALUES (?, ?)"; $adb->pquery($query, [$projectId, $eventNumericId]); log_event_creation('SUCCESS', "Событие привязано к проекту"); // Обновляем поля проекта с информацией о последнем событии try { $updateData = [ 'id' => $projectWsId, 'cf_1682' => $formattedDate, // Дата события 'cf_1684' => $formattedTime // Время события ]; vtws_update($updateData, $current_user); log_event_creation('SUCCESS', "Поля проекта обновлены (cf_1682, cf_1684)"); } catch (Exception $e) { log_event_creation('WARNING', "Не удалось обновить поля проекта: " . $e->getMessage()); } // Формируем успешный ответ $response = [ 'success' => true, 'event_id' => $createdEvent['id'], 'event_numeric_id' => $eventNumericId, 'event_name' => $eventName, 'event_date' => $formattedDate, 'event_time' => $formattedTime, 'project_id' => $projectId, 'message' => 'Событие успешно создано и привязано к проекту' ]; log_event_creation('SUCCESS', "=== ОБРАБОТКА ЗАВЕРШЕНА УСПЕШНО ==="); header('Content-Type: application/json; charset=utf-8'); echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); exit(0); } catch (Exception $e) { $error_message = $e->getMessage(); log_event_creation('ERROR', "Ошибка: $error_message"); log_event_creation('ERROR', "Стек: " . $e->getTraceAsString()); $response = [ 'success' => false, 'error' => $error_message, 'timestamp' => date('Y-m-d H:i:s') ]; header('Content-Type: application/json; charset=utf-8'); http_response_code(500); echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT); exit(1); } ?>