trinion_tp-1.0.x-dev/trinion_tp.module

trinion_tp.module
<?php

/**
 * Implements hook_theme().
 */
function trinion_tp_theme($existing, $type, $theme, $path) {
  return [
    'schet_klienta_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'schet_klienta',
      'path' => $path . '/templates',
    ],
    'zakaz_klienta_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'zakaz_klienta',
    ],
    'akt_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'akt',
    ],
    'kommercheskoe_predlogenie_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'kommercheskoe_predlogenie',
      'path' => $path . '/templates',
    ],
    'otgruzka_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'otgruzka',
      'path' => $path . '/templates',
    ],
    'upd_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'items' => NULL,
        'zakaz' => NULL,
        'otgruzka' => NULL,
        'org' => NULL,
        'customer' => NULL,
        'date' => NULL,
        'zakaz_date' => NULL,
      ],
      'template' => 'upd',
      'path' => $path . '/templates',
    ],
    'poluchennyy_platezh_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'poluchennyy_platezh',
      'path' => $path . '/templates',
    ],
    'otpravlennyy_platezh_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'otpravlennyy_platezh',
      'path' => $path . '/templates',
    ],
    'postuplenie_tovarov_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'postuplenie_tovarov',
      'path' => $path . '/templates',
    ],
    'schet_postavschika_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'schet_postavschika',
      'path' => $path . '/templates',
    ],
    'zakaz_postavshiku_pdf' => [
      'variables' => [
        'directory' => DRUPAL_ROOT . '/' . $path,
        'node' => NULL,
        'root_path' => NULL,
      ],
      'template' => 'zakaz_postavshiku',
      'path' => $path . '/templates',
    ],
  ];
}

function trinion_tp_preprocess_pdf(&$variables) {
}


function trinion_tp_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(), ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'zakaz_postavschiku', 'schet', 'schet_postavschika', 'otgruzka',  'postuplenie_tovarov', 'peremeshchenie_tovarov', 'trebovanie_nakladnaya', 'vypusk_produkcii', 'mrp_specifikaciya', 'tp_sales_plan', ])) {
      $variables['#attached']['library'][] =  'trinion_tp/tp';
    }
  }
  elseif ($route_name == 'node.add') {
    $node_type = $route_match->getParameter('node_type');
    if ($node_type && in_array($node_type->id(), ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'zakaz_postavschiku', 'schet', 'schet_postavschika', 'otgruzka', 'postuplenie_tovarov', 'peremeshchenie_tovarov', 'trebovanie_nakladnaya', 'vypusk_produkcii', 'mrp_specifikaciya', 'tp_sales_plan', ])) {
      $variables['#attached']['library'][] =  'trinion_tp/tp';
    }
  }
}

function trinion_tp_preprocess_page_title(&$variables) {
  $router_match = Drupal::routeMatch();
  $route_name = $router_match->getRouteName();
  $node = $router_match->getParameter('node');
  if (is_object($node)) {
    if ($node->bundle() == 'kommercheskoe_predlozhenie')
      $variables['title'] = 'Коммерческое предложение № ' . $node->label();
    elseif ($node->bundle() == 'zakaz_klienta')
      $variables['title'] = 'Заказ клинта № ' . $node->label();
    elseif ($node->bundle() == 'schet')
      $variables['title'] = 'Счет № ' . $node->label();
    elseif ($node->bundle() == 'zakaz_postavschiku')
      $variables['title'] = 'Заказ поставщику № ' . $node->label();
    elseif ($node->bundle() == 'otpravlennyy')
      $variables['title'] = 'Отправленный платеж № ' . $node->label();
    elseif ($node->bundle() == 'poluchennyy_platezh')
      $variables['title'] = 'Полученный платеж № ' . $node->label();
    elseif ($node->bundle() == 'schet_postavschika')
      $variables['title'] = 'Счет поставщика № ' . $node->label();
    elseif ($node->bundle() == 'otgruzka')
      $variables['title'] = 'Отгрузка № ' . $node->label();
  }
  else {
//    $node_type = $router_match->getParameter('node_type');
//    if ($node_type) {
//      if ($node_type->id() == 'zakaz_klienta') {
//        $variables['title'] = 'Создание заказа покупателя';
//      }
//      elseif ($node_type->id() == 'kommercheskoe_predlozhenie') {
//        $variables['title'] = 'Создание коммерческого предложения';
//      }
//      elseif ($node_type->id() == 'schet') {
//        $variables['title'] = 'Создание счета';
//      }
//      elseif ($node_type->id() == 'zakaz_postavschiku') {
//        $variables['title'] = 'Создание заказа поставщику';
//      }
//      elseif ($node_type->id() == 'poluchennyy_platezh') {
//        $variables['title'] = 'Создание полученного платежа';
//      }
//      elseif ($node_type->id() == 'otpravlennyy_platezh') {
//        $variables['title'] = 'Создание отправленного платежа';
//      }
//      elseif ($node_type->id() == 'schet_postavschika') {
//        $variables['title'] = 'Создание создание счета';
//      }
//      elseif ($node_type->id() == 'otgruzka') {
//        $variables['title'] = 'Создание отгрузки';
//      }
//    }
  }
}

