You are here

public function Invoice::preSave in Commerce Invoice 8.2

Acts on an entity before the presave hook is invoked.

Used before the entity is saved and before invoking the presave hook. Note that in case of translatable content entities this callback is only fired on their current translation. It is up to the developer to iterate over all translations if needed. This is different from its counterpart in the Field API, FieldItemListInterface::preSave(), which is fired on all field translations automatically. @todo Adjust existing implementations and the documentation according to https://www.drupal.org/node/2577609 to have a consistent API.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

Throws

\Exception When there is a problem that should prevent saving the entity.

Overrides ContentEntityBase::preSave

See also

\Drupal\Core\Field\FieldItemListInterface::preSave()

File

src/Entity/Invoice.php, line 569

Class

Invoice
Defines the invoice entity class.

Namespace

Drupal\commerce_invoice\Entity

Code

public function preSave(EntityStorageInterface $storage) {
  parent::preSave($storage);
  foreach ([
    'store_id',
  ] as $field) {
    if ($this
      ->get($field)
      ->isEmpty()) {
      throw new EntityMalformedException(sprintf('Required invoice field "%s" is empty.', $field));
    }
  }

  // Store the original override language to be able to put it back.
  $original_language = $this
    ->languageManager()
    ->getConfigOverrideLanguage();

  // Store the invoice type data in the invoice data for immutability reasons.
  $fields_whitelist = [
    'paymentTerms',
    'footerText',
    'logo',
  ];
  $fields_whitelist = array_combine($fields_whitelist, $fields_whitelist);

  // The following code is necessary to store the translated invoice type
  // data for each translation.
  foreach ($this
    ->getTranslationLanguages() as $langcode => $language) {
    $translated_invoice = $this
      ->getTranslation($langcode);
    if (!$translated_invoice
      ->getData('invoice_type', FALSE)) {
      $this
        ->languageManager()
        ->setConfigOverrideLanguage($language);
      $invoice_type = InvoiceType::load($this
        ->bundle());
      $invoice_type_data = $invoice_type
        ->toArray();

      // Store in the data array the following invoice type fields.
      $invoice_type_data = array_filter(array_intersect_key($invoice_type_data, $fields_whitelist));
      if ($invoice_type_data) {
        $translated_invoice
          ->setData('invoice_type', $invoice_type_data);
      }
    }
  }
  $this
    ->languageManager()
    ->setConfigOverrideLanguage($original_language);
  $invoice_type = InvoiceType::load($this
    ->bundle());

  // Skip generating an invoice number for draft invoices.
  if ($this
    ->getState()
    ->getId() != 'draft' && empty($this
    ->getInvoiceNumber())) {

    /** @var \Drupal\commerce_number_pattern\Entity\NumberPatternInterface $number_pattern */
    $number_pattern = $invoice_type
      ->getNumberPattern();
    if ($number_pattern) {
      $invoice_number = $number_pattern
        ->getPlugin()
        ->generate($this);
      $this
        ->setInvoiceNumber($invoice_number);
    }
  }
  $customer = $this
    ->getCustomer();

  // The customer has been deleted, clear the reference.
  if ($this
    ->getCustomerId() && $customer
    ->isAnonymous()) {
    $this
      ->setCustomerId(0);
  }

  // Make sure the billing profile is owned by the invoice, not the customer.
  $billing_profile = $this
    ->getBillingProfile();
  if ($billing_profile && $billing_profile
    ->getOwnerId()) {
    $billing_profile
      ->setOwnerId(0);
    $billing_profile
      ->save();
  }
  if (empty($this
    ->getInvoiceDateTime())) {
    $this
      ->setInvoiceDateTime(\Drupal::time()
      ->getRequestTime());
  }

  // Calculate the due date if not set and if configured to do so on the
  // invoice type.
  if ($this
    ->isNew() && empty($this
    ->getDueDateTime()) && !empty($invoice_type
    ->getDueDays())) {
    $invoice_date = DrupalDateTime::createFromTimestamp($this
      ->getInvoiceDateTime());
    $due_date = $invoice_date
      ->modify("+{$invoice_type->getDueDays()} days");
    $this
      ->setDueDateTime($due_date
      ->getTimestamp());
  }

  // When the invoice state is updated, clear the invoice file reference.
  // (A "paid" invoice probably looks different than a "pending" invoice).
  // That'll force the invoice file manager to regenerate an invoice PDF
  // the next time it's called.
  $original_state = isset($this->original) ? $this->original
    ->getState()
    ->getId() : '';
  if ($original_state && $original_state !== $this
    ->getState()
    ->getId() && !empty($this
    ->getFile())) {
    $this
      ->set('invoice_file', NULL);
  }
}