function action_delete()
 {
     log_debug("cdr_customers_services_ddi", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete DDI
     */
     $sql_obj->string = "DELETE FROM services_customers_ddi WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "cdr_customers_services_ddi", "An error occured whilst trying to delete the DDI.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "cdr_customers_services_ddi", "DDI has been successfully deleted.");
         return 1;
     }
 }
function invoice_form_tax_override_process($returnpage)
{
    log_debug("inc_invoices_items", "Executing invoice_form_tax_override_process({$returnpage})");
    /*
    	Start invoice_items object
    */
    $item = new invoice_items();
    $item->id_invoice = @security_form_input_predefined("int", "invoiceid", 1, "");
    $item->id_item = @security_form_input_predefined("int", "itemid", 1, "");
    $item->type_invoice = "ap";
    // only AP invoices can have taxes overridden
    /*
    	Fetch all form data
    */
    $data["amount"] = @security_form_input_predefined("money", "amount", 0, "");
    //// ERROR CHECKING ///////////////////////
    /*
    	Verify invoice/form data
    */
    if ($item->verify_invoice()) {
        if (!$item->verify_item()) {
            $_SESSION["error"]["message"][] = "The provided tax does not exist.";
        }
    } else {
        $_SESSION["error"]["message"][] = "The provided invoice does not exist.";
    }
    /// if there was an error, go back to the entry page
    if ($_SESSION["error"]["message"]) {
        $_SESSION["error"]["form"]["ap_invoice_" . $mode . "_override"] = "failed";
        header("Location: ../../index.php?page={$returnpage}&id=" . $item->id_invoice);
        exit(0);
    } else {
        /*
        	Start SQL Transaction
        */
        $sql_obj = new sql_query();
        $sql_obj->trans_begin();
        /*
        	Depending on the amount, we either delete the tax item (if the amount is 0) or we
        	adjust the tax item.
        */
        if ($data["amount"] == 0) {
            // delete item
            $item->action_delete();
            // done
            $_SESSION["notification"]["message"] = array("Deleted unwanted tax.");
        } else {
            // load & update the tax item
            $item->load_data();
            $item->data["amount"] = $data["amount"];
            $item->action_update();
            // done
            $_SESSION["notification"]["message"] = array("Updated tax value with custom input.");
        }
        // update invoice summary
        $item->action_update_total();
        // update ledger
        $item->action_update_ledger();
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "inc_invoice_items", "An error occured whilst overriding tax. No changes have been made");
        } else {
            $sql_obj->trans_commit();
        }
        // done
        header("Location: ../../index.php?page={$returnpage}&id=" . $item->id_invoice);
        exit(0);
    }
}
 function delete_invoice_item($itemid)
 {
     log_debug("accounts_invoices_manage", "Executing delete_invoice_itemid({$itemid})");
     // sanatise item ID
     $itemid = @security_script_input_predefined("any", $itemid);
     // fetch the invoice ID and type
     $sql_item_obj = new sql_query();
     $sql_item_obj->string = "SELECT invoiceid, invoicetype FROM account_items WHERE id='" . $itemid . "' LIMIT 1";
     $sql_item_obj->execute();
     if (!$sql_item_obj->num_rows()) {
         throw new SoapFault("Sender", "INVALID_ITEMID");
     }
     $sql_item_obj->fetch_array();
     if (user_permissions_get("accounts_" . $sql_item_obj->data[0]["invoicetype"] . "_write")) {
         $obj_invoice_item = new invoice_items();
         $obj_invoice_item->type_invoice = $sql_item_obj->data[0]["invoicetype"];
         $obj_invoice_item->id_invoice = $sql_item_obj->data[0]["invoiceid"];
         $obj_invoice_item->id_item = $itemid;
         // make sure invoice is not locked
         if ($obj_invoice_item->check_lock()) {
             throw new SoapFault("Sender", "LOCKED");
         }
         /*
         	Perform Changes
         */
         // start SQL transaction
         $sql_obj = new sql_query();
         $sql_obj->trans_begin();
         if (!$obj_invoice_item->action_delete()) {
             $sql_obj->trans_rollback();
             throw new SoapFault("Sender", "UNEXPECTED_ACTION_ERROR");
         }
         // re-calculate taxes, totals and ledgers as required
         $obj_invoice_item->action_update_tax();
         $obj_invoice_item->action_update_total();
         $obj_invoice_item->action_update_ledger();
         // commit
         if (error_check()) {
             $sql_obj->trans_rollback();
             throw new SoapFault("Sender", "UNEXPECTED_ACTION_ERROR");
         } else {
             $sql_obj->trans_commit();
             return 1;
         }
     } else {
         throw new SoapFault("Sender", "ACCESS DENIED");
     }
 }