function trinion_tp_preprocess_views_view_field(&$variables) {
  if ($variables['field']->field == 'field_tp_nacenka_summa') {
    $node = $variables['row']->_relationship_entities['field_tp_stroki'];
    $kolichestvo = floatval($node->get('field_tp_kolichestvo')->getString());
    $cena = floatval($node->get('field_tp_cena')->getString());
    $nacenka_sum = floatval($node->get('field_tp_nacenka_summa')->getString());
    $nacenka_procent = floatval($node->get('field_tp_nacenka')->getString());
    $nacenka_sum += ($cena / 100) * $nacenka_procent * $kolichestvo;
    $variables['output'] = $nacenka_sum;
  }
  elseif ($variables['field']->field == 'field_tp_skidka_summa') {
    $node = $variables['row']->_relationship_entities['field_tp_stroki'];
    $kolichestvo = floatval($node->get('field_tp_kolichestvo')->getString());
    $cena = floatval($node->get('field_tp_cena')->getString());
    $skidka_sum = floatval($node->get('field_tp_skidka_summa')->getString());
    $skidka_procent = floatval($node->get('field_tp_skidka')->getString());
    $skidka_sum += ($cena / 100) * $skidka_procent * $kolichestvo;
    $variables['output'] = $skidka_sum;
  }
}

/**
 * Implements hook_node_view().
 */
function trinion_tp_node_view(array &$build, \Drupal\node\NodeInterface $node, $display, $view_mode) {
  $bundle = $node->bundle();
  if (isset($build['field_tp_stroki'])) {
    $build['#cache']['max-age'] = 0;
    if ($bundle == 'poluchennyy_platezh' || $bundle == 'otpravlennyy_platezh') {
      $view = \Drupal\views\Views::getView('crm_stroki_schet_klienta_k_oplate');
      $view->setDisplay('default');
    } else {
      $view = \Drupal\views\Views::getView('crm_stroki_uit');
      if (in_array($bundle, ['otgruzka', 'mrp_specifikaciya', 'tp_sales_plan'])) {
        $view->setDisplay('block_2');
      } elseif ($bundle == 'postuplenie_tovarov' || $bundle == 'zakaz_postavschiku') {
        $view->setDisplay('block_3');
      } else {
        $view->setDisplay('block_1');
      }
    }
    $build['field_tp_stroki'] = $view->render();
  }
  if ($bundle == 'sdelki' && $display->id() == 'node.sdelki.default') {
    if ($zakaz = Drupal::service('trinion_tp.helper')->KPFromSdelka($node->id())) {
      $build['#kp'] = \Drupal\node\Entity\Node::load($zakaz);
    }
  }
  if ($bundle == 'kommercheskoe_predlozhenie' && $display->id() == 'node.kommercheskoe_predlozhenie.default') {
    if ($zakaz = Drupal::service('trinion_tp.helper')->zakazKlientaFromKommPredlozhenie($node->id())) {
      $build['#zakaz'] = \Drupal\node\Entity\Node::load($zakaz);
    }
  }
  if ($bundle == 'zakaz_klienta' && $display->id() == 'node.zakaz_klienta.default') {
    $build['#schet'] = $node->schet;
    $build['#otgruzka'] = $node->otgruzka;
  }
  if ($bundle == 'zakaz_postavschiku' && $display->id() == 'node.zakaz_postavschiku.default') {
    $build['#schet'] = $node->schet;
    $build['#postupleniye_tovarov'] = $node->postupleniye_tovarov;
  }
  if ($bundle == 'zakaz_klienta' && $display->id() == 'node.zakaz_klienta.default') {
    if ($zakaz_postavschiku = Drupal::service('trinion_tp.helper')->zakazPostavshikuFromZakazKlienta($node->id())) {
      $build['#zakaz_postavschiku'] = \Drupal\node\Entity\Node::load($zakaz_postavschiku);
    }
  }
  if (in_array($bundle, \Drupal::service('trinion_tp.helper')->getProductBundles())) {
    if (in_array('t_tp', \Drupal::currentUser()->getRoles())) {
      $view = \Drupal\views\Views::getView('crm_spisok_cen_tovara');
      $view->setDisplay('block_1');
      $content = $view->render();
      if ($view->total_rows) {
        $build['ceni'] = [
          '#type' => 'fieldset',
          '#title' => t('Prices'),
        ];
        $build['ceni'][] = $content;
      }
      if (\Drupal::service('module_handler')->moduleExists('trinion_mpr')) {
        $view = \Drupal\views\Views::getView('crm_list_of_product_specifications');
        $view->setDisplay('default');
        $content = $view->render();
        if ($view->total_rows) {
          $build['specificacii'] = [
            '#type' => 'fieldset',
            '#title' => t('Specifications'),
          ];
          $build['specificacii'][] = $content;
        }
      }
    }
  }
  if (in_array($bundle, ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'zakaz_postavschiku', 'schet_postavschika', 'postuplenie_tovarov', 'schet', 'otgruzka', 'poluchennyy_platezh', 'otpravlennyy_platezh', ])) {
    $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();
  }
  if ($bundle == 'ostatok' || $bundle == 'ostatki_materilov_v_proizvodstve') {
    $view = \Drupal\views\Views::getView('crm_list_of_movements');
    $view->setDisplay('block_1');
    $view->setArguments([$node->id()]);
    $build['spisok_dvizheniy'] = $view->render();
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function trinion_tp_entity_extra_field_info() {
  $extra = [];

  $extra['node']['tovar'] = [
    'display' => [
      'ceni' => [
        'label' => 'Таблица цен',
        'weight' => '100'
      ]
    ]
  ];
  return $extra;
}

/**
 * Implements hook_entity_create_access().
 */
function trinion_tp_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle) {
//  if ($entity_bundle == 'poluchennyy_platezh' || $entity_bundle == 'otpravlennyy_platezh') {
//    if ($companiya = \Drupal::request()->get('companiya'))
//      $companiya = \Drupal\node\Entity\Node::load($companiya);
//      if ($companiya)
//      return \Drupal\Core\Access\AccessResult::allowed();
//    return \Drupal\Core\Access\AccessResult::forbidden();
//  }
}

