commerce_funds-8.x-1.7/commerce_funds.install

commerce_funds.install
<?php

/**
 * @file
 * Install, update and uninstall functions for the commerce_funds module.
 */

use Drupal\Core\Entity\Schema\EntityStorageSchemaInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\commerce_funds\Entity\Transaction;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Implements hook_schema().
 */
function commerce_funds_schema() {
  $schema = [];

  $schema['commerce_funds_user_funds'] = [
    'description' => 'User Funds',
    'fields' => [
      'uid' => [
        'description' => 'The user id of the fund.',
        'type' => 'int',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ],
      'balance' => [
        'description' => 'The balance of the user.',
        'type' => 'blob',
        'serialize' => TRUE,
      ],
    ],
    'primary key' => [
      'uid',
    ],
  ];

  return $schema;
}

/**
 * Implements hook_install().
 */
function commerce_funds_install() {
  // Defines a default admin balance.
  $balance = [];
  // Write admin balance.
  \Drupal::database()->insert('commerce_funds_user_funds')
    ->fields([
      'uid' => 1,
      'balance' => serialize($balance),
    ])
    ->execute();
}

/**
 * Implements hook_uninstall().
 */
function commerce_funds_uninstall() {

  // Restore default mail config.
  $config = \Drupal::configFactory()->getEditable('system.mail');
  $mail_plugins = $config->get('interface');
  if (!in_array('commerce_funds', array_keys($mail_plugins))) {
    return;
  }

  unset($mail_plugins['commerce_funds']);
  $config->set('interface', $mail_plugins)->save();

  // Delete all products and product variations.
  $entity_manager = \Drupal::entityTypeManager();
  $entities = [
    'deposit_product' => $entity_manager->getStorage('commerce_product')->loadByProperties((['type' => 'deposit'])),
    'deposit_product_variation' => $entity_manager->getStorage('commerce_product_variation')->loadByProperties((['type' => 'deposit'])),
    'fee_product' => $entity_manager->getStorage('commerce_product')->loadByProperties((['type' => 'fee'])),
    'fee_product_variation' => $entity_manager->getStorage('commerce_product_variation')->loadByProperties((['type' => 'fee'])),
  ];
  foreach ($entities as $type => $entity) {
    if ($type == 'deposit_product' || $type == 'fee_product') {
      $entity_manager->getStorage('commerce_product')->delete($entity);
    }
    elseif ($type == 'deposit_product_variation' || $type == 'fee_product_variation') {
      $entity_manager->getStorage('commerce_product_variation')->delete($entity);
    }
  }

}

/**
 * Implements hook_update_N().
 *
 * Change transaction notes field to text_long.
 */
