You are here

function invoice_save_item in Invoice 7

Same name and namespace in other branches
  1. 6 invoice_ajax.inc \invoice_save_item()

Add an invoice item

1 string reference to 'invoice_save_item'
invoice_menu in ./invoice.module
Implements hook_menu()

File

./invoice_ajax.inc, line 113
Invoice module

Code

function invoice_save_item() {
  $fv =& $_POST;
  $data = array();

  // Validate anti-CSRF token
  if (!isset($_POST['token']) || !drupal_valid_token($_POST['token'], $GLOBALS['user']->uid)) {
    $data['error'] = t('Failed to validate post !');
    drupal_json_output($data);
    exit;
  }
  $fv['invoice_number'] = isset($fv['invoice_number']) ? $fv['invoice_number'] : 0;

  // Check user admin access for this invoice
  if (!_invoice_user_has_admin_access_to_invoice($fv['invoice_number'])) {
    $data['error'] = t('You are not the owner of this item id!');
    drupal_json_output($data);
    exit;
  }

  // Set locale so money has the right format for the preferred culture
  if ((int) $fv['invoice_number'] === 0) {
    $locale = _invoice_get_variable(_invoice_get_chosen_template(), 'locale');
    if ($locale) {
      setlocale(LC_MONETARY, $locale);
    }
    $active_template = _invoice_get_chosen_template();
  }
  else {
    $query = db_select('invoice_invoices', 'ii')
      ->fields('it', array(
      'name',
    ));
    $query
      ->leftJoin('invoice_templates', 'it', 'ii.tid = it.tid');
    $template = $query
      ->condition('ii.iid', $fv['invoice_number'])
      ->execute()
      ->fetchField();
    if ($template) {
      $locale = _invoice_get_variable($template, 'locale');
      if ($locale) {
        setlocale(LC_MONETARY, $locale);
      }
      $active_template = $template;
    }
  }

  // Display error if price_wihtout_vat and price_with_vat are both not filled in
  if (empty($fv['price_without_vat']) && empty($fv['price_with_vat'])) {
    $data['error'] = t('Error') . ': ' . t('You have to fill in either "Price without VAT" or "Price with VAT"!');
  }
  if (!empty($data['error'])) {
    drupal_json_output($data);
    exit;
  }

  // Typecast strings to doubles and replace comma with a dot
  $fv['quantity'] = (double) str_replace(',', '.', $fv['quantity']);
  $fv['price_without_vat'] = (double) str_replace(',', '.', $fv['price_without_vat']);
  $fv['price_with_vat'] = (double) str_replace(',', '.', $fv['price_with_vat']);

  // Get the price without VAT
  if (!empty($fv['price_without_vat'])) {
    $unitcost = $fv['price_without_vat'];
  }
  else {
    $unitcost = $fv['price_with_vat'] / _invoice_vat_percent_to_decimal(variable_get('invoice_vat', 0));
  }

  // Round the price to 3 decimals
  $unitcost = round($unitcost, 3);

  // Round quantity to 2 decimals
  $fv['quantity'] = round($fv['quantity'], 2);
  if (intval($fv['iid']) > 0) {

    // item id is greater than zero, so we are saving an existing invoice item
    db_update('invoice_items')
      ->fields(array(
      'description' => $fv['description'],
      'vat' => $fv['vat'],
      'quantity' => $fv['quantity'],
      'unitcost' => $unitcost,
    ))
      ->condition('iid', $fv['iid'])
      ->condition('uid', $GLOBALS['user']->uid)
      ->condition('invoice_id', $fv['invoice_number'])
      ->execute();
  }
  else {

    // Insert invoice item into the invoice items table
    $lastInsertId = db_insert('invoice_items')
      ->fields(array(
      'description' => $fv['description'],
      'vat' => $fv['vat'],
      'quantity' => $fv['quantity'],
      'unitcost' => $unitcost,
      'invoice_id' => $fv['invoice_number'] > 0 ? $fv['invoice_number'] : 0,
      'uid' => $GLOBALS['user']->uid,
      'created' => time(),
    ))
      ->execute();
  }

  // Count the added items and calculate invoice totals
  $count = db_query("SELECT COUNT(*) FROM {invoice_items} WHERE uid = :uid AND invoice_id = :invoice_id", array(
    ':uid' => $GLOBALS['user']->uid,
    ':invoice_id' => $fv['invoice_number'],
  ))
    ->fetchField();
  if (intval($fv['iid']) > 0) {

    // item id is greater than zero, so we are dealing with an existing invoice item
    $data['iid'] = check_plain($fv['iid']);
    $data['description'] = nl2br(check_plain($fv['description']));
    $data['vat'] = check_plain($fv['vat']) . '%';
    $data['quantity'] = check_plain($fv['quantity']);
    $data['exunitcost'] = _invoice_round_and_format_money($unitcost, 3);
    $data['incunitcost'] = _invoice_round_and_format_money($unitcost * _invoice_vat_percent_to_decimal($fv['vat']), 2);
    $data['exsubtotal'] = _invoice_round_and_format_money($fv['quantity'] * $unitcost, 2);
    $data['incsubtotal'] = _invoice_round_and_format_money($fv['quantity'] * $unitcost * _invoice_vat_percent_to_decimal($fv['vat']), 2);
    $data['actionvalue'] = t('Add item');
  }
  else {

    // Set row class name
    $token = drupal_get_token($lastInsertId);
    $class = 'item-' . $lastInsertId . ' iitoken-' . $token . ' invoice-item draggable';

    // Compose content to send back to the browser
    $data['content'] = sprintf('<tr class="%s"><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class="actions">%s</td></tr>', $count & 1 ? $class . ' odd' : $class . ' even', nl2br(check_plain($fv['description'])), check_plain($fv['vat']) . '%', check_plain($fv['quantity']), _invoice_round_and_format_money($unitcost, 3), _invoice_round_and_format_money($unitcost * _invoice_vat_percent_to_decimal($fv['vat']), 2), _invoice_round_and_format_money($fv['quantity'] * $unitcost, 2), _invoice_round_and_format_money($fv['quantity'] * $unitcost * _invoice_vat_percent_to_decimal($fv['vat']), 2), _invoice_get_icon('edit', NULL, array(
      'class' => 'action-button edit-action mouse-pointer',
      'title' => t('Edit'),
    )) . _invoice_get_icon('delete', NULL, array(
      'class' => 'action-button delete-action mouse-pointer',
      'title' => t('Delete'),
    )));

    // Remove the empty from the page
    $data['remove_empty_row'] = TRUE;
  }

  // Define active vat value to put back on the resetted item form
  $data['activevat'] = _invoice_get_variable($active_template, 'vat');

  // Get invoice totals
  $totals = _invoice_get_invoice_totals($fv['invoice_number'], $GLOBALS['user']->uid);

  // Set total
  $data['extotal'] = _invoice_round_and_format_money($totals['extotal'], 2);
  $data['inctotal'] = _invoice_round_and_format_money($totals['inctotal'], 2);
  drupal_json_output($data);
  exit;
}