/**
 * Implements hook_entity_access().
 */
function trinion_tp_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account) {
  $bundle = $entity->bundle();
  if ($operation == 'update') {
    if ($bundle == 'zakaz_klienta') {
      if ($entity->schet) {
        Drupal::messenger()->addWarning(t('Sales order has Invoice'));
        return \Drupal\Core\Access\AccessResult::forbidden();
      }
    }
    if ($entity->getEntityTypeId() == 'node' && $entity->hasField('field_tp_utverzhdeno')) {
      if ($entity->get('field_tp_utverzhdeno')->getString()) {
        Drupal::messenger()->addWarning(t('Document is Approved'));
        return \Drupal\Core\Access\AccessResult::forbidden();
      }
    }
  }
  elseif ($operation == 'view') {
    if ($bundle == 'zakaz_postavschiku')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp zakaz_postavschiku'));
    elseif ($bundle == 'otpravlennyy_platezh')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp otpravlennyy_platezh'));
    elseif ($bundle == 'poluchennyy_platezh')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp poluchennyy_platezh'));
    elseif ($bundle == 'schet_klienta')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp schet_klienta'));
    elseif ($bundle == 'ostatok' || $bundle == 'ostatki_materilov_v_proizvodstve')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp prosmotr_ostatkov'));
    elseif ($bundle == 'trebovanie_nakladnaya')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp trebovanie_nakladnaya'));
    elseif ($bundle == 'vypusk_produkcii')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp vypusk_produkcii'));
    elseif ($bundle == 'peremeshchenie_tovarov')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp prosmotr_peremeshcheniy_tovarov'));
    elseif ($bundle == 'tp_sales_plan')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp prosmotr_planov_prodazh'));
    elseif ($bundle == 'zakaz_klienta')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp zakaz_klienta') && $account->id() != $entity->get('uid')->getString());
    elseif ($bundle == 'tovari' || $bundle == 'cena')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp tovari'));
    elseif ($bundle == 'kommercheskoe_predlozhenie')
      return \Drupal\Core\Access\AccessResult::forbiddenIf(!$account->hasPermission('trinion_tp kommercheskie predlogeniya'));
    elseif ($bundle == 'tp_stroka_dokumenta_uit' || $bundle == 'tp_stroka_schet_klienta_k_oplate')
      return \Drupal\Core\Access\AccessResult::forbidden();
  }
}


/**
 * Implements hook_entity_load().
 */
