예제 #1
0
		/**
		*	Show the details of an order and allow them to print an invoice
		*/
		private function ViewOrderDetails()
		{
			$GLOBALS['SNIPPETS']['AccountOrderItemRow'] = "";
			$count = 0;

			if (!isset($_GET['order_id']) || !is_numeric($_GET['order_id'])) {
				redirect('account.php?action=view_orders');
			}

			$GLOBALS['FlassMessage'] = GetFlashMessageBoxes();

			// Retrieve the completed order that matches the customers user id
			$orderId = (int)$_GET['order_id'];
			$GLOBALS['OrderId'] = $orderId;

			$customerId = getClass('ISC_CUSTOMER')->getcustomerId();
			$query = "
				SELECT *, (
						SELECT CONCAT(custconfirstname, ' ', custconlastname)
						FROM [|PREFIX|]customers
						WHERE customerid=ordcustid
					) AS custname, (
						SELECT statusdesc
						FROM [|PREFIX|]order_status
						WHERE statusid=ordstatus
					) AS ordstatustext
				FROM [|PREFIX|]orders
				WHERE ordcustid='".(int)$customerId."' AND orderid='".(int)$orderId."' AND deleted = 0
			";
			$result = $GLOBALS['ISC_CLASS_DB']->query($query);
			$row = $GLOBALS['ISC_CLASS_DB']->fetch($result);
			if(!$row) {
				redirect('account.php?action=view_orders');
			}

			$GLOBALS['DisableReturnButton'] = "";
			if (!gzte11(ISC_LARGEPRINT)) {
				$GLBOALS['DisableReturnButton'] = "none";
			}

			$order = $row;

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

			// Fetch the shipping details for the order
			$query = "
				SELECT *
				FROM [|PREFIX|]order_shipping
				WHERE order_id=".$order['orderid'];
			$result = $GLOBALS['ISC_CLASS_DB']->query($query);
			while($shipping = $GLOBALS['ISC_CLASS_DB']->fetch($result)) {
				$addresses[$shipping['order_address_id']]['shipping'] = $shipping;
			}

			$GLOBALS['OrderComments'] = '';
			if($row['ordcustmessage'] != '') {
				$GLOBALS['OrderComments'] = nl2br(isc_html_escape($row['ordcustmessage']));
			}
			else {
				$GLOBALS['HideOrderComments'] = 'display: none';
			}

			if(OrderIsComplete($row['ordstatus'])) {
				if (!gzte11(ISC_LARGEPRINT)) {
					$GLOBALS['DisableReturnButton'] = "none";
				}

				if ($row['ordstatus'] == 4 || GetConfig('EnableReturns') == 0) {
					$GLOBALS['DisableReturnButton'] = "none";
				}

				$GLOBALS['HideOrderStatus'] = "none";
				$orderComplete = true;
			}
			else {
				$GLOBALS['HideOrderStatus'] = '';
				$GLOBALS['OrderStatus'] = $row['ordstatustext'];
				$GLOBALS['DisableReturnButton'] = "none";
				$orderComplete = false;
			}

			// Hide print order invoive if it's a incomplete order
			$GLOBALS['ShowOrderActions'] = '';
			if(!$row['ordstatus']) {
				$GLOBALS['ShowOrderActions'] = 'display:none';
			}

			$GLOBALS['OrderDate'] = isc_date(GetConfig('ExtendedDisplayDateFormat'), $row['orddate']);

			$GLOBALS['OrderTotal'] = CurrencyConvertFormatPrice($row['total_inc_tax'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);

			// Format the billing address
			$GLOBALS['ShipFullName'] = isc_html_escape($row['ordbillfirstname'].' '.$row['ordbilllastname']);
			$GLOBALS['ShipCompany'] = '';
			if($row['ordbillcompany']) {
				$GLOBALS['ShipCompany'] = '<br />'.isc_html_escape($row['ordbillcompany']);
			}

			$GLOBALS['ShipAddressLines'] = isc_html_escape($row['ordbillstreet1']);

			if ($row['ordbillstreet2'] != "") {
				$GLOBALS['ShipAddressLines'] .= '<br />' . isc_html_escape($row['ordbillstreet2']);
			}

			$GLOBALS['ShipSuburb'] = isc_html_escape($row['ordbillsuburb']);
			$GLOBALS['ShipState'] = isc_html_escape($row['ordbillstate']);
			$GLOBALS['ShipZip'] = isc_html_escape($row['ordbillzip']);
			$GLOBALS['ShipCountry'] = isc_html_escape($row['ordbillcountry']);
			$GLOBALS['ShipPhone'] = "";
			$GLOBALS['BillingAddress'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AddressLabel");

			// Is there a shipping address, or is it a digital download?
			if ($order['ordisdigital']) {
				$GLOBALS['HideSingleShippingAddress'] = 'display: none';
			}
			else if ($order['shipping_address_count'] > 1) {
				$GLOBALS['ShippingAddress'] = GetLang('OrderWillBeShippedToMultipleAddresses');
				$GLOBALS['HideItemDetailsHeader'] = 'display:none;';
			}
			else {
				$shippingAddress = current($addresses);
				$GLOBALS['ShipFullName'] = isc_html_escape($shippingAddress['first_name'].' '.$shippingAddress['last_name']);

				$GLOBALS['ShipCompany'] = '';
				if($shippingAddress['company']) {
					$GLOBALS['ShipCompany'] = '<br />'.isc_html_escape($shippingAddress['company']);
				}

				$GLOBALS['ShipAddressLines'] = isc_html_escape($shippingAddress['address_1']);

				if ($shippingAddress['address_2'] != "") {
					$GLOBALS['ShipAddressLines'] .= '<br />' . isc_html_escape($shippingAddress['address_2']);
				}

				$GLOBALS['ShipSuburb'] = isc_html_escape($shippingAddress['city']);
				$GLOBALS['ShipState'] = isc_html_escape($shippingAddress['state']);
				$GLOBALS['ShipZip'] = isc_html_escape($shippingAddress['zip']);
				$GLOBALS['ShipCountry'] = isc_html_escape($shippingAddress['country']);

				$GLOBALS['ShipPhone'] = "";
				$GLOBALS['ShippingAddress'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AddressLabel");
			}

			$itemTotalColumn = 'total_ex_tax';
			if(getConfig('taxDefaultTaxDisplayOrders') == TAX_PRICES_DISPLAY_INCLUSIVE) {
				$itemTotalColumn = 'total_inc_tax';
			}

			$GLOBALS['OrderTotalRows'] = '';
			$totalRows = getOrderTotalRows($order);
			foreach($totalRows as $id => $totalRow) {
				$GLOBALS['ISC_CLASS_TEMPLATE']->assign('label', $totalRow['label']);
				$GLOBALS['ISC_CLASS_TEMPLATE']->assign('classNameAppend', ucfirst($id));
				$value = currencyConvertFormatPrice(
					$totalRow['value'],
					$row['ordcurrencyid'],
					$row['ordcurrencyexchangerate']
				);
				$GLOBALS['ISC_CLASS_TEMPLATE']->assign('value', $value);
				$GLOBALS['OrderTotalRows'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->getSnippet('AccountOrderTotalRow');
			}

			$OrderProducts = array();
			$ProductIds = array();
			// Load up the items in this order
			$query = "
				SELECT
					o.*,
					op.*,
					oa.address_1,
					oa.address_2,
					oa.city,
					oa.zip,
					oa.country,
					oa.state,
					p.productid,
					p.prodpreorder,
					p.prodreleasedate,
					p.prodpreordermessage
				FROM
					[|PREFIX|]orders o
					LEFT JOIN [|PREFIX|]order_products op ON op.orderorderid
					LEFT JOIN [|PREFIX|]products p ON p.productid = op.ordprodid
					LEFT JOIN [|PREFIX|]order_addresses oa ON oa.`id` = op.order_address_id
				WHERE
					orderorderid = " . (int)$order['orderid'] ."
				ORDER BY
					op.order_address_id";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);

			//check if products are reorderable
			while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$OrderProducts[$row['orderprodid']] = $row;
				$ProductIds[] = $row['ordprodid'];
			}

			$UnreorderableProducts = $this->GetUnreorderableProducts($OrderProducts, $ProductIds);

			// for grouping of shipping addresses in template output
			$previousAddressId = null;
			$destinationCounter = 0;

			foreach ($OrderProducts as $row) {
				if ($count++ % 2 != 0) {
					$GLOBALS['ItemClass'] = "OrderItem2";
				} else {
					$GLOBALS['ItemClass'] = "OrderItem1";
				}

				$GLOBALS['OrderProductId'] = $row['orderprodid'];
				$GLOBALS['DisableReorder'] = '';

				$GLOBALS['ReorderMessage'] = "";
				$GLOBALS['HideItemMessage'] = 'display:none;';
				if(isset($UnreorderableProducts[$row['orderprodid']])) {
					$GLOBALS['DisableReorder'] = 'Disabled';
					$GLOBALS['ReorderMessage'] = $UnreorderableProducts[$row['orderprodid']];
					if(isset($_REQUEST['reorder']) && $_REQUEST['reorder']==1) {
						$GLOBALS['HideItemMessage'] = '';
					}
				}

				$GLOBALS['Qty'] = (int) $row['ordprodqty'];
				$GLOBALS['Name'] = isc_html_escape($row['ordprodname']);
				$GLOBALS['EventDate'] = '';

				if ($row['ordprodeventdate'] != 0) {
					$GLOBALS['EventDate'] = $row['ordprodeventname'] . ': '. isc_date('M jS Y', $row['ordprodeventdate']);
				}

				// Does the product still exist or has it been deleted?
				$prod_name = GetProdNameById($row['ordprodid']);

				if ($prod_name == "" && $row['ordprodtype'] == 'giftcertificate') {
					$GLOBALS['Link'] = "javascript:product_giftcertificate()";
					$GLOBALS['Target'] = "";
				}else if ($prod_name == "") {
					$GLOBALS['Link'] = "javascript:product_removed()";
					$GLOBALS['Target'] = "";
				}
				else {
					$GLOBALS['Link'] = ProdLink(GetProdNameById($row['ordprodid']));
					$GLOBALS['Target'] = "_blank";
				}

				$GLOBALS['DownloadsLink'] = '';
				if ($row['ordprodtype'] == "digital" && $orderComplete) {
					$GLOBALS['DownloadItemEncrypted'] = $this->EncryptDownloadKey($row['orderprodid'], $row['ordprodid'], $row['orderorderid'], $row['ordtoken']);
					$GLOBALS['DownloadsLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AccountOrderItemDownloadLink");
				}

				$GLOBALS['Refunded'] = '';
				$GLOBALS['StrikeEnd'] = '';
				$GLOBALS['StrikeStart'] = '';

				if ($row['ordprodrefunded'] > 0) {
					if ($row['ordprodrefunded'] == $row['ordprodqty']) {
						$GLOBALS['StrikeStart'] = "<s>";
						$GLOBALS['StrikeEnd'] = "</s>";
						$GLOBALS['Refunded'] = '<span class="Refunded">'.GetLang('OrderProductRefunded').'</span>';
					}
					else {
						$GLOBALS['Refunded'] = '<span class="Refunded">'.sprintf(GetLang('OrderProductsRefundedX'), $row['ordprodrefunded']).'</span>';
					}
				}

				$GLOBALS['Price'] = CurrencyConvertFormatPrice(
					$row[$itemTotalColumn],
					$order['ordcurrencyid'],
					$order['ordcurrencyexchangerate']
				);

				// Were there one or more options selected?
				$GLOBALS['ProductOptions'] = '';
				if($row['ordprodoptions'] != '') {
					$options = @unserialize($row['ordprodoptions']);
					if(!empty($options)) {
						$GLOBALS['ProductOptions'] = "<br /><small class='OrderItemOptions'>(";
						$comma = '';
						foreach($options as $name => $value) {
							$GLOBALS['ProductOptions'] .= $comma.isc_html_escape($name).": ".isc_html_escape($value);
							$comma = ', ';
						}
						$GLOBALS['ProductOptions'] .= ")</small>";
					}
				}

				if($row['ordprodwrapname']) {
					$GLOBALS['GiftWrappingName'] = isc_html_escape($row['ordprodwrapname']);
					$GLOBALS['HideWrappingOptions'] = '';
				}
				else {
					$GLOBALS['GiftWrappingName'] = '';
					$GLOBALS['HideWrappingOptions'] = 'display: none';
				}

				$GLOBALS['HideExpectedReleaseDate'] = 'display:none;';
				$GLOBALS['ExpectedReleaseDate'] = '';

				if ($row['prodpreorder']) {
					if ($row['prodreleasedate']) {
						$message = $row['prodpreordermessage'];
						if (!$message) {
							$message = GetConfig('DefaultPreOrderMessage');
						}
						$GLOBALS['ExpectedReleaseDate'] = '(' . str_replace('%%DATE%%', isc_date(GetConfig('DisplayDateFormat'), $row['prodreleasedate']), $message) . ')';
					} else {
						$GLOBALS['ExpectedReleaseDate'] = '(' . GetLang('PreOrderProduct') . ')';
					}
					$GLOBALS['HideExpectedReleaseDate'] = '';
				}

				$GLOBALS['ItemShippingRow'] = '';
				if ($order['shipping_address_count'] > 1 && ($previousAddressId != $row['order_address_id'])) {
					$destinationCounter++;

					$GLOBALS['Destination_Number'] = GetLang('Destination_Number', array('number' => $destinationCounter));

					$addressLine = array_filter(array(
						$row['address_1'],
						$row['address_2'],
						$row['city'],
						$row['state'],
						$row['zip'],
						$row['country'],
					));

					$GLOBALS['ItemShippingRow_AddressLine'] = Store_String::rightTruncate(implode(', ', $addressLine), 60);

					$GLOBALS['ItemShippingRow'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('AccountOrderItemShippingRow');
				}

				$GLOBALS['SNIPPETS']['AccountOrderItemRow'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AccountOrderItemRow");
				$previousAddressId = $row['order_address_id'];
			}

			$GLOBALS['ISC_CLASS_TEMPLATE']->SetPageTitle(sprintf("%s - %s%d", GetConfig('StoreName'), GetLang('OrderIdHash'), $orderId));
			$GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("account_order");
			$GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
		}
예제 #2
0
 /**
  * Handle a change of financial state of an order
  *
  * @param array $data The google request array
  *
  * @return void
  **/
 private function HandleFinancialStateChange($data)
 {
     $googleid = $data['google-order-number']['VALUE'];
     $orderid = $this->GetOrderIdByGoogleId($googleid);
     if ($orderid === false) {
         return;
     }
     $new_financial_state = $data['new-financial-order-state']['VALUE'];
     switch ($new_financial_state) {
         case 'REVIEWING':
             UpdateOrderStatus($orderid, ORDER_STATUS_PENDING, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_PENDING)));
             break;
         case 'CHARGEABLE':
             UpdateOrderStatus($orderid, ORDER_STATUS_AWAITING_PAYMENT, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_AWAITING_PAYMENT)));
             break;
         case 'CHARGING':
             // We don't need to do anything on our end when Google is midway through charging an order
             break;
         case 'CHARGED':
             $order = GetOrder($orderid, false);
             if (!OrderIsComplete($order['ordstatus'])) {
                 $this->module->debuglog($order);
                 if ($order['ordisdigital'] == 1) {
                     UpdateOrderStatus($orderid, ORDER_STATUS_COMPLETED, true, true);
                     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_COMPLETED)));
                 } else {
                     $status = $this->module->GetValue('orderchargestatus');
                     if (!$status) {
                         $status = ORDER_STATUS_AWAITING_FULFILLMENT;
                     }
                     UpdateOrderStatus($orderid, $status, false, true);
                     $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById($status)));
                 }
             }
             break;
         case 'PAYMENT_DECLINED':
             UpdateOrderStatus($orderid, ORDER_STATUS_DECLINED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_DECLINED)));
             break;
         case 'CANCELLED':
             UpdateOrderStatus($orderid, ORDER_STATUS_CANCELLED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_CANCELLED)));
             break;
         case 'CANCELLED_BY_GOOGLE':
             UpdateOrderStatus($orderid, ORDER_STATUS_CANCELLED, false, true);
             $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess($this->logtype, sprintf(GetLang('GoogleCheckoutOrderStatusUpdated'), $orderid, GetOrderStatusById(ORDER_STATUS_CANCELLED)));
             break;
         default:
             break;
     }
 }
