You are here

function invoice_insert in Invoice 7

Same name and namespace in other branches
  1. 6 invoice.module \invoice_insert()

Implements hook_insert()

File

./invoice.module, line 783
Invoice module

Code

function invoice_insert($node) {

  // Set user ID
  $uid = $GLOBALS['user']->uid;

  // Set template ID
  $tid = db_query("SELECT tid FROM {invoice_templates} WHERE name = :name", array(
    ':name' => $node->template,
  ))
    ->fetchField();

  // Set pay status
  $pay_status = isset($node->pay_status) && 'paid' == $node->pay_status ? 'paid' : 'unpaid';

  // Create invoice
  db_insert('invoice_invoices')
    ->fields(array(
    'iid' => $node->invoice_number,
    'nid' => $node->nid,
    'leading_zeros' => empty($node->invoice_invoice_number_zerofill) ? variable_get('invoice_invoice_number_zerofill', 0) : $node->invoice_invoice_number_zerofill,
    'prefix' => empty($node->invoice_invoice_number_prefix) ? variable_get('invoice_invoice_number_prefix', NULL) : $node->invoice_invoice_number_prefix,
    'description' => $node->invoice_description,
    'tid' => $tid,
    'pay_limit' => $node->pay_limit,
    'pay_status' => $pay_status,
    'uid' => $uid,
  ))
    ->execute();
  db_insert('invoice_customers')
    ->fields(array(
    'customer_number' => $node->customer_number,
    'company_name' => $node->company_name,
    'firstname' => $node->firstname,
    'lastname' => $node->lastname,
    'street' => $node->street,
    'building_number' => $node->building_number,
    'zipcode' => $node->zipcode,
    'city' => $node->city,
    'state' => $node->state,
    'country' => $node->country,
    'coc_number' => $node->coc_number,
    'vat_number' => $node->vat_number,
    'description' => $node->customer_description,
    'invoice_id' => $node->invoice_number,
  ))
    ->execute();
  if (isset($GLOBALS['invoice_api']) && true === $GLOBALS['invoice_api']) {
    if (count($node->invoice_items) > 0) {
      foreach ($node->invoice_items as $item) {

        // Round the price to 3 decimals
        $unitcost = round($item['unitcost'], 3);

        // Insert invoice item into the invoice items table
        $lastInsertId = db_insert('invoice_items')
          ->fields(array(
          'description' => $item['description'],
          'vat' => (double) $item['vat'],
          'quantity' => (double) $item['quantity'],
          'unitcost' => (double) $unitcost,
          'weight' => (int) $item['weight'],
          'invoice_id' => $node->invoice_number,
          'uid' => $uid,
          'created' => time(),
        ))
          ->execute();
      }
    }
  }
  else {
    db_update('invoice_items')
      ->fields(array(
      'invoice_id' => $node->invoice_number,
    ))
      ->condition('uid', $uid)
      ->condition('invoice_id', 0)
      ->execute();
  }
  db_update('node')
    ->fields(array(
    'promote' => 0,
  ))
    ->condition('type', 'invoice')
    ->condition('nid', $node->nid)
    ->execute();
  unset($_SESSION['invoice_template']);
}