function trinion_tp_entity_load($entities, $entity_type_id) {
  if ($entity_type_id == 'node') {
    foreach ($entities as $entity) {
      $bundle = $entity->bundle();
      if (in_array($bundle, ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'schet', 'zakaz_postavschiku', 'schet_postavschika', 'postuplenie_tovarov', 'peremeshchenie_tovarov', 'otgruzka', 'poluchennyy_platezh', 'otpravlennyy_platezh', 'trebovanie_nakladnaya', ])) {
        $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_tp_data')->getString())),
          ]
        );
      }
      if ($bundle == 'sdelki') {
        if ($schet_id = Drupal::service('trinion_tp.helper')->KPFromSdelka($entity->id())) {
          $entity->kp = \Drupal\node\Entity\Node::load($schet_id);
        }
      }
      elseif ($bundle == 'zakaz_postavschiku') {
        if ($schet_id = Drupal::service('trinion_tp.helper')->schetPostavshikaFromZakazPostavshika($entity->id())) {
          $entity->schet = \Drupal\node\Entity\Node::load($schet_id);
        }
        if ($postupleniya_ids = Drupal::service('trinion_tp.helper')->postupleniyeTovarovFromZakazPostavshika($entity->id())) {
          $entity->postupleniye_tovarov = \Drupal\node\Entity\Node::loadMultiple($postupleniya_ids);
        }
        $postupleniya = Drupal::service('trinion_tp.helper')->postupleniyeTovarovFromZakazPostavshika($entity->id());
        if (empty($postupleniya)) {
          $entity->otgruzka_status = t('Not shipped');
//          $entity->postupleniya = [];
        }
        else {
          if ($ne_otgruzheno = Drupal::service('trinion_tp.helper')->neOtgruzhenoIzZakazPostavshiku($entity, $postupleniya)) {
            $entity->otgruzka_status = t('Partially shipped');
          }
          else {
            $entity->otgruzka_status = t('Shipped');
          }
//          $entity->postupleniya = \Drupal\node\Entity\Node::loadMultiple($postupleniya);
        }
      }
      elseif ($bundle == 'zakaz_klienta') {
        $entity->payed_status_id = 1;
        $entity->payed_status = t('Not payed');
        $otgruzki = Drupal::service('trinion_tp.helper')->otgruzkiByZakazKlienta($entity->id());
        if (empty($otgruzki)) {
          $entity->otgruzka_status = t('Not shipped');
          $entity->otgruzka_status_id = 1;
          $entity->otgruzki = [];
        }
        else {
          if ($ne_otgruzheno = Drupal::service('trinion_tp.helper')->neOtgruzhenoIzZakazKlienta($entity, $otgruzki)) {
            $entity->otgruzka_status = t('Partially shipped');
            $entity->otgruzka_status_id = 2;
          }
          else {
            $entity->otgruzka_status = t('Shipped');
            $entity->otgruzka_status_id = 3;
          }
          $entity->otgruzki = \Drupal\node\Entity\Node::loadMultiple($otgruzki);
        }
        $utverzhdenniy_schet = FALSE;
        if ($schet_id = Drupal::service('trinion_tp.helper')->schetKlientaFromZakazKlienta($entity->id())) {
          // Check invoice is exists
          $proverka_schetov = [];
          foreach ($entity->get('field_tp_stroki') as $stroka) {
            $item = $stroka->entity;
            $key = $item->get('field_tp_tovar')->getString() . '-' . $item->get('field_tp_edinica_izmereniya')->getString() . '-' . $item->get('field_tp_kharakteristika_tovara')->getString();
            $proverka_schetov[$key] = $item->get('field_tp_kolichestvo')->getString();
          }
          $entity->schet = \Drupal\node\Entity\Node::loadMultiple($schet_id);

          $statusi_oplati = [];
          $platezhi = [];
          foreach ($entity->schet as $schet) {
            $platezhi = array_merge($platezhi, Drupal::service('trinion_tp.helper')->poluchenniyPlatezhFromSchetKlienta($schet->id()));
            if (!$schet->get('field_tp_utverzhdeno')->getString())
              continue;

            $statusi_oplati[] = $schet->sostoyanie_oplati_tid;
            $utverzhdenniy_schet = TRUE;
            foreach ($schet->get('field_tp_stroki') as $stroka) {
              $item = $stroka->entity;

              $key = $item->get('field_tp_tovar')->getString() . '-' . $item->get('field_tp_edinica_izmereniya')->getString() . '-' . $item->get('field_tp_kharakteristika_tovara')->getString();
              if (isset($proverka_schetov[$key]))
                $proverka_schetov[$key] -= $item->get('field_tp_kolichestvo')->getString();
              if ($proverka_schetov[$key] <= 0)
                unset($proverka_schetov[$key]);
            }
          }

          $entity->platezhi = $platezhi ? \Drupal\node\Entity\Node::loadMultiple($platezhi) : [];
          // Payment status
          // 1 - not payed
          // 2 - partially payed
          // 3 - payed
          $schet_klienta_oplachen_tid = Drupal::config('trinion_tp.settings')->get('schet_klienta_oplachen_tid');
          $schet_klienta_chast_oplachen_tid = Drupal::config('trinion_tp.settings')->get('schet_klienta_chast_oplachen_tid');
          $schet_klienta_nov_tid = Drupal::config('trinion_tp.settings')->get('schet_klienta_nov_tid');

          if (in_array($schet_klienta_chast_oplachen_tid, $statusi_oplati)) {
            $entity->payed_status_id = 2;
            $entity->payed_status = t('Partially payed');
          }
          elseif (in_array($schet_klienta_oplachen_tid, $statusi_oplati)) {
            if (in_array($schet_klienta_nov_tid, $statusi_oplati)) {
              $entity->payed_status_id = 2;
              $entity->payed_status = t('Partially payed');
            }
            else {
              $entity->payed_status_id = 3;
              $entity->payed_status = t('Payed');
            }
          }
        }
        // SO state based on Invoice Approve status
        // 1 - not exposed
        // 2 - partially exposed
        // 3 - exposed
        if ($utverzhdenniy_schet) {
          if (empty($proverka_schetov)) {
            $entity->schet_status_id = 3;
            $entity->schet_status = t('Exposed');
          }
          else {
            $entity->schet_status_id = 2;
            $entity->schet_status = t('Partially exposed');
          }
        }
        else {
          $entity->schet_status_id = 1;
          $entity->schet_status = t('Not exposed');
        }
      }
      elseif ($bundle == 'schet') {
        $schet_data = Drupal::service('trinion_tp.helper')->calculateSchetKlienta($entity);
        $entity->sostoyanie_oplati_tid = $schet_data['sostoyanie_oplati_tid'];
        $entity->sostoyanie_oplati = $schet_data['sostoyanie_oplati'];
        $entity->summa_oplati = $schet_data['summa_oplati'];
      }
      elseif ($bundle == 'schet_postavschika') {
        $schet_data = Drupal::service('trinion_tp.helper')->calculateSchetKlienta($entity);
        $entity->sostoyanie_oplati = $schet_data['sostoyanie_oplati'];
        $entity->summa_oplati = $schet_data['summa_oplati'];
      }
      elseif ($bundle == 'poluchennyy_platezh') {
        $total = $entity->get('field_tp_itogo')->getString();
        $managed = 0;
        foreach ($entity->get('field_tp_stroki') as $stroka) {
          $managed += $stroka->entity->get('field_tp_oplachennaya_summa')->getString();

        }
        $entity->ne_raspredeleno = $total - $managed;
      }
      elseif ($bundle == 'otpravlennyy_platezh') {
        $total = $entity->get('field_tp_itogo')->getString();
        $managed = 0;
        foreach ($entity->get('field_tp_stroki') as $stroka) {
          $managed += $stroka->entity->get('field_tp_oplachennaya_summa')->getString();
        }
        $entity->ne_raspredeleno = $total - $managed;
      }
      elseif ($bundle == 'tp_stroka_schet_klienta_k_oplate') {
        if ($schet = $entity->get('field_tp_schet')->first()->entity)
          $entity->schet_date = \Drupal::service('trinion_tp.helper')->getPluralDate($schet->get('field_tp_data')->getString());
      }
      elseif ($bundle == 'tp_stroka_dokumenta_uit') {
        $cena_itogo = floatval($entity->get('field_tp_cena')->getString()) * floatval($entity->get('field_tp_kolichestvo')->getString());
        $skidka = floatval($entity->get('field_tp_skidka')->getString());
        $skidka_abs = ($cena_itogo / 100) * $skidka;
        $skidka_abs += floatval($entity->get('field_tp_skidka_summa')->getString());

        $nacenka = floatval($entity->get('field_tp_nacenka')->getString());
        $nacenka_abs = ($cena_itogo / 100) * $nacenka;
        $nacenka_abs += floatval($entity->get('field_tp_nacenka_summa')->getString());

        $cena_itogo += $nacenka_abs - $skidka_abs;

        $nds = floatval($entity->get('field_tp_nds')->getString());
        $nds_abs = ($cena_itogo / 100) * $nds;

        $entity->nds = $nds_abs;
        $entity->nacenka_abs = $nacenka_abs;
        $entity->skidka_abs = $skidka_abs;
        $entity->cena_itogo = $cena_itogo;
      }
    }
  }
}