Esempio n. 4
0
 function action_delete()
 {
     log_debug("inc_vendors", "Executing action_delete()");
     // start transaction
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Vendor
     */
     $sql_obj->string = "DELETE FROM vendors WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete vendor taxes
     */
     $sql_obj->string = "DELETE FROM vendors_taxes WHERE vendorid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete vendor contacts and records
     */
     $sql_obj->string = "SELECT id from vendor_contacts WHERE id='" . $this->id . "'";
     $sql_obj->execute();
     $sql_obj->fetch_array();
     foreach ($sql_obj->data as $data) {
         $sql_obj->string = "DELETE FROM vendor_contact_records WHERE contact_id='" . $data["id"] . "'";
         $sql_obj->execute();
     }
     $sql_obj->string = "DELETE FROM vendor_contacts WHERE id='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete Journal
     */
     journal_delete_entire("vendors", $this->id);
     // commit
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_vendors", "An error occured whilst attempting to delete vendor. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_vendors", "Vendor has been successfully deleted.");
         return 1;
     }
 }
 function action_delete()
 {
     log_debug("service_groups", "Executing action_delete()");
     $id_parent = sql_get_singlevalue("SELECT id_parent AS value FROM service_groups WHERE id='{$this->id}' LIMIT 1");
     $child_groups = sql_get_singlecol("SELECT id AS col FROM service_groups WHERE id_parent='{$this->id}'");
     //exit("<pre>".print_r($child_groups,true)."</pre>");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete service group
     */
     $sql_obj->string = "DELETE FROM service_groups WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     $child_count = count($child_groups);
     if ($child_count > 0) {
         $sql_obj->string = "UPDATE `service_groups` SET `id_parent` = '{$id_parent}' WHERE `id` IN('" . implode("', '", $child_groups) . "') LIMIT {$child_count};";
         $sql_obj->execute();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "service_groups", "An error occured whilst trying to delete the service group.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "service_groups", "Service group has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 6
0
 function action_delete()
 {
     log_debug("inc_credits_refund", "Executing action_delete()");
     // we must have an ID provided
     if (!$this->id) {
         log_debug("inc_credits_refund", "No credit refund ID to action_delete function");
         return 0;
     }
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Credit Refund
     */
     $sql_obj->string = "DELETE FROM " . $this->type . "s_credits WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete Ledger Items
     */
     if ($this->type == "customer") {
         $sql_obj->string = "DELETE FROM account_trans WHERE (type='ar_refund') AND customid='" . $this->id . "'";
         $sql_obj->execute();
     } else {
         $sql_obj->string = "DELETE FROM account_trans WHERE (type='ap_refund') AND customid='" . $this->id . "'";
         $sql_obj->execute();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "invoice", "An error occured whilst deleting the credit refund. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         return 1;
     }
 }
function service_form_delete_process()
{
    log_debug("inc_services_process", "Executing service_form_delete_process()");
    /*
    	Fetch all form data
    */
    // get form data
    $id = @security_form_input_predefined("int", "id_service", 1, "");
    $data["delete_confirm"] = @security_form_input_predefined("any", "delete_confirm", 1, "You must confirm the deletion");
    //// ERROR CHECKING ///////////////////////
    // make sure the service actually exists
    $sql_obj = new sql_query();
    $sql_obj->string = "SELECT id FROM services WHERE id='{$id}' LIMIT 1";
    $sql_obj->execute();
    if (!$sql_obj->num_rows()) {
        log_write("error", "process", "The service you have attempted to edit - {$id} - does not exist in this system.");
    }
    // make sure the service is not active for any customers
    $sql_obj = new sql_query();
    $sql_obj->string = "SELECT id FROM services_customers WHERE serviceid='{$id}' LIMIT 1";
    $sql_obj->execute();
    if ($sql_obj->num_rows()) {
        log_write("error", "process", "Service is active for customers and can therefore not be deleted.");
    }
    /// if there was an error, go back to the entry page
    if ($_SESSION["error"]["message"]) {
        $_SESSION["error"]["form"]["service_delete"] = "failed";
        header("Location: ../index.php?page=services/delete.php&id={$id}");
        exit(0);
    } else {
        /*
        	Begin Transaction
        */
        $sql_obj = new sql_query();
        $sql_obj->trans_begin();
        /*
        	Delete the service data
        */
        $sql_obj->string = "DELETE FROM services WHERE id='{$id}' LIMIT 1";
        $sql_obj->execute();
        /*
        	Delete the service taxes
        */
        $sql_obj->string = "DELETE FROM services_taxes WHERE serviceid='{$id}'";
        $sql_obj->execute();
        /*
        	Delete the service bundle components (if any)
        */
        $sql_bundle_obj = new sql_query();
        $sql_bundle_obj->string = "SELECT id FROM services_bundles WHERE id_service='{$id}'";
        $sql_bundle_obj->execute();
        if ($sql_bundle_obj->num_rows()) {
            $sql_bundle_obj->fetch_array();
            foreach ($sql_bundle_obj->data as $data_bundle) {
                // delete any options for each bundle item
                $sql_obj->string = "DELETE FROM services_options WHERE option_type='service' AND option_type_id='" . $data_bundle["id"] . "'";
                $sql_obj->execute();
            }
        }
        $sql_obj->string = "DELETE FROM services_bundles WHERE id_service='{$id}'";
        $sql_obj->execute();
        /*
        	Delete the service cdr rate overrides (if any)
        */
        $sql_obj->string = "DELETE FROM cdr_rate_tables_overrides WHERE option_type='service' AND option_type_id='{$id}'";
        $sql_obj->execute();
        /*
        	Delete service journal data
        */
        journal_delete_entire("services", $id);
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "process", "An error occured whilst attempting to delete the transaction. No changes have been made.");
            header("Location: ../index.php?page=services/view.php&id={$id}");
            exit(0);
        } else {
            $sql_obj->trans_commit();
            log_write("notification", "process", "Service successfully deleted");
            header("Location: ../index.php?page=services/services.php");
            exit(0);
        }
    }
    // end if passed tests
}
Esempio n. 8
0
 function action_delete()
 {
     log_debug("inc_staff", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Employee
     */
     $sql_obj->string = "DELETE FROM staff WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete User <-> Employee permissions mappings
     */
     $sql_obj->string = "DELETE FROM users_permissions_staff WHERE staffid='{$this->id}'";
     $sql_obj->execute();
     /*
     	Delete Journal
     */
     journal_delete_entire("staff", $this->id);
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_staff", "An error occured whilst attempting to delete the employee. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_staff", "Employee has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 9
0
 function action_delete()
 {
     log_write("debug", "file_storage", "Executing action_delete()");
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Remove file data
     */
     if ($this->data["file_location"] == "db") {
         // delete file from the database
         $sql_obj->string = "DELETE FROM file_upload_data WHERE fileid='" . $this->id . "'";
         $sql_obj->execute();
     } else {
         // delete file from the filesystem
         $file_path = $this->config["data_storage_location"] . "/" . $this->id;
         @unlink($file_path);
     }
     /*
     	Remove metadata information from database
     */
     $sql_obj->string = "DELETE FROM file_uploads WHERE id='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "file_storage", "An error occured whilst attempting to upload the file, no changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("debug", "file_storage", "Successfully deleted file ID '" . $this->id . "'");
         return $this->id;
     }
 }
Esempio n. 10
0
 function action_delete()
 {
     log_debug("name_server_group", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Name Server Group
     
     	Note: no need to delete anything from dns_domains_groups, as the name server group
     	must be empty before it can be deleted.
     */
     $sql_obj->string = "DELETE FROM name_servers_groups WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "name_server_group", "An error occured whilst trying to delete the name server group.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "name_server_group", "Name server group has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 11
0
 function action_delete()
 {
     log_debug("inc_charts", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete chart
     */
     $sql_obj->string = "DELETE FROM account_charts WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete all chart menu options
     */
     $sql_obj->string = "DELETE FROM account_charts_menus WHERE chartid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_charts", "An error occured whilst attempting to delete account. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_charts", "Account has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 12
0
 function action_delete()
 {
     log_debug("attributes", "Executing action_delete()");
     // start transaction
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     // delete the attribute
     $sql_obj->string = "DELETE FROM attributes WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     // commit
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error" . "inc_attributes" . "An error occured whilst attempting to delete the attribute. No changes have been made.");
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_attributes", "Attribute has been successfully deleted.");
     }
     return 1;
 }
Esempio n. 13
0
 function action_delete()
 {
     log_debug("inc_gl", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete general ledger details
     */
     $sql_obj->string = "DELETE FROM account_gl WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete transaction items
     */
     $sql_obj->string = "DELETE FROM account_trans WHERE type='gl' AND customid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_gl", "An error occured whilst attempting to delete the transaction. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_gl", "Transaction has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 14
0
 function action_delete()
 {
     log_debug("name_server", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Name Server
     */
     $sql_obj->string = "DELETE FROM name_servers WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->string = "DELETE FROM cloud_zone_map WHERE id='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Un-associated any matched log entries
     */
     $sql_obj->string = "UPDATE logs SET id_server='0' WHERE id_server='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Update NS records
     
     	We need to run through all the domains and update the records - if the nameserver was an automated entry for all the domains,
     	after deleting the name server we should remove it from all the domains.
     */
     $obj_domain = new domain();
     $obj_domain->load_data_all();
     foreach ($obj_domain->data as $data_domain) {
         $obj_domain_sub = new domain();
         $obj_domain_sub->id = $data_domain["id"];
         $obj_domain_sub->load_data();
         $obj_domain_sub->action_update_ns();
         $obj_domain_sub->action_update_serial();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "name_server", "An error occured whilst trying to delete the name server.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "name_server", "Name server has been successfully deleted.");
         return 1;
     }
 }
Esempio n. 15
0
 function bundle_service_delete($id_service)
 {
     log_write("debug", "inc_services", "Executing bundle_service_delete({$id_service}))");
     /*
     	Begin Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Apply Changes
     */
     $sql_obj->string = "SELECT id FROM `services_bundles` WHERE id_bundle='" . $this->id . "' AND id_service='{$id_service}' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->fetch_array();
     $option_id = $sql_obj->data[0]["id"];
     $sql_obj->string = "DELETE FROM `services_bundles` WHERE id='{$option_id}' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->string = "DELETE FROM `services_options` WHERE option_type='bundle' AND option_type_id='{$option_id}'";
     $sql_obj->execute();
     /*
     	Update the Journal
     */
     journal_quickadd_event("services", $this->id, "Service component removed from bundle.");
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "process", "An error occured whilst attempting to remove a service from the bundle. No changes have been made.");
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "process", "Service successfully removed from bundle.");
     }
     return 0;
 }
function quotes_form_delete_process($returnpage_error, $returnpage_success)
{
    log_debug("inc_quotes_forms", "Executing quotes_form_delete_process({$mode}, {$returnpage_error}, {$returnpage_success})");
    /*
    	Fetch all form data
    */
    // get form data
    $id = @security_form_input_predefined("int", "id_quote", 1, "");
    $data["delete_confirm"] = @security_form_input_predefined("any", "delete_confirm", 1, "You must confirm the deletion");
    // we don't use this value (since we can't trust it) but we need to read it
    // in here to work around a limitation in the Amberphplib framework
    $data["date_create"] = @security_form_input_predefined("any", "date_create", 1, "");
    //// ERROR CHECKING ///////////////////////
    // make sure the quote actually exists
    $sql_obj = new sql_query();
    $sql_obj->string = "SELECT id, date_create FROM `account_quotes` WHERE id='{$id}' LIMIT 1";
    $sql_obj->execute();
    if (!$sql_obj->num_rows()) {
        $_SESSION["error"]["message"][] = "The quote you have attempted to edit - {$id} - does not exist in this system.";
    }
    /// if there was an error, go back to the entry page
    if ($_SESSION["error"]["message"]) {
        $_SESSION["error"]["form"]["quote_delete"] = "failed";
        header("Location: ../../index.php?page={$returnpage_error}&id={$id}");
        exit(0);
    } else {
        /*
        	Start SQL Transaction
        */
        $sql_obj = new sql_query();
        $sql_obj->trans_begin();
        /*
        	delete quote itself
        */
        $sql_obj->string = "DELETE FROM account_quotes WHERE id='{$id}' LIMIT 1";
        $sql_obj->execute();
        /*
        	delete all the item options
        */
        $sql_item_obj = new sql_query();
        $sql_item_obj->string = "SELECT id FROM account_items WHERE invoicetype='quotes' AND invoiceid='{$id}'";
        $sql_item_obj->execute();
        if ($sql_item_obj->num_rows()) {
            $sql_item_obj->fetch_array();
            foreach ($sql_item_obj->data as $data) {
                $sql_obj->string = "DELETE FROM account_items_options WHERE itemid='" . $data["id"] . "'";
                $sql_obj->execute();
            }
        }
        /*
        	delete all the quote items
        */
        $sql_obj->string = "DELETE FROM account_items WHERE invoicetype='quotes' AND invoiceid='{$id}'";
        $sql_obj->execute();
        /*
        	delete quote journal entries
        */
        journal_delete_entire("account_quotes", $id);
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "inc_quotes_forms", "An error occured whilst attempting to delete the quote. No changes have been made.");
            $_SESSION["error"]["form"]["quote_delete"] = "failed";
            header("Location: ../../index.php?page={$returnpage_error}&id={$id}");
            exit(0);
        } else {
            $sql_obj->trans_commit();
            log_write("notification", "inc_quotes_forms", "The quotation has been successfully deleted.");
            header("Location: ../../index.php?page={$returnpage_success}");
            exit(0);
        }
    }
    // end if passed tests
}
Esempio n. 17
0
 function action_delete()
 {
     log_debug("journal_process", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete files (if applicable)
     */
     if ($this->structure["type"] == "file") {
         $file_obj = new file_storage();
         $file_obj->data["type"] = "journal";
         $file_obj->data["customid"] = $this->structure["id"];
         $file_obj->load_data_bytype();
         $file_obj->action_delete();
     }
     /*
     	Delete journal record
     */
     $sql_obj->string = "DELETE FROM `journal` WHERE id='" . $this->structure["id"] . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         log_write("error", "journal_process", "An error occured preventing the journal record from being deleted");
         $sql_obj->trans_rollback();
         return 0;
     } else {
         log_write("notification", "journal_process", "Journal record cleanly removed.");
         $sql_obj->trans_commit();
         return 1;
     }
     return 0;
 }
 function action_delete()
 {
     log_write("debug", "traffic_types", "Executing action_delete()");
     /*
     	Start Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Traffic Type
     */
     $sql_obj = new sql_query();
     $sql_obj->string = "DELETE FROM `traffic_types` WHERE id='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "traffic_types", "An error occured when deleting the selected traffic type, no changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "traffic_types", "Traffic type successfully deleted");
         return 1;
     }
 }
Esempio n. 19
0
 function action_delete()
 {
     log_debug("inc_taxes", "Executing action_delete()");
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Tax
     */
     $sql_obj->string = "DELETE FROM account_taxes WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete tax from any services it is assigned to
     */
     $sql_obj->string = "DELETE FROM products_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any services it is assigned to
     */
     $sql_obj->string = "DELETE FROM services_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any vendors it is assigned to
     */
     // delete mapping from table
     $sql_obj->string = "DELETE FROM vendors_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     // unset any defaulttax usage
     $sql_obj->string = "UPDATE vendors SET tax_default='0' WHERE tax_default='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete tax from any customers it is assigned to
     */
     // delete mapping from table
     $sql_obj->string = "DELETE FROM customers_taxes WHERE taxid='" . $this->id . "'";
     $sql_obj->execute();
     // unset any defaulttax usage
     $sql_obj->string = "UPDATE customers SET tax_default='0' WHERE tax_default='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_taxes", "An error occured whilst attempting to delete the tax. No change has been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_taxes", "Tax has been successfully deleted.");
         return 1;
     }
 }
