예제 #1
0
 function updateInvoiceItem($id, $quantity, $product_id, $tax_id, $description, $attr1 = "", $attr2 = "", $attr3 = "", $unit_price = "")
 {
     $attr1 = explode("-", $attr1);
     $attr1 = $attr1[2];
     //echo "Attr1: ".$attr1." ";
     $attr2 = explode("-", $attr2);
     $attr2 = $attr2[2];
     //echo "Attr2 : ".$attr2." ";
     $attr3 = explode("-", $attr3);
     $attr3 = $attr3[2];
     //echo "Attr3 : ".$attr3;
     //echo "<br /><br />";
     $product = getProduct($product_id);
     $unit_price == "" ? $product_unit_price = $product['unit_price'] : ($product_unit_price = $unit_price);
     $tax = getTaxRate($tax_id);
     $total_invoice_item_tax = $product_unit_price * $tax['tax_percentage'] / 100;
     //:100?
     $tax_amount = $total_invoice_item_tax * $quantity;
     $total_invoice_item = $total_invoice_item_tax + $product_unit_price;
     $total = $total_invoice_item * $quantity;
     $gross_total = $product_unit_price * $quantity;
     if ($db_server == 'mysql' && !_invoice_items_check_fk(null, $product_id, $tax_id, 'update')) {
         return null;
     }
     $sql = "UPDATE " . TB_PREFIX . "invoice_items \r\n\t\tSET quantity =  :quantity,\r\n\t\tproduct_id = :product_id,\r\n\t\tunit_price = :unit_price,\r\n\t\ttax_id = :tax_id,\r\n\t\ttax = :tax,\r\n\t\ttax_amount = :tax_amount,\r\n\t\tgross_total = :gross_total,\r\n\t\tdescription = :description,\r\n\t\ttotal = :total,\t\t\t\r\n\t\tattribute_1 = :attr1,\t\t\t\r\n\t\tattribute_2 = :attr2,\t\t\t\r\n\t\tattribute_3 = :attr3\t\t\t\r\n\t\tWHERE id = :id";
     //echo $sql;
     return dbQuery($sql, ':quantity', $quantity, ':product_id', $product_id, ':unit_price', $product_unit_price, ':tax_id', $tax_id, ':tax', $tax[tax_percentage], ':tax_amount', $tax_amount, ':gross_total', $gross_total, ':description', $description, ':total', $total, ':id', $id, ':attr1', $attr1, ':attr2', $attr2, ':attr3', $attr3);
 }
예제 #2
0
/**
 * Updates a customer at Acumulus
 * @param $vars : $vars from the hook for API credentials
 * @param $clientid : clientid to update
 * @param null $customerid : customerid at Acumulus to update
 * @throws Exception
 * @return $customerid : new/updated customerid at Acumulus
 */
function updateCustomer($vars, $clientid, $customerid = null)
{
    global $whmcs;
    $whmcs->load_function('invoice');
    $clientQuery = mysql_query('SELECT tblclients.*, tblcustomfieldsvalues.value AS vatnumber FROM tblclients LEFT JOIN tblcustomfieldsvalues ON tblclients.id = tblcustomfieldsvalues.relid AND tblcustomfieldsvalues.fieldid = (SELECT id FROM tblcustomfields WHERE type = "client" AND fieldname = "' . $vars['vat_field'] . '" LIMIT 1) WHERE tblclients.id = ' . $clientid . ' LIMIT 1');
    if (mysql_num_rows($clientQuery) != 1) {
        throw new Exception('Failed to receive client ' . $clientid);
    }
    $clientFetch = mysql_fetch_assoc($clientQuery);
    $api = new api($vars['code'], $vars['username'], $vars['password']);
    $api->setCategory('contacts')->setAction('contact_manage');
    if (isset($vars['debug']) && $vars['debug'] == 'on') {
        $api->enableDebug($vars['debug_email']);
    }
    if ($clientFetch['acumulusid'] != null) {
        $api->setParam('contact/contactid', $clientFetch['acumulusid']);
    }
    if ($customerid != null) {
        $api->setParam('contact/contactid', $customerid);
    }
    if ($clientFetch['country'] == 'NL') {
        $api->setParam('contact/contactlocationcode', 1);
    } elseif (inEurope($clientFetch['country'])) {
        $api->setParam('contact/contactlocationcode', 2);
    } else {
        $api->setParam('contact/contactlocationcode', 3);
    }
    $taxData = getTaxRate(1, $clientQuery['state'], $clientQuery['country']);
    $api->setParams(array('contact' => array('contactemail' => $clientFetch['email'], 'contacttype' => 1, 'overwriteifexists' => 1, 'contactname1' => ucfirst($clientFetch['firstname']) . ' ' . $clientFetch['lastname'], 'contactname2' => '', 'contactperson' => '', 'contactsalutation' => '', 'contactaddress1' => $clientFetch['address1'], 'contactaddress2' => $clientFetch['address2'], 'contactpostalcode' => $clientFetch['postcode'], 'contactcity' => $clientFetch['city'], 'contactcountrycode' => inEurope($clientFetch['country']) ? $clientFetch['country'] : '', 'contactvatnumber' => $clientFetch['vatnumber'], 'contactvatratebase' => $clientFetch['taxexempt'] == 'on' ? -1 : round($taxData['rate']), 'contacttelephone' => $clientFetch['phonenumber'], 'contactfax' => '', 'contactsepaincassostatus' => 'FRST', 'contactinvoicetemplateid' => '', 'contactstatus' => 1)));
    if (!empty($clientFetch['companyname'])) {
        $api->setParams(array('contact' => array('contactname1' => $clientFetch['companyname'], 'contactperson' => ucfirst($clientFetch['firstname']) . ' ' . $clientFetch['lastname'])));
    }
    $api->execute();
    $response = $api->getResponse();
    if ($api->hasErrors()) {
        $errors = '';
        foreach ($api->getErrors() as $error) {
            $errors = $error['code'] . ' - ' . $error['message'] . ', ';
        }
        logActivity('Acumulus API error(s): ' . substr($errors, 0, -2));
        return false;
    } else {
        mysql_query('UPDATE tblclients SET acumulusid = ' . $response['contact']['contactid'] . ' WHERE id = ' . $clientid . ' LIMIT 1');
        return $response['contact']['contactid'];
    }
}
예제 #3
0
 public function formatForOutput()
 {
     global $whmcs;
     global $currency;
     $this->output = $this->data;
     $array = array("date", "duedate", "datepaid");
     foreach ($array as $v) {
         $this->output[$v] = substr($this->output[$v], 0, 10) != "0000-00-00" ? fromMySQLDate($this->output[$v], $v == "datepaid" ? "1" : "0", 1) : "";
     }
     $this->output['datecreated'] = $this->output['date'];
     $this->output['datedue'] = $this->output['duedate'];
     $currency = getCurrency($this->getData("userid"));
     $array = array("subtotal", "credit", "tax", "tax2", "total", "balance", "amountpaid");
     foreach ($array as $v) {
         $this->output[$v] = formatCurrency($this->output[$v]);
     }
     if (!function_exists("getClientsDetails")) {
         require ROOTDIR . "/includes/clientfunctions.php";
     }
     $clientsdetails = getClientsDetails($this->getData("userid"), "billing");
     $clientsdetails['country'] = $clientsdetails['countryname'];
     $this->output['clientsdetails'] = $clientsdetails;
     $customfields = array();
     $result = select_query("tblcustomfields", "tblcustomfields.id,tblcustomfields.fieldname,(SELECT value FROM tblcustomfieldsvalues WHERE tblcustomfieldsvalues.fieldid=tblcustomfields.id AND tblcustomfieldsvalues.relid=" . (int) $this->getData("userid") . ") AS value", array("type" => "client", "showinvoice" => "on"));
     while ($data = mysql_fetch_assoc($result)) {
         if ($data['value']) {
             $customfields[] = $data;
         }
     }
     $this->output['customfields'] = $customfields;
     if (0 < $this->getData("taxrate")) {
         $taxname = getTaxRate(1, $clientsdetails['state'], $clientsdetails['countrycode']);
         $this->output['taxname'] = $taxname['name'];
     } else {
         $this->output['taxrate'] = "0";
     }
     if (0 < $this->getData("taxrate2")) {
         $taxname = getTaxRate(2, $clientsdetails['state'], $clientsdetails['countrycode']);
         $this->output['taxname2'] = $taxname['name'];
     } else {
         $this->output['taxrate2'] = "0";
     }
     $this->output['statuslocale'] = $whmcs->get_lang("invoices" . strtolower($this->output['status']));
     $this->output['pagetitle'] = $whmcs->get_lang("invoicenumber") . $this->getData("invoicenum");
     $this->output['payto'] = nl2br($whmcs->get_config("InvoicePayTo"));
     $this->output['notes'] = nl2br($this->output['notes']);
     $this->output['subscrid'] = get_query_val("tblinvoiceitems", "tblhosting.subscriptionid", "tblinvoiceitems.type='Hosting' AND tblinvoiceitems.invoiceid=" . $this->getData("id") . " AND tblhosting.subscriptionid!=''", "tblhosting`.`id", "ASC", "", "tblhosting ON tblhosting.id=tblinvoiceitems.relid");
     $clienttotals = get_query_vals("tblinvoices", "SUM(credit),SUM(total)", array("userid" => $this->getData("userid"), "status" => "Unpaid"));
     $alldueinvoicespayments = get_query_val("tblaccounts", "SUM(amountin-amountout)", "invoiceid IN (SELECT id FROM tblinvoices WHERE userid=" . (int) $this->getData("userid") . " AND status='Unpaid')");
     $this->output['clienttotaldue'] = formatCurrency($clienttotals[0] + $clienttotals[1]);
     $this->output['clientpreviousbalance'] = formatCurrency($clienttotals[1] - $this->getData("total"));
     $this->output['clientbalancedue'] = formatCurrency($clienttotals[1] - $alldueinvoicespayments);
     $lastpayment = get_query_vals("tblaccounts", "(amountin-amountout),transid", array("invoiceid" => $this->getData("id")), "id", "DESC");
     $this->output['lastpaymentamount'] = formatCurrency($lastpayment[0]);
     $this->output['lastpaymenttransid'] = $lastpayment[1];
 }