/**
 * Implements hook_entity_delete().
 */
function trinion_tp_entity_delete(\Drupal\Core\Entity\EntityInterface $entity) {
  if (in_array($entity->bundle(), ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'schet', 'zakaz_postavschiku', 'zakaz_postavschiku', 'otgruzka', 'schet_postavschika'])) {
    foreach ($entity->get('field_tp_stroki') as $item) {
      if ($item->entity)
        $item->entity->delete();
    }
  }
  elseif ($entity->bundle() == 'poluchennyy_platezh') {
    foreach ($entity->get('field_tp_stroki') as $item) {
      if ($item->entity) {
        $item->entity->delete();
      }
    }
  }
  elseif ($entity->bundle() == 'otpravlennyy_platezh') {
    $scheta_to_recalc = [];
    foreach ($entity->get('field_tp_stroki') as $item) {
      if ($item->entity) {
        $scheta_to_recalc[] = $item->entity->get('field_tp_schet')->getString();
        $item->entity->delete();
      }
    }
    Drupal::service('trinion_tp.helper')->updateSchetProdavtsa($scheta_to_recalc, $entity->id(), 'delete');
  }
}

/**
 * Implements hook_entity_update().
 */
function trinion_tp_entity_insert(\Drupal\Core\Entity\EntityInterface $entity) {
  if (method_exists($entity, 'hasField') && $entity->hasField('field_tp_stroki')) {
    foreach ($entity->get('field_tp_stroki') as $stroka) {
      $stroka->entity->field_tp_roditelskiy_dokument = $entity->id();
      $stroka->entity->save();
    }
  }
}

