You are here

function invoice_delete_item in Invoice 7

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

Delete an invoice item

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

File

./invoice_ajax.inc, line 313
Invoice module

Code

function invoice_delete_item() {
  $fv =& $_GET;
  $data = array();

  // Validate anti-CSRF token
  if (!isset($_GET['iid']) || !isset($_GET['token']) || !drupal_valid_token($_GET['token'], $_GET['iid'])) {
    $data['error'] = t('Failed to validate item id !');
    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;
  }
  $template = db_query("SELECT it.name FROM {invoice_invoices} ii\n    LEFT JOIN {invoice_templates} it ON ii.tid = it.tid\n    WHERE ii.iid = :iid", array(
    ':iid' => $fv['invoice_number'],
  ))
    ->fetchField();

  // 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);
    }
  }
  elseif ($template) {
    $locale = _invoice_get_variable($template, 'locale');
    if ($locale) {
      setlocale(LC_MONETARY, $locale);
    }
  }

  // Check if the item to delete exists and is owned by this owner
  $count = db_query("SELECT COUNT(*) FROM {invoice_items}\n    WHERE iid = :iid AND invoice_id = :invoice_id GROUP BY iid", array(
    ':iid' => $fv['iid'],
    ':invoice_id' => $fv['invoice_number'],
  ))
    ->fetchField();
  if ($count == 0) {
    $data['error'] = t('This item id does not exist, does not belong to this invoice or you are not the owner!');
  }
  else {
    db_delete('invoice_items')
      ->condition('iid', $fv['iid'])
      ->condition('uid', $GLOBALS['user']->uid)
      ->condition('invoice_id', $fv['invoice_number'])
      ->execute();

    // 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;
}