예제 #4
0
function onapp_UsageUpdate($params)
{
    global $_LANG, $CONFIG;
    error_reporting(E_ERROR);
    ini_set("display_errors", 1);
    //    date_default_timezone_set('UTC');
    $serverid = $params['serverid'];
    $query = "\n        SELECT\n            tblservers.id,\n            tblservers.password,\n            tblservers.hostname,\n            tblservers.ipaddress,\n            tblservers.username,\n            tblhosting.regdate,\n            tblhosting.id as hosting_id,\n            tblhosting.bwusage,\n            tblhosting.domain,\n            tblhosting.bwlimit,\n            tblproducts.servertype,\n            tblhosting.lastupdate,\n            tblhosting.nextinvoicedate,\n            tblhosting.paymentmethod,\n            tblonappservices.vm_id,\n            tblproducts.overagesbwlimit as bwlimit,\n            tblproducts.overagesdisklimit as disklimit,\n            tblproducts.overagesenabled as enabled,\n            tblproducts.configoption10 as configoption10,\n            tblproducts.configoption22 as bandwidthconfigoption,\n            tblproducts.name as packagename,\n            tblproducts.overagesbwprice,\n            tblproducts.tax,\n            tblhostingconfigoptions.optionid,\n            tblupgrades.status as upgrade_status,\n            tblupgrades.paid as upgrade_paid,\n            tblupgrades.id as upgrade_id,\n            tblproductconfigoptionssub.sortorder as additional_bandwidth,\n            tblclients.id as clientid,\n            tblclients.taxexempt,\n            tblclients.state,\n            tblclients.country,\n            tblcurrencies.prefix,\n            tblcurrencies.code,\n            tblcurrencies.rate,\n            tblonappcronhostingdates.account_date\n        FROM\n            tblservers\n    \n        LEFT JOIN\n            tblhosting ON tblhosting.server = tblservers.id\n        LEFT JOIN\n            tblproducts ON tblhosting.packageid = tblproducts.id\n        LEFT JOIN\n            tblonappservices ON tblhosting.id = tblonappservices.service_id\n        LEFT JOIN\n            tblhostingconfigoptions\n            ON tblhostingconfigoptions.relid = tblhosting.id\n            AND tblhostingconfigoptions.configid = tblproducts.configoption22\n        LEFT JOIN\n            tblproductconfigoptionssub\n            ON\n            tblhostingconfigoptions.optionid = tblproductconfigoptionssub.id\n        LEFT JOIN\n            tblupgrades\n            ON tblupgrades.newvalue = tblhostingconfigoptions.optionid\n            AND tblupgrades.id = (SELECT MAX( id ) FROM tblupgrades WHERE\n            newvalue = tblhostingconfigoptions.optionid )\n        LEFT JOIN \n            tblclients ON tblhosting.userid = tblclients.id\n        LEFT JOIN\n            tblcurrencies ON tblcurrencies.id = tblclients.currency\n        LEFT JOIN\n            tblonappcronhostingdates ON tblonappcronhostingdates.hosting_id = tblhosting.id\n\n        WHERE\n           tblservers.id = {$serverid} AND\n           tblproducts.servertype = 'onapp' AND\n           tblproducts.overagesenabled = 1 AND\n           tblonappservices.vm_id != ''\n    ";
    $result = full_query($query);
    if (!$result || mysql_num_rows($result) < 1) {
        return;
    }
    $duedate = date('Ymd', time() + $GLOBALS['CONFIG']['CreateInvoiceDaysBefore'] * 86400);
    $today = date('Y-m-d H:i:s');
    $enddate = $today;
    $i = 0;
    while ($products = mysql_fetch_assoc($result)) {
        if ($products['account_date']) {
            $invoicedate = date('Y-m-d', strtotime($products['account_date']) + 31 * 24 * 60 * 60);
            $startdate = $products['account_date'];
        } else {
            $invoicedate = getAccountDate($products['regdate']);
            $time = strtotime($invoicedate) - 2678400;
            $startdate = date('Y-m-d H:00:00', $time);
        }
        $onapp = new OnApp_Factory($products['hostname'] ? $products['hostname'] : $products['ipaddress'], $products['username'], decrypt($products['password']));
        if ($onapp->getErrorsAsArray()) {
            // Debug
            echo '<b>Get OnApp Version Permission Error: </b>' . implode(PHP_EOL, $onapp->getErrorsAsArray()) . '. Skipping' . PHP_EOL;
            continue;
        }
        $network_interface = $onapp->factory('VirtualMachine_NetworkInterface');
        if (!$products['vm_id']) {
            // Debug
            echo 'virtual_machine_id is empty. Skipping' . PHP_EOL;
            continue;
        }
        $network_interfaces = $network_interface->getList($products['vm_id']);
        if ($network_interface->getErrorsAsArray()) {
            // Debug
            echo '<b>Network Interface Get List Error : </b>' . implode(PHP_EOL, $network_interface->getErrorsAsArray()) . '. Skipping' . PHP_EOL;
            continue;
        }
        $usage = $onapp->factory('VirtualMachine_NetworkInterface_Usage', true);
        $url_args = array('period[startdate]' => $startdate, 'period[enddate]' => $enddate);
        foreach ($network_interfaces as $interface) {
            $usage_stats[$i][$interface->_id] = $usage->getList($interface->_virtual_machine_id, $interface->_id, $url_args);
        }
        $traffic = 0;
        foreach ($usage_stats[$i] as $interface) {
            foreach ($interface as $bandwidth) {
                $traffic += $bandwidth->_data_sent;
                $traffic += $bandwidth->_data_received;
            }
        }
        $traffic = $traffic / 1024;
        // Count bandwidth limit + upgrades if needed
        $bandwidth_limit = $products['optionid'] && $products['additional_bandwidth'] && $products['upgrade_status'] == 'Completed' && $products['upgrade_paid'] == 'Y' ? $products['bwlimit'] + $products['additional_bandwidth'] : $products['bwlimit'];
        if (date('Y-m-d') == $invoicedate) {
            // debug
            echo 'Payment Day' . PHP_EOL;
            if ($traffic > $bandwidth_limit && !$params['extracall']) {
                // debug
                echo 'Called by the main cron' . PHP_EOL;
                echo 'Update cron dates' . PHP_EOL;
                $query = "REPLACE INTO\n                              tblonappcronhostingdates\n                              ( hosting_id, account_date )\n                          VALUES ( {$products['hosting_id']}, '" . $enddate . "'  )\n                ";
                $result = full_query($query);
                if (!$result) {
                    // debug
                    echo 'cron date REPLACE error ' . mysql_error() . PHP_EOL;
                }
                /// Generating Invoice ///
                /////////////////////////
                // debug
                echo 'Generating Invoice' . PHP_EOL;
                $sql = 'SELECT username FROM tbladmins LIMIT 1';
                $res = full_query($sql);
                $admin = mysql_fetch_assoc($res);
                $taxed = empty($products['taxexempt']) && $CONFIG['TaxEnabled'];
                if ($taxed) {
                    // debug
                    echo 'taxed invoice' . PHP_EOL;
                    $taxrate = getTaxRate(1, $products['state'], $products['country']);
                    $taxrate = $taxrate['rate'];
                } else {
                    $taxrate = '';
                }
                $amount = round(($traffic - $bandwidth_limit) * $products['overagesbwprice'] * $products['rate'], 2);
                $description = $products['packagename'] . ' - ' . $products['domain'] . ' ( ' . $startdate . ' / ' . $enddate . ' )' . PHP_EOL . $_LANG['onappbwusage'] . ' - ' . $traffic . ' MB' . PHP_EOL . $_LANG['onappbwlimit'] . ' - ' . $bandwidth_limit . ' MB' . PHP_EOL . $_LANG['onappbwoverages'] . ' - ' . ($traffic - $bandwidth_limit) . ' MB' . PHP_EOL . $_LANG['onapppriceformbbwoverages'] . ' - ' . $products['prefix'] . round($products['rate'] * $products['overagesbwprice'], 2) . ' ' . $products['code'] . PHP_EOL;
                $data = array('userid' => $products['clientid'], 'date' => $today, 'duedate' => $duedate, 'paymentmethod' => $products['paymentmethod'], 'taxrate' => $taxrate, 'sendinvoice' => true, 'itemdescription1' => $description, 'itemamount1' => $amount, 'itemtaxed1' => $taxed);
                // debug
                print '<pre>';
                print_r($data);
                echo PHP_EOL;
                $result = localAPI('CreateInvoice', $data, $admin);
                if ($result['result'] != 'success') {
                    // debug
                    echo 'Following error occurred: ' . $result['result'] . PHP_EOL;
                }
                // Generating Invoice End //
                ///////////////////////////
            }
            if (!$params['extracall']) {
                // debug
                echo 'Reset bwusage to 0' . PHP_EOL;
                $traffic = 0;
            }
        }
        $results[] = array('bwusage' => $traffic, 'disklimit' => $products['disklimit'], 'bwlimit' => $bandwidth_limit, 'domain' => $products['domain']);
        /// Debug block ///
        //////////////////
        print '<pre>';
        print_r($products);
        echo PHP_EOL;
        echo 'today  => ' . $today . PHP_EOL;
        echo 'regdate  => ' . $products['regdate'] . PHP_EOL;
        echo 'invoicedate  => ' . $invoicedate . PHP_EOL;
        echo 'startdate  => ' . $startdate . PHP_EOL;
        echo 'enddate  => ' . $enddate . PHP_EOL;
        echo 'bwlimit  (' . $products['bwlimit'] . ') + ';
        echo 'additional bwlimit (' . $products['additional_bandwidth'] . ') = ';
        echo $bandwidth_limit . PHP_EOL . PHP_EOL;
        echo 'Updating bwusage => ' . PHP_EOL;
        print '<pre>';
        print_r($results);
        echo '************************************************' . PHP_EOL . PHP_EOL;
        /// Debug block END ///
        //////////////////////
        $i++;
    }
    // Updating Usage Overages
    foreach ($results as $domain => $values) {
        update_query("tblhosting", array("disklimit" => $values['disklimit'], "bwusage" => $values['bwusage'], "bwlimit" => $values['bwlimit'], "lastupdate" => $today), array("server" => $serverid, "domain" => $values['domain']));
    }
}
예제 #5
0
function convertQuotetoInvoice($id, $invoicetype, $invoiceduedate, $depositpercent, $depositduedate, $finalduedate, $sendemail)
{
    global $CONFIG;
    global $_LANG;
    $result = select_query("tblquotes", "", array("id" => $id));
    $data = mysql_fetch_array($result);
    $userid = $data['userid'];
    $firstname = $data['firstname'];
    $lastname = $data['lastname'];
    $companyname = $data['companyname'];
    $email = $data['email'];
    $address1 = $data['address1'];
    $address2 = $data['address2'];
    $city = $data['city'];
    $state = $data['state'];
    $postcode = $data['postcode'];
    $country = $data['country'];
    $phonenumber = $data['phonenumber'];
    $currency = $data['currency'];
    if ($userid) {
        getUsersLang($userid);
        $clientsdetails = getClientsDetails($userid);
        $state = $clientsdetails['state'];
        $country = $clientsdetails['country'];
    } else {
        if (!function_exists("addClient")) {
            require ROOTDIR . "/clientfunctions.php";
        }
        $_SESSION['currency'] = $currency;
        $userid = addClient($firstname, $lastname, $companyname, $email, $address1, $address2, $city, $state, $postcode, $country, $phonenumber, substr(md5($id), 0, 10), 0, "", "on");
    }
    if ($CONFIG['TaxEnabled'] == "on") {
        $taxlevel1 = getTaxRate(1, $state, $country);
        $taxlevel2 = getTaxRate(2, $state, $country);
        $taxrate = $taxlevel1['rate'];
        $taxrate2 = $taxlevel2['rate'];
    }
    $subtotal = $data['subtotal'];
    $tax1 = $data['tax1'];
    $tax2 = $data['tax2'];
    $total = $data['total'];
    $result = select_query("tblpaymentgateways", "gateway", array("setting" => "name"), "order", "ASC");
    $data = mysql_fetch_array($result);
    $gateway = $data['gateway'];
    $duedate = $finaldate = "";
    if ($invoicetype == "deposit") {
        if ($depositduedate) {
            $duedate = toMySQLDate($depositduedate);
        }
        $finaldate = $finalduedate ? toMySQLDate($finalduedate) : date("Y-m-d");
    } else {
        if ($invoiceduedate) {
            $duedate = toMySQLDate($invoiceduedate);
        }
    }
    if (!$duedate) {
        $duedate = date("Y-m-d");
    }
    $invoiceid = insert_query("tblinvoices", array("date" => "now()", "duedate" => $duedate, "userid" => $userid, "status" => "Unpaid", "paymentmethod" => $gateway, "taxrate" => $taxrate, "taxrate2" => $taxrate2, "subtotal" => $subtotal, "tax" => $tax1, "tax2" => $tax2, "total" => $total, "notes" => $_LANG['quoteref'] . $id));
    if ($finaldate) {
        $finalinvoiceid = insert_query("tblinvoices", array("date" => "now()", "duedate" => $finaldate, "userid" => $userid, "status" => "Unpaid", "paymentmethod" => $gateway, "taxrate" => $taxrate, "taxrate2" => $taxrate2, "subtotal" => $subtotal, "tax" => $tax1, "tax2" => $tax2, "total" => $total, "notes" => $_LANG['quoteref'] . $id));
    }
    $result = select_query("tblquoteitems", "", array("quoteid" => $id), "id", "ASC");
    while ($data = mysql_fetch_array($result)) {
        $line_id = $data['id'];
        $line_desc = $data['description'];
        $line_qty = $data['quantity'];
        $line_unitprice = $data['unitprice'];
        $line_discount = $data['discount'];
        $line_taxable = $data['taxable'];
        $line_total = format_as_currency($line_qty * $line_unitprice * (1 - $line_discount / 100));
        $lineitemdesc = "" . $line_qty . " x " . $line_desc . " @ " . $line_unitprice;
        if (0 < $line_discount) {
            $lineitemdesc .= " - " . $line_discount . "% " . $_LANG['orderdiscount'];
        }
        if ($finalinvoiceid) {
            $originalamount = $line_total;
            $line_total = $originalamount * ($depositpercent / 100);
            $final_amount = $originalamount - $line_total;
            insert_query("tblinvoiceitems", array("invoiceid" => $finalinvoiceid, "userid" => $userid, "description" => $lineitemdesc . " (" . (100 - $depositpercent) . "% " . $_LANG['quotefinalpayment'] . ")", "amount" => $final_amount, "taxed" => $line_taxable));
            $lineitemdesc .= " (" . $depositpercent . "% " . $_LANG['quotedeposit'] . ")";
        }
        insert_query("tblinvoiceitems", array("invoiceid" => $invoiceid, "userid" => $userid, "description" => $lineitemdesc, "amount" => $line_total, "taxed" => $line_taxable));
    }
    if (!function_exists("updateInvoiceTotal")) {
        require ROOTDIR . "/includes/invoicefunctions.php";
    }
    updateInvoiceTotal($invoiceid);
    if ($finalinvoiceid) {
        updateInvoiceTotal($finalinvoiceid);
    }
    run_hook("InvoiceCreationPreEmail", array("invoiceid" => $invoiceid));
    if ($finalinvoiceid) {
        run_hook("InvoiceCreationPreEmail", array("invoiceid" => $finalinvoiceid));
    }
    if ($sendemail) {
        sendMessage("Invoice Created", $invoiceid);
        if ($finalinvoiceid) {
            sendMessage("Invoice Created", $finalinvoiceid);
        }
    }
    run_hook("InvoiceCreated", array("invoiceid" => $invoiceid));
    if ($finalinvoiceid) {
        run_hook("InvoiceCreated", array("invoiceid" => $finalinvoiceid));
    }
    if (1 < $CONFIG['InvoiceIncrement']) {
        $invoiceincrement = $CONFIG['InvoiceIncrement'] - 1;
        $counter = 1;
        while ($counter <= $invoiceincrement) {
            $tempinvoiceid = insert_query("tblinvoices", array("date" => "now()"));
            delete_query("tblinvoices", array("id" => $tempinvoiceid));
            $counter += 1;
        }
    }
    update_query("tblquotes", array("userid" => $userid, "stage" => "Accepted"), array("id" => $id));
    return $invoiceid;
}
예제 #6
0
 if ($CONFIG['TaxEnabled'] == "on") {
     if ($taxrate != "0.00") {
         echo "<tr><td colspan=\"2\" style=\"text-align:right;background-color:#efefef;\">";
         echo $taxrate;
         echo "% ";
         $taxdata = getTaxRate(1, $clientstate, $clientcountry);
         echo $taxdata['name'] ? $taxdata['name'] : $aInt->lang("invoices", "taxdue");
         echo ":&nbsp;</td><td width=\"90\" style=\"background-color:#efefef;\">";
         echo formatCurrency($tax);
         echo "</td><td style=\"background-color:#efefef;\">&nbsp;</td><td style=\"background-color:#efefef;\">&nbsp;</td></tr>";
     }
     if ($taxrate2 != "0.00") {
         echo "<tr><td colspan=\"2\" style=\"text-align:right;background-color:#efefef;\">";
         echo $taxrate2;
         echo "% ";
         $taxdata = getTaxRate(2, $clientstate, $clientcountry);
         echo $taxdata['name'] ? $taxdata['name'] : $aInt->lang("invoices", "taxdue");
         echo ":&nbsp;</td><td width=\"90\" style=\"background-color:#efefef;\">";
         echo formatCurrency($tax2);
         echo "</td><td style=\"background-color:#efefef;\">&nbsp;</td><td style=\"background-color:#efefef;\">&nbsp;</td></tr>";
     }
 }
 echo "<tr><td colspan=\"2\" style=\"text-align:right;background-color:#efefef;\">";
 echo $aInt->lang("fields", "credit");
 echo ":&nbsp;</td><td width=\"90\" style=\"background-color:#efefef;\">";
 echo formatCurrency($credit);
 echo "</td><td style=\"background-color:#efefef;\">&nbsp;</td><td style=\"background-color:#efefef;\">&nbsp;</td></tr>\n<tr><th colspan=\"2\" style=\"text-align:right;\">";
 echo $aInt->lang("fields", "totaldue");
 echo ":&nbsp;</th><th width=\"90\">";
 echo formatCurrency($total);
 echo "</th><th></th><th></th></tr>\n</table>\n</div>\n<p align=center><input type=\"submit\" value=\"";
예제 #7
0
파일: common.php 프로젝트: OnApp/WHMCS-vCD
 protected function generateInvoiceData($data, array $client)
 {
     require_once dirname(__DIR__) . '/OnAppvCD.php';
     $module = new OnAppvCDModule();
     $lang = $module->loadLang()->Invoice;
     //check if invoice should be generated
     $fromTime = strtotime($this->fromDate);
     $tillTime = strtotime($this->tillDate);
     if ($fromTime >= $tillTime) {
         return false;
     }
     if (empty($client['dueDate'])) {
         $dueDate = $this->dueDate;
     } else {
         $dueDate = date('Ymd', time() + $client['dueDate'] * 86400);
     }
     # check if the item should be taxed
     $taxed = empty($client['taxexempt']) && (int) $client['tax'];
     if ($taxed) {
         $taxrate = getTaxRate(1, $client['state'], $client['country']);
         $taxrate = $taxrate['rate'];
     } else {
         $taxrate = '';
     }
     $timeZone = ' UTC';
     if ($this->timeZoneOffset > 0) {
         $timeZone .= '+' . $this->timeZoneOffset / 3600;
     } elseif ($this->timeZoneOffset < 0) {
         $timeZone .= $this->timeZoneOffset / 3600;
     }
     $this->fromDate = date($lang->DateFormat, $fromTime);
     $this->tillDate = date($lang->DateFormat, $tillTime);
     $invoiceDescription = array($lang->Product . $client['packagename'], $lang->Period . $this->fromDate . ' - ' . $this->tillDate . $timeZone);
     $invoiceDescription = implode(PHP_EOL, $invoiceDescription);
     $return = array('userid' => $client['WHMCSUserID'], 'date' => $this->dueDate, 'duedate' => $dueDate, 'paymentmethod' => $client['paymentmethod'], 'taxrate' => $taxrate, 'sendinvoice' => true, 'itemdescription1' => $invoiceDescription, 'itemamount1' => 0, 'itemtaxed1' => $taxed);
     unset($data->total_cost);
     $i = 1;
     foreach ($data as $key => $value) {
         if ($value > 0) {
             $tmp = array('itemdescription' . ++$i => $lang->{$key}, 'itemamount' . $i => $value, 'itemtaxed' . $i => $taxed);
             $return = array_merge($return, $tmp);
         }
     }
     if ($this->printEnabled) {
         print_r($return);
     }
     return $return;
 }