function page_execute($argv)
{
    /*
    	Input Options
    */
    $option_date = NULL;
    $option_type = NULL;
    if (empty($argv[2])) {
        die("You must provide a date option in form of YYYY-MM-DD\n");
    }
    if (preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $argv[2])) {
        $option_date = $argv[2];
    } else {
        die("You must provide a date option in form of YYYY-MM-DD - wrong format supplied\n");
    }
    if (empty($argv[3])) {
        die("Service Type must be set.\n");
    }
    if (preg_match('/^\\S\\S*$/', $argv[3])) {
        $option_type = $argv[3];
        $option_type_id = sql_get_singlevalue("SELECT id as value FROM service_types WHERE name='{$option_type}' LIMIT 1");
        if (!$option_type_id) {
            die("Service type {$option_type} is unknown\n");
        }
    } else {
        die("You must provide a service type\n");
    }
    log_write("notification", "repair", "Executing usage charge rollback for invoices generated {$option_date} for service type {$option_type} (ID {$option_type_id})");
    /*
    	Fetch IDs of all sercices with selected option type
    */
    $option_services = array();
    $obj_sql_service = new sql_query();
    $obj_sql_service->string = "SELECT id FROM services WHERE typeid='" . $option_type_id . "'";
    $obj_sql_service->execute();
    if ($obj_sql_service->num_rows()) {
        $obj_sql_service->fetch_array();
        foreach ($obj_sql_service->data as $data) {
            $option_services[] = $data["id"];
        }
    }
    unset($obj_sql_service);
    log_write("notification", "repair", "Returned ID of matching services, array of " . format_arraytocommastring($option_services, NULL) . "");
    /*
    	Start Transaction
    */
    $obj_sql_trans = new sql_query();
    $obj_sql_trans->trans_begin();
    /*
    	Fetch AR Invoices for selected period
    */
    $obj_sql_ar = new sql_query();
    $obj_sql_ar->string = "SELECT id, customerid, code_invoice, dest_account, amount_total, amount_paid FROM account_ar WHERE date_trans='{$option_date}'";
    $obj_sql_ar->execute();
    if ($obj_sql_ar->num_rows()) {
        $obj_sql_ar->fetch_array();
        foreach ($obj_sql_ar->data as $data_ar) {
            $invoice_items = array();
            // store item details
            /*
            	Fetch Invoice Items
            */
            $obj_sql_items = new sql_query();
            $obj_sql_items->string = "SELECT id, customid, chartid, amount, description FROM account_items WHERE invoiceid='" . $data_ar["id"] . "' AND invoicetype='ar' AND type='service_usage'";
            $obj_sql_items->execute();
            if ($obj_sql_items->num_rows()) {
                $obj_sql_items->fetch_array();
                /*
                	For each item, check the service type and whether it is one of the items
                	that we want to credit.
                */
                foreach ($obj_sql_items->data as $data_item) {
                    if (in_array($data_item["customid"], $option_services)) {
                        // item is one of the target services, add details to array
                        log_write("debug", "repair", "Invoice ID #" . $data_ar["id"] . ", (" . $data_ar["code_invoice"] . ") item ID #" . $data_item["id"] . " is a valid service usage item to refund.");
                        // check if it's call charges
                        if (!strpos($data_item["description"], "call charges")) {
                            log_write("debug", "repair", "Skipping non-call charge usage item from credit");
                            continue;
                        }
                        // add invoice items
                        $invoice_items_tmp = array();
                        $invoice_items_tmp["id"] = $data_item["id"];
                        $invoice_items_tmp["customid"] = $data_item["customid"];
                        $invoice_items_tmp["chartid"] = $data_item["chartid"];
                        $invoice_items_tmp["amount"] = $data_item["amount"];
                        $invoice_items_tmp["description"] = $data_item["description"];
                        // add to array
                        $invoice_items[] = $invoice_items_tmp;
                    }
                }
            }
            // end of AR invoice items loop
            /*
            	If any items matched, we should create a credit note and add the items as credits
            */
            if (!empty($invoice_items)) {
                /*
                	Create Credit Note
                
                	We have all the information needed for the credit note from the invoice.
                */
                $credit = new credit();
                $credit->type = "ar_credit";
                $credit->prepare_set_defaults();
                $credit->data["invoiceid"] = $data_ar["id"];
                $credit->data["customerid"] = $data_ar["customerid"];
                $credit->data["employeeid"] = "0";
                $credit->data["date_trans"] = date("Y-m-d");
                $credit->data["dest_account"] = $data_ar["dest_account"];
                $credit->data["notes"] = "Automatically generated credit by repair process to cover service usage refund of invoice " . $data_ar["code_invoice"] . "";
                // create a new credit
                if ($credit->action_create()) {
                    log_write("notification", "repair", "Credit note successfully created");
                    journal_quickadd_event("account_ar_credit", $credit->id, "Credit Note successfully created");
                } else {
                    log_write("error", "repair", "An unexpected fault occured whilst attempting to create the credit note");
                }
                /*
                	Add Items
                
                	We loop through each selected item and for each item, we create an appropiate credit note item.
                */
                foreach ($invoice_items as $data_item) {
                    // create credit item
                    $item = new invoice_items();
                    $item->id_invoice = $credit->id;
                    $item->type_invoice = "ar_credit";
                    $item->type_item = "credit";
                    // set item details
                    $data = array();
                    $data["amount"] = $data_item["amount"];
                    $data["price"] = $data_item["amount"];
                    $data["chartid"] = $data_item["chartid"];
                    $data["description"] = "Credit For: " . $data_item["description"];
                    // fetch taxes for selected item
                    $sql_tax_obj = new sql_query();
                    $sql_tax_obj->string = "SELECT taxid FROM services_taxes WHERE serviceid='" . $data_item["customid"] . "'";
                    $sql_tax_obj->execute();
                    if ($sql_tax_obj->num_rows()) {
                        $sql_tax_obj->fetch_array();
                        foreach ($sql_tax_obj->data as $data_tax) {
                            $sql_cust_tax_obj = new sql_query();
                            $sql_cust_tax_obj->string = "SELECT id FROM customers_taxes WHERE customerid='" . $credit->data["customerid"] . "' AND taxid='" . $data_tax["taxid"] . "'";
                            $sql_cust_tax_obj->execute();
                            if ($sql_cust_tax_obj->num_rows()) {
                                $data["tax_" . $data_tax["taxid"]] = "on";
                            }
                        }
                    }
                    unset($sql_tax_obj);
                    if (!$item->prepare_data($data)) {
                        log_write("error", "process", "An error was encountered whilst processing supplied data.");
                    } else {
                        $item->action_create();
                        $item->action_update();
                    }
                    unset($data);
                }
                // end of items loop
                /*
                	Re-calculate Credit Note Totals
                */
                $item->action_update_tax();
                $item->action_update_total();
                $item->action_update_ledger();
                // finsihed with credit items
                unset($item);
                /*
                	Apply Credit Note against the invoice if it hasn't been paid in full.
                */
                $amount_invoice = array();
                if ($data_ar["amount_total"] != $data_ar["amount_paid"]) {
                    // determine amount owing
                    $amount_invoice["owing"] = $data_ar["amount_total"] - $data_ar["amount_paid"];
                    if ($amount_invoice["owing"] <= 0) {
                        // nothing todo
                        log_write("notification", "repair", "Ignoring overpaid invoice " . $data_ar["code_invoice"] . " and assigning credit note to customer account/pool instead");
                    } else {
                        // determine credit amount
                        $amount_invoice["credit"] = sql_get_singlevalue("SELECT amount_total as value FROM account_ar_credit WHERE id='" . $credit->id . "' LIMIT 1");
                        if ($amount_invoice["credit"] > $amount_invoice["owing"]) {
                            // pay the amount owing which is less than the credit
                            $amount_invoice["creditpay"] = $amount_invoice["owing"];
                        } else {
                            // customer owes more than the credit is for, make credit payment amount maximum
                            $amount_invoice["creditpay"] = $amount_invoice["credit"];
                        }
                        // make credit payment against the invoice
                        $item = new invoice_items();
                        $item->id_invoice = $data_ar["id"];
                        $item->type_invoice = "ar";
                        $item->type_item = "payment";
                        // set item details
                        $data = array();
                        $data["date_trans"] = date("Y-m-d");
                        $data["amount"] = $amount_invoice["creditpay"];
                        $data["chartid"] = "credit";
                        $data["source"] = "CREDITED FUNDS (AUTOMATIC)";
                        $data["description"] = "Credit from credit note " . $credit->data["code_credit"] . " for service usage charge correction";
                        if (!$item->prepare_data($data)) {
                            log_write("error", "process", "An error was encountered whilst processing supplied data for credit payment to invoice");
                        } else {
                            // create & update payment item
                            $item->action_create();
                            $item->action_update();
                            // update invoice totals & ledger
                            $item->action_update_tax();
                            $item->action_update_total();
                            $item->action_update_ledger();
                            log_write("notification", "repair", "Applied credit of " . $amount_invoice["creditpay"] . "");
                        }
                        unset($item);
                    }
                    // end if credit payment made
                } else {
                    log_write("notification", "repair", "Credited invoice " . $data_ar["code_invoice"] . " has already been paid in full, assigning credit note to customer's credit pool for future use.");
                }
                /*
                	Email PDF credit notes and message.
                */
                if ($GLOBALS["config"]["ACCOUNTS_INVOICE_AUTOEMAIL"] == 1 || $GLOBALS["config"]["ACCOUNTS_INVOICE_AUTOEMAIL"] == "enabled") {
                    $email = $credit->generate_email();
                    $credit->email_credit($email["sender"], $email["to"], $email["cc"], $email["bcc"], $email["subject"], $email["message"]);
                } else {
                    log_write("notification", "repair", "No credit note email sent, ACCOUNTS_INVOICE_AUTOEMAIL is disabled.");
                }
                // unset the credit note
                unset($credit);
                /*
                	Flag the refunded usage periods for re-billing.
                
                	Now that we have refunded the usage on the selected invoice, we should then flag any service periods
                	of the same service type and invoice ID, to cause the usge to be rebilled in the next service billing month.
                */
                // fetch id_service_customer values from services where customer matches invoice
                $obj_sql_cust = new sql_query();
                $obj_sql_cust->string = "SELECT id FROM services_customers WHERE customerid='" . $data_ar["customerid"] . "' AND serviceid IN (" . format_arraytocommastring($option_services, NULL) . ")";
                $obj_sql_cust->execute();
                if ($obj_sql_cust->num_rows()) {
                    $obj_sql_cust->fetch_array();
                    foreach ($obj_sql_cust->data as $data_cust) {
                        // update any periods for this customer-service which have the ID of the selected invoice as
                        // the usage period invoice.
                        //
                        // these usage periods will then be re-invoiced at the next service invoicing run.
                        //
                        $obj_sql_period = new sql_query();
                        $obj_sql_period->string = "UPDATE services_customers_periods SET invoiceid_usage='0', rebill='1' WHERE invoiceid_usage='" . $data_ar["id"] . "' AND id_service_customer='" . $data_cust["id"] . "'";
                        $obj_sql_period->execute();
                    }
                    log_write("notification", "repair", "Flagged services for customer " . $data_ar["customerid"] . " to bill for usage periods.");
                } else {
                    log_write("warning", "repair", "No usage periods found to flag for rebilling for customer " . $data_ar["customerid"] . ", possibly the service has been deleted?");
                }
                unset($obj_sql_cust);
            }
            // if creditable items exist on the selected invoice
            if (error_check()) {
                // there was an error, do not continue processing invoices.
                continue;
            }
        }
    }
    // end of AR invoice loop
    /*
    	Close Transaction
    */
    if (error_check()) {
        // rollback/failure
        log_write("error", "repair", "An error occured whilst executing, rolling back DB changes");
        $obj_sql_trans->trans_rollback();
    } else {
        // commit
        log_write("notification", "repair", "Successful execution, applying DB changes");
        $obj_sql_trans->trans_commit();
    }
}
        }
        /*
        	Update Phase Details
        */
        if ($phaseid) {
            $sql_obj->string = "UPDATE `project_phases` SET " . "name_phase='" . $data["name_phase"] . "', " . "description='" . $data["description"] . "' " . "WHERE id='{$phaseid}' LIMIT 1";
            $sql_obj->execute();
        }
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "process", "A fatal error occuring whilst attempting to update the phase. No changes were made.");
        } else {
            $sql_obj->trans_commit();
            if ($mode == "add") {
                log_write("notification", "project", "Phase successfully created.");
            } else {
                log_write("notification", "project", "Phase successfully updated.");
            }
        }
        // display updated details
        header("Location: ../index.php?page=projects/phases.php&id={$projectid}");
        exit(0);
    }
    /////////////////////////
} else {
    // user does not have perms to view this page/isn't logged on
    error_render_noperms();
    header("Location: ../index.php?page=message.php");
Esempio n. 22
0
 function autopay()
 {
     log_write("debug", "invoice_autopay", "Executing autopay()");
     // check capabilities
     if (!$this->capable) {
         if (!$this->check_autopay_capable()) {
             return 0;
         }
     }
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Load Invoice Data
     */
     $this->obj_invoice = new invoice();
     $this->obj_invoice->id = $this->id_invoice;
     $this->obj_invoice->type = $this->type_invoice;
     if (!$this->obj_invoice->load_data()) {
         log_write("error", "invoice_autopay", "Unable to load invoice data for checking for autopayments");
         return -1;
     }
     /*
     	Make AutoPayments
     */
     // handle credit payments
     $this->autopay_credit();
     // future: credit card, direct debit?
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "invoice_autopay", "An error occured whilst making an invoice autopayment");
         return 0;
     } else {
         $sql_obj->trans_commit();
         return 1;
     }
 }
