You are here

function invoice_save_item in Invoice 6

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

Add an invoice item

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

File

./invoice_ajax.inc, line 90
Invoice module

Code

function invoice_save_item() {
  $fv =& $_POST;
  $a_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;
  }

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

  // Set locale so money has the right format for the preferred culture
  if (intval($fv['invoice_number']) == 0) {
    if ($locale = _invoice_get_variable(_invoice_get_chosen_template(), 'locale')) {
      setlocale(LC_MONETARY, $locale);
    }
    $active_template = _invoice_get_chosen_template();
  }
  else {
    if ($template = db_result(db_query("SELECT it.name FROM {invoice_invoices} ii LEFT JOIN {invoice_templates} it ON ii.tid=it.tid WHERE ii.iid=%d", $fv['invoice_number']))) {
      if ($locale = _invoice_get_variable($template, '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'])) {
    $a_data['error'] = t('Error') . ': ' . t('You have to fill in either "Price without VAT" or "Price with VAT"!');
  }
  if (!empty($a_data['error'])) {
    drupal_json($a_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_query("UPDATE {invoice_items}\n      SET description='%s', vat='%f', quantity='%f', unitcost='%f' WHERE iid=%d AND uid=%d AND invoice_id=%d", $fv['description'], $fv['vat'], $fv['quantity'], $unitcost, $fv['iid'], $GLOBALS['user']->uid, $fv['invoice_number']);
  }
  else {

    // Insert invoice item into the invoice items table
    db_query("INSERT INTO {invoice_items}\n      (description,vat,quantity,unitcost,invoice_id,uid,created) VALUES ('%s',%f,%f,%f,%d,%d,'%s')", $fv['description'], $fv['vat'], $fv['quantity'], $unitcost, $fv['invoice_number'], $GLOBALS['user']->uid, date('Y-m-d H:i:s'));
  }

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

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

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

    // Compose content to send back to the browser
    $a_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
    $a_data['remove_empty_row'] = TRUE;
  }

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

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

  // Set total
  $a_data['extotal'] = _invoice_round_and_format_money($a_totals['extotal'], 2);
  $a_data['inctotal'] = _invoice_round_and_format_money($a_totals['inctotal'], 2);
  drupal_json($a_data);
  exit;
}