Snippets Collections
#!/bin/bash
####################################
#
# Rolling 7 day backup to local directory
#
####################################

mysqldump_location="path_to_place_mysql_dump_file"

/usr/bin/mysqldump --opt your_database_name --single-transaction --default-character-set=utf8mb4 > $mysqldump_location/your_dump_file_name.SQL

# What to backup.
backup_files="path_to_your_website_directory"

# Where to backup to.
dest="path_to_place_your_backup_files"

# Create archive filename.
day=$(date +%A)
hostname=$(hostname -s)
archive_file="your_domain_name-$day.zip"


# Backup the files using zip.
zip -r $dest/$archive_file $backup_files
rm -f $mysqldump_location/your_dump_file.SQL
Create Schema demo;

CREATE TABLE demo.emp_info (
    emp_id CHAR(4),
    emp_name VARCHAR(20),
    skills VARCHAR(40),
    exp INT
);

INSERT INTO demo.emp_info
VALUES
("A123", "Rohit Jain", "SQL|C|R|Python|Tableau", 7),
("A124", "Aaina Singh", "SQLC|R|Tableau", 4),
("A125", "Mark John", "C|Python|Java", 10),
("A126", "Sam Keith", "SQL|C", 2),
("A127", "Kenny Ford", "SQL|C|R|Python|Power BI", 5);

CREATE TABLE demo.emp_sal_desig (
    emp_id CHAR(4),
    desig VARCHAR(20),
    salary FLOAT
);

INSERT INTO demo.emp_sal_desig
VALUES
("A123", "L3", 4500),
("A126", "L1", 2500),
("A121", "L2", 3500),
("A122", "L5", 9500);
1. Find the product id and unit list price of products belonging to the 'Yoghurt' category.


SELECT 
	product_id, 
	unit_list_price
FROM 
	products
WHERE 
	product_category = 'yoghurt';

-----------
  
2. Find all the information (i.e., all columns) of the managers with null values in their first name.

SELECT 
   	*
FROM
	managers
WHERE
	first_name IS NULL;

-----------
  
3. Find the sales ID and sales date where quantity sold on that date is greater than or equal to 2100.

SELECT 
	sales_id, 
	sales_date, 
	quantity_sold
FROM
	sales
WHERE
	quantity_sold >= 2100;

-----------

4. Find the manager ID and the sum of quantity sold  for all products (except those with ID 7001001) for each of the managers in the sales table and sort the output by manager ID in descending order.

SELECT 
	sales_manager_id,
	SUM(quantity_sold) AS quant_sold
FROM
	sales
WHERE
	product_id <> 7001001
GROUP BY  
	sales_manager_id
ORDER BY
	sales_manager_id DESC;

-----------

5. Find the product ID, product name, and unit production cost of the products with maximum unit production cost below $1.10 and sort the output by production cost in ascending order (HINT: Use HAVING).

SELECT 
    product_id,
    product_name,
    MAX(unit_production_cost) AS unit_production_cost
FROM
    products
GROUP BY 1 , 2
HAVING 
	MAX(unit_production_cost) < 1.10
ORDER BY 
	unit_production_cost DESC;


SELECT 
    product_id,
    product_name,
	unit_production_cost
FROM
    products
WHERE 
	unit_production_cost < 1.10
ORDER BY 
	unit_production_cost DESC;

-----------

6. Find the product ID and sales date with the highest quantity sold from sales transacted after 30 Oct 2021 (exclusive) except for products with IDs 7001001 and 7001002.


SELECT 
    product_id, 
	sales_date, 
	quantity_sold
FROM
    sales
WHERE
    sales_date > '2021-10-30'
    AND 
	product_id NOT IN (7001001 , 7001002)
ORDER BY 
	quantity_sold desc
LIMIT 1;



SELECT 
    product_id, 
	sales_date, 
	quantity_sold
FROM
    sales
WHERE
    sales_date > '2021-10-30';
SUM(IF((((ca.value2 = 6 AND ca.value4 = 12) OR (ca.value2 = 3 AND ca.value4 = 8) OR (ca.value2 = 3 AND ca.value4 = 9)) AND (CA.value3 = 1 AND CA.value5 = 1)),1,0))
The Alphacodez Cryptocurrency Exchange Script is a robust solution for launching secure and efficient trading platforms, featuring user management, a high-performance trading engine, and wallet integration. It offers advanced security measures and customization options. Ongoing support and maintenance ensure smooth operation.
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
import pandas as pd
import sqlite3