/**
 * Implements hook_entity_presave().
 */
function trinion_tp_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
  $route_name = Drupal::routeMatch()->getRouteName();
  $bundle = $entity->bundle();
  if ($bundle == 'schet') {
    if ($route_name == 'node.add') {
      $scheta = \Drupal::service('trinion_tp.helper')->schetaCompaniiDliaOplati(1, [], 'schet');
      $neoplacheno = 0;
      foreach ($scheta as $schet_id) {
        if ($schet = \Drupal\node\Entity\Node::load($schet_id)) {
          $summa = $schet->get('field_tp_itogo')->getString();
          $oplachenaya_summa = $schet->get('field_tp_oplachennaya_summa')->getString();
          if (!is_numeric($oplachenaya_summa))
            $oplachenaya_summa = 0;

          $neoplacheno += $summa - $oplachenaya_summa;
        }
      }
      $entity->field_tp_en_ballance_due = $neoplacheno;
    }
  }
  if (in_array($bundle, ['schet', 'schet_postavschika',]) && $entity->get('field_tp_osnovanie_vruchnuyu')->getString());
  elseif (in_array($bundle, ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'schet', 'zakaz_postavschiku', 'schet_postavschika', 'postuplenie_tovarov'])) {
    if (in_array($bundle, ['schet', 'schet_postavschika',]))
      $entity->field_tp_osnovanie_platezha = '';
    $result = Drupal::service('trinion_tp.helper')->calculateTotals($entity);
    if (isset($result['nds_itog']))
      $entity->field_tp_nds_itogo = $result['nds_itog'];
    if (isset($result['nacenka_itog']))
      $entity->field_tp_nacenka = $result['nacenka_itog'];
    if (isset($result['skidka_itog']))
      $entity->field_tp_skidka = $result['skidka_itog'];
    if (isset($result['cena_itog']))
      $entity->field_tp_itogo = $result['cena_itog'];
  }
//  if ($bundle == 'poluchennyy_platezh' || $bundle == 'otpravlennyy_platezh') {
//    $scheta_to_recalc = [];
//    $stroki_scheta_to_delete = [];
//    foreach ($entity->get('field_tp_stroki') as $item)
//      if ($item->entity)
//        $scheta_to_recalc[] = $item->entity->get('field_tp_schet')->getString();
//    if ($entity->original) {
//      foreach ($entity->original->get('field_tp_stroki') as $item)
//        if ($item->entity) {
//          $id = $item->entity->get('field_tp_schet')->getString();
//          if (!in_array($id, $scheta_to_recalc))
//            $stroki_scheta_to_delete[] = $item->entity->id();
//          $scheta_to_recalc[] = $id;
//        }
//    }
//    foreach ($stroki_scheta_to_delete as $stroka_id) {
//      if ($stroka = \Drupal\node\Entity\Node::load($stroka_id))
//        $stroka->delete();
//    }
//  }
  if ($bundle == 'cena') {
    $entity->title = 'Цена';
  }
}

/**
 * Implements hook_views_pre_execute().
 */
function trinion_tp_views_pre_execute(\Drupal\views\ViewExecutable $view) {
  if (in_array($view->id(), ['crm_spisok_tovary', 'crm_spisok_kommercheskikh_predlozheniy', 'crm_spisok_zakazy_klienta', 'crm_spisok_scheta_klienta', 'crm_spisok_zakazy_postavschiku', 'crm_spisok_schetov_postavschika', 'crm_spisok_postupleniya_tovarov', 'crm_spisok_otgruzki', 'crm_spisok_poluchennye', 'crm_spisok_otpravlennykh_platezhey',])) {
    $show_only_my = Drupal::service('trinion_main.helper')->getMyAllSwitcherValue($view->id());
    if ($show_only_my) {
      $query = $view->build_info['query'];
      $uid = Drupal::currentUser()->id();
      if ($view->id() == 'crm_spisok_tovary')
        $query->leftJoin('node__field_tl_otvetstvennyy', 'ru', 'node_field_data.nid = ru.entity_id AND ru.field_tl_otvetstvennyy_target_id = :uid', [':uid' => $uid]);
      else
        $query->leftJoin('node__field_tp_otvetstvennyy', 'ru', 'node_field_data.nid = ru.entity_id AND ru.field_tp_otvetstvennyy_target_id = :uid', [':uid' => $uid]);
      $query->isNotNull('ru.entity_id');
      $view->build_info['query'] = $query;
      $view->build_info['count_query'] = $query;
    }
  }
}

