Exemple #1
2
/**
 * [addOrder функция добавления заказа]
 * @param array $arParams
 * @return array or false
 */
function addOrder($arParams)
{
    if (!CModule::IncludeModule('sale')) {
        return false;
    }
    global $USER;
    global $DB;
    $addCommentsOrder = false;
    $commentForManager = "";
    updateBasketPreOrder();
    // обновляем корзину
    $arBasketItems = array();
    $dbBasketItems = CSaleBasket::GetList(array("NAME" => "ASC", "ID" => "ASC"), array("FUSER_ID" => CSaleBasket::GetBasketUserID(), "LID" => SITE_ID, "ORDER_ID" => "NULL"), false, false, array("ID", "CALLBACK_FUNC", "MODULE", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "WEIGHT", "NAME", "CURRENCY", "CATALOG_XML_ID", "VAT_RATE", "NOTES", "DISCOUNT_PRICE", "PRODUCT_PROVIDER_CLASS", "DIMENSIONS", "TYPE", "SET_PARENT_ID", "DETAIL_PAGE_URL"));
    while ($arItem = $dbBasketItems->Fetch()) {
        $arPropItem = getItemCart($arItem["PRODUCT_ID"]);
        $db_res = CSaleBasket::GetPropsList(array("SORT" => "ASC", "NAME" => "ASC"), array("BASKET_ID" => $arItem['ID']), false, array());
        while ($ar_res = $db_res->Fetch()) {
            if ($ar_res["CODE"] == "DEPOSIT" && $ar_res["VALUE"] == "N") {
                $addCommentsOrder = true;
            }
        }
        $arBasketItems[] = $arItem;
        $arItem["ARTIKUL"] = $arPropItem["PROPERTY_ARTIKUL_VALUE"];
        $strOrderList .= '<a href="http://' . $_SERVER["HTTP_HOST"] . $arItem["DETAIL_PAGE_URL"] . '">' . $arItem["ARTIKUL"] . '</a> ' . $arItem["NAME"] . ' - ' . $arItem["QUANTITY"] * 1 . ' шт. x ' . SaleFormatCurrency($arItem["PRICE"], $arItem["CURRENCY"]);
        $strOrderList .= "<br />";
        $allDiscountItems += $arItem["DISCOUNT_PRICE"];
    }
    if (!$arBasketItems) {
        return false;
    }
    $arOrderDat = CSaleOrder::DoCalculateOrder(SITE_ID, $USER->GetID(), $arBasketItems, 1, $arUserResult["ORDER_PROP"], $arParams["DELIVERY_ID"], $arParams["PAY_SYSTEM_ID"], array(), $arErrors, $arWarnings);
    $arOrderDat["ORDER_PROP"][20] = $arParams["ORDER_PROP_20"];
    $arOrderDat["ORDER_PROP"][7] = $arParams["ORDER_PROP_7"];
    $arOrderDat["ORDER_PROP"][3] = $arParams["ORDER_PROP_3"];
    //echo "<pre>";print_r($PRICE);echo "</pre>";die();
    //echo "<pre>";print_r($arOrderDat);echo "</pre>";die();
    //echo "<pre>";print_r($arParams);echo "</pre>";die();
    $arFields = array("LID" => SITE_ID, "PERSON_TYPE_ID" => 1, "PAYED" => "N", "CANCELED" => "N", "STATUS_ID" => "N", "PRICE" => $arOrderDat["ORDER_PRICE"], "CURRENCY" => $arOrderDat["CURRENCY"], "USER_ID" => IntVal($USER->GetID()), "PAY_SYSTEM_ID" => $arOrderDat["PAY_SYSTEM_ID"], "PRICE_DELIVERY" => $arOrderDat["PRICE_DELIVERY"], "DELIVERY_ID" => $arOrderDat["DELIVERY_ID"], "DISCOUNT_VALUE" => $arOrderDat["DISCOUNT_VALUE"], "TAX_VALUE" => $arOrderDat["TAX_VALUE"], "DELIVERY_LOCATION" => $arOrderDat["DELIVERY_LOCATION"], "USER_DESCRIPTION" => $arParams["ORDER_DESCRIPTION"], "COMMENTS" => $commentForManager);
    $ORDER_ID = (int) CSaleOrder::DoSaveOrder($arOrderDat, $arFields, 0, $arResult["ERROR"]);
    if ($ORDER_ID > 0) {
        $arOrder = getOrder($ORDER_ID);
        // для менеджера
        if ($addCommentsOrder === true && $arParams["PAY_SYSTEM_ID"] == 10) {
            // сообщение для менеджера
            $commentForManager .= 'Выбран способ оплаты PayKeeper, но в заказе есть товары "По запросу".';
            $commentForManager .= "\n";
            $commentForManager .= "Ссылка для оплаты: http://" . $_SERVER["HTTP_HOST"] . "/personal/order/payment/?ORDER_ID=" . $ORDER_ID;
            $arFields = array("COMMENTS" => $commentForManager);
            CSaleOrder::Update($ORDER_ID, $arFields);
        }
        // отправляем письмо
        $arFieldsEvent = array("ORDER_ID" => getNumberOrder($ORDER_ID), "ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))), "ORDER_USER" => $USER->GetFormattedName(false), "PRICE" => SaleFormatCurrency($arOrderDat["ORDER_PRICE"], $arOrderDat["CURRENCY"]), "BCC" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "EMAIL" => strlen($arUserResult["USER_EMAIL"]) > 0 ? $arUserResult["USER_EMAIL"] : $USER->GetEmail(), "ORDER_LIST" => $strOrderList, "SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "DISCOUNT" => $allDiscountItems . " руб.", "DELIVERY_PRICE" => "", "DELIVERY_TYPE" => getDeliveryName($arOrderDat["DELIVERY_ID"]), "ADDRESS" => strlen($arParams["ORDER_PROP_7"]) > 0 ? $arParams["ORDER_PROP_7"] : "Адрес не указан", "COMMENT" => strlen($arParams["ORDER_DESCRIPTION"]) > 0 ? $arParams["ORDER_DESCRIPTION"] : "Нет комментария");
        //Формируем писмо для отправки менеджеру
        switch ($arParams["PAY_SYSTEM_ID"]) {
            case 10:
                $price_method = 'Оплата банковской картой VISA, MASTERCARD, MAESTRO';
                break;
            case 8:
                $price_method = 'Безналичный расчет';
                break;
            case 1:
                $price_method = 'Наличными при получении';
                break;
        }
        $rsGroups = CGroup::GetList($by = "c_sort", $order = "asc", array("ID" => implode('|', $USER->GetUserGroupArray())));
        $groups = array();
        if (intval($rsGroups->SelectedRowsCount()) > 0) {
            while ($arGroups = $rsGroups->Fetch()) {
                if ((int) $arGroups['ID'] != 2 && (int) $arGroups['ID'] != 3 && (int) $arGroups['ID'] != 4) {
                    $groups[] = $arGroups['NAME'];
                }
            }
        }
        $arFieldsManager = array('NUMBER' => getNumberOrder($ORDER_ID), 'DATE' => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))), 'SELLER_TYPE' => implode(',', $groups), 'FIO' => $USER->GetFormattedName(false), 'PHONE' => strlen($arParams["ORDER_PROP_3"]) > 0 ? $arParams["ORDER_PROP_3"] : "Телефон не указан", 'EMAIL' => $USER->GetEmail(), 'ADRESS' => strlen($arParams["ORDER_PROP_7"]) > 0 ? $arParams["ORDER_PROP_7"] : "Адрес не указан", 'DOSTAVKA' => getDeliveryName($arOrderDat["DELIVERY_ID"]), 'PRICE_METHOD' => $price_method, 'ORDERS' => $strOrderList . '<br />Итого: ' . $arOrderDat["ORDER_PRICE"], 'DISCOUNT' => $allDiscountItems . " руб.", 'COMMENT' => strlen($arParams["ORDER_DESCRIPTION"]) > 0 ? $arParams["ORDER_DESCRIPTION"] : "Нет комментария");
        $eventName = "SALE_NEW_ORDER";
        $eventNameManager = "FORM_FILLING_NEW_ORDER";
        $bSend = true;
        foreach (GetModuleEvents("sale", "OnOrderNewSendEmail", true) as $arEvent) {
            if (ExecuteModuleEventEx($arEvent, array($arResult["ORDER_ID"], &$eventName, &$arFields)) === false) {
                $bSend = false;
            }
        }
        if ($bSend) {
            $event = new CEvent();
            $event->Send($eventName, SITE_ID, $arFieldsEvent, "N");
            $event->Send($eventNameManager, SITE_ID, $arFieldsManager, "N");
        }
        return $ORDER_ID;
    }
    return false;
}
Exemple #2
0
function getOrderOp()
{
    if (getOrder() == 'asc') {
        return 'desc';
    } else {
        return 'asc';
    }
}
Exemple #3
0
        getVcode();
        break;
    case 'upload':
        uploadFile($uri);
        break;
    case 'files':
        files();
        break;
    case 'dxyzm':
        dxyzm();
        break;
    case 'cleartmpuserphone':
        clearTmpUserPhone();
        break;
    case 'getOrder':
        getOrder();
        break;
    case 'orderNotify':
        orderNotify();
        break;
    default:
        ABase::toJson(1, 'Error code 404');
}
function getCountys()
{
    $pid = isset($_GET['pid']) ? (int) $_GET['pid'] : 0;
    $ajax = isset($_GET['ajax']) ? (int) $_GET['ajax'] : 0;
    $countys = Countys::getCountys($pid);
    if ($ajax) {
        ABase::toJson(0, 'OK', $countys);
    }
 * the buyer gets redirected here post approval / cancellation of
 * payment.
 */
require_once __DIR__ . '/../bootstrap.php';
session_start();
if (!isSignedIn()) {
    header('Location: ../user/sign_in.php');
    exit;
}
if (isset($_GET['success'])) {
    // We were redirected here from PayPal after the buyer approved/cancelled
    // the payment
    if ($_GET['success'] == 'true' && isset($_GET['PayerID']) && isset($_GET['orderId'])) {
        $orderId = $_GET['orderId'];
        try {
            $order = getOrder($orderId);
            $payment = executePayment($order['payment_id'], $_GET['PayerID']);
            updateOrder($orderId, $payment->getState());
            $messageType = "success";
            $message = "Your payment was successful. Your order id is {$orderId}.";
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            $message = parseApiError($ex->getData());
            $messageType = "error";
        } catch (Exception $ex) {
            $message = $ex->getMessage();
            $messageType = "error";
        }
    } else {
        $messageType = "error";
        $message = "Your payment was cancelled.";
    }
Exemple #5
0
function either($a, $b)  {  if ($a != NULL) return $a; return $b;}

$TMG_PK_SERVER_ADDR = CSalePaySystemAction::GetParamValue("TMG_PK_SERVER_ADDR");

$user_id = (int)$GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["USER_ID"];
$sum = (float)either(
    CSalePaySystemAction::GetParamValue("SHOULD_PAY"), 
    $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SHOULD_PAY"]);
$orderid = (int)either(
    CSalePaySystemAction::GetParamValue("ORDER_ID"), 
    $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["ID"]);
$email = either($GLOBALS["SALE_INPUT_PARAMS"]["PROPERTY"]["EMAIL"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["USER_EMAIL"]);
$phone = htmlspecialchars($GLOBALS['SALE_INPUT_PARAMS']['PROPERTY']['PHONE']);

// --- BEGIN --- костыль для arteva
$arOrder = getOrder($orderid);
$user_id = $arOrder["ACCOUNT_NUMBER"]; // вместо пользователя передаём номер заказа (не ID)
// --- END ---

$opts = array ("sum"=>$sum, "user_id"=>$user_id);
$payment_parameters = array("clientid"=>$user_id, "orderid"=>$orderid, "sum"=>$sum, "phone"=>$phone, "email"=>$email);
$query = http_build_query($payment_parameters);
$err_num = $err_text = NULL;

$form = QueryGetData($TMG_PK_SERVER_ADDR, 80, "/external/", $query, $err_num, $err_text);

if ($form  == "")
  $form = "<h3>Произошла ошибка при инциализации платежа</h3><p>$err_num: ".htmlspecialchars($err_text)."</p>";
?>
<div id='tmg_pk_form_container'>
<?php 
Exemple #6
0
/**
* A Resoruce List for Products to include HTTP Verbs
* Switch Statement used for HTTP Verbs (GET, POST, DELETE, and PATCH)
* Server Request_Method is an array which contains information of paths and locations
* Routing for Products Starts Here
*/
// Remove white space (trim) and check if variable is set and not empty(isset)
$pathParts = trim(isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/', '/');
$pathParts = explode('/', $pathParts);
switch ($_SERVER['REQUEST_METHOD']) {
    // Gets List of all products or single product using GET Method
    case 'GET':
        if (empty($pathParts[1])) {
            echo getOrders();
        } else {
            echo getOrder($pathParts[1]);
        }
        break;
        // Create product on database using POST and view it using GET Method
    // Create product on database using POST and view it using GET Method
    case 'POST':
        postOrders(json_decode(file_get_contents('php://input')));
        break;
        // Delete requrested product from database using DELETE Method
    // Delete requrested product from database using DELETE Method
    case 'DELETE':
        if (empty($pathParts[1])) {
            echo "you can delete everthing!!";
        } else {
            deleteOrders($pathParts[1]);
        }
Exemple #7
0
/**
 * Generate a packing slip for an entire order. If the order has multiple
 * shipping destinations then a packing slip will be generated for each.
 *
 * @param int The order ID to print the packing slip for.
 * @return string The generated packing slip (HTML)
 */
function generateOrderPackingSlip($orderId)
{
	$db = $GLOBALS['ISC_CLASS_DB'];

	// allow access to deleted orders if printing from within control panel
	$isAdmin = (defined('ISC_ADMIN_CP') && ISC_ADMIN_CP);

	$order = getOrder($orderId, null, null, $isAdmin);
	if(empty($order) || $order['ordisdigital']) {
		return false;
	}

	// Fetch the shipping addresses in this order
	$addresses = array();
	$query = "
		SELECT *
		FROM [|PREFIX|]order_addresses
		WHERE order_id='".(int)$orderId."'
	";
	$result = $db->query($query);
	while($address = $db->fetch($result)) {
		$addresses[$address['id']] = $address;
	}

	// Fetch shipping details for this order too
	$query = "
		SELECT *
		FROM [|PREFIX|]order_shipping
		WHERE order_id='".(int)$orderId."'
		ORDER BY order_address_id
	";
	$result = $db->query($query);
	while($shipping = $db->fetch($result)) {
		$addresses[$shipping['order_address_id']]['shipping'] = $shipping;
	}

	// Now fetch products
	$addressProducts = array();
	$query = "
		SELECT *
		FROM [|PREFIX|]order_products
		WHERE orderorderid='".(int)$orderId."'
	";
	$result = $db->query($query);
	while($product = $db->fetch($result)) {
		// Digital item - these do not have an address
		if(!$product['order_address_id']) {
			continue;
		}
		$addressProducts[$product['order_address_id']][] = array(
			'prodcode' => $product['ordprodsku'],
			'prodname' => $product['ordprodname'],
			'prodqty' => $product['ordprodqty'],
			'prodoptions' => $product['ordprodoptions'],
			'prodvariationid' => $product['ordprodvariationid'],
			'prodordprodid' => $product['orderprodid'],
			'prodeventdatename' => $product['ordprodeventname'],
			'prodeventdate' => $product['ordprodeventdate'],
		);
	}

	$packingSlips = '';
	foreach($addresses as $addressId => $address) {
		if(empty($addressProducts[$addressId])) {
			continue;
		}
		$title = sprintf(GetLang('PackingSlipTitleOrder'), $order['orderid']);
		$shipmentDetails = array(
			'shipcustid'			=> $order['ordcustid'],
			'shipping_module'		=> $address['shipping']['module'],
			'shipmethod'			=> $address['shipping']['method'],
			'shiporderid'			=> $order['orderid'],
			'shiporderdate'			=> $order['orddate'],
			'shipcomments'			=> $order['ordcustmessage'],
			'shipbillfirstname'		=> $order['ordbillfirstname'],
			'shipbilllastname'		=> $order['ordbilllastname'],
			'shipbillcompany'		=> $order['ordbillcompany'],
			'shipbillstreet1'		=> $order['ordbillstreet1'],
			'shipbillstreet2'		=> $order['ordbillstreet2'],
			'shipbillsuburb'		=> $order['ordbillsuburb'],
			'shipbillstate'			=> $order['ordbillstate'],
			'shipbillzip'			=> $order['ordbillzip'],
			'shipbillcountry'		=> $order['ordbillcountry'],
			'shipbillcountrycode'	=> $order['ordbillcountrycode'],
			'shipbillcountryid'		=> $order['ordbillcountryid'],
			'shipbillstateid'		=> $order['ordbillstateid'],
			'shipbillphone'			=> $order['ordbillphone'],
			'shipbillemail'			=> $order['ordbillemail'],
			'shipshipfirstname'		=> $address['first_name'],
			'shipshiplastname'		=> $address['last_name'],
			'shipshipcompany'		=> $address['company'],
			'shipshipstreet1'		=> $address['address_1'],
			'shipshipstreet2'		=> $address['address_2'],
			'shipshipsuburb'		=> $address['city'],
			'shipshipstate'			=> $address['state'],
			'shipshipzip'			=> $address['zip'],
			'shipshipcountry'		=> $address['country'],
			'shipshipcountrycode'	=> $address['country_iso2'],
			'shipshipcountryid'		=> $address['country_id'],
			'shipshipstateid'		=> $address['state_id'],
			'shipshipphone'			=> $address['phone'],
			'shipshipemail'			=> $address['email'],
		);

		if($packingSlips) {
			$packingSlips .= '<p class="PageBreak">&nbsp;</p>';
		}
		$packingSlips .= generatePrintablePackingSlip($title, $shipmentDetails, $addressProducts[$addressId]);
	}
	return $packingSlips;
}
Exemple #8
0
function getOrderViaJS($exchange, $product, $level, $user)
{
    if ($_SESSION["instabid_userId"] == NULL) {
        return '{"result":"FAIL","msg":"Sorry but this user is unidentified creating a risk of outside fraudulent access. You have to call the function authorize_user_to_bid(userId) in instabid.php first"}';
    } else {
        //return $_SESSION["instabid_userId"];
        return getOrder($exchange, $product, $level, $user);
    }
}
	public function handleRemoteAdminRequest()
	{
		if (empty($_POST['orderId'])) {
			exit;
		}

		$order = getOrder($_POST['orderId']);
		$extraInfo = @unserialize($order['extrainfo']);
		if (empty($order) && !is_array($extraInfo)) {
			exit;
		}

		unset($extraInfo['cc_ccno']);
		unset($extraInfo['cc_cvv2']);
		unset($extraInfo['cc_name']);
		unset($extraInfo['cc_ccaddress']);
		unset($extraInfo['cc_cczip']);
		unset($extraInfo['cc_cctype']);
		unset($extraInfo['cc_ccexpm']);
		unset($extraInfo['cc_ccexpy']);

		if(isset($extraInfo['cc_issueno'])) {
			unset($extraInfo['cc_issueno']);
		}

		if(isset($extraInfo['cc_issuedatey'])) {
			unset($extraInfo['cc_issuedatey']);
			unset($extraInfo['cc_issuedatem']);
			unset($extraInfo['cc_issuedated']);
		}

		$updatedOrder = array(
			"extrainfo" => serialize($extraInfo)
		);
		$GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='".$order['orderid']."'");
		echo 1;
	}
Exemple #10
0
<?php

// Get list of all users or one in particualr if the id is given
include_once '../include/headers.php';
include_once '../include/dbutils.php';
include_once '../include/main.php';
include_once 'domain/orders.php';
db_connect();
$expand = isset($_GET['expand']) ? $_GET['expand'] : null;
$status = isset($_GET['status']) ? $_GET['status'] : null;
if (isset($_GET['id'])) {
    $value = getOrder($_GET['id']);
} else {
    $value = getOrders($status, $_GET['providerId'], $expand);
}
//return JSON array
exit(json_encode($value));
				<td>' . $shop_offer_type . '</td></tr><br>
				<tr><td align="center" ><b>Offer Description:</b></td>
				<td>' . $shop_offer_description . '</td></tr><br>
				<tr><td align="center" ><b>Offer Name:</b></td>
				<td>' . $shop_offer_name . '</td></tr>
				<br><form action="?subtopic=shopadmin&action=addoffer" method="post" ><input name="submit" type="submit" value="Back" title="Back"/></form>';
        }
    }
    if ($action == "viewoffer") {
        $items = simplexml_load_file($config['site']['server_path'] . '/data/items/items.xml') or die('<b>Could not load items!</b>');
        foreach ($items->item as $v) {
            $itemList[(int) $v['id']] = $v['name'];
        }
        $order = array("id" => "id", "points" => "points", "offer_type" => "offer_type", "itemid1" => "itemid1", "itemid2" => "itemid2");
        $main_content .= '<center><table width="100%" border="1" cellspacing="0" cellpadding="4" style="text-align:center"><tr BGCOLOR="#505050"><td><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'id') . '" class=white>ID</td><td width="5"><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'points') . '" class=white>VIP Coins</td><td width="7">
			<font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'itemid1') . '" class=white>ID Item</td><td width="5"><font color="white">Qtd.</td><td width="7"><center><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'itemid2') . '" class=white>ID Mochila</center></td><td width="5"><font color="white">Count</td><td width="7"><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'offer_type') . '" class=white>Tipo</td>
			<td width="85"><font color="white">Descrição</td><td width="30"><font color="white">Nome</td><td width="30"></td></tr>';
        $shopoffers = $SQL->query('SELECT id, points, itemid1, count1, itemid2, count2, offer_type, offer_description, offer_name, pid FROM z_shop_offer ' . makeOrder($order, 'order', 'id'));
        foreach ($shopoffers as $shop) {
            $main_content .= '</B><tr BGCOLOR="#D4C0A1"><td align="center">' . $shop['id'] . '<td align="center">' . $shop['points'] . '</td>';
            if ($shop['itemid1'] == "0") {
                $main_content .= '<td align="center">' . $shop['itemid1'] . '<br></td>';
            } else {
                $main_content .= '<td align="center">' . $shop['itemid1'] . '<br>(' . $itemList[(int) $shop['itemid1']] . ')</td>';
            }
            $main_content .= '<td align="center">' . $shop['count1'] . '</td>';
            if ($shop['itemid2'] == "0") {
                $main_content .= '<td align="center">' . $shop['itemid2'] . '</td>';
            } else {
                $main_content .= '<td align="center">' . $shop['itemid2'] . '<br>(' . $itemList[(int) $shop['itemid2']] . ')</td>';
            }
Exemple #12
0
echo CHtml::checkBoxList('licensesIds', $licensesIdsFilter, CHtml::listData(DriverLicenses::model()->findAll(array('order' => getOrder($licensesIdsFilter) . 'name ASC')), 'id', 'name'), array('template' => '{beginLabel}{input} {labelTitle}{endLabel}', 'separator' => ''));
?>
                    </div>
                </td>
                <td class="<?php 
echo getClassName($applicantTypeIdsFilter);
?>
">
                    <strong><?php 
echo CHtml::encode(CvList::model()->getAttributeLabel('applicantTypeIds'));
?>
</strong><br />
                    <input type="text" name="applicantTypesFilter" class="filter" size="10" />
                    <div class="div-overflow narrow">
                        <?php 
echo CHtml::checkBoxList('applicantTypeIds', $applicantTypeIdsFilter, CHtml::listData(CvApplicantTypes::model()->findAll(array('order' => getOrder($applicantTypeIdsFilter) . 'name ASC')), 'id', 'name'), array('template' => '{beginLabel}{input} {labelTitle}{endLabel}', 'separator' => ''));
?>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <br />
    <input type="submit" class="btn btn-primary btn-small" value="Знайти" />
    <input type="button" class="btn btn-primary btn-small reset" value="Скинути" onclick="$(':input','#filter').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected'); $('#filter').submit();" />
</form>
    <h4>
        <?php 
echo Yii::t('main', 'profiles.status.statistic');
?>
        <?php 
class StatusTransacaoAkatus
{
    const AGUARDANDO_PAGAMENTO = 'Aguardando Pagamento';
    const EM_ANALISE = 'Em Análise';
    const APROVADO = 'Aprovado';
    const CANCELADO = 'Cancelado';
    const DEVOLVIDO = 'Devolvido';
    const COMPLETO = 'Completo';
    const ESTORNADO = 'Estornado';
}
require_once 'app/Mage.php';
require_once 'app/code/core/Mage/Sales/Model/Order.php';
$codigoTransacao = $_POST["transacao_id"];
$statusAkatus = $_POST["status"];
$tokenRecebido = $_POST["token"];
$order = getOrder($codigoTransacao);
$tokenNIP = Mage::getStoreConfig('payment/akatus/tokennip', $order->getStoreId());
if ($tokenNIP == $tokenRecebido) {
    $newOrderState = getNewOrderState($statusAkatus, $order);
    Mage::Log('new order state: ' . $newOrderState);
    if ($newOrderState) {
        updateOrder($order, $newOrderState);
    }
}
function getOrder($codigoTransacao)
{
    $mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : '';
    $mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'store';
    Mage::app($mageRunCode, $mageRunType);
    $db = Mage::getSingleton('core/resource')->getConnection('core_write');
    $retorno = $db->query("SELECT idpedido FROM akatus_transacoes WHERE codtransacao = '" . $codigoTransacao . "' ORDER BY id DESC");
Exemple #14
0
	private function ValidateReorder()
	{
		if(empty($_REQUEST['orderid'])) {
			flashMessage(getLang('InvalidOrderId'), MSG_ERROR, 'cart.php');
		}

		$customerId = getClass('ISC_CUSTOMER')->getCustomerId();
		if(!$customerId) {
			flashMessage(getLang('MustBeLoggedInToReorder'), MSG_ERROR, 'cart.php');
		}

		// Was this order placed by the same customer?
		$order = getOrder($_REQUEST['orderid']);
		if($order['ordcustid'] != $customerId) {
			flashMessage(getLang('InvalidOrderId'), MSG_ERROR, 'cart.php');
		}
	}
Exemple #15
0
	/**
	 * Subscribe a customer to newsletter and other lists based on their order
	 * if they have opted in to them
	 *
	 * @param array $orderRow An array that is ready to be passed to CreateOrder()
	 *
	 * @return void
	 */
	public function SubscribeCustomerToLists($orderid)
	{
		$orderRow = getOrder($orderid);

		if ($orderRow === false) {
			return;
		}

		// No point trying to subscribe them if we don't have an email to subscribe them with
		if (trim($orderRow['ordbillemail']) == '') {
			return;
		}

		// If the customer didn't opt in, stop immediately
		if ($this->response->data['new-order-notification']['buyer-marketing-preferences']['email-allowed']['VALUE'] != 'true') {
			return;
		}

		// Should we add them to our newsletter mailing list?
		$this->SubscribeCustomerToNewsletter($orderRow['ordbillemail'], $orderRow['ordbillfirstname']);

		// Should we add them to our special offers & discounts mailing list?
		$this->SubscribeCustomerToOtherLists($orderRow);
	}
Exemple #16
0
			$sql = "INSERT INTO telerecord
							VALUES ('{$teleNum}', '{$orderNum}', '{$orderState}')";
			addOrder($sql);		
		}
		$sql2 = "select * from telerecord where orderNum = '{$orderNum}'";
		getOrder($sql2);
	}

	if($action == "updateOrder"){
		if(!empty($teleNum) && (!empty($orderNum)) && (!empty($orderState))){
			$sql = "UPDATE telerecord SET teleNum='{$teleNum}', orderState='{$orderState}'
							WHERE orderNum='{$orderNum}'";
		}
		updateOrder($sql);
		$sql2 = "select * from telerecord where orderNum = '{$orderNum}'";
		getOrder($sql2);
	}

	$conn=null;

	function connectDb(){
		global $conn;
		$servername = "localhost";
		$username = "******";
		$password = "******";

		try {
	    $conn = new PDO("mysql:host=$servername;dbname=yjz", $username, $password);
	    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	    $conn->exec("SET CHARACTER SET UTF8");
	  }	catch(PDOException $e)
Exemple #17
0
	public function UpdateReturnStatus(&$return, $status, $crediting = false)
	{

		// Start a transaction
		$GLOBALS['ISC_CLASS_DB']->Query("START TRANSACTION");

		// Changing the status of this return to "Refunded", so we need to perform some additional things
		if($status == 5 && $return['retstatus'] != 5) {
			$refundAmount = $return['retprodcost'] * $return['retprodqty'];
			$updatedProduct = array(
				"ordprodrefundamount" => $return['retprodcost'],
				"ordprodrefunded" => $return['retprodqty'],
				"ordprodreturnid" => $return['returnid']
			);

			$order = getOrder($return['retorderid']);
			if (!$order) {
				return false;
			}

			$GLOBALS['ISC_CLASS_DB']->UpdateQuery("order_products", $updatedProduct, "orderprodid='".$GLOBALS['ISC_CLASS_DB']->Quote($return['retordprodid'])."'");

			$query = "
				UPDATE [|PREFIX|]orders
				SET ordrefundedamount = ordrefundedamount + ".$refundAmount."
				WHERE orderid='".$return['retorderid']."'
			";
			$this->db->query($query);

			// Have all items in this order been refunded? Mark the order as refunded.
			$query = sprintf("SELECT SUM(ordprodqty-ordprodrefunded) FROM [|PREFIX|]order_products WHERE orderorderid=%d", $return['retorderid']);
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			$remainingItems = $GLOBALS['ISC_CLASS_DB']->FetchOne($result);
			if($remainingItems == 0) {
				$updatedOrder = array(
					'ordstatus' => 4
				);
				$GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='".$GLOBALS['ISC_CLASS_DB']->Quote($return['retorderid'])."'");
			}

			// Update the status of this return
			$updatedReturn = array(
				"retstatus" => 5,
				"retuserid" => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUserId()
			);
			$GLOBALS['ISC_CLASS_DB']->UpdateQuery("returns", $updatedReturn, "returnid='".$GLOBALS['ISC_CLASS_DB']->Quote($return['returnid'])."'");

			// Update the product inventory for this returned item
			$query = sprintf("SELECT * FROM [|PREFIX|]order_products WHERE ordprodid='%d'", $return['retordprodid']);
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			$row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);

			UpdateInventoryOnReturn($return['retordprodid']);

			// dont send a refund through the checkout module if a store credit was issued
			if (!$crediting) {
				// If the checkout module that was used for an order is still enabled and has a function
				// to handle a status change, then call that function
				$valid_checkout_modules = GetAvailableModules('checkout', true, true);
				$valid_checkout_module_ids = array();
				foreach ($valid_checkout_modules as $valid_module) {
					$valid_checkout_module_ids[] = $valid_module['id'];
				}

				$newStatus = $order['ordstatus'];
				if (isset($updatedOrder['ordstatus'])) {
					$newStatus = $updatedOrder['ordstatus'];
				}

				// attempt to refund this amount with the checkout provider
				$order = GetOrder($return['retorderid'], false);
				if (in_array($order['orderpaymentmodule'], $valid_checkout_module_ids)) {
					GetModuleById('checkout', $checkout_module, $order['orderpaymentmodule']);
					if (method_exists($checkout_module, 'HandleStatusChange')) {
						call_user_func(array($checkout_module, 'HandleStatusChange'), $return['retorderid'], $order['ordstatus'], $newStatus, $refundAmount);
					}
				}
			}
		}
		else {
			// Update the status of this return
			$updatedReturn = array(
				"retstatus" => $status
			);
			$GLOBALS['ISC_CLASS_DB']->UpdateQuery("returns", $updatedReturn, "returnid='".$GLOBALS['ISC_CLASS_DB']->Quote($return['returnid'])."'");
		}

		$return['retstatus'] = $status;

		if(GetConfig('NotifyOnReturnStatusChange') == 1) {
			$this->EmailReturnStatusChange($return);
		}

		if($GLOBALS['ISC_CLASS_DB']->GetErrorMsg() == "") {
			$GLOBALS['ISC_CLASS_DB']->Query("COMMIT");
			return true;
		}
		else {
			return false;
		}
	}
Exemple #18
0
function loadAlerts()
{
    global $ThisUsername;
    //gain access to the curent username
    global $ThisUsers;
    //gain access to the current user data
    global $ThisSchools;
    //gain access to the current school data
    global $ThisGroups;
    //gain access to the current group data
    global $ThisOrders;
    //gain access to the current order data
    global $ThisProjects;
    //gain access to the current project data
    global $alertHtml;
    //gain access to the alert html variable (end display html)
    global $alertRemovedA;
    //gain access to the array of removed alerts
    global $alertA;
    //gain access to the array of all alerts
    getUser($ThisUsername);
    //load the current user data based upon the user's username
    getSchool($ThisUsers['School Code']);
    //load the current school data for this user
    getGroup($ThisUsers['Group Code']);
    //load the current group data for this user
    getOrder($ThisGroups['Order Code']);
    //load the current order data for this group
    getProject($ThisOrders['Doc Code']);
    //load the current project data for this order
    $userDBAlertsA = explode("&&&", $ThisUsers['Alerts']);
    //split the user alert data string by &&& and store this array
    if (count($userDBAlertsA) == 2) {
        //if this array has two parts, (one &&& seperator)
        $alertRemovedA = explode(",,,", $userDBAlertsA[0]);
        //split the first part by ,,, and make these items the removed alerts (add the user removed alerts)
        addAlerts($userDBAlertsA[1]);
        //and process the other part using the addAlerts function (add the user alerts with respect to the removed alerts)
    }
    addAlerts($ThisSchools['Alerts']);
    //add the school alerts with respect to the removed alerts
    addAlerts($ThisGroups['Alerts']);
    //add the group alerts with respect to the removed alerts
    addAlerts($ThisOrders['Alerts']);
    //add the order alerts with respect to the removed alerts
    addAlerts($ThisProjects['Alerts']);
    //add the project alerts with respect to the removed alerts
    addAlerts("13,,,12,,,0,,,This is an alert! these can be sent to peeples' dashboards! They can be sent per group, school, individual, etc. ! This one should be blueish! Dale and Erik, you can make it look basicly however you want as long as it is stackable in this right pane!");
    //example alert
    addAlerts("23,,,22,,,1,,,Alerts basicly go away forever when you dismiss them.. these are just for testing.. This should be yellow-ish!");
    //example alert
    addAlerts("34,,,33,,,2,,,This one should be red-sih! WARNING! THE WORLD HAS ENDED!");
    //example alert
    $alertHtml = "";
    //set the alert html to be blank
    for ($i = 0; $i < count($alertA); $i++) {
        //for each alert that is to be printed,
        $thisAlertA = $alertA[$i];
        //create a temporary variable to store the data for this alert
        $alertHtml = $alertHtml . '<div class="alert-item-outer color-' . $thisAlertA[2] . '" id="alert-' . $thisAlertA[0] . '"><p align="left">' . $thisAlertA[3] . '</p><p align="right"><a style="color:#606060;" href="#" onclick="dismissAlert(' . "'" . $thisAlertA[0] . "'" . ');">Dismiss</a></p></div>';
        //add this alert
    }
    if ($alertHtml == '') {
        //if no alerts were added
        $alertHtml = '<p style="margin-top:3em;color:#ffffff;font-size: 300%;">No new alerts at this time</p>';
        //display the no new alerts text
    }
}
Exemple #19
0
 if ($next && $_SESSION[$wr_key]['step'] == 5) {
     $widget_id = $_SESSION[$wr_key]['widget_id'];
     $widget_type = $_SESSION[$wr_key]['widget_type'];
     $widget_asset = $_SESSION[$wr_key]['widget_asset'];
     $widget_title = $_SESSION[$wr_key]['widget_title'];
     $widget_help = $_SESSION[$wr_key]['widget_help'];
     $widget_refresh = $_SESSION[$wr_key]['widget_refresh'];
     $widget_height = $_SESSION[$wr_key]['widget_height'];
     $widget_url = $_SESSION[$wr_key]['widget_url'];
     $owner = $_SESSION[$wr_key]['owner'];
     $id_content = $_SESSION[$wr_key]['id_content'];
     $widget_media = $_SESSION[$wr_key]['widget_media'];
     $widget_params = $_SESSION[$wr_key]['widget_params'];
     if ($id_content != "") {
         $column = getColumn($dbconn, $id_content);
         $order = getOrder($dbconn, $id_content);
     } else {
         $id_content = getNewId($dbconn, $tab);
         $column = 0;
         $order = 0;
         $error = reorder_widgets($dbconn, $tab);
     }
     ossim_valid($column, OSS_DIGIT, 'illegal:' . _("Widget Column"));
     ossim_valid($order, OSS_DIGIT, 'illegal:' . _("Widget Row"));
     if (ossim_error()) {
         $info_error[] = ossim_get_error();
         ossim_clean_error();
         $error = true;
     }
     if ($widget_type == 'report' && !$pro) {
         $info_error[] = _('Report section is only available in professional version');
include_once "ini.dbstring.php";
include_once "ini.functions.php";
sec_session_start();
include_once "mod.login.php";
include_once "mod.order.php";
include_once "mod.client.php";
include_once "mod.optional.php";
include_once "ctrl.order.php";
include_once "ctrl.client.php";
include_once "ctrl.login.php";
// check user authentication
checkSession($_SESSION['sess_user_id']);
checkOrderSession($_SESSION['sess_order_type'], $_SESSION['sess_client']);
$d['sess_order_type'] = $_SESSION['sess_order_type'];
$d['sess_client'] = $_SESSION['sess_client'];
$ordlist = getOrder($d, $db);
$sta = getStatus($db);
$rf = getRf($db);
$os = getOS($db);
$app = getApp($db);
$reload = $_SERVER['PHP_SELF'] . "?tpages=" . $tpages;
$per_page = PERPAGE;
// number of results to show per page
$total_results = count($ordlist);
$total_pages = ceil($total_results / $per_page);
//total pages we going to have
//-------------if page is setcheck------------------//
$show_page = 1;
if (isset($_GET['page'])) {
    $show_page = $_GET['page'];
    //it will telles the current page
Exemple #21
0
                                                <tr>
                                                    <center>
                                                        <th><center>ลำดับ</center></th>
                                                        <th><center>รหัสใบคำสั่งซื้อ</center></th>
                                                        <th><center>วันที่สั่งซื้อ</center></th>
                                                        <th><center>เวลาสั่งซื้อ</center></th>
                                                        <th><center>ชื่อร้านค้า</center></th>
                                                        <th><center>จำนวนรายการสินค้า</center></th>
                                                        <th><center>ราคาขายรวมต่อบิล</center></th>
                                                        <th><center>การกระทำ</center></th>
                                                    </center>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
$getOrder = getOrder();
$i = 0;
foreach ($getOrder as $value) {
    $i++;
    $val_idorder_p = $value['idorder_p'];
    $val_code_order_p = $value['code'];
    $val_date_order_p = $value['date_order_p'];
    $date_for = date_create($val_date_order_p);
    $date_for->add(new DateInterval('P543Y0M0DT0H0M0S'));
    $val_time_order_p = $value['time_order_p'];
    $val_name_shop = $value['name_shop'];
    $val_count_product = $value['count_product'];
    $val_price_product_order = $value['price_product_order'];
    $getPrice_percent = getPricePercent($val_idorder_p);
    $price_percent = $getPrice_percent['price_percent'];
    $getPrice_bath = getPriceBath($val_idorder_p);
Exemple #22
0
        echo 'OK';
    } else {
        echo 'Error!';
    }
    exit;
}
/**=================================================================================================
-------------------      DOWNLOAD CONTENT FOR VIEWS AND SWITCH FUNCTIONS      ----------------------
===================================================================================================**/
switch ($view) {
    case 'admin_orders':
        $orders = getOrders();
        $users = getUsersForOrders($orders);
        break;
    case 'admin_order':
        $order = getOrder($order_id);
        $user = getUserForOrder($order['user_id']);
        if (!$user) {
            setSession('admin', array('error' => 'database_error'));
        } else {
            unset($_SESSION['admin']['error']);
        }
        $tiraj = getTiraj($order['tiraj']);
        if (!$tiraj) {
            setSession('admin', array('error' => 'database_error'));
        }
        if (!empty($order['paper_type'])) {
            $paper = getPaperType($order['paper_type']);
        }
        if ($order['layout']) {
            $layouts = getOrderLayouts($order_id);
//This was a test to get the JSON Data
$result = mysql_query("INSERT INTO post_details (details) VALUES ('{$details}')");
//get the use with this phone number
$phone = '+254' . substr($phone, -9);
//get user by phone number
$user = getUser($phone);
// print_r($user['id']);
// exit;
//$u;
//update user balance
// print_r($user);
// exit;
$new_balance = $user['balance'] + $amount;
updateUserBalance($user['id'], $new_balance);
//get the latest order by the current user and compare with the amount sent
$order = getOrder($user['id']);
$latest_order_amount = $order['amount_ordered'];
//check if the user new balance is greater than the ordered airtime
if ($new_balance + 1 > $latest_order_amount) {
    //send airtime
    //building the recipients array
    $recipients = array();
    $data = array();
    $data['phoneNumber'] = $phone;
    $data['amount'] = "KES " . $latest_order_amount;
    array_push($recipients, $data);
    //sending the airtime
    sendAirtime($recipients);
    //reduce the user balance by the sent airtime amount
    $balance = $new_balance - $latest_order_amount;
    // and update user balance
Exemple #24
0
echo CHtml::checkBoxList('assistanceIds', $assistanceIdsFilter, CHtml::listData(AssistanceTypes::model()->findAll(array('order' => getOrder($assistanceIdsFilter) . 'name ASC')), 'id', 'name'), array('template' => '{beginLabel}{input} {labelTitle}{endLabel}', 'separator' => ''));
?>
                    </div>
                </td>
                <td class="<?php 
echo getClassName($licensesIdsFilter);
?>
">
                    <strong><?php 
echo CHtml::encode(CvList::model()->getAttributeLabel('driverLicensesIds'));
?>
</strong><br />
                    <input type="text" name="licensesFilter" class="filter" size="10" />
                    <div class="div-overflow narrow">
                        <?php 
echo CHtml::checkBoxList('licensesIds', $licensesIdsFilter, CHtml::listData(DriverLicenses::model()->findAll(array('order' => getOrder($licensesIdsFilter) . 'name ASC')), 'id', 'name'), array('template' => '{beginLabel}{input} {labelTitle}{endLabel}', 'separator' => ''));
?>
                    </div>
                </td>
            </tr>
        </table>
    </div>
    <br />
    <input type="submit" class="btn btn-primary btn-small" value="Знайти" />
    <input type="button" class="btn btn-primary btn-small reset" value="Скинути" onclick="$(':input','#filter').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected'); $('#filter').submit();" />
</form>
    <h4>
        <?php 
echo Yii::t('main', 'profiles.status.statistic');
?>
        <?php 
Exemple #25
0
		/**
		*	Print an invoice for the selected order using the invoice_print template
		*/
		public function PrintInvoice()
		{
			if (!isset($_GET['order_id']) || !is_numeric($_GET['order_id'])) {
				echo "<script type=\"text/javascript\">window.close();</script>";
			}

			$order = getOrder($_GET['order_id']);
			if(!$order || $order['ordcustid'] != getClass('ISC_CUSTOMER')->getCustomerId()) {
				echo "<script type=\"text/javascript\">window.close();</script>";
				return;
			}

			require_once ISC_BASE_PATH . '/lib/order.printing.php';
			echo GeneratePrintableInvoicePage(array($_GET['order_id']));
		}
Exemple #26
0
	/**
	 * Create the pending order in the database with the customers selected payment details, etc.
	 *
	 * @return array An array containing information about what needs to be done next.
	 */
	public function SavePendingOrder()
	{
		$provider = null;
		$verifyPaymentProvider = true;
		$redirectToFinishOrder = false;
		$providerId = '';

		$pendingOrderResult = array();
		$creditUsed = 0;
		$giftCertificates = array();

		$orderTotal = $this->getQuote()->getGrandTotal();

		// store the discounted subtotal in the session for affiliate tracking
		$incTax = (getConfig('taxDefaultTaxDisplayOrders') == TAX_PRICES_DISPLAY_INCLUSIVE);
		$_SESSION['LAST_ORDER_DISCOUNTED_SUBTOTAL'] = $this->getQuote()->getDiscountedSubTotal($incTax);

		// Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
		$selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);

		$giftCertificates = $this->getQuote()->getAppliedGiftCertificates();
		if(!empty($giftCertificates)) {
			$badCertificates = array();
			$remainingBalance = 0;
			$totalWithoutCertificates =
				$this->getQuote()->getGrandTotalWithoutGiftCertificates();
			$giftCertificateAmount =
				$this->getQuote()->getGiftCertificateTotal();
			getClass('ISC_GIFTCERTIFICATES')
				->giftCertificatesApplicableToOrder(
					$totalWithoutCertificates,
					$giftCertificates,
					$remainingBalance,
					$badCertificates);

			// One or more gift certificates were invalid so this order is now invalid
			if(!empty($badCertificates)) {
				$badCertificatesList = '<strong>'.GetLang('BadGiftCertificates').'</strong><ul>';
				foreach($badCertificates as $code => $reason) {
					if(is_array($reason) && $reason[0] == "expired") {
						$reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
					}
					else {
						$reason = GetLang('BadGiftCertificate'.ucfirst($reason));
					}
					$badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
				}
				$badCertificatesList .= "</ul>";
				$pendingOrderResult = array(
					'error' => GetLang('OrderContainedInvalidGiftCertificates'),
					'errorDetails' => $badCertificatesList
				);
				return $pendingOrderResult;
			}
			// This order was entirely paid for using gift certificates but the totals don't add up
			else if($totalWithoutCertificates == $giftCertificateAmount && $remainingBalance > 0) {
				$pendingOrderResult = array(
					'error' => GetLang('OrderTotalStillRemainingCertificates')
				);
				return $pendingOrderResult;
			}
			// Order was entirely paid for using gift certificates
			else if($totalWithoutCertificates == $giftCertificateAmount) {
				$providerId = 'giftcertificate';
				$verifyPaymentProvider = false;
				$redirectToFinishOrder = true;
			}
		}

		// If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
		if($orderTotal == 0) {
			$providerId = '';
			$verifyPaymentProvider = false;
			$redirectToFinishOrder = true;
		}

		$selected_provider = '';
		if($verifyPaymentProvider) {
			$candidate = '';
			if (isset($_POST['checkout_provider']) && $_POST['checkout_provider'] != '') {
				$candidate = $_POST['checkout_provider'];
			} else if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != '') {
				// used by paypal
				$candidate = $_POST['credit_checkout_provider'];
			}

			// Check if the chosen checkout method is valid
			$providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
			foreach ($providers as $p) {
				if ($p['id'] == $candidate) {
					$selected_provider = $candidate;
				}
			}

			// If there's only one payment provider, then they're paying via that
			if($selected_provider == '' && count($providers) == 1) {
				$selected_provider = $providers[0]['object']->GetId();
			}

			// Are we using our store credit?
			$customer = getClass('ISC_CUSTOMER')->getCustomerDataByToken();
			if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1
				&& $customer['custstorecredit'] > 0) {
					// User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
					if ($selected_provider == '' && $customer['custstorecredit'] < $orderTotal) {
						return false;
					}
					// Otherwise we can use the store credit.
					// Subtract store credit from users account and send them to the finished page
					else {
						$onlyCredit = false;
						$updateExtra = '';
						// If we're only using store credit
						$creditToUse = $orderTotal;
						if ($customer['custstorecredit'] >= $creditToUse) {
							// Set the checkout provider
							$providerId = 'storecredit';
							$verifyPaymentProvider = false;
							$redirectToFinishOrder = true;
							$creditUsed = $creditToUse;
							$onlyCredit = true;
						}
						else {
							// Using all of our store credit to pay for this order and we owe more.
							$creditUsed = $customer['custstorecredit'];
						}
					}
			}
		}

		$orderStatus = ORDER_STATUS_INCOMPLETE;

		// Now with round 2, do we still need to verify the payment provider?
		if($verifyPaymentProvider) {
			// If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
			if ((count($providers) == 0 ||
				(count($providers) > 1 && $selected_provider == '')) &&
					!isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
					return false;
			}

			// Is the payment provider selected actually valid?
			if (!GetModuleById('checkout', $provider, $selected_provider)) {
				return false;
			}
			$providerId = $provider->GetId();
		}

		if(isset($_COOKIE['SHOP_TOKEN'])) {
			$customerToken = $_COOKIE['SHOP_TOKEN'];
		}
		else {
			$customerToken = '';
		}

		$orderComments = '';
		if(isset($_REQUEST['ordercomments'])) {
			$orderComments = $_POST['ordercomments'];
		}

		// Set up the order to be created
		$this->getQuote()
			->setAppliedStoreCredit($creditUsed)
			->setCustomerMessage($orderComments);
			;

		$newOrder = array(
			'orderpaymentmodule' => $providerId,
			'ordcurrencyid' => $selectedCurrency['currencyid'],
			'ordcurrencyexchangerate' => $selectedCurrency['currencyexchangerate'],
			'ordipaddress' => getIp(),
			'ordstatus' => $orderStatus,
			'extraInfo' => array(),

			'quote' => $this->getQuote(),
		);


		// OK, we're successful down to here - do they want to create an account? If so then assign it to
		// a session so we can create the actual record on a successful order
		if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT']) ||
			!customerIsSignedIn() && getConfig('GuestCheckoutCreateAccounts')) {
				$createAccount = array(
					'addresses' => array()
				);
				if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
					$createAccount['password'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['password'];
					$createAccount['customFormFields'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['customFields'];
				}
				else {
					$createAccount['autoCreated'] = 1;
				}

				// Handle saving of addresses for new customers
				foreach($this->getQuote()->getAllAddresses() as $address) {
					if($address->getSaveAddress()) {
						$customerAddress = $address->getAsArray();
						$customFields = $address->getCustomFields();
						if(!empty($customFields)) {
							$customerAddress['customFormFields'] = $customFields;

							// Shipping fields need to be mapped back to billing so they can be stored
							if($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
								$newCustomFields = array();
								$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
								foreach($map as $oldId => $newId) {
									$newCustomFields[$newId] = $customFields[$oldId];
								}
								$customerAddress['customFormFields'] = $newCustomFields;
							}
						}

						$createAccount['addresses'][] = $customerAddress;
					}
				}

				$newOrder['extraInfo']['createAccount'] = $createAccount;
		}

		// Did they agree to signup to any mailing lists?
		if (isset($_POST['join_mailing_list'])) {
			$newOrder['extraInfo']['join_mailing_list'] = true;
		}

		if (isset($_POST['join_order_list'])) {
			$newOrder['extraInfo']['join_order_list'] = true;
		}

		if (isset($_POST['join_mailing_list']) || isset($_POST['join_order_list'])) {
			if (isset($_POST['mail_format_preference'])) {
				$newOrder['extraInfo']['mail_format_preference'] = (int)$_POST['mail_format_preference'];
			} else {
				$newOrder['extraInfo']['mail_format_preference'] = Interspire_EmailIntegration_Subscription::FORMAT_PREF_NONE;
			}
			$newOrder['extraInfo']['join_order_list'] = true;
		}


		if(isset($_POST['ordermessage'])) {
			$newOrder['ordermessage'] = $_POST['ordermessage'];
		} else {
			$newOrder['ordermessage'] = '';
		}

		$entity = new ISC_ENTITY_ORDER();
		$orderId = $entity->add($newOrder);

		// Failed to create the order
		if(!$orderId) {
			return false;
		}

		$order = getOrder($orderId);

		// Persist the pending order token as a cookie for 24 hours
		ISC_SetCookie("SHOP_ORDER_TOKEN", $order['ordtoken'], time() + (3600*24), true);
		$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

		// Redirecting to finish order page?
		if($redirectToFinishOrder) {
			return array(
				'redirectToFinishOrder' => true
			);
		}

		// Otherwise, the gateway want's to do something
		$orderData = LoadPendingOrdersByToken($order['ordtoken']);
		$provider->SetOrderData($orderData);

		// Is this an online payment provider? It would like to do something
		if($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
			// Call the checkout process for the selected provider
			if(method_exists($provider, "ShowPaymentForm")) {
				return array(
					'provider' => $provider,
					'showPaymentForm' => true
				);
			}
			else {
				return array(
					'provider' => $provider
				);
			}
		}
		// If an offline method, we throw them to the "Thank you for your order" page
		else {
			return array(
				'provider' => $provider
			);
		}
	}
Exemple #27
0
				<td>' . $shop_offer_type . '</td></tr><br>
				<tr><td align="center" ><b>Offer Description:</b></td>
				<td>' . $shop_offer_description . '</td></tr><br>
				<tr><td align="center" ><b>Offer Name:</b></td>
				<td>' . $shop_offer_name . '</td></tr>
				<br><form action="?subtopic=shopadmin&action=addoffer" method="post" ><input name="submit" type="submit" value="Back" title="Back"/></form>';
        }
    }
    if ($action == "viewoffer") {
        $items = simplexml_load_file($config['site']['server_path'] . '/data/items/items.xml') or die('<b>Could not load items!</b>');
        foreach ($items->item as $v) {
            $itemList[(int) $v['id']] = $v['name'];
        }
        $order = array("id" => "id", "points" => "points", "offer_type" => "offer_type", "itemid1" => "itemid1", "itemid2" => "itemid2");
        $main_content .= '<center><table width="550"><tr BGCOLOR="#505050"><td width="5"><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'id') . '" class=white>ID:</td><td width="5"><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'points') . '" class=white>Points:</td><td width="7">
			<font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'itemid1') . '" class=white>Item ID:</td><td width="5"><font color="white">Count:</td><td width="7"><center><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'itemid2') . '" class=white>Container ID:</center></td><td width="5"><font color="white">Count:</td><td width="7"><font color="white"><a href="index.php?subtopic=shopadmin&action=viewoffer&order=' . getOrder($order, 'order', 'offer_type') . '" class=white>Offer Type:</td>
			<td width="85"><font color="white">Offer Description:</td><td width="30"><font color="white">Offer Name:</td><td width="30"></td></tr>';
        $shopoffers = $SQL->query('SELECT id, points, itemid1, count1, itemid2, count2, offer_type, offer_description, offer_name, pid FROM z_shop_offer ' . makeOrder($order, 'order', 'id'));
        foreach ($shopoffers as $shop) {
            $main_content .= '</B><tr BGCOLOR="#D4C0A1"><td align="center">' . $shop['id'] . '<td align="center">' . $shop['points'] . '</td>';
            if ($shop['itemid1'] == "0") {
                $main_content .= '<td align="center">' . $shop['itemid1'] . '<br></td>';
            } else {
                $main_content .= '<td align="center">' . $shop['itemid1'] . '<br>(' . $itemList[(int) $shop['itemid1']] . ')</td>';
            }
            $main_content .= '<td align="center">' . $shop['count1'] . '</td>';
            if ($shop['itemid2'] == "0") {
                $main_content .= '<td align="center">' . $shop['itemid2'] . '</td>';
            } else {
                $main_content .= '<td align="center">' . $shop['itemid2'] . '<br>(' . $itemList[(int) $shop['itemid2']] . ')</td>';
            }
 public function pz_order()
 {
     //echo "843785845";die;
     $maprow = array();
     $searchMap['status'] = array("in", '1,4,6,7,3');
     $parm['map'] = $searchMap;
     $parm['pagesize'] = 2;
     $sort = "desc";
     $parm['orderby'] = "b.status ASC,b.id DESC";
     $list = getOrder($parm);
     $Bconfig = (require C("APP_ROOT") . "Conf/borrow_config.php");
     //var_dump($list);die;
     if ($this->isAjax()) {
         $str = '';
         foreach ($list['list'] as $vb) {
             $tims = date('Y-m-d H:i:s', $vb[add_time]);
             $str .= "<div class='box'>";
             $str .= "<p class='tit'><a href='#'>{$vb['id']}</a></p>";
             $str .= "<table cellpadding='0' cellspacing='0' border='0' class='table'>";
             $str .= "<tbody>";
             $str .= "<tr>";
             $str .= "<td>用户名:</td>";
             $str .= "<td>{$vb['user_name']}</td>";
             $str .= "<td>本金:</td>";
             $str .= "<td>{$vb['principal']}</td>";
             $str .= "</tr><tr>";
             $str .= "<td>&emsp;管理费:</td>";
             $str .= "<td>{$vb['manage_fee']}</td>";
             $str .= "<td>所获配资金额:</td>";
             $str .= "<td>{$vb['shares_money']}</td>";
             $str .= "</tr><tr>";
             $str .= " <td>订单号:</td>";
             $str .= "<td>{$vb['order']}</td>";
             $str .= " <td>平仓线:</td>";
             $str .= "<td>{$vb['open']}</td>";
             $str .= "</tr><tr>";
             $str .= "<td>警戒线:</td>";
             $str .= "<td>{$vb['alert']}</td>";
             $str .= "<td>添加时间:</td>";
             $str .= "<td>{$tims}</td>";
             $str .= "</tr><tr>";
             $str .= "<td>期限:</td>";
             $str .= "<td>{$vb['duration']}</td>";
             $str .= "</tr></tbody></table>";
             $str .= "<p class='sub'>";
             $str .= "<strong class='strong' style='font-size: 12px'>操盘中</strong>";
             $str .= "<a class='btn-a fr' style='font-size: 11px' href='javascript:void(0);' onclick='look(({$vb['id']}),({$vb['client_user']}),({$vb['client_pass']}));'>查看HOME账号</a></p></div>";
         }
         echo $str;
     } else {
         $this->assign('list', $list);
         $this->assign('Bconfig', $Bconfig);
         $this->display();
     }
 }