# Create database
conn = sqlite3.connect('guests.db')
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE guests
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              name TEXT,
              phone TEXT,
              email TEXT,
              visits INTEGER)''')

# Insert data
df = pd.read_csv('guests.csv')
df.to_sql('guests', conn, if_exists='append', index=False)

# Close connection
conn.close()
#Needed to filter out all classes that occur at least 5 times in the column.

select class
FROM Courses
GROUP BY class
having count(*) >5
#Find patients with Type 1 Diabetes using the prefix 'DIAB1'

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| patient_id   | int     |
| patient_name | varchar |
| conditions   | varchar |
+--------------+---------+ 

  Input: 
Patients table:
+------------+--------------+--------------+
| patient_id | patient_name | conditions   |
+------------+--------------+--------------+
| 1          | Daniel       | YFEV COUGH   |
| 2          | Alice        |              |
| 3          | Bob          | DIAB100 MYOP |
| 4          | George       | ACNE DIAB100 |
| 5          | Alain        | DIAB201      |
+------------+--------------+--------------+
SELECT *
FROM Patients
WHERE conditions LIKE 'DIAB1%' 
or conditions LIKE '% DIAB1%';
#Find emails: they that MUST start with a letter and MUST BE FOR LEETCODE.COM. 
#Emails can contain letters, numbers, underscores, periods, dashes and hyphens.

SELECT *
FROM Users
WHERE mail REGEXP '^[A-Za-z][A-Za-z0-9_\.\-]*@leetcode(\\?com)?\\.com$';
#Fixing names column so only first letter is uppercase.
Table: Users
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+
  
select user_id,
CONCAT (UPPER(LEFT(name,1)),
LOWER(right(name,LENGTH(name)-1)))
as name from Users
ORDER BY user_id;
Table: Employees

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
| salary      | int     |
+-------------+---------+
 If Employee name does not start with M, AND salary is an odd number, give them a bonus of 100%.

         -- select entries with odd  employee id and name not start with M
            select employee_id , salary as bonus 
            from employees 
            where employee_id%2 <>0 and name not like 'M%'
            
        -- join both selection 
            union
            
        -- select remaining entries from table 
            select employee_id , 0 as bonus
            from employees
            where employee_id%2 = 0 or name like 'M%'
            order by employee_id;
+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| tweet_id       | int     |
| content        | varchar |
+----------------+---------+
tweet_id is the primary key (column with unique values) for this table.
This table contains all the tweets in a social media app.


SELECT tweet_id
FROM Tweets
WHERE CHAR_LENGTH(content) > 15;
$database = \Drupal::database();
  $entity_type_id = 'basic';
  $fields = [
    'employees',
    'employees_to_employ',
    'average_statistical_number_of_em',
  ];

  foreach ($fields as $field_name) {
    $old_rows = NULL;
    $table = $entity_type_id . '__' . $field_name;
    $new_fields_list = [];
    $field_storage = FieldStorageConfig::loadByName($entity_type_id, $field_name);

    if (!$field_storage) {
      continue;
    }

    // Get all current data from DB.
    if ($database->schema()->tableExists($table)) {
      // The table data to restore after the update is completed.
      $old_rows = $database->select($table, 'n')
        ->fields('n')
        ->execute()
        ->fetchAll();
    }

    // Use existing field config for new field.
    foreach ($field_storage->getBundles() as $bundle => $label) {
      if ($bundle !== 'partner_data') {
        continue;
      }
      $field = FieldConfig::loadByName($entity_type_id, $bundle, $field_name);
      $new_field = $field->toArray();
      $new_field['field_type'] = 'decimal';
      $new_fields_list[] = $new_field;
    }

    // Deleting field storage which will also delete bundles(fields).
    $new_field_storage = $field_storage->toArray();
    $new_field_storage['type'] = 'decimal';

    $field_storage->delete();

    // Purge field data now to allow new field and field_storage with same name
    // to be created.
    field_purge_batch(40);

    // Create new field storage.
    $new_field_storage = FieldStorageConfig::create($new_field_storage);
    $new_field_storage->save();

    // Create new fields.
    foreach ($new_fields_list as $new_field) {
      $new_field_config = FieldConfig::create($new_field);
      $new_field_config->save();
    }

    // Restore existing data in new table.
    if ($old_rows) {
      foreach ($old_rows as $row) {
        $database->insert($table)
          ->fields((array) $row)
          ->execute();
      }
    }
  }
SELECT DISTINCT e.employeeNumber, e.lastName, e.firstName
FROM customers c
JOIN employees e ON c.salesRepEmployeeNumber = e.employeeNumber
WHERE customerNumber IN (
	SELECT DISTINCT o.customerNumber
	FROM orderdetails od
	JOIN products p ON od.productCode = p.productCode
	JOIN orders o ON o.orderNumber = od.orderNumber
	WHERE od.priceEach < p.MSRP
);
SELECT temp.customerNumber, country, AVG(timeShipped) AS avgTimeShipped
FROM (
	SELECT customerNumber, shippedDate - orderDate AS timeShipped
	FROM orders
) AS temp
JOIN customers c ON temp.customerNumber = c.customerNumber
GROUP BY customerNumber
ORDER BY country, avgTimeShipped DESC;
WITH CustomerSales AS (
	SELECT p.customerNumber, customerName, salesRepEmployeeNumber, SUM(amount) as total
	FROM payments p
	JOIN customers c ON p.customerNumber = c.customerNumber
	GROUP BY customerNumber
)
SELECT cs.salesRepEmployeeNumber, e.lastName, e.firstName, SUM(total) AS total
FROM CustomerSales cs
JOIN employees e ON cs.salesRepEmployeeNumber = e.employeeNumber
GROUP BY salesRepEmployeeNumber
ORDER BY total DESC
LIMIT 5;
WITH CustomerPayments AS (
    SELECT c.customerNumber, 
           c.customerName,
           SUM(amount) AS total
    FROM customers c
    LEFT JOIN payments p ON c.customerNumber = p.customerNumber
    GROUP BY c.customerNumber, c.customerName
)
SELECT customerName, 
       total,
       CASE
           WHEN total >= 100000 THEN "high-valued"
           WHEN total < 100000 AND total > 0 THEN "medium-valued"
           ELSE "low-valued"
       END AS priority
FROM CustomerPayments
ORDER BY total DESC;
 mysql -h 172.31.74.118 logistics_auth -u user -p3d2de4c0d1aba8fa4155e22c  --port=3306
function deleteRow(){
    global $connection;
    $id = $_POST['id'];

    $query = "DELETE FROM users ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }
}
function updateTable() {
    global $connection;

    $username = $_POST['username'];
    $password = $_POST['password'];
    $id = $_POST['id'];

    $query = "UPDATE users SET ";
    $query .= "username = '$username', ";
    $query .= "password = '$password' ";
    $query .= "WHERE id = $id ";

    $result = mysqli_query($connection, $query);

    if (!$result) {
        die("Query Failed" . mysqli_error($connection));
    }

}

// HTML FILE
<?php
if(isset($_POST['submit'])){
    updateTable();
}

?>
  
  <form action="update.php" method="post">
    <select name="id" id="">

        <?php
        showAllData();

        ?>

    </select>

    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit" name="submit">Update</button>
</form>
function readAll(){
  // Connect to db
    global $connection;
  // make result global so you can use it in the other file
    global $result;

    $query = "SELECT * FROM USERS";

    $result = mysqli_query($connection, $query);
}


// HTML FILE
<?php
readAll();
while ($row = mysqli_fetch_assoc($result)){
?>

<pre>
    <?php
    print_r($row);
    }
    ?>
</pre>
function create(){
	//If linking to database from external file
    global $connection;

	//Grab form data
    $username = $_POST['username'];
    $password = $_POST['password'];
	
    //Sanatize user input
    $username = mysqli_real_escape_string($connection,$username);
    $password = mysqli_real_escape_string($connection,$password);

	//Query that inserts value into database
    $query = "INSERT INTO users(username,password) ";
    $query .= "VALUES ('$username', '$password')";

    $result = mysqli_query($connection,$query);

    if(!$result){
        die('Query failed' . mysqli_error());
    }
}


//HTML FILE
if (isset($_POST['submit'])) {
    create();

}
<?php
//hostname,username,password,database
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');

if(!$connection){
die('connection failed')
}
load data infile '/home/cloudera/Desktop/shared_local/flipkart_dataset.csv'
into table flipkart_tab
fields terminated by ','
enclosed by '"' LINES
TERMINATED BY '\n' (category_1,category_2,category_3,title,product_rating,selling_price,mrp,seller_name,seller_rating,description,highlights,image_links);
#!/usr/bin/python



-- coding: UTF-8 --


pip install MySQL-python



import MySQLdb, os




try:
    conn = MySQLdb.connect(host='172.17.42.1', user='my_email', passwd='normal', db='database', port=3306)




cur = conn.cursor()
cur.execute('SELECT `id`, `name`, `path`, FROM `doc_file`')

# results
resulsts=cur.fetchall()    id, name, path = r[0], r[1], r[2]

    if path and not os.path.exists(path):
        print 'file not exist: ', id, name, path, flashpath

cur.close()
conn.close()

 



except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])




</pre> 

 

 



                    
 
$pr = \Drupal::entityTypeManager()->getStorage('cfp_payment_request')->load(4221);
$pr->setAmountDedicatedToAp(NULL);
$pr->set('date_of_completion', NULL);
$pr->setState('under_approval');
$pr->save();


$transition_history = $pr->get('transition_history')->getValue();
array_splice($transition_history, -2);
$pr->set('transition_history', $transition_history);
$pr->set('items_approvement_closed', FALSE);
$pr->save();
/** BASE FIELD */  

  $entity_type_id = 'applicant';
  $field_name = 'main_company_address';
  $schema = \Drupal::database()->schema();
  $schema_repository = \Drupal::service('entity.last_installed_schema.repository');
  $key_value = \Drupal::keyValue('entity.storage_schema.sql');
  $key_name = $entity_type_id . '.field_schema_data.' . $field_name;
  $storage_schema = $key_value->get($key_name);
  $storage_schema['applicant']['fields']['main_company_address__cadastral_municipality'] = [
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ];
  $key_value->set($key_name, $storage_schema);
  $schema->addField($entity_type_id, 'main_company_address__cadastral_municipality', $storage_schema['applicant']['fields']['main_company_address__cadastral_municipality']);
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $field_definitions = $entity_field_manager->getBaseFieldDefinitions($entity_type_id);
  $storage = $field_definitions[$field_name]->getFieldStorageDefinition();
  $schema_repository->setLastInstalledFieldStorageDefinition($storage);


/** CONFIG FIELD */


  $entity_type_id = 'basic';
  $field_name = 'cf_settlement';
  $schema = \Drupal::database()->schema();
  $key_value = \Drupal::keyValue('entity.storage_schema.sql');
  $key_name = $entity_type_id . '.field_schema_data.' . $field_name;
  $storage_schema = $key_value->get($key_name);
  $storage_schema['basic__cf_settlement']['fields']['cf_settlement_cadastral_municipality'] = [
    'type' => 'varchar',
    'length' => 255,
    'not null' => FALSE,
  ];
  $key_value->set($key_name, $storage_schema);
  $schema->addField('basic__cf_settlement', 'cf_settlement_cadastral_municipality', $storage_schema['basic__cf_settlement']['fields']['cf_settlement_cadastral_municipality']);
/**
 * Implements hook_theme().
 */
function application_theme() {
  return [
    'application_info' => [
      'variables' => [
        'application_type_label' => NULL,
        'funding_amount' => NULL,
        'application_started' => NULL,
        'contact_person' => NULL,
        'project_leader' => [
          'first_name' => NULL,
          'last_name' => NULL,
          'phone' => NULL,
        ],
        'files' => [],
        'criteria_link' => NULL,
      ],
  ]
}
  $element = [
    '#theme' => 'application_info',
    '#application_type_label' => $application->getApplicationType()->label(),
    '#funding_amount' => $application->getFundingAmountPrinted(),
    '#project_leader' => [
      'first_name' => $advisor_address->given_name,
      'last_name' => $advisor_address->family_name,
      'phone' => $advisor->get('field_ezs_festnetz_telefon')->value,
    ],
    '#files' => [],
    '#criteria_link' => Url::fromRoute('application.application_files', [
      'application_type' => $application->bundle(),
      'file_type' => 'criteria',
    ])->toString(),
//      [
//      '#type' => 'link',
//      '#title' => t('Here'),
//      '#url' => Url::fromRoute('application.application_files', [
//        'application_type' => $application->bundle(),
//        'file_type' => 'criteria',
//      ])
//    ],
    '#cache' => [
      'context' => [
        'user.roles',
        'languages:language_interface',
      ]
    ]
  ];
<div class="application-info-block">
  <h3>{% trans %}Information{% endtrans %}</h3>
  <div><span class="field-label">{{ 'Application program'|trans }} {{ application_type_label }}</span></div>
  {% if funding_amount %}
    <div><span class="field-label">{{ 'Founding Amount'|trans }} {{ funding_amount }}</span></div>
  {% endif %}
  <div><span class="field-label">{{ 'EZS project manager'|trans }}</span> {{ _self.render_person(project_leader) }}</div>
  {% if contact_person %}
    <div><span class="field-label">{{ 'Contact'|trans }}</span> {{ _self.render_person(contact_person) }}</div>
  {% endif %}
  {% if files %}
    <label>{{ 'Files'|trans }}</label>
    <div>{{ files }}</div>
  {% endif %}
  <div>
    {# TODO: Replace for renderable element #}
    {{ '<a target="_blank" href="@url">Here</a> you will find the latest funding criteria'|trans({'@url': criteria_link }) }}
  </div>
</div>

{% macro render_person(person) %}
  {% if person.company %}
    <span>{{ person.company }}</span>
  {% endif %}
  {% if person.salutation %}
    <span>{{ person.salutation }}</span>
  {% endif %}

  <span>{{ person.first_name }} {{ person.last_name }}</span>
  {% if person.street %}
    <span>{{ person.street }}</span>
  {% endif %}
  <span>
    {% if person.postal_code %}
      {{ person.postal_code }}
    {% endif %}
    {% if person.locality %}
      {{ person.locality }}
    {% endif %}
    {% if person.country %}
      {{ person.country }}
    {% endif %}
  </span>
  {% if person.email %}
    <span>{{ person.email }}</span>
  {% endif %}
  <span>{{ person.phone }} </span>
  {% if person.availability %}
    <span>{{ person.availability }}</span>
  {% endif %}
{% endmacro %}
SELECT `data`, COUNT(data)
FROM `santa_log`
WHERE `action` = 'Render cron is running' AND `data` != '[]'
GROUP BY `data`
HAVING COUNT(data) > 1
Grab up to 30% off on our blockchain fork development Services limited time Offer ends in November 25.

For the development of many business sectors, blockchain forks are essential. However, depending on the position, the process requires the use of technology. This is why we're going to look at some of the ways that cryptocurrencies can be developed, including forking existing blockchains to create new ones.

Hivelance, a leading blockchain fork development company, creates a customizable Blockchain Fork Development on various blockchain networks such as Ethereum, Tron, and Binance Smart Chain (BSC), allowing innovators to launch their businesses faster.

visit our site for know more-

https://www.hivelance.com/blockchain-forking
Black Friday sale : Grab up to 30% off on our NFT Token development Services limited time Offer ends in November 25.

Hivelance is a reputable NFT Token development business that works with clients from all over the world and across many industry sectors. We have developed secure, efficient, and revenue-generating NFT development solutions. Hivelance is a leading NFT token development company that offering a  top-notch innovative NFT token development solutions for various businesses across multiple industries. Being the best token development company we create and launch the different types of tokens according to the client’s requirement. We make engaging non-fungible token with transparency, high-end security, and faster delivery.

visit our website for more info-

https://www.hivelance.com/nft-token-development
Grab up to 30% off on our ERC20 Token development Services limited time Offer ends in November 25.

The ERC20 Token contract is the smart contract code logic that executes the fungible token activity. When a contract is put into practise on Ethereum, it can be exchanged for any tokens with a similar value. The ERC20 token standard is used for crypto staking, voting, and the exchange of digital cash as a result. Anyone can generate ERC20 tokens and import them into Ethereum virtual machines.

Hivelance provides ERC20 token development service.  We offer an alot of options as part of our ERC20 Token development package, such as code generation, logo design, an audit of the ERC token contract, deployment to the EVM, ongoing development, security audits at regular intervals, and more. We have supported various ICO projects and helped them scale up their fundraising efforts.

https://www.hivelance.com/erc20-token-development
$post = Post::find(1);
$newPost = $post->replicate();
$newPost->created_at = Carbon::now();
$newPost->save();
SELECT
  teams.team_name AS team_name,
  projects.project_name AS project_name
FROM TABLE teams
INNER JOIN matches
  ON teams.id = matches.team_id
INNER JOIN matches
  ON matches.project_id = projects.id
ORDER BY teams.id;
<?php


namespace Drupal\cfp_payment_request\Form;

use Drupal\cfp_payment_request\Entity\PaymentRequestItem;
use Drupal\cfp_payment_request\Entity\PaymentRequestItemType;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\inline_entity_form\Form\EntityInlineForm;

class PaymentRequestItemInlineForm extends EntityInlineForm {

  const DATA_SOURCE_CLASS = 'pr-data-source';
  const DATA_COPY_NAME = 'data-pr-set';
  const DATA_NAME_STARTS_WITH = 'data-pr-name-starts-with';

  /**
   * {@inheritdoc}
   */
  public function entityForm(array $entity_form, FormStateInterface $form_state) {
    $parent_entity = $form_state->getFormObject()->getEntity();
    if ($parent_entity->getEntityTypeId() === 'cfp_payment_request') {
      $entity_form['#entity']->setParent($parent_entity);
    }
    $entity = $entity_form['#entity'];
    $form_display = $this->getFormDisplay($entity, $entity_form['#form_mode']);

    $this->extraFields($entity_form, $entity, $form_display);

    $entity_form = parent::entityForm($entity_form, $form_state);

    $this->attachValuesCopyBehaviour($entity_form, $parent_entity);

    return $entity_form;
  }

  /**
   * {@inheritdoc}
   */
  public function isTableDragEnabled($element) {
    return FALSE;
  }

  protected function extraFields(&$form, PaymentRequestItem $entity, EntityFormDisplayInterface $form_display) {
    if ($form_display->getComponent('item_support_intensity') && $form_display->getComponent('cost_item_name')) {
      $form['#after_build'][] = '\Drupal\cfp_payment_request\Form\PaymentRequestItemInlineForm::statesToSupportIntensity';
      $form['item_support_intensity'] = [
        '#type' => 'container',
      ];
      $entity = $form['#entity'];
      if (($pr = $entity->getParent()) && ($cfp = $pr->getParent())) {
        $name = 'will_be_build_after';

        /** @var \Drupal\pos_entity_cost_item\AdditionalCostItem $items */
        $items = $cfp->getWrappedAllItems(FALSE, TRUE);

        foreach ($items as $item_id => $item) {
          $form['item_support_intensity'][$item_id] = [
            '#type' => 'container',
            'contents' => [
              '#markup' => '<label>Tételhez kapcsolódó támogatási intenzitás: </label><span class="price">' . $item->getSupportRatio() . '%</span>'
            ],
            '#states' => [
              'visible' => [
                $name => ['value' => $item_id],
              ],
            ],
            '#attributes' => [
              'class' => ['item-support-intensity']
            ],
          ];
        }
      }
    }
    if ($form_display->getComponent('participation_type')) {
      $payment_request = $entity->getParent();

      $cfp = $entity->getCfp();
      $cost_item = $cfp->getCostItemEntities();
      $cost_item = reset($cost_item);
      $own_participation = $cost_item->get('cost_item_participation');
      if ($own_participation_value = $own_participation->value) {
        $own_participation_definition = $cost_item->getFieldDefinition('cost_item_participation');
        $own_participation_label = $own_participation_definition->getSettings()['allowed_values'][$own_participation_value];
      }
      $form['participation_type'] = [
        '#type' => 'markup',
        '#markup' => '<div class="own-participation"><b>Vrsta sopstvenog učešća: </b>' . $own_participation_label . '</div>',
        '#weight' => 10,
      ];
    }

    $payment_request_item_type = PaymentRequestItemType::load($entity->bundle());

    if (!empty($payment_request_item_type->get('documents_helptext')) && $form_display->getComponent('documents_helptext')) {
      $helptext = $payment_request_item_type->get('documents_helptext');
      $form['documents_helptext'] = [
        '#type' => 'container',
        'helptext' => [
          '#type' => 'markup',
          '#markup' => '<div class="documents_helptext">' . $helptext . '</div>',
        ],
      ];
    }


  }

  public static function statesToSupportIntensity($form, FormStateInterface $form_state) {
    if (isset($form['cost_item_name']['widget']['#name']) && isset($form['item_support_intensity'])) {
      $name = $form['cost_item_name']['widget']['#name'];
      foreach ($form['item_support_intensity'] as $item_id => &$element) {
        if (isset($element['#states']['visible'])) {
          $element['#states']['visible'] = [
            '[name="'  . $name . '"]' => ['value' => $item_id],
          ];
        }

      }
    }
//    if (isset($form['cost_item_name']['widget']['#name'])) {
//      $entity = $form['#entity'];
//      if (($pr = $entity->getParent()) && ($cfp = $pr->getParent())) {
//        $name = $form['cost_item_name']['widget']['#name'];
//        /** @var \Drupal\pos_entity_cost_item\AdditionalCostItem $items */
//        $items = $cfp->getWrappedAllItems(FALSE, TRUE);
//
//        foreach ($items as $item_id => $item) {
//
//          $form['item_support_intensity'][$item_id] = [
//            '#type' => 'container',
//            'contents' => [
//              '#markup' => $item->getSupportRatio(),
//            ],
//            '#states' => [
//              'visible' => [
//                '[name="'  . $name . '"]' => ['value' => $item_id],
//              ],
//            ]
//          ];
//        }
//      }
//    }
    return $form;
  }

  /**
   * @param $entity_form
   *
   */
  protected function attachValuesCopyBehaviour(&$entity_form, $parent_entity) {
    if (isset($entity_form['cost_item_name']['widget'])) {
      $entity_form['cost_item_name']['widget']['#attributes']['class'][] = self::DATA_SOURCE_CLASS;
      $entity_form['cost_item_name']['widget']['#after_build'][] = '\Drupal\cfp_payment_request\Form\PaymentRequestItemInlineForm::constructNameStartsWithAfterBuild';
    }
    else {
      return;
    }

    /** @var \Drupal\pos_entity_cfp\Entity\Cfp $cfp */
    $cfp = $parent_entity->getParent();

    $wrapped_items = $cfp->getWrappedAllItems(FALSE, TRUE);
    /**
     * Second parameter is either method for wrapped item, or field name of cost
     *   item.
     *
     * @var $field_mapper
     */
    $field_mapper = [
      'cf_manufacturer' => 'cost_item_manufacturer',
      'cf_unique_item_id' => 'cost_item_identificator',
      'cf_distributor' => 'cost_item_distributor',
      'cf_distributor_vat_number' => 'cost_item_vat_number',
      'cf_distributor_bank_account_num' => 'cost_item_distributor_account',
      'item_support' => 'getSupportValue',
      'item_pay_off' => 'getEligibleCost',
      'item_net_unit' => 'cost_item_neto_price',
      'item_unit_vat' => 'cost_item_vat',
      'item_quantity' => 'cost_item_quantity',
    ];

    foreach ($field_mapper as $value_field_name => $method_or_field) {
      $values = [];
      if (!isset($entity_form[$value_field_name]['widget'][0]['value'])) {
        continue;
      }
      foreach ($wrapped_items as $id => $wrapped_item) {
        if (method_exists($wrapped_item, $method_or_field)) {
//          $wrapped_item->getEligibleCost();
          $values[$id] = $wrapped_item->$method_or_field();
        }
        elseif ($wrapped_item->getCostItem()?->hasField($method_or_field)) {
          $values[$id] = $wrapped_item->getCostItem()->get($method_or_field)->value;
        }
      }
      $entity_form[$value_field_name]['widget'][0]['value']['#attributes'][self::DATA_COPY_NAME] = Json::encode($values);
    }

    $entity_form['#attached']['library'][] = 'cfp_payment_request/pr_item_autopopulate.js';
  }

  /**
   * Constructs name starts with for inline entity form.
   */
  public static function constructNameStartsWithAfterBuild($element, FormStateInterface $form_state) {
    $name_starts_with = explode('['. $element['#field_name'] . ']', $element['#name'])[0];
    $element['#attributes'][self::DATA_NAME_STARTS_WITH] = $name_starts_with;
    return $element;
  }

}
(function (Drupal, once) {
  'use strict';

  const DATA_COPY_NAME = 'data-pr-set';
  const DATA_SOURCE_CLASS = 'pr-data-source';
  const DATA_NAME_STARTS_WITH = 'data-pr-name-starts-with';

  const handleCopy = (context, value, name_starts_with) => {
    context.querySelectorAll(`[name^="${name_starts_with}"][${DATA_COPY_NAME}]`).forEach((element) => {
      const values = JSON.parse(element.getAttribute(DATA_COPY_NAME));
      if (values.hasOwnProperty(value)) {
        setElementValue(element, values[value]);
      }
      else {
        setElementValue(element);
      }
    });
  }

  const setElementValue = (element, value) => {
    if (element.classList.contains('mask-money--apply')) {
      // element.value = value;
      Drupal.behaviors.autoCalculateFormulaBehaviour.setValue(element.getAttribute('name'), value === undefined ? 0 : parseFloat(value));
    }
    else {
      element.value = value === undefined ? '' : value;
      const event = new Event('change');
      element.dispatchEvent(event);
    }
  }

  Drupal.behaviors.copyItemValues = {
    attach: (context) => {
      once('copy-item-values', `.${DATA_SOURCE_CLASS}`,  context).forEach((element) =>  {
        element.addEventListener('change', (event) => {
          handleCopy(context, event.target.value, event.target.getAttribute(DATA_NAME_STARTS_WITH));
        });
      });
    }
  }

})(Drupal, once);
<?php

namespace Drupal\pos_field_address;

use Drupal\Core\Cache\Cache;
use Drupal\Component\Serialization\Yaml;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Messenger\MessengerInterface;

/**
 * Class PosAddressConfigBuilder.
 */
class PosAddressConfigBuilder {

  const COUNTRIES = 'countries.yml';

  /**
   * Cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * Messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * PosAddressConfigBuilder constructor.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   Cache.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   Messenger.
   */
  public function __construct(CacheBackendInterface $cache, MessengerInterface $messenger) {
    $this->cache = $cache;
    $this->messenger = $messenger;
  }

  /**
   * Parse file.
   *
   * @param string $file
   *   Filename.
   *
   * @return bool|mixed
   *   File content.
   */
  private function parseFile($file) {
    $cache_name = 'address__' . str_replace('.yml', '', $file);
    if ($cached = $this->cache->get($cache_name)) {
      return $cached->data;
    }
    $path = realpath(__DIR__) . '/../values/' . $file;
    if (!is_file($path)) {
      return FALSE;
    }
    $content = file_get_contents($path);
    if ($content === FALSE) {
      return $content;
    }
    $content = Yaml::decode($content);
    $this->cache->set($cache_name, $content, Cache::PERMANENT);

    return $content;
  }

  /**
   * Get country codes.
   *
   * @return array
   *   Country codes.
   */
  public function getCountryCodes() {
    return array_keys($this->getCountriesDetailed());
  }

  /**
   * Get country list.
   *
   * @param array $allowed_countries
   *   Allowed countries.
   *
   * @return array|bool|mixed
   *   Countries.
   */
  public function getCountries(array $allowed_countries = []) {
    $countries = $this->getCountriesDetailed();
    foreach ($countries as $country_code => $country) {
      if (empty($allowed_countries) || in_array($country_code, $allowed_countries)) {
        $countries[$country_code] = $country['country'];
      }
      else {
        unset($countries[$country_code]);
      }
    }
    return $countries;
  }

  /**
   * Detailed country data.
   *
   * @return array|bool|mixed
   *   Data.
   */
  public function getCountriesDetailed() {
    $countries_detailed = &drupal_static('address_countries_detailed');
    if (!isset($countries_detailed)) {
      $countries_detailed = $this->parseFile(self::COUNTRIES);
    }
    return $countries_detailed;
  }

  /**
   * Country schema.
   *
   * @param string $country_code
   *   Country code.
   *
   * @return bool|mixed
   *   Schema.
   */
  public function getCountrySchema($country_code, $force_input_schema = FALSE) {
    $countries = $this->getCountriesDetailed();
    if ($countries === FALSE || !array_key_exists($country_code, $countries)) {
      return FALSE;
    }
    if ($force_input_schema) {
      return ['input' => t('Input')];
    }
    return $countries[$country_code]['schema'];
  }

  public function isOriginallyInputCountrySchema($country_code) {
    $schema = $this->getCountrySchema($country_code);
    if ($schema === FALSE) {
      return TRUE;
    }
    return array_key_exists('input', $schema);
  }

  /**
   * Check if country schema exists.
   *
   * @param string $country_code
   *   Country code.
   *
   * @return bool
   *   Does schema exist?
   */
  public function countrySchemaExists($country_code) {
    $countries = $this->getCountriesDetailed();
    if ($countries === FALSE || !array_key_exists($country_code, $countries)) {
      return FALSE;
    }
    return TRUE;
  }

  /**
   * Returns tree for single country.
   */
  public function getTree($country_code) {
    $tree = &drupal_static('address_countries_schema_' . $country_code);
    if (!isset($tree)) {
      $tree = $this->parseFile($country_code . '.yml');
    }
    if ($tree === FALSE) {
      return [];
    }
    return $tree === FALSE ? [] : $tree;
  }

  /**
   * Returns data at depth.
   */
  public function getCurrentDepthData($country_code, $data = [], $filter = FALSE, $filter_cache_context = FALSE, $force_input_schema = FALSE) {
    $microtime = microtime(TRUE);
    $tree = $this->cache->get($filter_cache_context);
    if ($filter !== FALSE && $filter_cache_context !== FALSE && $tree) {
      $tree = $tree->data;
    }
    else {
      $tree = $this->getTree($country_code);
      if ($filter !== FALSE) {
        $this->filterTree($tree, $filter, $country_code);
        if ($filter_cache_context !== FALSE) {
          $this->cache->set($filter_cache_context, $tree);
        }
      }
    }
    $schema = $this->getCountrySchema($country_code, $force_input_schema);
    if ($schema === FALSE) {
      return FALSE;
    }

    $return_data = [];
    $current_depth_data = $tree;
    $return_data['country'] = $tree;
    if (empty($schema)) {
      return [];
    }
    elseif (key($schema) == 'input') {
      return $return_data['country'];
    }
    do {
      if (current($data) !== FALSE) {
        $current_code = current($data);
      }
      else {
        $current_code = key($current_depth_data[key($schema)]);
      }
      $current_depth_data = $current_depth_data[key($schema)];

      if (!array_key_exists($current_code, $current_depth_data)) {
        $current_code = key($current_depth_data);
      }

      $return_data[key($schema)] = $current_depth_data[$current_code];
      $return_data[key($schema)]['code'] = $current_code;
      $current_depth_data = $current_depth_data[$current_code];
      if ((microtime(TRUE) - $microtime) > 2) {
        $this->messenger->addMessage('Report this problem to administrator');
        break;
      }
      next($data);
    } while (next($schema) !== FALSE);

    return $return_data;
  }

  /**
   * Filters tree.
   */
  private function filterTree(&$tree, $filter, $country_code) {
    if (!is_array($filter)) {
      return $tree;
    }
    $schema = $this->getCountrySchema($country_code);

    foreach ($filter as $key => $value) {
      if ($value[0] !== $country_code) {
        unset($filter[$key]);
      }
    }

    foreach ($schema as $schema_key => $label) {
      $this->unsetUnexisting($tree, $filter, $schema, $schema_key);
    }
  }

  /**
   * Deletes locations not in filter.
   */
  private function unsetUnexisting(&$tree, $filter, $schema, $schema_key) {
    $tree_copy = $tree;
    $filter_key = 1;
    reset($schema);
    $this->goToCurrentDepth($tree[key($schema)], $filter, $schema, $filter_key, $schema_key);
    return $tree_copy;
  }

  /**
   * Go through the depth.
   *
   * @param array $tree
   *   Tree.
   * @param mixed $filter
   *   Filter.
   * @param array $schema
   *   Schema.
   * @param mixed $filter_key
   *   Filter key.
   * @param mixed $schema_key
   *   Schema key.
   */
  private function goToCurrentDepth(array &$tree, &$filter, array &$schema, &$filter_key, $schema_key) {
    if (key($schema) === $schema_key) {
      foreach ($tree as $key => $value) {
        $found = FALSE;
        foreach ($filter as $filter_code) {
          if ($filter_code[$filter_key] == $key) {
            $found = TRUE;
            break;
          }
        }
        if (!$found) {
          unset($tree[$key]);
        }
      }
    }
    else {
      next($schema);
      $current_key = key($schema);
      $filter_key++;
      $current_filter = $filter_key;
      foreach ($tree as $code_key => $code) {
        $this->goToCurrentDepth($tree[$code_key][$current_key], $filter, $schema, $filter_key, $schema_key);
        $filter_key = $current_filter;
        reset($schema);
        while (key($schema) !== $current_key) {
          next($schema);
        }
      }
    }
  }

  /**
   * Get select schema.
   *
   * @param string $country_code
   *   Country code.
   *
   * @return array
   *   Schema.
   */
  public function getSelectSchema($country_code) {
    $tree = $this->getTree($country_code);
    $schema = $this->getCountrySchema($country_code);
    $values = [];
    $codes = [];
    end($schema);
    $this->getSubnames($tree, key($schema), $values, $codes, TRUE, $country_code);
    return array_combine($codes, $values);
  }

  /**
   * Get subnames.
   *
   * @param array $current_tree
   *   Current tree.
   * @param mixed $last_schema_key
   *   Last schema key.
   * @param array $values
   *   Values.
   * @param array $codes
   *   Codes.
   * @param mixed $first
   *   First.
   * @param string $country_code
   *   Country code.
   *
   * @return array
   *   Subnames.
   */
  private function getSubnames(array $current_tree, $last_schema_key, array &$values, array &$codes, $first, $country_code = '') {
    $keys = array_keys($current_tree);
    if (!array_key_exists($country_code, $this->getCountriesDetailed())) {
      $country_name = '';
    }
    else {
      $country_name = $this->getCountriesDetailed()[$country_code]['country'];
    }

    $schema_key = FALSE;
    foreach ($keys as $key) {
      if ($key != 'name') {
        $schema_key = $key;
      }
    }
    $subnames = [];
    if (empty($current_tree)) {
      return [];
    }
    foreach ($current_tree[$schema_key] as $code => $tree) {
      if ($first) {
        $subnames = $this->getSubnames($tree, $last_schema_key, $values, $codes, FALSE);
        foreach ($subnames as $subname) {
          $values[] = $country_name . '->' . $tree['name'] . '->' . $subname['name'];
          $codes[] = $country_code . '{||}' . $code . '{||}' . $subname['code'];
        }
      }
      elseif ($last_schema_key === $schema_key) {
        $subnames[] = ['name' => $tree['name'], 'code' => $code];
      }
      else {
        $return_value = $this->getSubnames($tree, $last_schema_key, $values, $codes, FALSE);
        foreach ($return_value as $subname) {
          $subnames[] = [
            'name' => $tree['name'] . '->' . $subname['name'],
            'code' => $code . '{||}' . $subname['code'],
          ];
        }
      }
    }
    if (!$first) {
      return $subnames;
    }
  }

  /**
   * Get all options for country schema element.
   *
   * @param string $country_code
   *   Country code.
   * @param mixed $schema_key
   *   Schema key.
   *
   * @return array
   *   Options.
   */
  public function getAllOptionsForCountrySchemaElement($country_code, $schema_key) {
    $tree = $this->getTree($country_code);
    $country_schema = $this->getCountrySchema($country_code);
    $values = [];
    if (!empty($country_schema)) {
      $this->getAllValuesToGivenDepth($tree[key($country_schema)], $country_schema, $schema_key, $values);
    }
    return $values;
  }

  /**
   * Get all values to given depth.
   *
   * @param array $tree
   *   Tree.
   * @param array $country_schema
   *   Schema.
   * @param mixed $schema_key
   *   Schema key.
   * @param array $values
   *   Values.
   * @param array $current_depth_value
   *   Current value.
   */
  public function getAllValuesToGivenDepth(array $tree, array &$country_schema, $schema_key, array &$values, array $current_depth_value = []) {
    $current_key_schema = key($country_schema);
    next($country_schema);
    foreach ($tree as $value => $sub_tree) {
      $current_depth_value[$current_key_schema] = (string) $value;
      if ($schema_key === $current_key_schema) {
        $values[] = [
          'name' => $sub_tree['name'],
          'value' => $current_depth_value,
        ];
      }
      else {
        $this->getAllValuesToGivenDepth($sub_tree[key($country_schema)], $country_schema, $schema_key, $values, $current_depth_value);
      }
    }
    prev($country_schema);
  }

  /**
   * Validates if data is valid.
   */
  public function validateValue($country_code, $data) {
    $tree = $this->getTree($country_code);
    $schema = $this->getCountrySchema($country_code);
    if (key($schema) === 'input' && is_string($data)) {
      return TRUE;
    }
    if (count($data) == 0 && !empty($tree)) {
      return TRUE;
    }
    elseif (count($data) == 0 && empty($tree)) {
      return FALSE;
    }
    foreach ($schema as $schema_key => $label) {
      if (array_key_exists(current($data), $tree[$schema_key])) {
        $tree = $tree[$schema_key][current($data)];
      }
      else {
        return FALSE;
      }
      if (next($data) === FALSE) {
        break;
      }
    }
    return TRUE;
  }

  /**
   * Returns all schema keys that exists.
   */
  public function getAllSchemaKeys() {
    $detailed_countries = $this->getCountriesDetailed();
    $all_schema_keys = [];
    foreach ($detailed_countries as $detailed_country) {
      foreach ($detailed_country['schema'] as $key => $label) {
        if (!in_array($key, $all_schema_keys)) {
          $all_schema_keys[] = $key;
        }
      }
    }
    return $all_schema_keys;
  }

}
/**
 * @file
 * Remove button for the Address field.
 */

(function ($, Drupal) {
  'use strict';

  Drupal.behaviors.addressFilterBehaviour = {
    attach: function (context) {
      $('.address-filer-country').once('address-filter-behaviour').on('change', function () {
        let countryElement = $(this);
        $.get('/pos_field_address/country-schema?country=' + $(this).val(), function (data) {
          let element = $(countryElement.data('schema-selector'));
          element.empty();
          $.each(data, function (key,value) {
            element.append($('<option></option>')
              .attr('value', key).text(value));
          });
          element.trigger('change');
        }, 'json');
        $.get('/pos_field_address/schema-options?country=' + $(this).val() + '&schema=' + 'settlement', function (data) {
          let newElement = $(countryElement.data('value-selector'));
          newElement.empty();
          $.each(data, function (key, value) {
            newElement.append($('<option></option>')
              .attr('value', key).text(value));
          });
          newElement.trigger('change');
        })
      });
      $('.address-filter-schema').once('address-filter-behaviour').on('change', function () {
        let schemaElement = $(this);
        let countryCode = $(schemaElement.data('country-selector')).val();
        $.get('/pos_field_address/schema-options?country=' + countryCode + '&schema=' + schemaElement.val(), function (data) {
          let element = $(schemaElement.data('value-selector'));
          element.empty();
          $.each(data, function (key,value) {
            element.append($('<option></option>')
              .attr('value', key).text(value));
          });
        }, 'json');
      });
    }
  };

})(jQuery, Drupal);
<?php

namespace Drupal\pos_field_address\Plugin\views\filter;

use Drupal\Core\Database\Connection;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Drupal\pos_field_address\PosAddressConfigBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a custom filter for filtering by addresses.
 *
 * @ingroup views_filter_handlers
 * @ViewsFilter("pos_address_advance_filter")
 */
class PosAddressAdvanceFilter extends FilterPluginBase {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Config builder.
   *
   * @var \Drupal\pos_field_address\PosAddressConfigBuilder
   */
  protected $configBuilder;

  /**
   * {@inheritdoc}
   */
  public $operator = 'LIKE';

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection, PosAddressConfigBuilder $config_builder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->connection = $connection;
    $this->configBuilder = $config_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('database'),
      $container->get('pos_field_address.config_builder')
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['operator'] = ['default' => 'LIKE'];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildExposedForm(&$form, FormStateInterface $form_state) {
    $identifier = $this->options['expose']['identifier'];
    $exposed_input = $this->view->getExposedInput();
    $form[$identifier] = [
      '#type' => 'fieldset',
      '#title' => $this->options['expose']['label'],
      '#attached' => [
        'library' => [
          'pos_field_address/view-exposed-filter',
        ],
      ],
    ];
    $element = &$form[$identifier];
    // Define classes.
    $country_class = str_replace('_', '-', $identifier) . '-country';
    $schema_class = str_replace('_', '-', $identifier) . '-schema';
    $value_class = str_replace('_', '-', $identifier) . '-value';

    // Country element.
    $countries = $this->configBuilder->getCountries();
    $country_code = isset($exposed_input[$identifier . '_country']) ? $exposed_input[$identifier . '_country'] : key($countries);
    $element[$identifier . '_country'] = [
      '#type' => 'select',
      '#title' => 'Entitet',
      '#options' => $this->configBuilder->getCountries(),
      '#attributes' => [
        'class' => ['address-filer-country', $country_class],
        'data-schema-selector' => '.' . $schema_class,
        'data-value-selector' => '.' . $value_class,
      ],
      '#default_value' => $country_code,
    ];
    // Country schema element.
    $country_schema = $this->configBuilder->getCountrySchema($country_code);
    $country_schema_key = isset($exposed_input[$identifier . '_country_schema']) ? $exposed_input[$identifier . '_country_schema'] : key($country_schema);
//    $element[$identifier . '_country_schema'] = [
//      '#type' => 'select',
//      '#title' => $this->t('Search by'),
//      '#options' => $country_schema,
//      '#attributes' => [
//        'class' => ['address-filter-schema', $schema_class],
//        'data-country-selector' => '.' . $country_class,
//        'data-value-selector' => '.' . $value_class,
//      ],
//      '#default_value' => $country_schema_key,
//    ];
    // Value element.
    $values = $this->configBuilder->getAllOptionsForCountrySchemaElement($country_code, $country_schema_key);
    $options = ['' => $this->t('- None -')];
    foreach ($values as $value) {
      $serialized = serialize($value['value']);
      $options[str_replace('}', '', substr($serialized, strpos($serialized, '{') + 1))] = $value['name'];
    }
    $default_value = isset($exposed_input[$identifier]) ? $exposed_input[$identifier] : NULL;
    $element[$identifier] = [
      '#title' => $this->options['expose']['label'],
      '#type' => 'select',
      '#attributes' => [
        'class' => [$value_class, 'address-filter-city'],
        'data-schema-selector' => '.' . $schema_class,
      ],
      '#options' => $options,
      '#default_value' => $default_value,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    if (!empty($this->value) && !empty(reset($this->value))) {
      $this->ensureMyTable();
      $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", '%' . $this->connection->escapeLike(reset($this->value)) . '%', $this->operator);
    }
    else if (!empty($this->view->getExposedInput()) && $this->view->getExposedInput()['main_company_address_country'] === 'BD') {
      $no_settlement = 's:0:""';
      $this->query->addWhere($this->options['group'], "$this->tableAlias.$this->realField", '%' . $this->connection->escapeLike($no_settlement) . '%', $this->operator);
    }
  }

}
<?php

/**
 * @file
 * Contains cfp_payment_request.module.
 */

use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\cfp_payment_request\Entity\PaymentRequestType;
use Drupal\pos_entity_cfp\Entity\CfpType;
use Drupal\Core\Entity\EntityTypeInterface;

module_load_include('inc', 'cfp_payment_request', 'cfp_payment_request.extra_fields');
module_load_include('inc', 'cfp_payment_request', 'cfp_payment_request.tokens');
\Drupal::moduleHandler()->loadInclude('cfp_payment_request', 'inc', 'cfp_payment_request.validation');
require_once realpath(__DIR__) . '/cfp_payment_request.currency_conv.inc';

/**
 * Implements hook_help().
 */
function cfp_payment_request_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the cfp_payment_request module.
    case 'help.page.cfp_payment_request':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Payment Request for CFP') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_mail().
 */
function cfp_payment_request_mail($key, &$message, $params) {
  switch ($key) {
    case 'pos_payment_request_mail':
      $mail_sender = \Drupal::config('system.site')->get('mail');
      $message['headers']['From'] = $mail_sender;
      $message['headers']['Sender'] = $mail_sender;
      $message['headers']['Return-Path'] = $mail_sender;
      $message['headers']['Content-Type'] = 'text/html';
      $message['from'] = $mail_sender;
      /** @var \Drupal\Core\Utility\Token $token */
      $token = \Drupal::service('token');
      $token_data = [
        'cfp_payment_request' => $params['entity'],
      ];
      $message['subject'] = $token->replace($params['title'], $token_data);
      $message['body'][] = $token->replace($params['message'], $token_data);

      $email_log = \Drupal::entityTypeManager()
        ->getStorage('pos_entity_email_logs')
        ->create([
          'title' => $message['subject'],
          'body' => isset($message['body'][0]) ? $message['body'][0] : '',
          'cfp' => $params['entity']->get('parent')->target_id,
        ]);
      $email_log->save();
      break;
  }
}

/**
 * Implements hook_theme().
 */
function cfp_payment_request_theme() {
  $theme = [];
  $theme['cfp_payment_request'] = [
    'render element' => 'elements',
    'file' => 'cfp_payment_request.page.inc',
    'template' => 'cfp_payment_request',
  ];
  $theme['cfp_payment_request_content_add_list'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'cfp_payment_request.page.inc',
  ];
  $theme['cfp_payment_request_item'] = [
    'render element' => 'elements',
    'file' => 'cfp_payment_request_item.page.inc',
    'template' => 'cfp_payment_request_item',
  ];
  $theme['cfp_payment_request_item_content_add_list'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'cfp_payment_request_item.page.inc',
  ];
  $theme['cfp_payment_request_checklist'] = [
    'render element' => 'elements',
    'file' => 'cfp_payment_request_checklist.page.inc',
  ];
  $theme['pr_invoice'] = [
    'render element' => 'elements',
  ];
  return $theme;
}

/**
 * Prepares variables for invoice templates.
 *
 * Default template: pr-invoice.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the invoice information and any
 *     fields attached to the entity.
 *   - attributes: HTML attributes for the containing element.
 */
function template_preprocess_pr_invoice(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function cfp_payment_request_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'cfp_payment_request') {
    $pr_type = \Drupal::entityTypeManager()->getStorage('cfp_payment_request_type')->load($bundle);
    if ($pr_type) {
      if (isset($fields['items'])) {
        $settings = $fields['items']->getSettings();
        $settings['handler_settings']['target_bundles'] = [$pr_type->get('payment_request_item_type') => $pr_type->get('payment_request_item_type')];
        $fields['items']->setSettings($settings);
      }
      if (isset($fields['invoices'])) {
        $settings = $fields['invoices']->getSettings();
        $settings['handler_settings']['target_bundles'] = [$pr_type->get('payment_request_invoice_type') => $pr_type->get('payment_request_invoice_type')];
        $fields['invoices']->setSettings($settings);
      }
    }
  }
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function cfp_payment_request_theme_suggestions_cfp_payment_request(array $variables) {
  $entity = $variables['elements']['#cfp_payment_request'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  return build_template_suggestions($entity, $sanitized_view_mode);
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function cfp_payment_request_theme_suggestions_cfp_payment_request_item(array $variables) {
  $entity = $variables['elements']['#cfp_payment_request_item'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  return build_template_suggestions($entity, $sanitized_view_mode);
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function cfp_payment_request_theme_suggestions_cfp_payment_request_checklist(array $variables) {
  $entity = $variables['elements']['#cfp_payment_request_checklist'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  return build_template_suggestions($entity, $sanitized_view_mode);
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function cfp_payment_request_theme_suggestions_pr_invoice(array $variables) {
  $entity = $variables['elements']['#pr_invoice'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  return build_template_suggestions($entity, $sanitized_view_mode);
}

/**
 * Adds template suggestions.
 */
function build_template_suggestions($entity, $sanitized_view_mode) {
  $suggestions = [];
  $suggestions[] = $entity->getEntityTypeId() . '__' . $sanitized_view_mode;
  $suggestions[] = $entity->getEntityTypeId() . '__' . $entity->bundle();
  $suggestions[] = $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = $entity->getEntityTypeId() . '__' . $entity->id();
  $suggestions[] = $entity->getEntityTypeId() . '__' . $entity->id() . '__' . $sanitized_view_mode;
  return $suggestions;
}

/**
 * Implements hook_file_download().
 */
function cfp_payment_request_file_download($uri) {
  if (str_starts_with($uri, 'temporary://temporary_excel_exports/')) {
    return [
      'Content-disposition' => 'attachment; filename="' . basename($uri) . '"',
    ];
  }

}

/**
 * Implements hook_add_more_entities_to_field_access_alter().
 */
function cfp_payment_request_add_more_entities_to_field_access_alter(&$access, FieldItemListInterface $items, FieldDefinitionInterface $field_definition) {
  // @todo review this logic?
  $target_type = $field_definition->getSetting('target_type');
  if ($target_type === 'cfp_payment_request') {
    // TODO: Delete comment.
    /** @var \Drupal\pos_entity_cfp\Entity\Cfp $parent_entity */
//    $parent_entity = $items->getEntity();
//    if ($parent_entity->getState()->getId() != 'project_implementation') {
//      return FALSE;
//    }
//    $current_user = \Drupal::currentUser();
//    $access = $access ?: $current_user->id() == $parent_entity->getOwnerId();
//    if ($access) {
//      /** @var \Drupal\pos_entity_cfp\Entity\CfpType $cfp_type */
//      $cfp_type = CfpType::load($parent_entity->bundle());
//      /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestType $payment_request_type */
//      $payment_request_type = PaymentRequestType::load($cfp_type->getPaymentRequestBundle());
//      if (!$payment_request_type) {
//        $access = FALSE;
//        return;
//      }
//      if ($current_user->hasPermission('administer payment request')) {
//        $entity_limit = $payment_request_type->get('entity_limit_for_admin');
//      } else {
//        $entity_limit = $payment_request_type->get('entity_limit_for_applicant');
//      }
//      if ($entity_limit !== -1  && $items->count() >= $entity_limit) {
//        $access = FALSE;
//      }
//    }
  }
}

/**
 * Implements hook_add_more_entity_alter().
 */
function cfp_payment_request_add_more_entity_alter(FieldableEntityInterface $entity, FieldableEntityInterface $parent, FieldDefinitionInterface $field_definition) {
  if ($entity->getEntityTypeId() === 'cfp_payment_request') {
    // @todo Probably move this logic to presave.
    $entity->set('parent', $parent);
    $entity->setOwnerId($parent->getOwnerId());
  }
}

/**
 * Implements hook_options_list_alter().
 */
function cfp_payment_request_options_list_alter(array &$options, array $context) {
  if ($context['fieldDefinition']->getName() === 'pr_type' && $context['fieldDefinition']->getTargetEntityTypeId() === 'cfp_payment_request') {
    /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestType $pr_type */
    $pr_type = $context['entity']->get('type')->entity;
    $allowed_options = $pr_type->get('allowed_pr_types') + ['_none' => '_none'];
    if (!empty($allowed_options)) {
      foreach ($options as $option_key => $option) {
        if (!in_array($option_key, $allowed_options)) {
          unset($options[$option_key]);
        }
      }
    }
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function cfp_payment_request_preprocess_field__entity_reference(&$variables) {
  if ($variables['field_name'] === 'payment_request' && $variables['entity_type'] === 'cfp') {
    foreach ($variables['items'] as $item) {
      $pr = $item['content']['#cfp_payment_request'];
      if ($pr->getState() === 'reopened') {
        $item['attributes']->setAttribute('style', 'border: 3px solid #ff0000');
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function cfp_payment_request_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#id'] === 'views-exposed-form-payment-requests-page-1') {
    $workflow_manager = \Drupal::service('plugin.manager.workflow');
    $workflow = $workflow_manager->createInstance('payment_request');
    $states = $workflow->getStates();
    $states = array_map(function ($state) {
      return $state->getLabel();
    }, $states);

    $form['state'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $states,
    ];
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function cfp_payment_request_form_cfp_payment_request_pr_2022_01_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['cf_customs_documents']['#states'] = [
    'visible' => [
      ':input[name="pr_type"]' => ['value' => 'closing']
    ]
  ];
  $form['cf_eur1_form']['#states'] = [
    'visible' => [
      ':input[name="pr_type"]' => ['value' => 'closing']
    ]
  ];

  // @TODO: Ovo treba ispraviti. Ne verujem da ovo može tu da bude.
  // Payment request item conditional fields.
  $conditional_fields = [
    'cf_final_account',
    'cf_confirm_final_payment',
    'cf_purchase_contract',
    'cf_protocol_record',
    'cf_driving_license',
    'cf_pictures',
  ];
  foreach ($conditional_fields as $conditional_field) {
    if (isset($form[$conditional_field])) {
      $form[$conditional_field]['#states'] = [
        'visible' => [
          ':input[name="pr_type"]' => ['value' => 'closing']
        ]
      ];
    }
  }
}
<?php

/**
 * Implements hook_entity_validation_ENTITY_TYPE_alter().
 */
function cfp_payment_request_entity_validation_cfp_payment_request_alter($entity_typed_data, $validation_context) {
  $entity_typed_data->getDataDefinition()->addConstraint('GlobalPaymentRequestConstraint', []);
  if ($validation_context === 'cfp_payment_request.pr_2022_01') {
    $required_fields = [
      'cf_promissory_notes',
      'cf_no_debts_confirmation',
      'cf_technical_report_start',
      'cf_technical_report_end',
      'cf_project_description',
      'items',
    ];

    /** @var Drupal\Core\Entity\EntityInterface $entity */
    $entity = $entity_typed_data->getEntity();

    if ($entity->get('pr_type')->value === 'closing') {
      array_push($required_fields, 'cf_eur1_form', 'cf_customs_documents');
    }

    /** @var \Drupal\Core\Field\FieldDefinition[] $field_definitions */
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($required_fields as $required_field) {
      $field_definitions[$required_field]->setRequired(TRUE);
    }
  }
}

/**
 * Implements hook_entity_validation_ENTITY_TYPE_rollback_alter().
 */
function cfp_payment_request_entity_validation_cfp_payment_request_item_rollback_alter($entity_typed_data, $validation_context, $rollback_info) {
  if ($validation_context === 'cfp_payment_request.pr_2022_01') {
    $required_fields = [
      'cost_item_name',
      'cf_manufacturer',
      'cf_distributor',
      'cf_unique_item_id',
      'cf_distributor_bank_account_num',
      'cf_distributor_vat_number',
      'item_quantity',
    ];

    $decimal_fields = [
      'item_net_unit',
      'item_unit_vat',
      'item_pay_off',
      'item_support',
    ];

    /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestItem $entity */
    $entity = $entity_typed_data->getEntity();
    $payment_request = $entity->getParent();
    if ($payment_request->get('pr_type')->value === 'closing') {
      array_push($required_fields,
        'cf_final_account',
        'cf_confirm_final_payment',
        'cf_purchase_contract',
        'cf_protocol_record',
        'cf_driving_license',
        'cf_pictures',
      );
    }
    /** @var \Drupal\Core\Field\FieldDefinition[] $field_definitions */
    $field_definitions = $entity->getFieldDefinitions();
    foreach ($required_fields as $required_field) {
      $field_definitions[$required_field]->setRequired(TRUE);
    }
    foreach ($decimal_fields as $decimal_field) {
      if ($entity->get($decimal_field)->value === "0.00") {
        $entity->set($decimal_field, NULL);
      }
      $field_definitions[$decimal_field]->setRequired(TRUE);
    }
  }
}
<?php

namespace Drupal\cfp_payment_request\Entity;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\pos_core\PosFieldVariables;
use Drupal\pos_entity_autocalculate\AutoCalculateFormula;
use Drupal\pos_entity_autocalculate\Entity\AutocalculateEntityTrait;
use Drupal\pos_entity_cost_item\AdditionalCostItem;
use Drupal\pos_entity_cost_item\Entity\CostItemAcceptableInterface;
use Drupal\pos_parent_entity\Entity\ChildEntityTrait;
use Drupal\user\UserInterface;

/**
 * Defines the Payment request item entity.
 *
 * @ingroup cfp_payment_request
 *
 * @ContentEntityType(
 *   id = "cfp_payment_request_item",
 *   label = @Translation("Payment request item"),
 *   bundle_label = @Translation("Payment request item type"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\cfp_payment_request\PaymentRequestItemListBuilder",
 *     "views_data" = "Drupal\cfp_payment_request\Entity\PaymentRequestItemViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\cfp_payment_request\Form\PaymentRequestItemForm",
 *       "add" = "Drupal\cfp_payment_request\Form\PaymentRequestItemForm",
 *       "edit" = "Drupal\cfp_payment_request\Form\PaymentRequestItemForm",
 *       "delete" = "Drupal\cfp_payment_request\Form\PaymentRequestItemDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\cfp_payment_request\PaymentRequestItemHtmlRouteProvider",
 *     },
 *     "access" = "Drupal\cfp_payment_request\PaymentRequestItemAccessControlHandler",
 *     "inline_form" = "\Drupal\cfp_payment_request\Form\PaymentRequestItemInlineForm",
 *   },
 *   base_table = "cfp_payment_request_item",
 *   translatable = FALSE,
 *   admin_permission = "administer payment request item entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "bundle" = "type",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "published" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/cfp_payment_request_item/{cfp_payment_request_item}",
 *     "add-page" = "/admin/structure/cfp_payment_request_item/add",
 *     "add-form" = "/admin/structure/cfp_payment_request_item/add/{cfp_payment_request_item_type}",
 *     "edit-form" = "/admin/structure/cfp_payment_request_item/{cfp_payment_request_item}/edit",
 *     "delete-form" = "/admin/structure/cfp_payment_request_item/{cfp_payment_request_item}/delete",
 *     "collection" = "/admin/structure/cfp_payment_request_item",
 *   },
 *   bundle_entity_type = "cfp_payment_request_item_type",
 *   field_ui_base_route = "entity.cfp_payment_request_item_type.edit_form"
 * )
 */
class PaymentRequestItem extends ContentEntityBase implements PaymentRequestItemInterface {

  use EntityChangedTrait;
  use EntityPublishedTrait;
  use ChildEntityTrait;
  use AutocalculateEntityTrait {
    preSave as autoCalculatePreSave;
    addFormulas as autoCalculateAddFormulas;
  }

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    if ($this->getPRIType()->arePricesInCurrencies()) {
      if (($currency = $this->getCurrency()) && ($currency_date = $this->getCurrencyDate())) {
        if ($exchange_rate = self::getExchangeRate($currency, $currency_date)) {
          $this->populateValuesWithExchange($exchange_rate);
        }
      }
      $this->autoCalculatePreSave($storage);
    } else {
      $this->autoCalculatePreSave($storage);
    }
    if ($this->get('accepted')->value !== 'accepted_with_new_value') {
      $this->set('new_item_pay_off', NULL)
        ->set('new_item_support', NULL);
    }
  }

  /**
   * {@inheritDoc}
   * Some computed field directly depend on another field, and we need to access
   *   it right after.
   */
  public function onChange($name) {
    parent::onChange($name);
    $field_influence_connection = [
      'accepted' => ['item_pay_off_computed', 'item_support_computed'],
      'item_pay_off' => ['item_pay_off_computed'],
      'new_item_pay_off' => ['item_pay_off_computed'],
      'new_item_support' => ['item_support_computed'],
      'item_support' => ['item_support_computed'],
    ];
    foreach ($field_influence_connection[$name] ?? [] as $field_influence) {
      $this->get($field_influence)->forceRecomputeValue();
    }
  }

  /**
   * @param $exchange_value
   */
  public function populateValuesWithExchange($exchange_value) {
    $exchange_value = (float) $exchange_value;
    foreach ($this->getFieldDefinitions() as $field_definition) {
      if (strpos($field_definition->getName(), '_currency_value') !== FALSE) {
        $value = $this->get($field_definition->getName())->value;
        if ($value) {
          $forint_field_name = str_replace('_currency_value', '', $field_definition->getName());
          $this->set($forint_field_name, bcmul($value, $exchange_value));
        } elseif(is_numeric($value)) {
          $forint_field_name = str_replace('_currency_value', '', $field_definition->getName());
          $this->set($forint_field_name, 0);
        } else {
          $this->set($forint_field_name, NULL);
        }
      }
    }
  }

  public static function getExchangeRate($currency, $currency_date) {
    if ($currency === 'HUF') {
      return 1;
    }
    $exchange_rate = str_replace(',', '.', _get_mnb_currency_value($currency, $currency_date));
    return is_numeric($exchange_rate) ? $exchange_rate : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('name')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    return $this->getName();
  }

  /**
   * Payment request item type.
   *
   * @return \Drupal\cfp_payment_request\Entity\PaymentRequestItemType
   */
  public function getPRIType() {
    return PaymentRequestItemType::load($this->bundle());
  }

  /**
   * @return mixed
   */
  public function getCurrency() {
    $currency = $this->get('currency')->value;
    return $currency;
  }

  /**
   *
   */
  public function getCurrencyDate() {
    if (!$this->get('currency_date')->isEmpty()) {
      return $this->get('currency_date')->date->format(CURRENCY_DATE_FORMAT);
    }
  }

  /**
   * Cost item identifier.
   *
   * @return string
   *   Identifier of item.
   */
  public function getCostItemIdentifier() {
    return $this->get('cost_item_name')->value;
  }

  /**
   * Returns accepted state.
   *
   * @return string
   *   Accepted state.
   */
  public function getAcceptedState() {
    return $this->get('accepted')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function addFormulas() {
    $this->autoCalculateAddFormulas();
    if ($this->getPRIType()->arePricesInCurrencies()) {
      // Currency values.
      $this->addAutoCalculateFormula('item_net_amount_currency_value', AutoCalculateFormula::create()
        ->addFieldWithOperation('item_net_unit_currency_value')
        ->multiplyField('item_quantity'));

      $this->addAutoCalculateFormula('item_vat_currency_value', AutoCalculateFormula::create()
        ->addFieldWithOperation('item_unit_vat_currency_value')
        ->multiplyField('item_quantity')
      );

      $this->addAutoCalculateFormula('item_bruto_currency_value', AutoCalculateFormula::create()
        ->addFieldWithOperation('item_net_amount_currency_value')
        ->addField('item_vat_currency_value')
      );

    }

    // Forint values.
    $this->addAutoCalculateFormula('item_net_amount', AutoCalculateFormula::create()
      ->addFieldWithOperation('item_net_unit')
      ->multiplyField('item_quantity'));

    $this->addAutoCalculateFormula('item_vat', AutoCalculateFormula::create()
      ->addFieldWithOperation('item_unit_vat')
      ->multiplyField('item_quantity')
    );

    $this->addAutoCalculateFormula('item_bruto', AutoCalculateFormula::create()
      ->addFieldWithOperation('item_net_amount')
      ->addField('item_vat')
    );

    $this->addAutoCalculateFormula('item_support_percentage', AutoCalculateFormula::create()
      ->addField('item_support')
      ->divideField('item_pay_off')
      ->addNumberWithOperation(100, AutoCalculateFormula::MULTIPLY)
    );

    $this->addAutoCalculateFormula('item_own_source', AutoCalculateFormula::create()
      ->addFieldWithOperation('item_pay_off')
      ->subtractField('item_support'));

    $this->addAutoCalculateFormula('item_bruto_unit', AutoCalculateFormula::create()
      ->addFieldWithOperation('item_bruto')
      ->divideField('item_quantity')
    );
  }

  /**
   * {@inheritDoc}
   */
  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
    $fields = [];
    if ($bundle) {
      /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestItemType $pri_type */
      $pri_type = \Drupal::entityTypeManager()
        ->getStorage('cfp_payment_request_item_type')
        ->load($bundle);
      if ($pri_type) {
        $prices_in_currencies = $pri_type->arePricesInCurrencies();
        foreach ($base_field_definitions as $field_name => $base_field_definition) {
          if (strpos($field_name, '_currency_value') !== FALSE) {
            if (!$prices_in_currencies) {
              $fields[$field_name] = clone $base_field_definition;
              $fields[$field_name]->setDisplayConfigurable('form', FALSE)
                ->setDisplayConfigurable('view', FALSE);
            }
            else {
              $basic_field_name = str_replace('_currency_value', '', $field_name);
              $fields[$basic_field_name] = clone $base_field_definitions[$basic_field_name];
              $fields[$basic_field_name]->setDisplayConfigurable('form', FALSE);
            }
          }
        }
      }
    }

    return $fields;

  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    // Add the published field.
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Payment request item entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Tétel sorszáma'))
      ->setDescription(t('The name of the Payment request item entity.'))
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayConfigurable('view', TRUE);

    $fields['cost_item_name'] = BaseFieldDefinition::create('list_string')
      ->setLabel('Stavka na koju se isplata odnosi')
      ->setSetting('allowed_values_function', '\Drupal\cfp_payment_request\Entity\PaymentRequestItem::itemNames')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
    // NUMERIC FIELDS.
    $numeric_fields = [
      'item_net_unit' => 'Neto jedinična cijena',
      'item_unit_vat' => 'PDV po neto jediničnoj cijeni',
      'item_bruto_unit' => 'Jedinična bruto cijena',
      'item_quantity' => 'Količina',
      'item_pay_off' => 'Prihvatljivi trošak nabavke artikla',
      'item_support' => 'Iznos bespovratnih sredstava koji tražite za artikal (EUR)',
      'item_net_amount' => 'Neto ukupni trošak nabavke artikla (EUR)',
      'item_vat' => 'Ukupan PDV',
      'item_bruto' => 'Bruto ukupni trošak nabavke artikla (EUR)',
      'item_own_source' => 'Iznos sopstvenog učešća (EUR)',
    ];
    $exception_numeric_field_names = [
      'item_quantity',
      'item_pay_off',
      'item_support',
      'item_own_source',
    ];
    foreach ($numeric_fields as $numeric_field_machine_name => $numeric_field) {
      $fields[$numeric_field_machine_name] = BaseFieldDefinition::create($numeric_field_machine_name === 'item_quantity' ? 'integer' : 'decimal')
        ->setLabel($numeric_field)
        ->setSettings([
          'precision' => 12,
          'scale' => 2,
          'suffix' => '€',
        ])
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE);
      if (!in_array($numeric_field_machine_name,  $exception_numeric_field_names)) {
        $fields[$numeric_field_machine_name .'_currency_value'] = BaseFieldDefinition::create('decimal')
          ->setLabel(str_replace(' (Ft)', '', $numeric_field))
          ->setSettings([
            'precision' => 12,
            'scale' => 2,
          ])
          ->setDisplayConfigurable('form', TRUE)
          ->setDisplayConfigurable('view', TRUE);
      }
    }

    $fields['new_item_pay_off'] = BaseFieldDefinition::create('decimal')
      ->setLabel('New payoff')
      ->setSettings([
        'precision' => 12,
        'scale' => 2,
        'suffix' => '€',
      ]);

    $fields['new_item_support'] = BaseFieldDefinition::create('decimal')
      ->setLabel('New Support')
      ->setSettings([
        'precision' => 12,
        'scale' => 2,
        'suffix' => '€',
      ]);

    $fields['currency'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Currency'))
      ->setSetting('allowed_values_function', '_get_mnb_currencies')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['currency_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Currency date'))
      ->setSettings([
        'datetime_type' => 'date',
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['item_support_percentage'] = BaseFieldDefinition::create('decimal')
      ->setLabel('Postotak bespovratnih sredstava koji tražite (%)')
      ->setSettings([
        'prefix' => '',
        'suffix' => '%',
      ])
      ->setSettings(PosFieldVariables::PERCENTAGE_DEFAULT_FIELD_SETTINGS)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['item_pay_off_computed'] = BaseFieldDefinition::create('decimal')
      ->setLabel('Ügyintéző által jóváhagyott elszámolható költség')
      ->setComputed(TRUE)
      ->setClass('\Drupal\cfp_payment_request\Plugin\Field\ItemPayOffComputedFieldItemList')
      ->setDisplayConfigurable('view', TRUE);

    $fields['item_support_computed'] = BaseFieldDefinition::create('decimal')
      ->setLabel('Ügyintéző által jóváhagyott támogatási összeg')
      ->setComputed(TRUE)
      ->setClass('\Drupal\cfp_payment_request\Plugin\Field\ItemSupportComputedFieldItemList')
      ->setDisplayConfigurable('view', TRUE);

    $fields['supplier'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Supplier'))
      ->setSetting('target_type', 'supplier')
      ->setSetting('handler', 'default:supplier')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['accepted'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Status'))
      ->setDefaultValue('accepted')
      ->setInitialValue('accepted')
      ->setSetting('allowed_values', PaymentRequestItem::getAllowedAcceptedValues())
      ->setDisplayConfigurable('view', TRUE);

    $fields['status']->setDescription(t('A boolean indicating whether the Payment request item is published.'));

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    return $fields;
  }

  public static function getAllowedAcceptedValues() {
    return [
      'rejected' => t('Rejected'),
      'accepted' => t('Accepted'),
      'accepted_with_new_value' => t('Accepted with new value'),
    ];
  }

  /**
   * Get item names.
   *
   * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition
   *   Field definition.
   * @param \Drupal\Core\Entity\ContentEntityInterface|null $entity
   *   Content entity.
   *
   * @return array
   *   Item names.
   */
  public static function itemNames(FieldStorageDefinitionInterface $definition = NULL, ContentEntityInterface $entity = NULL) {
    if ($parent = $entity->getParent()) {
      /** @var \Drupal\pos_payment_request\Entity\PaymentRequest $parent */
      if ($parent_cfp = $parent->get('parent')->entity) {
        /** @var \Drupal\pos_entity_cost_item\Entity\CostItemsParentEntityInterface $parent_cfp */
        $additional_options= array_filter(array_map(function (CostItemAcceptableInterface $cost_item) {
          if ($cost_item->isNewTotalSupportDefined() || $cost_item->isAccepted()) {
            return $cost_item->getName();
          }
        }, $parent_cfp->getCostItemEntities()));
        foreach ($parent_cfp->getAdditionalCostItems() as $key => $cost_item) {
          $additional_options["additional_cost_item_$key"] = $cost_item['name'];
        }
        return $additional_options;
      }
    }
    return [];
  }

  /**
   * @return array
   */
  public function getItemsCriteria() {
    if ($parent = $this->getParent()) {
      /** @var \Drupal\pos_payment_request\Entity\PaymentRequest $parent */
      if ($parent_cfp = $parent->get('parent')->entity) {
        /** @var \Drupal\pos_entity_cost_item\Entity\CostItemsParentEntityInterface $parent_cfp */
        $additional_options= array_filter(array_map(function (CostItemAcceptableInterface $cost_item) {
          if ($cost_item->isNewTotalSupportDefined() || $cost_item->isAccepted()) {
            return new AdditionalCostItem([
              'name' => $cost_item->getName(),
              'value' => $cost_item->getAcceptedTotalSupport(),
              'own_contribution_value' => $cost_item->getAcceptedOwnContribution(),
            ]);
          }
        }, $parent_cfp->getCostItemEntities()));
        foreach ($parent_cfp->getAdditionalCostItems() as $key => $cost_item) {
          $additional_options["additional_cost_item_$key"] = $cost_item;
        }
        return $additional_options;
      }
    }
  }

}
{#
/**
 * @file review.html.twig
 * Default theme implementation to present Review data.
 *
 * This template is used when viewing Review pages.
 *
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 * - attributes: HTML attributes for the container element.
 *
 * @see template_preprocess_review()
 *
 * @ingroup themeable
 */
#}
<link rel="stylesheet" type="text/css" href="/themes/custom/pos/css/print.css">

<script type="text/javascript">
  window.onload = () => {window.print();}
</script>

<div{{ attributes.addClass('review') }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</div>
<div class="signatures">
  <div class="signature-date">
    <p>Mjesto i datum: ____________________________ 2022.</p>
  </div>
  <div class="signature"><p>____________________________________________________________</p>
    <p>Potpis</p>
  </div>
</div>
{#
/**
 * @file review.html.twig
 * Default theme implementation to present Review data.
 *
 * This template is used when viewing Review pages.
 *
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 * - attributes: HTML attributes for the container element.
 *
 * @see template_preprocess_review()
 *
 * @ingroup themeable
 */
#}
<link rel="stylesheet" type="text/css" href="/themes/custom/pos/css/print.css">

<script type="text/javascript">
  window.onload = () => {window.print();}
</script>

<div{{ attributes.addClass('review') }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</div>
<div class="signatures">
  <div class="signature-date">
    <p>Mjesto i datum: ____________________________ 2022.</p>
  </div>
  <div class="signature"><p>____________________________________________________________</p>
    <p>Potpis</p>
  </div>
</div>
<?php

/**
 * @file
 * Contains pos_entity_review.module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\pos_entity_cfp\Entity\Cfp;
use Drupal\pos_entity_form_part\Form\EntityPartForm;
use Drupal\pos_entity_review\Entity\ReviewType;
use Drupal\pos_entity_review\Entity\ReviewTypeInterface;

/**
 * Implements hook_help().
 */
function pos_entity_review_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the pos_entity_review module.
    case 'help.page.pos_entity_review':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Pos Review Base Entity Used by CFP in some states') . '</p>';
      return $output;

    default:
  }
}

/**
 * Returns all execution as options.
 *
 * @return array
 *   Array of all review types with labels.
 *
 * @throws \ReflectionException
 */
function _get_review_types_as_options() {
  $reflection_class = new ReflectionClass(ReviewTypeInterface::class);
  $states = [];
  foreach ($reflection_class->getConstants() as $constant_name => $constant) {
    if (strpos($constant_name, 'REVIEW_TYPE') !== FALSE) {
      $states[$constant] = ucfirst(strtolower(str_replace([
        'REVIEW_TYPE_',
        '_',
      ], [
        '',
        ' ',
      ], $constant_name)));
    }
  }
  return $states;
}

/**
 * Implements hook_theme().
 */
function pos_entity_review_theme() {
  $theme = [];
  $theme['review'] = [
    'render element' => 'elements',
    'file' => 'review.page.inc',
    'template' => 'review',
  ];
  $theme['review_content_add_list'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'review.page.inc',
  ];
  return $theme;
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function pos_entity_review_theme_suggestions_review(array $variables) {
  $suggestions = [];
  $entity = $variables['elements']['#review'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'review__' . $sanitized_view_mode;
  $suggestions[] = 'review__' . $entity->bundle();
  $suggestions[] = 'review__' . $entity->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'review__' . $entity->id();
  $suggestions[] = 'review__' . $entity->id() . '__' . $sanitized_view_mode;
  return $suggestions;
}

/**
 * Implements hook_entity_extra_field_info().
 */
function pos_entity_review_entity_extra_field_info() {
  $extra = [];
  foreach (ReviewType::loadMultiple() as $review_type) {
    $extra['review'][$review_type->id()]['display']['view_link'] = [
      'label' => t('View link'),
      'description' => 'Entity view link',
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['edit_link'] = [
      'label' => t('Edit link'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['entity_label'] = [
      'label' => t('Entity label'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    if ($review_type->questionCanBeClarified()) {
      $extra['review'][$review_type->id()]['display']['clarify_question'] = [
        'label' => t('Clarify question button'),
        'weight' => 0,
        'visible' => FALSE,
      ];
    }
    $extra['review'][$review_type->id()]['display']['correction_data'] = [
      'label' => t('Correction data(correction data for given)'),
      'description' => t('If review is for correction state, corrections will be shown'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['reviewer_additional_files'] = [
      'label' => t('Shows file upload for additional files'),
      'description' => t('Reviewer need to attach document during work in some cases'),
      'weight' => 0,
      'visible' => FALSE,
    ];
  }

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function pos_entity_review_review_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  /** @var \Drupal\pos_entity_review\Entity\Review $entity */

  if ($display->getComponent('view_link') && $entity->access('view') && !$entity->access('update')) {
    $view_link = $entity->toUrl();
    $build['view_link'] = [
      '#type' => 'link',
      '#title' => t('View'),
      '#url' => $view_link,
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('edit_link') && $entity->access('update')) {
    $edit_link = $entity->toUrl('edit-form');
    $edit_link->setRouteParameter('destination', Url::fromRoute('<current>')->toString());
    $build['edit_link'] = [
      '#type' => 'link',
      '#title' => t('Edit'),
      '#url' => $edit_link,
      '#attributes' => [
        'class' => ['button', 'button--primary'],
      ],
    ];
  }
  if ($display->getComponent('entity_label')) {
    $build['entity_label'] = [
      '#type' => 'markup',
      '#markup' => '<h3>' . $entity->label() . '</h3>',
    ];
  }
  if ($display->getComponent('clarify_question') && $entity->access('update')) {
    $build['clarify_question'] = [
      '#title' => t('Clarify question'),
      '#type' => 'link',
      '#url' => $entity->toUrl('question-form')->setRouteParameter('destination', Url::fromRoute('<current>')->toString()),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('correction_data')) {
    /** @var \Drupal\pos_entity_cfp\Entity\Cfp $cfp */
    $cfp = $entity->getCfpEntity();
    if ($cfp && $state_for_review = $entity->get('state_for_review')->value) {
      $correction_plugin = $cfp->getStateCorrectionPlugin($state_for_review);
      if ($correction_plugin) {
        $build['correction_data']['#type'] = 'container';
        $build['correction_data']['questions'] = $correction_plugin->getCorrectionQuestionElement();
        $build['correction_data']['answers'] = $correction_plugin->getCorrectionAnswersElement();
      }
    }
  }
  if ($display->getComponent('reviewer_additional_files')) {
    if ((\Drupal::currentUser()->id() == $entity->getAssigneeId()) || (in_array('administrator', \Drupal::currentUser()->getRoles()))) {
      $field = 'reviewer_files';

      /** @var \Drupal\pos_entity_form_part\Form\EntityPartForm $form_part */
      $form_part = \Drupal::classResolver()
        ->getInstanceFromDefinition(EntityPartForm::class);
      $form_state = new FormState();
      $form_part->setFields([$field]);
      $form_part->setEntity($entity);
      $form_part->setRedirectionRoute('<current>');
      $form_part->setCurrentTabRedirect(TRUE);
      $form = \Drupal::formBuilder()->buildForm($form_part, $form_state);
      $form['reviewer_files']['widget']['#disable_dragging'] = TRUE;
      $build['reviewer_additional_files'] = $form;
    }
  }
}

/**
 * Implements hook_cron().
 */
function pos_entity_review_cron() {
  $query = \Drupal::database()->query('SELECT id FROM `review` WHERE cfp NOT IN (SELECT id FROM cfp)');
  $review_storage = \Drupal::entityTypeManager()->getStorage('review');
  while ($row = $query->fetch()) {
    $review = $review_storage->load($row->id);
    if ($review) {
      $review->delete();
    }
  }
}

/**
 * Implements hook_views_data_alter().
 */
function pos_entity_review_views_data_alter(array &$data) {
  $data['review']['review_project_implementation_filter'] = [
    'title' => t('Járás" - Okres - Project Implementation Place (Filter)'),
    'filter' => [
      'title' => t('Járás - Okres - Project Implementation Place (Filter)'),
      'field' => 'cfp',
      'id' => 'pos_review_address_filter',
    ],
  ];
}

/**
 * Implements hook_review_passed_alter().
 */
function pos_entity_review_review_passed_alter(&$passed, $entity) {
  /** @var \Drupal\pos_entity_review\Entity\ReviewType $review_type */
  $review_type = ReviewType::load($entity->bundle());
  if (($key_field = $review_type->getKeyField()) && !empty($accept_values = $review_type->getAcceptValues())) {
    if (in_array($entity->get($key_field)->value, $accept_values)) {
      if (pos_printer_is_printable_entity($entity->getEntityType(), $entity->bundle())) {
        if ($entity->isPrintConfirmed()) {
          $passed = TRUE;
        }
      }
      else {
        $passed = TRUE;
      }
    }
  }
}

/**
 * Implements hook_review_rejected_alter().
 */
function pos_entity_review_review_rejected_alter(&$rejected, $entity) {
  /** @var \Drupal\pos_entity_review\Entity\ReviewType $review_type */
  $review_type = ReviewType::load($entity->bundle());
  if (($key_field = $review_type->getKeyField()) && !empty($reject_values = $review_type->getRejectValues())) {
    if (in_array($entity->get($key_field)->value, $reject_values)) {
      if (pos_printer_is_printable_entity($entity->getEntityType(), $entity->bundle())) {
        if ($entity->isPrintConfirmed()) {
          $rejected = TRUE;
        }
      }
      else {
        $rejected = TRUE;
      }
    }
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function pos_entity_review_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'review' && !empty($bundle)) {
    $review_type = ReviewType::load($bundle);
    if ($key_field = $review_type->getKeyField()) {
      if (isset($fields[$key_field])) {
        $fields[$key_field]->addConstraint('reviewKeyFieldCondition');
      }
    }
  }
  if ($entity_type->id() === 'review' && $bundle === 'acceptance_2022_01') {
    if ($fields['cf_comment']) {
      $fields['cf_comment']->setRequired(TRUE);
      $fields['cf_comment']->addPropertyConstraints('value', ['NamedLength' => ['min' => 20, 'max' => 500]]);
    }
  }
}

/**
 * Implements hook_mail().
 */
function pos_entity_review_mail($key, &$message, $params) {
  switch ($key) {
    case 'reviewer_clarify_question':
      $message['headers']['From'] = $params['from'];
      $message['headers']['Sender'] = $params['from'];
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['message'];
      $message['headers']['Content-Type'] = 'text/html';
      break;
  }
}

{#
/**
 * @file review.html.twig
 * Default theme implementation to present Review data.
 *
 * This template is used when viewing Review pages.
 *
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 * - attributes: HTML attributes for the container element.
 *
 * @see template_preprocess_review()
 *
 * @ingroup themeable
 */
#}
<link rel="stylesheet" type="text/css" href="/themes/custom/pos/css/print.css">

<script type="text/javascript">
  window.onload = () => {window.print();}
</script>

<div{{ attributes.addClass('review') }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</div>
<div class="signatures">
  <div class="signature-date">
    <p>Mjesto i datum: ____________________________ 2022.</p>
  </div>
  <div class="signature"><p>____________________________________________________________</p>
    <p>Potpis</p>
  </div>
</div>
<?php

/**
 * @file
 * Contains pos_entity_review.module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\pos_entity_cfp\Entity\Cfp;
use Drupal\pos_entity_form_part\Form\EntityPartForm;
use Drupal\pos_entity_review\Entity\ReviewType;
use Drupal\pos_entity_review\Entity\ReviewTypeInterface;

/**
 * Implements hook_help().
 */
function pos_entity_review_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the pos_entity_review module.
    case 'help.page.pos_entity_review':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Pos Review Base Entity Used by CFP in some states') . '</p>';
      return $output;

    default:
  }
}

/**
 * Returns all execution as options.
 *
 * @return array
 *   Array of all review types with labels.
 *
 * @throws \ReflectionException
 */
function _get_review_types_as_options() {
  $reflection_class = new ReflectionClass(ReviewTypeInterface::class);
  $states = [];
  foreach ($reflection_class->getConstants() as $constant_name => $constant) {
    if (strpos($constant_name, 'REVIEW_TYPE') !== FALSE) {
      $states[$constant] = ucfirst(strtolower(str_replace([
        'REVIEW_TYPE_',
        '_',
      ], [
        '',
        ' ',
      ], $constant_name)));
    }
  }
  return $states;
}

/**
 * Implements hook_theme().
 */
function pos_entity_review_theme() {
  $theme = [];
  $theme['review'] = [
    'render element' => 'elements',
    'file' => 'review.page.inc',
    'template' => 'review',
  ];
  $theme['review_content_add_list'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'review.page.inc',
  ];
  return $theme;
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function pos_entity_review_theme_suggestions_review(array $variables) {
  $suggestions = [];
  $entity = $variables['elements']['#review'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'review__' . $sanitized_view_mode;
  $suggestions[] = 'review__' . $entity->bundle();
  $suggestions[] = 'review__' . $entity->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'review__' . $entity->id();
  $suggestions[] = 'review__' . $entity->id() . '__' . $sanitized_view_mode;
  return $suggestions;
}

/**
 * Implements hook_entity_extra_field_info().
 */
function pos_entity_review_entity_extra_field_info() {
  $extra = [];
  foreach (ReviewType::loadMultiple() as $review_type) {
    $extra['review'][$review_type->id()]['display']['view_link'] = [
      'label' => t('View link'),
      'description' => 'Entity view link',
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['edit_link'] = [
      'label' => t('Edit link'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['entity_label'] = [
      'label' => t('Entity label'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    if ($review_type->questionCanBeClarified()) {
      $extra['review'][$review_type->id()]['display']['clarify_question'] = [
        'label' => t('Clarify question button'),
        'weight' => 0,
        'visible' => FALSE,
      ];
    }
    $extra['review'][$review_type->id()]['display']['correction_data'] = [
      'label' => t('Correction data(correction data for given)'),
      'description' => t('If review is for correction state, corrections will be shown'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['reviewer_additional_files'] = [
      'label' => t('Shows file upload for additional files'),
      'description' => t('Reviewer need to attach document during work in some cases'),
      'weight' => 0,
      'visible' => FALSE,
    ];
    $extra['review'][$review_type->id()]['display']['raw_signature'] = [
      'label' => t('Signature'),
      'visible' => FALSE,
    ];
  }

  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function pos_entity_review_review_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  /** @var \Drupal\pos_entity_review\Entity\Review $entity */

  if ($display->getComponent('view_link') && $entity->access('view') && !$entity->access('update')) {
    $view_link = $entity->toUrl();
    $build['view_link'] = [
      '#type' => 'link',
      '#title' => t('View'),
      '#url' => $view_link,
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('edit_link') && $entity->access('update')) {
    $edit_link = $entity->toUrl('edit-form');
    $edit_link->setRouteParameter('destination', Url::fromRoute('<current>')->toString());
    $build['edit_link'] = [
      '#type' => 'link',
      '#title' => t('Edit'),
      '#url' => $edit_link,
      '#attributes' => [
        'class' => ['button', 'button--primary'],
      ],
    ];
  }
  if ($display->getComponent('entity_label')) {
    $build['entity_label'] = [
      '#type' => 'markup',
      '#markup' => '<h3>' . $entity->label() . '</h3>',
    ];
  }
  if ($display->getComponent('clarify_question') && $entity->access('update')) {
    $build['clarify_question'] = [
      '#title' => t('Clarify question'),
      '#type' => 'link',
      '#url' => $entity->toUrl('question-form')->setRouteParameter('destination', Url::fromRoute('<current>')->toString()),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('correction_data')) {
    /** @var \Drupal\pos_entity_cfp\Entity\Cfp $cfp */
    $cfp = $entity->getCfpEntity();
    if ($cfp && $state_for_review = $entity->get('state_for_review')->value) {
      $correction_plugin = $cfp->getStateCorrectionPlugin($state_for_review);
      if ($correction_plugin) {
        $build['correction_data']['#type'] = 'container';
        $build['correction_data']['questions'] = $correction_plugin->getCorrectionQuestionElement();
        $build['correction_data']['answers'] = $correction_plugin->getCorrectionAnswersElement();
      }
    }
  }
  if ($display->getComponent('reviewer_additional_files')) {
    if ((\Drupal::currentUser()->id() == $entity->getAssigneeId()) || (in_array('administrator', \Drupal::currentUser()->getRoles()))) {
      $field = 'reviewer_files';

      /** @var \Drupal\pos_entity_form_part\Form\EntityPartForm $form_part */
      $form_part = \Drupal::classResolver()
        ->getInstanceFromDefinition(EntityPartForm::class);
      $form_state = new FormState();
      $form_part->setFields([$field]);
      $form_part->setEntity($entity);
      $form_part->setRedirectionRoute('<current>');
      $form_part->setCurrentTabRedirect(TRUE);
      $form = \Drupal::formBuilder()->buildForm($form_part, $form_state);
      $form['reviewer_files']['widget']['#disable_dragging'] = TRUE;
      $build['reviewer_additional_files'] = $form;
    }
  }
  if ($display->getComponent('raw_signature')) {
    /** @var \Drupal\pos_entity_cfp\Entity\Cfp $cfp */
    $cfp = $entity->getCfpEntity();
    $build['raw_signature'] = [
      '#type' => 'inline_template',
      '#template' => pos_entity_review_get_signature_part($cfp),
    ];
  }
}

/**
 * Get signature part.
 */
function pos_entity_review_get_signature_part(Cfp $cfp) {
  $representative = $cfp->getApplicantEntity()->getCompanyRepresentative();
  return '<div class="signatures">
        <div class="signature-date"><p>Mjesto i datum: ____________________________ 2022.</p></div>
        <div class="signature">
            <p>____________________________</p>
            <p>' . $cfp->getApplicantEntity()->get('applicant_name')->value . '</p>
            <p>' . $representative?->label() .'</p>
        </div>';
}

/**
 * Implements hook_cron().
 */
function pos_entity_review_cron() {
  $query = \Drupal::database()->query('SELECT id FROM `review` WHERE cfp NOT IN (SELECT id FROM cfp)');
  $review_storage = \Drupal::entityTypeManager()->getStorage('review');
  while ($row = $query->fetch()) {
    $review = $review_storage->load($row->id);
    if ($review) {
      $review->delete();
    }
  }
}

/**
 * Implements hook_views_data_alter().
 */
function pos_entity_review_views_data_alter(array &$data) {
  $data['review']['review_project_implementation_filter'] = [
    'title' => t('Járás" - Okres - Project Implementation Place (Filter)'),
    'filter' => [
      'title' => t('Járás - Okres - Project Implementation Place (Filter)'),
      'field' => 'cfp',
      'id' => 'pos_review_address_filter',
    ],
  ];
}

/**
 * Implements hook_review_passed_alter().
 */
function pos_entity_review_review_passed_alter(&$passed, $entity) {
  /** @var \Drupal\pos_entity_review\Entity\ReviewType $review_type */
  $review_type = ReviewType::load($entity->bundle());
  if (($key_field = $review_type->getKeyField()) && !empty($accept_values = $review_type->getAcceptValues())) {
    if (in_array($entity->get($key_field)->value, $accept_values)) {
      if (pos_printer_is_printable_entity($entity->getEntityType(), $entity->bundle())) {
        if ($entity->isPrintConfirmed()) {
          $passed = TRUE;
        }
      }
      else {
        $passed = TRUE;
      }
    }
  }
}

/**
 * Implements hook_review_rejected_alter().
 */
function pos_entity_review_review_rejected_alter(&$rejected, $entity) {
  /** @var \Drupal\pos_entity_review\Entity\ReviewType $review_type */
  $review_type = ReviewType::load($entity->bundle());
  if (($key_field = $review_type->getKeyField()) && !empty($reject_values = $review_type->getRejectValues())) {
    if (in_array($entity->get($key_field)->value, $reject_values)) {
      if (pos_printer_is_printable_entity($entity->getEntityType(), $entity->bundle())) {
        if ($entity->isPrintConfirmed()) {
          $rejected = TRUE;
        }
      }
      else {
        $rejected = TRUE;
      }
    }
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function pos_entity_review_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'review' && !empty($bundle)) {
    $review_type = ReviewType::load($bundle);
    if ($key_field = $review_type->getKeyField()) {
      if (isset($fields[$key_field])) {
        $fields[$key_field]->addConstraint('reviewKeyFieldCondition');
      }
    }
  }
  if ($entity_type->id() === 'review' && $bundle === 'acceptance_2022_01') {
    if ($fields['cf_comment']) {
      $fields['cf_comment']->setRequired(TRUE);
      $fields['cf_comment']->addPropertyConstraints('value', ['NamedLength' => ['min' => 20, 'max' => 500]]);
    }
  }
}

/**
 * Implements hook_mail().
 */
function pos_entity_review_mail($key, &$message, $params) {
  switch ($key) {
    case 'reviewer_clarify_question':
      $message['headers']['From'] = $params['from'];
      $message['headers']['Sender'] = $params['from'];
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['message'];
      $message['headers']['Content-Type'] = 'text/html';
      break;
  }
}

<?php


namespace Drupal\pos_entity_review\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\pos_entity_cfp\Entity\CfpType;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class ReviewQuestionClaficationForm
 *
 * @package Drupal\pos_entity_review\Form
 */
class ReviewQuestionClarificationForm extends ContentEntityForm {

  /**
   * Mail Manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * Constructs a new ReviewQuestionClarificationForm.
   *
   * @param EntityRepositoryInterface $entity_repository
   * @param EntityTypeBundleInfoInterface $entity_type_bundle_info
   * @param TimeInterface $time
   * @param MailManagerInterface $mailManager
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, MailManagerInterface $mailManager) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->mailManager = $mailManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
      $container->get('entity.repository'),
      $container->get('entity_type.bundle.info'),
      $container->get('datetime.time'),
      $container->get('plugin.manager.mail'),
    );
  }

  /**
   * {@inheritDoc}
   */
  public function getFormDisplay(FormStateInterface $form_state) {
    $entity_form_display = EntityFormDisplay::create([
      'targetEntityType' => 'review',
      'third_party_settings' => [],
      'bundle' => $this->entity->bundle(),
      'content' => [
        'question' => [
          'type' => 'string_textarea',
          'region' => 'content',
          'weight' => 0,
          'settings' => [
            'rows' => 10,
            'placeholder' => '',
          ],
          'third_party_settings' => [],
        ]
      ],
    ]);
    return $entity_form_display;
  }

  /**
   * {@inheritDoc}
   */
  public function setFormDisplay(EntityFormDisplayInterface $form_display, FormStateInterface $form_state) {
    return parent::setFormDisplay($this->getFormDisplay($form_state), $form_state);
  }

  /**
   * {@inheritDoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);
    return $actions;
  }

  /**
   * Route title callback.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   */
  public function titleCallback() {
    return $this->t('Clarify question');
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\pos_entity_review\Entity\Review $review */
    $review = $this->entity;

    $cfp = $review->getCfpEntity();
    $cfp_type = CfpType::load($cfp->bundle());
    $reviewer = $review->getAssignee();

    // If admin is the one who is sending the mail, then it needs to be sent to reviewers email address.
    if ($this->currentUser()->hasPermission('admin view all call for proposal entities')) {
      $to = $reviewer->getEmail();
      $from = $cfp_type->get('mail_sender')->value ?? 'noreply@forsrpska.org';
    }
    else {
      $to = $cfp_type->get('notification_email')->value ?? 'info@forsrpska.org';
      $from = $reviewer->getEmail();
    }

    $this->mailManager->mail(
      'pos_entity_review',
      'reviewer_clarify_question',
      $to,
      \Drupal::languageManager()->getCurrentLanguage()->getId(),
      [
        'from' => $from,
        'subject' => t('Clarify question'),
        'message' => reset($form_state->getValue('question'))['value'],
      ],
      NULL,
      TRUE
    );

  }

}
<?php

namespace Drupal\cfp_payment_request\Entity;

use Drupal\cfp_payment_request\Event\PRTransitionEvent;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Drupal\halo_closable_entity\Entity\ClosableEntityTrait;
use Drupal\halo_entity_cfp\Entity\Cfp;
use Drupal\halo_entity_validator\Entity\HaloEntityValidationTrait;
use Drupal\halo_parent_entity\Entity\ChildEntityTrait;
use Drupal\halo_printer\Entity\HaloPrintableEntityTrait;
use Drupal\halo_printer\Entity\PrintTokenEntityInterface;
use Drupal\halo_transition_history_field\Plugin\Field\TransitionDateSearchItemList;
use Drupal\user\UserInterface;
use Drupal\halo_entity_cfp\Entity\CfpPaymentInterface;

/**
 * Defines the Payment request entity.
 *
 * @ingroup cfp_payment_request
 *
 * @ContentEntityType(
 *   id = "cfp_payment_request",
 *   label = @Translation("Payment request"),
 *   bundle_label = @Translation("Payment request type"),
 *   handlers = {
 *     "view_builder" = "Drupal\cfp_payment_request\PaymentRequestEntityViewBuilder",
 *     "list_builder" = "Drupal\cfp_payment_request\PaymentRequestListBuilder",
 *     "views_data" = "Drupal\cfp_payment_request\Entity\PaymentRequestViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\cfp_payment_request\Form\PaymentRequestForm",
 *       "add" = "Drupal\cfp_payment_request\Form\PaymentRequestForm",
 *       "edit" = "Drupal\cfp_payment_request\Form\PaymentRequestForm",
 *       "delete" = "Drupal\cfp_payment_request\Form\PaymentRequestDeleteForm",
 *       "suspended_documents" = "\Drupal\cfp_payment_request\Form\PaymentRequestSuspendedDocumentsForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\cfp_payment_request\PaymentRequestHtmlRouteProvider",
 *     },
 *     "access" = "Drupal\cfp_payment_request\PaymentRequestAccessControlHandler",
 *   },
 *   base_table = "cfp_payment_request",
 *   translatable = FALSE,
 *   admin_permission = "administer payment request entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "bundle" = "type",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "published" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/cfp_payment_request/{cfp_payment_request}",
 *     "add-page" = "/admin/structure/cfp_payment_request/add",
 *     "add-form" = "/admin/structure/cfp_payment_request/add/{cfp_payment_request_type}",
 *     "edit-form" = "/admin/structure/cfp_payment_request/{cfp_payment_request}/edit",
 *     "current-correction-form" = "/admin/structure/cfp_payment_request/{cfp_payment_request}/correction",
 *     "correction-submit-form" = "/admin/structure/cfp_payment_request/{cfp_payment_request}/correction_submit",
 *     "delete-form" = "/admin/structure/cfp_payment_request/{cfp_payment_request}/delete",
 *     "collection" = "/admin/structure/cfp_payment_request",
 *     "admin-view" = "/admin/structure/cfp_payment_request/{cfp_payment_request}/admin_view",
 *     "suspended-documents" = "/cfp_payment_request/{cfp_payment_request}/suspended_documents",
 *     "suspended-documents-submit" = "/cfp_payment_request/{cfp_payment_request}/suspended_documents_submit"
 *   },
 *   bundle_entity_type = "cfp_payment_request_type",
 *   field_ui_base_route = "entity.cfp_payment_request_type.edit_form"
 * )
 */
class PaymentRequest extends ContentEntityBase implements PaymentRequestInterface, CfpPaymentInterface, PrintTokenEntityInterface {

  use EntityChangedTrait;
  use EntityPublishedTrait;
  use HaloEntityValidationTrait;
  use ClosableEntityTrait;
  use HaloPrintableEntityTrait;
  use ChildEntityTrait;

  const ADD_UP_FIELDS = [
    'item_pay_off',
    'item_support',
    'item_pay_off_computed',
    'item_support_computed',
    'item_net_amount',
    'item_vat',
    'item_bruto',
    'item_own_source',
  ];

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return $this->get('label')->value;
  }

  /**
   * {@inheritdoc}
   * @todo Refactor this in more functions.
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestType $payment_request_type */
    $payment_request_type = $this->get('type')->entity;
    $clear_reopen_instructions = FALSE;
    if (!$this->isNew()) {
      // On opening payment request.
      if ($this->getState() === 'open_state' && $this->getState() !== $this->original->getState()) {
        $this->set('validation_passed', FALSE);
        $this->set('closed', FALSE);
        $this->set('print', NULL);
        $this->set('print_confirmed', FALSE);
      }
      // On reopening payment request.
      if ($this->getState() === 'reopened' && $this->getState() !== $this->original->getState()) {
        /** @var \Drupal\file\Entity\File $old_print_file */
        $old_print_file = $this->get('print')->entity;
        if ($old_print_file) {
          $this->get('old_prints')->appendItem([
            'target_id' => $old_print_file->id(),
            'description' => DrupalDateTime::createFromTimestamp($old_print_file->getCreatedTime())->format('Y.m.d.') . ' - print',
          ]);
        }
        $reopen_instructions = $this->get('reopen_instructions')->value ?? '-';
        $this->get('previous_reopen_instructions')->appendItem(['value' => $reopen_instructions]);
        $clear_reopen_instructions = TRUE;
        $this->invalidate()->open()->clearPrintFile()->unconfirmPrint();
      }
      if ($this->isPrintConfirmed() === TRUE && $this->original->isPrintConfirmed() === FALSE) {
        $this->appendChecklist($this->getState() === 'reopened');
        $this->setState('sent');
        if ($this->get('first_submission_date')->isEmpty()) {
          $this->set('first_submission_date', \Drupal::time()->getCurrentTime());
        }
      }
      if (!$this->original->isClosed() && $this->isClosed()) {
        $datetime = new DrupalDateTime();
        $datetime->setTimezone(new \DateTimeZone('UTC'));
        $this->set('closed_date', $datetime->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT));
      }
      if ($this->getState() === 'correction_submitted' &&
        $this->original->getState() === 'correction'
      ) {
        $current_correction = (int) $this->get('current_correction')->value;
        $this->appendChecklist(TRUE);
        $this->set('current_correction', ($current_correction + 1));
      }
      if ($this->getState() === 'deadline_expired' &&
        $this->original->getState() === 'reopened') {
        // This function needs to accept one more optional argument (after_deadline).
        $this->appendChecklist(FALSE, TRUE);
      }
      if (($this->getState() === 'approved' || $this->getState() === 'accepted_with_reduction') && $this->stateHasChangedFromOriginal()) {
        $this->set('date_of_completion', \Drupal::time()->getCurrentTime());
      }
      // Flag that cfp has closing payment request.
      if ($this->stateHasChangedFromOriginal() && $this->hasField('pr_type') && $this->get('pr_type')->value === 'closing') {
        if (in_array($this->getState(), Cfp::getPaidStates())) {
          if ($this->hasParent() && !$this->getParent()->isFlagged('has_closing_payment_request')) {
            $this->getParent()->flag('has_closing_payment_request')->save();
          }
        }
        if (in_array($this->getState(), Cfp::getCompletionStates())) {
          if ($this->hasParent() && !$this->getParent()->isFlagged('has_approved_closing_pr')) {
            $this->getParent()->flag('has_approved_closing_pr')->save();
          }
        }
      }
      if ($this->getState() !== $this->original->getState()) {
        $event = new PRTransitionEvent(
          $this,
          $this->original->getState(),
          $this->getState()
        );
        \Drupal::service('event_dispatcher')->dispatch(PRTransitionEvent::TRANSITION_EVENT, $event);
        $this->appendTransition($this->getState());
        $this->set('correction_deadline', NULL);
      }
      if ($this->stateHasChangedFromOriginal() && in_array($this->getState(), Cfp::getCompletionInvalidationStates())) {
        $this->setAmountDedicatedToAp(NULL);
        $this->set('date_of_completion', NULL);
      }
    }
    if ($this->get('label')->isEmpty() && $this->hasParent()) {
      $parent = $this->getParent();
      $order = $parent->get('payment_request')->count() + 1;
      $this->set('label', $parent->label() . '/' . $payment_request_type->get('order_prefix') . $order);
    }
    if ($this->hasParent()) {
      $this->setOwnerId($this->getParent()->getOwnerId());
    }
    if ($clear_reopen_instructions) {
      $this->set('reopen_instructions', NULL);
    }
    $items = $this->getItems(TRUE);
    $this->calculateTotals($items);
    $this->constructItemLabels($items);
    $this->setInvoiceOrdering();
  }

  /**
   * Calculates totals.
   */
  public function calculateTotals($items = NULL) {
    if (!isset($items)) {
      $items = $this->getItems(TRUE);
    }
    foreach (self::ADD_UP_FIELDS as $add_up_field) {
      $total = 0;
      foreach ($items as $item) {
        $total += $item->get($add_up_field)->value ?? 0;
      }
      $this->set("{$add_up_field}_total", $total);
    }

    if (($this->getState() === 'approved' || $this->getState() === 'accepted_with_reduction') && isset($this->original) && $this->original->getState() !== $this->getState()) {
      /** @var \Drupal\halo_entity_cfp\Entity\Cfp $cfp */
      $cfp = $this->getParent();
      $not_covered_ap = $cfp->getNotCoveredApAmount();
      if ($not_covered_ap > $this->getTotalSupport()) {
        $this->setAmountDedicatedToAp($this->getTotalSupport());
      }
      else {
        $this->setAmountDedicatedToAp($not_covered_ap);
      }
    }
  }

  /**
   * Has state changed since original.
   *
   * @return bool
   *   Has state changed.
   */
  protected function stateHasChangedFromOriginal() {
    if (!isset($this->original)) {
      return FALSE;
    }
    return $this->original->getState() !== $this->getState();
  }

  /**
   * Constructs labels based on order from parent payment request(this entity).
   *
   * @param \Drupal\cfp_payment_request\Entity\PaymentRequestItem[] $items
   *   Payment request items.
   */
  public function constructItemLabels($items) {
    foreach ($items as $delta => $item) {
      $label = $this->label() . '-' . str_pad(($delta + 1), 3, '0', STR_PAD_LEFT);
      if ($item->getName() != $label) {
        $item->setName($label);
        $item->save();
      }
    }
  }

  public function setInvoiceOrdering() {
    foreach ($this->getInvoices() as $order => $invoice) {
      if (((int) ($order + 1)) !== ((int) $invoice->get('invoice_order')->value)) {
        $invoice->set('invoice_order', $order + 1);
        $invoice->save();
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('label', $name);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * Item type for this payment request.
   *
   * @return string
   *   Item type for this payment request.
   */
  public function getPaymentRequestItemType() {
    return \Drupal::entityTypeManager()
      ->getStorage('cfp_payment_request_type')
      ->load($this->bundle())
      ->get('payment_request_item_type');
  }

  /**
   * @return \Drupal\cfp_payment_request\Entity\PaymentRequestItem[]
   */
  public function getItems($with_invoice = FALSE) {
    $items = [];
    foreach ($this->get('items') as $field_item) {
      if ($item = $field_item->entity) {
        $items[] = $item;
      }
    }
    if ($with_invoice) {
      foreach ($this->getInvoices() as $invoice) {
        foreach ($invoice->getItems() as $item) {
          $items[] = $item;
        }
      }
    }
    return $items;
  }

  /**
   * @return \Drupal\cfp_payment_request\Entity\PrInvoice[]
   */
  public function getInvoices() {
    $invoices = [];
    foreach ($this->get('invoices') as $field_item) {
      if ($invoice = $field_item->entity) {
        $invoices[] = $invoice;
      }
    }
    return $invoices;
  }

  /**
   * Returns active state.
   *
   * @return string
   *   Active state.
   */
  public function getState() {
    return $this->get('state')->value ?: 'open_state';
  }

  /**
   * Returns active state.
   *
   * @return string
   *   Active state.
   */
  public function getStateId(): string {
    return $this->getState();
  }

  /**
   * {@inheritDoc}
   */
  public function getCompletionTimestamp(): int|string|null {
    return $this->get('date_of_completion')->value;
  }

  /**
   * Payment request state.
   *
   * @param string $state
   *   Payment request state.
   *
   * @return static
   *   Returns
   */
  public function setState($state) {
    $this->set('state', $state);
    return $this;
  }

  /**
   * Returns user friendly state value.
   *
   * @return string
   *   User friendly value.
   */
  public function getStateLabel() {
    return $this->get('state')->first()->getLabel();
  }

  /**
   * {@inheritdoc}
   */
  public function inheritsParentAccess() {
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    return $this->get('label')->value;
  }

  /**
   * Is item approvement closed.
   *
   * @return bool
   *
   */
  public function isItemApprovementClosed() {
    return (bool) $this->get('items_approvement_closed')->value;
  }

  /**
   * {@inheritDoc}
   */
  public function appendChecklist($during_correction = FALSE, $after_deadline = FALSE) {
    /** @var \Drupal\cfp_payment_request\Entity\PaymentRequestType $payment_request_type */
    $payment_request_type = $this->get('type')->entity;
    if (!$during_correction) {
      if ($after_deadline) {
        $payment_request_checklist = $this->generateDuplicateChecklist($during_correction, $after_deadline);
      }
      else {
        $payment_request_checklist = \Drupal::entityTypeManager()
          ->getStorage('cfp_payment_request_checklist')
          ->create([
            'bundle' => $payment_request_type->get('payment_request_checklist_type'),
            'created_during_correction' => $during_correction,
            'created_after_deadline' => $after_deadline,
          ]);
      }
    } else {
      $payment_request_checklist = $this->generateDuplicateChecklist($during_correction, $after_deadline);
    }
    $payment_request_checklist->save();
    $this->get('checklist')->appendItem($payment_request_checklist->id());
  }

  /**
   * Generates new checklist.
   *
   * @param $correction
   * @param $deadline
   *
   * @return \Drupal\cfp_payment_request\Entity\CfpPaymentRequestChecklist
   */
  private function generateDuplicateChecklist($correction, $deadline): CfpPaymentRequestChecklist {
    $last_checklist = $this->getLastChecklist();
    $payment_request_checklist = $last_checklist->createDuplicate();
    $payment_request_checklist->set('closed', FALSE);
    $payment_request_checklist->set('validation_passed', FALSE);
    $payment_request_checklist->set('created_during_correction', $correction);
    $payment_request_checklist->set('created_after_deadline', $deadline);

    return $payment_request_checklist;
  }

  /**
   * Returns last checklist.
   *
   * @return \Drupal\cfp_payment_request\Entity\CfpPaymentRequestChecklist
   */
  public function getLastChecklist() {
    if ($this->get('checklist')->isEmpty()) {
      return FALSE;
    }
    /** @var \Drupal\cfp_payment_request\Entity\CfpPaymentRequestChecklist $checklist */
    $checklist = $this->get('checklist')->get(($this->get('checklist')->count() - 1))->entity;
    return $checklist;
  }

  /**
   * @return \Drupal\cfp_payment_request\Entity\PrCorrectionData
   */
  public function getCurrentCorrectionData() {
    $current_correction = $this->get('current_correction')->value;
    if ($item = $this->get('correction_data')->get($current_correction)) {
      if ($correction_data = $item->entity) {
        return $correction_data;
      }
    }
    return FALSE;
  }

  /**
   * @param $to_state
   */
  public function appendTransition($to_state) {
    $this->get('transition_history')->appendItem([
      'to' => $to_state,
      'timestamp' => \Drupal::time()->getCurrentTime(),
      'user_id' => \Drupal::currentUser()->id(),
      'user_email' => \Drupal::currentUser()->getEmail(),
      'user_display_name' => \Drupal::currentUser()->getDisplayName(),
      'deadline' => $this->get('correction_deadline')->value,
    ]);
  }

  /**
   * Total support.
   *
   * @return int
   *   Total support.
   */
  public function getTotalSupport() {
    // TODO: Check every call.
    return (int) $this->get('item_support_computed_total')->value;
  }

  /**
   * Amount to pay.
   *
   * @return int
   *   Amount to pay.
   */
  public function getAmountToPay() {
    return (int) $this->get('amount_to_pay')->value;
  }

  /**
   * Amount dedicated to advance payment.
   *
   * @return int
   *   Amount dedicated to advance payment.
   */
  public function getAmountDedicatedToAp() {
    return (int) $this->get('computed_amount_dedicated_to_ap')->value;
  }

  /**
   * Returns pr type.
   *
   * @return string
   *   Returns value of config field pr type.
   */
  public function getPaymentRequestType() {
    return $this->hasField('pr_type') ? $this->get('pr_type')->value : NULL;
  }

  /**
   * @return string
   */
  public function getPaymentRequestTypeLabel() {
    if ($type = $this->getPaymentRequestType()) {
      $allowed_values = $this->get('pr_type')->getFieldDefinition()->getSetting('allowed_values');
      return $allowed_values[$type];
    }
  }

  /**
   * Set amount dedicated to advance payment coverage.
   *
   * @param $amount
   *   Amount dedicated to advance payment.
   */
  public function setAmountDedicatedToAp($amount) {
    $this->set('amount_dedicated_to_ap', $amount);
    return $this;
  }

  /**
   * @return string
   *   Last reopening instructions.
   */
  public function getLastReopeningInstructions() {
    if (!$this->get('previous_reopen_instructions')->isEmpty()) {
      return $this->get('previous_reopen_instructions')->get($this->get('previous_reopen_instructions')->count() - 1)->value;
    }
  }

  public function getSignatureToken() {
    /** @var \Drupal\halo_entity_cfp\Entity\Cfp $cfp */
    $cfp = $this->getParent();
    return $cfp->getApplicantEntity()->label();
  }

  public static function bundleFieldDefinitions(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
    $fields = [];
    $pr_type = \Drupal::entityTypeManager()->getStorage('cfp_payment_request_type')->load($bundle);
    if ($pr_type) {
      $settings = $base_field_definitions['items']->getSettings();
      $fields['items'] = clone $base_field_definitions['items'];
      $settings['handler_settings']['target_bundles'] = [$pr_type->get('payment_request_item_type') => $pr_type->get('payment_request_item_type')];
      $fields['items']->setSettings($settings);

      $settings = $base_field_definitions['invoices']->getSettings();
      $fields['invoices'] = clone $base_field_definitions['invoices'];
      $settings['handler_settings']['target_bundles'] = [$pr_type->get('payment_request_invoice_type') => $pr_type->get('payment_request_invoice_type')];
      $fields['invoices']->setSettings($settings);
    }
    return $fields;
  }

  /**
   * Returns checklist that was before given checklist.
   *
   * @param \Drupal\cfp_payment_request\Entity\CfpPaymentRequestChecklist $payment_request_checklist
   */
  public function getPreviousChecklist(CfpPaymentRequestChecklist $payment_request_checklist) {
    $current_entity = NULL;
    foreach ($this->get('checklist') as $item) {
      if ($looping_payment_request_checklist = $item->entity) {
        if ($looping_payment_request_checklist->id() == $payment_request_checklist->id()) {
          return $current_entity;
        }
        $current_entity = $looping_payment_request_checklist;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    // Add the published field.
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Payment request entity.'))
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Kifizetési Igénylés sorszáma'))
      ->setDescription(t('The name of the Payment request entity.'))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['item_pay_off_total'] = BaseFieldDefinition::create('integer')
      ->setLabel('Igényelt elszámolási összeg (Ft)')
      ->setSetting('size', 'big')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['item_support_total'] = BaseFieldDefinition::create('integer')
      ->setLabel('Igényelt támogatási összeg (Ft)')
      ->setSetting('size', 'big')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields_definitions = isolate_numeric_field_types('cfp_payment_request_item');
    foreach (static::ADD_UP_FIELDS as $add_up_field) {
      $field_name = $add_up_field . '_total';
      if (!isset($fields[$field_name])) {
        $fields[$field_name] = self::createAddUpFieldFromFieldDefinition($fields_definitions[$add_up_field]);
      }
    }

    $fields['item_pay_off_computed_total']->setInitialValueFromField('item_pay_off_total');
    $fields['item_support_computed_total']->setInitialValueFromField('item_support_total');

    $fields['computed_amount_dedicated_to_ap'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Amount dedicated to advance payment'))
      ->setClass('\Drupal\cfp_payment_request\Plugin\Field\AmountDedicatedToAP')
      ->setComputed(TRUE)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['amount_dedicated_to_ap'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Amount dedicated to advance payment'))
      ->setSetting('size', 'big')
      ->setReadOnly(TRUE);

    $fields['amount_to_pay'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Amount to pay'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\cfp_payment_request\Plugin\Field\PrAmountToPayItemList')
      ->setSetting('size', 'big')
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['items'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Items'))
      ->setSetting('target_type', 'cfp_payment_request_item')
      ->setSetting('handler', 'default')
      ->setSetting('handler_settings', [
        'target_bundles' => [],
      ])
      ->setClass('\Drupal\cfp_payment_request\Plugin\Field\FieldType\PRFieldItemList')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['items_approvement_closed'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Items approvement closed'))
      ->setReadOnly(TRUE);

    $fields['invoices'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Invoices'))
      ->setSetting('target_type', 'pr_invoice')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['checklist'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Checklist'))
      ->setSetting('target_type', 'cfp_payment_request_checklist')
      ->setSetting('handler', 'default')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['state'] = BaseFieldDefinition::create('state')
      ->setLabel(t('State'))
      ->setSetting('max_length', 255)
      ->setDefaultValue('open_state')
      ->setSetting('workflow', 'payment_request')
      ->setDisplayConfigurable('view', TRUE);

    $fields['comment'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Comment'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['justification'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Justification'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['reopen_instructions'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Reopen instructions'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['previous_reopen_instructions'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Previous reopening instructions'))
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('view', TRUE);

    $fields['closed_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Closed date'))
      ->setDisplayConfigurable('view', TRUE);

    $fields['submission_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Last submission date'))
      ->setComputed(TRUE)
      ->setSettings([
        'state' => 'sent',
        'search_for' => TransitionDateSearchItemList::SEARCH_LAST,
        'field_name' => 'transition_history',
      ])
      ->setClass('\Drupal\halo_transition_history_field\Plugin\Field\TransitionDateSearchItemList')
      ->setDisplayConfigurable('view', TRUE);

    $fields['first_submission_date'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('First submission date'))
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['current_correction'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('Current correction'))
      ->setDefaultValue(0)
      ->setReadOnly(TRUE);

    $fields['correction_data'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel('Correction data')
      ->setSetting('target_type', 'correction_data')
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('view', TRUE);

    $fields['old_prints'] = BaseFieldDefinition::create('file')
      ->setLabel(t('Older prints'))
      ->setSettings([
        'file_directory' => 'payment_request/new/print_files',
        'max_filesize' => '100 MB',
        'file_extensions' => 'pdf',
        'description_field' => TRUE,
        'uri_scheme' => 'public',
      ])
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
      ->setDisplayConfigurable('view', TRUE);

    $fields['date_of_completion'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Date of completion'))
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['statements_accepted'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Statements'))
      ->setReadOnly(TRUE)
      ->setDefaultValue(FALSE);

    $fields['attached_documents'] = BaseFieldDefinition::create('file')
      ->setLabel(t('Documents attached by an administrator'))
      ->setSettings([
        'file_directory' => 'pr_attached_files',
        'max_filesize' => '100 MB',
        'file_extensions' => 'pdf png jpg doc docx xls xlsx',
        'description_field' => TRUE,
        'uri_scheme' => 'public',
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['suspended_documents'] = BaseFieldDefinition::create('file')
      ->setLabel(t('Suspended documents'))
      ->setSettings([
        'file_directory' => 'payment_request/suspended_documents',
        'max_filesize' => '100 MB',
        'file_extensions' => 'doc docx jpeg jpg png pdf',
        'description_field' => TRUE,
        'uri_scheme' => 'public',
      ])
      ->setDescription(t('Documents attached during suspension'))
      ->setDisplayConfigurable('view', TRUE)
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED);

    $fields['transition_history'] = BaseFieldDefinition::create('transition_history')
      ->setLabel(t('Transition History'))
      ->setSetting('state_field', 'state')
      ->setReadOnly(TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED);

    $fields['status']->setDescription(t('A boolean indicating whether the Payment request is published.'));

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    $fields['correction_deadline'] = BaseFieldDefinition::create('timestamp')
      ->setLabel(t('Correction deadline'))
      ->setDescription(t('Deadline for submitting PR correction'))
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

  /**
   * Create add up field form definition.
   */
  protected static function createAddUpFieldFromFieldDefinition(FieldDefinitionInterface $field_definition) {
    return BaseFieldDefinition::create($field_definition->getType())
      ->setLabel($field_definition->getLabel() . ' ' . t('total'))
      ->setSettings($field_definition->getSettings())
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
  }

}
<?php

/**
 * @file
 * Contains halo_views_2.module.
 */

use Drupal\cfp_modification_request\Entity\CfpModificationRequest;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\user\Entity\User;

module_load_include('inc', 'halo_front_page', 'halo_front_page.views');

/**
 * Implements hook_toolbar().
 */
function halo_front_page_toolbar() {
  return [
    'admin_front_page_link' => [
      '#type' => 'toolbar_item',
      'tab' => [
        '#type' => 'link',
        '#title' => t('Admin front page'),
        '#url' => Url::fromRoute('halo_front_page.admin_front_page'),
      ],
      '#weight' => -5,
    ],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function halo_front_page_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Cfp state.
  if (in_array($form['#id'], [
    'views-exposed-form-cfp-page-1',
    'views-exposed-form-cfp-page-2',
    'views-exposed-form-cfp-page-3',
    'views-exposed-form-ced-main-data-page-1',
    'views-exposed-form-cfp-modification-requests-page-1',
  ])) {
    $workflow_manager = \Drupal::service('plugin.manager.workflow');
    $workflow = $workflow_manager->createInstance('cfp');
    $states = $workflow->getStates();
    $states = array_map(function ($state) {
      return $state->getLabel();
    }, $states);
    $form['state'] = [
      '#type' => 'select',
      '#options' => [
        '' => t('- Any -'),
      ] + $states,
      '#default_value' => reset($states),
    ];

    $entity_field_manager = \Drupal::service('entity_field.manager');
    $fields = $entity_field_manager->getFieldStorageDefinitions('cfp');
    $sub_state_options = options_allowed_values($fields['sub_state']);
    unset($sub_state_options['void_sub_state']);
    $form['sub_state'] = [
      '#title' => t('Sub state'),
      '#type' => 'select',
      '#options' => [
        '' => t('- Any -'),
      ] + $sub_state_options,
    ];
  }

  if ($form['#id'] === 'views-exposed-form-payment-requests-page-1') {
    $workflow_manager = \Drupal::service('plugin.manager.workflow');
    $workflow = $workflow_manager->createInstance('payment_request');
    $states = $workflow->getStates();
    $states = array_map(function ($state) {
      return $state->getLabel();
    }, $states);

    $form['state'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $states,
    ];

    $form['state'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $states,
    ];
    $entity_field_manager = \Drupal::service('entity_field.manager');
    $fields = $entity_field_manager->getFieldStorageDefinitions('cfp');
    $form['location_check_state'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $fields['location_check_state']->getSetting('allowed_values'),
    ];
    $form['location_check_type'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $fields['location_check_type']->getSetting('allowed_values'),
    ];
  }

  if ($form['#id'] === 'views-exposed-form-locations-halo-page-1') {
    if (!isset($entity_field_manager)) {
      $entity_field_manager = \Drupal::service('entity_field.manager');
    }
    $fields = $entity_field_manager->getFieldStorageDefinitions('cfp');
    $form['location_check_state'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $fields['location_check_state']->getSetting('allowed_values'),
    ];
    $form['location_check_type'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $fields['location_check_type']->getSetting('allowed_values'),
    ];
  }

  if ($form['#id'] === 'views-exposed-form-advance-payment-page-1') {
    $workflow_manager = \Drupal::service('plugin.manager.workflow');
    $workflow = $workflow_manager->createInstance('advance_payment');
    $states = $workflow->getStates();
    $states = array_map(function ($state) {
      return $state->getLabel();
    }, $states);
    $form['state'] = [
      '#type' => 'select',
      '#options' => [
        '' => t('- Any -'),
      ] + $states,
    ];
  }
  if ($form['#id'] === 'views-exposed-form-cfp-modification-requests-page-1') {
    $form['request_type'] = [
      '#type' => 'select',
      '#options' => [
        '' => t('- Any -'),
      ] + _request_type_callback()
    ];
    $form['state_1'] = [
      '#type' => 'select',
      '#options' => [
        '' => t('- Any -'),
      ] + CfpModificationRequest::getStates(),
    ];
  }
  if ($form['#id'] === 'views-exposed-form-technical-report-page-1') {
    $workflow_manager = \Drupal::service('plugin.manager.workflow');
    $workflow = $workflow_manager->createInstance('technical_report');
    $states = $workflow->getStates();
    $states = array_map(function ($state) {
      return $state->getLabel();
    }, $states);
    $form['state']  = $form['transition_history_to'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + $states
    ];
  }

  // First submission date.
  if (in_array($form['#id'], ['views-exposed-form-payment-requests-page-1', 'views-exposed-form-technical-report-page-1', 'views-exposed-form-advance-payment-page-1'])) {
    $form['first_submission_date_wrapper']['first_submission_date']['min']['#type'] = 'date';
    $form['first_submission_date_wrapper']['first_submission_date']['min']['#title'] = '-tól';
    $form['first_submission_date_wrapper']['first_submission_date']['max']['#type'] = 'date';
    $form['first_submission_date_wrapper']['first_submission_date']['max']['#title'] = '-ig';
//    if (isset($form['correction_deadline_wrapper'])) {
//      $form['correction_deadline_wrapper']['correction_deadline']['min']['#type'] = 'date';
//      $form['correction_deadline_wrapper']['correction_deadline']['min']['#title'] = '-tól';
//      $form['correction_deadline_wrapper']['correction_deadline']['max']['#type'] = 'date';
//      $form['correction_deadline_wrapper']['correction_deadline']['max']['#title'] = '-ig';
//    }
    if (isset($form['deadline_expired_wrapper'])) {
      $form['deadline_expired_wrapper']['deadline_expired']['min']['#type'] = 'date';
      $form['deadline_expired_wrapper']['deadline_expired']['min']['#title'] = '-tól';
      $form['deadline_expired_wrapper']['deadline_expired']['max']['#type'] = 'date';
      $form['deadline_expired_wrapper']['deadline_expired']['max']['#title'] = '-ig';
    }
  }

  if ($form['#id'] === 'views-exposed-form-applicants-page-1') {
    $form['cfp_type_group_owner_value'] = [
      '#type' => 'select',
      '#options' => [
          '' => t('- Any -'),
        ] + _cfp_group_types(),
    ];
  }


  if ($form['#id'] === 'views-exposed-form-locations-page-1') {
    $form['closed']['#options'][1] = t('Closed');
    $form['closed']['#options'][0] = t('Open');
    $form['date']['#type'] = 'date';
    $form['date_1']['#type'] = 'date';
  }
}

/**
 * Implements hook_link_alter().
 */
function halo_front_page_link_alter(&$variables) {
  $url = $variables['url'];
  if ($url->isExternal() || !$url->isRouted()) {
    return;
  }

  $route = $url->getRouteName();
  if ($route === 'user.page') {
    $variables['text'] = \Drupal::currentUser()->getDisplayName();
  }
}

/**
 * Implements hook_user_format_name_alter().
 */
function halo_front_page_user_format_name_alter(&$name, AccountInterface $account) {
  $user = User::load($account->id());
  $name = $user->field_lastname->value . ' ' . $user->field_firstname->value;
}

/**
 * Implements hook_views_data_alter().
 */
function halo_front_page_views_data_alter(array &$data) {
  $data['review']['assignable_filter'] = [
    'title' => t('Assignable filter'),
    'filter' => [
      'title' => t('Assignable filter'),
      'help' => t('Filters by assignable entities.'),
      'field' => 'id',
      'id' => 'assignable_filter',
    ],
  ];
}
<?php

namespace Drupal\cfp_payment_request\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\views\Plugin\views\filter\FilterPluginBase;

/**
 * Filter PR view by correction deadline date.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("pr_correction_deadline")
 */
class PaymentRequestCorrectionDeadlineFilter extends FilterPluginBase {

  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function acceptExposedInput($input) {
    return TRUE;
  }

  /**
   * {@inheritDoc}
   */
  public function buildExposedForm(&$form, FormStateInterface $form_state) {
    if (empty($this->options['exposed'])) {
      return;
    }

    $identifier = $this->options['expose']['identifier'];
    $exposed_input = $this->view->getExposedInput();

    $form[$identifier] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Correction deadline'),
    ];
    $form[$identifier]['start_date'] = [
      '#type' => 'date',
      '#title' => $this->t('Start date'),
      '#default_value' => $exposed_input['start_date'] ?? NULL,
    ];
    $form[$identifier]['end_date'] = [
      '#type' => 'date',
      '#title' => $this->t('End date'),
      '#default_value' => $exposed_input['end_date'] ?? NULL,
    ];

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function query() {
    $this->ensureMyTable();

    /** @var \Drupal\views\Plugin\views\query\Sql $query */
    $query = $this->query;

    $query->addTable("cfp_payment_request__transition_history");
    $input = $this->view->getExposedInput();
    $start = isset($input['start_date']) ? strtotime($input['start_date']) : NULL;
    if ($start) {
      $query->addWhere($this->options['group'], "cfp_payment_request__transition_history.transition_history_deadline", $start, ">=");
    }
    $end = isset($input['end_date']) ? strtotime($input['end_date']) : NULL;
    if ($end) {
      $query->addWhere($this->options['group'], "cfp_payment_request__transition_history.transition_history_deadline", $end, "<=");
    }
  }

}
<?php

namespace Drupal\cfp_payment_request\Entity;

use Drupal\views\EntityViewsData;

/**
 * Provides Views data for Payment request entities.
 */
class PaymentRequestViewsData extends EntityViewsData {

  /**
   * {@inheritdoc}
   */
  public function getViewsData() {
    $data = parent::getViewsData();
    $data['cfp_payment_request']['correction_deadline']['filter']['id'] = 'pr_correction_deadline';
    return $data;
  }

}
<?php

namespace Drupal\pos_entity_cfp\Plugin;

use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\pos_entity_cfp\Form\CorrectionTextForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Base class for Cfp correction type plugins.
 */
abstract class CfpCorrectionTypeBase extends PluginBase implements CfpCorrectionTypeInterface, ContainerFactoryPluginInterface {

  use StringTranslationTrait;

  /**
   * Form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * State to handle.
   *
   * @var string
   */
  protected $correctionState;

  /**
   * Correction order.
   *
   * @var int
   */
  protected $correctionOrder;

  /**
   * Cfp to handle.
   *
   * @var \Drupal\pos_entity_cfp\Entity\Cfp
   */
  protected $cfp;

  /**
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, AccountProxyInterface $account_proxy, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->correctionState = $configuration['correctionState'];
    $this->cfp = $configuration['cfp'];
    $this->formBuilder = $form_builder;
    $this->currentUser = $account_proxy;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('form_builder'),
      $container->get('current_user'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCorrectionState() {
    return $this->correctionState;
  }

  /**
   * {@inheritdoc}
   */
  public function getCorrectionOrder() {
    return $this->correctionOrder;
  }

  /**
   * {@inheritdoc}
   */
  public function getCfp() {
    return $this->cfp;
  }

  /**
   * {@inheritdoc}
   */
  public function startCorrection() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function endCorrection() {
    return TRUE;
  }

  /**
   * Get correction config form.
   *
   * @return array
   *   Config form.
   */
  public function getCorrectionConfigForm() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function isCorrectionActive() {
    return $this->getCfp()->getState()->getId() === $this->getCorrectionState();
  }

  /**
   * Check if multiple.
   *
   * @return bool
   *   Is multiple.
   */
  public function isMultiple() {
    $definition = $this->getPluginDefinition();
    return isset($definition['multiple']) ? $definition['multiple'] : FALSE;
  }

  /**
   * Get correction text.
   */
  abstract public function getCorrectionText();

  /**
   * Get correction question element.
   */
  public function getCorrectionQuestionElement() {
    return $this->formBuilder->getForm(CorrectionTextForm::class, $this->getCfp(), $this->getCorrectionState(), $this->getPluginId());
  }

  /**
   * Returns if user has access to start correction.
   *
   * @return bool
   *   Returns if user has access to start correction.
   */
  public function userHasAccessToStartCorrection() {
    if ($this->cfp->getState()->getId() !== $this->correctionState) {
      return FALSE;
    }
    if ($this->cfp->isInCorrection()) {
      return FALSE;
    }
    return $this->currentUser->hasPermission('start cfp correction');
  }

  /**
   * Get correction operations form.
   */
  public function getCorrectionOperationsForm() {
    $state_item = $this->getCfp()->getState();
    $current_url = Url::fromRoute('<current>');
    if ($this->getCfp()->getSubState() != 'correction_started') {
      if ($this->userHasAccessToStartCorrection()) {
        $correction_data = $this->getCfp()->getCorrectionData($state_item->getId());
        $element['start_correction'] = [
          '#type' => 'link',
          '#title' => $this->t('Start correction @order', ['@order' => number_to_roman_representation($correction_data['number_of_corrections'] + 1)]),
          '#url' => Url::fromRoute('pos_entity_cfp.confirm_start_correction_user_cfp_form', [
            'cfp' => $this->getCfp()->id(),
            'destination' => $current_url->toString(),
          ]),
          '#attributes' => [
            'class' => ['button'],
          ],
        ];
      }
    }
    else {
      $element['start_correction'] = [
        '#type' => 'markup',
        '#markup' => '<div class="correction-info-text">' . $this->t('Correction is in progress') . '</div>',
      ];
      if ($this->currentUser->hasPermission('access correction form')) {
        $plugin_definition = $this->getCfp()->getCurrentStateCorrectionPlugin()->getPluginDefinition();
        $element['help_correction'] = [
          '#type' => 'link',
          '#title' => $this->t('Help applicant with correction'),
          '#url' => Url::fromRoute($plugin_definition['correction_form_route'], [
            'cfp' => $this->getCfp()->id(),
            'destination' => $current_url->toString(),
          ]),
          '#attributes' => [
            'class' => ['button'],
          ],
        ];
        $element['close_correction'] = [
          '#type' => 'link',
          '#title' => $this->t('Close correction'),
          '#url' => Url::fromRoute('pos_entity_cfp.confirm_correction_user_cfp_form', [
            'cfp' => $this->getCfp()->id(),
            'destination' => $current_url->toString(),
          ]),
          '#attributes' => [
            'class' => ['button'],
          ],
        ];
      }
    }
    return $element ?? [];
  }

  /**
   * Correction answers.
   */
  public function getCorrectionAnswersElement() {
    $correction_data = $this->getCfp()->getCorrectionData($this->getCorrectionState());
    $element = [];
    foreach ($correction_data['info'] as $correction_order => $correction_datum) {
      if (!is_numeric($correction_order)) {
        continue;
      }
      if (isset($correction_datum['started'])) {
        $started_date = DrupalDateTime::createFromTimestamp($correction_datum['started']);
        $started_date->setTimezone(new \DateTimeZone('Europe/Budapest'));
        $element[$correction_order]['started'] = [
          '#type' => 'item',
          '#title' => $this->t('Correction started'),
          '#markup' => $started_date->format('d/m/Y - H:i'),
        ];
      }
      if (isset($correction_datum['ended'])) {
        $ended_date = DrupalDateTime::createFromTimestamp($correction_datum['ended']);
        $ended_date->setTimezone(new \DateTimeZone('Europe/Budapest'));
        $element[$correction_order]['ended'] = [
          '#type' => 'item',
          '#title' => $this->t('Correction ended'),
          '#markup' => $ended_date->format('d/m/Y - H:i'),
        ];
      }
        if (isset($correction_data['info'][$correction_order]['correction_text'])) {
          $element[$correction_order][] = [
            '#type' => 'item',
            // @codingStandardsIgnoreStart
            '#title' => $this->t(ucfirst('correction') . ' text @order', [
              '@order' => number_to_roman_representation($correction_order + 1),
            ]),
            // @codingStandardsIgnoreEnd
            'markup' => ['#markup' => check_markup($correction_data['info'][$correction_order]['correction_text'])],
          ];
        }
        elseif (isset($correction_data['info'][$correction_order]['correction_text'])) {
          $element[$correction_order][] = [
            '#type' => 'item',
            // @codingStandardsIgnoreStart
            '#title' => $this->t(ucfirst('correction') . ' text @order', [
              '@order' => number_to_roman_representation($correction_order + 1),
            ]),
            // @codingStandardsIgnoreEnd
            'markup' => ['#markup' => check_markup($correction_data['info'][$correction_order]['correction_text'])],
          ];
        }


      if (isset($correction_datum['correction_answer_text']) && !empty($correction_datum['correction_answer_text'])) {
        $element[$correction_order]['correction_text'] = [
          '#type' => 'item',
          '#title' => t('Correction answer @order', ['@order' => number_to_roman_representation($correction_order + 1)]),
          '#markup' => check_markup($correction_datum['correction_answer_text']),
        ];
      }
      if (isset($correction_datum['correction_files']) && !empty($correction_datum['correction_files'])) {
        foreach ($correction_datum['correction_files'] as $delta => $fid) {
          $file = File::load($fid);
          $element[$correction_order]['correction_files'][$delta] = [
            '#theme' => 'file_link',
            '#file' => $file,
            '#cache' => [
              'tags' => $file->getCacheTags(),
            ],
          ];
        }
      }
      if (isset($element[$correction_order])) {
        $element[$correction_order]['#type'] = 'fieldset';
        $element[$correction_order]['#title'] = $this->t('Correction @order', ['@order' => number_to_roman_representation($correction_order + 1)]);
      }

      if (isset($correction_datum['started']) && !isset($correction_datum['ended'])) {
        $started_date = DrupalDateTime::createFromTimestamp($correction_datum['started']);
        $started_date->setTimezone(new \DateTimeZone('Europe/Budapest'));
        $now = DrupalDateTime::createFromTimestamp(time());
        $now->setTimezone(new \DateTimeZone('Europe/Budapest'));
        $days_limit = $this->pluginDefinition['correction_limit_in_days'];
        if ($started_date->diff($now)->d > $days_limit) {
          $element[$correction_order]['warning'] = [
            '#type' => 'markup',
            '#markup' => '<p class="correction-warning">' . $this->t('@number_of_days days limit expired!', [
              '@number_of_days' => $days_limit,
            ]) . '</p>',
          ];
        }
      }
    }
    if (!empty($element)) {
      $element['#type'] = 'container';
    }
    return $element;
  }

}
<?php

use Drupal\Core\Entity\EntityTypeInterface;

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function pos_cfp_bundle_2022_01_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'review' && $bundle === 'acceptance_2022_01') {
    $fields['cf_acceptable_application']->addConstraint('ConditionalValues', [
      'conditions' => [
        [
          'required_choice' => 'no',
          'on_values' => [
            'cf_submit_ontime' => ['no'],
            'cf_submit_original_ontime' => ['no'],
            'cf_scanned_application' => ['no'],
            'cf_application_submitt' => ['no'],
            'cf_liquidation_applicant' => ['no'],
            'cf_rpg_registration' => ['no'],
            'cf_anti_labour_protection' => ['no'],
            'cf_disqualification_conditions' => ['no'],
          ],
          'conjunction' => 'OR',
          'error_message' => 'Ukoliko su polja iz prve dve sekcije "Ne", ovo polje mora biti Ne.',
        ],
        [
          'required_choice' => 'yes',
          'on_values' => [
            'cf_submit_ontime' => ['yes'],
            'cf_submit_original_ontime' => ['yes'],
            'cf_scanned_application' => ['yes'],
            'cf_application_submitt' => ['yes'],
            'cf_liquidation_applicant' => ['yes'],
            'cf_rpg_registration' => ['yes'],
            'cf_anti_labour_protection' => ['yes'],
            'cf_disqualification_conditions' => ['yes'],
          ],
          'conjunction' => 'AND',
          'error_message' => 'Ukoliko su sva polja iz prve dve sekcije "Da", ovo polje mora biti Da.',
        ]
      ],
    ]);
  }
}

/**
 * Implements hook_review_passed_alter().
 */
function pos_cfp_bundle_2022_01_review_passed_alter(&$passed, $entity) {
  if ($entity->bundle() === 'technical_review_2022_01') {
    $passed = $entity->isPrintConfirmed();
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function pos_entity_review_form_review_acceptance_2022_01_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['cf_application_identifier'])) {
    $form['cf_application_identifier']['#states'] = [
      'visible' => [
        ':input[name="cf_only_one_request"]' => ['value' => 'no']
      ],
      'required' => [
        ':input[name="cf_only_one_request"]' => ['value' => 'no']
      ]
    ];
  }
  $form['#validate'][] = 'custom_field_validation';
}

function custom_field_validation($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $only_request_field = !empty($form_state->getValue('cf_only_one_request')) ? $form_state->getValue('cf_only_one_request')[0]['value'] : '';
  $cf_application_identifier = $form_state->getValue('cf_application_identifier');
  if ($only_request_field === 'no' && empty($cf_application_identifier[0]['value'])) {
    $form_state->setErrorByName('cf_application_identifier', t('Identifikator aplikacije je obavezan ako je podnosioc zahtjeva podnio više od jednog zahtjeva'));
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function pos_cfp_bundle_2022_01_form_review_legal_check_2022_01_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form_object = $form_state->getFormObject();
  $review = $form_object->getEntity();
  foreach ($review->getFields() as $machine_name => $field) {
    if ($field->getFieldDefinition()->getType() === 'options_correction') {
      if ($review->get($machine_name)->value === 'replacement') {
        $form[$machine_name]['#attributes'] = [
          'class' => ['red_field'],
        ];
      }
    }
  }
}
<?php

namespace Drupal\pos_entity_email_template\Plugin\Action;

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\Settings;
use Drupal\file\Entity\File;

/**
 * Provides a a Send Applicant email action.
 *
 * @Action(
 *   id = "send_applicant_email",
 *   label = @Translation("Send Applicant email"),
 *   type = "user",
 *   category = @Translation("Custom"),
 *   confirm = TRUE
 * )
 *
 * @DCG
 * For a simple updating entity fields consider extending FieldUpdateActionBase.
 */
class SendApplicantEmailAction extends ConfigurableActionBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'title' => '',
      'body' => '',
      'attachment_files' => [],
      ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    //@todo: Check which templates will be available for this kind of e-mails. Maybe create a new type of templates.

    $templates = \Drupal::entityTypeManager()
      ->getStorage('pos_entity_email_template')->loadMultiple();

    $options = ['_none' => $this->t('None')];
    foreach ($templates as $template) {
      $options[$template->id()] = $template->id() . ') ' . $template->label();
    }
    ksort($options, SORT_NUMERIC);

    $form['template'] = [
      '#type' => 'select',
      '#title' => $this->t('Template'),
      '#options' => $options,
      '#ajax' => [
        'callback' => '\Drupal\pos_entity_email_template\Plugin\Action\SendApplicantEmailAction::replaceElements'
      ]
    ];

    $form['title'] = [
      '#title' => $this->t('Title'),
      '#type' => 'textfield',
      '#wrapper_attributes' => [
        'class' => 'mrmot-title',
      ],
    ];

    $form['body'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Body'),
      '#format' => 'ckeditor_5',
      '#wrapper_attributes' => [
        'class' => 'mrmot-body',
      ],
    ];

    $form['attachment_files'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Attachments'),
      '#description' => t('Allowed types: pdf xls xlsx odt doc docx.'),
      '#upload_validators' => [
        'file_validate_extensions' => ['pdf xls xlsx odt doc docx'],
      ],
      '#upload_location' => 'public://email_attachments/',
      '#progress_indicator' => 'bar',
      '#multiple' => TRUE,
      '#wrapper_attributes' => [
        'class' => 'mrmot',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['title'] = $form_state->getValue('title');
    $this->configuration['body'] = $form_state->getValue('body')['value'];
    $this->configuration['file_ids'] = $form_state->getValue('attachment_files');
    foreach ($form_state->getValue('attachment_files') as $fid) {
      $file = File::load($fid);
      $this->configuration['attachments'][] = [
        'filepath' => $file->getFileUri(),
        'filename' => $file->getFilename(),
        'filemime' => $file->getMimeType(),
      ];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function access($node, AccountInterface $account = NULL, $return_as_object = FALSE) {
    return $return_as_object ? AccessResult::allowedIfHasPermission($account, 'send emails from administration') : $account->hasPermission('send emails from administration');
  }

  /**
   * {@inheritdoc}
   */
  public function execute($user = NULL) {
    $params['headers'] = [
      'Content-Type' => 'text/html; charset=UTF-8;',
      'Content-Transfer-Encoding' => '8Bit',
    ];
    /** @var \Drupal\Core\Mail\MailManagerInterface $mail_manager */
    $mail_manager = \Drupal::service('plugin.manager.mail');
    $user_mail = $user->getEmail();
    $emails = [$user_mail];
    $params['title'] = $this->configuration['title'];
    $params['message'] = $this->configuration['body'];
    $params['file_ids'] = $this->configuration['file_ids'];
    $params['attachments'] = $this->configuration['attachments'];
    $params['entity'] = $user;
    $result = $mail_manager->mail('pos_entity_applicant', 'pos_entity_applicant_mail_send', implode(',', $emails), 'hu', $params, NULL, TRUE);
  }

  public static function replaceElements(array &$form, FormStateInterface $form_state) {
    // @todo: Check what kind of templates will be used.
    $triggering_element = $form_state->getTriggeringElement();
    $response = new AjaxResponse();
    /** @var \Drupal\pos_entity_email_template\Entity\EmailTemplateEntity $email_template */
    if (is_numeric($triggering_element['#value'])) {
      $email_template = \Drupal::entityTypeManager()
        ->getStorage('pos_entity_email_template')
        ->load($triggering_element['#value']);
      $form['title']['#value'] = $email_template->getTitle();
      $form['body']['value']['#value'] = $email_template->getBody();

      $form['attachment_files']['#value']['fids'] = array_unique(array_merge($form['attachment_files']['#value']['fids'], $email_template->getAttachmentsInElementFormat()));
      $form['attachment_files']['fids']['#value'] = array_unique(array_merge($form['attachment_files']['fids']['#value'], $email_template->getAttachmentsInElementFormat()));
      foreach ($form['attachment_files']['#value']['fids'] as $fid) {
        $form['attachment_files']['#files'][$fid] = File::load($fid);
      }
      $element = &$form['attachment_files'];
      foreach ($element['#files'] as $delta => $file) {
        $file_link = [
          '#theme' => 'file_link',
          '#file' => $file,
        ];
        if ($element['#multiple']) {
          $element['file_' . $delta]['selected'] = [
            '#type' => 'checkbox',
            '#title' => \Drupal::service('renderer')->renderPlain($file_link),
          ];
        }
        else {
          $element['file_' . $delta]['filename'] = $file_link + ['#weight' => -10];
        }
        // Anonymous users who have uploaded a temporary file need a
        // non-session-based token added so $this->valueCallback() can check
        // that they have permission to use this file on subsequent submissions
        // of the same form (for example, after an Ajax upload or form
        // validation error).
        if ($file->isTemporary() && \Drupal::currentUser()->isAnonymous()) {
          $element['file_' . $delta]['fid_token'] = [
            '#type' => 'hidden',
            '#value' => Crypt::hmacBase64('file-' . $delta, \Drupal::service('private_key')->get() . Settings::getHashSalt()),
          ];
        }
      }
      $form_state->setRebuild(TRUE);
    }
    else {
      $form['title']['#value'] = '';
      $form['body']['value']['#value'] = '';
    }
    $response->addCommand(new RemoveCommand('[id^=edit-body-format]'));
    $response->addCommand(new ReplaceCommand('.mrmot-body', $form['body']));
    $response->addCommand(new ReplaceCommand('.mrmot-title', $form['title']));
    $response->addCommand(new ReplaceCommand('.mrmot', $form['attachment_files']));
    return $response;
  }
}
<?php

/**
 * @file
 * Contains pos_entity_applicant.module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\pos_entity_applicant\Entity\ApplicantType;
use Drupal\pos_entity_applicant\Event\UserCancelEvent;

module_load_include('inc', 'pos_entity_applicant', 'pos_entity_applicant.tokens');
module_load_include('inc','pos_entity_applicant', 'pos_entity_applicant.views');
module_load_include('inc', 'pos_entity_applicant', 'pos_entity_applicant.validation');

/**
 * Implements hook_help().
 */
function pos_entity_applicant_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the pos_entity_applicant module.
    case 'help.page.pos_entity_applicant':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('General Applicant Entity') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_theme().
 */
function pos_entity_applicant_theme() {
  $theme = [];
  $theme['applicant'] = [
    'render element' => 'elements',
    'file' => 'applicant.page.inc',
    'template' => 'applicant',
  ];
  $theme['applicant_content_add_list'] = [
    'render element' => 'content',
    'variables' => ['content' => NULL],
    'file' => 'applicant.page.inc',
  ];
  return $theme;
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function pos_entity_applicant_theme_suggestions_applicant(array $variables) {
  $suggestions = [];
  $entity = $variables['elements']['#applicant'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'applicant__' . $sanitized_view_mode;
  $suggestions[] = 'applicant__' . $entity->bundle();
  $suggestions[] = 'applicant__' . $entity->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'applicant__' . $entity->id();
  $suggestions[] = 'applicant__' . $entity->id() . '__' . $sanitized_view_mode;
  return $suggestions;
}

/**
 * Implements hook_entity_extra_field_info().
 */
function pos_entity_applicant_entity_extra_field_info() {
  $extra = [];
  foreach (ApplicantType::loadMultiple() as $bundle) {
    $extra['applicant'][$bundle->id()]['display']['edit_link'] = [
      'label' => t('Edit link'),
      'description' => 'Entity edit link',
      'weight' => 20,
      'visible' => TRUE,
    ];

    $extra['applicant'][$bundle->id()]['display']['view_link'] = [
      'label' => t('View link'),
      'description' => 'Entity view link',
      'weight' => 20,
      'visible' => TRUE,
    ];

    $extra['applicant'][$bundle->id()]['display']['state_description'] = [
      'label' => t('State description'),
      'description' => 'Shows state description defined in applicant bundle',
      'weight' => 20,
      'visible' => TRUE,
    ];

    $extra['applicant'][$bundle->id()]['display']['locked_button'] = [
      'label' => t('Locked button'),
      'description' => 'Locked',
      'weight' => 20,
      'visible' => TRUE,
    ];

    $extra['applicant'][$bundle->id()]['display']['representative'] = [
      'label' => t('Ovlašteno lice za zastupanje'),
      'description' => t('Ime i prezime predstavnika'),
      'weight' => 20,
      'visible' => FALSE,
    ];
  }
  return $extra;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function pos_entity_applicant_applicant_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('edit_link') && $entity->access('update')) {
    $build['edit_link'] = [
      '#type' => 'link',
      '#title' => t('Edit'),
      '#url' => Url::fromRoute('entity.' . $entity->getEntityTypeId() . '.edit_form', [
        $entity->getEntityTypeId() => $entity->id(),
      ]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('view_link') && $entity->access('view')) {
    $build['view_link'] = [
      '#type' => 'link',
      '#title' => t('View'),
      '#url' => Url::fromRoute('entity.' . $entity->getEntityTypeId() . '.canonical', [
        $entity->getEntityTypeId() => $entity->id(),
      ]),
      '#attributes' => [
        'class' => ['button'],
      ],
    ];
  }
  if ($display->getComponent('state_description')) {
    $applicant_type = ApplicantType::load($entity->bundle());
    if ($description = $applicant_type->getStateDescription($entity->getState())) {
      $build['state_description'] = [
        '#type' => 'inline_template',
        '#template' => '<div class="applicant__state-description">' . $description . '</div>',
      ];
    }
  }
  if ($display->getComponent('locked_button')) {
    if (!$entity->isLocked() && (bool) $entity->get('validation_passed')->value) {
      $build['locked_button'] = [
        '#type' => 'link',
        '#url' => new Url('pos_entity_applicant.applicant_lock_data_confirm', [
          'applicant' => $entity->id(),
        ]),
        '#title' => t('Lock'),
        '#attributes' => [
          'class' => [
            'button',
          ],
        ],
      ];
    }
  }
  if ($display->getComponent('representative') && $entity->get('company_representative')->target_id) {
    $representative = $entity->get('company_representative')->entity;
    $rep_name = $representative->get('field_firstname')->value ?? '';
    $rep_lastname = $representative->get('field_lastname')->value ?? '';
    if ($rep_name === '' && $rep_lastname === '') {

    }
    else {
      $build['representative'] = [
        '#type' => 'container',
        'zastupnik' => [
          '#type' => 'container',
          'label' => [
            '#type' => 'markup',
            '#markup' => t('Ovlašteno lice za zastupanje'),
          ],
          '#attributes' => [
            'class' => ['current_applicant_representative-label'],
          ]
        ],
        'representative' => [
          '#type' => 'markup',
          '#markup' => '<div class="current_applicant_representative-item">' . $rep_lastname . ' ' . $rep_name . '</div>',
        ]
      ];
    }
  }
}

/**
 * Implements hook_cron().
 */
function pos_entity_applicant_cron() {
  $query = \Drupal::database()->query('SELECT applicant.id FROM applicant WHERE applicant.id NOT IN (SELECT applicant FROM users_field_data) ');
  $storage = \Drupal::entityTypeManager()->getStorage('applicant');
  while ($row = $query->fetch()) {
    $company = $storage->load($row->id);
    $company->delete();
  }
}

/**
 * Get applicant bundles.
 *
 * @return array
 *   Applicant bundles.
 */
function get_applicant_bundles() {
  $applicant_types = ApplicantType::loadMultiple();
  $applicant_list = [];
  foreach ($applicant_types as $applicant_type) {
    $applicant_list[$applicant_type->id()] = $applicant_type->label();
  }
  return $applicant_list;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function pos_entity_applicant_form_applicant_company_edit_form_alter(&$form, FormStateInterface $form_state) {
  $form['vat_number_entitled_true']['#states'] = [
    'visible' => [
      ':input[name="entitled_to_vat_refund"]' => ['value' => 'yes']
    ],
  ];
  $form['annual_income']['widget']['#description'] = 'Molimo vas da unesete najmanje podatke za 2021.godinu, ukoliko je vaše pravno lice osnovano prije 31. decembra 2021.';
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function pos_entity_applicant_form_applicant_individual_edit_form_alter(&$form, FormStateInterface $form_state) {
  $form['vat_number_entitled_true']['#states'] = [
    'visible' => [
      ':input[name="entitled_to_vat_refund"]' => ['value' => 'yes']
    ],
  ];
  $form['annual_income']['widget']['#description'] = 'Molimo vas da unesete najmanje podatke za 2021.godinu, ukoliko je vaše gazdinstvo osnovano prije 31. decembra 2021.';
}

/**
 * Implements hook_inline_entity_form_entity_form_alter().
 */
function pos_entity_applicant_inline_entity_form_entity_form_alter(array &$entity_form, FormStateInterface &$form_state) {
  if ($entity_form['#entity']->getEntityTypeId() === 'basic' && $entity_form['#entity']->bundle() === 'owned_other_companies') {
    if (isset($entity_form['cf_vat_number_entitled_true'])) {
      $entity_form['cf_vat_number_entitled_true']['#states'] = [
        'visible' => [
          [
            ':input[name="cf_owners_companies[form][inline_entity_form][entities][0][form][cf_entitled_to_vat_refund]"]' => ['value' => 1],
          ],
          'or',
          [
            ':input[name="cf_owners_companies[form][0][cf_entitled_to_vat_refund]"]' => ['value' => 1],
          ],
        ],
      ];
    }
  }
}

/**
 * Implements hook_views_data().
 */
function pos_entity_applicant_views_data() {
  $data = [];

  $data['views']['applicant_has_cfp'] = [
    'title' => t('Did the applicant start cfp - Custom filter'),
    'filter' => [
      'title' => t('Did the applicant start cfp - Custom filter'),
      'field' => 'id',
      'id' => 'applicant_has_cfp',
    ],
  ];
  $data['views']['applicant_cfp'] = [
    'title' => t('Did the applicant start cfp - NEW Custom filter'),
    'filter' => [
      'title' => t('Did the applicant start cfp - NEW Custom filter'),
      'field' => 'id',
      'id' => 'applicant_cfp'
    ],
  ];

  return $data;
}

/**
 * Implements hook_ENTITY_TYPE_predelete().
 */
function pos_entity_applicant_user_predelete(\Drupal\Core\Entity\EntityInterface $entity) {
  $event = new UserCancelEvent($entity);

  $event_dispatcher = \Drupal::service('event_dispatcher');
  $event_dispatcher->dispatch($event, UserCancelEvent::EVENT_NAME);
}

/**
 * Implements hook_mail().
 */
function pos_entity_applicant_mail($key, &$message, $params) {
  switch($key) {
    case 'pos_entity_applicant_mail_send':
      $mail_sender = \Drupal::config('system.site')->get('mail');
      $message['headers']['From'] = $mail_sender;
      $message['headers']['Sender'] = $mail_sender;
      $message['headers']['Return-Path'] = $mail_sender;
      $message['headers']['Content-Type'] = 'text/html';
      $message['from'] = $mail_sender;
      $message['subject'] = $params['title'];
      /** @var \Drupal\Core\Utility\Token $token */
      $token = \Drupal::service('token');
      /** @var \Drupal\pos_entity_applicant\Entity\Applicant $applicant */
      $applicant = $params['entity']->get('applicant')->entity ?? NULL;
      // Not using this tokens currently, but maybe we will some day in the future.
      $token_data = [
        'applicant' => $applicant,
        'user' => $params['entity'],
      ];
      $message['subject'] = $token->replace($params['title'], $token_data, ['clear' => TRUE]);
      $message['body'][] = $token->replace($params['message'], $token_data, ['clear' => TRUE]);

      $files = [];
      if (isset($params['attachments'])) {
        $message['params']['files'] = $params['attachments'];
        foreach ($params['attachments'] as $file) {
          $files[] = $file['filename'];
        }
      }
      $email_log = \Drupal::entityTypeManager()
        ->getStorage('pos_entity_email_logs')
        ->create([
          'title' => $message['subject'],
          'body' => isset($message['body'][0]) ? $message['body'][0] : '',
        ]);
      $email_log->save();
      break;
  }
}
const session = require('express-session');

const SequelizeStore = require('connect-session-sequelize')(session.Store);

const sess = {
  secret: 'Super secret secret',
  cookie: {},
  resave: false,
  saveUninitialized: true,
  store: new SequelizeStore({
    db: sequelize
  })
};

app.use(session(sess));
<?php

namespace Drupal\maintenance_2020_01\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'Maintenance Documents' formatter.
 *
 * @FieldFormatter(
 *   id = "maintenance_documents",
 *   label = @Translation("Maintenance Documents"),
 *   field_types = {
 *     "file"
 *   }
 * )
 */
class MaintenanceDocumentsFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
      $description = $item->getValue()['description'];
      $file = $item->entity;
      $created_timestamp = $file->get('created')->value;
      $element[$delta] = [
        '#theme' => 'file_link',
        '#file' => $file,
        '#description' => $description . ' (' . \Drupal::service('date.formatter')->format($created_timestamp, 'custom', 'Y.m.d') . ')',
        '#cache' => [
          'tags' => $file->getCacheTags(),
        ],
      ];
    }

    return $element;
  }

}
SELECT
    TABLE_NAME,
    COLUMN_NAME,
    CONSTRAINT_NAME,
    REFERENCED_TABLE_NAME,
    REFERENCED_COLUMN_NAME
FROM
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
    REFERENCED_TABLE_NAME = 'table_name';
$host = '127.0.0.1';
$db   = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
function pos_core_update_9014($sandbox) {
  $user_ids_to_delete = [32, 30, 29, 28, 27, 24, 22, 20, 16, 15, 14, 13];

  // Delete all cfps where the users are going to be deleted.
  \Drupal::database()->delete('cfp')
    ->condition('user_id', $user_ids_to_delete, 'IN')
    ->execute();

  // Delete all applicants associated to the user that is going to be deleted.
  foreach ($user_ids_to_delete as $user_id_to_delete) {
    $user = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load($user_id_to_delete);

    if ($applicant_id = $user->get('applicant')->target_id) {
      \Drupal::database()
        ->delete('applicant')
        ->condition('id', $applicant_id)
        ->execute();
    }
    // Delete users.
    $user->delete();
  }
}
// Ovo ide ispod prethodnog filtera (koji ću verovatno i obrisati).
$data['views']['applicant_cfp'] = [
    'title' => t('Did the applicant start cfp - NEW Custom filter'),
    'filter' => [
      'title' => t('Did the applicant start cfp - NEW Custom filter'),
      'field' => 'id',
      'id' => 'applicant_cfp'
    ],
  ];
<?php

namespace Drupal\pos_entity_applicant\Plugin\views\filter;

use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\filter\FilterPluginBase;
use Symfony\Contracts\Translation\TranslatorTrait;

/**
 * Class ProgramCoordinatorFilter
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("applicant_cfp")
 */
class ApplicantCfpFilter extends FilterPluginBase {

  use TranslatorTrait;

  /**
   * {@inheritDoc}
   */
  public function acceptExposedInput($input) {
    return TRUE;
  }

  public function buildExposedForm(&$form, FormStateInterface $form_state) {
    if (empty($this->options['exposed'])) {
      return;
    }
    $identifier = $this->options['expose']['identifier'];
    $exposed_input = $this->view->getExposedInput();

    $form[$identifier] = [
      '#type' => 'select',
      '#title' => $this->t('Da li aplikant ima konkurs?'),
      '#options' => [
        NULL => $this->t('- Any -'),
        'yes' => $this->t('Da'),
        'no' => $this->t('Ne'),
      ],
      '#default_value' => $exposed_input,
      '#validated' => TRUE,
    ];
    return $form;
  }

  public function query() {
    $this->ensureMyTable();
    /** @var \Drupal\views\Plugin\views\query\Sql $query */
    $query = $this->query;
    $input = $this->view->getExposedInput();

    if (isset($input['applicant_cfp']) && !empty($input['applicant_cfp'])) {
      $input['applicant_cfp'] === 'yes' ?
        $query->addWhereExpression(0,"users_field_data.uid IN (SELECT DISTINCT user_id FROM users_field_data JOIN cfp ON cfp.user_id)")
      : $query->addWhereExpression(0,"users_field_data.uid NOT IN (SELECT DISTINCT user_id FROM users_field_data JOIN cfp ON cfp.user_id)");
    }
  }
}
<?php

//The example selects and prints a specific row.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//This time we use named placeholder (:id) and bindParam.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = :id");
$stm->bindParam(":id", $id, PDO::PARAM_INT);
$stm->execute();

$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In the example, we use bindValue to create a parameterized query. We use question mark placeholder.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "root";
$passwd = "andrea";

$pdo = new PDO($dsn, $user, $passwd);


$id = 12;

//Say this input comes from a user.
$stm = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
$stm->bindValue(1, $id);
$stm->execute();

//The select statement fetches a specific row from the table. We bind the value with bindValue to a question mark placeholder.
$row = $stm->fetch(PDO::FETCH_ASSOC);

echo "Id: " . $row['id'] . PHP_EOL;
echo "Name: " . $row['name'] . PHP_EOL;
echo "Population: " . $row['population'] . PHP_EOL;

?>
<?php

//In this example, we fetch data as an associative array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$stm = $pdo->query("SELECT * FROM countries");

//In the fetchAll method, we use the PDO::FETCH_ASSOC style.
$rows = $stm->fetchAll(PDO::FETCH_ASSOC);

foreach($rows as $row) {

    printf("{$row['id']} {$row['name']} {$row['population']}\n");
}

?>
<?php

//In this code example, we get data in an indexed array.

$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

//We select all data from the countries table.
$stm = $pdo->query("SELECT * FROM countries");

//We pass the PDO:FETCH_NUM style to the fetchAll method.
$rows = $stm->fetchAll(PDO::FETCH_NUM);

//We go over the $rows array and print the fields. The fields are accessed via array indexes.
foreach($rows as $row) {
    printf("$row[0] $row[1] $row[2]\n");
}

?>
<?php
//The code example deletes three rows. It prints the number of affected rows.


$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

$pdo = new PDO($dsn, $user, $passwd);

$id = 12;

//In this SQL statement, we delete rows with ids 1, 2, and 3. The number of deleted rows is stored in the $nrows variable.
$nrows = $pdo->exec("DELETE FROM countries WHERE id IN (1, 2, 3)");

//We print the number of deleted rows.
echo "The statement affected $nrows rows\n";

?>
<?php

//These variables are used to create a connection string to the database. The dsn is the Data Source Name, which contains the information required to connect to the database.
$dsn = "mysql:host=localhost;dbname=mydb";
$user = "user12";
$passwd = "12user";

//A new PDO object is created. We pass the constructor the data source name and the user name and password. The PDO class represents a connection between PHP and a database server.
$pdo = new PDO($dsn, $user, $passwd);

//The query method executes an SQL statement in a single function call. It returns the result set.
$stm = $pdo->query("SELECT VERSION()");

//The PDO statement's fetch method fetches the next row from a result set. In our case it is a version of MySQL.
$version = $stm->fetch();

//The $version is an array; we get its first value.
echo $version[0] . PHP_EOL;

?>
# connection name == any name we can give 
#ex: connection name = Mysql_connection
#connection_method = standard(tcp/ip)
#host name  = localhost , port = 3306
#username = root (for local then only it work)
#password = root (for local server we much give the root as password )
#test connection
[root@mysql-in-servicecloud-consolidated-slave-1 ~]# cat /usr/local/scripts/check_slave_status.py
import commands
import os
import time

for x in range(0, 4):
        status = commands.getoutput("mysql --login-path=statuser -sN -e \"show slave status\"")
#        SLACK_URL="https://hooks.slack.com/services/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"
        SLACK_URL="https://hooks.slack.com/services/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"       

        for row in status.split("\n"):
                SERVER_NAME = "mysql-in-servicecloud-consolidated-slave-01"
                SLACK_MESSAGE = "<!channel> Problem in \`[Azure] "+SERVER_NAME+" \`: "
                Slave_IO_Running = row.split("\t")[10]
                Slave_SQL_Running = row.split("\t")[11]
                Seconds_Behind_Master = row.split("\t")[32]
                if Slave_IO_Running.find("No")!=-1 or Slave_SQL_Running.find("No")!=-1 or int(Seconds_Behind_Master)>5:
                        SLACK_MESSAGE = SLACK_MESSAGE + "\`Slave_SQL_Running: "+Slave_SQL_Running+"\`; \`Slave_IO_Running: "+Slave_IO_Running+"\`; \`Seconds_Behind_Master: "+Seconds_Behind_Master+"\`"
                        os.system("curl -X POST --data \"payload={\'text\':\'"+SLACK_MESSAGE+"\', \'username\':\'gcp-watchman\', \'icon_emoji\':\':bangbang:\'}\" "+SLACK_URL)
                os.system("curl -i -XPOST 'http://gcp-in-int-grafana.onedirect.in:8086/write?db=collectd' --data-binary 'mysql_slave_lag,slave_name='"+SERVER_NAME+"' value='"+Seconds_Behind_Master+"''")
                time.sleep(10);#!/usr/bin/python
mydate=`date +"%m/%d/%Y -%H:%M:%S"`
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
mytime=`date +%T`

USER=anirban
PW=Bose9711
filename="/var/lib/mysql-files/VFS_Ticket_data.csv"


rm -rf "/var/lib/mysql-files/VFS_Ticket_data.csv"
reportname="/tmp/VFS_Ticket_data_$current_time.csv"
mysql -u$USER -p$PW -e"call onedirect.get_export_to_excel_summary(8112,current_timestamp - interval 2 hour,current_timestamp)">/var/lib/mysql-files/VFS_Ticket_data.csv


mv /var/lib/mysql-files/VFS_Ticket_data.csv $reportname
echo " ****TRANSFER START**** "
echo $reportname
azcopy cp "$reportname" "https://prjdwuatadls.dfs.core.windows.net/vfsbiproject?sp=rwle&st=2022-08-05T05:47:28Z&se=2022-09-05T13:47:28Z&spr=https&sv=2021-06-08&sr=c&sig=GuyhDRcueFwQUdtL7%2FQ%2Bq5IdRFnd3QKpud1dusF%2Bu0E%3D"

echo " ****TRANSFER END**** "
mydate=`date +"%m/%d/%Y -%H:%M:%S"`
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
mytime=`date +%T`

USER=anirban
PW=Bose9711
filename="/var/lib/mysql-files/VFS_Ticket_data.csv"


rm -rf "/var/lib/mysql-files/VFS_Ticket_data.csv"
reportname="/tmp/VFS_Ticket_data_$current_time.csv"
mysql -u$USER -p$PW -e"call onedirect.get_export_to_excel_summary(8112,current_timestamp - interval 2 hour,current_timestamp)">/var/lib/mysql-files/VFS_Ticket_data.csv


mv /var/lib/mysql-files/VFS_Ticket_data.csv $reportname
echo " ****TRANSFER START**** "
echo $reportname
azcopy cp "$reportname" "https://prjdwuatadls.dfs.core.windows.net/vfsbiproject?sp=rwle&st=2022-08-05T05:47:28Z&se=2022-09-05T13:47:28Z&spr=https&sv=2021-06-08&sr=c&sig=GuyhDRcueFwQUdtL7%2FQ%2Bq5IdRFnd3QKpud1dusF%2Bu0E%3D"

echo " ****TRANSFER END**** "
services:
  hederavita_core.event_subscriber:
    class: Drupal\hederavita_core\EventSubscriber\OderPlacedSubscriber
    arguments: ['@messenger', '@marketing_tools.google_event_storage', '@path.current']
    tags:
      - { name: event_subscriber }
<?php

namespace Drupal\hederavita_core\EventSubscriber;

use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\marketing_tools\GoogleEventStorage;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Hederavita Core event subscriber.
 */
class OderPlacedSubscriber implements EventSubscriberInterface {

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The marketing tool.
   *
   * @var \Drupal\marketing_tools\GoogleEventStorage
   */
  protected $marketing_tool;

  /**
   * The current path.
   *
   * @var \Drupal\Core\Path\CurrentPathStack
   */
  protected $current_path;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\marketing_tools\GoogleEventStorage $marketing_tool
   *   The marketing tool.
   * @param \Drupal\Core\Path\CurrentPathStack $current_path
   */
  public function __construct(MessengerInterface $messenger, GoogleEventStorage $marketing_tool, CurrentPathStack $current_path) {
    $this->messenger = $messenger;
    $this->marketing_tool = $marketing_tool;
    $this->current_path = $current_path;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    $this->messenger->addStatus(__FUNCTION__);
  }

  /**
   * Kernel response event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
   *   Response event.
   */
  public function onKernelResponse(FilterResponseEvent $event) {
    $this->messenger->addStatus(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [
      'commerce_order.place.pre_transition' => ['addEvent', 50],
    ];
    return $events;
  }

  /**
   * Create google event
   *
   * @return void
   */
  public function addEvent() {
    $path = $this->current_path->getPath();
    $path_parts = explode('/', $path);
    foreach ($path_parts as $path_part) {
      if (is_numeric($path_part)) {
        $order = \Drupal::entityTypeManager()
          ->getStorage('commerce_order')
          ->load($path_part);
      }
    }

    /** @var \Drupal\commerce_order\Entity\Order $order */
    $value = $order->getTotalPrice()->getNumber();
    $order_id = $order->id();

    $this->marketing_tool->addEvent([
      'event'  => 'conversion',
      'sendTo' => 'GTM-PZQ4TQZ',
      'value' => $value,
      'currency' => 'RSD',
      'transaction_id' => $order_id,
    ]);
  }

}
SELECT Id_card, COUNT(Id_card)
FROM user_application_tbl
GROUP BY Id_card
HAVING COUNT(Id_card) > 1
name: Baross core
type: module
description: Baross Core module
package: Custom
core: 8.x
core_version_requirement: ^8 || ^9
<?php

/**
 * Implements hook_install().
 */
function baross_core_install() {
  if (!\Drupal::moduleHandler()->moduleExists('path_alias')) {
    \Drupal::database()->delete('key_value')
      ->condition('name', 'path_alias')
      ->execute();
  }
}

/**
 * Implements hook_update_N().
 */
function baross_core_update_8002(&$sandbox) {
  \Drupal::database()->schema()->dropTable('menu_link_content_revision');
}
<?php

/**
 * @file
 * Contains belmil_product_rating.module.
 */

use Drupal\block\Entity\Block;
use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_product\Entity\ProductType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\RouteMatchInterface;
use \Drupal\user\EntityOwnerInterface;
/**
 * Implements hook_help().
 */
function belmil_product_rating_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the belmil_product_rating module.
    case 'help.page.belmil_product_rating':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('This module provides custom rating functionalities for products.') . '</p>';
      return $output;

    default:
  }

  return '';
}

/**
 * Implements hook_theme().
 */
function belmil_product_rating_theme() {
  return [
    'belmil_product_rating' => [
      'render element' => 'children',
    ],
    'belmil_product_rating_statistics_widget' => [
      'render element' => 'children',
    ]
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function belmil_product_rating_comment_insert(EntityInterface $entity) {
  $userRoles = \Drupal::currentUser()->getRoles();
  if ($entity instanceof EntityOwnerInterface) {
      $ownerEmail = $entity->getOwner()->getEmail();
    if (!in_array('administrator', $userRoles) && $ownerEmail != 'trustami@studiopresent.com') {
      $link = '/comment/' . $entity->id() . '/edit';
      $body = t('There is new comment on your site') . '<br> <a target="_blank" href="' . $link . '">' . t('Show') . ' </a>';

      // Send mail.
      /** @var \Drupal\Core\Mail\MailManagerInterface $mailManager */
      $mailManager = \Drupal::service('plugin.manager.mail');

      $module = $key = 'belmil_product_rating';
      // Get email from config and remove whitespaces.
      $to = \Drupal::config('system.site')->get('mail');
      $params['subject'] = t('New comment on website');
      $params['body'] = $body;
      $params['format'] = 'text/html';
      $langcode = \Drupal::currentUser()->getPreferredLangcode();

      $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, TRUE);

      // Log result.
      if ($result['result'] != TRUE) {
        $message = t('There was a problem sending your email notification to @email.', ['@email' => $to]);
        \Drupal::logger('mail')->error($message);
      }
      else {
        $message = t('An email notification for new comment has been sent to @email.', ['@email' => $to]);
        \Drupal::logger('mail')->notice($message);
      }
    }
  }
}

/**
 * Implements hook_mail().
 */
function belmil_product_rating_mail($key, &$message, $params) {
  switch ($key) {
    case 'belmil_product_rating':
      $message['subject'] = $params['subject'];
      $message['body'][] = Markup::create($params['body']);
      $message['headers']['Content-Type'] = $params['format'];
      break;
  }
}

/**
 * Implements hook_form_alter().
 */
function belmil_product_rating_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Open details for admin comment approval.
  if ($form_id == "comment_product_comment_form") {
    $form['#validate'][] = 'belmil_product_rating_settings_validate';
    if (isset($form['author'])) {
      $form['author']['#open'] = TRUE;
    }
  }
}

/**
 * Implements hook_form_submit().
 */
function belmil_product_rating_settings_validate(&$form, FormStateInterface $form_state) {
  $uid = \Drupal::currentUser()->id();
  if (empty($form_state->getValue('uid'))) {
    $form['author']['uid']['#value'] = $uid;
    $form['author']['name']['#value'] = 'Anonymous';
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function belmil_product_rating_entity_extra_field_info() {
  $stars_field = [];

  foreach (ProductType::loadMultiple() as $bundle) {
    $stars_field['commerce_product'][$bundle->id()]['display']['trustamiproductreview'] = [
      'label' => t('Trustami product review'),
      'description' => t('A pseudo field to display the Trustami product review block'),
      'weight' => 0,
      'visible' => TRUE,
    ];

    // Define stars field for displaying rating by stars and link to comment section.
    $stars_field['commerce_product'][$bundle->id()]['display']['stars_field'] = [
      'label' => t('Product stars'),
      'description' => t('This is pseudo field for showing stars rating'),
      'visible' => FALSE,
    ];

    // Define statistic widget for rating.
    $stars_field['commerce_product'][$bundle->id()]['display']['stars_widget'] = [
      'label' => t('Stars widget'),
      'description' => t('Stars widget with statistic by marks'),
      'visible' => FALSE,
    ];
  }

  return $stars_field;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 *
 * Add stars field & widget to product view.
 */
function belmil_product_rating_commerce_product_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('trustamiproductreview')) {
    $block = Block::load('trustamiproductreview');
    if ($block) {
      $build['trustamiproductreview'] = $block->getPlugin()->build();
    }
  }

  if ($display->getComponent('stars_field') ||
    $display->getComponent('stars_widget')
  ) {
    /** @var \Drupal\belmil_product_rating\BelmilProductRatingManager $product_rating_manager */
    $product_rating_manager = \Drupal::service('belmil_product_rating.belmil_product_rating_manager');

    $productRating = 0;
    $numOfComments = 0;
    $productsWithSameTagWithComments = [];
    $ratings = [];

    // Get product with same tag which contain comments for default product type.
    if ($entity->bundle() === "default") {
      $tagId = (int) $entity->get('field_tag')->target_id;
      $productsWithSameTagWithComments = $product_rating_manager
        ->getProductsWithSameTagWithComments($tagId);
    }
    // Get comments of single product for universal product type.
    elseif ($entity->bundle() === "universal") {
      $productsWithSameTagWithComments = [$entity->id()];
    }

    // Call get rating function.
    $product_rating_manager->getRating($productsWithSameTagWithComments, $productRating, $numOfComments, $ratings);
    // Prepare stars data - num of stars is fixed to 5.
    $starsData = $product_rating_manager->prepareStarsData(5, $productRating);
  }

  // Render product stars.
  if ($display->getComponent('stars_field')) {
    $build['stars_field'] = [
      '#markup' => \Drupal::theme()->render('belmil_product_rating', [
        'rating' => $productRating,
        'stars' => 5,
        'vote_type' => "fivestar-widget-static-vote",
        'num_of_comments' => $numOfComments,
        'widget' => ['name' => 'fivestar-basic'],
        'stars_data' => $starsData,
        'product_id' => $entity->id(),
      ]),
    ];
  }

  // Render stars statistics widget.
  if ($display->getComponent('stars_widget')) {
    // Render only if there is any comment.
    if (!empty($ratings)) {
      $totalRating = ($productRating / 20 );
      $statistics = $product_rating_manager->getStatisticsRatingData($ratings);
      // Get percentage of each mark.
      foreach ($statistics as $key => $rating) {
        $statistics[$key] = $rating / count($ratings) * 100;
      }

      $build['stars_widget'] = [
        '#markup' => \Drupal::theme()->render('belmil_product_rating_statistics_widget', [
          'ratings' => $statistics,
          'total_rating' => $totalRating,
          'rating' => $productRating,
          'stars' => 5,
          'vote_type' => "fivestar-widget-static-vote",
          'num_of_comments' => $numOfComments,
          'widget' => ['name' => 'fivestar-basic'],
          'stars_data' => $starsData,
          'product_id' => $entity->id(),
        ]),
      ];
    }
  }
}

/**
 * Implements hook_page_attachments().
 */
function belmil_product_rating_page_attachments(array &$page) {
  // Get request and entity.
  $request = \Drupal::request();
  $path = $request->attributes->get('_route_object')->getPath();
  /** @var \Drupal\commerce_product\Entity\ProductInterface $entity */
  $entity = $request->attributes->get('_entity');

  // Check if we are on product view page.
  if (!empty($entity) && $path == "/product/{commerce_product}") {
    // Attach google schema style script.
    /** @var \Drupal\belmil_product_rating\BelmilProductRatingManager $product_rating_manager */
    $product_rating_manager = \Drupal::service('belmil_product_rating.belmil_product_rating_manager');

    $product_rating_manager->attachGoogleSchemaStyleScript($entity, $page);

    // Attach Trustami Comment Widget.
    $referrerMeta = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'referrer',
        'content' => 'strict-origin-when-cross-origin',
      ],
    ];
    $page['#attached']['html_head'][] = [$referrerMeta, 'referrerMeta'];
    // attachTrustamiCommentsWidgetScript($entity, $page);
  }
}

/**
 * Trustami product widget script.
 *
 * @param \Drupal\commerce_product\Entity\ProductInterface $entity
 *   The product entity.
 * @param array $page
 *   The page array.
 */
function attachTrustamiCommentsWidgetScript(ProductInterface $entity, array &$page) {
  $variations = $entity->getVariations();
  $variation = reset($variations);

  if ($variation) {
    $trustamiProductWidgetScript = [
      '#tag' => 'script',
      '#attributes' => [
        'type' => 'text/javascript',
        'id' => 'trustami-product-widget',
        'src' => 'https://cdn.trustami.com/widgetapi/productWidget/trustami-product-widget.js',
        'data-uid' => '601e2fffcc96c5152b8b46de',
        'data-gtin' => $variation->getSku(),
        'data-asin' => $variation->get('field_asin')->value,
        'data-modes' => "[4]",
      ],
      '#value' => '',
    ];

    // Add script to head.
    $page['#attached']['html_head'][] = [
      $trustamiProductWidgetScript,
      'trustamiProductWidgetScript'
    ];
  }
}
<?php

declare(strict_types = 1);

namespace Drupal\enmon_core\Plugin\search_api\processor;

use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;

/**
 * @SearchApiProcessor(
 *   id = "only_special_offer",
 *   label = @Translation("Only special offer"),
 *   description = @Translation("Calculates whether the only special offer is true on all variation"),
 *   stages = {
 *     "add_properties" = 0,
 *   },
 * )
 */
class OnlySpecialOffer extends ProcessorPluginBase {

  /**
   * {@inheritdoc}
   */
  public static function supportsIndex(IndexInterface $index) {
    $supported_entity_types = ['commerce_product'];
    foreach ($index->getDatasources() as $datasource) {
      if (in_array($datasource->getEntityTypeId(), $supported_entity_types)) {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
    $properties = [];

    if (!$datasource) {
      $definition = [
        'label' => $this->t('Only special offers'),
        'description' => $this->t('Whether the product all variation marked with only special offer'),
        'type' => 'boolean',
        'is_list' => TRUE,
        'processor_id' => $this->getPluginId(),
      ];
      $properties['only_special_offers'] = new ProcessorProperty($definition);
    }

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function addFieldValues(ItemInterface $item) {
    $fields = $item->getFields();

    $only_special_offer_fields = $this->getFieldsHelper()
      ->filterForPropertyPath($fields, NULL, 'only_special_offers');

    /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entity_adapter */
    $entity_adapter = $item->getOriginalObject();

    /** @var \Drupal\commerce_product\Entity\Product $product */
    $product = $entity_adapter->getEntity();

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
    foreach ($product->getVariations() as $product_variation) {
      $is_only_special_offer = $product_variation->get('field_only_special_offer')->value;

      foreach ($only_special_offer_fields as $only_special_offer_field) {
        $only_special_offer_field->addValue($is_only_special_offer);
      }
    }
  }

}
/**
 * Implements hook_views_pre_view().
 */
function enmon_core_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() === 'special_offers') {
    $format_values = \Drupal::entityTypeManager()
      ->getStorage('commerce_product_attribute_value')
      ->getQuery()
      ->condition('attribute', 'master_format')
      ->execute();
    $color_values = \Drupal::entityTypeManager()
      ->getStorage('commerce_product_attribute_value')
      ->getQuery()
      ->condition('attribute', 'master_color')
      ->execute();
    $filters = $view->display_handler->getOption('filters');
    if (array_key_exists('attribute_master_format_target_id_1', $filters)) {
      foreach ($format_values as $format_key => $format_value) {
        $filters['attribute_master_format_target_id_1']['value'][$format_key] = $format_value;
      }
    }
    if (array_key_exists('attribute_master_color_target_id_1', $filters)) {
      foreach ($color_values as $color_key => $color_value) {
        $filters['attribute_master_color_target_id_1']['value'][$color_key] = $color_value;
      }
    }
    $view->display_handler->overrideOption('filters', $filters);
  }
}
TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;
select w2.id,w2.value, w.name from workflowstepfieldexecution w2
         inner join workflowstepfield w on w2.workflowstepfield_id = w.id
         where w.name like '%%' AND
        workflowstepexecution_id in
        (select id from workflowstepexecution where workflowdefinitionexecution_id in  (select id from workflowdefinitionexecution
         where workflowexecution_id = (select id from workflowexecution where ordernumber like '%002619%' limit 1)));
select registrationnum,idcpicregistration from professionaldata where id =
(select  professionaldata_id from account where id =
(select senderaccount_id from workflowexecution where ordernumber like '%010598%' limit 1));
select w2.id,w2.value from workflowstepfieldexecution w2
         inner join workflowstepfield w on w2.workflowstepfield_id = w.id
         where w.name like '%MATRICULA%' AND
        workflowstepexecution_id in
        (select id from workflowstepexecution where workflowdefinitionexecution_id in  (select id from workflowdefinitionexecution
         where workflowexecution_id = (select id from workflowexecution where ordernumber like '%010598%' limit 1)));
CREATE DATABASE databasename;
CREATE DATABASE databasename;
(function (Drupal) {

  const handleExpand = (element) => {
    const expandElement = element.target.parentElement.querySelector('.to-expand');
    if (expandElement.style.display === "inline") {
      expandElement.style.display = "none";
      element.target.innerHTML = Drupal.t('Read more');
    } else {
      expandElement.style.display = "inline";
      element.target.innerHTML = Drupal.t('Collapse');
    }
  };

  document.querySelectorAll('.expand-link').forEach((element) => {
    element.addEventListener('click', handleExpand);
  });
}) (Drupal);
read_more:
  version: 1.x
  js:
    js/read_more.js: {}
  dependencies:
    - core/drupal
<?php

namespace Drupal\halo_widget_altering\Element;

use Drupal\Core\Render\Element\RenderElement;

/**
 * Provides a render element to display read more text.
 *
 * Properties:
 * - #text: Text to be printed.
 * - #limit_chars: Number of characters to limit.
 *
 * Usage Example:
 * @code
 * $build['read_more'] = [
 *   '#type' => 'correction_value_viewer',
 *   '#entity' => EntityInterface,
 * ];
 * @endcode
 * @RenderElement("read_more")
 */
class ReadMore extends RenderElement {

  /**
   * {@inheritDoc}
   */
  public function getInfo() {
    return [
      '#pre_render' => [
        [get_class($this), 'printText'],
      ],
      '#text' => NULL,
      '#limit_chars' => 250,
    ];
  }



  /**
   * @return
   */
  public static function printText(array $element) {
    $text = $element['#text'];
    $limit_characters = $element['#limit_chars'];

    if (empty($text)) {
      return [];
    }

    if (strlen($text) <= $limit_characters) {
      return [
        'text' => [
          '#type' => 'inline_template',
          '#template' => '{{ value|nl2br }}',
          '#context' => ['value' => $text],
        ],
      ];
    }
    $first_half_text = substr($text, 0, $limit_characters);
    $second_half_text = substr($text, $limit_characters);

    $element['text'] = [
      'text' => [
        '#type' => 'inline_template',
        '#template' => '{{ value1|nl2br }}<span class="to-expand" style="display: none">{{ value2|nl2br }}</span><a class="expand-link">{{ read_more_text }}</a>',
        '#context' => [
          'value1' => $first_half_text,
          'value2' => $second_half_text,
          'read_more_text' => t('Read more'),
        ],
      ],
    ];
    $element['#attached']['library'][] = 'halo_widget_altering/read_more';
    return $element;
  }

}
      $entity_row[] = [
        '#type' => 'read_more',
        '#text' => $entity->get('description')->value,
//        '#limit_chars' => 10,
      ];
    }
<?php
/**
* Implements hook_token_info().
*/
function mycustomtokenmodule_token_info() {
   $type = [
       'name' => t('Custom Token'),
       'description' => t('Tokens for custom things.'),
   ];
   $node['title'] = [
       'name' => t("Node Title"),
       'description' => t('The node\'s title'),
   ];
   $node['dateformat'] = [
       'name' => t("Custom Date Format"),
       'dynamic' => TRUE,
       'description' => t('Show a custom format for the current date'),
   ];
   return [
       'types' => ['customtoken' => $type],
       'tokens' => ['customtoken' => $node],
   ];
}
/**
* Implements hook_tokens().
*/
function mycustomtokenmodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
   $replacements = [];
   
   if ($type == 'customtoken' && !empty($data['node'])) {
       foreach ($tokens as $name => $original) {
           switch ($name) {
               case 'title':
                   $replacements[$original] = $data['node']->getTitle();
               break;
           }
       }
       if ($dateTokens = \Drupal::token()->findWithPrefix($tokens, 'dateformat')) {
           // var_dump($dateTokens)
           // retult: array(1) { ["Y-m-d"]=> string(30) "[customtoken:dateformat:Y-m-d]" }
           foreach ($dateTokens as $format => $original) {
               $replacements[$original] = date($format);
           }
       }
   }
   return $replacements;
}
function change_maintenance_date() {
  //Change the date so the Report date is 2024. 07. 15.
  $cfp = \Drupal::entityTypeManager()->getStorage('cfp')->load(190);
  $cfp->set('maintenance_period', '2021-07-15')->save(); // Ovaj datum je 
}
SELECT entity_id, COUNT(variations_target_id)
FROM `commerce_product__variations`
GROUP BY entity_id
HAVING COUNT(variations_target_id) > 1;
SELECT gender, day, sum(score_points) over (partition by gender order by day) as total FROM Scores 
ORDER BY gender, day
/* AQUI CREARE LA TABLA */
CREATE DATABASE fejesus;

CREATE TABLE leccion (
    id_leccion INT NOT NULL AUTO_INCREMENT, 
    titulo VARCHAR(30),
    instructor VARCHAR(50),
    no_leccion INT,

    PRIMARY KEY(id_leccion),
    INDEX(no_leccion)
    
) ENGINE=INNODB;

DESCRIBE leccion;

CREATE TABLE preguntas (
    id_pregunta INT NOT NULL AUTO_INCREMENT,
    pregunta VARCHAR(200),
    verso VARCHAR(40),
    id_leccion INT NOT NULL,
    id_seccion INT NOT NULL,

    PRIMARY KEY (id_pregunta),
    INDEX(id_leccion),
    INDEX(id_seccion),

    FOREIGN KEY (id_leccion)
        REFERENCES leccion(id_leccion)
        ON UPDATE CASCADE ON DELETE RESTRICT
    
) ENGINE=INNODB;

DESCRIBE preguntas;

CREATE TABLE seccion ( 
    id_seccion INT NOT NULL AUTO_INCREMENT, 
    leccion_id INT NOT NULL, 
    titulo VARCHAR(100), 

    PRIMARY KEY(id_seccion), 
    INDEX (leccion_id), 
        
    FOREIGN KEY (leccion_id) 
        REFERENCES leccion(id_leccion) ON UPDATE CASCADE ON DELETE RESTRICT

) ENGINE=INNODB;

DESCRIBE seccion;
select id from workflowexecution where subject like '%FOZG-069338%';

update workflowexecution set state = 4, cancellationDate=CURRENT_TIMESTAMP where id = 34470;

update workflowdefinitionexecution set state = 4 , cancellationDate=CURRENT_TIMESTAMP where workflowexecution_id = (select id from workflowexecution where id = 34470);

update workflowstepexecution set state = 4 where workflowdefinitionexecution_id in (select id from workflowdefinitionexecution where workflowexecution_id = (select id from workflowexecution where id = 34470));
$data = array(
  	'nazov' => $name,
  	'poznamka' => $poznamka,
  	'user_id' => $user_id,            
  	'date_modify' => date('Y-m-d H:i:s')
);

$this->db->where('ponuka_id',$ponuka_id);
$this->db->update('tsv_ponuky_h',$data);
$select = "SELECT * FROM tsv_sablonah WHERE sablona_id = '".(int)$sablona."'";
        
if($this->db->query($select)->num_rows() > 0 ){
  	return $this->db->query($select)->row();
} else {
  	return '';
}
$data = array(
  'nazov' => $name,
  'poznamka' => $poznamka,
  'user_id' => $user_id,
  'date_added' => date('Y-m-d H:i:s')
);
$this->db->insert('tsv_ponuky_h',$data);

$new_id = $this->db->insert_id();
CREATE TABLE drivers (
 emp_id INT PRIMARY KEY,
  first_name VARCHAR(40),
  last_name VARCHAR(40),
  Age INT,
  sex VARCHAR(1),
  Salary  INT,
  boss_id INT,
  team_id INT
);


CREATE TABLE employee (
  emp_id INT PRIMARY KEY,
  first_name VARCHAR(40),
  last_name VARCHAR(40),
  birth_day DATE,
  sex VARCHAR(1),
  salary INT,
  super_id INT,
  branch_id INT
);

CREATE TABLE team (
  team_id INT PRIMARY KEY,
  team_name VARCHAR(40),
  boss_id INT,
  boss_name VARCHAR(20),
  FOREIGN KEY(boss_id) REFERENCES drivers(driver_id) ON DELETE SET NULL
);


CREATE TABLE team (
  team_id INT PRIMARY KEY,
  team_name VARCHAR(40),
  boss_id INT,
  boss_name VARCHAR(20),
  FOREIGN KEY(boss_id) REFERENCES drivers(driver_id) ON DELETE SET NULL
);








ALTER TABLE drivers33
ADD FOREIGN KEY(team_id)
REFERENCES team(team_id)
ON DELETE SET NULL;

ALTER TABLE drivers33
ADD FOREIGN KEY(boss_id)
REFERENCES drivers(emp_id)
ON DELETE SET NULL;














CREATE TABLE client (
  client_id INT PRIMARY KEY,
  client_name VARCHAR(40),
  branch_id INT,
  FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE SET NULL
);

CREATE TABLE works_with (
  emp_id INT,
  client_id INT,
  total_sales INT,
  PRIMARY KEY(emp_id, client_id),
  FOREIGN KEY(emp_id) REFERENCES employee(emp_id) ON DELETE CASCADE,
  FOREIGN KEY(client_id) REFERENCES client(client_id) ON DELETE CASCADE
);

CREATE TABLE branch_supplier (
  branch_id INT,
  supplier_name VARCHAR(40),
  supply_type VARCHAR(40),
  PRIMARY KEY(branch_id, supplier_name),
  FOREIGN KEY(branch_id) REFERENCES branch(branch_id) ON DELETE CASCADE
);


-- -----------------------------------------------------------------------------

-- Corporate
INSERT INTO employee VALUES(100, 'David', 'Wallace', '1967-11-17', 'M', 250000, NULL, NULL);

INSERT INTO branch VALUES(1, 'Corporate', 100, '2006-02-09');

UPDATE employee
SET branch_id = 1
WHERE emp_id = 100;

INSERT INTO employee VALUES(101, 'Jan', 'Levinson', '1961-05-11', 'F', 110000, 100, 1);

-- Scranton
INSERT INTO employee VALUES(102, 'Michael', 'Scott', '1964-03-15', 'M', 75000, 100, NULL);

INSERT INTO branch VALUES(2, 'Scranton', 102, '1992-04-06');

UPDATE employee
SET branch_id = 2
WHERE emp_id = 102;

INSERT INTO employee VALUES(103, 'Angela', 'Martin', '1971-06-25', 'F', 63000, 102, 2);
INSERT INTO employee VALUES(104, 'Kelly', 'Kapoor', '1980-02-05', 'F', 55000, 102, 2);
INSERT INTO employee VALUES(105, 'Stanley', 'Hudson', '1958-02-19', 'M', 69000, 102, 2);

-- Stamford
INSERT INTO employee VALUES(106, 'Josh', 'Porter', '1969-09-05', 'M', 78000, 100, NULL);

INSERT INTO branch VALUES(3, 'Stamford', 106, '1998-02-13');

UPDATE employee
SET branch_id = 3
WHERE emp_id = 106;

INSERT INTO employee VALUES(107, 'Andy', 'Bernard', '1973-07-22', 'M', 65000, 106, 3);
INSERT INTO employee VALUES(108, 'Jim', 'Halpert', '1978-10-01', 'M', 71000, 106, 3);


-- BRANCH SUPPLIER
INSERT INTO branch_supplier VALUES(2, 'Hammer Mill', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'Uni-ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Patriot Paper', 'Paper');
INSERT INTO branch_supplier VALUES(2, 'J.T. Forms & Labels', 'Custom Forms');
INSERT INTO branch_supplier VALUES(3, 'Uni-ball', 'Writing Utensils');
INSERT INTO branch_supplier VALUES(3, 'Hammer Mill', 'Paper');
INSERT INTO branch_supplier VALUES(3, 'Stamford Lables', 'Custom Forms');

-- CLIENT
INSERT INTO client VALUES(400, 'Dunmore Highschool', 2);
INSERT INTO client VALUES(401, 'Lackawana Country', 2);
INSERT INTO client VALUES(402, 'FedEx', 3);
INSERT INTO client VALUES(403, 'John Daly Law, LLC', 3);
INSERT INTO client VALUES(404, 'Scranton Whitepages', 2);
INSERT INTO client VALUES(405, 'Times Newspaper', 3);
INSERT INTO client VALUES(406, 'FedEx', 2);

-- WORKS_WITH
INSERT INTO works_with VALUES(105, 400, 55000);
INSERT INTO works_with VALUES(102, 401, 267000);
INSERT INTO works_with VALUES(108, 402, 22500);
INSERT INTO works_with VALUES(107, 403, 5000);
INSERT INTO works_with VALUES(108, 403, 12000);
INSERT INTO works_with VALUES(105, 404, 33000);
INSERT INTO works_with VALUES(107, 405, 26000);
INSERT INTO works_with VALUES(102, 406, 15000);
INSERT INTO works_with VALUES(105, 406, 130000);
SELECT table_name ,
  round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;
UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldurl', 'http://www.newurl') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://www.oldurl','http://www.newurl');

UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldurl', 'http://www.newurl');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.oldurl','http://www.newurl');
mysqldump -u root -p -h host_name_or_ip -P port_number --databases db_name --tables tbl_1 tbl_2 > db_name.sql

//to import table
mysql -u -p host_name_or_ip -P port_number database_name < table_name.sql
CREATE DATABASE mydatabase CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
UPDATE wp_options SET option_value = replace(option_value, 'oldurl.com', 'newurl.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'oldurl.com','newurl.com');
UPDATE wp_posts SET post_content = replace(post_content, 'oldurl.com', 'newurl.com');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'oldurl.com','newurl.com');
    mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
    mysql> exit;
    if year < 2020 and not (year == 2019 and quarter == 4):
        query_churn = "SELECT sum(eur) FROM salesforce_summaries WHERE (\"Type of Business\" = 'Churn' AND \"Import from Weekly KPI Excel\" = 'True') AND time >= '{quarter_start}' AND time <= '{quarter_end}'".format(
            quarter_start=quarter_start, quarter_end=quarter_end)
CREATE DEFINER=`rdsadmin`@`localhost` PROCEDURE `rds_set_configuration`(IN name VARCHAR(30), IN value INT)
    READS SQL DATA
    DETERMINISTIC
BEGIN
   DECLARE sql_logging BOOLEAN;

   IF name = 'binlog retention hours' AND value NOT BETWEEN 1 AND 168 THEN
       SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'For binlog retention hours the value must be between 1 and 168 inclusive or be NULL';
   END IF;

   SELECT @@sql_log_bin INTO sql_logging;
   SET @@sql_log_bin = OFF;   
   UPDATE mysql.rds_configuration
   SET mysql.rds_configuration.value = value
   WHERE BINARY mysql.rds_configuration.name = BINARY name;
   SET @@sql_log_bin = sql_logging;
END
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
</dependency>
mysqldump --opt --no-tablespaces --compress -u <username> -p [-h <hostname>] -r <file.sql> <database>
                                                              
mysqldump --opt --no-tablespaces --compress -u <username> -p [-h <hostname>] <database> | gzip > <file.sql.gz>
  
### >= TYPO3 12

vendor/bin/typo3 database:export -c Default -e 'cf_*' -e 'cache_*' -e '[bf]e_sessions' -e sys_log | gzip > <file.sql.gz>

# To ignore tables like fe_users and sys_redirects
# mysqldump --opt --no-tablespaces --compress [--ignore-tables <database>.<table>] [--ignore-tables <database>.<table>] -u <username> -p [-h <hostname>] -r <file> <database>


# mysqldump [--no-tablespaces] --default-character-set=utf8 -e -u $USER -p $DBNAME > /path/to/file.sql
SELECT 
  GROUP_CONCAT(lv SEPARATOR ',')
  #lv
FROM 
  (
    SELECT 
      @pv :=(
        SELECT 
          GROUP_CONCAT(cid SEPARATOR ',') 
        FROM 
          categories 
        WHERE 
          FIND_IN_SET(parent, @pv)
      ) AS lv 
    FROM 
      categories 
      JOIN (
        SELECT 
          @pv := 5
      ) tmp
  ) tmp2
// Custom query that will return the ancestors of a given id, it will
        // return a hierarchical data of parents and children in one query
        // For detailed explanation of the query, please see link below
        // https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/
        $sql = "
            SELECT t2.id, t2.sender_id, t2.invitee_id, t2.deal_admin_id, t2.agent_structure_id, t3.level, t3.sub_level, t3.position_type
            FROM (
                SELECT
                    @r AS _invitee_id,
                    (SELECT @r := sender_id FROM " . $agentInvitationTable . " WHERE invitee_id = _invitee_id AND status = :status LIMIT 1) AS sender_id,
                    @l := @l + 1 AS lvl
                FROM (SELECT @r := :userId, @l := 0) vars, " . $agentInvitationTable . " t
                WHERE @r <> 0
            ) t1
            JOIN " . $agentInvitationTable . " t2 ON t1._invitee_id = t2.invitee_id
            LEFT JOIN  " . $agentStructureTable . " t3 ON t2.agent_structure_id = t3.id
            WHERE t2.status = :status
            ORDER BY t1.lvl DESC;
        ";
sudo docker build . -t vitesse
UPDATE `qm_aktuelle_liste` SET params = JSON_INSERT(params, '$.ohneMangel', 'x') WHERE id <300
CREATE TABLE test ( 
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
);
# If your logged in to mysql (mysql -u root -p) you can create the database
#CREATE DATABASE database_name;
CREATE DATABASE <database> CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';

# The user can be created with
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';

# This user also needs access to the database
GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';

# To make the new access rights available you have to reload them
FLUSH PRIVILEGES;

# In file /etc/my.cnf or /etc/mysql/my.cnf (depending on your operating system), change
# "sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES" or add following

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

# This should take care of the problem. Another way  to change sql_mode directly would be

mysql -u root -p -e „SET GLOBAL sql_mode = ‚NO_ENGINE_SUBSTITUTION‘;“

# But the later option only seems to set the mode temporarely, so I would advise going
# for the my.cnf file.
# /etc/my.cnf
# Raise max size to 4GB
SET GLOBAL tmp_table_size = 1024 * 1024 * 1024 * 4;
SET GLOBAL max_heap_table_size = 1024 * 1024 * 1024 * 4;
# If you are checking the above variables with
SELECT @@max_heap_table_size;
# Or
SHOW VARIABLES LIKE 'max_heap_table_size"

# If already a memory table, the alter will not change anything.
# Only apply the new max size.
ALTER TABLE table_name ENGINE=MEMORY;
select * from externalactivity ea 
join crmcache cc on cc.personid = ea.RecipientPersonID
join person p on p.personid = ea.RecipientPersonID
where ea.successdate is null and externalid = 13342
SELECT ea.externalresponse, ea.recipientpersonid, ea.externalid, ea.customfield01, cc.crmid, concat (cc.firstname, ' ', cc.lastname) FROM externalactivity ea join crmcache cc on cc.crmid = ea.RecipientPersonID WHERE SuccessDate IS NULL
IFNULL(tppp.preferredname, 'WA') AS 'SOR'
FROM person p
JOIN student_program sp ON sp.personid=p.personid AND sp.statusid=1 AND sp.is_deleted=0
JOIN enrollment e ON e.personid=p.personid
JOIN enrollmenttostudentdebit esd USING (enrollmentid)
JOIN studentdebit sd USING (studentdebitid)
LEFT JOIN studentdebit asd ON asd.adjustsdebitid=sd.studentdebitid AND asd.obsolete=0
LEFT JOIN thirdpartypayerengagement tppe ON tppe.tppengagementid=sd.tppengagementid
LEFT JOIN thirdpartypayer tpp ON tpp.tppayerid=tppe.tppayerid
LEFT JOIN person tppp ON tppp.personid=tpp.tppayerpersonid
DELIMITER $$
DROP PROCEDURE IF EXISTS sp_no_math_la$$
CREATE PROCEDURE sp_no_math_la()

BEGIN

...


END $$
DELIMITER ;

CALL sp_no_math_la();
-- these scripts will delete the tables if it's already there

DROP TABLE IF EXISTS StudentEnrollments;
DROP TABLE IF EXISTS Students;
DROP TABLE IF EXISTS Classrooms;


-- create and populate the students table
CREATE TABLE Students
(
	StudentId INTEGER PRIMARY KEY,
	FirstName VARCHAR(200) NOT NULL,
	LastName VARCHAR(200) NOT NULL,
	Nationality VARCHAR(100) NOT NULL,
	DateOfBirth DATETIME NULL
);


INSERT INTO Students
	(StudentId, FirstName, LastName, Nationality, DateOfBirth)
VALUES
	('1','Mickey', 'Mouse', 'American', '1991-05-02'),
	('2','Donald', 'Duck', 'Japanese', '1992-11-12'),
	('3','Goofy', 'Goof', 'American', '1980-04-15'),
	('4','Daisy', 'Duck', 'French', '1985-02-16'),
	('5','Huey', 'Duck', 'French', '1986-05-19'),
	('6','Scrooge', 'McDuck', 'Japanese', '1983-11-11'),
	('7','Minnie', 'Mouse', 'Canadian', '1983-11-30'),
	('8','Louie', 'Duck', 'French', '1985-09-09');

-- create and populate the classroom table
CREATE TABLE Classrooms
(
	ClassroomId INTEGER PRIMARY KEY,
	ClassName VARCHAR(200) NOT NULL,
	Weight DECIMAL NOT NULL
);

INSERT INTO Classrooms
	(ClassroomId, ClassName, Weight)
VALUES
	(1, 'Public Interaction', 0.10),
	(2, 'Pranks', 0.15),
	(3, 'Running', 0.15),
	(4, 'Acting', 0.30),
	(5, 'Making Jokes', 0.30);

-- create and populate the student enrollment table
CREATE TABLE StudentEnrollments
(
	StudentEnrollmentId INTEGER PRIMARY KEY,
	StudentId INTEGER NOT NULL,
	ClassroomId INTEGER NOT NULL,
	Grade DECIMAL NOT NULL,
	FOREIGN KEY(StudentId) REFERENCES Students(StudentId),
	FOREIGN KEY(ClassroomId) REFERENCES Classrooms(ClassroomId)
);

INSERT INTO StudentEnrollments
	(StudentEnrollmentId, StudentId, ClassroomId, Grade)
VALUES
	(1, 1, 1, 91),
	(2, 1, 2, 68),
	(3, 1, 3, 89),
	(4, 1, 4, 60),
	(5, 1, 5, 65),
	(6, 2, 1, 79),
	(7, 2, 2, 85),
	(8, 2, 3, 68),
	(9, 2, 4, 89),
	(10, 2, 5, 80),
	(11, 3, 1, 96),
	(12, 3, 2, 62),
	(13, 3, 3, 78),
	(14, 3, 4, 100),
	(15, 3, 5, 64),
	(16, 4, 1, 81),
	(17, 4, 2, 90),
	(18, 4, 3, 85),
	(19, 4, 4, 95),
	(20, 4, 5, 64),
	(21, 5, 1, 81),
	(22, 5, 2, 73),
	(23, 5, 3, 60),
	(24, 5, 4, 99),
	(25, 5, 5, 70),
	(26, 6, 1, 75),
	(27, 6, 2, 74),
	(28, 6, 3, 69),
	(29, 6, 4, 79),
	(30, 6, 5, 88),
	(31, 7, 1, 60),
	(32, 7, 2, 75),
	(33, 7, 3, 82),
	(34, 7, 4, 66),
	(35, 7, 5, 65),
	(36, 8, 1, 69),
	(37, 8, 2, 81),
	(38, 8, 3, 100),
	(39, 8, 4, 63),
	(40, 8, 5, 62);
CONCAT(',', section_id, ',') REGEXP ',(val1|val2|val3),'"
UPDATE deltadb.transactions_temp
SET ticker =(CASE CEIL(RAND()*2)
              WHEN 1 THEN '3CN:SP'
              WHEN 2 THEN 'AGV:SP'
          END);
SELECT ticker,`datetime`
FROM (
  SELECT ticker, MAX(`datetime`) `datetime`
  FROM Bloomberg_hist_data
  GROUP BY ticker
) t ORDER BY `datetime`
CURRENT_TIMESTAMP	ON UPDATE CURRENT_TIMESTAMP
CREATE TABLE firends (
	id INTEGER,
  	firstname VARCHAR(64)
);
Db::getInstance()->executeS("DELETE FROM product_images WHERE id_product NOT IN (" . join($allProductIds,',') . ")")
SELECT id, account_id, amount, created_at, null as type
 	FROM subscription_invoice
UNION ALL
SELECT id, account_id, amount, created_at, 
	`type` as type
FROM subscription_payment
ORDER BY created_at DESC
ALTER DATABASE database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
sudo killall mysqld
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
[root@jiaoyou mysql]# pwd
/var/lib/mysql
[root@jiaoyou mysql]# ls -ls
338256 -rw-rw---- 1 mysql mysql 346030080 2010-04-22 08:08 ibdata1
626812 -rw-rw---- 1 mysql mysql 641222072 2010-01-26 07:17 mysql-bin.000008
316892 -rw-rw---- 1 mysql mysql 324173772 2010-03-25 12:51 mysql-bin.000009
52724 -rw-rw---- 1 mysql mysql  53931666 2010-04-12 12:13 mysql-bin.000010
10136 -rw-rw---- 1 mysql mysql  10359639 2010-04-22 08:32 mysql-bin.000011

mysql> SHOW BINARY LOGS; 
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000008 | 641222072 | 
| mysql-bin.000009 | 324173772 | 
| mysql-bin.000010 |  53931666 | 
| mysql-bin.000011 |  10360680 | 
+------------------+-----------+


Solution

PURGE BINARY LOGS TO 'mysql-bin.010';
star

Wed Sep 18 2024 19:29:50 GMT+0000 (Coordinated Universal Time) https://admin-junkies.com/threads/regular-backups-and-disaster-recovery-planning.15429/

#bash #backup #mysql #ddbb
star

Mon Sep 09 2024 11:41:18 GMT+0000 (Coordinated Universal Time)

#bsg.rise #mysql #sql
star

Sat Sep 07 2024 05:00:50 GMT+0000 (Coordinated Universal Time)

#bsg.rise #mysql #sql
star

Tue Jul 09 2024 19:29:24 GMT+0000 (Coordinated Universal Time)

#mysql
star

Fri Jun 28 2024 08:03:06 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/cryptocurrency-exchange-script

#html #angular #css #javascript #java #sql #mysql
star

Fri Jun 28 2024 08:00:36 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/cryptocurrency-exchange-script

#html #angular #css #javascript #java #sql #mysql
star

Thu Jun 06 2024 09:48:59 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/cryptocurrency-exchange-script

#html #angular #mysql #php
star

Thu May 16 2024 12:33:51 GMT+0000 (Coordinated Universal Time) https://tophomeworkhelper.com/programming-help.html

#programming #html #css #mysql #python #java
star

Sat May 11 2024 12:48:49 GMT+0000 (Coordinated Universal Time) https://www.alphacodez.com/paxful-clone-script

#html #angular #mysql #php
star

Mon Dec 18 2023 06:33:06 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/

#swift #javascript #kotlin #mysql
star

Fri Oct 20 2023 06:54:16 GMT+0000 (Coordinated Universal Time)

#python #mysql
star

Mon Oct 09 2023 22:50:10 GMT+0000 (Coordinated Universal Time) https://bling2.com/

#json #mysql #react.js #nodejs
star

Wed Oct 04 2023 20:39:58 GMT+0000 (Coordinated Universal Time)

#mysql
star

Fri Sep 29 2023 17:53:14 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/patients-with-a-condition/description/?envType=study-plan-v2&envId=30-days-of-pandas&lang=pythondata

#mysql
star

Fri Sep 29 2023 17:31:04 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/big-countries/?envType

#mysql
star

Fri Sep 29 2023 17:17:33 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/fix-names-in-a-table/?envType=study-plan-v2&envId=30-days-of-pandas&lang=pythondata

#mysql
star

Fri Sep 29 2023 17:06:07 GMT+0000 (Coordinated Universal Time)

#mysql
star

Fri Sep 29 2023 16:51:10 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/big-countries/?envType

#mysql
star

Thu Sep 28 2023 15:42:44 GMT+0000 (Coordinated Universal Time) https://box11.betsrv.com/robots.txt

#mysql
star

Sun Aug 06 2023 20:20:32 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Jul 30 2023 03:49:06 GMT+0000 (Coordinated Universal Time)

#mysql
star

Sat Jul 29 2023 01:33:36 GMT+0000 (Coordinated Universal Time)

#mysql
star

Sat Jul 29 2023 01:11:22 GMT+0000 (Coordinated Universal Time)

#mysql
star

Sat Jul 29 2023 00:32:35 GMT+0000 (Coordinated Universal Time)

#mysql
star

Wed May 10 2023 07:44:09 GMT+0000 (Coordinated Universal Time)

#mysql
star

Sun Apr 02 2023 21:06:53 GMT+0000 (Coordinated Universal Time)

#php #mysql
star

Sun Apr 02 2023 21:05:35 GMT+0000 (Coordinated Universal Time)

#php #mysql
star

Sun Apr 02 2023 21:02:49 GMT+0000 (Coordinated Universal Time)

#php #mysql
star

Sun Apr 02 2023 18:56:09 GMT+0000 (Coordinated Universal Time)

#php #mysql
star

Sun Apr 02 2023 16:52:26 GMT+0000 (Coordinated Universal Time)

#php #mysql
star

Sat Apr 01 2023 08:57:51 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Wed Mar 29 2023 23:57:51 GMT+0000 (Coordinated Universal Time) https://search.brave.com/search?q

#mysql
star

Fri Mar 03 2023 02:59:12 GMT+0000 (Coordinated Universal Time) https://www.open-open.com/code/view/1457829300325

#python #mysql #database #thirdparty
star

Thu Jan 05 2023 12:04:54 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Nov 24 2022 11:12:16 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Nov 24 2022 11:01:54 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Nov 24 2022 11:01:12 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Nov 24 2022 08:02:37 GMT+0000 (Coordinated Universal Time)

#mysql #magicsanta
star

Tue Nov 22 2022 11:39:18 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/blockchain-forking

#b2b #c++ #css #react.js #javascript #mongoshell #mysql #crypto #nft #blockchainfork development
star

Tue Nov 22 2022 11:38:10 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/nft-token-development

#b2b #c++ #css #react.js #javascript #mongoshell #mysql #crypto #nft #nfttoken
star

Tue Nov 22 2022 11:36:30 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/erc20-token-development

#erc20 #b2b #c++ #css #react.js #javascript #mongoshell #mysql #crypto
star

Mon Nov 14 2022 10:46:17 GMT+0000 (Coordinated Universal Time) https://laravel-news.com/duplicate-database-record

#mysql #sql #mariadb
star

Tue Nov 08 2022 12:39:12 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/sql-inner-join-how-to-join-3-tables-in-sql-and-mysql/

#mysql
star

Sun Oct 30 2022 16:19:54 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 30 2022 16:19:19 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 18 2022 22:11:26 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 18 2022 22:11:01 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 18 2022 22:10:39 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Oct 12 2022 21:21:53 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Oct 12 2022 17:53:38 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Oct 10 2022 16:41:42 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 09 2022 13:13:17 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 09 2022 13:11:54 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 09 2022 13:09:06 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 09 2022 13:08:32 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 04 2022 20:05:53 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 04 2022 20:05:24 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Oct 04 2022 17:06:33 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Oct 03 2022 21:44:11 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Oct 03 2022 21:43:15 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Oct 03 2022 21:42:32 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sun Oct 02 2022 21:01:33 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Sat Oct 01 2022 10:53:16 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Sep 29 2022 17:35:11 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Sep 29 2022 17:34:26 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Sep 28 2022 22:08:18 GMT+0000 (Coordinated Universal Time)

#javascript #mysql #sequelize #sessions
star

Fri Sep 16 2022 11:17:18 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Sep 14 2022 14:16:13 GMT+0000 (Coordinated Universal Time)

#mysql
star

Wed Sep 14 2022 13:34:16 GMT+0000 (Coordinated Universal Time) https://phpdelusions.net/pdo

#mysql #bd #pdo #php
star

Tue Sep 13 2022 08:46:33 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Sep 12 2022 17:18:06 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Sep 12 2022 17:17:17 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu Sep 08 2022 09:32:40 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:30:39 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:24:44 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:22:09 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:17:16 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Thu Sep 08 2022 09:13:05 GMT+0000 (Coordinated Universal Time) https://zetcode.com/php/pdo/

#php #mysql #pdo
star

Wed Sep 07 2022 08:10:48 GMT+0000 (Coordinated Universal Time) https://gist.github.com/nextab/6a9b33919ab15e1f59828b4798682dd4

#mysql #sql
star

Mon Sep 05 2022 04:56:57 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Wed Aug 17 2022 05:42:53 GMT+0000 (Coordinated Universal Time)

#bash #mysql #slack
star

Tue Aug 16 2022 15:21:47 GMT+0000 (Coordinated Universal Time)

#bash #mysql
star

Tue Aug 16 2022 15:21:46 GMT+0000 (Coordinated Universal Time)

#bash #mysql
star

Wed Aug 10 2022 10:55:35 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Aug 10 2022 10:55:10 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Fri Aug 05 2022 03:15:02 GMT+0000 (Coordinated Universal Time) https://www.aidication.com/adminer/?username

#mysql #sql
star

Wed Aug 03 2022 10:14:47 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Aug 03 2022 10:14:27 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Aug 02 2022 10:18:11 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Tue Jul 26 2022 12:41:49 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jul 25 2022 20:01:19 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jul 11 2022 15:04:49 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jul 04 2022 20:25:04 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Mon Jul 04 2022 19:02:51 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Mon Jul 04 2022 18:56:51 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Mon Jun 20 2022 14:19:04 GMT+0000 (Coordinated Universal Time)

#mysql
star

Mon Jun 20 2022 14:18:47 GMT+0000 (Coordinated Universal Time)

#mysql
star

Mon Jun 13 2022 20:07:08 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jun 13 2022 20:06:44 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jun 13 2022 19:47:28 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon Jun 13 2022 19:46:54 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed Jun 01 2022 19:07:07 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Thu May 26 2022 14:07:36 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Wed May 25 2022 20:21:32 GMT+0000 (Coordinated Universal Time)

#drupal #mysql
star

Mon May 09 2022 19:58:09 GMT+0000 (Coordinated Universal Time)

#mysql
star

Sun May 01 2022 19:23:49 GMT+0000 (Coordinated Universal Time)

#mysql #sql #scripting
star

Mon Apr 25 2022 18:35:28 GMT+0000 (Coordinated Universal Time)

#sql #mysql
star

Fri Apr 22 2022 18:52:53 GMT+0000 (Coordinated Universal Time)

#ci #mysql #portal
star

Fri Apr 22 2022 18:51:59 GMT+0000 (Coordinated Universal Time)

#ci #mysql #portal
star

Fri Apr 22 2022 18:50:28 GMT+0000 (Coordinated Universal Time)

#ci #mysql #portal
star

Sat Apr 16 2022 22:53:29 GMT+0000 (Coordinated Universal Time)

#mysql
star

Fri Feb 25 2022 12:24:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/136782/convert-from-mysql-datetime-to-another-format-with-php

#php #date #mysql
star

Sat Feb 12 2022 23:13:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/9620198/how-to-get-the-sizes-of-the-tables-of-a-mysql-database

#mysql
star

Thu Jan 27 2022 08:33:32 GMT+0000 (Coordinated Universal Time)

#mysql #mysqldump #remote
star

Fri Jan 21 2022 08:26:17 GMT+0000 (Coordinated Universal Time)

#mysql #mysqldump #remote
star

Wed Dec 22 2021 16:17:30 GMT+0000 (Coordinated Universal Time) https://dba.stackexchange.com/questions/76788/create-a-mysql-database-with-charset-utf-8

#sql #mysql #mysql5.7
star

Thu Dec 09 2021 11:10:27 GMT+0000 (Coordinated Universal Time)

#mysql #wordpress
star

Mon Dec 06 2021 17:34:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23921117/disable-only-full-group-by

#mysql
star

Thu Nov 25 2021 14:40:12 GMT+0000 (Coordinated Universal Time) https://gitlab.hornetsecurity.com/search?group_id

#python #mysql
star

Fri Nov 19 2021 08:45:09 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/aws/comments/gj1i1u/permanently_setting_binlog_retention_period_on/

#mysql #binlog
star

Tue Oct 19 2021 23:21:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/33123985/cannot-load-driver-class-com-mysql-jdbc-driver-spring/33124093

#mysql
star

Mon Oct 04 2021 14:33:05 GMT+0000 (Coordinated Universal Time)

#mysql