You are here

function invoice_delete_item in Invoice 6

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

Delete an invoice item

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

File

./invoice_ajax.inc, line 283
Invoice module

Code

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

  // 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);
    }
  }
  elseif ($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);
    }
  }

  // Check if the item to delete exists and is owned by this owner
  $a_invoice = db_fetch_object(db_query("SELECT COUNT(*) AS count FROM {invoice_items} WHERE iid=%d AND invoice_id=%d GROUP BY iid", $fv['iid'], $fv['invoice_number']));
  if ($a_invoice->count == 0) {
    $a_data['error'] = t('This item id does not exist, does not belong to this invoice or you are not the owner!');
  }
  else {
    db_query("DELETE FROM {invoice_items} WHERE iid=%d AND uid=%d AND invoice_id=%d", $fv['iid'], $GLOBALS['user']->uid, $fv['invoice_number']);

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