trinion_crm-1.0.x-dev/trinion_crm.module
trinion_crm.module
<?php
use Drupal\user\Entity\User;
/**
* Implements hook_form_alter().
*/
function trinion_crm_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
if (isset($form['field_tl_organizaciya'])) {
$config = Drupal::config('trinion_crm.settings');
if ($default_value = $config->get('default_organization'))
$form['field_tl_organizaciya']['widget']['#default_value'] = $default_value;
}
if (in_array($form_id, ['taxonomy_term_crm_bankovskie_scheta_form', 'taxonomy_term_metody_vkhozhdeniya_lida_form', 'taxonomy_term_status_obrabotki_lida_form', 'taxonomy_term_statusy_sdelki_form',])) {
$form['description']['#access'] = FALSE;
$form['relations']['#access'] = FALSE;
$form['status']['#access'] = FALSE;
}
if (preg_match('/^contact_message_.+_form$/', $form_id)) {
$form['actions']['submit']['#submit'][] = 'trinion_crm_contact_form_submit';
}
if (preg_match('/^node_(.*)_form$/U', $form_id, $match)) {
if (isset($form['field_tl_otvetstvennyy'])) {
$form['field_tl_otvetstvennyy']['widget'][0]['target_id']['#default_value'] = \Drupal\user\Entity\User::load(Drupal::currentUser()->id());
}
if (in_array($match[1], ['sdelki', 'lead'])) {
$form['title']['widget']['0']['value']['#default_value'] = Drupal::service('trinion_crm.helper')->getNextDocumentNumber($match[1]);
}
}
if (preg_match('/^node_(.*)(_edit|)_form$/U', $form_id, $match)) {
if (in_array($match[1], ['sdelki',])) {
$form['field_tl_kompaniya']['widget'][0]['target_id']['#attributes']['class'][] = 'pole_kompanii';
$form['field_tl_contact']['widget'][0]['target_id']['#attributes']['class'][] = 'pole_kontakta';
}
}
if ($form_id == 'node_lead_form') {
if ($mail_nid = Drupal::request()->get('mail')) {
$node_mail = \Drupal\node\Entity\Node::load($mail_nid);
$form['field_tl_email']['widget'][0]['value']['#default_value'] = $node_mail->get('field_tm_sender_email')->getString();
$form['field_tl_text']['widget'][0]['value']['#default_value'] = $node_mail->get('field_tm_text')->getValue()[0]['value'];
$form['field_tl_status_obrabotki_lida']['widget']['#default_value'] = Drupal::config('trinion_crm.settings')->get('status_obrabotki_lida_noviy_tid');
$form['field_tl_metod_vkhozhdeniya_lida']['widget']['#default_value'] = Drupal::config('trinion_crm.settings')->get('lead_metod_vhozhdeniya_email_tid');
}
}
if ($form_id == 'node_contact_form') {
if ($comp_nid = Drupal::request()->get('kompaniya')) {
if ($comp = \Drupal\node\Entity\Node::load($comp_nid)) {
$form['field_tl_kompaniya']['widget'][0]['target_id']['#default_value'] = $comp;
}
}
}
// if ($form_id == 'node_kompanii_edit_form' || $form_id == 'node_contact_edit_form') {
// $view = \Drupal\views\Views::getView('pole_kommunikacii');
// $view->setDisplay('block_1');
// $view->setArguments([Drupal::routeMatch()->getParameter('node')->id()]);
// $form['field_kommunikaciya'] = $view->render();
// }
}
function trinion_crm_contact_form_submit($form, \Drupal\Core\Form\FormState $form_state) {
$text = [];
if (!preg_match('/^contact-message-(.*)-form$/U', $form['#id'], $match))
return;
$field_definition = \Drupal::service('entity_field.manager')->getFieldDefinitions('contact_message', str_replace('-', '_', $match[1]));
foreach ($form_state->getValues() as $field_name => $value) {
if (in_array($field_name, ['langcode', 'copy', 'preview', 'antibot_key']) || empty($value))
continue;
if (is_array($value)) {
if (isset($value[0]['value']))
$value = $value[0]['value'];
else
$value = $value['value'];
}
if (empty($title))
$title = $value;
switch ($field_name) {
case 'mail':
$field_name = 'E-Mail';
$title = $value;
break;
case 'name':
$field_name = 'Имя';
$title = $value;
break;
case 'subject':
$field_name = 'Тема сообщения';
break;
case 'message':
$field_name = 'Текст сообщения';
break;
default:
$field_name = $field_definition[$field_name]->label();
}
$text[] = "{$field_name}: {$value}";
}
$config = \Drupal::config('trinion_crm.settings');
$lead_data = [
'type' => 'lead',
'title' => $title ?? 'Лид',
'uid' => Drupal::currentUser()->id(),
'status' => 1,
'field_tl_text' => implode("\n", $text),
'field_tl_metod_vkhozhdeniya_lida' => $config->get('lead_metod_vhozhdeniya_form_tid'),
'field_tl_status_obrabotki_lida' => $config->get('status_obrabotki_lida_noviy_tid'),
];
$node = \Drupal\node\Entity\Node::create($lead_data);
$node->save();
// Отправка уведомления о лиде
$to = [];
foreach ($config->get('lid_poluchatel_uvedomleniya') as $item) {
if ($user = User::load($item['target_id'])) {
$to[] = $user->get('mail')->getString();
}
}
$to = implode(',', $to);
$mail_manager = \Drupal::service('plugin.manager.mail');
$params['message'] = "Новый лид: {$lead_data['title']}<br><br>
{$lead_data['field_tl_text']}";
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$mail_manager->mail('trinion_crm', 'lid_manager_notice', $to, $langcode, $params, NULL, $send);
}
/**
* Implements hook_mail().
*/
function trinion_crm_mail($key, &$message, $params) {
if ($key == 'lid_manager_notice') {
$message['subject'] = \Drupal::config('system.site')->get('name') . '. Создан новый лид.';
$message['body'][] = $params['message'];
}
}
/**
* Implements hook_theme().
*/
function trinion_crm_theme($existing, $type, $theme, $path) {
return [
'kompaniya_pdf' => [
'variables' => [
'directory' => DRUPAL_ROOT . '/' . $path,
'node' => NULL,
'root_path' => NULL,
],
'template' => 'kompaniya',
],
'kontakt_pdf' => [
'variables' => [
'directory' => DRUPAL_ROOT . '/' . $path,
'node' => NULL,
'root_path' => NULL,
],
'template' => 'contact',
],
'lead_pdf' => [
'variables' => [
'directory' => DRUPAL_ROOT . '/' . $path,
'node' => NULL,
'root_path' => NULL,
],
'template' => 'lead',
],
'sdelka_pdf' => [
'variables' => [
'directory' => DRUPAL_ROOT . '/' . $path,
'node' => NULL,
'root_path' => NULL,
],
'template' => 'sdelka',
],
];
}
/**
* Implements hook_entity_load().
*/
function trinion_crm_entity_load($entities, $entity_type_id) {
if ($entity_type_id == 'node') {
foreach ($entities as $entity) {
$bundle = $entity->bundle();
if ($bundle == 'sdelki') {
$entity->node_title = t('@document № @num from @date', [
'@document' => $entity->get('type')->first()->entity->label(),
'@num' => $entity->label(),
'@date' => date('j.m.Y H:i', strtotime($entity->get('field_tl_data')->getString())),
]
);
}
if (in_array($bundle, ['kompanii', 'contact', ])) {
$entity->node_title = t('@document № @num from @date', [
'@document' => $entity->get('type')->first()->entity->label(),
'@num' => $entity->label(),
'@date' => date('j.m.Y', $entity->get('created')->getString()),
]
);
}
}
}
}
function trinion_crm_preprocess_page(&$variables) {
$route_match = Drupal::routeMatch();
$route_name = $route_match->getRouteName();
if ($route_name == 'entity.node.edit_form') {
$node = $route_match->getParameter('node');
if ($node && in_array($node->bundle(), ['sdelki', ])) {
$variables['#attached']['library'][] = 'trinion_crm/crm';
}
}
elseif ($route_name == 'node.add') {
$node_type = $route_match->getParameter('node_type');
if ($node_type && in_array($node_type->id(), ['sdelki', ])) {
$variables['#attached']['library'][] = 'trinion_crm/crm';
}
}
}
function trinion_crm_preprocess_page_title(&$variables) {
$router_match = Drupal::routeMatch();
$node = $router_match->getParameter('node');
if (is_object($node)) {
if ($node->bundle() == 'sdelki')
$variables['title'] = 'Сделка № ' . $node->label();
}
else {
$node_type = $router_match->getParameter('node_type');
if ($node_type) {
if ($node_type->id() == 'sdelki') {
$variables['title'] = 'Создание сделки';
}
}
}
}
function trinion_crm_preprocess_views_view(&$variables) {
if (in_array($variables['view']->id(), ['crm_spisok_kontaktov_v_kompanii', 'crm_spisok_sdelok_v_kompanii'])) {
$variables['no_border'] = TRUE;
}
}
function trinion_crm_node_view(array &$build, \Drupal\node\NodeInterface $node, $display, $view_mode) {
$build['#cache']['max-age'] = 0;
$bundle = $node->bundle();
if ($bundle == 'kompanii') {
if ($display->getComponent('kontakti')) {
$view = \Drupal\views\Views::getView('crm_spisok_kontaktov_v_kompanii');
$view->setDisplay('default');
$view->setArguments([$node->id()]);
$build['kontakti'] = $view->render();
}
if ($display->getComponent('sdelki')) {
$view = \Drupal\views\Views::getView('crm_spisok_sdelok_v_kompanii');
$view->setDisplay('default');
$view->setArguments([$node->id()]);
$build['sdelki'] = $view->render();
}
if ($display->getComponent('scheta')) {
if ($view = \Drupal\views\Views::getView('crm_spisok_schetov_v_kompanii')) {
$view->setArguments([$node->id()]);
$view->setDisplay('block_1');
$build['scheta']['scheta_pokupateliu'] = $view->render();
}
if ($view = \Drupal\views\Views::getView('crm_spisok_schetov_v_kompanii')) {
$view->setArguments([$node->id()]);
$view->setDisplay('block_2');
$build['scheta']['scheta_prodavtsa'] = $view->render();
}
}
if ($display->getComponent('kommercheskie_predlozheniya')) {
if ($view = \Drupal\views\Views::getView('crm_spisok_kommercheskih_predlozheniy_v_kompanii')) {
$view->setArguments([$node->id()]);
$view->setDisplay('default');
$build['kommercheskie_predlozheniya'] = $view->render();
}
}
if ($display->getComponent('zadacha')) {
if ($view = \Drupal\views\Views::getView('list_tasks_in_company')) {
$view->setArguments([$node->id()]);
$view->setDisplay('default');
$build['zadachi'] = $view->render();
}
}
}
if ($bundle == 'sdelki') {
$docs = Drupal::service('trinion_base.related_docs')->getRalatedDocs($node);
$view = \Drupal\views\Views::getView('base_spisok_sviazannih_documentov');
$view->setDisplay('block_1');
$view->setArguments([implode('+', $docs)]);
$build['spisok_sviazannih_documentov'] = $view->render();
}
}
/**
* Implements hook_entity_extra_field_info().
*/
function trinion_crm_entity_extra_field_info() {
$extra = [
'node' => [
'kompanii' => [
'display' => [
'kontakti' => [
'label' => 'Список контактов',
'weight' => '110'
],
'sdelki' => [
'label' => 'Список сделок',
'weight' => '120'
]
]
],
],
];
$module_handler = \Drupal::service('module_handler');
if ($module_handler->moduleExists('trinion_tp')) {
$extra['node']['kompanii']['display']['scheta'] = [
'label' => 'Список счетов',
'weight' => '130'
];
$extra['node']['kompanii']['display']['kommercheskie_predlozheniya'] = [
'label' => 'Список коммерческих предложений',
'weight' => '140'
];
}
if ($module_handler->moduleExists('trinion_zadachnik_crm')) {
$extra['node']['kompanii']['display']['zadacha'] = [
'label' => t('List of tasks'),
'weight' => '150'
];
}
return $extra;
}
/**
* Implements hook_views_query_alter().
*/
function trinion_crm_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query) {
if ($view->id() == 'ssylka_na_suschnost_kontakty_v_kompanii') {
$request = Drupal::request();
if ($referer = $request->server->get('HTTP_REFERER')) {
$parts = parse_url($referer);
if (isset($parts['query'])) {
parse_str($parts['query'], $q);
if (isset($q['comp']) && preg_match('/\((\d+)\)[^(]*$/', $q['comp'], $match)) {
foreach ($query->where as $key => $group) {
foreach ($group['conditions'] as $gkey => $condition) {
if ($condition['field'] == 'node__field_tl_kompaniya.field_tl_kompaniya_target_id') {
$query->where[$key]['conditions'][$gkey]['value'] = $match[1];
}
}
}
}
}
}
}
}
/**
* Implements hook_views_pre_execute().
*/
function trinion_crm_views_pre_execute(\Drupal\views\ViewExecutable $view) {
if (in_array($view->id(), ['crm_spisok_kompanii', 'crm_spisok_sdelki', 'crm_spisok_kontakty', 'lidy'])) {
$show_only_my = Drupal::service('trinion_main.helper')->getMyAllSwitcherValue($view->id());
if ($show_only_my) {
$query = $view->build_info['query'];
$uid = Drupal::currentUser()->id();
$query->leftJoin('node__field_tl_otvetstvennyy', 'ru', 'node_field_data.nid = ru.entity_id AND ru.field_tl_otvetstvennyy_target_id = :uid', [':uid' => $uid]);
$query->isNotNull('ru.entity_id');
$view->build_info['query'] = $query;
$view->build_info['count_query'] = $query;
}
}
}
/**
* Implements hook_entity_presave().
*/
function trinion_crm_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
$bundle = $entity->bundle();
$entity_type = $entity->getEntityType()->id();
if ($entity_type == 'comment' && $bundle == 'tz_k_zadache') {
if ($entity->getCommentedEntity()->bundle() != 'zadacha')
Drupal::service('trinion_main.mails')->uvedomlenieNoviyCommentKDocumentu($entity);
}
}
/**
* Implements hook_entity_access().
*/
function trinion_crm_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
$bundle = $entity->bundle();
if ($operation == 'view') {
if ($bundle == 'lead')
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_crm lead'));
elseif ($bundle == 'kompanii')
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_crm company'));
elseif ($bundle == 'contact')
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_crm contact'));
elseif ($bundle == 'sdelki')
return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_crm sdelki'));
}
}