Esempio n. 23
0
 function invoice_generate($invoiceid = NULL)
 {
     log_write("debug", "inc_customers", "Executing invoice_generate()");
     // we don't need to worry about checking if this is the appropiate date, that logic is handled by
     // other functions before calling this one.
     // initatiate SQL
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     // do we need to create an invoice?
     if (!$invoiceid) {
         $obj_invoice = new invoice();
         $obj_invoice->type = "ar";
         $obj_invoice->data["customerid"] = $this->id;
         $obj_invoice->data["employeeid"] = 1;
         $obj_invoice->data["notes"] = "Invoice generated from customer orders page.";
         $obj_invoice->prepare_date_shift();
         $obj_invoice->action_create();
         $invoiceid = $obj_invoice->id;
         log_write("debug", "inc_customers", "Creating a new invoice with ID of {$invoiceid}");
     } else {
         // reuse existing
         log_write("debug", "inc_customers", "Using specified invoice {$invoiceid} for orders invoicing");
     }
     // run through the items and add to the invoice
     $obj_orders_sql = new sql_query();
     $obj_orders_sql->string = "SELECT * FROM customers_orders WHERE id_customer='" . $this->id . "'";
     $obj_orders_sql->execute();
     if ($obj_orders_sql->num_rows()) {
         $obj_orders_sql->fetch_array();
         foreach ($obj_orders_sql->data as $data_order) {
             log_write("debug", "inc_customers", "Adding order item " . $data_order["id"] . " to invoice " . $invoiceid . " for customer " . $this->id . "");
             // select values desired, certain safety checks
             $data_order_tmp = array();
             $data_order_tmp["customid"] = $data_order["customid"];
             $data_order_tmp["quantity"] = $data_order["quantity"];
             $data_order_tmp["units"] = addslashes($data_order["units"]);
             $data_order_tmp["amount"] = $data_order["amount"];
             $data_order_tmp["price"] = $data_order["price"];
             $data_order_tmp["discount"] = $data_order["discount"];
             $data_order_tmp["description"] = addslashes($data_order["description"]);
             // Add each order as an item on the invoice.
             $obj_item = new invoice_items();
             $obj_item->id_invoice = $invoiceid;
             $obj_item->type_invoice = "ar";
             $obj_item->type_item = $data_order["type"];
             $obj_item->prepare_data($data_order_tmp);
             $obj_item->action_create();
             $obj_item->action_update();
             // delete the item now that it's been added
             $obj_delete_sql = new sql_query();
             $obj_delete_sql->string = "DELETE FROM customers_orders WHERE id='" . $data_order["id"] . "' LIMIT 1";
             $obj_delete_sql->execute();
             unset($obj_delete_sql);
         }
         // update invoice summary information
         $obj_item->action_update_tax();
         $obj_item->action_update_total();
         $obj_item->action_update_ledger();
         unset($obj_item);
     }
     // end if order items.
     // make automated payments - such as customer credit pool or auto-pay credit card functionality
     if ($GLOBALS["config"]["ACCOUNTS_AUTOPAY"]) {
         log_write("debug", "inc_services_invoicegen", "Autopay Functionality Enabled, running appropiate functions for invoice ID {$invoiceid}");
         $obj_autopay = new invoice_autopay();
         $obj_autopay->id_invoice = $invoiceid;
         $obj_autopay->type_invoice = "ar";
         $obj_autopay->autopay();
         unset($obj_autopay);
     }
     // save changes
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "inc_customers", "An error occurred whilst attempting to generate an invoice.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         log_write("notification", "inc_customers", "Successfully generate invoice " . $obj_invoice->data["code_invoice"] . " for customer " . $this->data["name_customer"] . "");
         return $invoiceid;
     }
 }