예제 #3
0
/**
 * Completes a pending order and marks it's status as whatever it should be next.
 * This function will process any payments, capture amounts from gateways, increase
 * # sold for each product in the order, etc.
 *
 * @param string The pending order token.
 * @param int The status to set the completed order to.
 * @return boolean True if successful, false on failure.
 */
function CompletePendingOrder($pendingOrderToken, $status, $sendInvoice = true)
{
    $orderData = LoadPendingOrdersByToken($pendingOrderToken, true);
    if ($orderData === false) {
        return false;
    }
    $processedStoreCredit = false;
    $processedGiftCertificates = false;
    $orderStoreCredit = 0;
    $orderTotalAmount = 0;
    // Sum up our total amount and store credit
    foreach ($orderData['orders'] as $order) {
        if ($order['ordstatus'] != 0) {
            continue;
        }
        $orderStoreCredit += $order['ordstorecreditamount'];
        $orderTotalAmount += $order['ordtotalamount'];
    }
    foreach ($orderData['orders'] as $order) {
        // Wait, was the order already complete? Then we don't do anything
        if ($order['ordstatus'] != 0) {
            continue;
        }
        // If this order is digital, and the status is awaiting fulfillment, there's nothing
        // to actually fulfill, so set it to completed.
        if ($order['ordisdigital'] && $status == ORDER_STATUS_AWAITING_FULFILLMENT) {
            $status = ORDER_STATUS_COMPLETED;
        }
        // Don't email the customer if this order was declined
        if ($status != ORDER_STATUS_DECLINED) {
            if ($sendInvoice && !EmailInvoiceToCustomer($order['orderid'], $status)) {
                $GLOBALS['HideError'] = "";
                $GLOBALS['ErrorMessage'] = GetLang('ErroSendingInvoiceEmail');
                $GLOBALS['HideSuccess'] = "none";
            }
            // Are we updating the inventory levels when an order has been placed?
            if (GetConfig('UpdateInventoryLevels') == 1) {
                DecreaseInventoryFromOrder($order['orderid']);
            }
        }
        // If this order now complete, we need to activate any gift certificates
        if (OrderIsComplete($status)) {
            $GLOBALS['ISC_CLASS_GIFTCERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
            $GLOBALS['ISC_CLASS_GIFTCERTIFICATES']->ActivateGiftCertificates($order['orderid']);
        }
        // If we've had one or more coupons been applied to this order, we now need to increment the number of uses
        $couponIds = array();
        $query = "\n\t\t\tSELECT *\n\t\t\tFROM [|PREFIX|]order_coupons\n\t\t\tWHERE ordcouporderid='" . (int) $order['orderid'] . "'\n\t\t";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        while ($coupon = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $couponIds[] = $coupon['ordcouponid'];
        }
        if (!empty($couponIds)) {
            $couponsUsed = array_unique($couponIds);
            $couponList = implode(",", array_map("intval", $couponsUsed));
            $query = "\n\t\t\t\tUPDATE [|PREFIX|]coupons\n\t\t\t\tSET couponnumuses=couponnumuses+1\n\t\t\t\tWHERE couponid IN (" . $couponList . ")\n\t\t\t";
            $GLOBALS['ISC_CLASS_DB']->Query($query);
        }
        // If we used store credit on this order, we now need to subtract it from the users account.
        if ($order['ordstorecreditamount'] > 0 && $processedStoreCredit == false) {
            $GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
            $currentCredit = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerStoreCredit($order['ordcustid']);
            $newCredit = $currentCredit - $orderStoreCredit;
            if ($newCredit < 0) {
                $newCredit = 0;
            }
            $updatedCustomer = array('custstorecredit' => $newCredit);
            $GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updatedCustomer, "customerid='" . (int) $order['ordcustid'] . "'");
            $processedStoreCredit = true;
        }
        $extraInfo = @unserialize($order['extrainfo']);
        if (!is_array($extraInfo)) {
            $extraInfo = array();
        }
        // If one or more gift certificates were used we need to apply them to this order and subtract the total
        if ($order['ordgiftcertificateamount'] > 0 && isset($extraInfo['giftcertificates']) && !empty($extraInfo['giftcertificates']) && $processedGiftCertificates == false) {
            $usedCertificates = array();
            $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
            $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($order['orderid'], $orderTotalAmount, $extraInfo['giftcertificates'], $usedCertificates);
            unset($extraInfo['giftcertificates']);
            $processedGiftCertificates = true;
        }
        // If there are one or more digital products in this order then we need to create a record in the order_downloads table
        // for each of them and set the expiry dates
        $query = "\n\t\t\tSELECT ordprodid, ordprodqty\n\t\t\tFROM [|PREFIX|]order_products\n\t\t\tWHERE orderorderid='" . $order['orderid'] . "' AND ordprodtype='digital'\n\t\t";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        $digitalProductIds = array();
        while ($digitalProduct = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $digitalProductIds[$digitalProduct['ordprodid']] = $digitalProduct;
        }
        if (!empty($digitalProductIds)) {
            $query = "\n\t\t\t\tSELECT downloadid, productid, downexpiresafter, downmaxdownloads\n\t\t\t\tFROM [|PREFIX|]product_downloads\n\t\t\t\tWHERE productid IN (" . implode(',', array_keys($digitalProductIds)) . ")\n\t\t\t";
            $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
            while ($digitalDownload = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
                $expiryDate = 0;
                // If this download has an expiry date, set it to now + expiry time
                if ($digitalDownload['downexpiresafter'] > 0) {
                    $expiryDate = time() + $digitalDownload['downexpiresafter'];
                }
                // If they've purchased more than one, we need to give them max downloads X quantity downloads
                $quantity = $digitalProductIds[$digitalDownload['productid']]['ordprodqty'];
                $newDownload = array('orderid' => $order['orderid'], 'downloadid' => $digitalDownload['downloadid'], 'numdownloads' => 0, 'downloadexpires' => $expiryDate, 'maxdownloads' => $digitalDownload['downmaxdownloads'] * $quantity);
                $GLOBALS['ISC_CLASS_DB']->InsertQuery('order_downloads', $newDownload);
            }
        }
        // Now update the order and set the status
        $updatedOrder = array("ordstatus" => $status, "extrainfo" => serialize($extraInfo));
        $GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='" . $order['orderid'] . "'");
    }
    return true;
}
예제 #4
0
파일: orders.php 프로젝트: hungnv0789/vhtm
/**
 * Completes a pending order and marks it's status as whatever it should be next.
 * This function will process any payments, capture amounts from gateways, increase
 * # sold for each product in the order, etc.
 *
 * @param string The pending order token.
 * @param int The status to set the completed order to.
 * @return boolean True if successful, false on failure.
 */