function commerce_funds_update_8101() {
  // Reset configuration.
  \Drupal::service('config.installer')->installDefaultConfig('module', 'commerce_funds');

  // Rename old table.
  \Drupal::database()->schema()->renameTable('commerce_funds_transactions', 'commerce_funds_transactions_bkp');
  // Create new schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $entity_type = $manager->getEntityType('commerce_funds_transaction');
  $manager->installEntityType($entity_type);

  $storage_definition = BaseFieldDefinition::create('text_long')
    ->setLabel(t('Notes'))
    ->setDescription(t('Notes of the issuer of the transaction.'))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayOptions('form', [
      'type' => 'text_textarea',
      'weight' => 6,
      'rows' => 6,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayOptions('view', [
      'label' => 'visible',
      'type' => 'text_default',
      'weight' => 6,
    ]);
  $manager->installFieldStorageDefinition('notes', 'commerce_funds_transaction', 'commerce_funds_transaction', $storage_definition);

  // Transfers data into new schema cspell:disable-next-line.
  $old_data = \Drupal::database()->select('commerce_funds_transactions_bkp', 'cftb')->fields('cftb')
    ->execute()
    ->fetchAll();
  foreach ($old_data as $data) {
    Transaction::create([
      'type' => $data->type,
      'issuer' => $data->issuer,
      'recipient' => $data->recipient,
      'method' => $data->method,
      'created' => $data->created,
      'brut_amount' => $data->brut_amount,
      'net_amount' => $data->net_amount,
      'fee' => $data->fee,
      'currency' => $data->currency,
      'from_currency' => $data->from_currency,
      'status' => $data->status,
      'notes' => [
        'value' => $data->notes,
        'format' => 'basic_html',
      ],
    ])->save();
  }
  // Drop old db.
  \Drupal::database()->schema()->dropTable('commerce_funds_transactions_bkp');
}

/**
 * Implements hook_update_N().
 *
 * Restore default email and
 * add new field definition to transaction method and status.
 */
function commerce_funds_update_8102() {
  // Restore default mail system.
  $config = \Drupal::configFactory()->getEditable('system.mail');
  $mail_plugins = $config->get('interface');
  if (in_array('commerce_funds', array_keys($mail_plugins))) {
    unset($mail_plugins['commerce_funds']);
    $config->set('interface', $mail_plugins)->save();
  }

  // No need to apply changes on first install cspell:disable-next-line.
  $transactions = \Drupal::database()->select('commerce_funds_transactions', 'cft')->fields('cft')->range(0, 1)->execute()->fetchAll();
  if (!empty($transactions)) {
    $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
    /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
    $last_installed_schema_repository = \Drupal::service('entity.last_installed_schema.repository');

    $entity_type = $definition_update_manager->getEntityType('commerce_funds_transaction');
    $field_storage_definitions = $last_installed_schema_repository->getLastInstalledFieldStorageDefinitions('commerce_funds_transaction');
    // Update the field storage definition.
    $field_storage_definitions['status']->setRequired(TRUE);
    $field_storage_definitions['status']->setDefaultValue('Completed');

    $field_storage_definitions['method']->setRequired(TRUE);
    $field_storage_definitions['method']->setDefaultValue('internal');
    $definition_update_manager->updateFieldableEntityType($entity_type, $field_storage_definitions);
  }
}

/**
 * Implements hook_update_N().
 *
 * Implements transaction hash.
 * Creates hash for each previous transaction.
 */
function commerce_funds_update_8103(&$sandbox) {
  // Initialize variables on first batch operation.
  if (!isset($sandbox['total'])) {
    $transaction_ids = \Drupal::entityQuery('commerce_funds_transaction')
      ->execute();
    $sandbox['total'] = count($transaction_ids);
    $sandbox['current'] = 0;

    // Update the field storage definition.
    $new_hash_field = BaseFieldDefinition::create('string')
      ->setLabel(t('Hash'))
      ->setDescription(t('Unique transaction hash.'))
      ->setDefaultValueCallback('Drupal\commerce_funds\Entity\Transaction::hashGenerate')
      ->setRequired(TRUE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE);

    \Drupal::entityDefinitionUpdateManager()->installFieldStorageDefinition('hash', 'commerce_funds_transaction', 'commerce_funds_transaction', $new_hash_field);
  }

  // Handles one batch operation.
  $transaction_ids = \Drupal::entityQuery('commerce_funds_transaction')
    ->range($sandbox['current'], $sandbox['current'] + 10)
    ->execute();

  foreach ($transaction_ids as $transaction_id) {
    $transaction = Transaction::load($transaction_id);
    $transaction->setHash(Transaction::hashGenerate());
    $transaction->save();
    $sandbox['current']++;
  }

  // Once $sandbox['#finished'] == 1, the process is complete.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
}

/**
 * Implements hook_update_N().
 *
 * Update field fee with a scale of 3.
 */
function commerce_funds_update_8104(&$sandbox) {
  // Initialize variables on first batch operation.
  if (!isset($sandbox['total'])) {
    $transaction_ids = \Drupal::entityQuery('commerce_funds_transaction')
      ->execute();
    $sandbox['total'] = count($transaction_ids);
    $sandbox['current'] = 0;

    // Rename old table.
    \Drupal::database()->schema()->renameTable('commerce_funds_transactions', 'commerce_funds_transactions_bkp');
    // Create new schema.
    $manager = \Drupal::entityDefinitionUpdateManager();
    $entity_type = $manager->getEntityType('commerce_funds_transaction');
    $manager->installEntityType($entity_type);
  }

  // Transfers data into new schema per batch cspell:disable-next-line.
  $old_data = \Drupal::database()->select('commerce_funds_transactions_bkp', 'cftb')->fields('cftb')
    ->range($sandbox['current'], $sandbox['current'] + 10)
    ->execute()
    ->fetchAllAssoc('transaction_id', PDO::FETCH_ASSOC);
  foreach ($old_data as $data) {
    \Drupal::database()->insert('commerce_funds_transactions')->fields($data)->execute();
    $sandbox['current']++;
  }
  // Once $sandbox['#finished'] == 1, the process is complete.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  if ($sandbox['#finished'] == 1) {
    // Drop old db.
    \Drupal::database()->schema()->dropTable('commerce_funds_transactions_bkp');
  }
}

/**
 * Install mails schema for translations.
 */
function commerce_funds_update_8105() {
  // Backup user funds.
  \Drupal::database()->schema()->renameTable('commerce_funds_user_funds', 'commerce_funds_user_funds_bkp');
  // Store configs for later.
  $config_messages = [
    'mail_transfer_issuer',
    'mail_transfer_recipient',
    'mail_escrow_created_issuer',
    'mail_escrow_created_recipient',
    'mail_escrow_canceled_by_issuer_issuer',
    'mail_escrow_canceled_by_issuer_recipient',
    'mail_escrow_canceled_by_recipient_issuer',
    'mail_escrow_canceled_by_recipient_recipient',
    'mail_escrow_released_issuer',
    'mail_escrow_released_recipient',
    'mail_withdrawal_declined',
    'mail_withdrawal_approved',
  ];
  foreach ($config_messages as $config_message) {
    $configs[$config_message] = \Drupal::config('commerce_funds.settings')->get($config_message);
  }
  // Delete existing schema and install new.
  \Drupal::database()->schema()->dropTable('commerce_funds_user_funds');
  // Restore user funds.
  \Drupal::database()->schema()->renameTable('commerce_funds_user_funds_bkp', 'commerce_funds_user_funds');
  // Restore configs.
  foreach ($configs as $config_name => $config) {
    \Drupal::configFactory()->getEditable('commerce_funds.settings')->set($config_name, $config)->save();
  }
}

/**
 * Reset withdrawal methods schema.
 */
function commerce_funds_update_8106() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('commerce_funds.settings');
  $config->set('withdrawal_methods', $config->get('withdrawal_methods')['methods']);
  $config->save(TRUE);
}