function service_invoices_generate($customerid = NULL)
{
    log_debug("inc_services_invoicegen", "Executing service_invoices_generate({$customerid})");
    /*
    	Invoice Report Statistics
    */
    $invoice_stats = array();
    $invoice_stats["time_start"] = time();
    $invoice_stats["total"] = 0;
    $invoice_stats["total_failed"] = 0;
    /*
    	Run through all the customers
    */
    $sql_customers_obj = new sql_query();
    $sql_customers_obj->string = "SELECT id, code_customer, name_customer FROM customers";
    if ($customerid) {
        $sql_customers_obj->string .= " WHERE id='{$customerid}' LIMIT 1";
    }
    $sql_customers_obj->execute();
    if ($sql_customers_obj->num_rows()) {
        $sql_customers_obj->fetch_array();
        foreach ($sql_customers_obj->data as $customer_data) {
            /*
            	Fetch all periods belonging to this customer which need to be billed.
            */
            $sql_periods_obj = new sql_query();
            $sql_periods_obj->string = "SELECT " . "services_customers_periods.id, " . "services_customers_periods.rebill, " . "services_customers_periods.invoiceid, " . "services_customers_periods.invoiceid_usage, " . "services_customers_periods.date_start, " . "services_customers_periods.date_end, " . "services_customers.date_period_first, " . "services_customers.date_period_next, " . "services_customers.date_period_last, " . "services_customers.id as id_service_customer, " . "services_customers.serviceid " . "FROM services_customers_periods " . "LEFT JOIN services_customers ON services_customers.id = services_customers_periods.id_service_customer " . "WHERE " . "services_customers.customerid='" . $customer_data["id"] . "' " . "AND (invoiceid = '0' OR rebill = '1')" . "AND date_billed <= '" . date("Y-m-d") . "'";
            $sql_periods_obj->execute();
            if ($sql_periods_obj->num_rows()) {
                $sql_periods_obj->fetch_array();
                /*
                	BILL CUSTOMER
                
                	This customer has at least one service that needs to be billed. We need to create
                	a new invoice, and then process each service, adding the services to the invoice as 
                	items.
                */
                /*
                	Start Transaction
                
                	(one transaction per invoice)
                */
                $sql_obj = new sql_query();
                $sql_obj->trans_begin();
                /*
                	Create new invoice
                */
                $invoice = new invoice();
                $invoice->type = "ar";
                $invoice->prepare_code_invoice();
                $invoice->data["customerid"] = $customer_data["id"];
                $invoice->data["employeeid"] = 1;
                // set employee to the default internal user
                $invoice->prepare_date_shift();
                if (!$invoice->action_create()) {
                    log_write("error", "services_invoicegen", "Unexpected problem occured whilst attempting to create invoice.");
                    $sql_obj->trans_rollback();
                    return 0;
                }
                $invoiceid = $invoice->id;
                $invoicecode = $invoice->data["code_invoice"];
                unset($invoice);
                /*
                	Create Service Items
                						
                	We need to create an item for basic service plan - IE: the regular fixed fee, and another item for any
                	excess usage.
                */
                foreach ($sql_periods_obj->data as $period_data) {
                    /*
                    	TODO:
                    
                    	We should be able to re-bill usage here when needed with a clever cheat - if we load the periods to be billed,
                    	we can then ignore the plan item, and rebill the usage item.
                    */
                    $period_data["mode"] = "standard";
                    if ($period_data["rebill"]) {
                        if (!$period_data["invoiceid_usage"] && $period_data["invoiceid"]) {
                            // the selected period has been billed, but the usage has been flagged for rebilling - we need to *ignore* the base plan
                            // item and only bill for the usage range.
                            $period_data["mode"] = "rebill_usage";
                        }
                    }
                    // fetch service details
                    $obj_service = new service_bundle();
                    $obj_service->option_type = "customer";
                    $obj_service->option_type_id = $period_data["id_service_customer"];
                    if (!$obj_service->verify_id_options()) {
                        log_write("error", "customers_services", "Unable to verify service ID of " . $period_data["id_service_customer"] . " as being valid.");
                        return 0;
                    }
                    $obj_service->load_data();
                    $obj_service->load_data_options();
                    // ratio is used to adjust prices for partial periods
                    $ratio = 1;
                    if ($obj_service->data["billing_mode_string"] == "monthend" || $obj_service->data["billing_mode_string"] == "monthadvance" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                        log_debug("services_invoicegen", "Invoice bills by month date");
                        /*
                        	Handle monthly billing
                        
                        	Normally, monthly billing is easy, however the very first billing period is special, as it may span a more than 1 month, or
                        	consist of less than the full month, depending on the operational mode.
                        
                        	SERVICE_PARTPERIOD_MODE == seporate
                        
                        		If a service is started on 2008-01-09, the end date of the billing period will be 2008-01-31, which is less
                        		than one month - 22 days.
                        
                        		We can calculate with:
                        
                        		( standard_cost / normal_month_num_days ) * num_days_in_partial_month == total_amount
                        
                        
                        	SERVICE_PARTPERIOD_MODE == merge
                        
                        		If a service is started on 2008-01-09, the end of the billing period will be 2008-02-29, which is 1 month + 21 day.
                        
                        		We can calculate with:
                        
                        		( standard_cost / normal_month_num_days ) * num_days_in_partial_month == extra_amount
                        		total_amount = (extra_amount + normal_amount)
                        
                        	Note: we do not increase included units for licenses service types, since these need to remain fixed and do not
                        	scale with the month.
                        */
                        // check if the period start date is not the first of the month - this means that the period
                        // is an inital partial period.
                        if (time_calculate_daynum($period_data["date_start"]) != "01") {
                            // very first billing month
                            log_write("debug", "services_invoicegen", "First billing month for this service, adjusting pricing to suit days.");
                            // figure out normal period length - rememeber, whilst service may be configured to align monthly, it needs to
                            // handle pricing calculations for variations such as month, year, etc.
                            // get the number of days of a regular period - this correctly handles, month, year, etc
                            // 1. generate the next period dates, this will be of regular length
                            // 2. calculate number of days
                            $tmp_dates = service_period_dates_generate($period_data["date_period_next"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                            $regular_period_num_days = sql_get_singlevalue("SELECT DATEDIFF('" . $tmp_dates["end"] . "', '" . $tmp_dates["start"] . "') as value");
                            // process for short/long periods
                            //
                            if ($GLOBALS["config"]["SERVICE_PARTPERIOD_MODE"] == "seporate") {
                                log_write("debug", "services_invoicegen", "Adjusting for partial month period (SERVICE_PARTPERIOD_MODE == seporate)");
                                // work out the total number of days in partial month
                                $short_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_data["date_start"]));
                                $short_month_days_short = $short_month_days_total - time_calculate_daynum($period_data["date_start"]);
                                log_write("debug", "services_invoicegen", "Short initial billing period of {$short_month_days_short} days");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $regular_period_num_days * $short_month_days_short;
                                // calculate ratio
                                $ratio = $short_month_days_short / $regular_period_num_days;
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                            } else {
                                log_write("debug", "services_invoicegen", "Adjusting for extended month period (SERVICE_PARTPERIOD_MODE == merge");
                                // work out the number of days extra
                                $extra_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_data["date_start"]));
                                $extra_month_days_extra = $extra_month_days_total - time_calculate_daynum($period_data["date_start"]);
                                log_debug("services_invoicegen", "{$extra_month_days_extra} additional days ontop of started billing period");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $regular_period_num_days * $extra_month_days_extra + $obj_service->data["price"];
                                // calculate ratio
                                $ratio = ($extra_month_days_extra + $extra_month_days_total) / $regular_period_num_days;
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle extended period.");
                            }
                        }
                    }
                    /*
                    	Service Last Period Handling
                    
                    	If this is the last period for a service, it may be of a different link to the regular full period term
                    	- this effects both month and period based services.
                    */
                    if ($period_data["date_period_last"] != "0000-00-00") {
                        log_write("debug", "services_invoicegen", "Service has a final period date set (" . $period_data["date_period_last"] . ")");
                        if ($period_data["date_period_last"] == $period_data["date_end"] || time_date_to_timestamp($period_data["date_period_last"]) < time_date_to_timestamp($period_data["date_end"])) {
                            log_write("debug", "services_invoicegen", "Service is a final period, checking for time adjustment (if any)");
                            // fetch the regular end date
                            $orig_dates = service_period_dates_generate($period_data["date_start"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                            if ($orig_dates["end"] != $period_data["date_end"]) {
                                // work out the total number of days
                                $time = NULL;
                                $time["start"] = time_date_to_timestamp($period_data["date_start"]);
                                $time["end_orig"] = time_date_to_timestamp($orig_dates["end"]);
                                $time["end_new"] = time_date_to_timestamp($period_data["date_end"]);
                                $time["orig_days"] = sprintf("%d", ($time["end_orig"] - $time["start"]) / 86400);
                                $time["new_days"] = sprintf("%d", ($time["end_new"] - $time["start"]) / 86400);
                                log_write("debug", "services_invoicegen", "Short initial billing period of " . $time["new_days"] . " days rather than expected " . $time["orig_days"] . "");
                                // calculate correct base fee
                                $obj_service->data["price"] = $obj_service->data["price"] / $time["orig_days"] * $time["new_days"];
                                // calculate ratio
                                $ratio = $time["new_days"] / $time["orig_days"];
                                log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                unset($time);
                            } else {
                                log_write("debug", "services_invoicegen", "Final service period is regular size, no adjustment required.");
                            }
                        }
                    }
                    /*
                    	Service Base Plan Item
                    
                    	Note: There can be a suitation where we shouldn't charge for the base plan
                    	fee, when the period end date is older than the service first start date.
                    
                    	This can happen due to the migration mode, which creates a usage-only period
                    	before the actual plan starts properly.
                    */
                    if (time_date_to_timestamp($period_data["date_period_first"]) < time_date_to_timestamp($period_data["date_end"]) && $period_data["mode"] == "standard") {
                        // date of the period is newer than the start date
                        log_write("debug", "inc_service_invoicegen", "Generating base plan item for period " . $period_data["date_start"] . " to " . $period_data["date_end"] . "");
                        // start the item
                        $invoice_item = new invoice_items();
                        $invoice_item->id_invoice = $invoiceid;
                        $invoice_item->type_invoice = "ar";
                        $invoice_item->type_item = "service";
                        $itemdata = array();
                        // chart ID
                        $itemdata["chartid"] = $obj_service->data["chartid"];
                        // service ID
                        $itemdata["customid"] = $obj_service->id;
                        // no units apply
                        $itemdata["units"] = "";
                        // description
                        switch ($obj_service->data["typeid_string"]) {
                            case "phone_single":
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " from " . $period_data["date_start"] . " to " . $period_data["date_end"] . " (" . $obj_service->data["phone_ddi_single"] . ")";
                                if ($obj_service->data["description"]) {
                                    $itemdata["description"] .= "\n\n";
                                    $itemdata["description"] .= addslashes($obj_service->data["description"]);
                                }
                                break;
                            default:
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " from " . $period_data["date_start"] . " to " . $period_data["date_end"];
                                if ($obj_service->data["description"]) {
                                    $itemdata["description"] .= "\n\n";
                                    $itemdata["description"] .= addslashes($obj_service->data["description"]);
                                }
                                break;
                        }
                        // handle final periods
                        if ($period_data["date_period_last"] != "0000-00-00" && $period_data["date_start"] == $period_data["date_end"]) {
                            $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " service terminated as of " . $period_data["date_end"] . "";
                        }
                        // is this service item part of a bundle? if it is, we shouldn't charge for the plan
                        if (!empty($obj_service->data["id_bundle_component"])) {
                            // no charge for the base plan, since this is handled by
                            // the bundle item itself
                            $itemdata["price"] = "0.00";
                            $itemdata["quantity"] = 1;
                            $itemdata["discount"] = "0";
                            // append description
                            $itemdata["description"] .= " (part of bundle)";
                        } else {
                            // amount
                            $itemdata["price"] = $obj_service->data["price"];
                            $itemdata["quantity"] = 1;
                            $itemdata["discount"] = $obj_service->data["discount"];
                        }
                        // create item
                        $invoice_item->prepare_data($itemdata);
                        $invoice_item->action_update();
                        unset($invoice_item);
                    } else {
                        log_write("debug", "inc_service_invoicegen", "Skipping base plan item generation, due to migration or rebill mode operation");
                    }
                    /*
                    	Service Usage Items
                    
                    	Create another item on the invoice for any usage, provided that the service type is a usage service
                    */
                    $period_usage_data = array();
                    /*
                    	Depending on the service type, we need to handle the usage period in one of two ways:
                    	1. Invoice usage for the current period that has just ended (periodend/monthend)
                    	2. Invoice usage for the period BEFORE the current period. (periodtelco/monthtelco)
                    */
                    if ($obj_service->data["billing_mode_string"] == "periodtelco" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                        log_write("debug", "service_invoicegen", "Determining previous period for telco-style usage billing (if any)");
                        if ($period_data["mode"] == "standard") {
                            // fetch previous period (if any) - we can determine the previous by subtracting one day from the current period start date.
                            $tmp_date = explode("-", $period_data["date_start"]);
                            $period_usage_data["date_end"] = date("Y-m-d", mktime(0, 0, 0, $tmp_date[1], $tmp_date[2] - 1, $tmp_date[0]));
                        } elseif ($period_data["mode"] == "rebill_usage") {
                            // use the period as the usage period
                            log_write("debug", "service_invoicegen", "Using the selected period " . $period_usage_data["date_end"] . " for rebill_usage mode");
                            $period_usage_data["date_end"] = $period_data["date_end"];
                        }
                        // fetch period data to confirm previous period
                        $sql_obj = new sql_query();
                        $sql_obj->string = "SELECT id, date_start, date_end FROM services_customers_periods WHERE id_service_customer='" . $period_data["id_service_customer"] . "' AND date_end='" . $period_usage_data["date_end"] . "' LIMIT 1";
                        $sql_obj->execute();
                        if ($sql_obj->num_rows()) {
                            log_write("debug", "service_invoicegen", "Billing for seporate past usage period");
                            // there is a valid usage period
                            $period_usage_data["active"] = "yes";
                            // fetch dates
                            $sql_obj->fetch_array();
                            $period_usage_data["id_service_customer"] = $period_data["id_service_customer"];
                            $period_usage_data["id"] = $sql_obj->data[0]["id"];
                            $period_usage_data["date_start"] = $sql_obj->data[0]["date_start"];
                            $period_usage_data["date_end"] = $sql_obj->data[0]["date_end"];
                            // tracing
                            log_write("debug", "service_invoicegen", "Current period is (" . $period_data["date_start"] . " to " . $period_data["date_end"] . "), usage period is (" . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . ")");
                            // reset ratio
                            $ratio = 1;
                            /*
                            	TODO: This code is a replicant of the section further above for calculating partial
                            	periods and should really be functionalised as part of service usage continual improvements
                            */
                            // calculate usage abnormal period
                            if ($obj_service->data["billing_mode_string"] == "monthend" || $obj_service->data["billing_mode_string"] == "monthadvance" || $obj_service->data["billing_mode_string"] == "monthtelco") {
                                log_debug("services_invoicegen", "Usage period service bills by month date");
                                if (time_calculate_daynum($period_usage_data["date_start"]) != "01") {
                                    // very first billing month
                                    log_write("debug", "services_invoicegen", "First billing month for this usage period, adjusting pricing to suit days.");
                                    if ($GLOBALS["config"]["SERVICE_PARTPERIOD_MODE"] == "seporate") {
                                        log_write("debug", "services_invoicegen", "Adjusting for partial month period (SERVICE_PARTPERIOD_MODE == seporate)");
                                        // work out the total number of days
                                        $short_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_usage_data["date_start"]));
                                        $short_month_days_short = $short_month_days_total - time_calculate_daynum($period_usage_data["date_start"]);
                                        log_write("debug", "services_invoicegen", "Short initial billing period of {$short_month_days_short} days");
                                        // calculate ratio
                                        $ratio = $short_month_days_short / $short_month_days_total;
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                    } else {
                                        log_write("debug", "services_invoicegen", "Adjusting for extended month period (SERVICE_PARTPERIOD_MODE == merge");
                                        // work out the number of days extra
                                        $extra_month_days_total = time_calculate_daynum(time_calculate_monthdate_last($period_usage_data["date_start"]));
                                        $extra_month_days_extra = $extra_month_days_total - time_calculate_daynum($period_usage_data["date_start"]);
                                        log_debug("services_invoicegen", "{$extra_month_days_extra} additional days ontop of started billing period");
                                        // calculate ratio
                                        $ratio = ($extra_month_days_extra + $extra_month_days_total) / $extra_month_days_total;
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle extended period.");
                                    }
                                }
                            }
                            // end of calculate usage abnormal period
                            if ($period_data["date_period_last"] != "0000-00-00") {
                                log_write("debug", "services_invoicegen", "Service has a final period date set (" . $period_data["date_period_last"] . ")");
                                if ($period_data["date_period_last"] == $period_usage_data["date_end"] || time_date_to_timestamp($period_data["date_period_last"]) < time_date_to_timestamp($period_usage_data["date_end"])) {
                                    log_write("debug", "services_invoicegen", "Service is a final period, checking for time adjustment (if any)");
                                    // fetch the regular end date
                                    $orig_dates = service_period_dates_generate($period_usage_data["date_start"], $obj_service->data["billing_cycle_string"], $obj_service->data["billing_mode_string"]);
                                    if ($orig_dates["end"] != $period_usage_data["date_end"]) {
                                        // work out the total number of days
                                        $time = NULL;
                                        $time["start"] = time_date_to_timestamp($period_usage_data["date_start"]);
                                        $time["end_orig"] = time_date_to_timestamp($orig_dates["end"]);
                                        $time["end_new"] = time_date_to_timestamp($period_usage_data["date_end"]);
                                        $time["orig_days"] = sprintf("%d", ($time["end_orig"] - $time["start"]) / 86400);
                                        $time["new_days"] = sprintf("%d", ($time["end_new"] - $time["start"]) / 86400);
                                        log_write("debug", "services_invoicegen", "Short initial billing period of " . $time["new_days"] . " days rather than expected " . $time["orig_days"] . "");
                                        // calculate correct base fee
                                        $obj_service->data["price"] = $obj_service->data["price"] / $time["orig_days"] * $time["new_days"];
                                        // calculate ratio
                                        $ratio = $time["new_days"] / $time["orig_days"];
                                        log_write("debug", "services_invoicegen", "Calculated service bill ratio of {$ratio} to handle short period.");
                                        unset($time);
                                    } else {
                                        log_write("debug", "services_invoicegen", "Final service period is regular size, no adjustment required.");
                                    }
                                }
                            }
                        } else {
                            log_write("debug", "service_invoicegen", "Not billing for past usage, as this appears to be the first plan period so no usage can exist yet");
                        }
                    } else {
                        log_write("debug", "service_invoicegen", "Using plan period as data usage period (" . $period_data["date_start"] . " to " . $period_data["date_end"] . "");
                        // use current period
                        $period_usage_data["active"] = "yes";
                        $period_usage_data["id_service_customer"] = $period_data["id_service_customer"];
                        $period_usage_data["id"] = $period_data["id"];
                        $period_usage_data["date_start"] = $period_data["date_start"];
                        $period_usage_data["date_end"] = $period_data["date_end"];
                    }
                    /*
                    	Create usage items if there is a valid usage period
                    */
                    if (!empty($period_usage_data["active"])) {
                        log_write("debug", "service_invoicegen", "Creating usage items due to active usage period");
                        switch ($obj_service->data["typeid_string"]) {
                            case "generic_with_usage":
                                /*
                                	GENERIC_WITH_USAGE
                                
                                	This service is to be used for any non-traffic, non-time accounting service that needs to track usage. Examples of this
                                	could be counting the number of API requests, size of disk usage on a vhost, etc.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for generic_with_usage");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Adjust Included Units to handle partial or extended periods
                                */
                                if ($ratio != "1") {
                                    $obj_service->data["included_units"] = sprintf("%d", $obj_service->data["included_units"] * $ratio);
                                }
                                /*
                                	Fetch usage amount
                                */
                                $usage_obj = new service_usage_generic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usagedata();
                                    if ($usage_obj->data["total_byunits"]) {
                                        $usage = $usage_obj->data["total_byunits"];
                                    } else {
                                        $usage = $usage_obj->data["total"];
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	Charge for the usage in units
                                */
                                $unitname = addslashes($obj_service->data["units"]);
                                if ($usage > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $usage_excess = $usage - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"];
                                    $itemdata["quantity"] = $usage_excess;
                                    $itemdata["units"] = $unitname;
                                    // description example:		Used 120 ZZ out of 50 ZZ included in plan
                                    //				Excess usage of 70 ZZ charged at $5.00 per ZZ
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                    $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . $obj_service->data["price_extraunits"] . " per {$unitname}.";
                                } else {
                                    // description example:		Used 120 ZZ out of 50 ZZ included in plan
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='{$usage}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                break;
                            case "licenses":
                                /*
                                	LICENSES
                                
                                	No data usage, but there is a quantity field for the customer's account to specify the
                                	quantity of licenses that they have.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for licenses");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Determine Additional Charges
                                */
                                // charge for any extra licenses
                                if ($obj_service->data["quantity"] > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $licenses_excess = $obj_service->data["quantity"] - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"] * $ratio;
                                    $itemdata["quantity"] = $licenses_excess;
                                    $itemdata["units"] = addslashes($obj_service->data["units"]);
                                    // description example:		10 licences included
                                    //				2 additional licenses charged at $24.00 each
                                    $itemdata["description"] .= "\n" . $obj_service->data["included_units"] . " " . $obj_service->data["units"] . " included";
                                    $itemdata["description"] .= "\n{$licenses_excess} additional " . $obj_service->data["units"] . " charged at " . $obj_service->data["price_extraunits"] . " each.";
                                } else {
                                    // description example:		10 licenses
                                    $itemdata["description"] .= "\n" . $period_data["quantity"] . " " . $period_data["units"] . ".";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                break;
                            case "time":
                                /*
                                	TIME
                                
                                	Simular to the generic usage type, but instead of units being a text field, units
                                	is an ID to the service_units table.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for time traffic");
                                /*
                                	Usage Item Basics
                                */
                                // start the item
                                $invoice_item = new invoice_items();
                                $invoice_item->id_invoice = $invoiceid;
                                $invoice_item->type_invoice = "ar";
                                $invoice_item->type_item = "service_usage";
                                $itemdata = array();
                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                $itemdata["customid"] = $obj_service->id;
                                $itemdata["discount"] = 0;
                                /*
                                	Adjust Included Units to handle partial or extended periods
                                */
                                if ($ratio != "1") {
                                    $obj_service->data["included_units"] = sprintf("%d", $obj_service->data["included_units"] * $ratio);
                                }
                                /*
                                	Fetch usage amount
                                */
                                $usage_obj = new service_usage_generic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usagedata();
                                    if ($usage_obj->data["total_byunits"]) {
                                        $usage = $usage_obj->data["total_byunits"];
                                    } else {
                                        $usage = $usage_obj->data["total"];
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	Charge for the usage in units
                                */
                                $unitname = sql_get_singlevalue("SELECT name as value FROM service_units WHERE id='" . $obj_service->data["units"] . "'");
                                if ($usage > $obj_service->data["included_units"]) {
                                    // there is excess usage that we can bill for.
                                    $usage_excess = $usage - $obj_service->data["included_units"];
                                    // set item attributes
                                    $itemdata["price"] = $obj_service->data["price_extraunits"];
                                    $itemdata["quantity"] = $usage_excess;
                                    $itemdata["units"] = $unitname;
                                    // description example:		Used 120 GB out of 50 GB included in plan
                                    //				Excess usage of 70 GB charged at $5.00 per GB
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                    $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . $obj_service->data["price_extraunits"] . " per {$unitname}.";
                                } else {
                                    // description example:		Used 10 out of 50 included units
                                    $itemdata["description"] .= "\nUsed {$usage} {$unitname} out of " . $obj_service->data["included_units"] . " {$unitname} included in plan.";
                                }
                                /*
                                	Add the item to the invoice
                                */
                                $invoice_item->prepare_data($itemdata);
                                $invoice_item->action_update();
                                unset($invoice_item);
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='{$usage}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                break;
                            case "data_traffic":
                                /*
                                	DATA_TRAFFIC
                                
                                	We make use of the service_usage_traffic logic to determine the usage across all IP
                                	addressess assigned to this customer and then bill accordingly.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for time/data_traffic");
                                /*
                                	Fetch data traffic plan usage type
                                */
                                $unitname = sql_get_singlevalue("SELECT name as value FROM service_units WHERE id='" . $obj_service->data["units"] . "'");
                                /*
                                	Fetch usage amount - the returned usage structure will include breakdown of traffic
                                	by configured types.
                                */
                                $usage_obj = new service_usage_traffic();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                /*
                                	Fetch Traffic Caps & Details
                                
                                	Returns all the traffic cap types including overrides.
                                
                                	id_type,
                                	id_cap,
                                	type_name,
                                	type_label,
                                	cap_mode,
                                	cap_units_included,
                                	cap_units_price
                                */
                                $traffic_types_obj = new traffic_caps();
                                $traffic_types_obj->id_service = $obj_service->id;
                                $traffic_types_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $traffic_types_obj->load_data_traffic_caps();
                                $traffic_types_obj->load_data_override_caps();
                                /*
                                	Generate Traffic Bills
                                */
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usage_traffic();
                                    foreach ($traffic_types_obj->data as $data_traffic_cap) {
                                        // Adjust Included Units to handle partial or extended periods
                                        if ($ratio != "1") {
                                            $data_traffic_cap["cap_units_included"] = sprintf("%d", $data_traffic_cap["cap_units_included"] * $ratio);
                                        }
                                        // if there is only a single traffic cap, we should make the traffic type name blank, since there's only going to be
                                        // one line item anyway.
                                        if ($traffic_types_obj->data_num_rows == 1) {
                                            $data_traffic_cap["type_name"] = "";
                                        }
                                        // if the any traffic type is zero and there are other traffic types, we should skip it, since most likely
                                        // the other traffic types provide everything expected.
                                        //
                                        if ($traffic_types_obj->data_num_rows > 1 && $data_traffic_cap["type_label"] == "*" && $usage_obj->data["total_byunits"]["*"] == 0) {
                                            continue;
                                        }
                                        // start service item
                                        $invoice_item = new invoice_items();
                                        $invoice_item->id_invoice = $invoiceid;
                                        $invoice_item->type_invoice = "ar";
                                        $invoice_item->type_item = "service_usage";
                                        $itemdata = array();
                                        $itemdata["chartid"] = $obj_service->data["chartid"];
                                        $itemdata["customid"] = $obj_service->id;
                                        // base details
                                        $itemdata["price"] = 0;
                                        $itemdata["quantity"] = 0;
                                        $itemdata["discount"] = 0;
                                        $itemdata["units"] = "";
                                        $itemdata["description"] = addslashes($obj_service->data["name_service"]) . " usage from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"];
                                        if ($data_traffic_cap["cap_mode"] == "unlimited") {
                                            // unlimited data cap, there will never be any excess traffic charges, so the line item
                                            // description should be purely for informative purposes.
                                            $itemdata["description"] .= "\nUnlimited " . addslashes($data_traffic_cap["type_name"]) . " traffic, total of " . $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] . " {$unitname} used\n";
                                        } else {
                                            // capped traffic - check for excess changes, otherwise just report on how much traffic
                                            // that the customer used.
                                            // description example:		Used 10 GB out of 50 GB included in plan
                                            $itemdata["description"] .= "\nCapped " . addslashes($data_traffic_cap["type_name"]) . " traffic, used " . $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] . " {$unitname} out of " . $data_traffic_cap["cap_units_included"] . " {$unitname} in plan.";
                                            // handle excess charges
                                            //
                                            if ($usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] > $data_traffic_cap["cap_units_included"]) {
                                                // there is excess usage that we can bill for.
                                                $usage_excess = $usage_obj->data["total_byunits"][$data_traffic_cap["type_label"]] - $data_traffic_cap["cap_units_included"];
                                                // set item attributes
                                                $itemdata["price"] = $data_traffic_cap["cap_units_price"];
                                                $itemdata["quantity"] = $usage_excess;
                                                $itemdata["units"] = $unitname;
                                                // description example:		Excess usage of 70 GB charged at $5.00 per GB
                                                $itemdata["description"] .= "\nExcess usage of {$usage_excess} {$unitname} charged at " . format_money($data_traffic_cap["cap_units_price"]) . " per {$unitname}.";
                                            }
                                        }
                                        // end of traffic cap mode
                                        // add trunk usage item
                                        //
                                        $invoice_item->prepare_data($itemdata);
                                        $invoice_item->action_update();
                                        unset($invoice_item);
                                    }
                                }
                                /*
                                	Update usage value for period - this summary value is visable on the service
                                	history page and saves having to query lots of records to generate period totals.
                                */
                                $sql_obj = new sql_query();
                                $sql_obj->string = "UPDATE services_customers_periods SET usage_summary='" . $usage_obj->data["total_byunits"]["total"] . "' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                                $sql_obj->execute();
                                unset($usage_obj);
                                unset($traffic_types_obj);
                                break;
                            case "phone_single":
                            case "phone_tollfree":
                            case "phone_trunk":
                                /*
                                	PHONE_* SERVICES
                                
                                	The phone services are special and contain multiple usage items, for:
                                	* Additional DDI numbers
                                	* Additional Trunks
                                
                                	There are also multiple items for the call charges, grouped into one
                                	item for each DDI.
                                */
                                log_write("debug", "service_invoicegen", "Processing usage items for phone_single/phone_tollfree/phone_trunk");
                                // setup usage object
                                $usage_obj = new service_usage_cdr();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                $usage_obj->load_data_service();
                                /*
                                	1. DDI CHARGES
                                
                                	We need to fetch the total number of DDIs and see if there are any excess
                                	charges due to overage of the allocated amount in the plan.
                                */
                                if ($obj_service->data["typeid_string"] == "phone_trunk" && $period_data["mode"] == "standard") {
                                    // start service item
                                    $invoice_item = new invoice_items();
                                    $invoice_item->id_invoice = $invoiceid;
                                    $invoice_item->type_invoice = "ar";
                                    $invoice_item->type_item = "service_usage";
                                    $itemdata = array();
                                    $itemdata["chartid"] = $obj_service->data["chartid"];
                                    $itemdata["customid"] = $obj_service->id;
                                    $itemdata["discount"] = 0;
                                    // fetch DDI usage
                                    $usage = $usage_obj->load_data_ddi();
                                    // determine excess usage charges
                                    if ($usage > $obj_service->data["phone_ddi_included_units"]) {
                                        // there is excess usage that we can bill for.
                                        $usage_excess = $usage - $obj_service->data["phone_ddi_included_units"];
                                        // set item attributes
                                        $itemdata["price"] = $obj_service->data["phone_ddi_price_extra_units"] * $ratio;
                                        log_write("debug", "DEBUG", "Ratio is {$ratio}, price is " . $itemdata["price"] . "");
                                        $itemdata["quantity"] = $usage_excess;
                                        $itemdata["units"] = "DDIs";
                                        if ($obj_service->data["phone_ddi_included_units"]) {
                                            $itemdata["description"] = $obj_service->data["phone_ddi_included_units"] . "x DDI numbers included in service plan plus additional " . $usage_excess . "x numbers from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        } else {
                                            // no included units, we use an alternative string format
                                            $itemdata["description"] = $usage_excess . "x DDI numbers from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        }
                                    } else {
                                        // no charge for this item
                                        $itemdata["description"] = $obj_service->data["phone_ddi_included_units"] . "x DDI numbers included in service plan from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                    }
                                    // add trunk usage item
                                    $invoice_item->prepare_data($itemdata);
                                    $invoice_item->action_update();
                                    unset($invoice_item);
                                }
                                /*
                                	2. Trunk Charges
                                */
                                if (($obj_service->data["typeid_string"] == "phone_trunk" || $obj_service->data["typeid_string"] == "phone_tollfree") && $period_data["mode"] == "standard") {
                                    // fetch the number of trunks included in the plan, along with the number provided
                                    // we can then see if there are any excess charges for these
                                    // start service item
                                    $invoice_item = new invoice_items();
                                    $invoice_item->id_invoice = $invoiceid;
                                    $invoice_item->type_invoice = "ar";
                                    $invoice_item->type_item = "service_usage";
                                    $itemdata = array();
                                    $itemdata["chartid"] = $obj_service->data["chartid"];
                                    $itemdata["customid"] = $obj_service->id;
                                    $itemdata["discount"] = 0;
                                    // determine excess usage charges
                                    if ($obj_service->data["phone_trunk_quantity"] > $obj_service->data["phone_trunk_included_units"]) {
                                        // there is excess usage that we can bill for.
                                        $usage_excess = $obj_service->data["phone_trunk_quantity"] - $obj_service->data["phone_trunk_included_units"];
                                        // set item attributes
                                        $itemdata["price"] = $obj_service->data["phone_trunk_price_extra_units"] * $ratio;
                                        $itemdata["quantity"] = $usage_excess;
                                        $itemdata["units"] = "trunks";
                                        if ($obj_service->data["phone_trunk_included_units"]) {
                                            $itemdata["description"] = $obj_service->data["phone_trunk_included_units"] . "x trunks included in service plan plus additional " . $usage_excess . "x trunks from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        } else {
                                            // no included trunks, adjust string to suit.
                                            $itemdata["description"] = $usage_excess . "x trunks from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                        }
                                    } else {
                                        // no charge for this item
                                        $itemdata["description"] = $obj_service->data["phone_trunk_included_units"] . "x trunks included in service plan from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                    }
                                    // add trunk usage item
                                    $invoice_item->prepare_data($itemdata);
                                    $invoice_item->action_update();
                                    unset($invoice_item);
                                }
                                /*
                                									Call Charges
                                	Use CDR usage billing module to handle call charges.
                                */
                                $usage_obj = new service_usage_cdr();
                                $usage_obj->id_service_customer = $period_usage_data["id_service_customer"];
                                $usage_obj->date_start = $period_usage_data["date_start"];
                                $usage_obj->date_end = $period_usage_data["date_end"];
                                $billgroup_obj = new sql_query();
                                $billgroup_obj->string = "SELECT id, billgroup_name FROM cdr_rate_billgroups";
                                $billgroup_obj->execute();
                                $billgroup_obj->fetch_array();
                                if ($usage_obj->load_data_service()) {
                                    $usage_obj->fetch_usage_calls();
                                    foreach ($billgroup_obj->data as $data_billgroup) {
                                        foreach ($usage_obj->data_ddi as $ddi) {
                                            if ($usage_obj->data[$ddi][$data_billgroup["id"]]["charges"] > 0) {
                                                // start service item
                                                $invoice_item = new invoice_items();
                                                $invoice_item->id_invoice = $invoiceid;
                                                $invoice_item->type_invoice = "ar";
                                                $invoice_item->type_item = "service_usage";
                                                $itemdata = array();
                                                $itemdata["chartid"] = $obj_service->data["chartid"];
                                                $itemdata["customid"] = $obj_service->id;
                                                // extra service details
                                                $itemdata["id_service_customer"] = $period_usage_data["id_service_customer"];
                                                $itemdata["id_period"] = $period_usage_data["id"];
                                                // determine excess usage charges
                                                $itemdata["discount"] = 0;
                                                $itemdata["price"] = $usage_obj->data[$ddi][$data_billgroup["id"]]["charges"];
                                                $itemdata["quantity"] = "1";
                                                $itemdata["units"] = "";
                                                $itemdata["description"] = $data_billgroup["billgroup_name"] . " call charges for {$ddi} from " . $period_usage_data["date_start"] . " to " . $period_usage_data["date_end"] . "";
                                                $itemdata["cdr_billgroup"] = $data_billgroup["id"];
                                                // add trunk usage item
                                                $invoice_item->prepare_data($itemdata);
                                                $invoice_item->action_update();
                                                unset($invoice_item);
                                            } else {
                                                log_write("debug", "inc_service_invoicegen", "Excluding DDI {$ddi} from " . $data_billgroup["billgroup_name"] . " due to no charges for the current period");
                                            }
                                        }
                                    }
                                }
                                unset($usage_obj);
                                /*
                                	If enabled, generate the CDR output format for the current service usage and attach
                                	it to the invoice via the invoice journal.
                                
                                	This feature can be enabled/disabled on a per-customer per-service basis.
                                */
                                if ($obj_service->data["billing_cdr_csv_output"]) {
                                    log_write("debug", "inc_service_invoicegen", "Generating CDR export file and attaching to invoice journal");
                                    // generate the CSV formatted export.
                                    $cdr_options = array('id_customer' => $customer_data["id"], 'id_service_customer' => $period_usage_data["id_service_customer"], 'period_start' => $period_usage_data["date_start"], 'period_end' => $period_usage_data["date_end"]);
                                    $csv = new cdr_csv($cdr_options);
                                    if (!($cdr_output = $csv->getCSV())) {
                                        log_write("error", "inc_service_invoicegen", "Unable to generate CSV ouput for the configured range");
                                        return 0;
                                    }
                                    // create journal entry
                                    $journal = new journal_process();
                                    $journal->prepare_set_journalname("account_ar");
                                    $journal->prepare_set_customid($invoiceid);
                                    $journal->prepare_set_type("file");
                                    // we use the prefix "SERVICE:" to find the journal at invoice time
                                    $journal->prepare_set_title("SERVICE: Service CDR Export Attachment");
                                    // details can be anything (just a text block)
                                    $data["content"] = NULL;
                                    $data["content"] .= "Automatically exported CDR for service " . addslashes($obj_service->data["name_service"]) . "\n";
                                    $data["content"] .= "\n";
                                    $journal->prepare_set_content($data["content"]);
                                    $journal->action_update();
                                    // create journal entry
                                    $journal->action_lock();
                                    // lock entry to avoid users deleting it or breaking it
                                    // upload file as an attachment for the journal
                                    $file_obj = new file_storage();
                                    $file_obj->data["type"] = "journal";
                                    $file_obj->data["customid"] = $journal->structure["id"];
                                    $file_obj->data["file_name"] = "invoice_" . $invoicecode . "_service_CDR_export.csv";
                                    if (!$file_obj->action_update_var($cdr_output)) {
                                        log_write("error", "inc_service_invoicegen", "Unable to upload export CDR invoice to journal.");
                                    }
                                    unset($csv);
                                    unset($journal);
                                    unset($file_obj);
                                    unset($cdr_output);
                                }
                                break;
                            case "generic_no_usage":
                            case "bundle":
                                // nothing todo for these service types
                                log_write("debug", "service_invoicegen", "Not processing usage, this is a non-usage service type");
                                break;
                            default:
                                // we should always match all service types, even if we don't need to do anything
                                // in particular for that type.
                                die("Unable to process unknown service type: " . $obj_service->data["typeid_string"] . "");
                                break;
                        }
                        // end of processing usage
                    } else {
                        log_write("debug", "service_invoicegen", "Not billing for current usage, as this appears to be the first plan period so no usage can exist yet");
                    }
                    /*
                    	Set invoice ID for period - this prevents the period from being added to
                    	any other invoices and allows users to see which invoice it was billed under
                    */
                    // set for plan period
                    $sql_obj = new sql_query();
                    $sql_obj->string = "UPDATE services_customers_periods SET invoiceid='{$invoiceid}', rebill='0' WHERE id='" . $period_data["id"] . "' LIMIT 1";
                    $sql_obj->execute();
                    // set for usage period
                    if (!empty($period_usage_data["active"])) {
                        $sql_obj = new sql_query();
                        $sql_obj->string = "UPDATE services_customers_periods SET invoiceid_usage='{$invoiceid}' WHERE id='" . $period_usage_data["id"] . "' LIMIT 1";
                        $sql_obj->execute();
                    }
                }
                // end of processing periods
                /*
                	Only process orders and invoice
                	summary details if we had no errors above.
                */
                if (!error_check()) {
                    /*
                    	Process any customer orders
                    */
                    if ($GLOBALS["config"]["ORDERS_BILL_ONSERVICE"]) {
                        log_write("debug", "inc_service_invoicegen", "Checking for customer orders to add to service invoice");
                        $obj_customer_orders = new customer_orders();
                        $obj_customer_orders->id = $customer_data["id"];
                        if ($obj_customer_orders->check_orders_num()) {
                            log_write("debug", "inc_service_invoicegen", "Order items exist, adding them to service invoice");
                            $obj_customer_orders->invoice_generate($invoiceid);
                        }
                    } else {
                        log_write("debug", "inc_service_invoicegen", "Not checking for customer orders, ORDERS_BILL_ONSERVICE is disabled currently");
                    }
                    /*
                    	Update the invoice details + Ledger
                    
                    	Processes:
                    	- taxes
                    	- ledger
                    	- invoice summary
                    
                    	We use the invoice_items class to perform these tasks, but we don't need
                    	to define an item ID for the functions being used to work.
                    */
                    $invoice = new invoice_items();
                    $invoice->id_invoice = $invoiceid;
                    $invoice->type_invoice = "ar";
                    $invoice->action_update_tax();
                    $invoice->action_update_ledger();
                    $invoice->action_update_total();
                    unset($invoice);
                    /*
                    	Update period information with invoiceid
                    */
                    $sql_obj = new sql_query();
                    $sql_obj->string = "UPDATE services_customers_periods SET invoiceid='{$invoiceid}' WHERE id='" . $period_data["id"] . "'";
                    $sql_obj->execute();
                }
                // end if error check
                /*
                	Automatic Payments
                
                	Makes automatic invoice payments using sources such as customer credit pools, reoccuring credit card transactions
                	and other sources.
                */
                if ($GLOBALS["config"]["ACCOUNTS_AUTOPAY"]) {
                    log_write("debug", "inc_services_invoicegen", "Autopay Functionality Enabled, running appropiate functions for invoice ID {$invoiceid}");
                    $obj_autopay = new invoice_autopay();
                    $obj_autopay->id_invoice = $invoiceid;
                    $obj_autopay->type_invoice = "ar";
                    $obj_autopay->autopay();
                    unset($obj_autopay);
                }
                /*
                	Commit
                
                	Conduct final error check, before commiting the new invoice and sending the customer an email
                	if appropiate.
                
                	(we obviously don't want to email them if the invoice is getting rolled back!)
                */
                $sql_obj = new sql_query();
                if (error_check()) {
                    $sql_obj->trans_rollback();
                    log_write("error", "inc_services_invoicegen", "An error occured whilst creating service invoice. No changes have been made.");
                } else {
                    $sql_obj->trans_commit();
                    // invoice creation complete - remove any notifications made by the invoice functions and return
                    // our own notification
                    $_SESSION["notification"]["message"] = array();
                    log_write("notification", "inc_services_invoicegen", "New invoice {$invoicecode} for customer " . $customer_data["code_customer"] . " created");
                    /*
                    		Send the invoice to the customer as a PDF via email
                    */
                    $emailed = "unsent";
                    if (sql_get_singlevalue("SELECT value FROM config WHERE name='EMAIL_ENABLE'") == "enabled") {
                        if (sql_get_singlevalue("SELECT value FROM config WHERE name='ACCOUNTS_INVOICE_AUTOEMAIL'") == "enabled") {
                            // load completed invoice data
                            $invoice = new invoice();
                            $invoice->id = $invoiceid;
                            $invoice->type = "ar";
                            $invoice->load_data();
                            $invoice->load_data_export();
                            if ($invoice->data["amount_total"] > 0) {
                                // generate an email
                                $email = $invoice->generate_email();
                                // send email
                                $invoice->email_invoice("system", $email["to"], $email["cc"], $email["bcc"], $email["subject"], $email["message"]);
                                // complete
                                log_write("notification", "inc_services_invoicegen", "Invoice {$invoicecode} has been emailed to customer (" . $email["to"] . ")");
                            } else {
                                // complete - invoice is for $0, so don't want to email out
                                log_write("notification", "inc_services_invoicegen", "Invoice {$invoicecode} has not been emailed to the customer due to invoice being for \$0.");
                            }
                            $emailed = "emailed - " . $email["to"];
                            unset($invoice);
                        }
                    }
                    // end if email enabled
                }
                // end if commit successful
                /*
                	Review Status
                
                	Here we need to check whether invoicing succeded/failed for the selected customer and process accordingly - we
                	also want to re-set the error flag if running a batch mode, to enable other customers to still be invoiced.
                */
                if (error_check()) {
                    // an error occured
                    $invoice_stats["total_failed"]++;
                    $invoice_stats["failed"][] = array("code_customer" => $customer_data["code_customer"], "name_customer" => $customer_data["name_customer"], "code_invoice" => $invoicecode);
                    // clear the error strings if we are processing from CLI this will allow us to continue on
                    // with additional invoices.
                    if (!empty($_SESSION["mode"])) {
                        if ($_SESSION["mode"] == "cli") {
                            log_write("debug", "inc_services_invoicegen", "Processing from CLI, clearing error flag and continuing with additional invoices");
                            error_clear();
                        }
                    }
                } else {
                    // successful
                    $invoice_stats["total"]++;
                    $invoice_stats["generated"][] = array("code_customer" => $customer_data["code_customer"], "name_customer" => $customer_data["name_customer"], "code_invoice" => $invoicecode, "sent" => $emailed);
                }
                // end of success/stats review
            }
            // end of processing customers
        }
        // end of if customers exist
    } else {
        log_debug("inc_services_invoicegen", "No services assigned to customer {$customerid}");
    }
    /*
    	Write Invoicing Report
    	
    	This only takes place if no customer ID is provided, eg we have run a full automatic invoice generation report.
    */
    if ($customerid == NULL) {
        log_write("debug", "inc_service_invoicegen", "Generating invoice report for invoice generation process");
        /*
        	Invoice Stats Calculations
        */
        $invoice_stats["time"] = time() - $invoice_stats["time_start"];
        if ($invoice_stats["time"] == 0) {
            $invoice_stats["time"] = 1;
        }
        /*
        	Write Invoice Report
        */
        $invoice_report = array();
        $invoice_report[] = "Complete Invoicing Run Time:\t" . $invoice_stats["time"] . " seconds";
        $invoice_report[] = "Total Invoices Generated:\t" . $invoice_stats["total"];
        $invoice_report[] = "Failed Invoices/Customers:\t" . $invoice_stats["total_failed"];
        if (isset($invoice_stats["generated"])) {
            $invoice_report[] = "";
            $invoice_report[] = "Customers / Invoices Generated";
            foreach (array_keys($invoice_stats["generated"]) as $id) {
                $invoice_report[] = " * " . $invoice_stats["generated"][$id]["code_invoice"] . ": " . $invoice_stats["generated"][$id]["code_customer"] . " -- " . $invoice_stats["generated"][$id]["name_customer"];
                $invoice_report[] = "   [" . $invoice_stats["generated"][$id]["sent"] . "]";
            }
            $invoice_report[] = "";
        }
        if (isset($invoice_stats["failed"])) {
            $invoice_report[] = "";
            $invoice_report[] = "Failed Customers / Invoices";
            foreach (array_keys($invoice_stats["failed"]) as $id) {
                $invoice_report[] = " * " . $invoice_stats["failed"][$id]["code_customer"] . " -- " . $invoice_stats["failed"][$id]["name_customer"];
            }
            $invoice_report[] = "";
            $invoice_report[] = "Failed invoices will be attempted again on the following billing run.";
            $invoice_report[] = "";
        }
        $invoice_report[] = "Invoicing Run Complete";
        // display to debug log
        log_write("debug", "inc_service_invoicegen", "----");
        foreach ($invoice_report as $line) {
            // loop through invoice report lines
            log_write("debug", "inc_service_invoicegen", $line);
        }
        log_write("debug", "inc_service_invoicegen", "----");
        // email if appropiate
        if ($GLOBALS["config"]["ACCOUNTS_INVOICE_BATCHREPORT"] && ($invoice_stats["total"] > 0 || $invoice_stats["total_failed"] > 0)) {
            log_write("debug", "inc_service_invoicegen", "Emailing invoice generation report to " . $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"] . "");
            /*
            	External dependency of Mail_Mime
            */
            if (!@(include_once 'Mail.php')) {
                log_write("error", "invoice", "Unable to find Mail module required for sending email");
                break;
            }
            if (!@(include_once 'Mail/mime.php')) {
                log_write("error", "invoice", "Unable to find Mail::Mime module required for sending email");
                break;
            }
            /*
            	Email the Report
            */
            $email_sender = $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"];
            $email_to = $GLOBALS["config"]["ACCOUNTS_EMAIL_ADDRESS"];
            $email_subject = "Invoice Batch Process Report";
            $email_message = $GLOBALS["config"]["COMPANY_NAME"] . "\n\nInvoice Batch Process Report for " . time_format_humandate() . "\n\n";
            foreach ($invoice_report as $line) {
                $email_message .= $line . "\n";
            }
            // prepare headers
            $mail_headers = array('From' => $email_sender, 'Subject' => $email_subject);
            $mail_mime = new Mail_mime("\n");
            $mail_mime->setTXTBody($email_message);
            $mail_body = $mail_mime->get();
            $mail_headers = $mail_mime->headers($mail_headers);
            $mail =& Mail::factory('mail');
            $status = $mail->send($email_to, $mail_headers, $mail_body);
            if (PEAR::isError($status)) {
                log_write("error", "inc_service_invoicegen", "An error occured whilst attempting to send the batch report email: " . $status->getMessage() . "");
            } else {
                log_write("debug", "inc_service_invoicegen", "Successfully sent batch report email.");
            }
        }
        // end if email
    }
    // end if report
    return 1;
}