InvoiceStorage.php in Commerce Invoice 8.2
File
src/InvoiceStorage.php
View source
<?php
namespace Drupal\commerce_invoice;
use Drupal\commerce\CommerceContentEntityStorage;
use Drupal\commerce_invoice\Entity\InvoiceInterface;
use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderType;
use Drupal\Core\Entity\EntityInterface;
use Drupal\language\Entity\ContentLanguageSettings;
class InvoiceStorage extends CommerceContentEntityStorage {
protected function invokeHook($hook, EntityInterface $entity) {
if ($hook == 'presave') {
$this
->doInvoicePresave($entity);
}
parent::invokeHook($hook, $entity);
}
protected function doInvoicePresave(InvoiceInterface $invoice) {
$invoice
->recalculateTotalPrice();
$original_paid = isset($invoice->original) ? $invoice->original
->isPaid() : FALSE;
if ($invoice
->isPaid() && !$original_paid) {
$transitions = $invoice
->getState()
->getTransitions();
if (isset($transitions['pay'])) {
$invoice
->getState()
->applyTransitionById('pay');
}
}
}
public function createFromOrder(OrderInterface $order, array $values = []) {
$order_type = OrderType::load($order
->bundle());
$values += [
'type' => $order_type
->getThirdPartySetting('commerce_invoice', 'invoice_type', 'default'),
'state' => 'draft',
'store_id' => $order
->getStoreId(),
'mail' => $order
->getEmail(),
'uid' => $order
->getCustomerId(),
'billing_profile' => $order
->getBillingProfile(),
];
if (!array_key_exists('payment_method', $values)) {
if ($order
->hasField('payment_method') && !$order
->get('payment_method')
->isEmpty()) {
if ($payment_method = $order
->get('payment_method')->entity) {
$values['payment_method'] = $payment_method
->label();
}
}
elseif ($order
->hasField('payment_gateway') && !$order
->get('payment_gateway')
->isEmpty()) {
if ($payment_gateway = $order
->get('payment_gateway')->entity) {
$values['payment_method'] = $payment_gateway
->label();
}
}
}
$invoice = parent::create($values);
if ($this->moduleHandler
->moduleExists('language')) {
$config = ContentLanguageSettings::loadByEntityTypeBundle('commerce_invoice', $invoice
->bundle());
if ($config && $config
->getThirdPartySetting('commerce_invoice', 'generate_translations', FALSE)) {
$languages = $this->languageManager
->getLanguages();
foreach ($languages as $langcode => $language) {
if ($invoice
->hasTranslation($langcode)) {
continue;
}
$invoice
->addTranslation($langcode, $invoice
->toArray());
}
}
}
return $invoice;
}
public function loadByOrders($invoice_type, array $orders) {
$order_ids = array_map(function (OrderInterface $order) {
return $order
->id();
}, $orders);
return $this
->loadByProperties([
'type' => $invoice_type,
'orders' => $order_ids,
]);
}
}