예제 #8
0
 public function calcTotals()
 {
     global $whmcs;
     $retarray = array("subtotal" => "0", "taxenabled" => false, "taxname" => "", "taxrate" => 0, "taxname2" => "", "taxrate2" => 0);
     $subtotal = 11;
     foreach ($this->lineitems as $vals) {
         $subtotal += $vals['amount'];
     }
     $subtotal = round($subtotal, 2);
     if ($subtotal < 0 && !$whmcs->get_config("CreditOnDowngrade")) {
         $subtotal = 11;
     }
     if (is_array($this->promodata)) {
     } else {
         $promodata = get_query_vals("tblpromotions", "code,type,value", array("lifetimepromo" => 1, "recurring" => 1, "id" => get_query_val("tblhosting", "promoid", array("id" => $serviceid))));
         if (is_array($promodata)) {
             $smartyvalues['promocode'] = $promocode = $promodata['code'];
             $smartyvalues['promorecurring'] = $smartyvalues['promodesc'] = $promodata['type'] == "Percentage" ? $promodata['value'] . "%" : formatCurrency($promodata['value']);
             $smartyvalues->promodesc .= " " . $_LANG['orderdiscount'];
         }
     }
     $tax = $tax2 = 0;
     if ($whmcs->get_config("TaxEnabled") && $this->getProductInfo("tax")) {
         $clientsdetails = getClientsDetails($this->getProductInfo("userid"));
         $state = $clientsdetails['state'];
         $country = $clientsdetails['country'];
         $taxexempt = $clientsdetails['taxexempt'];
         if (!$taxexempt) {
             $retarray['taxenabled'] = true;
             $taxdata = getTaxRate(1, $state, $country);
             $retarray['taxname'] = $taxdata['name'];
             $retarray['taxrate'] = $taxrate = $taxdata['rate'];
             $taxdata2 = getTaxRate(2, $state, $country);
             $retarray['taxname2'] = $taxdata2['name'];
             $retarray['taxrate2'] = $taxrate2 = $taxdata2['rate'];
             if ($taxrate) {
                 if ($CONFIG['TaxType'] == "Inclusive") {
                     $inctaxrate = 1 + $taxrate / 100;
                     $tempsubtotal = $subtotal;
                     $subtotal = $subtotal / $inctaxrate;
                     $tax = $tempsubtotal - $subtotal;
                 } else {
                     $tax = $subtotal * ($taxrate / 100);
                 }
             }
             if ($taxrate2) {
                 $tempsubtotal = $subtotal;
                 if ($CONFIG['TaxL2Compound']) {
                     $tempsubtotal += $tax;
                 }
                 if ($CONFIG['TaxType'] == "Inclusive") {
                     $inctaxrate = 1 + $taxrate / 100;
                     $subtotal = $tempsubtotal / $inctaxrate;
                     $tax2 = $tempsubtotal - $subtotal;
                 } else {
                     $tax2 = $tempsubtotal * ($taxrate2 / 100);
                 }
             }
             $tax = round($tax, 2);
             $tax2 = round($tax2, 2);
         }
     }
     $retarray['subtotal'] = formatCurrency($subtotal);
     $retarray['tax'] = formatCurrency($tax);
     $retarray['tax2'] = formatCurrency($tax2);
     $retarray['total'] = formatCurrency($subtotal + $tax + $tax2);
     return $retarray;
 }
예제 #9
0
 public static function expense_item_tax($expense_id, $line_item_tax_id, $unit_price, $quantity, $action = "")
 {
     global $logger;
     global $db;
     $logger->log("Exp ITEM :: Key: " . $key . " Value: " . $value, Zend_Log::INFO);
     //if editing invoice delete all tax info then insert first then do insert again
     //probably can be done without delete - someone to look into this if required - TODO
     if ($action == "update") {
         $sql_delete = "DELETE from\n                                " . TB_PREFIX . "expense_item_tax\n                           WHERE\n                                expense_id = :expense_id";
         $logger->log("Expense item: " . $expense_id . " tax lines deleted", Zend_Log::INFO);
         $db->query($sql_delete, ':expense_id', $expense_id);
     }
     foreach ($line_item_tax_id as $key => $value) {
         if ($value !== "") {
             $tax = getTaxRate($value);
             $logger->log("Expense - item tax :: Key: " . $key . " Value: " . $value, Zend_Log::INFO);
             $logger->log('Expense - item tax :: tax rate: ' . $tax['tax_percentage'], Zend_Log::INFO);
             $tax_amount = lineItemTaxCalc($tax, $unit_price, $quantity);
             //get Total tax for line item
             $tax_total = $tax_total + $tax_amount;
             $logger->log('Expense - item tax :: Qty: ' . $quantity . ' Unit price: ' . $unit_price, Zend_Log::INFO);
             $logger->log('Expense - item tax :: Tax rate: ' . $tax[tax_percentage] . ' Tax type: ' . $tax['type'] . ' Tax $: ' . $tax_amount, Zend_Log::INFO);
             $sql = "INSERT \n                            INTO \n                        " . TB_PREFIX . "expense_item_tax \n                        (\n                            expense_id, \n                            tax_id, \n                            tax_type, \n                            tax_rate, \n                            tax_amount\n                        ) \n                        VALUES \n                        (\n                            :expense_id, \n                            :tax_id,\n                            :tax_type,\n                            :tax_rate,\n                            :tax_amount\n                        )";
             $db->query($sql, ':expense_id', $expense_id, ':tax_id', $tax[tax_id], ':tax_type', $tax[type], ':tax_rate', $tax[tax_percentage], ':tax_amount', $tax_amount);
         }
     }
     //TODO fix this
     return true;
 }
예제 #10
0
        $set.="taxincluded='f' ";
        $sql="update customer ".$set;
        $sql.="where id=".$rs[0]["id"];
        $rc=query("erp",$sql,"insKdData");
        if ($rc === -99) {
		//$sql="delete from customer where id=".$rs[0]["id"];
		//$rc=query("shop",$sql,"insNewKd");
		return false;
	} else { return $rs[0]["id"]; }
}


