示例#1
0
 function autopay_credit()
 {
     log_write("debug", "invoice_autopay", "Executing autopay_credit()");
     /*
     	Fetch Current Credit Pool Amount
     
     	NOTE: we do a full query here, to prevent caching from giving us incorrect information.
     */
     $sql_obj = new sql_query();
     $sql_obj->string = "SELECT SUM(amount_total) as value FROM customers_credits WHERE id_customer='" . $this->id_org . "' LIMIT 1";
     $sql_obj->execute();
     $sql_obj->fetch_array();
     $amount_credit = $sql_obj->data[0]["value"];
     unset($sql_obj);
     if ($amount_credit > 0) {
         $this->obj_invoice->data["amount_due"] = $this->obj_invoice->data["amount_total"] - $this->obj_invoice->data["amount_paid"];
         if ($amount_credit > $this->obj_invoice->data["amount_due"]) {
             $amount_credit = $this->obj_invoice->data["amount_due"];
         }
     } else {
         log_write("debug", "invoice_autopay", "No credit available");
         return 0;
     }
     /*
     	Define Item Details
     */
     $item = new invoice_items();
     $item->id_invoice = $this->id_invoice;
     $item->type_invoice = $this->type_invoice;
     $item->type_item = "payment";
     $data = array();
     $data["date_trans"] = date("Y-m-d");
     $data["amount"] = $amount_credit;
     $data["source"] = "CREDIT";
     $data["description"] = "Automated Credit Payment";
     $data["chartid"] = "credit";
     if (!$item->prepare_data($data)) {
         log_write("error", "invoice_autopay", "An error was encountered whilst processing credit payment data.");
         return 0;
     }
     $item->action_create();
     $item->action_update();
     $item->action_update_total();
     $item->action_update_ledger();
     if (!$item->id_item) {
         log_write("error", "invoice_autopay", "An error occured whilst creating the credit autopay item");
     }
     unset($item);
     /*
     	Make Credit Payment Item
     */
     log_write("debug", "invoice_autopay", "Autopayment against invoice " . $this->id_invoice . " made from credit pool.");
     return 1;
 }
 $code = @security_form_input_predefined("any", $name . "-code", 0, "");
 $reference = @security_form_input_predefined("any", $name . "-reference", 0, "");
 $particulars = @security_form_input_predefined("any", $name . "-particulars", 0, "");
 $other_party = @security_form_input_predefined("any", $name . "-other_party", 0, "");
 $transaction_type = @security_form_input_predefined("any", $name . "-transaction_type", 0, "");
 switch ($type) {
     case "ap":
     case "ar":
         /*
         	AR // AP INVOICE PAYMENTS
         
         	Handling AR and AP payments is almost identical - we need to validate
         	and then create a payment item on the invoice.
         */
         $data = array();
         $item = new invoice_items();
         if ($type == "ar") {
             // determine customer and invoice
             $customer = @security_form_input_predefined("int", $name . "-customer", 1, "");
             $arinvoice = @security_form_input_predefined("int", $name . "-arinvoice", 1, "");
             $item->id_invoice = $arinvoice;
         } else {
             // determine vendor and invoice
             $vendor = @security_form_input_predefined("int", $name . "-vendor", 1, "");
             $apinvoice = @security_form_input_predefined("int", $name . "-apinvoice", 1, "");
             $item->id_invoice = $apinvoice;
         }
         $item->type_invoice = $type;
         $item->type_item = 'payment';
         $data["date_trans"] = $date;
         if ($amount < 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");
     }
 }