/**
 * Add index on transaction hashes.
 */
function commerce_funds_update_8107(&$sandbox) {
  // Initialize variables on first batch operation.
  if (!isset($sandbox['total'])) {
    $transaction_ids = \Drupal::entityQuery('commerce_funds_transaction')
      ->condition('status', 'Cancelled')
      ->execute();
    $sandbox['total'] = count($transaction_ids) ?: 1;
    $sandbox['current'] = $transaction_ids ? 0 : 1;
    // Update transaction storage schema.
    $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
    $entity_type = $definition_update_manager->getEntityType('commerce_funds_transaction');
    $entity_type->setHandlerClass('storage_schema', 'Drupal\commerce_funds\TransactionStorageSchema');
    $definition_update_manager->updateEntityType($entity_type);
    // Do update schema in db.
    $original = \Drupal::service('entity.last_installed_schema.repository')->getLastInstalledDefinition('commerce_funds_transaction');
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type->id());
    if ($storage instanceof EntityStorageSchemaInterface && $storage->requiresEntityDataMigration($entity_type, $original)) {
      throw new \InvalidArgumentException('The entity schema update for the ' . $entity_type->id() . ' entity type requires a data migration.');
    }
    $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('commerce_funds_transaction');
    $original_field_Storage_definitions = \Drupal::service('entity.last_installed_schema.repository')->getLastInstalledFieldStorageDefinitions('commerce_funds_transaction');
    \Drupal::service('entity_type.listener')->onFieldableEntityTypeUpdate($entity_type, $original, $field_storage_definitions, $original_field_Storage_definitions);
  }
  // Agree on US spelling of "canceled".
  $entity_query = \Drupal::entityQuery('commerce_funds_transaction');
  $entity_query->condition('status', 'Cancelled');
  $entity_query->range($sandbox['current'], $sandbox['current'] + 50);
  $entity_ids = $entity_query->execute();
  foreach ($entity_ids as $transaction_id) {
    $transaction = Transaction::load($transaction_id);
    $transaction->setStatus('Canceled');
    $transaction->save();
    $sandbox['current']++;
  }

  // Once $sandbox['#finished'] == 1, the process is complete.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
}

/**
 * Add transaction field to deposit order.
 */
function commerce_funds_update_8108() {
  // Creates field storage.
  $field_storage = FieldStorageConfig::create([
    'field_name' => 'field_transaction',
    'entity_type' => 'commerce_order',
    'type' => 'entity_reference',
    'cardinality' => 1,
    'settings' => [
      'target_type' => 'commerce_funds_transaction',
    ],
  ]);
  $field_storage->save();
  // Creates field.
  $field = FieldConfig::create([
    'field_storage' => $field_storage,
    'bundle' => 'deposit',
    'label' => t('Transaction'),
  ]);
  $field->save();

  /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
  $display_repository = \Drupal::service('entity_display.repository');

  // Remove field from default form mode.
  $display_repository->getFormDisplay('commerce_order', 'deposit')
    ->removeComponent('field_transaction')
    ->save();

  // Remove field for the 'default' and 'teaser' view modes.
  $display_repository->getViewDisplay('commerce_order', 'deposit')
    ->removeComponent('field_transaction')
    ->save();

}

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

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