function commerce_reports_tax_order_save in Commerce Reporting 7.4
Same name and namespace in other branches
- 7.3 modules/tax/commerce_reports_tax.module \commerce_reports_tax_order_save()
Stores the tax information of an order.
If the order has already been processed in the past it will compare the information in the database with the generated information and update accordingly.
3 calls to commerce_reports_tax_order_save()
- commerce_reports_tax_entity_insert in modules/
tax/ commerce_reports_tax.module - Implements hook_entity_insert().
- commerce_reports_tax_entity_update in modules/
tax/ commerce_reports_tax.module - Implements hook_entity_update().
- _commerce_reports_tax_generate in modules/
tax/ commerce_reports_tax.batch.inc - Build the table of tax information.
File
- modules/
tax/ commerce_reports_tax.module, line 270 - Module file for Commerce Reports Tax.
Code
function commerce_reports_tax_order_save($order) {
/** @var EntityDrupalWrapper $wrapper */
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_id = $wrapper->order_id
->value();
// Loop through all line items and get taxes from taxable line items.
$applied_taxes = array();
foreach ($wrapper->commerce_line_items as $line_item_wrapper) {
if ($tax_rates = _commerce_reports_tax_get_tax_rates($line_item_wrapper)) {
// Taxable.
$taxable = $line_item_wrapper->commerce_total
->value();
// Taxed.
foreach ($tax_rates as $tax_rate) {
$taxed = commerce_price_component_total($taxable, $tax_rate['price_component']);
$id = $tax_rate['name'] . $order_id . $taxed['currency_code'];
// Create fresh record if it doesn't exist.
if (empty($applied_taxes[$id])) {
$applied_taxes[$id] = new stdClass();
$applied_taxes[$id]->tax_rate = $tax_rate['name'];
$applied_taxes[$id]->order_id = $order_id;
$applied_taxes[$id]->currency_code = $taxed['currency_code'];
$applied_taxes[$id]->taxable = 0;
$applied_taxes[$id]->taxed = 0;
}
// Increase the amounts.
$applied_taxes[$id]->taxable += $taxable['amount'];
$applied_taxes[$id]->taxed += round($taxed['amount']);
}
}
else {
// TODO: Keep track of amount where taxes were not applied?
}
}
// Check to see if save records exist before saving new record.
$result = db_query("SELECT tax_rate, order_id, currency_code, taxable, taxed FROM {commerce_reports_tax} WHERE order_id = :order_id", array(
':order_id' => $order->order_id,
));
// If we have records, update the existing, else add new.
if ($result
->rowCount() > 0) {
// Update record.
while ($row = $result
->fetchAssoc()) {
$tax_record_id = $row['tax_rate'] . $row['order_id'] . $row['currency_code'];
drupal_write_record('commerce_reports_tax', $applied_taxes[$tax_record_id], array(
'tax_rate',
'order_id',
'currency_code',
));
}
}
else {
// Insert any of the remaining applied taxes.
foreach ($applied_taxes as $tax) {
drupal_write_record('commerce_reports_tax', $tax);
}
}
}