示例#4
0
 function action_delete()
 {
     log_debug("inc_credits", "Executing action_delete()");
     // we must have an ID provided
     if (!$this->id) {
         log_debug("inc_credits", "No credit note ID to action_delete function");
         return 0;
     }
     /*
     	Start SQL Transaction
     */
     $sql_obj = new sql_query();
     $sql_obj->trans_begin();
     /*
     	Delete Credit Note
     */
     $sql_obj->string = "DELETE FROM account_" . $this->type . " WHERE id='" . $this->id . "' LIMIT 1";
     $sql_obj->execute();
     /*
     	Delete Credit Items (aka Invoice Items)
     
     	We do this by using the invoice_items::action_delete() function, since there are number of complex
     	steps when deleting certain invoice items.
     */
     $sql_items_obj = new sql_query();
     $sql_items_obj->string = "SELECT id FROM account_items WHERE invoicetype='" . $this->type . "' AND invoiceid='" . $this->id . "'";
     $sql_items_obj->execute();
     if ($sql_items_obj->num_rows()) {
         $sql_items_obj->fetch_array();
         foreach ($sql_items_obj->data as $data_sql) {
             // delete each item one-at-a-time.
             $obj_credit_item = new invoice_items();
             $obj_credit_item->type_invoice = $this->type;
             $obj_credit_item->id_invoice = $this->id;
             $obj_credit_item->id_item = $data_sql["id"];
             $obj_credit_item->action_delete();
             unset($obj_credit_item);
         }
     }
     /*
     	Delete Journal
     */
     journal_delete_entire("account_" . $this->type . "", $this->id);
     /*
     	Delete transactions from ledger
     	
     	(Most transactions are deleted by the item deletion code, but tax, pay and AR/AP
     	 ledger transactions need to be removed manually)
     */
     $sql_obj->string = "DELETE FROM account_trans WHERE (type='" . $this->type . "' || type='" . $this->type . "_tax') AND customid='" . $this->id . "'";
     $sql_obj->execute();
     /*
     	Delete customer/vendor credit allocations
     */
     if ($this->type == "ap") {
         $sql_obj->string = "DELETE FROM vendors_credits WHERE id_vendor='" . $this->data["vendorid"] . "' AND type='creditnote' AND id_custom='" . $this->id . "' LIMIT 1";
         $sql_obj->execute();
     } else {
         $sql_obj->string = "DELETE FROM customers_credits WHERE id_customer='" . $this->data["customerid"] . "' AND type='creditnote' AND id_custom='" . $this->id . "' LIMIT 1";
         $sql_obj->execute();
     }
     /*
     	Commit
     */
     if (error_check()) {
         $sql_obj->trans_rollback();
         log_write("error", "invoice", "An error occured whilst deleting the credit note. No changes have been made.");
         return 0;
     } else {
         $sql_obj->trans_commit();
         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 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();
    }
}
function quotes_form_convert_process($returnpage_error, $returnpage_success)
{
    log_debug("inc_quotes_forms", "Executing quotes_form_convert_process({$mode}, {$returnpage_error}, {$returnpage_success})");
    /*
    	Fetch all form data
    */
    $id = @security_form_input_predefined("int", "id_quote", 1, "");
    // general data
    $data["code_invoice"] = @security_form_input_predefined("any", "code_invoice", 0, "");
    $data["code_ordernumber"] = @security_form_input_predefined("any", "code_ordernumber", 0, "");
    $data["code_ponumber"] = @security_form_input_predefined("any", "code_ponumber", 0, "");
    $data["date_trans"] = @security_form_input_predefined("date", "date_trans", 1, "");
    $data["date_due"] = @security_form_input_predefined("date", "date_due", 1, "");
    // other
    $data["dest_account"] = @security_form_input_predefined("int", "dest_account", 1, "");
    //// ERROR CHECKING ///////////////////////
    // make sure the quote actually exists, and fetch various fields that we need to create the invoice.
    $sql_quote_obj = new sql_query();
    $sql_quote_obj->string = "SELECT id, employeeid, customerid, amount_total, amount_tax, amount, notes FROM `account_quotes` WHERE id='{$id}' LIMIT 1";
    $sql_quote_obj->execute();
    if (!$sql_quote_obj->num_rows()) {
        $_SESSION["error"]["message"][] = "The quote you have attempted to edit - {$id} - does not exist in this system.";
    } else {
        $sql_quote_obj->fetch_array();
    }
    /// if there was an error, go back to the entry page
    if ($_SESSION["error"]["message"]) {
        $_SESSION["error"]["form"]["quote_convert"] = "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();
        // make an invoice ID if one is not supplied by the user
        if (!$data["code_invoice"]) {
            $data["code_invoice"] = config_generate_uniqueid("ACCOUNTS_AR_INVOICENUM", "SELECT id FROM account_ar WHERE code_invoice='VALUE'");
        }
        /*
        	Create new invoice
        */
        $sql_obj->string = "INSERT INTO `account_ar` (code_invoice, date_create) VALUES ('" . $data["code_invoice"] . "', '" . date("Y-m-d") . "')";
        $sql_obj->execute();
        $invoiceid = $sql_obj->fetch_insert_id();
        if ($invoiceid) {
            /*
            	Update general invoice details
            */
            $sql_obj->string = "UPDATE `account_ar` SET " . "customerid='" . $sql_quote_obj->data[0]["customerid"] . "', " . "employeeid='" . $sql_quote_obj->data[0]["employeeid"] . "', " . "notes='" . $sql_quote_obj->data[0]["notes"] . "', " . "code_invoice='" . $data["code_invoice"] . "', " . "code_ordernumber='" . $data["code_ordernumber"] . "', " . "code_ponumber='" . $data["code_ponumber"] . "', " . "date_trans='" . $data["date_trans"] . "', " . "date_due='" . $data["date_due"] . "', " . "dest_account='" . $data["dest_account"] . "', " . "amount='" . $sql_quote_obj->data[0]["amount"] . "', " . "amount_tax='" . $sql_quote_obj->data[0]["amount_tax"] . "', " . "amount_total='" . $sql_quote_obj->data[0]["amount_total"] . "' " . "WHERE id='{$invoiceid}' LIMIT 1";
            $sql_obj->execute();
            /*
            	Migrate all the items from the quote to the invoice
            */
            $sql_obj->string = "UPDATE account_items SET invoiceid='{$invoiceid}', invoicetype='ar' WHERE invoiceid='{$id}' AND invoicetype='quotes'";
            $sql_obj->execute();
            /*
            	Call functions to create transaction entries for all the items.
            	(remember that the quote had nothing in account_trans for the items)
            */
            $invoice_item = new invoice_items();
            $invoice_item->id_invoice = $invoiceid;
            $invoice_item->type_invoice = "ar";
            $invoice_item->action_update_ledger();
            unset($invoice_item);
            /*
            	Migrate the journal
            */
            $sql_obj->string = "UPDATE journal SET customid='{$invoiceid}', journalname='account_ar' WHERE customid='{$id}' AND journalname='account_quotes'";
            $sql_obj->execute();
            /*
            	Delete the quote
            */
            $sql_obj->string = "DELETE FROM account_quotes WHERE id='{$id}' LIMIT 1";
            $sql_obj->execute();
        }
        /*
        	Update the Journal
        */
        journal_quickadd_event("account_ar", $invoiceid, "Converted quotation into invoice");
        /*
        	Commit
        */
        if (error_check()) {
            $sql_obj->trans_rollback();
            log_write("error", "inc_quotes_forms", "An error occured whilst attempting to convert the quote into an invoice. No changes have been made.");
            $_SESSION["error"]["form"]["quote_convert"] = "failed";
            header("Location: ../../index.php?page={$returnpage_error}&id={$id}");
            exit(0);
        } else {
            $sql_obj->trans_commit();
            log_write("notification", "inc_quotes_forms", "Quotation has been converted to an invoice successfully.");
            header("Location: ../../index.php?page={$returnpage_success}&id={$invoiceid}");
            exit(0);
        }
    }
    // end if passed tests
}
     }
 }
 //if there are errors, redirect
 if (error_check()) {
     $_SESSION["error"]["form"]["invoice-bulk-payments-ar"] = "failed";
     header("Location: ../../index.php?page=accounts/ar/invoice-bulk-payments.php");
     exit(0);
 }
 //process
 $sql_obj = new sql_query();
 $sql_obj->trans_begin();
 foreach ($invoices as $id => $record) {
     //only process rows that have been ticked 'to pay'
     if ($invoices[$id]["checked"] == "true") {
         //create new invoice item
         $item = new invoice_items();
         $item->id_invoice = $id;
         $item->type_invoice = "ar";
         $item->type_item = "payment";
         //verify invoice exists
         if (!$item->verify_invoice()) {
             log_write("error", "process", "The requested invoice does not exist.");
         }
         //get amount
         $data["amount"] = $invoices[$id]["amount"];
         //process
         if (!$item->prepare_data($data)) {
             log_write("error", "process", "An error was encountered whilst processing supplied data.");
         }
         $item->action_create();
         $item->action_update();
示例#9
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;
}