You are here

function invoice_node_presave in Invoice 7

Implements hook_node_presave()

Parameters

object $node:

File

./invoice.module, line 439
Invoice module

Code

function invoice_node_presave($node) {
  if ($node->type == 'invoice') {

    // If true we are creating a new invoice
    if (intval($node->invoice_number) == 0) {

      // Get new invoice number
      if (intval($node->user_defined_invoice_number) > 0) {
        $node->invoice_number = $node->user_defined_invoice_number;
      }
      else {
        $node->invoice_number = _invoice_get_new_invoice_number();
      }
    }

    // Save the title, this must happen when creating AND editing a node because otherwise
    // the pathauto module will give an error
    if (intval($node->invoice_number) > 0) {
      $node->title = t('Invoice') . ' #' . _invoice_get_formatted_invoice_number($node->invoice_number, $node);
    }
    if (!isset($node->customer_number) || $node->customer_number < 1) {
      $template = _invoice_get_chosen_template();
      $tid = (int) db_query("SELECT tid FROM {invoice_templates} WHERE name = :name", array(
        ':name' => $template,
      ))
        ->fetchField();

      // Get customer number
      if (!empty($node->company_name)) {
        $customer_number = db_query("SELECT customer_number FROM {invoice_customers} ic\n            JOIN {invoice_invoices} ii ON ic.invoice_id = ii.iid AND ii.tid = :tid\n            WHERE company_name = :company_name AND country = :country LIMIT 1", array(
          ':tid' => $tid,
          ':company_name' => $node->company_name,
          ':country' => $node->country,
        ))
          ->fetchField();
      }
      elseif (!empty($node->lastname)) {
        $customer_number = db_query("SELECT customer_number FROM {invoice_customers} ic\n            JOIN {invoice_invoices} ii ON ic.invoice_id = ii.iid AND ii.tid = :tid\n            WHERE lastname = :lastname AND zipcode = :zipcode AND building_number = :building_number\n            LIMIT 1", array(
          ':tid' => $tid,
          ':lastname' => $node->lastname,
          ':zipcode' => $node->zipcode,
          ':building_number' => $node->building_number,
        ))
          ->fetchField();
      }

      // If customer number is still empty, get a new one
      if (empty($customer_number)) {
        $customer_number = 1 + db_query("SELECT MAX(customer_number) FROM {invoice_customers} ic\n              JOIN {invoice_invoices} ii ON ic.invoice_id = ii.iid AND ii.tid = :tid", array(
          ':tid' => $tid,
        ))
          ->fetchField();
      }

      // Add customer number to the node object
      $node->customer_number = $customer_number;
    }

    // Set language undefined
    $node->language = 'und';
  }
}