public function InvoiceTest::testTotalCalculation in Commerce Invoice 8.2
Tests the invoice total recalculation logic.
@covers ::recalculateTotalPrice
File
- tests/
src/ Kernel/ Entity/ InvoiceTest.php, line 285
Class
- InvoiceTest
- Tests the invoice entity.
Namespace
Drupal\Tests\commerce_invoice\Kernel\EntityCode
public function testTotalCalculation() {
$invoice = Invoice::create([
'type' => 'default',
'store_id' => $this->store
->id(),
]);
$invoice
->save();
/** @var \Drupal\commerce_invoice\Entity\InvoiceItemInterface $invoice_item */
$invoice_item = InvoiceItem::create([
'type' => 'commerce_product_variation',
'quantity' => '2',
'unit_price' => new Price('2.00', 'USD'),
]);
$invoice_item
->save();
$invoice_item = $this
->reloadEntity($invoice_item);
/** @var \Drupal\commerce_invoice\Entity\InvoiceItemInterface $another_invoice_item */
$another_invoice_item = InvoiceItem::create([
'type' => 'commerce_product_variation',
'quantity' => '1',
'unit_price' => new Price('3.00', 'USD'),
]);
$another_invoice_item
->save();
$another_invoice_item = $this
->reloadEntity($another_invoice_item);
$adjustments = [];
$adjustments[0] = new Adjustment([
'type' => 'tax',
'label' => 'Tax',
'amount' => new Price('100.00', 'USD'),
'included' => TRUE,
]);
$adjustments[1] = new Adjustment([
'type' => 'tax',
'label' => 'Tax',
'amount' => new Price('2.121', 'USD'),
'source_id' => 'us_sales_tax',
]);
$adjustments[2] = new Adjustment([
'type' => 'tax',
'label' => 'Tax',
'amount' => new Price('5.344', 'USD'),
'source_id' => 'us_sales_tax',
]);
// Included adjustments do not affect the invoice total.
$invoice
->addAdjustment($adjustments[0]);
$invoice_item
->addAdjustment($adjustments[1]);
$another_invoice_item
->addAdjustment($adjustments[2]);
$invoice
->setItems([
$invoice_item,
$another_invoice_item,
]);
$invoice
->save();
/** @var \Drupal\commerce_invoice\Entity\InvoiceInterface $invoice */
$invoice = $this
->reloadEntity($invoice);
$collected_adjustments = $invoice
->collectAdjustments();
$this
->assertCount(3, $collected_adjustments);
$this
->assertEquals($adjustments[1], $collected_adjustments[0]);
$this
->assertEquals($adjustments[2], $collected_adjustments[1]);
$this
->assertEquals($adjustments[0], $collected_adjustments[2]);
// The total will be correct only if the adjustments were correctly
// combined, and rounded.
$this
->assertEquals(new Price('14.47', 'USD'), $invoice
->getTotalPrice());
// Test handling deleted invoice items + non-inclusive adjustments.
$invoice
->addAdjustment($adjustments[1]);
$invoice_item
->delete();
$another_invoice_item
->delete();
$invoice
->recalculateTotalPrice();
$this
->assertNull($invoice
->getTotalPrice());
}