function CompletePendingOrder($pendingOrderToken, $status, $sendInvoice=true)
{
	$orderData = LoadPendingOrdersByToken($pendingOrderToken, true);
	if($orderData === false) {
		return false;
	}

	$processedStoreCredit = false;
	$processedGiftCertificates = false;
	$orderStoreCredit = 0;
	$orderTotalAmount = 0;

	// Flag used to create the customer record but only if atleast one order was successful
	$createCustomer = false;

	// Sum up our total amount and store credit
	foreach ($orderData['orders'] as $order) {
		if ($order['ordstatus'] != 0) {
			continue;
		}

		$orderStoreCredit += $order['ordstorecreditamount'];
		$orderTotalAmount += $order['total_inc_tax'];
	}

	// flag to indicate if we should send notifications? only if the order was previously incomplete and the new status isn't declined/cancelled/refunded
	$sendNotifications = false;

	foreach($orderData['orders'] as $order) {
		$newStatus = $status;

		// Wait, was the order already complete? Then we don't do anything
		if($order['ordstatus'] != ORDER_STATUS_INCOMPLETE) {
			continue;
		}

		// If this order is digital, and the status is awaiting fulfillment, there's nothing
		// to actually fulfill, so set it to completed.
		if($order['ordisdigital'] && $newStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
			$newStatus = ORDER_STATUS_COMPLETED;
		}

		$extraInfo = @unserialize($order['extrainfo']);
		if(!is_array($extraInfo)) {
			$extraInfo = array();
		}

		// only email and update order data (coupons, certificates, store credit etc) if it's not a declined, cancelled or refunded order
		if($newStatus != ORDER_STATUS_DECLINED && $newStatus != ORDER_STATUS_CANCELLED && $newStatus != ORDER_STATUS_REFUNDED) {
			$createCustomer = true;
			$sendNotifications = true;

			if($sendInvoice && !EmailInvoiceToCustomer($order['orderid'], $newStatus)) {
				$GLOBALS['HideError'] = "";
				$GLOBALS['ErrorMessage'] = GetLang('ErroSendingInvoiceEmail');
				$GLOBALS['HideSuccess'] = "none";
			}

			// Are we updating the inventory levels when an order has been placed?
			if(GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($order['orderid']);
			}

			// If this order now complete, we need to activate any gift certificates
			if(OrderIsComplete($newStatus)) {
				$GLOBALS['ISC_CLASS_GIFTCERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
				$GLOBALS['ISC_CLASS_GIFTCERTIFICATES']->ActivateGiftCertificates($order['orderid']);
			}

			// If we've had one or more coupons been applied to this order, we now need to increment the number of uses
			$couponIds = array();
			$query = "
				SELECT *
				FROM [|PREFIX|]order_coupons
				WHERE ordcouporderid='".(int)$order['orderid']."'
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			while($coupon = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$couponIds[] = $coupon['ordcouponid'];
			}
			if(!empty($couponIds)) {
				$couponsUsed = array_unique($couponIds);
				$couponList = implode(",", array_map("intval", $couponsUsed));
				$query = "
					UPDATE [|PREFIX|]coupons
					SET couponnumuses=couponnumuses+1
					WHERE couponid IN (".$couponList.")
				";
				$GLOBALS['ISC_CLASS_DB']->Query($query);

				foreach ($couponIds as $cid) {
					getclass('ISC_COUPON')->updatePerCustomerUsage($cid);
				}
			}

			// If we used store credit on this order, we now need to subtract it from the users account.
			if($order['ordstorecreditamount'] > 0 && $processedStoreCredit == false) {
				$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
				$currentCredit = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerStoreCredit($order['ordcustid']);
				$newCredit = $currentCredit - $orderStoreCredit;
				if($newCredit < 0) {
					$newCredit = 0;
				}
				$updatedCustomer = array(
					'custstorecredit' => $newCredit,
				);
				$GLOBALS['ISC_CLASS_DB']->UpdateQuery('customers', $updatedCustomer, "customerid='".(int)$order['ordcustid']."'");
				$processedStoreCredit = true;
			}

			// If one or more gift certificates were used we need to apply them to this order and subtract the total
			if($order['ordgiftcertificateamount'] > 0 && isset($extraInfo['giftcertificates']) && !empty($extraInfo['giftcertificates']) && $processedGiftCertificates == false) {
				$usedCertificates = array();
				$GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
				$GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($order['orderid'], $orderTotalAmount + $order['ordgiftcertificateamount'], $extraInfo['giftcertificates'], $usedCertificates);
				unset($extraInfo['giftcertificates']);
				$processedGiftCertificates = true;
			}

			// If there are one or more digital products in this order then we need to create a record in the order_downloads table
			// for each of them and set the expiry dates
			$query = "
				SELECT ordprodid, ordprodqty
				FROM [|PREFIX|]order_products
				WHERE orderorderid='".$order['orderid']."' AND ordprodtype='digital'
			";
			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
			$digitalProductIds = array();
			while($digitalProduct = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$digitalProductIds[$digitalProduct['ordprodid']] = $digitalProduct;
			}

			if(!empty($digitalProductIds)) {
				$query = "
					SELECT downloadid, productid, downexpiresafter, downmaxdownloads
					FROM [|PREFIX|]product_downloads
					WHERE productid IN (".implode(',', array_keys($digitalProductIds)).")
				";
				$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
				while($digitalDownload = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
					$expiryDate = 0;

					// If this download has an expiry date, set it to now + expiry time
					if($digitalDownload['downexpiresafter'] > 0) {
						$expiryDate = time() + $digitalDownload['downexpiresafter'];
					}

					// If they've purchased more than one, we need to give them max downloads X quantity downloads
					$quantity = $digitalProductIds[$digitalDownload['productid']]['ordprodqty'];

					$newDownload = array(
						'orderid' => $order['orderid'],
						'downloadid' => $digitalDownload['downloadid'],
						'numdownloads' => 0,
						'downloadexpires' => $expiryDate,
						'maxdownloads' => $digitalDownload['downmaxdownloads'] * $quantity
					);
					$GLOBALS['ISC_CLASS_DB']->InsertQuery('order_downloads', $newDownload);
				}
			}
		}

		// Does a customer account need to be created?
		if(!empty($extraInfo['createAccount'])) {
			createOrderCustomerAccount($order, $extraInfo['createAccount']);
			unset($extraInfo['createAccount']);
		}

		// Now update the order and set the status
		$updatedOrder = array(
			"ordstatus" => $newStatus,
			"extrainfo" => serialize($extraInfo)
		);
		$GLOBALS['ISC_CLASS_DB']->UpdateQuery("orders", $updatedOrder, "orderid='".$order['orderid']."'");
	}

	if($sendNotifications) {
		// Trigger all active new order notification methods
		SendOrderNotifications($pendingOrderToken);

		// Do we need to add them to a Interspire Email Marketer mailing list?
		SubscribeCustomerToLists($pendingOrderToken);

		// Update the current uses of each rule
		$quote = getCustomerQuote();
		$appliedRules = array_keys(getCustomerQuote()->getAppliedDiscountRules());
		if(!empty($appliedRules)) {
			require_once ISC_BASE_PATH.'/lib/rule.php';
			updateRuleUses($appliedRules);
		}
	}

	// Empty the users cart and kill the checkout process
	EmptyCartAndKillCheckout();

	return true;
}
예제 #5
0
 /**
  *	Show the details of an order and allow them to print an invoice
  */
 private function ViewOrderDetails()
 {
     $GLOBALS['SNIPPETS']['AccountOrderItemRow'] = "";
     $count = 0;
     if (isset($_GET['order_id']) && is_numeric($_GET['order_id'])) {
         $GLOBALS['FlassMessage'] = GetFlashMessageBoxes();
         // Retrieve the completed order that matches the customers user id
         $order_id = (int) $_GET['order_id'];
         $GLOBALS['OrderId'] = $order_id;
         $query = sprintf("select *, (select concat(custconfirstname, ' ', custconlastname) from [|PREFIX|]customers where customerid=ordcustid) as custname, (select statusdesc from [|PREFIX|]order_status where statusid=ordstatus) as ordstatustext from [|PREFIX|]orders where ordcustid='%d' and orderid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId()), $order_id);
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $GLOBALS['DisableReturnButton'] = "";
         if (!gzte11(ISC_LARGEPRINT)) {
             $GLBOALS['DisableReturnButton'] = "none";
         }
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result) == 0) {
             // No order or the user doesn't own the order
             $this->ViewOrders();
         } else {
             // The order is valid, display it
             $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
             $order = $row;
             $GLOBALS['OrderComments'] = '';
             if ($row['ordcustmessage'] != '') {
                 $GLOBALS['OrderComments'] = nl2br(isc_html_escape($row['ordcustmessage']));
             } else {
                 $GLOBALS['HideOrderComments'] = 'display: none';
             }
             if (OrderIsComplete($row['ordstatus'])) {
                 if (!gzte11(ISC_LARGEPRINT)) {
                     $GLOBALS['DisableReturnButton'] = "none";
                 }
                 if ($row['ordstatus'] == 4 || GetConfig('EnableReturns') == 0) {
                     $GLOBALS['DisableReturnButton'] = "none";
                 }
                 $GLOBALS['HideOrderStatus'] = "none";
                 $orderComplete = true;
             } else {
                 $GLOBALS['HideOrderStatus'] = '';
                 $GLOBALS['OrderStatus'] = $row['ordstatustext'];
                 $GLOBALS['DisableReturnButton'] = "none";
                 $orderComplete = false;
             }
             //hide print order invoive if it's a incomplete order
             $GLOBALS['ShowOrderActions'] = '';
             if (!$row['ordstatus']) {
                 $GLOBALS['ShowOrderActions'] = 'display:none';
             }
             $GLOBALS['OrderDate'] = isc_date(GetConfig('ExtendedDisplayDateFormat'), $row['orddate']);
             $GLOBALS['Recipient'] = isc_html_escape($row['custname']);
             $GLOBALS['OrderTotal'] = CurrencyConvertFormatPrice($row['ordtotalamount'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
             // Format the billing address
             $GLOBALS['ShipFullName'] = isc_html_escape($row['ordbillfirstname'] . ' ' . $row['ordbilllastname']);
             $GLOBALS['ShipCompany'] = '';
             if ($row['ordbillcompany']) {
                 $GLOBALS['ShipCompany'] = '<br />' . isc_html_escape($row['ordbillcompany']);
             }
             $GLOBALS['ShipAddressLine1'] = isc_html_escape($row['ordbillstreet1']);
             if ($row['ordbillstreet2'] != "") {
                 $GLOBALS['ShipAddressLine2'] = isc_html_escape($row['ordbillstreet2']);
             } else {
                 $GLOBALS['ShipAddressLine2'] = '';
             }
             $GLOBALS['ShipSuburb'] = isc_html_escape($row['ordbillsuburb']);
             $GLOBALS['ShipState'] = isc_html_escape($row['ordbillstate']);
             $GLOBALS['ShipZip'] = isc_html_escape($row['ordbillzip']);
             $GLOBALS['ShipCountry'] = isc_html_escape($row['ordbillcountry']);
             $GLOBALS['ShipPhone'] = "";
             $GLOBALS['BillingAddress'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AddressLabel");
             // Is there a shipping address, or is it a digital download?
             if ($row['ordshipfirstname'] == "") {
                 $GLOBALS['ShippingAddress'] = GetLang('NA');
             } else {
                 $GLOBALS['ShipFullName'] = isc_html_escape($row['ordshipfirstname'] . ' ' . $row['ordshiplastname']);
                 $GLOBALS['ShipCompany'] = '';
                 if ($row['ordshipcompany']) {
                     $GLOBALS['ShipCompany'] = '<br />' . isc_html_escape($row['ordshipcompany']);
                 }
                 $GLOBALS['ShipAddressLine1'] = isc_html_escape($row['ordshipstreet1']);
                 if ($row['ordshipstreet2'] != "") {
                     $GLOBALS['ShipAddressLine2'] = isc_html_escape($row['ordshipstreet2']);
                 } else {
                     $GLOBALS['ShipAddressLine2'] = '';
                 }
                 $GLOBALS['ShipSuburb'] = isc_html_escape($row['ordshipsuburb']);
                 $GLOBALS['ShipState'] = isc_html_escape($row['ordshipstate']);
                 $GLOBALS['ShipZip'] = isc_html_escape($row['ordshipzip']);
                 $GLOBALS['ShipCountry'] = isc_html_escape($row['ordshipcountry']);
                 $GLOBALS['ShipPhone'] = "";
                 $GLOBALS['ShippingAddress'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AddressLabel");
             }
             $GLOBALS['OrderSubTotal'] = CurrencyConvertFormatPrice($row['ordsubtotal'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate']);
             $GLOBALS['ShippingCost'] = CurrencyConvertFormatPrice($row['ordshipcost'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate']);
             if ($row['ordhandlingcost'] == 0) {
                 $GLOBALS['HideHandling'] = "none";
             } else {
                 $GLOBALS['HideHandling'] = "";
                 $GLOBALS['HandlingCost'] = CurrencyConvertFormatPrice($row['ordhandlingcost'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate']);
             }
             // Is there any sales tax?
             if ($row['ordtaxtotal'] > 0) {
                 if ($row['ordtaxname']) {
                     $GLOBALS['SalesTaxName'] = isc_html_escape($row['ordtaxname']);
                 } else {
                     $GLOBALS['SalesTaxName'] = GetLang('InvoiceSalesTax');
                 }
                 if ($row['ordtotalincludestax']) {
                     $GLOBALS['HideTax'] = 'none';
                     $GLOBALS['SalesTaxName'] .= ' ' . GetLang('IncludedInTotal');
                 } else {
                     $GLOBALS['HideTaxIncluded'] = 'none';
                 }
                 $GLOBALS['TaxCost'] = CurrencyConvertFormatPrice($row['ordtaxtotal'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate']);
             } else {
                 $GLOBALS['HideTax'] = "none";
                 $GLOBALS['HideTaxIncluded'] = 'none';
             }
             $OrderProducts = array();
             $ProductIds = array();
             // Load up the items in this order
             $query = sprintf("select * from [|PREFIX|]order_products p, [|PREFIX|]orders o where p.orderorderid = o.orderid AND orderorderid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($order_id));
             $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
             $wrappingTotal = 0;
             //check if products are reorderable
             while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
                 $OrderProducts[$row['orderprodid']] = $row;
                 $ProductIds[] = $row['ordprodid'];
             }
             $UnreorderableProducts = $this->GetUnreorderableProducts($OrderProducts, $ProductIds);
             foreach ($OrderProducts as $row) {
                 if ($count++ % 2 != 0) {
                     $GLOBALS['ItemClass'] = "OrderItem2";
                 } else {
                     $GLOBALS['ItemClass'] = "OrderItem1";
                 }
                 $GLOBALS['OrderProductId'] = $row['orderprodid'];
                 $GLOBALS['DisableReorder'] = '';
                 $GLOBALS['ReorderMessage'] = "";
                 $GLOBALS['HideItemMessage'] = 'display:none;';
                 if (isset($UnreorderableProducts[$row['orderprodid']])) {
                     $GLOBALS['DisableReorder'] = 'Disabled';
                     $GLOBALS['ReorderMessage'] = $UnreorderableProducts[$row['orderprodid']];
                     if (isset($_REQUEST['reorder']) && $_REQUEST['reorder'] == 1) {
                         $GLOBALS['HideItemMessage'] = '';
                     }
                 }
                 $GLOBALS['Qty'] = (int) $row['ordprodqty'];
                 $GLOBALS['Name'] = isc_html_escape($row['ordprodname']);
                 $GLOBALS['EventDate'] = '';
                 if ($row['ordprodeventdate'] != 0) {
                     $GLOBALS['EventDate'] = $row['ordprodeventname'] . ': ' . isc_date('M jS Y', $row['ordprodeventdate']);
                 }
                 // Does the product still exist or has it been deleted?
                 $prod_name = GetProdNameById($row['ordprodid']);
                 if ($prod_name == "") {
                     $GLOBALS['Link'] = "javascript:product_removed()";
                     $GLOBALS['Target'] = "";
                 } else {
                     $GLOBALS['Link'] = ProdLink(GetProdNameById($row['ordprodid']));
                     $GLOBALS['Target'] = "_blank";
                 }
                 $GLOBALS['DownloadsLink'] = '';
                 if ($row['ordprodtype'] == "digital" && $orderComplete) {
                     $GLOBALS['DownloadItemEncrypted'] = $this->EncryptDownloadKey($row['orderprodid'], $row['ordprodid'], $row['orderorderid'], $row['ordtoken']);
                     $GLOBALS['DownloadsLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AccountOrderItemDownloadLink");
                 }
                 $GLOBALS['StrikeStart'] = $GLOBALS['StrikeEnd'] = $GLOBALS['Refunded'] = '';
                 if ($row['ordprodrefunded'] > 0) {
                     if ($row['ordprodrefunded'] == $row['ordprodqty']) {
                         $GLOBALS['StrikeStart'] = "<s>";
                         $GLOBALS['StrikeEnd'] = "</s>";
                         $GLOBALS['Refunded'] = '<span class="Refunded">' . GetLang('OrderProductRefunded') . '</span>';
                     } else {
                         $GLOBALS['Refunded'] = '<span class="Refunded">' . sprintf(GetLang('OrderProductsRefundedX'), $row['ordprodrefunded']) . '</span>';
                     }
                 }
                 $itemTotal = $row['ordprodcost'] * ($row['ordprodqty'] - $row['ordprodrefunded']);
                 $GLOBALS['Price'] = CurrencyConvertFormatPrice($itemTotal, $order['ordcurrencyid'], $order['ordcurrencyexchangerate']);
                 if ($GLOBALS['Price'] === 0) {
                     $GLOBALS['Price'] = "0.00";
                 }
                 // Were there one or more options selected?
                 $GLOBALS['ProductOptions'] = '';
                 if ($row['ordprodoptions'] != '') {
                     $options = @unserialize($row['ordprodoptions']);
                     if (!empty($options)) {
                         $GLOBALS['ProductOptions'] = "<br /><small class='OrderItemOptions'>(";
                         $comma = '';
                         foreach ($options as $name => $value) {
                             $GLOBALS['ProductOptions'] .= $comma . isc_html_escape($name) . ": " . isc_html_escape($value);
                             $comma = ', ';
                         }
                         $GLOBALS['ProductOptions'] .= ")</small>";
                     }
                 }
                 if ($row['ordprodwrapcost'] > 0) {
                     $wrappingTotal += $row['ordprodwrapcost'] * $row['ordprodqty'];
                 }
                 if ($row['ordprodwrapname']) {
                     $GLOBALS['GiftWrappingName'] = isc_html_escape($row['ordprodwrapname']);
                     $GLOBALS['HideWrappingOptions'] = '';
                 } else {
                     $GLOBALS['GiftWrappingName'] = '';
                     $GLOBALS['HideWrappingOptions'] = 'display: none';
                 }
                 $GLOBALS['SNIPPETS']['AccountOrderItemRow'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("AccountOrderItemRow");
             }
             if ($wrappingTotal > 0) {
                 $GLOBALS['GiftWrappingTotal'] = CurrencyConvertFormatPrice($wrappingTotal, $order['ordcurrencyid'], $order['ordcurrencyexchangerate']);
             } else {
                 $GLOBALS['HideGiftWrappingTotal'] = 'display: none';
             }
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetPageTitle(sprintf("%s - %s%d", GetConfig('StoreName'), GetLang('OrderIdHash'), $order_id));
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("account_order");
             $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
         }
     } else {
         $this->ViewOrders();
     }
 }