$LAND=array("Germany"=>"D","Austria"=>"A","Switzerland"=>"CH");
$skosten=array("Versand"=>"ot_shipping","NachName"=>"ot_cod_fee","Paypal"=>"ot_cod_fee","Minder"=>"ot_loworderfee");
$inclTax=checkTaxIncl();
$TaxFactor=($inclTax)?getTaxRate():1;
$bestellungen=getBestellung();
$ok=count($bestellungen);
$gesKd=0;
$neuKd=0;
if ($ok) {
	echo "Es liegen $ok Bestellungen vor. <br>";
	chkKunden();
    	echo $gesKd." Kunde(n), davon ".$neuKd." neue(r) Kunde(n).<br>";
    	foreach ($bestellungen as $bestellung) {
        	insAuftrag($bestellung);
    	}
} else { echo "Es liegen keine Bestellungen vor!<br>"; };
?>
<!--a href='trans.php'>zur&uuml;ck</a-->
</body>
예제 #11
0
$smarty->assign("quotenum", $id);
$smarty->assign("payto", nl2br($CONFIG['InvoicePayTo']));
$smarty->assign("datecreated", $date);
$smarty->assign("datedue", $duedate);
$smarty->assign("subtotal", number_format(round($subtotal, 2), 2));
$smarty->assign("discount", $discount) . "%";
$smarty->assign("tax", number_format(round($tax, 2), 2));
$smarty->assign("tax2", number_format(round($tax2, 2), 2));
$smarty->assign("total", number_format(round($total, 2), 2));
if ($taxrate != "0.00") {
    $taxname = getTaxRate(1, $clientsdetails['state'], $clientsdetails['country']);
    $smarty->assign("taxname", $taxname['name']);
    $smarty->assign("taxrate", $taxrate);
}
if ($taxrate2 != "0.00") {
    $taxname = getTaxRate(2, $clientsdetails['state'], $clientsdetails['country']);
    $smarty->assign("taxname2", $taxname['name']);
    $smarty->assign("taxrate2", $taxrate2);
}
$smarty->assign("stage", $stage);
$smarty->assign("validuntil", $validuntil);
$quoteitems = array();
$result = select_query("tblquoteitems", "quantity,description,unitprice,discount,taxable", array("quoteid" => $id), "id", "ASC");
while ($data = mysql_fetch_array($result)) {
    $qty = $data[0];
    $description = $data[1];
    $unitprice = $data[2];
    $discountpc = $discount = $data[3];
    $taxed = $data[4] ? true : false;
    if (1 < $qty) {
        $description = $qty . " x " . $description . " @ " . $unitprice . $_LANG['invoiceqtyeach'];
예제 #12
0
function createInvoicesProcess($data, $noemails = "", $nocredit = "")
{
    global $whmcs;
    global $cron;
    global $CONFIG;
    global $_LANG;
    global $invoicecount;
    global $invoiceid;
    $itemid = $data['id'];
    $userid = $data['userid'];
    $type = $data['type'];
    $relid = $data['relid'];
    $duedate = $data['duedate'];
    $paymentmethod = $invpaymentmethod = $data['paymentmethod'];
    if (!$invpaymentmethod) {
        if (!function_exists("getClientsPaymentMethod")) {
            require ROOTDIR . "/includes/clientfunctions.php";
        }
        $invpaymentmethod = getClientsPaymentMethod($userid);
        update_query("tblinvoiceitems", array("paymentmethod" => $invpaymentmethod), array("id" => $itemid));
    }
    if ($itemid) {
        if (get_query_val("tblinvoiceitems", "invoiceid", array("id" => $itemid))) {
            return false;
        }
    }
    $taxrate = $taxrate2 = 0;
    if ($CONFIG['TaxEnabled']) {
        $data = get_query_vals("tblclients", "taxexempt,state,country,separateinvoices", array("id" => $userid));
        $taxexempt = $data['taxexempt'];
        $taxstate = $data['state'];
        $taxcountry = $data['country'];
        if (!$taxexempt) {
            $taxrate = getTaxRate(1, $taxstate, $taxcountry);
            $taxrate2 = getTaxRate(2, $taxstate, $taxcountry);
            $taxrate = $taxrate['rate'];
            $taxrate2 = $taxrate2['rate'];
        }
    }
    $invoiceid = insert_query("tblinvoices", array("date" => "now()", "duedate" => $duedate, "userid" => $userid, "status" => "Unpaid", "taxrate" => $taxrate, "taxrate2" => $taxrate2, "paymentmethod" => $invpaymentmethod, "notes" => $invoicenotes));
    if ($itemid) {
        update_query("tblinvoiceitems", array("invoiceid" => $invoiceid), array("invoiceid" => "0", "userid" => $userid, "type" => "Promo" . $type, "relid" => $relid));
        $where = array("id" => $itemid);
    } else {
        $where = array("invoiceid" => "", "duedate" => $duedate, "userid" => $userid, "paymentmethod" => $paymentmethod);
    }
    update_query("tblinvoiceitems", array("invoiceid" => $invoiceid), $where);
    logActivity("Created Invoice - Invoice ID: " . $invoiceid, $userid);
    if (is_object($cron)) {
        $cron->logActivityDebug("Generated Invoice #" . $invoiceid);
    }
    $billableitemstax = $CONFIG['TaxEnabled'] && $CONFIG['TaxCustomInvoices'] ? "1" : "0";
    $result2 = select_query("tblbillableitems", "", array("userid" => $userid, "invoiceaction" => "2", "invoicecount" => "0"));
    while ($data = mysql_fetch_array($result2)) {
        insert_query("tblinvoiceitems", array("invoiceid" => $invoiceid, "userid" => $userid, "type" => "Item", "relid" => $data['id'], "description" => $data['description'], "amount" => $data['amount'], "taxed" => $billableitemstax));
        update_query("tblbillableitems", array("invoicecount" => "+1"), array("id" => $data['id']));
    }
    updateInvoiceTotal($invoiceid);
    $data2 = get_query_vals("tblclients", "credit,groupid", array("id" => $userid));
    $credit = $data2['credit'];
    $groupid = $data2['groupid'];
    $data2 = get_query_vals("tblinvoices", "subtotal,total", array("id" => $invoiceid));
    $subtotal = $data2['subtotal'];
    $total = $data2['total'];
    $isaddfundsinvoice = get_query_val("tblinvoiceitems", "COUNT(id)", "invoiceid='" . $invoiceid . "' AND (type='AddFunds' OR type='Invoice')");
    if ($groupid && !$isaddfundsinvoice) {
        $discountpercent = get_query_val("tblclientgroups", "discountpercent", array("id" => $groupid));
        if (0 < $discountpercent) {
            $discountamount = $subtotal * ($discountpercent / 100) * (0 - 1);
            insert_query("tblinvoiceitems", array("invoiceid" => $invoiceid, "userid" => $userid, "type" => "GroupDiscount", "description" => $_LANG['clientgroupdiscount'], "amount" => $discountamount, "taxed" => "1"));
            updateInvoiceTotal($invoiceid);
            $data2 = get_query_vals("tblclients", "credit,groupid", array("id" => $userid));
            $credit = $data2['credit'];
            $groupid = $data2['groupid'];
            $data2 = get_query_vals("tblinvoices", "subtotal,total", array("id" => $invoiceid));
            $subtotal = $data2['subtotal'];
            $total = $data2['total'];
        }
    }
    if ($whmcs->get_config("ContinuousInvoiceGeneration")) {
        $result2 = select_query("tblinvoiceitems", "", array("invoiceid" => $invoiceid));
        while ($data = mysql_fetch_array($result2)) {
            $type = $data['type'];
            $relid = $data['relid'];
            $nextinvoicedate = $data['duedate'];
            $year = substr($nextinvoicedate, 0, 4);
            $month = substr($nextinvoicedate, 5, 2);
            $day = substr($nextinvoicedate, 8, 2);
            $proratabilling = false;
            if ($type == "Hosting") {
                $data = get_query_vals("tblhosting", "billingcycle,packageid,regdate,nextduedate", array("id" => $relid));
                $billingcycle = $data['billingcycle'];
                $packageid = $data['packageid'];
                $regdate = $data['regdate'];
                $nextduedate = $data['nextduedate'];
                $data = get_query_vals("tblproducts", "proratabilling,proratadate,proratachargenextmonth", array("id" => $packageid));
                $proratabilling = $data['proratabilling'];
                $proratadate = $data['proratadate'];
                $proratachargenextmonth = $data['proratachargenextmonth'];
                $proratamonths = getBillingCycleMonths($billingcycle);
                $nextinvoicedate = date("Ymd", mktime(0, 0, 0, $month + $proratamonths, $day, $year));
            } else {
                if ($type == "Domain" || $type == "DomainRegister" || $type == "DomainTransfer") {
                    $data = get_query_vals("tbldomains", "registrationperiod,nextduedate", array("id" => $relid));
                    $registrationperiod = $data['registrationperiod'];
                    $nextduedate = explode("-", $data['nextduedate']);
                    $billingcycle = "";
                    $nextinvoicedate = date("Ymd", mktime(0, 0, 0, $nextduedate[1], $nextduedate[2], $nextduedate[0] + $registrationperiod));
                } else {
                    if ($type == "Addon") {
                        $billingcycle = get_query_val("tblhostingaddons", "billingcycle", array("id" => $relid));
                        $proratamonths = getBillingCycleMonths($billingcycle);
                        $nextinvoicedate = date("Ymd", mktime(0, 0, 0, $month + $proratamonths, $day, $year));
                    }
                }
            }
            if ($billingcycle == "One Time") {
                $nextinvoicedate = "00000000";
            }
            if ($regdate == $nextduedate && $proratabilling) {
                if ($billingcycle != "Monthly") {
                    $proratachargenextmonth = 0;
                }
                $orderyear = substr($regdate, 0, 4);
                $ordermonth = substr($regdate, 5, 2);
                $orderday = substr($regdate, 8, 2);
                if ($orderday < $proratadate) {
                    $proratamonth = $ordermonth;
                } else {
                    $proratamonth = $ordermonth + 1;
                }
                $days = (strtotime(date("Y-m-d", mktime(0, 0, 0, $proratamonth, $proratadate, $orderyear))) - strtotime(date("Y-m-d"))) / (60 * 60 * 24);
                $totaldays = 30;
                $nextinvoicedate = date("Y-m-d", mktime(0, 0, 0, $proratamonth, $proratadate, $orderyear));
                if ($proratachargenextmonth <= $orderday && $days < 31) {
                    $nextinvoicedate = date("Y-m-d", mktime(0, 0, 0, $proratamonth + $proratamonths, $proratadate, $orderyear));
                }
            }
            if ($type == "Hosting") {
                update_query("tblhosting", array("nextinvoicedate" => $nextinvoicedate), array("id" => $relid));
            }
            if ($type == "Domain" || $type == "DomainRegister" || $type == "DomainTransfer") {
                update_query("tbldomains", array("nextinvoicedate" => $nextinvoicedate), array("id" => $relid));
            }
            if ($type == "Addon") {
                update_query("tblhostingaddons", array("nextinvoicedate" => $nextinvoicedate), array("id" => $relid));
            }
        }
    }
    $doprocesspaid = false;
    if (!$nocredit && $credit != "0.00" && !$CONFIG['NoAutoApplyCredit']) {
        if ($total <= $credit) {
            $creditleft = $credit - $total;
            $credit = $total;
            $doprocesspaid = true;
        } else {
            $creditleft = 0;
        }
        logActivity("Credit Automatically Applied at Invoice Creation - Invoice ID: " . $invoiceid . " - Amount: " . $credit, $userid);
        insert_query("tblcredit", array("clientid" => $userid, "date" => "now()", "description" => "Credit Applied to Invoice #" . $invoiceid, "amount" => $credit * (0 - 1)));
        update_query("tblclients", array("credit" => $creditleft), array("id" => $userid));
        update_query("tblinvoices", array("credit" => $credit), array("id" => $invoiceid));
        updateInvoiceTotal($invoiceid);
    }
    run_hook("InvoiceCreationPreEmail", array("invoiceid" => $invoiceid));
    if ($doprocesspaid) {
        processPaidInvoice($invoiceid);
    }
    $result2 = select_query("tblpaymentgateways", "value", array("gateway" => $invpaymentmethod, "setting" => "type"));
    $data2 = mysql_fetch_array($result2);
    $paymenttype = $data2['value'];
    if ($noemails != "true") {
        sendMessage(($paymenttype == "CC" || $paymenttype == "OfflineCC" ? "Credit Card " : "") . "Invoice Created", $invoiceid);
    }
    $result2 = select_query("tblinvoices", "total", array("id" => $invoiceid, "status" => "Unpaid"));
    $data2 = mysql_fetch_array($result2);
    $total = $data2['total'];
    if ($total == "0.00") {
        processPaidInvoice($invoiceid);
    }
    run_hook("InvoiceCreated", array("invoiceid" => $invoiceid));
    $invoicetotal = 0;
    ++$invoicecount;
    if (1 < $CONFIG['InvoiceIncrement']) {
        $invoiceincrement = $CONFIG['InvoiceIncrement'] - 1;
        $counter = 1;
        while ($counter <= $invoiceincrement) {
            $tempinvoiceid = insert_query("tblinvoices", array("date" => "now()"));
            delete_query("tblinvoices", array("id" => $tempinvoiceid));
            $counter += 1;
        }
    }
}
예제 #13
0
<?php

//stop the direct browsing to this file - let index.php handle which files get displayed
checkLogin();
#get the invoice id
$product_id = $_GET['id'];
$product = getProduct($product_id);
#get custom field labels
$customFieldLabel = getCustomFieldLabels();
$taxes = getActiveTaxes();
$tax_selected = getTaxRate($product['default_tax_id']);
$smarty->assign("defaults", getSystemDefaults());
$smarty->assign('product', $product);
$smarty->assign('taxes', $taxes);
$smarty->assign('tax_selected', $tax_selected);
$smarty->assign('customFieldLabel', $customFieldLabel);
$smarty->assign('pageActive', 'product_manage');
$subPageActive = $_GET['action'] == "view" ? "product_view" : "product_edit";
$smarty->assign('subPageActive', $subPageActive);
$smarty->assign('active_tab', '#product');
예제 #14
0
function calcCartTotals($checkout = "", $ignorenoconfig = "")
{
    global $CONFIG;
    global $_LANG;
    global $remote_ip;
    global $currency;
    global $promo_data;
    $cart_total = $cart_discount = $cart_tax = 0;
    run_hook("PreCalculateCartTotals", $_SESSION['cart']);
    if (!$ignorenoconfig) {
        if (array_key_exists("products", $_SESSION['cart'])) {
            foreach ($_SESSION['cart']['products'] as $key => $productdata) {
                if ($productdata['noconfig']) {
                    unset($_SESSION['cart']['products'][$key]);
                    continue;
                }
            }
        }
        $bundlewarnings = bundlesValidateCheckout();
        if (array_key_exists("products", $_SESSION['cart'])) {
            $_SESSION['cart']['products'] = array_values($_SESSION['cart']['products']);
        }
    }
    if ($checkout) {
        if (!$_SESSION['cart']) {
            return false;
        }
        run_hook("PreShoppingCartCheckout", $_SESSION['cart']);
        $order_number = generateUniqueID();
        $paymentmethod = $_SESSION['cart']['paymentmethod'];
        $availablegateways = getAvailableOrderPaymentGateways();
        if (!array_key_exists($paymentmethod, $availablegateways)) {
            foreach ($availablegateways as $k => $v) {
                $paymentmethod = $k;
                break;
            }
        }
        $userid = $_SESSION['uid'];
        $ordernotes = "";
        if ($_SESSION['cart']['notes'] && $_SESSION['cart']['notes'] != $_LANG['ordernotesdescription']) {
            $ordernotes = $_SESSION['cart']['notes'];
        }
        $cartitems = count($_SESSION['cart']['products']) + count($_SESSION['cart']['addons']) + count($_SESSION['cart']['domains']) + count($_SESSION['cart']['renewals']);
        if (!$cartitems) {
            return false;
        }
        $orderid = insert_query("tblorders", array("ordernum" => $order_number, "userid" => $userid, "contactid" => $_SESSION['cart']['contact'], "date" => "now()", "status" => "Pending", "paymentmethod" => $paymentmethod, "ipaddress" => $remote_ip, "notes" => $ordernotes));
        logActivity("New Order Placed - Order ID: " . $orderid . " - User ID: " . $userid);
        $domaineppcodes = array();
    }
    $promotioncode = array_key_exists("promo", $_SESSION['cart']) ? $_SESSION['cart']['promo'] : "";
    if ($promotioncode) {
        $result = select_query("tblpromotions", "", array("code" => $promotioncode));
        $promo_data = mysql_fetch_array($result);
    }
    if (!isset($_SESSION['uid'])) {
        if (!$_SESSION['cart']['user']['country']) {
            $_SESSION['cart']['user']['country'] = $CONFIG['DefaultCountry'];
        }
        $state = $_SESSION['cart']['user']['state'];
        $country = $_SESSION['cart']['user']['country'];
    } else {
        $clientsdetails = getClientsDetails($_SESSION['uid']);
        $state = $clientsdetails['state'];
        $country = $clientsdetails['country'];
    }
    if ($CONFIG['TaxEnabled']) {
        $taxdata = getTaxRate(1, $state, $country);
        $taxname = $taxdata['name'];
        $taxrate = $taxdata['rate'];
        $rawtaxrate = $taxrate;
        $inctaxrate = $taxrate / 100 + 1;
        $taxrate /= 100;
        $taxdata = getTaxRate(2, $state, $country);
        $taxname2 = $taxdata['name'];
        $taxrate2 = $taxdata['rate'];
        $rawtaxrate2 = $taxrate2;
        $inctaxrate2 = $taxrate2 / 100 + 1;
        $taxrate2 /= 100;
    }
    if ($CONFIG['TaxInclusiveDeduct'] && (!$taxrate && !$taxrate2 || $clientsdetails['taxexempt'])) {
        $result = select_query("tbltax", "", "");
        $data = mysql_fetch_array($result);
        $excltaxrate = 1 + $data['taxrate'] / 100;
    } else {
        $CONFIG['TaxInclusiveDeduct'] = 0;
    }
    $cartdata = $productsarray = $tempdomains = $orderproductids = $orderdomainids = $orderaddonids = $orderrenewalids = $freedomains = array();
    $recurring_cycles_total = array("monthly" => 0, "quarterly" => 0, "semiannually" => 0, "annually" => 0, "biennially" => 0, "triennially" => 0);
    if (array_key_exists("products", $_SESSION['cart']) && is_array($_SESSION['cart']['products'])) {
        foreach ($_SESSION['cart']['products'] as $key => $productdata) {
            $result = select_query("tblproducts", "tblproducts.id,tblproducts.gid,tblproductgroups.name AS groupname,tblproducts.name,tblproducts.paytype,tblproducts.allowqty,tblproducts.proratabilling,tblproducts.proratadate,tblproducts.proratachargenextmonth,tblproducts.tax,tblproducts.servertype,tblproducts.servergroup,tblproducts.stockcontrol,tblproducts.freedomain,tblproducts.freedomainpaymentterms,tblproducts.freedomaintlds", array("tblproducts.id" => $productdata['pid']), "", "", "", "tblproductgroups ON tblproductgroups.id=tblproducts.gid");
            $data = mysql_fetch_array($result);
            $pid = $data['id'];
            $gid = $data['gid'];
            $groupname = $data['groupname'];
            $productname = $data['name'];
            $paytype = $data['paytype'];
            $allowqty = $data['allowqty'];
            $proratabilling = $data['proratabilling'];
            $proratadate = $data['proratadate'];
            $proratachargenextmonth = $data['proratachargenextmonth'];
            $tax = $data['tax'];
            $servertype = $data['servertype'];
            $servergroup = $data['servergroup'];
            $stockcontrol = $data['stockcontrol'];
            $freedomain = $data['freedomain'];
            if ($freedomain) {
                $freedomainpaymentterms = $data['freedomainpaymentterms'];
                $freedomaintlds = $data['freedomaintlds'];
                $freedomainpaymentterms = explode(",", $freedomainpaymentterms);
                $freedomaintlds = explode(",", $freedomaintlds);
            } else {
                $freedomainpaymentterms = $freedomaintlds = array();
            }
            $productinfo = getProductInfo($pid);
            $productdata['productinfo'] = $productinfo;
            if (!function_exists("getCustomFields")) {
                require ROOTDIR . "/includes/customfieldfunctions.php";
            }
            $customfields = getCustomFields("product", $pid, "", true, "", $productdata['customfields']);
            $productdata['customfields'] = $customfields;
            $pricing = getPricingInfo($pid);
            $qty = $productdata['qty'];
            if (!$allowqty || !$qty) {
                $qty = 1;
            }
            $productdata['allowqty'] = $allowqty;
            $productdata['qty'] = $qty;
            if ($pricing['type'] == "recurring") {
                $billingcycle = strtolower($productdata['billingcycle']);
                if (!in_array($billingcycle, array("monthly", "quarterly", "semiannually", "annually", "biennially", "triennially"))) {
                    $billingcycle = "";
                }
                if ($pricing['rawpricing'][$billingcycle] < 0) {
                    $billingcycle = "";
                }
                if (!$billingcycle) {
                    if (0 <= $pricing['rawpricing']['monthly']) {
                        $billingcycle = "monthly";
                    } else {
                        if (0 <= $pricing['rawpricing']['quarterly']) {
                            $billingcycle = "quarterly";
                        } else {
                            if (0 <= $pricing['rawpricing']['semiannually']) {
                                $billingcycle = "semiannually";
                            } else {
                                if (0 <= $pricing['rawpricing']['annually']) {
                                    $billingcycle = "annually";
                                } else {
                                    if (0 <= $pricing['rawpricing']['biennially']) {
                                        $billingcycle = "biennially";
                                    } else {
                                        if (0 <= $pricing['rawpricing']['triennially']) {
                                            $billingcycle = "triennially";
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                if ($pricing['type'] == "onetime") {
                    $billingcycle = "onetime";
                } else {
                    $billingcycle = "free";
                }
            }
            $productdata['billingcycle'] = $billingcycle;
            if ($billingcycle == "free") {
                $product_setup = $product_onetime = $product_recurring = "0";
                $databasecycle = "Free Account";
            } else {
                if ($billingcycle == "onetime") {
                    $product_setup = $pricing['rawpricing']['msetupfee'];
                    $product_onetime = $pricing['rawpricing']['monthly'];
                    $product_recurring = 0;
                    $databasecycle = "One Time";
                } else {
                    $product_setup = $pricing['rawpricing'][substr($billingcycle, 0, 1) . "setupfee"];
                    $product_onetime = $product_recurring = $pricing['rawpricing'][$billingcycle];
                    $databasecycle = ucfirst($billingcycle);
                    if ($databasecycle == "Semiannually") {
                        $databasecycle = "Semi-Annually";
                    }
                }
            }
            $before_priceoverride_value = "";
            if ($bundleoverride = bundlesGetProductPriceOverride("product", $key)) {
                $before_priceoverride_value = $product_setup + $product_onetime;
                $product_setup = 0;
                $product_onetime = $product_recurring = $bundleoverride;
            }
            $hookret = run_hook("OrderProductPricingOverride", array("key" => $key, "pid" => $pid, "proddata" => $productdata));
            foreach ($hookret as $hookret2) {
                if (is_array($hookret2)) {
                    if ($hookret2['setup']) {
                        $product_setup = $hookret2['setup'];
                    }
                    if ($hookret2['recurring']) {
                        $product_onetime = $product_recurring = $hookret2['recurring'];
                        continue;
                    }
                    continue;
                }
            }
            $productdata['pricing']['baseprice'] = formatCurrency($product_onetime);
            $configurableoptions = array();
            $configurableoptions = getCartConfigOptions($pid, $productdata['configoptions'], $billingcycle);
            $configoptions = "";
            if ($configurableoptions) {
                foreach ($configurableoptions as $confkey => $value) {
                    $configoptions[] = array("name" => $value['optionname'], "type" => $value['optiontype'], "option" => $value['selectedoption'], "optionname" => $value['selectedname'], "setup" => 0 < $value['selectedsetup'] ? formatCurrency($value['selectedsetup']) : "", "recurring" => formatCurrency($value['selectedrecurring']), "qty" => $value['selectedqty']);
                    $configoptionsdb[$value['id']] = array("value" => $value['selectedvalue'], "qty" => $value['selectedqty']);
                    $product_setup += $value['selectedsetup'];
                    $product_onetime += $value['selectedrecurring'];
                    if (strlen($before_priceoverride_value)) {
                        $before_priceoverride_value += $value['selectedrecurring'];
                    }
                    if ($billingcycle != "onetime") {
                        $product_recurring += $value['selectedrecurring'];
                        continue;
                    }
                }
            }
            $productdata['configoptions'] = $configoptions;
            if (in_array($billingcycle, $freedomainpaymentterms)) {
                $domain = $productdata['domain'];
                $domainparts = explode(".", $domain, 2);
                $tld = "." . $domainparts[1];
                if (in_array($tld, $freedomaintlds)) {
                    $freedomains[$domain] = $freedomain;
                }
            }
            if ($proratabilling) {
                $proratavalues = getProrataValues($billingcycle, $product_onetime, $proratadate, $proratachargenextmonth, date("d"), date("m"), date("Y"), $_SESSION['uid']);
                $product_onetime = $proratavalues['amount'];
                $productdata['proratadate'] = fromMySQLDate($proratavalues['date']);
            }
            if ($CONFIG['TaxInclusiveDeduct']) {
                $product_setup = format_as_currency($product_setup / $excltaxrate);
                $product_onetime = format_as_currency($product_onetime / $excltaxrate);
                $product_recurring = format_as_currency($product_recurring / $excltaxrate);
            }
            $product_total_today_db = $product_setup + $product_onetime;
            $product_recurring_db = $product_recurring;
            $productdata['pricing']['setup'] = $product_setup * $qty;
            $productdata['pricing']['recurring'][$billingcycle] = $product_recurring * $qty;
            $productdata['pricing']['totaltoday'] = $product_total_today_db * $qty;
            if ($product_onetime == 0 && $product_recurring == 0) {
                $pricing_text = $_LANG['orderfree'];
            } else {
                $pricing_text = "";
                if (strlen($before_priceoverride_value)) {
                    $pricing_text .= "<strike>" . formatCurrency($before_priceoverride_value) . "</strike> ";
                }
                $pricing_text .= formatCurrency($product_onetime);
                if (0 < $product_setup) {
                    $pricing_text .= " + " . formatCurrency($product_setup) . " " . $_LANG['ordersetupfee'];
                }
                if ($allowqty && 1 < $qty) {
                    $pricing_text .= $_LANG['invoiceqtyeach'] . "<br />" . $_LANG['invoicestotal'] . ": " . formatCurrency($productdata['pricing']['totaltoday']);
                }
            }
            $productdata['pricingtext'] = $pricing_text;
            if ($promotioncode) {
                $onetimediscount = $recurringdiscount = $promoid = 0;
                if ($promocalc = CalcPromoDiscount($pid, $databasecycle, $product_total_today_db, $product_recurring_db, $product_setup)) {
                    $onetimediscount = $promocalc['onetimediscount'];
                    $recurringdiscount = $promocalc['recurringdiscount'];
                    $product_total_today_db -= $onetimediscount;
                    $product_recurring_db -= $recurringdiscount;
                    $cart_discount += $onetimediscount * $qty;
                    $promoid = $promo_data['id'];
                }
            }
            if (isset($productdata['priceoverride'])) {
                $product_total_today_db = $product_recurring_db = $product_onetime = $productdata['priceoverride'];
                $product_setup = 0;
            }
            $cart_total += $product_total_today_db * $qty;
            $product_total_qty_recurring = $product_recurring_db * $qty;
            if ($CONFIG['TaxEnabled'] && $tax && !$clientsdetails['taxexempt']) {
                $cart_tax += $product_total_today_db * $qty;
                if ($CONFIG['TaxType'] == "Exclusive") {
                    if ($CONFIG['TaxL2Compound']) {
                        $product_total_qty_recurring += $product_total_qty_recurring * $taxrate;
                        $product_total_qty_recurring += $product_total_qty_recurring * $taxrate2;
                    } else {
                        $product_total_qty_recurring += $product_total_qty_recurring * $taxrate + $product_total_qty_recurring * $taxrate2;
                    }
                }
            }
            $recurring_cycles_total[$billingcycle] += $product_total_qty_recurring;
            $domain = $productdata['domain'];
            $serverhostname = $productdata['server']['hostname'];
            $serverns1prefix = $productdata['server']['ns1prefix'];
            $serverns2prefix = $productdata['server']['ns2prefix'];
            $serverrootpw = encrypt($productdata['server']['rootpw']);
            if ($serverns1prefix && $domain) {
                $serverns1prefix = $serverns1prefix . "." . $domain;
            }
            if ($serverns2prefix && $domain) {
                $serverns2prefix = $serverns2prefix . "." . $domain;
            }
            if ($serverhostname) {
                $domain = $domain ? $serverhostname . "." . $domain : $serverhostname;
            }
            $productdata['domain'] = $domain;
            if ($checkout) {
                $multiqtyids = array();
                $qtycount = 1;
                while ($qtycount <= $qty) {
                    $serverid = $servertype ? getServerID($servertype, $servergroup) : "0";
                    $hostingquerydates = $databasecycle == "Free Account" ? "0000-00-00" : date("Y-m-d");
                    $serviceid = insert_query("tblhosting", array("userid" => $userid, "orderid" => $orderid, "packageid" => $pid, "server" => $serverid, "regdate" => "now()", "domain" => $domain, "paymentmethod" => $paymentmethod, "firstpaymentamount" => $product_total_today_db, "amount" => $product_recurring_db, "billingcycle" => $databasecycle, "nextduedate" => $hostingquerydates, "nextinvoicedate" => $hostingquerydates, "domainstatus" => "Pending", "ns1" => $serverns1prefix, "ns2" => $serverns2prefix, "password" => $serverrootpw, "promoid" => $promoid));
                    $multiqtyids[$qtycount] = $serviceid;
                    $orderproductids[] = $serviceid;
                    if ($stockcontrol) {
                        full_query("UPDATE tblproducts SET qty=qty-1 WHERE id='" . mysql_real_escape_string($pid) . "'");
                    }
                    if ($configoptionsdb) {
                        foreach ($configoptionsdb as $key => $value) {
                            insert_query("tblhostingconfigoptions", array("relid" => $serviceid, "configid" => $key, "optionid" => $value['value'], "qty" => $value['qty']));
                        }
                    }
                    foreach ($productdata['customfields'] as $key => $value) {
                        insert_query("tblcustomfieldsvalues", array("fieldid" => $value['id'], "relid" => $serviceid, "value" => $value['rawvalue']));
                    }
                    $productdetails = getInvoiceProductDetails($serviceid, $pid, date("Y-m-d"), $hostingquerydates, $databasecycle, $domain);
                    $invoice_description = $productdetails['description'];
                    $invoice_tax = $productdetails['tax'];
                    if (!$_SESSION['cart']['geninvoicedisabled']) {
                        $prodinvoicearray = array();
                        $prodinvoicearray['userid'] = $userid;
                        $prodinvoicearray['type'] = "Hosting";
                        $prodinvoicearray['relid'] = $serviceid;
                        $prodinvoicearray['taxed'] = $invoice_tax;
                        $prodinvoicearray['duedate'] = $hostingquerydates;
                        $prodinvoicearray['paymentmethod'] = $paymentmethod;
                        if (0 < $product_setup) {
                            $prodinvoicearray['description'] = $productname . " " . $_LANG['ordersetupfee'];
                            $prodinvoicearray['amount'] = $product_setup;
                            insert_query("tblinvoiceitems", $prodinvoicearray);
                            $prodinvoicearray['type'] = "";
                            $prodinvoicearray['relid'] = 0;
                        }
                        if (0 < $product_onetime) {
                            $prodinvoicearray['description'] = $invoice_description;
                            $prodinvoicearray['amount'] = $product_onetime;
                            insert_query("tblinvoiceitems", $prodinvoicearray);
                        }
                        $promovals = getInvoiceProductPromo($product_total_today_db, $promoid, $userid, $serviceid, $product_setup + $product_onetime);
                        if ($promovals['description']) {
                            $prodinvoicearray['type'] = "PromoHosting";
                            $prodinvoicearray['description'] = $promovals['description'];
                            $prodinvoicearray['amount'] = $promovals['amount'];
                            insert_query("tblinvoiceitems", $prodinvoicearray);
                        }
                    }
                    $adminemailitems .= $_LANG['orderproduct'] . (": " . $groupname . " - " . $productname . "<br>\r\n");
                    if ($domain) {
                        $adminemailitems .= $_LANG['orderdomain'] . (": " . $domain . "<br>\r\n");
                    }
                    foreach ($configurableoptions as $confkey => $value) {
                        $adminemailitems .= $value['optionname'] . ": " . $value['selectedname'] . "<br />\r\n";
                    }
                    foreach ($customfields as $customfield) {
                        if (!$customfield['adminonly']) {
                            $adminemailitems .= "" . $customfield['name'] . ": " . $customfield['value'] . "<br />\r\n";
                            continue;
                        }
                    }
                    $adminemailitems .= $_LANG['firstpaymentamount'] . ": " . formatCurrency($product_total_today_db) . "<br>\r\n";
                    if ($product_recurring_db) {
                        $adminemailitems .= $_LANG['recurringamount'] . ": " . formatCurrency($product_recurring_db) . "<br>\r\n";
                    }
                    $adminemailitems .= $_LANG['orderbillingcycle'] . ": " . $_LANG["orderpaymentterm" . str_replace(array("-", " "), "", strtolower($databasecycle))] . "<br>\r\n";
                    if ($allowqty && 1 < $qty) {
                        $adminemailitems .= $_LANG['quantity'] . (": " . $qty . "<br>\r\n") . $_LANG['invoicestotal'] . ": " . $productdata['pricing']['totaltoday'] . "<br>\r\n";
                    }
                    $adminemailitems .= "<br>\r\n";
                    ++$qtycount;
                }
            }
            $addonsarray = array();
            $addons = $productdata['addons'];
            if ($addons) {
                foreach ($addons as $addonid) {
                    $result = select_query("tbladdons", "name,description,billingcycle,tax", array("id" => $addonid));
                    $data = mysql_fetch_array($result);
                    $addon_name = $data['name'];
                    $addon_description = $data['description'];
                    $addon_billingcycle = $data['billingcycle'];
                    $addon_tax = $data['tax'];
                    if (!$CONFIG['TaxEnabled']) {
                        $addon_tax = "";
                    }
                    $result = select_query("tblpricing", "msetupfee,monthly", array("type" => "addon", "currency" => $currency['id'], "relid" => $addonid));
                    $data = mysql_fetch_array($result);
                    $addon_setupfee = $data['msetupfee'];
                    $addon_recurring = $data['monthly'];
                    $hookret = run_hook("OrderAddonPricingOverride", array("key" => $key, "pid" => $pid, "addonid" => $addonid, "proddata" => $productdata));
                    foreach ($hookret as $hookret2) {
                        if (is_array($hookret2)) {
                            if ($hookret2['setup']) {
                                $addon_setupfee = $hookret2['setup'];
                            }
                            if ($hookret2['recurring']) {
                                $addon_recurring = $hookret2['recurring'];
                                continue;
                            }
                            continue;
                        }
                    }
                    $addon_total_today_db = $addon_setupfee + $addon_recurring;
                    $addon_recurring_db = $addon_recurring;
                    $addon_total_today = $addon_total_today_db * $qty;
                    if ($CONFIG['TaxInclusiveDeduct']) {
                        $addon_total_today_db = round($addon_total_today_db / $excltaxrate, 2);
                        $addon_recurring_db = round($addon_recurring_db / $excltaxrate, 2);
                    }
                    if ($promotioncode) {
                        $onetimediscount = $recurringdiscount = $promoid = 0;
                        if ($promocalc = CalcPromoDiscount("A" . $addonid, $addon_billingcycle, $addon_total_today_db, $addon_recurring_db, $addon_setupfee)) {
                            $onetimediscount = $promocalc['onetimediscount'];
                            $recurringdiscount = $promocalc['recurringdiscount'];
                            $addon_total_today_db -= $onetimediscount;
                            $addon_recurring_db -= $recurringdiscount;
                            $cart_discount += $onetimediscount * $qty;
                        }
                    }
                    if ($checkout) {
                        $qtycount = 1;
                        while ($qtycount <= $qty) {
                            $serviceid = $multiqtyids[$qtycount];
                            $addonsetupfee = $addon_total_today_db - $addon_recurring_db;
                            $aid = insert_query("tblhostingaddons", array("hostingid" => $serviceid, "addonid" => $addonid, "orderid" => $orderid, "regdate" => "now()", "name" => "", "setupfee" => $addonsetupfee, "recurring" => $addon_recurring_db, "billingcycle" => $addon_billingcycle, "status" => "Pending", "nextduedate" => "now()", "nextinvoicedate" => "now()", "paymentmethod" => $paymentmethod, "tax" => $addon_tax));
                            $orderaddonids[] = $aid;
                            $adminemailitems .= $_LANG['clientareaaddon'] . (": " . $addon_name . "<br>\r\n") . $_LANG['ordersetupfee'] . ": " . formatCurrency($addonsetupfee) . "<br>\r\n";
                            if ($addon_recurring_db) {
                                $adminemailitems .= $_LANG['recurringamount'] . ": " . formatCurrency($addon_recurring_db) . "<br>\r\n";
                            }
                            $adminemailitems .= $_LANG['orderbillingcycle'] . ": " . $_LANG["orderpaymentterm" . str_replace(array("-", " "), "", strtolower($addon_billingcycle))] . "<br>\r\n<br>\r\n";
                            ++$qtycount;
                        }
                    }
                    $addon_total_today_db *= $qty;
                    $cart_total += $addon_total_today_db;
                    $addon_recurring_db *= $qty;
                    if ($addon_tax && !$clientsdetails['taxexempt']) {
                        $cart_tax += $addon_total_today_db;
                        if ($CONFIG['TaxType'] == "Exclusive") {
                            if ($CONFIG['TaxL2Compound']) {
                                $addon_recurring_db += $addon_recurring_db * $taxrate;
                                $addon_recurring_db += $addon_recurring_db * $taxrate2;
                            } else {
                                $addon_recurring_db += $addon_recurring_db * $taxrate + $addon_recurring_db * $taxrate2;
                            }
                        }
                    }
                    $addon_billingcycle = str_replace(array("-", " "), "", strtolower($addon_billingcycle));
                    $recurring_cycles_total[$addon_billingcycle] += $addon_recurring_db;
                    if ($addon_setupfee == "0" && $addon_recurring == "0") {
                        $pricing_text = $_LANG['orderfree'];
                    } else {
                        $pricing_text = formatCurrency($addon_recurring);
                        if ($addon_setupfee != "0.00") {
                            $pricing_text .= " + " . formatCurrency($addon_setupfee) . " " . $_LANG['ordersetupfee'];
                        }
                        if ($allowqty && 1 < $qty) {
                            $pricing_text .= $_LANG['invoiceqtyeach'] . "<br />" . $_LANG['invoicestotal'] . ": " . formatCurrency($addon_total_today);
                        }
                    }
                    $addonsarray[] = array("name" => $addon_name, "pricingtext" => $pricing_text, "setup" => formatCurrency($addon_setupfee), "recurring" => formatCurrency($addon_recurring), "totaltoday" => formatCurrency($addon_total_today));
                    $productdata['pricing']['setup'] += $addon_setupfee * $qty;
                    $productdata['pricing']['addons'] += $addon_recurring * $qty;
                    $productdata['pricing']['recurring'][$addon_billingcycle] += $addon_recurring * $qty;
                    $productdata['pricing']['totaltoday'] += $addon_total_today;
                }
            }
            $productdata['addons'] = $addonsarray;
            $totaltaxrates = 1;
            if ($CONFIG['TaxEnabled'] && $tax && !$clientsdetails['taxexempt']) {
                $product_tax = $productdata['pricing']['totaltoday'];
                if ($CONFIG['TaxType'] == "Inclusive") {
                    $totaltaxrates = 1 + ($taxrate + $taxrate2);
                    $total_without_tax = $productdata['pricing']['totaltoday'] = $product_tax / $totaltaxrates;
                    $total_tax_1 = $total_without_tax * $taxrate;
                    $total_tax_2 = $total_without_tax * $taxrate2;
                } else {
                    $total_tax_1 = $product_tax * $taxrate;
                    if ($CONFIG['TaxL2Compound']) {
                        $total_tax_2 = ($product_tax + $total_tax_1) * $taxrate2;
                    } else {
                        $total_tax_2 = $product_tax * $taxrate2;
                    }
                }
                $total_tax_1 = round($total_tax_1, 2);
                $total_tax_2 = round($total_tax_2, 2);
                $productdata['pricing']['totaltoday'] += $total_tax_1 + $total_tax_2;
                if (0 < $total_tax_1) {
                    $productdata['pricing']['tax1'] = formatCurrency($total_tax_1);
                }
                if (0 < $total_tax_2) {
                    $productdata['pricing']['tax2'] = formatCurrency($total_tax_2);
                }
            }
            $productdata['pricing']['setup'] = formatCurrency($productdata['pricing']['setup']);
            foreach ($productdata['pricing']['recurring'] as $cycle => $recurring) {
                unset($productdata['pricing']['recurring'][$cycle]);
                if (0 < $recurring) {
                    $recurringwithtax = $recurring;
                    if ($CONFIG['TaxEnabled'] && $tax && !$clientsdetails['taxexempt'] && $CONFIG['TaxType'] == "Exclusive") {
                        $rectax = $recurringwithtax * $taxrate;
                        if ($CONFIG['TaxL2Compound']) {
                            $rectax += ($recurringwithtax + $rectax) * $taxrate2;
                        } else {
                            $rectax += $recurringwithtax * $taxrate2;
                        }
                        $recurringwithtax += $rectax;
                    }
                    $productdata['pricing']['recurring'][$_LANG["orderpaymentterm" . $cycle]] = formatCurrency($recurringwithtax);
                    $productdata['pricing']['recurringexcltax'][$_LANG["orderpaymentterm" . $cycle]] = formatCurrency($recurring / $totaltaxrates);
                    continue;
                }
            }
            if (0 < $productdata['pricing']['addons']) {
                $productdata['pricing']['addons'] = formatCurrency($productdata['pricing']['addons']);
            }
            $productdata['pricing']['totaltoday'] = formatCurrency($productdata['pricing']['totaltoday']);
            $productsarray[$key] = $productdata;
        }
    }
    $cartdata['products'] = $productsarray;
    $addonsarray = array();
    if (array_key_exists("addons", $_SESSION['cart']) && is_array($_SESSION['cart']['addons'])) {
        foreach ($_SESSION['cart']['addons'] as $key => $addon) {
            $addonid = $addon['id'];
            $serviceid = $addon['productid'];
            $result = select_query("tbladdons", "name,description,billingcycle,tax", array("id" => $addonid));
            $data = mysql_fetch_array($result);
            $addon_name = $data['name'];
            $addon_description = $data['description'];
            $addon_billingcycle = $data['billingcycle'];
            $addon_tax = $data['tax'];
            if (!$CONFIG['TaxEnabled']) {
                $addon_tax = "";
            }
            $result = select_query("tblpricing", "msetupfee,monthly", array("type" => "addon", "currency" => $currency['id'], "relid" => $addonid));
            $data = mysql_fetch_array($result);
            $addon_setupfee = $data['msetupfee'];
            $addon_recurring = $data['monthly'];
            $hookret = run_hook("OrderAddonPricingOverride", array("key" => $key, "addonid" => $addonid, "serviceid" => $serviceid));
            foreach ($hookret as $hookret2) {
                if (strlen($hookret2)) {
                    if ($hookret2['setup']) {
                        $addon_setupfee = $hookret2['setup'];
                    }
                    if ($hookret2['recurring']) {
                        $addon_recurring = $hookret2['recurring'];
                        continue;
                    }
                    continue;
                }
            }
            $addon_total_today_db = $addon_setupfee + $addon_recurring;
            $addon_recurring_db = $addon_recurring;
            if ($CONFIG['TaxInclusiveDeduct']) {
                $addon_total_today_db = round($addon_total_today_db / $excltaxrate, 2);
                $addon_recurring_db = round($addon_recurring_db / $excltaxrate, 2);
            }
            if ($promotioncode) {
                $onetimediscount = $recurringdiscount = $promoid = 0;
                if ($promocalc = CalcPromoDiscount("A" . $addonid, $addon_billingcycle, $addon_total_today_db, $addon_recurring_db, $addon_setupfee)) {
                    $onetimediscount = $promocalc['onetimediscount'];
                    $recurringdiscount = $promocalc['recurringdiscount'];
                    $addon_total_today_db -= $onetimediscount;
                    $addon_recurring_db -= $recurringdiscount;
                    $cart_discount += $onetimediscount;
                }
            }
            if ($checkout) {
                $addonsetupfee = $addon_total_today_db - $addon_recurring_db;
                $aid = insert_query("tblhostingaddons", array("hostingid" => $serviceid, "addonid" => $addonid, "orderid" => $orderid, "regdate" => "now()", "name" => "", "setupfee" => $addonsetupfee, "recurring" => $addon_recurring_db, "billingcycle" => $addon_billingcycle, "status" => "Pending", "nextduedate" => "now()", "nextinvoicedate" => "now()", "paymentmethod" => $paymentmethod, "tax" => $addon_tax));
                $orderaddonids[] = $aid;
                $adminemailitems .= $_LANG['clientareaaddon'] . (": " . $addon_name . "<br>\r\n") . $_LANG['ordersetupfee'] . ": " . formatCurrency($addonsetupfee) . "<br>\r\n";
                if ($addon_recurring_db) {
                    $adminemailitems .= $_LANG['recurringamount'] . ": " . formatCurrency($addon_recurring_db) . "<br>\r\n";
                }
                $adminemailitems .= $_LANG['orderbillingcycle'] . ": " . $_LANG["orderpaymentterm" . str_replace(array("-", " "), "", strtolower($addon_billingcycle))] . "<br>\r\n<br>\r\n";
            }
            $cart_total += $addon_total_today_db;
            if ($addon_tax && !$clientsdetails['taxexempt']) {
                $cart_tax += $addon_total_today_db;
                if ($CONFIG['TaxType'] == "Exclusive") {
                    if ($CONFIG['TaxL2Compound']) {
                        $addon_recurring_db += $addon_recurring_db * $taxrate;
                        $addon_recurring_db += $addon_recurring_db * $taxrate2;
                    } else {
                        $addon_recurring_db = $addon_recurring_db + $addon_recurring_db * $taxrate + $addon_recurring_db * $taxrate2;
                    }
                }
            }
            $addon_billingcycle = str_replace(array("-", " "), "", strtolower($addon_billingcycle));
            $recurring_cycles_total[$addon_billingcycle] += $addon_recurring_db;
            if ($addon_setupfee == "0" && $addon_recurring == "0") {
                $pricing_text = $_LANG['orderfree'];
            } else {
                $pricing_text = formatCurrency($addon_recurring);
                if ($addon_setupfee != "0.00") {
                    $pricing_text .= " + " . formatCurrency($addon_setupfee) . " " . $_LANG['ordersetupfee'];
                }
            }
            $result = select_query("tblhosting", "tblproducts.name,tblhosting.domain", array("tblhosting.id" => $serviceid), "", "", "", "tblproducts ON tblproducts.id=tblhosting.packageid");
            $data = mysql_fetch_array($result);
            $productname = $data['name'];
            $domainname = $data['domain'];
            $addonsarray[] = array("name" => $addon_name, "productname" => $productname, "domainname" => $domainname, "pricingtext" => $pricing_text);
        }
        $cartdata['addons'] = $addonsarray;
    }
    include ROOTDIR . "/includes/additionaldomainfields.php";
    $totaldomainprice = 0;
    if (array_key_exists("domains", $_SESSION['cart']) && is_array($_SESSION['cart']['domains'])) {
        $result = select_query("tblpricing", "", array("type" => "domainaddons", "currency" => $currency['id'], "relid" => 0));
        $data = mysql_fetch_array($result);
        $domaindnsmanagementprice = $data['msetupfee'];
        $domainemailforwardingprice = $data['qsetupfee'];
        $domainidprotectionprice = $data['ssetupfee'];
        foreach ($_SESSION['cart']['domains'] as $key => $domain) {
            $domaintype = $domain['type'];
            $domainname = $domain['domain'];
            $regperiod = $domain['regperiod'];
            $domainparts = explode(".", $domainname, 2);
            $sld = $domainparts[0];
            $tld = $domainparts[1];
            $temppricelist = getTLDPriceList("." . $tld);
            if (!isset($temppricelist[$regperiod][$domaintype])) {
                $tldyears = array_keys($temppricelist);
                $regperiod = $tldyears[0];
            }
            if (!isset($temppricelist[$regperiod][$domaintype])) {
                exit("Invalid TLD/Registration Period Supplied for Domain Registration");
            }
            if (array_key_exists($domainname, $freedomains)) {
                $tldyears = array_keys($temppricelist);
                $regperiod = $tldyears[0];
                $domainprice = "0.00";
                $renewprice = $freedomains[$domainname] == "once" ? $temppricelist[$regperiod]['renew'] : ($renewprice = "0.00");
            } else {
                $domainprice = $temppricelist[$regperiod][$domaintype];
                $renewprice = $temppricelist[$regperiod]['renew'];
            }
            $before_priceoverride_value = "";
            if ($bundleoverride = bundlesGetProductPriceOverride("domain", $key)) {
                $before_priceoverride_value = $domainprice;
                $domainprice = $renewprice = $bundleoverride;
            }
            $hookret = run_hook("OrderDomainPricingOverride", array("type" => $domaintype, "domain" => $domainname, "regperiod" => $regperiod, "dnsmanagement" => $domain['dnsmanagement'], "emailforwarding" => $domain['emailforwarding'], "idprotection" => $domain['idprotection'], "eppcode" => html_entity_decode($domain['eppcode'])));
            foreach ($hookret as $hookret2) {
                if (strlen($hookret2)) {
                    $before_priceoverride_value = $domainprice;
                    $domainprice = $hookret2;
                    continue;
                }
            }
            if ($domain['dnsmanagement']) {
                $dnsmanagement = true;
                $domainprice += $domaindnsmanagementprice * $regperiod;
                $renewprice += $domaindnsmanagementprice * $regperiod;
                if (strlen($before_priceoverride_value)) {
                    $before_priceoverride_value += $domaindnsmanagementprice * $regperiod;
                }
            } else {
                $dnsmanagement = false;
            }
            if ($domain['emailforwarding']) {
                $emailforwarding = true;
                $domainprice += $domainemailforwardingprice * $regperiod;
                $renewprice += $domainemailforwardingprice * $regperiod;
                if (strlen($before_priceoverride_value)) {
                    $before_priceoverride_value += $domainemailforwardingprice * $regperiod;
                }
            } else {
                $emailforwarding = false;
            }
            if ($domain['idprotection']) {
                $idprotection = true;
                $domainprice += $domainidprotectionprice * $regperiod;
                $renewprice += $domainidprotectionprice * $regperiod;
                if (strlen($before_priceoverride_value)) {
                    $before_priceoverride_value += $domainidprotectionprice * $regperiod;
                }
            } else {
                $idprotection = false;
            }
            if ($CONFIG['TaxInclusiveDeduct']) {
                $domainprice = round($domainprice / $excltaxrate, 2);
                $renewprice = round($renewprice / $excltaxrate, 2);
            }
            $domain_price_db = $domainprice;
            $domain_renew_price_db = $renewprice;
            if ($promotioncode) {
                $onetimediscount = $recurringdiscount = $promoid = 0;
                if ($promocalc = CalcPromoDiscount("D." . $tld, $regperiod . "Years", $domain_price_db, $domain_renew_price_db)) {
                    $onetimediscount = $promocalc['onetimediscount'];
                    $recurringdiscount = $promocalc['recurringdiscount'];
                    $domain_price_db -= $onetimediscount;
                    $domain_renew_price_db -= $recurringdiscount;
                    $cart_discount += $onetimediscount;
                    $promoid = $promo_data['id'];
                }
            }
            if ($regperiod == "1") {
                $domain_billing_cycle = "annually";
            } else {
                if ($regperiod == "2") {
                    $domain_billing_cycle = "biennially";
                } else {
                    if ($regperiod == "3") {
                        $domain_billing_cycle = "triennially";
                    }
                }
            }
            $recurring_cycles_total[$domain_billing_cycle] += $domain_renew_price_db;
            if ($CONFIG['TaxEnabled'] && $CONFIG['TaxDomains'] && $CONFIG['TaxType'] == "Exclusive" && !$clientsdetails['taxexempt']) {
                if ($CONFIG['TaxL2Compound']) {
                    $recurring_cycles_total[$domain_billing_cycle] += $domain_renew_price_db * $taxrate + ($domain_renew_price_db + $domain_renew_price_db * $taxrate) * $taxrate2;
                } else {
                    $recurring_cycles_total[$domain_billing_cycle] += $domain_renew_price_db * $taxrate + $domain_renew_price_db * $taxrate2;
                }
            }
            if ($checkout) {
                $donotrenew = $CONFIG['DomainAutoRenewDefault'] ? "" : "on";
                $domainid = insert_query("tbldomains", array("userid" => $userid, "orderid" => $orderid, "type" => $domaintype, "registrationdate" => "now()", "domain" => $domainname, "firstpaymentamount" => $domain_price_db, "recurringamount" => $domain_renew_price_db, "registrationperiod" => $regperiod, "status" => "Pending", "paymentmethod" => $paymentmethod, "expirydate" => "00000000", "nextduedate" => "now()", "nextinvoicedate" => "now()", "dnsmanagement" => $dnsmanagement, "emailforwarding" => $emailforwarding, "idprotection" => $idprotection, "donotrenew" => $donotrenew, "promoid" => $promoid));
                $orderdomainids[] = $domainid;
                $adminemailitems .= $_LANG['orderdomainregistration'] . ": " . ucfirst($domaintype) . "<br>\r\n" . $_LANG['orderdomain'] . (": " . $domainname . "<br>\r\n") . $_LANG['firstpaymentamount'] . ": " . formatCurrency($domain_price_db) . "<br>\r\n" . $_LANG['recurringamount'] . ": " . formatCurrency($domain_renew_price_db) . "<br>\r\n" . $_LANG['orderregperiod'] . (": " . $regperiod . " ") . $_LANG['orderyears'] . "<br>\r\n";
                if ($dnsmanagement) {
                    $adminemailitems .= " + " . $_LANG['domaindnsmanagement'] . "<br>\r\n";
                }
                if ($emailforwarding) {
                    $adminemailitems .= " + " . $_LANG['domainemailforwarding'] . "<br>\r\n";
                }
                if ($idprotection) {
                    $adminemailitems .= " + " . $_LANG['domainidprotection'] . "<br>\r\n";
                }
                $adminemailitems .= "<br>\r\n";
                if ($domaintype == "register") {
                    unset($tempdomainfields);
                    $tempdomainfields = $additionaldomainfields["." . $tld];
                    if ($tempdomainfields) {
                        foreach ($tempdomainfields as $fieldkey => $value) {
                            $storedvalue = $domain['fields'][$fieldkey];
                            insert_query("tbldomainsadditionalfields", array("domainid" => $domainid, "name" => $value['Name'], "value" => $storedvalue));
                        }
                    }
                }
                if ($domaintype == "transfer" && $domain['eppcode']) {
                    $domaineppcodes[$domainname] = html_entity_decode($domain['eppcode']);
                }
            }
            $pricing_text = "";
            if (strlen($before_priceoverride_value)) {
                $pricing_text .= "<strike>" . formatCurrency($before_priceoverride_value) . "</strike> ";
            }
            $pricing_text .= formatCurrency($domainprice);
            $tempdomains[$key] = array("type" => $domaintype, "domain" => $domainname, "regperiod" => $regperiod, "price" => $pricing_text, "renewprice" => formatCurrency($renewprice), "dnsmanagement" => $dnsmanagement, "emailforwarding" => $emailforwarding, "idprotection" => $idprotection, "eppvalue" => $domain['eppcode']);
            $totaldomainprice += $domain_price_db;
        }
    }
    $cartdata['domains'] = $tempdomains;
    $cart_total += $totaldomainprice;
    if ($CONFIG['TaxDomains']) {
        $cart_tax += $totaldomainprice;
    }
    $orderrenewals = "";
    if (array_key_exists("renewals", $_SESSION['cart']) && is_array($_SESSION['cart']['renewals'])) {
        $result = select_query("tblpricing", "", array("type" => "domainaddons", "currency" => $currency['id'], "relid" => 0));
        $data = mysql_fetch_array($result);
        $domaindnsmanagementprice = $data['msetupfee'];
        $domainemailforwardingprice = $data['qsetupfee'];
        $domainidprotectionprice = $data['ssetupfee'];
        foreach ($_SESSION['cart']['renewals'] as $domainid => $regperiod) {
            $result = select_query("tbldomains", "", array("id" => $domainid));
            $data = mysql_fetch_array($result);
            $domainname = $data['domain'];
            $expirydate = $data['expirydate'];
            if ($expirydate == "0000-00-00") {
                $expirydate = $data['nextduedate'];
            }
            $dnsmanagement = $data['dnsmanagement'];
            $emailforwarding = $data['emailforwarding'];
            $idprotection = $data['idprotection'];
            $domainparts = explode(".", $domainname, 2);
            $sld = $domainparts[0];
            $tld = "." . $domainparts[1];
            $temppricelist = getTLDPriceList($tld, "", true);
            if (!isset($temppricelist[$regperiod]['renew'])) {
                exit("Invalid TLD/Registration Period Supplied for Domain Renewal");
            }
            $renewprice = $temppricelist[$regperiod]['renew'];
            if ($dnsmanagement) {
                $renewprice += $domaindnsmanagementprice * $regperiod;
            }
            if ($emailforwarding) {
                $renewprice += $domainemailforwardingprice * $regperiod;
            }
            if ($idprotection) {
                $renewprice += $domainidprotectionprice * $regperiod;
            }
            if ($CONFIG['TaxInclusiveDeduct']) {
                $renewprice = round($renewprice / $excltaxrate, 2);
            }
            $domain_renew_price_db = $renewprice;
            if ($promotioncode) {
                $onetimediscount = $recurringdiscount = $promoid = 0;
                if ($promocalc = CalcPromoDiscount("D" . $tld, $regperiod . "Years", $domain_renew_price_db, $domain_renew_price_db)) {
                    $onetimediscount = $promocalc['onetimediscount'];
                    $domain_renew_price_db -= $onetimediscount;
                    $cart_discount += $onetimediscount;
                }
            }
            $cart_total += $domain_renew_price_db;
            if ($CONFIG['TaxDomains']) {
                $cart_tax += $domain_renew_price_db;
            }
            if ($checkout) {
                $domain_renew_price_db = format_as_currency($domain_renew_price_db);
                $orderrenewalids[] = $domainid;
                $orderrenewals .= "" . $domainid . "=" . $regperiod . ",";
                $adminemailitems .= $_LANG['domainrenewal'] . (": " . $domainname . " - " . $regperiod . " ") . $_LANG['orderyears'] . "<br>\r\n";
                $domaindesc = $_LANG['domainrenewal'] . (" - " . $domainname . " - " . $regperiod . " ") . $_LANG['orderyears'] . " (" . fromMySQLDate($expirydate) . " - " . fromMySQLDate(getInvoicePayUntilDate($expirydate, $regperiod)) . ")";
                if ($dnsmanagement) {
                    $adminemailitems .= " + " . $_LANG['domaindnsmanagement'] . "<br>\r\n";
                    $domaindesc .= "\r\n + " . $_LANG['domaindnsmanagement'];
                }
                if ($emailforwarding) {
                    $adminemailitems .= " + " . $_LANG['domainemailforwarding'] . "<br>\r\n";
                    $domaindesc .= "\r\n + " . $_LANG['domainemailforwarding'];
                }
                if ($idprotection) {
                    $adminemailitems .= " + " . $_LANG['domainidprotection'] . "<br>\r\n";
                    $domaindesc .= "\r\n + " . $_LANG['domainidprotection'];
                }
                $adminemailitems .= "<br>\r\n";
                $tax = $CONFIG['TaxDomains'] ? "1" : "0";
                update_query("tbldomains", array("registrationperiod" => $regperiod, "recurringamount" => $domain_renew_price_db), array("id" => $domainid));
                insert_query("tblinvoiceitems", array("userid" => $userid, "type" => "Domain", "relid" => $domainid, "description" => $domaindesc, "amount" => $domain_renew_price_db, "taxed" => $tax, "duedate" => "now()", "paymentmethod" => $paymentmethod));
                $result = select_query("tblinvoiceitems", "tblinvoiceitems.id,tblinvoiceitems.invoiceid", array("type" => "Domain", "relid" => $domainid, "status" => "Unpaid", "tblinvoices.userid" => $_SESSION['uid']), "", "", "", "tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid");
                while ($data = mysql_fetch_array($result)) {
                    $itemid = $data['id'];
                    $invoiceid = $data['invoiceid'];
                    $result2 = select_query("tblinvoiceitems", "COUNT(*)", array("invoiceid" => $invoiceid));
                    $data = mysql_fetch_array($result2);
                    $itemcount = $data[0];
                    if ($itemcount == 1) {
                        update_query("tblinvoices", array("status" => "Cancelled"), array("id" => $invoiceid));
                        logActivity("Cancelled Previous Domain Renewal Invoice - Invoice ID: " . $invoiceid . " - Domain: " . $domainname);
                    }
                    delete_query("tblinvoiceitems", array("id" => $itemid));
                    updateInvoiceTotal($invoiceid);
                    logActivity("Removed Previous Domain Renewal Line Item - Invoice ID: " . $invoiceid . " - Domain: " . $domainname);
                }
            }
            $cartdata['renewals'][$domainid] = array("domain" => $domainname, "regperiod" => $regperiod, "price" => formatCurrency($renewprice), "dnsmanagement" => $dnsmanagement, "emailforwarding" => $emailforwarding, "idprotection" => $idprotection);
        }
    }
    $cart_adjustments = 0;
    $adjustments = run_hook("CartTotalAdjustment", $_SESSION['cart']);
    foreach ($adjustments as $k => $adjvals) {
        if ($checkout) {
            insert_query("tblinvoiceitems", array("userid" => $userid, "type" => "", "relid" => "", "description" => $adjvals['description'], "amount" => $adjvals['amount'], "taxed" => $adjvals['taxed'], "duedate" => "now()", "paymentmethod" => $paymentmethod));
        }
        $adjustments[$k]['amount'] = formatCurrency($adjvals['amount']);
        $cart_adjustments += $adjvals['amount'];
        if ($adjvals['taxed']) {
            $cart_tax += $adjvals['amount'];
            continue;
        }
    }
    if ($CONFIG['TaxEnabled'] && !$clientsdetails['taxexempt']) {
        if ($CONFIG['TaxType'] == "Inclusive") {
            $totaltaxrates = 1 + ($taxrate + $taxrate2);
            $total_without_tax = $cart_tax / $totaltaxrates;
            $total_tax_1 = $total_without_tax * $taxrate;
            $total_tax_2 = $total_without_tax * $taxrate2;
        } else {
            $total_tax_1 = $cart_tax * $taxrate;
            if ($CONFIG['TaxL2Compound']) {
                $total_tax_2 = ($cart_tax + $total_tax_1) * $taxrate2;
            } else {
                $total_tax_2 = $cart_tax * $taxrate2;
            }
        }
        $total_tax_1 = round($total_tax_1, 2);
        $total_tax_2 = round($total_tax_2, 2);
        if ($CONFIG['TaxType'] == "Inclusive") {
            $cart_total -= $total_tax_1 + $total_tax_2;
        }
    } else {
        $total_tax_1 = $total_tax_2 = 0;
    }
    $cart_subtotal = $cart_total + $cart_discount;
    $cart_total += $total_tax_1 + $total_tax_2 + $cart_adjustments;
    $cart_subtotal = format_as_currency($cart_subtotal);
    $cart_discount = format_as_currency($cart_discount);
    $cart_adjustments = format_as_currency($cart_adjustments);
    $total_tax_1 = format_as_currency($total_tax_1);
    $total_tax_2 = format_as_currency($total_tax_2);
    $cart_total = format_as_currency($cart_total);
    if ($checkout) {
        $adminemailitems .= $_LANG['ordertotalduetoday'] . ": " . formatCurrency($cart_total);
        if ($promotioncode && $promo_data['promoapplied']) {
            update_query("tblpromotions", array("uses" => "+1"), array("code" => $promotioncode));
            $promo_recurring = $promo_data['recurring'] ? "Recurring" : "One Time";
            update_query("tblorders", array("promocode" => $promo_data['code'], "promotype" => $promo_recurring . " " . $promo_data['type'], "promovalue" => $promo_data['value']), array("id" => $orderid));
        }
        if ($_SESSION['cart']['ns1'] && $_SESSION['cart']['ns1']) {
            $ordernameservers = $_SESSION['cart']['ns1'] . "," . $_SESSION['cart']['ns2'];
            if ($_SESSION['cart']['ns3']) {
                $ordernameservers .= "," . $_SESSION['cart']['ns3'];
            }
            if ($_SESSION['cart']['ns4']) {
                $ordernameservers .= "," . $_SESSION['cart']['ns4'];
            }
            if ($_SESSION['cart']['ns5']) {
                $ordernameservers .= "," . $_SESSION['cart']['ns5'];
            }
        }
        $domaineppcodes = count($domaineppcodes) ? serialize($domaineppcodes) : "";
        $orderdata = array();
        if (is_array($_SESSION['cart']['bundle'])) {
            foreach ($_SESSION['cart']['bundle'] as $bvals) {
                $orderdata['bundleids'][] = $bvals['bid'];
            }
        }
        update_query("tblorders", array("amount" => $cart_total, "nameservers" => $ordernameservers, "transfersecret" => $domaineppcodes, "renewals" => substr($orderrenewals, 0, 0 - 1), "orderdata" => serialize($orderdata)), array("id" => $orderid));
        $invoiceid = 0;
        if (!$_SESSION['cart']['geninvoicedisabled']) {
            if (!$userid) {
                exit("An Error Occurred");
            }
            $invoiceid = createInvoices($userid, true, "", array("products" => $orderproductids, "addons" => $orderaddonids, "domains" => $orderdomainids));
            if ($CONFIG['OrderDaysGrace']) {
                $new_time = mktime(0, 0, 0, date("m"), date("d") + $CONFIG['OrderDaysGrace'], date("Y"));
                $duedate = date("Y-m-d", $new_time);
                update_query("tblinvoices", array("duedate" => $duedate), array("id" => $invoiceid));
            }
            if (!$CONFIG['NoInvoiceEmailOnOrder']) {
                sendMessage("Invoice Created", $invoiceid);
            }
        }
        if ($invoiceid) {
            update_query("tblorders", array("invoiceid" => $invoiceid), array("id" => $orderid));
            $result = select_query("tblinvoices", "status", array("id" => $invoiceid));
            $data = mysql_fetch_array($result);
            $status = $data['status'];
            if ($status == "Paid") {
                $invoiceid = "";
            }
        }
        if (!$_SESSION['adminid']) {
            if (isset($_COOKIE['WHMCSAffiliateID'])) {
                $result = select_query("tblaffiliates", "clientid", array("id" => (int) $_COOKIE['WHMCSAffiliateID']));
                $data = mysql_fetch_array($result);
                $clientid = $data['clientid'];
                if ($clientid && $_SESSION['uid'] != $clientid) {
                    foreach ($orderproductids as $orderproductid) {
                        insert_query("tblaffiliatesaccounts", array("affiliateid" => (int) $_COOKIE['WHMCSAffiliateID'], "relid" => $orderproductid));
                    }
                }
            }
            if (isset($_COOKIE['WHMCSLinkID'])) {
                update_query("tbllinks", array("conversions" => "+1"), array("id" => $_COOKIE['WHMCSLinkID']));
            }
        }
        $result = select_query("tblclients", "firstname, lastname, companyname, email, address1, address2, city, state, postcode, country, phonenumber, ip, host", array("id" => $userid));
        $data = mysql_fetch_array($result);
        list($firstname, $lastname, $companyname, $email, $address1, $address2, $city, $state, $postcode, $country, $phonenumber, $ip, $host) = $data;
        $customfields = getCustomFields("client", "", $userid, "", true);
        $clientcustomfields = "";
        foreach ($customfields as $customfield) {
            $clientcustomfields .= "" . $customfield['name'] . ": " . $customfield['value'] . "<br />\r\n";
        }
        $result = select_query("tblpaymentgateways", "value", array("gateway" => $paymentmethod, "setting" => "name"));
        $data = mysql_fetch_array($result);
        $nicegatewayname = $data['value'];
        sendAdminMessage("New Order Notification", array("order_id" => $orderid, "order_number" => $order_number, "order_date" => fromMySQLDate(date("Y-m-d H:i:s"), true), "invoice_id" => $invoiceid, "order_payment_method" => $nicegatewayname, "order_total" => formatCurrency($cart_total), "client_id" => $userid, "client_first_name" => $firstname, "client_last_name" => $lastname, "client_email" => $email, "client_company_name" => $companyname, "client_address1" => $address1, "client_address2" => $address2, "client_city" => $city, "client_state" => $state, "client_postcode" => $postcode, "client_country" => $country, "client_phonenumber" => $phonenumber, "client_customfields" => $clientcustomfields, "order_items" => $adminemailitems, "order_notes" => nl2br($ordernotes), "client_ip" => $ip, "client_hostname" => $host), "account");
        if (!$_SESSION['cart']['orderconfdisabled']) {
            sendMessage("Order Confirmation", $userid, array("order_id" => $orderid, "order_number" => $order_number, "order_details" => $adminemailitems));
        }
        $_SESSION['cart'] = array();
        $_SESSION['orderdetails'] = array("OrderID" => $orderid, "OrderNumber" => $order_number, "ServiceIDs" => $orderproductids, "DomainIDs" => $orderdomainids, "AddonIDs" => $orderaddonids, "RenewalIDs" => $orderrenewalids, "PaymentMethod" => $paymentmethod, "InvoiceID" => $invoiceid, "TotalDue" => $cart_total, "Products" => $orderproductids, "Domains" => $orderdomainids, "Addons" => $orderaddonids, "Renewals" => $orderrenewalids);
        run_hook("AfterShoppingCartCheckout", $_SESSION['orderdetails']);
    }
    $total_recurringmonthly = $recurring_cycles_total['monthly'] <= 0 ? "" : formatCurrency($recurring_cycles_total['monthly']);
    $total_recurringquarterly = $recurring_cycles_total['quarterly'] <= 0 ? "" : formatCurrency($recurring_cycles_total['quarterly']);
    $total_recurringsemiannually = $recurring_cycles_total['semiannually'] <= 0 ? "" : formatCurrency($recurring_cycles_total['semiannually']);
    $total_recurringannually = $recurring_cycles_total['annually'] <= 0 ? "" : formatCurrency($recurring_cycles_total['annually']);
    $total_recurringbiennially = $recurring_cycles_total['biennially'] <= 0 ? "" : formatCurrency($recurring_cycles_total['biennially']);
    $total_recurringtriennially = $recurring_cycles_total['triennially'] <= 0 ? "" : formatCurrency($recurring_cycles_total['triennially']);
    $cartdata['bundlewarnings'] = $bundlewarnings;
    $cartdata['rawdiscount'] = $cart_discount;
    $cartdata['subtotal'] = formatCurrency($cart_subtotal);
    $cartdata['discount'] = formatCurrency($cart_discount);
    $cartdata['promotype'] = $promo_data['type'];
    $cartdata['promovalue'] = $promo_data['type'] == "Fixed Amount" || $promo_data['type'] == "Price Override" ? formatCurrency($promo_data['value']) : round($promo_data['value'], 2);
    $cartdata['promorecurring'] = $promo_data['recurring'] ? $_LANG['recurring'] : $_LANG['orderpaymenttermonetime'];
    $cartdata['taxrate'] = $rawtaxrate;
    $cartdata['taxrate2'] = $rawtaxrate2;
    $cartdata['taxname'] = $taxname;
    $cartdata['taxname2'] = $taxname2;
    $cartdata['taxtotal'] = formatCurrency($total_tax_1);
    $cartdata['taxtotal2'] = formatCurrency($total_tax_2);
    $cartdata['adjustments'] = $adjustments;
    $cartdata['adjustmentstotal'] = formatCurrency($cart_adjustments);
    $cartdata['rawtotal'] = $cart_total;
    $cartdata['total'] = formatCurrency($cart_total);
    $cartdata['totalrecurringmonthly'] = $total_recurringmonthly;
    $cartdata['totalrecurringquarterly'] = $total_recurringquarterly;
    $cartdata['totalrecurringsemiannually'] = $total_recurringsemiannually;
    $cartdata['totalrecurringannually'] = $total_recurringannually;
    $cartdata['totalrecurringbiennially'] = $total_recurringbiennially;
    $cartdata['totalrecurringtriennially'] = $total_recurringtriennially;
    return $cartdata;
}
예제 #15
0
     $datecreated = getTodaysDate();
     $validuntil = fromMySQLDate(date("Y-m-d", mktime(0, 0, 0, date("m") + 1, date("d"), date("Y"))));
     $clienttype = "existing";
 }
 if ($userid) {
     $clienttype = "existing";
     $clientsdetails = getClientsDetails($userid);
     $fortax_state = $clientsdetails['state'];
     $fortax_country = $clientsdetails['country'];
 } else {
     $clienttype = "new";
     $fortax_state = $state;
     $fortax_country = $country;
 }
 $taxlevel1 = getTaxRate(1, $fortax_state, $fortax_country);
 $taxlevel2 = getTaxRate(2, $fortax_state, $fortax_country);
 if ($duplicated) {
     infoBox("Quote Duplicated", "The quote was duplicated successfully - new quote #" . $id);
 }
 if ($sent) {
     infoBox("Quote Delivered", "The quote was successfully sent via email to the client");
 }
 echo $infobox;
 if (!$currency['id']) {
     $currency['id'] = 1;
 }
 $jquerycode = "\$(\"#clienttypeexisting\").click(function () {\n    \$(\"#newclientform\").slideUp(\"slow\");\n});\n\$(\"#clienttypenew\").click(function () {\n    \$(\"#newclientform\").slideDown(\"slow\");\n});\n\$(\"#userdropdown\").change(function () {\n    \$(\"#clienttypeexisting\").click();\n});\n\$(\"#addproduct\").change(function () {\n    if (this.options[this.selectedIndex].value) {\n        \$.post(\"quotes.php\", { action: \"getdesc\", id: this.options[this.selectedIndex].value },\n        function(data){\n            \$(\"#add_desc\").val(data);\n        });\n        \$.post(\"quotes.php\", { action: \"getprice\", currency: " . $currency['id'] . ", id: this.options[this.selectedIndex].value },\n        function(data){\n            \$(\"#add_up\").val(data);\n        });\n    }\n});\n\$(\"textarea.expanding\").autogrow({\n    minHeight: 16,\n    lineHeight: 14\n});";
 $jscode .= "function selectSingle() {\n    \$(\"#singleoptions\").slideToggle();\n    \$(\"#depositoptions\").slideToggle();\n}\nfunction selectDeposit() {\n    \$(\"#singleoptions\").slideToggle();\n    \$(\"#depositoptions\").slideToggle();\n}";
 foreach ($addons_html as $addon_html) {
     echo "<div style=\"margin-bottom:15px;\">" . $addon_html . "</div>";
 }
예제 #16
0
<?php

//stop the direct browsing to this file - let index.php handle which files get displayed
checkLogin();
#table
jsBegin();
jsFormValidationBegin("frmpost");
jsValidateRequired("tax_description", $LANG['tax_description']);
jsValidateifNum("tax_percentage", $LANG['tax_percentage']);
jsFormValidationEnd();
jsEnd();
#get the invoice id
$tax_rate_id = $_GET['id'];
$tax = getTaxRate($tax_rate_id);
$types = getTaxTypes();
$smarty->assign("tax", $tax);
$smarty->assign("types", $types);
$smarty->assign('pageActive', 'tax_rate');
$subPageActive = $_GET['action'] == "view" ? "tax_rates_view" : "tax_rates_edit";
$smarty->assign('subPageActive', $subPageActive);
$smarty->assign('active_tab', '#setting');
예제 #17
0
function invoice_item_tax($invoice_item_id, $line_item_tax_id, $unit_price, $quantity, $action = '', $domain_id = '')
{
    global $logger;
    $domain_id = domain_id::get($domain_id);
    //if editing invoice delete all tax info then insert first then do insert again
    //probably can be done without delete - someone to look into this if required - TODO
    if ($action == "update") {
        $sql_delete = "DELETE from\n\t\t\t\t\t\t\t" . TB_PREFIX . "invoice_item_tax\n\t\t\t\t\t   WHERE\n\t\t\t\t\t\t\tinvoice_item_id = :invoice_item_id";
        $logger->log("Invoice item: " . $invoice_item_id . " tax lines deleted", Zend_Log::INFO);
        dbQuery($sql_delete, ':invoice_item_id', $invoice_item_id);
    }
    foreach ($line_item_tax_id as $key => $value) {
        if ($value !== "") {
            $tax = getTaxRate($value, $domain_id);
            $logger->log("ITEM :: Key: " . $key . " Value: " . $value, Zend_Log::INFO);
            $logger->log('ITEM :: tax rate: ' . $tax['tax_percentage'], Zend_Log::INFO);
            $logger->log('ITEM :: domain_id: ' . $domain_id, Zend_Log::INFO);
            $tax_amount = lineItemTaxCalc($tax, $unit_price, $quantity);
            //get Total tax for line item (unused here)
            // $tax_total = $tax_total + $tax_amount;
            $logger->log('ITEM :: Qty: ' . $quantity . ' Unit price: ' . $unit_price, Zend_Log::INFO);
            $logger->log('ITEM :: Tax rate: ' . $tax[tax_percentage] . ' Tax type: ' . $tax['type'] . ' Tax $: ' . $tax_amount, Zend_Log::INFO);
            $sql = "INSERT \n\t\t\t\t\t\tINTO \n\t\t\t\t\t" . TB_PREFIX . "invoice_item_tax \n\t\t\t\t\t(\n\t\t\t\t\t\tinvoice_item_id, \n\t\t\t\t\t\ttax_id, \n\t\t\t\t\t\ttax_type, \n\t\t\t\t\t\ttax_rate, \n\t\t\t\t\t\ttax_amount\n\t\t\t\t\t) \n\t\t\t\t\tVALUES \n\t\t\t\t\t(\n\t\t\t\t\t\t:invoice_item_id, \n\t\t\t\t\t\t:tax_id,\n\t\t\t\t\t\t:tax_type,\n\t\t\t\t\t\t:tax_rate,\n\t\t\t\t\t\t:tax_amount\n\t\t\t\t\t)";
            dbQuery($sql, ':invoice_item_id', $invoice_item_id, ':tax_id', $tax['tax_id'], ':tax_type', $tax['type'], ':tax_rate', $tax['tax_percentage'], ':tax_amount', $tax_amount);
        }
    }
    //TODO fix this
    return true;
}
예제 #18
0
}
$result = select_query("tblclients", "id", array("id" => $_POST['userid']));
$data = mysql_fetch_array($result);
if (!$data['id']) {
    $apiresults = array("result" => "error", "message" => "Client ID Not Found");
    return null;
}
$taxrate = $_POST['taxrate'];
$taxrate2 = $_POST['taxrate2'];
if ($CONFIG['TaxEnabled'] == "on" && !$taxrate && !$taxrate2) {
    $clientsdetails = getClientsDetails($_POST['userid']);
    if (!$clientsdetails['taxexempt']) {
        $state = $clientsdetails['state'];
        $country = $clientsdetails['country'];
        $taxdata = getTaxRate(1, $state, $country);
        $taxdata2 = getTaxRate(2, $state, $country);
        $taxrate = $taxdata['rate'];
        $taxrate2 = $taxdata2['rate'];
    }
}
$invoiceid = insert_query("tblinvoices", array("date" => $_POST['date'], "duedate" => $_POST['duedate'], "userid" => $_POST['userid'], "status" => "Unpaid", "taxrate" => $taxrate, "taxrate2" => $taxrate2, "paymentmethod" => $_POST['paymentmethod'], "notes" => $_POST['notes']));
foreach ($_POST as $k => $v) {
    if (substr($k, 0, 10) == "itemamount") {
        $counter = substr($k, 10);
        $description = $_POST["itemdescription" . $counter];
        $amount = $_POST["itemamount" . $counter];
        $taxed = $_POST["itemtaxed" . $counter];
        if ($description) {
            insert_query("tblinvoiceitems", array("invoiceid" => $invoiceid, "userid" => $userid, "description" => $description, "amount" => $amount, "taxed" => $taxed));
            continue;
        }
예제 #19
0
    $set .= "taxincluded='f' ";
    $sql = "update customer " . $set;
    $sql .= "where id=" . $rs[0]["id"];
    $rc = query("erp", $sql, "insKdData");
    if ($rc === -99) {
        //$sql="delete from customer where id=".$rs[0]["id"];
        //$rc=query("shop",$sql,"insNewKd");
        return false;
    } else {
        return $rs[0]["id"];
    }
}
$LAND = array("Germany" => "D", "Austria" => "A", "Switzerland" => "CH");
$skosten = array("Versand" => "ot_shipping", "NachName" => "ot_cod_fee", "Paypal" => "ot_cod_fee", "Minder" => "ot_loworderfee");
$inclTax = checkTaxIncl();
$TaxFactor = $inclTax ? getTaxRate() : 1;
$bestellungen = getBestellung();
$ok = count($bestellungen);
$gesKd = 0;
$neuKd = 0;
if ($ok) {
    echo "Es liegen {$ok} Bestellungen vor. <br>";
    chkKunden();
    echo $gesKd . " Kunde(n), davon " . $neuKd . " neue(r) Kunde(n).<br>";
    foreach ($bestellungen as $bestellung) {
        insAuftrag($bestellung);
    }
} else {
    echo "Es liegen keine Bestellungen vor!<br>";
}
?>
예제 #20
0
 protected function generateInvoiceData($data, array $client)
 {
     global $_LANG;
     if (!isset($_LANG['onappusersstatvirtualmachines'])) {
         require_once dirname(__DIR__) . '/onappusers.php';
     }
     loadLang($client['language']);
     //check if invoice should be generated
     $fromTime = strtotime($this->fromDate);
     $tillTime = strtotime($this->tillDate);
     if ($fromTime >= $tillTime) {
         return false;
     }
     if ($client['dueDate'] == 1) {
         $dueDate = $this->dueDate;
     } else {
         $dueDate = date('Ymd', time() + $GLOBALS['CONFIG']['CreateInvoiceDaysBefore'] * 86400);
     }
     //check if the item should be taxed
     $taxed = empty($client['taxexempt']) && (int) $client['tax'];
     if ($taxed) {
         $taxrate = getTaxRate(1, $client['state'], $client['country']);
         $taxrate = $taxrate['rate'];
     } else {
         $taxrate = '';
     }
     $timeZone = ' UTC' . ($this->timeZoneOffset >= 0 ? '+' : '-') . $this->timeZoneOffset / 3600;
     $this->fromDate = date($_LANG['onappusersstatdateformat'], $fromTime);
     $this->tillDate = date($_LANG['onappusersstatdateformat'], $tillTime);
     $invoiceDescription = array($_LANG['onappusersstatproduct'] . $client['packagename'], $_LANG['onappusersstatperiod'] . $this->fromDate . ' - ' . $this->tillDate . $timeZone);
     $invoiceDescription = implode(PHP_EOL, $invoiceDescription);
     $return = array('userid' => $client['client_id'], 'date' => $this->dueDate, 'duedate' => $dueDate, 'paymentmethod' => $client['paymentmethod'], 'taxrate' => $taxrate, 'sendinvoice' => true, 'itemdescription1' => $invoiceDescription, 'itemamount1' => 0, 'itemtaxed1' => $taxed);
     unset($data->total_cost);
     $i = 1;
     foreach ($data as $key => $value) {
         if ($value > 0) {
             $tmp = array('itemdescription' . ++$i => $_LANG['onappusers_invoice_' . $key], 'itemamount' . $i => $value, 'itemtaxed' . $i => $taxed);
             $return = array_merge($return, $tmp);
         }
     }
     if ($this->printEnabled) {
         print_r($return);
     }
     return $return;
 }