function trinion_tp_select_company_callback($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $contact = $form['field_tl_contact'];
  $response->addCommand(new \Drupal\Core\Ajax\InsertCommand('.field--name-field-tl-contact', $contact));
  return $response;
}

function trinion_tp_poluchennyy_platezh_select_company_callback($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  return $form['field_tp_stroki'];
}

function trinion_tp_otpravlennyy_platezh_select_company_callback($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  return $form['field_tp_stroki'];
}
/**
 * Implements hook_form_alter().
 */
function trinion_tp_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['field_tp_organizaciya'])) {
    $config = Drupal::config('trinion_crm.settings');
    if ($default_value = $config->get('default_organization'))
      $form['field_tp_organizaciya']['widget']['#default_value'] = $default_value;
  }

  if (in_array($form_id, ['taxonomy_term_tp_charts_of_accounts_form', 'taxonomy_term_statusy_scheta_klienta_form', 'taxonomy_term_edinicy_izmereniya_form', 'taxonomy_term_organizaciya_form', 'taxonomy_term_platezhnye_sistemy_form', 'taxonomy_term_sklad_form', 'taxonomy_term_so_status_for_customer_form', 'taxonomy_term_status_priema_platezha_form', 'taxonomy_term_tp_delivery_method_form', 'taxonomy_term_tip_ceny_form', 'taxonomy_term_tp_payment_terms_form', 'taxonomy_term_tp_podrazdelenie_form', 'taxonomy_term_tp_shipping_carrier_form', 'taxonomy_term_tp_skorost_dostavki_form', 'taxonomy_term_tp_usloviya_postavki_form',])) {
    $form['description']['#access'] = FALSE;
    $form['relations']['#access'] = FALSE;
    $form['status']['#access'] = FALSE;
  }

  if ($form_id == 'taxonomy_term_tp_charts_of_accounts_form') {
    $ops = $form['field_tp_account_type']['widget']['#options'];
    $form['field_tp_account_type']['widget']['#options'] = [
      'Assets' => [
        'other_assets' => t($ops['other_assets']),
        'other_current_assets' => t($ops['other_current_assets']),
        'cash' => t($ops['cash']),
        'bank' => t($ops['bank']),
        'fixed_assets' => t($ops['fixed_assets']),
        'stock' => t($ops['stock']),
        'payment_clearing' => t($ops['payment_clearing']),
      ],
      'Liability' => [
        'other_current_liability' => t($ops['other_current_liability']),
        'credit_card' => t($ops['credit_card']),
        'long_term_liability' => t($ops['long_term_liability']),
        'other_liability' => t($ops['other_liability']),
      ],
      'Income' => [
        'income' => t($ops['income']),
        'other_income' => t($ops['other_income']),
      ],
      'Expense' => [
        'expense' => t($ops['expense']),
        'cost_of_goods_sold' => t($ops['cost_of_goods_sold']),
        'other_expense' => t($ops['other_expense']),
      ],
    ];
  }
  $route_name = Drupal::routeMatch()->getRouteName();
  if (preg_match('/^node_(.*)(_edit|)_form$/U', $form_id, $match)) {
    if (isset($form['field_tp_chart_of_account'])) {
      $form['field_tp_chart_of_account']['widget']['#options'] = \Drupal::service('trinion_tp.helper')->getDerevoStateyZatratDliaPoliya();
    }
    if (in_array($match[1], ['mrp_specifikaciya', ])) {
      $form['field_tp_kharakteristika_tovara']['#attributes']['class'] = ['harakteristika_wrapper'];
      $form['field_tp_kharakteristika_tovara']['widget']['#multiple'] = FALSE;
      $form['field_tp_tovar']['widget'][0]['target_id']['#ajax'] = [
        'callback' => 'trinion_tp_field_tp_tovar_harakterisitka_callback',
        'method' => 'replace',
        'event' => 'autocompleteclose',
      ];
    }
    if (in_array($match[1], ['schet', 'schet_postavschika'])) {
      $form['field_tp_osnovanie_platezha']['#states'] = $form['field_tp_itogo']['#states'] = [
        'visible' => [
          ':input[name="field_tp_osnovanie_vruchnuyu[value]"]' => ['checked' => TRUE],
        ]
      ];
      $form['field_tp_stroki']['#states'] = [
        'visible' => [
          ':input[name="field_tp_osnovanie_vruchnuyu[value]"]' => ['checked' => FALSE],
        ]
      ];
    }
    if (in_array($match[1], ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'schet', 'zakaz_postavschiku', 'schet_postavschika', 'postuplenie_tovarov'])) {
      $form['#node'] = Drupal::routeMatch()->getParameter('node');
    }
    if (in_array($match[1], ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'schet',])) {
      $form['field_tp_schet_dlya']['widget'][0]['target_id']['#attributes']['class'][] = 'pole_kompanii';
    }
    if (in_array($match[1], ['peremeshchenie_tovarov',])) {
      $form['#attributes']['class'][] = 'peremeshenie_tovarov_form';
      $form['field_tp_sklad']['widget']['#attributes']['class'][] = 'pole_sklada';
    }
    if ($match[1] == 'kommercheskoe_predlozhenie' || $match[1] == 'schet_postavschika' || $match[1] == 'schet') {
      $form['field_tp_schet_dlya']['widget'][0]['target_id']['#ajax'] = [
        'callback' => 'trinion_tp_select_company_callback',
        'event' => 'autocompleteclose',
        'method' => 'replace',
      ];
    }
    if ($match[1] == 'zakaz_klienta' || $match[1] == 'zakaz_postavschiku') {
      $form['field_tp_zakaz_dlya']['widget'][0]['target_id']['#ajax'] = [
        'callback' => 'trinion_tp_select_company_callback',
        'event' => 'autocompleteclose',
        'method' => 'replace',
      ];
    }
    if ($match[1] == 'poluchennyy_platezh') {
      $form['field_tp_platelschik']['widget'][0]['target_id']['#ajax'] = [
        'callback' => 'trinion_tp_poluchennyy_platezh_select_company_callback',
        'event' => 'autocompleteclose',
        'wrapper' => 'field-tp-stroki-add-more-wrapper',
      ];
    }
    if ($match[1] == 'otpravlennyy_platezh') {
      $form['field_tp_poluchatel']['widget'][0]['target_id']['#ajax'] = [
        'callback' => 'trinion_tp_otpravlennyy_platezh_select_company_callback',
        'event' => 'autocompleteclose',
        'wrapper' => 'field-tp-stroki-add-more-wrapper',
      ];
    }
    if ($match[1] == 'schet') {
      $query = Drupal::database()->select('taxonomy_term__field_tp_organizaciya', 't')
        ->fields('t', ['entity_id', 'field_tp_organizaciya_target_id']);
      $data = $query->execute()->fetchAll();
      $form['#attached']['drupalSettings']['org_scheta'] = $data;
    }
    if (in_array($match[1], ['postuplenie_tovarov'])) {
      $form['field_tp_zakazy_postavschiku']['widget']['add_more']['#access'] = FALSE;
    }
  }
  if (preg_match('/^node_(.*)_form$/U', $form_id, $match)) {
    if (in_array($match[1], ['kommercheskoe_predlozhenie', 'zakaz_klienta', 'zakaz_postavschiku', 'poluchennyy_platezh', 'otpravlennyy_platezh', 'schet', 'schet_postavschika', 'postuplenie_tovarov', 'otgruzka', 'peremeshchenie_tovarov', 'trebovanie_nakladnaya', 'vypusk_produkcii', 'tp_sales_plan', ])) {
      $form['title']['widget']['0']['value']['#default_value'] = Drupal::service('trinion_tp.helper')->getNextDocumentNumber($match[1]);
    }
  }
  if ($form_id == 'node_cena_form') {
    if ($tovar_nid = Drupal::request()->get('tovar'))
      if ($tovar = \Drupal\node\Entity\Node::load($tovar_nid))
        $form['field_tp_tovar']['widget'][0]['target_id']['#default_value'] = $tovar;
  }
  if ($route_name == 'node.add') {
    if (isset($form['field_tp_otvetstvennyy']))
      $form['field_tp_otvetstvennyy']['widget'][0]['target_id']['#default_value'] = \Drupal\user\Entity\User::load(Drupal::currentUser()->id());
  }
}

function trinion_tp_field_tp_tovar_harakterisitka_callback($form, \Drupal\Core\Form\FormState $form_state) {
  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $harakteristika = $form['field_tp_kharakteristika_tovara'];
  $response->addCommand(new \Drupal\Core\Ajax\InsertCommand('.harakteristika_wrapper', $harakteristika));
  return $response;
}

function trinion_tp_preprocess_views_view(&$variables) {
  if (in_array($variables['view']->id(), ['crm_spisok_schetov_v_kompanii', 'crm_spisok_kommercheskih_predlozheniy_v_kompanii'])) {
    $variables['no_border'] = TRUE;
  }
}

/**
 * Implements hook_mail().
 */
function trinion_tp_mail($key, &$message, $params) {
  if ($key == 'trinion_tp_otpravka_scheta') {
    $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
    $message['subject'] = (string)$params['subject'];
    $message['body'][] = \Drupal\Core\Mail\MailFormatHelper::wrapMail($params['body']);
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc