fortnox-8.x-1.x-dev/src/Plugin/ResourceTrait.php

src/Plugin/ResourceTrait.php
<?php

namespace Drupal\fortnox\Plugin;

use Drupal\Component\Plugin\Exception\PluginException;

/**
 * Methods to retrieve complementary resources while creating a resource.
 */
trait ResourceTrait {

  /**
   * Prepares currency select list's options.
   *
   * Makes a request to Fortnox API to get available currencies.
   *
   * @param array $form
   *   The form array.
   * @param string $defaultValue
   *   The default value.
   *
   * @return array
   *   Returns the options array.
   */
  public function createCurrencyFields(array &$form, $defaultValue = '') {
    // This call will retrieve all available currencies.
    $currencies = \Drupal::service('fortnox.client')->makeRequest('GET', 'https://api.fortnox.se/3/currencies/', []);
    // If currencies are found, create the currency field.
    if (!empty($currencies['Currencies'])) {
      $form['Currency'] = [
        '#type' => 'select',
        '#title' => 'Currency',
        '#default_value' => $defaultValue,
      ];
      // Set the unit and rate values of the first element as default values
      // for the actual fields.
      if (isset($currencies['Currencies'][0]['SellRate']) && isset($currencies['Currencies'][0]['Unit'])) {
        $form['CurrencyUnit']['#default_value'] = $currencies['Currencies'][0]['Unit'];
        $form['CurrencyRate']['#default_value'] = $currencies['Currencies'][0]['SellRate'];
      }
      foreach ($currencies['Currencies'] as $currency) {
        if (isset($currency['Code'])) {
          // Set the currency options.
          $form['Currency']['#options'][$currency['Code']] = $currency['Code'];
          // Set the unit and sell rate values for each currency.
          $form['#attached']['drupalSettings'][$currency['Code']]['CurrencyUnit'] = $currency['Unit'];
          $form['#attached']['drupalSettings'][$currency['Code']]['CurrencyRate'] = $currency['SellRate'];
        }
      }
    }
    // Add the library that updates the rate and unit when the currency
    // value is changed.
    $form['#attached']['library'][] = 'fortnox/fortnox_currencies';

    return $form;
  }

  /**
   * Creates a list of options based on the resource type.
   *
   * @param string $resourceID
   *   The resource id.
   * @param string $field
   *   The field that retrieves the resource name.
   * @param array $validate
   *   An array containing the resource's field name as key and field value
   *   as value to validate if the resource option should be added or not.
   * @param array $buildOptions
   *   An array of parameters for the request.
   *
   * @return mixed
   *   The options array.
   */
  public function getDynamicResourceOptions($resourceID, $field, array $validate = [], array $buildOptions = []) {
    $options[''] = $this->t('- None -');

    try {
      $resourcePlugin = \Drupal::service('plugin.manager.resource')->createInstance($resourceID);
      if (is_object($resourcePlugin)) {
        $properties = $resourcePlugin->getResourceDetails();
        if (!isset($buildOptions['limit'])) {
          $buildOptions['limit'] = 500;
        }
        if (!isset($buildOptions['page'])) {
          $buildOptions['page'] = 1;
        }
        else {
          $buildOptions['page']++;
        }
        $response = $resourcePlugin->getResponse($buildOptions);
        if (!empty($response[$properties['id-plural']])) {
          $resources = $response[$properties['id-plural']];
          foreach ($resources as $resource) {
            if ($this->validateResourceOption($validate, $resource)) {
              $options[$resource[$properties['property-name']]] = $resource[$field];
            }
          }
        }
        if (isset($response['MetaInformation'])) {
          $totalPages = $response['MetaInformation']['@TotalPages'];
          if ($totalPages > 1) {
            if ($buildOptions['page'] < $totalPages) {
              $options += $this->getDynamicResourceOptions($resourceID, $field, $validate, $buildOptions);
            }
          }
        }
      }
    }
    catch (PluginException $e) {
      \Drupal::logger('fortnox')->error($e);
    }

    return $options;
  }

  /**
   * Validates (if needed) the option that will be added to the select list.
   *
   * @param array $validate
   *   An array with the field name and the value of the field that has to be
   *   validated. If the array has multiple values, multiple fields will be
   *   validated at once.
   * @param array $resource
   *   The resource to be validated.
   *
   * @return bool
   *   Returns TRUE if it is valid or no validation is needed, FALSE otherwise.
   */
  protected function validateResourceOption(array $validate, array $resource) {
    if (!empty($validate)) {
      foreach ($validate as $key => $value) {
        if (!isset($resource[$key]) || $resource[$key] !== $value) {
          return FALSE;
        }
      }
    }

    return TRUE;
  }

  /**
   * Creates a list of Cause Codes to be used in the select list.
   *
   * @return array
   *   The cause codes array.
   */
  public static function getCauseCodesList() {
    return [
      'ASK' => t('Work injury'),
      'ATF' => t('Shortening of working hours'),
      'FPE' => t('Parental leave'),
      'FRA' => t('Other'),
      'FR1' => t('Other (PAXml)'),
      'HAV' => t('Pregnancy allowance'),
      'KOM' => t('Complete'),
      'MIL' => t('Military service (max 60 days)'),
      'NAR' => t('Related Care'),
      'NÄR' => t('Related Care (PAXml)'),
      'OS1' => t('Sick OB 1'),
      'OS2' => t('Sick OB 2'),
      'OS3' => t('Sick OB 3'),
      'OS4' => t('Sick OB 4'),
      'OS5' => t('Sick OB 5'),
      'PAP' => t('Dad days'),
      'PEM' => t('Permission'),
      'PER' => t('Permitted'),
      'SEM' => t('Semester'),
      'SJK' => t('Sick leave'),
      'SMB' => t('Infect carrier'),
      'SVE' => t('Swedish for immigrants'),
      'TJL' => t('Leave'),
      'UTB' => t('Professional Training'),
      'FAc' => t('Professional Training (PAXml)'),
      'VAB' => t('Children care'),
    ];
  }

  /**
   * Gets a list of options for each select list.
   *
   * @param string $fieldName
   *   The field to retrieve the options for.
   *
   * @return array
   *   The options array.
   */
  public function getSelectListOptions($fieldName) {
    $options = [];
    switch ($fieldName) {
      case 'EmployeeId':
        $options = $this->getDynamicResourceOptions('employees', 'FullName');
        break;

      case 'CauseCode':
        $options = self::getCauseCodesList();
        break;

      case 'Project':
        $options = $this->getDynamicResourceOptions('projects', 'Description');
        break;

      case 'CostCenter':
        $options = $this->getDynamicResourceOptions('cost-centers', 'Description', ['Active' => TRUE]);
        break;

      case 'Currency':
        $options = $this->getDynamicResourceOptions('currencies', 'Description');
        break;

      case 'CustomerNumber':
      case 'ContactPerson':
        $options = $this->getDynamicResourceOptions('customers', 'Name');
        break;

      case 'CostCenterSettings':
      case 'ProjectSettings':
      case 'TransactionInformationSettings':
        $options = self::getSettingsFieldOptions();
        break;

      case 'Year':
        $options = $this->getDynamicResourceOptions('financial-years', 'Id');
        break;

      case 'SupplierNumber':
        $options = $this->getDynamicResourceOptions('suppliers', 'Name');
        break;

      case 'Account':
      case 'AccountNumber':
        $options = $this->getDynamicResourceOptions('accounts', 'Description');
        break;

      case 'ArticleNumber':
        $options = $this->getDynamicResourceOptions('articles', 'Description');
        break;

      case 'SalesType':
        $options = self::getSalesTypesOptions();
        break;

      case 'TemplateNumber':
        $options = $this->getDynamicResourceOptions('contract-templates', 'ContractTemplateName');
        break;

      case 'WayOfDelivery':
        $options = $this->getDynamicResourceOptions('way-of-delivery', 'Description');
        break;

      case 'TermsOfDelivery':
        $options = $this->getDynamicResourceOptions('terms-of-deliveries', 'Description');
        break;

      case 'TermsOfPayment':
        $options = $this->getDynamicResourceOptions('terms-of-payment', 'Description');
        break;

      case 'YourOrderNumber':
        $options = $this->getDynamicResourceOptions('orders', 'DocumentNumber');
        break;

      case 'DiscountType':
        $options = self::getDiscountTypesList();
        break;

      case 'Unit':
        $options = $this->getDynamicResourceOptions('units', 'Description');
        break;

      case 'Language':
        $options = self::getLanguagesOptions();
        break;

      case 'PriceList':
        $options = $this->getDynamicResourceOptions('prices-lists', 'Description');
        break;

      case 'EmploymentForm':
        $options = self::getEmploymentFormsOptions();
        break;

      case 'ForaType':
        $options = self::getForaTypesOptions();
        break;

      case 'PersonelType':
        $options = self::getPersonelTypesOptions();
        break;

      case 'SalaryForm':
        $options = self::getSalaryFormsOptions();
        break;

      case 'ScheduleId':
        $options = [
          '0' => t('0 schedule hourly'),
          'HEL' => t('Heltid'),
        ];
        break;

      case 'TaxAllowance':
        $options = self::getTaxAllowancesOptions();
        break;

      case 'Status':
        $options = self::getStatusOptions();
        break;
    }

    return $options;
  }

  /**
   * Creates a list of static status options.
   *
   * @return array
   *   The options array.
   */
  protected static function getStatusOptions() {
    return [
      'NOTSTARTED' => t('Not Started'),
      'ONGOING' => t('Ongoing'),
      'COMPLETED' => t('Completed'),
    ];
  }

  /**
   * Creates a list of static employment forms options.
   *
   * @return array
   *   The options array.
   */
  protected static function getEmploymentFormsOptions() {
    return [
      'TV' => t('Post with conditional tenure'),
      'PRO' => t('Probationary appointment'),
      'TID' => t('Temporary employment'),
      'VIK' => t('Cover staff'),
      'PRJ' => t('Project employment'),
      'PRA' => t('Work experience'),
      'FER' => t('Holiday work'),
      'SES' => t('Seasonal employment'),
      'NEJ' => t('Not employed'),
    ];
  }

  /**
   * Creates a list of static fora types options.
   *
   * @return array
   *   The options array.
   */
  protected static function getForaTypesOptions() {
    return [
      '-' => t('Not Assigned'),
      'A' => t('Worker'),
      'A3' => t('Workers, Painters'),
      'A91' => t('Worker, Electrician - Installation plant contract'),
      'A92' => t('Worker, Electrician - Power plant contract'),
      'A93' => t('Worker, Electrician - Elektroskandia contract'),
      'A51' => t('Worker, Technology Agreement IF Metall'),
      'A52' => t('Worker, TEKO Agreement'),
      'A53' => t('Worker, Food Production Agreement'),
      'A54' => t('Worker, Tobacco Industry'),
      'A55' => t('Worker, Company agreement for V&S Vin & Spirit AB'),
      'A56' => t('Worker, Coffee Roasters and Spice Factories'),
      'A57' => t('Worker, Construction Materials Industry'),
      'A58' => t('Worker, Bottle Glass Industry'),
      'A59' => t('Worker, Motor Industry Agreement'),
      'A60' => t('Worker, Industry Agreement'),
      'A61' => t('Worker, Leather & Sporting Goods'),
      'A62' => t('Worker, Chemical Factories'),
      'A63' => t('Worker, Glass Industry'),
      'A64' => t('Worker, Common Metals'),
      'A65' => t('Worker, Explosive Materials Industry'),
      'A66' => t('Worker, Allochemical Industry'),
      'A67' => t('Worker, Recycling Company'),
      'A68' => t('Worker, Laundy Industry'),
      'A69' => t('Worker, Quarrying Industry'),
      'A70' => t('Worker, Oil Refineries'),
      'A71' => t('Worker, Sugar Industry (Nordic Sugar AB)'),
      'A72' => t('Worker, IMG Agreement'),
      'A73' => t('Worker, Sawmill Agreement'),
      'A74' => t('Worker, Forestry Agreement'),
      'A75' => t('Worker, Scaling of timber'),
      'A76' => t('Worker, Upholstery Industry'),
      'A77' => t('Worker, Wood Industry'),
      'T' => t('Salaried employee'),
      'T6' => t('Salaried employee, Employed CEO'),
    ];
  }

  /**
   * Creates a list of static tax allowances options.
   *
   * @return array
   *   The options array.
   */
  protected static function getTaxAllowancesOptions() {
    return [
      'HUV' => t('Main employer'),
      'EXT' => t('Extra income or short-time work'),
      'TMP' => t('Short-time work less than one week'),
      'STU' => t('Student without tax deduction'),
      'EJ' => t('Not tax allowance'),
      '???' => t('Unknown tax circumstances'),
    ];
  }

  /**
   * Creates a list of static personel types options.
   *
   * @return array
   *   The options array.
   */
  protected static function getPersonelTypesOptions() {
    return [
      'TJM' => t('Salaried employee'),
      'ARB' => t('Worker'),
    ];
  }

  /**
   * Creates a list of static salary forms options.
   *
   * @return array
   *   The options array.
   */
  protected static function getSalaryFormsOptions() {
    return [
      'MAN' => t('Monthly salary'),
      'TIM' => t('Hourly pay'),
    ];
  }

  /**
   * Creates a list of static field options.
   *
   * @return array
   *   The options array.
   */
  public static function getSettingsFieldOptions() {
    return [
      'ALLOWED' => t('Allowed'),
      'NOTALLOWED' => t('Not Allowed'),
      'MANDATORY' => t('Mandatory'),
    ];
  }

  /**
   * Creates a list of static sales types options.
   *
   * @return array
   *   The options array.
   */
  public static function getSalesTypesOptions() {
    return [
      'STOCK' => 'STOCK',
      'SERVICE' => 'SERVICE',
    ];
  }

  /**
   * Creates a list of static discount types options.
   *
   * @return array
   *   The options array.
   */
  public static function getDiscountTypesList() {
    return [
      'AMOUNT' => t('Amount'),
      'PERCENT' => t('Percent'),
    ];
  }

  /**
   * Creates a list of static languages options.
   *
   * @return array
   *   The options array.
   */
  public static function getLanguagesOptions() {
    return [
      'SV' => t('Swedish'),
      'EN' => t('English'),
    ];
  }

}

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

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