public function __get($strName)
 {
     switch ($strName) {
         case 'Price':
             return $this->GetPrice(TaxCode::GetDefault(), $this->product->tax_status_id);
         case 'PriceExclusive':
             return $this->GetPrice(TaxCode::GetDefault(), $this->product->tax_status_id, true);
         default:
             return parent::__get($strName);
     }
 }
Esempio n. 2
0
 public static function VerifyAnyDestination()
 {
     $objAnyDest = Destination::model()->findByAttributes(array('country' => null, 'state' => null));
     if (!$objAnyDest instanceof Destination) {
         $objTax = TaxCode::GetNoTaxCode();
         if ($objTax) {
             $objNewAny = new Destination();
             $objNewAny->country = null;
             $objNewAny->state = null;
             $objNewAny->zipcode1 = '';
             $objNewAny->zipcode2 = '';
             $objNewAny->taxcode = $objTax->lsid;
             $objNewAny->save();
         }
     }
 }
Esempio n. 3
0
 /**
  * For a product, returns tax rate for all defined destinations
  * Useful for RSS exports
  * @return TaxGrid[]
  */
 public function GetTaxRateGrid()
 {
     $arrGrid = array();
     $intTaxStatus = $this->tax_status_id;
     $objStatus = TaxStatus::LoadByLS($intTaxStatus);
     $objDestinations = Destination::model()->findAll();
     foreach ($objDestinations as $objDestination) {
         //Because of differences in how Google defines zip code ranges, we can't convert our ranges
         //to theirs. At this time we won't be able to support zip code ranges
         if (!is_null($objDestination->country) && $objDestination->Zipcode1 == '') {
             $objTaxCode = TaxCode::LoadByLS($objDestination->taxcode);
             //print_r($objTaxCode);
             $fltRate = 0.0;
             for ($x = 1; $x <= 5; $x++) {
                 $statusstring = "tax" . $x . "_status";
                 $codestring = "tax" . $x . "_rate";
                 if ($objStatus->{$statusstring} == 0) {
                     $fltRate += $objTaxCode->{$codestring};
                 }
             }
             //Our four elements
             $strCountry = Country::CodeById($objDestination->country);
             if (!is_null($objDestination->state)) {
                 $strState = State::CodeById($objDestination->state);
             } else {
                 $strState = '';
             }
             //$fltRate -- built above
             $strTaxShip = Yii::app()->params['SHIPPING_TAXABLE'] == '1' ? "y" : "n";
             $arrGrid[] = array($strCountry, $strState, $fltRate, $strTaxShip);
         }
     }
     return $arrGrid;
 }
Esempio n. 4
0
 /**
  * Returns an indexed array of hypothetical cart scenarios ordered by the
  * shipping price of the scenario from lowest to highest.
  *
  * TODO: WS-3481 Refactor this to use Cart instead of ShoppingCart.
  * TODO: WS-3676 Refactor Shipping::getCartScenarios to implicitly modify the cart and the checkoutform
  *
  * @param $checkoutForm
  * @return array Indexed array of cart scenarios where each cart scenario
  * is an associative array with the following keys:
  *    formattedCartSubtotal - The formatted subtotal of the cart for this
  *        scenario,
  *    formattedCartTax - The formatted amount of tax on the cart,
  *    formattedCartTotal - The formatted total price of the cart,
  *    formattedShippingPrice - The formatted shipping price,
  *    module - The internal module string identifier (xlsws_module.module).
  *    priorityIndex - An index for the shipping priority (unique per provider),
  *    priorityLabel - A label for the shipping priority,
  *    providerId - The xlsws_module.id of the shipping provider,
  *    providerLabel - A label for the shipping provider,
  *    shippingLabel - A label describing the provider and priority,
  *    shippingPrice - The shipping price for this priortity,
  *    shoppingCart - An instance of ShoppingCart with attributes set for
  *        this scenario,
  *    sortOrder - The xlsws_module.sort_order.
  *    cartItems - The individual cartItem objects for the scenario
  *
  * Formatted currencies are formatted according to the user's language.
  *
  * @throws Exception If $checkoutForm does not contain enough details to
  * get shipping rates.
  * @throws Exception If no shipping providers are enabled (via
  * Shipping::getAvailableShippingProviders).
  * @throws Exception If no shipping providers are able to provide rates
  * (via Shipping::addRatesToShippingProviders).
  */
 public static function getCartScenarios($checkoutForm)
 {
     $logLevel = 'info';
     if (CPropertyValue::ensureBoolean(_xls_get_conf('DEBUG_SHIPPING', false)) === true) {
         $logLevel = 'error';
     }
     // TODO: This, and the setting of hasTaxModeChanged, should be
     // refactored out of this method. It would be better if
     // getCartScenarios did not have side-effects.
     Yii::app()->shoppingcart->setTaxCodeByCheckoutForm($checkoutForm);
     // We are going to modify the shopping cart and save the intermediate
     // values so we need to save the current value.
     $savedTaxId = Yii::app()->shoppingcart->tax_code_id;
     $cart = Yii::app()->shoppingcart->getModel();
     // The call to setTaxCodeByCheckoutForm() on the shopping cart will call
     // recalculateAndSave(). That call is going to add taxes on shipping by
     // calling updateTaxShipping(). The first run will have the correct values.
     // On later runs, we will have taxes set in the shopping cart and add more
     // when we call updateTaxShipping(). Plus, we used to also make a call to
     // recalculateAndSave() while going through the shipping providers. Then we
     // would call AddTaxes() which would add taxes on top of taxes.
     $cart->updateTaxExclusive();
     $savedStorePickup = $cart->blnStorePickup;
     // Get the list of shipping modules.
     $arrShippingProvider = self::getAvailableShippingProviders($checkoutForm);
     Yii::log('Got shipping modules ' . print_r($arrShippingProvider, true), $logLevel, 'application.' . __CLASS__ . '.' . __FUNCTION__);
     // Run each shipping module to get the rates.
     $arrShippingProvider = self::addRatesToShippingProviders($arrShippingProvider);
     // Compile each shipping providers rates into an array of "cart scenarios".
     // Each cart scenario is an associative array containing details about
     // the cart as it would be if a particular shipping option were chosen.
     $arrCartScenario = array();
     // The shopping cart variable has to be set in case we encounter
     // a case where the arrShippingProvider is empty.
     $shoppingCart = Yii::app()->shoppingcart->getModel();
     $savedStorePickup = false;
     foreach ($arrShippingProvider as $shippingModuleId => $shippingProvider) {
         // Since Store Pickup means paying local taxes, set the cart so our
         // scenarios work out.
         if ($shippingProvider['component']->IsStorePickup === true) {
             Yii::app()->shoppingcart->tax_code_id = TaxCode::getDefaultCode();
             $cart->blnStorePickup = true;
         } else {
             Yii::app()->shoppingcart->tax_code_id = $savedTaxId;
             $cart->blnStorePickup = false;
         }
         // Get the "shipping" product, which may vary from module to module.
         $strShippingProduct = $shippingProvider['component']->LsProduct;
         Yii::log('Shipping Product for ' . $shippingProvider['module']->module . ' is ' . $strShippingProduct, $logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__);
         if (Yii::app()->params['SHIPPING_TAXABLE'] == 1) {
             // When shipping is taxable we need to find the tax code on the actual shipping product.
             $objShipProduct = Product::LoadByCode($strShippingProduct);
             if ($objShipProduct instanceof Product === true) {
                 $intShipProductLsid = $objShipProduct->taxStatus->lsid;
             } else {
                 // We may not find a shipping product in cloud mode, so
                 // just use -1 which skips statuses.
                 $intShipProductLsid = -1;
             }
         }
         foreach ($shippingProvider['rates'] as $priorityIndex => $priority) {
             $priorityPrice = $priority['price'];
             $includeTaxInShippingPrice = false;
             $shippingTaxValues = array();
             if (Yii::app()->params['SHIPPING_TAXABLE'] == '1') {
                 $shippingTaxPrices = Tax::calculatePricesWithTax($priority['price'], Yii::app()->shoppingcart->tax_code_id, $intShipProductLsid);
                 Yii::log("Shipping Taxes retrieved " . print_r($shippingTaxPrices, true), $logLevel, 'application.' . __CLASS__ . "." . __FUNCTION__);
                 $shippingTaxValues = $shippingTaxPrices['arrTaxValues'];
                 if (Yii::app()->params['TAX_INCLUSIVE_PRICING'] == '1') {
                     $includeTaxInShippingPrice = true;
                 }
                 if ($includeTaxInShippingPrice === true) {
                     $priorityPrice = $shippingTaxPrices['fltSellTotalWithTax'];
                 } else {
                     Yii::app()->shoppingcart->AddTaxes($shippingTaxValues);
                 }
             }
             $formattedCartTax = _xls_currency(Yii::app()->shoppingcart->TaxTotal);
             if (Yii::app()->params['TAX_INCLUSIVE_PRICING'] == '1') {
                 // For tax inclusive stores, we never show cart tax. This is because either:
                 // 1. The destination is inside the tax-inclusive region, or
                 // 2. The destination is inside a tax-exclusive region, in
                 //    which case it must be set up as 0% tax.
                 $formattedCartTax = '';
             }
             // TODO: Do the _xls_currency() in the formatter rather than here.
             $arrCartScenario[] = array('formattedCartSubtotal' => _xls_currency(Yii::app()->shoppingcart->subtotal), 'formattedCartTax' => $formattedCartTax, 'formattedCartTax1' => _xls_currency(Yii::app()->shoppingcart->tax1), 'formattedCartTax2' => _xls_currency(Yii::app()->shoppingcart->tax2), 'formattedCartTax3' => _xls_currency(Yii::app()->shoppingcart->tax3), 'formattedCartTax4' => _xls_currency(Yii::app()->shoppingcart->tax4), 'formattedCartTax5' => _xls_currency(Yii::app()->shoppingcart->tax5), 'formattedCartTotal' => _xls_currency($cart->getTotalWithShipping($priorityPrice)), 'cartTax1' => Yii::app()->shoppingcart->tax1, 'cartTax2' => Yii::app()->shoppingcart->tax2, 'cartTax3' => Yii::app()->shoppingcart->tax3, 'cartTax4' => Yii::app()->shoppingcart->tax4, 'cartTax5' => Yii::app()->shoppingcart->tax5, 'formattedShippingPrice' => _xls_currency($priorityPrice), 'module' => $shippingProvider['module']->module, 'priorityIndex' => $priorityIndex, 'priorityLabel' => $priority['label'], 'providerId' => $shippingModuleId, 'providerLabel' => $shippingProvider['component']->Name, 'shippingLabel' => $shippingProvider['component']->Name . ' ' . $priority['label'], 'shippingPrice' => $priority['price'], 'shippingPriceWithTax' => $priorityPrice, 'shippingProduct' => $strShippingProduct, 'cartAttributes' => $cart->attributes, 'cartItems' => $cart->cartItems, 'sortOrder' => $shippingProvider['module']->sort_order);
             // Remove shipping taxes to accommodate the next shipping priority in the loop.
             if (Yii::app()->params['SHIPPING_TAXABLE'] == '1' && $includeTaxInShippingPrice === false) {
                 Yii::app()->shoppingcart->SubtractTaxes($shippingTaxValues);
             }
         }
     }
     // Restore the original storePickup boolean
     $cart->blnStorePickup = $savedStorePickup;
     // Restore the original tax code on the cart.
     Yii::app()->shoppingcart->setTaxCodeId($savedTaxId);
     // Sort the shipping options based on the price key.
     usort($arrCartScenario, function ($item1, $item2) {
         if ($item1['shippingPrice'] == $item2['shippingPrice']) {
             return 0;
         }
         return $item1['shippingPrice'] > $item2['shippingPrice'] ? 1 : -1;
     });
     return $arrCartScenario;
 }
 /**
  * Update all webstore orders before a timestamp 
  * **DEPRECIATED - DO NOT USE, USED ONLY AS A WRAPPER FOR LIGHTSPEED DOWNLOAD REQUESTS, DO NOT DELETE**
  * We also piggyback on this statement for pseudo-cron jobs since we know it's triggered at least once an hour
  *
  * @param string $passkey
  * @param int $intDttSubmitted
  * @param int $intDownloaded
  * @return string
  */
 public function update_order_downloaded_status_by_ts($passkey, $intDttSubmitted, $intDownloaded)
 {
     //Make sure we have our Any/Any default tax set in Destinations
     TaxCode::VerifyAnyDestination();
     Yii::app()->cronJobs->run();
     return self::OK;
 }
Esempio n. 6
0
        <div class="editinstructions">
			<?php 
echo Yii::t('admin', 'These orders are ready to be downloaded into Lightspeed. Editing provided for troubleshooting purposes only. Please use caution when using these options, and consult our online documentation and technical support resources for assistance. <strong>Note: missing tax codes will prevent an order from downloading.</strong>');
?>
        </div>
    </div>
    <div class="clearfix search">
        <div class="pull-right">
			<?php 
echo CHtml::beginForm($this->createUrl('databaseadmin/pending'), 'get');
?>
			<?php 
echo CHtml::textField('q', Yii::app()->getRequest()->getQuery('q'), array('id' => 'xlsSearch', 'placeholder' => 'SEARCH...', 'submit' => ''));
?>
			<?php 
echo CHtml::endForm();
?>
        </div>
    </div>

	<?php 
$this->widget('bootstrap.widgets.TbGridView', array('id' => 'user-grid', 'itemsCssClass' => 'table-bordered', 'dataProvider' => $model->searchAdmin(), 'summaryText' => '', 'columns' => array(array('name' => 'id_str', 'header' => 'Web Order #', 'type' => 'raw', 'value' => '"<a href=\\"#\\" id=\\"".$data->id."\\" class=\\"basic\\">".$data->id_str."</a>"', 'headerHtmlOptions' => array('class' => 'span2')), array('name' => 'customer.fullname', 'header' => 'Customer', 'headerHtmlOptions' => array('class' => 'span4')), array('header' => 'Items', 'sortable' => false, 'name' => 'item_count', 'headerHtmlOptions' => array('class' => 'span1')), array('name' => 'shipping.shipping_sell', 'header' => 'Shipping', 'sortable' => false, 'headerHtmlOptions' => array('class' => 'span2'), 'value' => '_xls_currency($data->shipping_sell)'), array('class' => 'editable.EditableColumn', 'name' => 'tax_code_id', 'headerHtmlOptions' => array('class' => 'span2'), 'sortable' => false, 'editable' => array('type' => 'select', 'url' => $this->createUrl('databaseadmin/update'), 'source' => CHtml::listData(TaxCode::model()->findAll(), 'lsid', 'code'), 'options' => array('onblur' => 'submit', 'showbuttons' => false, 'emptytext' => 'MISSING!'))), array('name' => 'total', 'sortable' => false, 'headerHtmlOptions' => array('style' => 'span1'), 'value' => '_xls_currency($data->total)'))));
?>


</div>




Esempio n. 7
0
 /**
  * Removes the tax from a tax inclusive price. Since our TaxIn prices are generated from our
  * default tax code, we can use this to undo the tax
  * @param $fltPrice
  * @return float
  */
 public static function StripTaxesFromPrice($fltSellTotal, $intTaxStatusId)
 {
     static $objTaxes;
     // Cached for better performance
     $fltSellTotalTaxed = $fltSellTotal;
     $arrTaxAmount = array(1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0);
     $intTaxCodeId = 0;
     $objTaxCodes = TaxCode::model()->findAll(array('order' => 'list_order'));
     //Default tax code is first in list
     $objTaxCode = $objTaxCodes[0];
     if (!$objTaxCode) {
         if (!is_null($intTaxCodeId)) {
             //Ignore null at this stage
             Yii::log("Unknown tax code passed: {$intTaxCodeId}", 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
         }
         return array($fltSellTotalTaxed, $arrTaxAmount);
     }
     if ($intTaxStatusId instanceof TaxStatus) {
         $objTaxStatus = $intTaxStatusId;
     } elseif ($intTaxStatusId >= 0) {
         $objTaxStatus = TaxStatus::model()->findByAttributes(array('lsid' => $intTaxStatusId));
     } else {
         $objTaxStatus = false;
     }
     if (!$objTaxes) {
         $objTaxes = Tax::model()->findAll();
     }
     $taxtypes = 5;
     // Number of taxes in LS
     // for each exempt, reset the code to 0
     if ($objTaxStatus) {
         if ($objTaxStatus->tax1_status) {
             $objTaxCode->tax1_rate = 0;
         }
         if ($objTaxStatus->tax2_status) {
             $objTaxCode->tax2_rate = 0;
         }
         if ($objTaxStatus->tax3_status) {
             $objTaxCode->tax3_rate = 0;
         }
         if ($objTaxStatus->tax4_status) {
             $objTaxCode->tax4_rate = 0;
         }
         if ($objTaxStatus->tax5_status) {
             $objTaxCode->tax5_rate = 0;
         }
     }
     $i = 0;
     foreach ($objTaxes as $objTax) {
         $strRate = "tax" . ($i + 1) . "_rate";
         if ($objTaxCode->{$strRate} > 0) {
             if ($objTax->compounded) {
                 $fltTaxAmount = $fltSellTotalTaxed / ($objTaxCode->{$strRate} / 100);
             } else {
                 $fltOrig = $fltSellTotal / (1 + $objTaxCode->{$strRate} / 100);
                 $fltTaxAmount = round($fltSellTotal - $fltOrig, 2);
             }
         } else {
             $fltTaxAmount = 0;
         }
         if ($objTax->max_tax > 0 && $fltTaxAmount >= $objTax->max_tax) {
             $fltTaxAmount = $objTax->max_tax;
         }
         $arrTaxAmount[$i + 1] = $fltTaxAmount;
         $fltSellTotalTaxed = $fltSellTotalTaxed - $fltTaxAmount;
         $i++;
         if ($i >= $taxtypes) {
             $i = $taxtypes;
         }
     }
     return $fltSellTotalTaxed;
 }
Esempio n. 8
0
 /**
  * Update Cart by setting taxes when in Tax Inclusive
  */
 public function UpdateTaxInclusive()
 {
     if (_xls_get_conf('TAX_INCLUSIVE_PRICING', '0') != '1') {
         return;
     }
     $TAX_DECIMAL = _xls_get_conf('TAX_DECIMAL', 2);
     // Reset taxes
     $this->tax1 = 0;
     $this->tax2 = 0;
     $this->tax3 = 0;
     $this->tax4 = 0;
     $this->tax5 = 0;
     // Get the rowid for "No Tax"
     $objNoTax = TaxCode::GetNoTaxCode();
     $intNoTax = 999;
     if ($objNoTax) {
         $intNoTax = $objNoTax->lsid;
     }
     // Tax Inclusive && Want taxes, so return and set prices back to inclusive if needed
     if ($this->fk_tax_code_id != $intNoTax) {
         if (!$this->tax_inclusive) {
             //if the last destination was exclusive, and we have inclusive now, we need to reset the line items
             $this->tax_inclusive = 1;
             foreach ($this->documentItems as $objItem) {
                 // Set back tax inclusive prices
                 $objItem->sell = $objItem->product->GetPrice($objItem->qty);
                 $objItem->sell_base = $objItem->sell;
                 $objItem->tax_in = true;
                 $objItem->save();
             }
         }
         return;
     }
     $this->tax_inclusive = 0;
     // Tax Inclusive && Don't want taxes
     foreach ($this->documentItems as $objItem) {
         // For quote to cart, we have to remove prices manually
         if ($objItem->cart_type == CartType::quote && $objItem->tax_in) {
             $taxes = $objItem->product->CalculateTax(TaxCode::GetDefault(), $objItem->Sell);
             // Taxes are deducted from cart for Lightspeed
             $this->tax1 -= $taxes[1];
             $this->tax2 -= $taxes[2];
             $this->tax3 -= $taxes[3];
             $this->tax4 -= $taxes[4];
             $this->tax5 -= $taxes[5];
             $objItem->sell -= round(array_sum($taxes), $TAX_DECIMAL);
             $objItem->sell_base = $objItem->Sell;
             $objItem->sell_total = $objItem->sell * $objItem->qty;
             $objItem->tax_in = false;
             $objItem->save();
         } elseif ($objItem->cart_type = CartType::order && $objItem->tax_in) {
             // Set Tax Exclusive price
             $objItem->sell = $objItem->product->GetPrice($objItem->qty, true);
             $objItem->sell_base = $objItem->sell;
             $objItem->tax_in = false;
             $objItem->save();
         }
     }
 }
Esempio n. 9
0
 /**
  * Find the tax code associated with the provided address and update the
  * shopping cart to use it.
  *
  * When the shipping country is empty, the Store Default tax code is used.
  * This is generally used before an address is entered and for store
  * pickup.
  *
  * If the provided address is not matched to any destination, the tax code
  * for ANY/ANY is used.
  *
  * @param mixed $shippingCountry The 2-letter country code for the country or the country ID.
  * @param mixed $shippingState The 2-letter code for the state or the state ID.
  * @param string $shippingPostal The postal code with all spaces removed.
  * @return void
  * @throws CException If tax destinations are not configured.
  */
 public function setTaxCodeByAddress($shippingCountry, $shippingState, $shippingPostal)
 {
     $previousTaxCodeId = $this->getModel()->tax_code_id;
     $taxCode = TaxCode::getTaxCodeByAddress($shippingCountry, $shippingState, $shippingPostal);
     $newTaxCodeId = $taxCode->lsid;
     $this->setTaxCodeId($newTaxCodeId);
     // Validate the promo code after saving, since recalculating updates
     // the cart item prices and may invalidate a promo code based on its
     // threshold.
     $this->recalculateAndSave();
     $this->revalidatePromoCode();
     // In a tax inclusive environment there can only be 2 tax codes.
     // Changing tax code means we've gone from tax-inclusive to
     // tax-exclusive or vice versa. This implies that the price display has
     // changed.
     // TODO: Is this always true? What if tax_code_id was null?
     if (CPropertyValue::ensureBoolean(_xls_get_conf('TAX_INCLUSIVE_PRICING')) == 1 && $previousTaxCodeId !== $newTaxCodeId) {
         Yii::app()->user->setFlash('taxModeChange', Yii::t('checkout', 'Prices have changed based on your tax locale.'));
     }
 }
Esempio n. 10
0
	    <?php 
$this->widget('bootstrap.widgets.TbGridView', array('id' => 'user-grid', 'itemsCssClass' => 'table-bordered', 'dataProvider' => $model->search(), 'summaryText' => '', 'columns' => array(array('class' => 'editable.EditableColumn', 'sortable' => false, 'id' => 'country', 'name' => 'country', 'headerHtmlOptions' => array('id' => '$data->id', 'style' => 'width: 110px'), 'editable' => array('type' => 'select', 'url' => $this->createUrl('shipping/updateDestination'), 'placement' => 'right', 'source' => Country::getCountriesForTaxes(), 'options' => array('onblur' => 'submit', 'showbuttons' => false, 'success' => 'js:function(response, newValue) {
									if(response=="delete")
										window.location.reload();
									else {
										var pk = $(this).data("pk");
										var country = newValue;
										var state = $("a[rel=user-grid_Destination_state][data-pk="+pk+"]");
										var newurl = "' . $this->createUrl('shipping/destinationstates') . '?a=1&country_id=" + country;
										$.get(newurl,function(jsdata) {
											response = $.parseJSON(jsdata);
											state.editable("option", "source", jsdata);
											state.editable("setValue", null);
											 });
									}
								}', 'emptytext' => 'Any'))), array('class' => 'editable.EditableColumn', 'name' => 'state', 'headerHtmlOptions' => array('style' => 'width: 110px'), 'sortable' => false, 'editable' => array('url' => $this->createUrl('shipping/updateDestination'), 'type' => 'select', 'source' => $this->createUrl('shipping/destinationstates') . '?a=1&country_id=0', 'placement' => 'right', 'onInit' => 'js: function(e, params) {
							if ($(this).data("value")>=0) {
								var pk = $(this).data("pk");
								var country = $("a[rel=user-grid_Destination_country][data-pk="+pk+"]").editable("getValue").country;
								var newurl = "' . $this->createUrl('shipping/destinationstates') . '?a=1&country_id=" + country;
								$(this).editable("option", "source", newurl);
							}}', 'options' => array('onblur' => 'submit', 'showbuttons' => false, 'emptytext' => 'Please Choose'))), array('class' => 'editable.EditableColumn', 'sortable' => false, 'name' => 'zipcode1', 'headerHtmlOptions' => array('style' => 'width: 110px'), 'editable' => array('url' => $this->createUrl('shipping/updateDestination'), 'options' => array('onblur' => 'submit'))), array('class' => 'editable.EditableColumn', 'sortable' => false, 'name' => 'zipcode2', 'headerHtmlOptions' => array('style' => 'width: 110px'), 'editable' => array('url' => $this->createUrl('shipping/updateDestination'), 'options' => array('onblur' => 'submit'))), array('class' => 'editable.EditableColumn', 'sortable' => false, 'name' => 'taxcode', 'headerHtmlOptions' => array('style' => 'width: 110px'), 'editable' => array('url' => $this->createUrl('shipping/updateDestination'), 'type' => 'select', 'source' => CHtml::listData(TaxCode::model()->findAll(), 'lsid', 'code'), 'options' => array('onblur' => 'submit', 'showbuttons' => false, 'emptytext' => 'MISSING!'))))));
?>


</div>




Esempio n. 11
0
 /**
  * Checks if current taxcode should be tax inclusive or not..
  * @return
  */
 public function ResetTaxIncFlag()
 {
     $this->tax_inclusive = 0;
     if (_xls_get_conf('TAX_INCLUSIVE_PRICING', '0') == 1) {
         $objTaxCode = TaxCode::GetDefault();
         if ($objTaxCode instanceof TaxCode) {
             $this->tax_code_id = $objTaxCode->lsid;
             $this->tax_inclusive = 1;
         }
     }
 }
Esempio n. 12
0
 /**
  * Tax Code List
  *
  * @param string $passkey
  * @return string
  * @throws SoapFault
  * @soap
  */
 public function list_tax_codes($passkey)
 {
     self::check_passkey($passkey);
     $obj = TaxCode::model()->findAll();
     return CJSON::encode($obj);
 }
Esempio n. 13
0
		<?php 
echo $form->textField($model, 'zipcode2');
?>
		<?php 
echo $form->error($model, 'zipcode2');
?>
    </div>
</div>

<div class="row">
    <div class="span5">
		<?php 
echo $form->labelEx($model, 'taxcode');
?>
		<?php 
echo $form->dropDownList($model, 'taxcode', CHtml::listData(TaxCode::model()->findAll(array('order' => 'list_order')), 'lsid', 'code'));
?>
		<?php 
echo $form->error($model, 'taxcode');
?>
    </div>
</div>

<div class="row">
    <div class="pull-right" >
	    <?php 
echo CHtml::ajaxSubmitButton(Yii::t('global', 'Save'), array('shipping/newdestination'), array('type' => "POST", 'success' => 'js:function(data) {
	                if (data=="success")
	                window.location.reload();
	                else alert(data);
                 }'), array('id' => 'btnSubmit', 'class' => 'btn btn-primary btn-small'));
Esempio n. 14
0
    /**
     * Displays and processes the checkout form. This is our big function which
     * validates everything and calls for order completion when done.
     * TODO: Would be better broken into small functions to aid unit testing.
     */
    public function actionCheckout()
    {
        // We shouldn't be in this controller if we don't have any products in
        // our cart.
        if (!Yii::app()->shoppingcart->itemCount) {
            Yii::log("Attempted to check out with no cart items", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
            Yii::app()->user->setFlash('warning', Yii::t('cart', 'Oops, you cannot checkout. You have no items in your cart.'));
            if (!Yii::app()->user->isGuest && Yii::app()->user->fullname == "Guest") {
                // Probably here because of cancelling an AIM payment.
                Yii::log("Checkout as Guest .. logging out", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                Yii::app()->user->logout();
            }
            $this->redirect($this->createAbsoluteUrl("/cart", array(), 'http'));
        }
        $this->pageTitle = _xls_get_conf('STORE_NAME') . ' : Checkout';
        // Set breadcrumbs.
        $this->breadcrumbs = array(Yii::t('global', 'Edit Cart') => array('/cart'), Yii::t('global', 'Checkout') => array('cart/checkout'));
        $model = new CheckoutForm();
        $model->objAddresses = CustomerAddress::getActiveAddresses();
        // If this cart was built from another person's wish list.
        if (Yii::app()->shoppingcart->HasShippableGift) {
            $model->objAddresses = array_merge($model->objAddresses, Yii::app()->shoppingcart->GiftAddress);
        }
        if (isset($_POST['CheckoutForm'])) {
            $strLogLevel = Yii::app()->getComponent('log')->routes[0]->levels;
            if (stripos($strLogLevel, ",info")) {
                $arrSubmitted = $_POST['CheckoutForm'];
                // Redact sensitive information.
                if (isset($arrSubmitted['cardNumber'])) {
                    $arrSubmitted['cardNumber'] = "A " . strlen($arrSubmitted['cardNumber']) . " digit number here";
                }
                if (isset($arrSubmitted['cardCVV'])) {
                    $arrSubmitted['cardCVV'] = "A " . strlen($arrSubmitted['cardCVV']) . " digit number here";
                }
                Yii::log("*** CHECKOUT FORM *** Submission data: " . print_r($arrSubmitted, true), 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
            }
            $model->attributes = $_POST['CheckoutForm'];
            if (Yii::app()->params['SHIP_SAME_BILLSHIP']) {
                $model->billingSameAsShipping = 1;
            }
            // Force lower case on emails.
            $model->contactEmail = strtolower($model->contactEmail);
            $model->contactEmail_repeat = strtolower($model->contactEmail_repeat);
            $cacheModel = clone $model;
            unset($cacheModel->cardNumber);
            unset($cacheModel->cardCVV);
            unset($cacheModel->cardExpiryMonth);
            unset($cacheModel->cardExpiryYear);
            Yii::app()->session['checkout.cache'] = $cacheModel;
            if (!Yii::app()->user->IsGuest) {
                $model->setScenario('formSubmitExistingAccount');
            } elseif ($model->createPassword) {
                $model->setScenario('formSubmitCreatingAccount');
            } else {
                $model->setScenario('formSubmitGuest');
            }
            // Copy address book to field if necessary.
            $model->fillFieldsFromPreselect();
            // Validate our primary CheckoutForm model here.
            $valid = $model->validate();
            //For any payment processor with its own form -- not including CC -- validate here
            if ($model->paymentProvider) {
                $objPaymentModule = Modules::model()->findByPk($model->paymentProvider);
                $objComponent = Yii::app()->getComponent($objPaymentModule->module);
                if (isset($objComponent->subform)) {
                    Yii::log("Form validation for card provider  " . strip_tags($objComponent->name()), 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    $paymentSubform = $objComponent->subform;
                    $paymentSubformModel = new $paymentSubform();
                    $paymentSubformModel->attributes = isset($_POST[$paymentSubform]) ? $_POST[$paymentSubform] : array();
                    $subValidate = $paymentSubformModel->validate();
                    $valid = $subValidate && $valid;
                } else {
                    Yii::log("Payment module " . strip_tags($objComponent->name()), 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                }
            }
            //If this came in as AJAX validation, return the results and exit
            if (Yii::app()->getRequest()->getIsAjaxRequest()) {
                echo $valid;
                Yii::app()->end();
            }
            //If all our validation passed, run our checkout procedure
            if ($valid) {
                Yii::log("All actionCheckout validation passed, attempting to complete checkout", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                $objCart = Yii::app()->shoppingcart;
                //Assign CartID if not currently assigned
                //If we have provided a password
                if ($model->createPassword) {
                    Yii::log("Password was part of CheckoutForm", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    // Test to see if we can log in with the provided password.
                    $identity = new UserIdentity($model->contactEmail, $model->createPassword);
                    $identity->authenticate();
                    switch ($identity->errorCode) {
                        case UserIdentity::ERROR_PASSWORD_INVALID:
                            //Oops, email is already in system but not with that password
                            Yii::app()->user->setFlash('error', Yii::t('global', 'This email address already exists but that is not the correct password so we cannot log you in.'));
                            Yii::log($model->contactEmail . " login from checkout with invalid password", 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                            $this->refresh();
                            return;
                        case UserIdentity::ERROR_USERNAME_INVALID:
                            $objCustomer = Customer::CreateFromCheckoutForm($model);
                            $identity = new UserIdentity($model->contactEmail, $model->createPassword);
                            $identity->authenticate();
                            if ($identity->errorCode !== UserIdentity::ERROR_NONE) {
                                Yii::log("Error logging in after creating account for " . $model->contactEmail . ". Error:" . $identity->errorCode . " Cannot continue", 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                                Yii::app()->user->setFlash('error', Yii::t('global', 'Error logging in after creating account. Cannot continue.'));
                                $this->refresh();
                                return;
                            }
                            break;
                        case UserIdentity::ERROR_NONE:
                            break;
                        default:
                            Yii::log("Error: Unhandled errorCode " . $identity->errorCode, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                            break;
                    }
                    $intTaxCode = Yii::app()->shoppingcart->tax_code_id;
                    //Save tax code already chosen
                    Yii::app()->user->login($identity, 3600 * 24 * 30);
                    Yii::app()->user->setState('createdoncheckout', 1);
                    Yii::app()->shoppingcart->tax_code_id = $intTaxCode;
                }
                // If we're not logged in, create guest account, or get our logged in ID.
                if (Yii::app()->user->isGuest) {
                    Yii::log("Creating Guest account to complete checkout", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    if (is_null($objCart->customer_id)) {
                        //create a new guest ID
                        $identity = new GuestIdentity();
                        Yii::app()->user->login($identity, 300);
                        $intCustomerId = $objCart->customer_id = $identity->getId();
                        $this->intGuestCheckout = 1;
                        $objCustomer = Customer::model()->findByPk($intCustomerId);
                        $objCustomer->first_name = $model->contactFirstName;
                        $objCustomer->last_name = $model->contactLastName;
                        $objCustomer->mainphone = $model->contactPhone;
                        $objCustomer->email = $model->contactEmail;
                        $objCustomer->save();
                    } else {
                        $intCustomerId = $objCart->customer_id;
                        $objCustomer = Customer::model()->findByPk($intCustomerId);
                    }
                } else {
                    $intCustomerId = Yii::app()->user->getId();
                    $objCustomer = Customer::model()->findByPk($intCustomerId);
                }
                $objCart->customer_id = $intCustomerId;
                if (trim($objCart->currency) == '') {
                    $objCart->currency = _xls_get_conf('CURRENCY_DEFAULT', 'USD');
                }
                $objCart->save();
                //If shipping address is value, then choose that
                //otherwise enter new shipping address
                //and assign value
                if ($model->intShippingAddress) {
                    $objCart->shipaddress_id = $model->intShippingAddress;
                } else {
                    Yii::log("Creating new shipping address", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    if (empty($model->shippingLabel)) {
                        $model->shippingLabel = Yii::t('global', 'Unlabeled Address');
                    }
                    $objAddress = new CustomerAddress();
                    $objAddress->customer_id = $intCustomerId;
                    $objAddress->address_label = $model->shippingLabel;
                    $objAddress->first_name = $model->shippingFirstName;
                    $objAddress->last_name = $model->shippingLastName;
                    $objAddress->address1 = $model->shippingAddress1;
                    $objAddress->address2 = $model->shippingAddress2;
                    $objAddress->city = $model->shippingCity;
                    $objAddress->state_id = $model->shippingState;
                    $objAddress->postal = $model->shippingPostal;
                    $objAddress->country_id = $model->shippingCountry;
                    $objAddress->residential = $model->shippingResidential;
                    if (!$objAddress->save()) {
                        Yii::app()->user->setFlash('error', print_r($objAddress->getErrors(), true));
                        Yii::log("Error creating CustomerAddress Shipping " . print_r($objAddress->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                        $this->refresh();
                    }
                    $objCart->shipaddress_id = $model->intShippingAddress = $objAddress->id;
                    unset($objAddress);
                }
                if ($objCustomer instanceof Customer) {
                    if (is_null($objCustomer->default_shipping_id)) {
                        $objCustomer->default_shipping_id = $model->intShippingAddress;
                        $objCustomer->save();
                        try {
                            $objCart->setTaxCodeByDefaultShippingAddress();
                        } catch (Exception $e) {
                            Yii::log("Error updating customer cart " . $e->getMessage(), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                        }
                        $objCart->recalculateAndSave();
                    }
                }
                // If billing address is value, then choose that otherwise enter
                // new billing address and assign value.
                if ($model->intBillingAddress) {
                    $objCart->billaddress_id = $model->intBillingAddress;
                } elseif ($model->billingSameAsShipping) {
                    $objCart->billaddress_id = $model->intBillingAddress = $model->intShippingAddress;
                } else {
                    if (empty($model->billingLabel)) {
                        $model->billingLabel = Yii::t('checkout', 'Unlabeled address');
                    }
                    if (!Yii::app()->user->isGuest) {
                        $objCustomer = Customer::GetCurrent();
                        if ($objCustomer instanceof Customer) {
                            $model->contactFirstName = $objCustomer->first_name;
                            $model->contactLastName = $objCustomer->last_name;
                        }
                    }
                    $objAddress = new CustomerAddress();
                    $objAddress->customer_id = $intCustomerId;
                    $objAddress->address_label = $model->billingLabel;
                    $objAddress->first_name = $model->contactFirstName;
                    $objAddress->last_name = $model->contactLastName;
                    $objAddress->company = $model->contactCompany;
                    $objAddress->address1 = $model->billingAddress1;
                    $objAddress->address2 = $model->billingAddress2;
                    $objAddress->city = $model->billingCity;
                    $objAddress->state_id = $model->billingState;
                    $objAddress->postal = $model->billingPostal;
                    $objAddress->country_id = $model->billingCountry;
                    $objAddress->phone = $model->contactPhone;
                    $objAddress->residential = $model->billingResidential;
                    if (!$objAddress->save()) {
                        Yii::app()->user->setFlash('error', print_r($objAddress->getErrors(), true));
                        Yii::log("Error creating CustomerAddress Billing " . print_r($objAddress->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                        $this->refresh();
                    }
                    $objCart->billaddress_id = $model->intBillingAddress = $objAddress->id;
                    unset($objAddress);
                }
                if ($objCustomer instanceof Customer) {
                    if (is_null($objCustomer->default_billing_id)) {
                        $objCustomer->default_billing_id = $model->intBillingAddress;
                        $objCustomer->save();
                    }
                }
                // Mark order as awaiting payment.
                Yii::log("Marking as " . OrderStatus::AwaitingPayment, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                $objCart->cart_type = CartType::awaitpayment;
                $objCart->status = OrderStatus::AwaitingPayment;
                $objCart->downloaded = 0;
                $objCart->origin = _xls_get_ip();
                $objCart->save();
                //save cart so far
                // Assign next WO number, and LinkID.
                $objCart->SetIdStr();
                Yii::log("Order assigned " . $objCart->id_str, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                $objCart->linkid = $objCart->GenerateLink();
                // Get Shipping Information.
                // Prices are stored in session from Calculate Shipping.
                // TODO: rewrite to use the "selectedCartScenario" mechanism.
                $objShippingModule = Modules::model()->findByPk($model->shippingProvider);
                $arrShippingOptionPrice = Yii::app()->session->get('ship.prices.cache', null);
                if ($arrShippingOptionPrice === null) {
                    Yii::app()->user->setFlash('error', Yii::t('global', 'Oops, something went wrong, please try submitting your order again.'));
                    Yii::log('Cannot checkout: ship.prices.cache was not cached. This should never happen.', 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    // Must use false here to prevent process termination or
                    // the UTs die completely when this occurs.
                    $this->refresh(false);
                    return;
                }
                $fltShippingSell = $arrShippingOptionPrice[$model->shippingProvider][$model->shippingPriority];
                $fltShippingCost = $fltShippingSell - $objShippingModule->markup;
                // If the chosen shipping module has In-Store pickup, charge
                // store local tax.
                if (Yii::app()->getComponent($objShippingModule->module)->IsStorePickup) {
                    Yii::log("In Store pickup chosen, requires store tax code", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    $objCart->tax_code_id = TaxCode::getDefaultCode();
                    $objCart->recalculateAndSave();
                }
                // If we have a shipping object already, update it, otherwise create it.
                if (isset($objCart->shipping)) {
                    $objShipping = $objCart->shipping;
                    //update
                } else {
                    //create
                    $objShipping = new CartShipping();
                    if (!$objShipping->save()) {
                        print_r($objShipping->getErrors());
                    }
                }
                $objShipping->shipping_module = $objShippingModule->module;
                Yii::log("Shipping module is " . $objShipping->shipping_module, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                $providerLabel = Yii::app()->session['ship.providerLabels.cache'][$model->shippingProvider];
                $priorityLabel = Yii::app()->session['ship.priorityLabels.cache'][$model->shippingProvider][$model->shippingPriority];
                if (stripos($priorityLabel, $providerLabel) !== false) {
                    $strLabel = $priorityLabel;
                } else {
                    $strLabel = $providerLabel . ' ' . $priorityLabel;
                }
                $objShipping->shipping_data = $strLabel;
                $objShipping->shipping_method = $objShippingModule->product;
                $objShipping->shipping_cost = $fltShippingCost;
                $objShipping->shipping_sell = $fltShippingSell;
                $objShipping->save();
                $objCart->shipping_id = $objShipping->id;
                $objCart->save();
                //save cart so far
                // Update the cart totals.
                $objCart->recalculateAndSave();
                // Get payment Information.
                $objPaymentModule = Modules::model()->findByPk($model->paymentProvider);
                // If we have a payment object already, update it, otherwise create it.
                if (isset($objCart->payment)) {
                    $objPayment = $objCart->payment;
                    //update
                } else {
                    //create
                    $objPayment = new CartPayment();
                    if (!$objPayment->save()) {
                        print_r($objPayment->getErrors());
                    }
                }
                Yii::log("Payment method is " . $objPaymentModule->payment_method, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                $objPayment->payment_method = $objPaymentModule->payment_method;
                $objPayment->payment_module = $objPaymentModule->module;
                $objPayment->save();
                $objCart->payment_id = $objPayment->id;
                $objCart->save();
                /* RUN PAYMENT HERE */
                Yii::log("Running payment on " . $objCart->id_str, 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                // See if we have a subform for our payment module, set that as
                // part of running payment module.
                if (isset($paymentSubformModel)) {
                    $arrPaymentResult = Yii::app()->getComponent($objPaymentModule->module)->setCheckoutForm($model)->setSubForm($paymentSubformModel)->run();
                } else {
                    $arrPaymentResult = Yii::app()->getComponent($objPaymentModule->module)->setCheckoutForm($model)->run();
                }
                // If we have a full Jump submit form, render it out here.
                if (isset($arrPaymentResult['jump_form'])) {
                    Yii::log("Using payment jump form", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    $objCart->printed_notes .= $model->orderNotes;
                    $this->completeUpdatePromoCode();
                    $this->layout = '//layouts/jumper';
                    Yii::app()->clientScript->registerScript('submit', '$(document).ready(function(){
						$("form:first").submit();
						});');
                    $this->render('jumper', array('form' => $arrPaymentResult['jump_form']));
                    Yii::app()->shoppingcart->releaseCart();
                    return;
                }
                // At this point, if we have a JumpURL, off we go...
                if (isset($arrPaymentResult['jump_url']) && $arrPaymentResult['jump_url']) {
                    Yii::log("Using payment jump url", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    // Redirect to another URL for payment.
                    $objCart->printed_notes .= $model->orderNotes;
                    $this->completeUpdatePromoCode();
                    Yii::app()->shoppingcart->releaseCart();
                    Yii::app()->controller->redirect($arrPaymentResult['jump_url']);
                    return;
                }
                // to support error messages that occur with Cayan during the createTransaction process
                // see the extension for more info
                if (isset($arrPaymentResult['errorMessage'])) {
                    Yii::app()->user->setFlash('error', $arrPaymentResult['errorMessage']);
                    $this->redirect($this->createAbsoluteUrl('/cart/checkout'));
                }
                // If we are this far, we're using an Advanced Payment (or
                // non-payment like COD) so save the result of the payment
                // process (may be pass or fail).
                $objPayment->payment_data = $arrPaymentResult['result'];
                $objPayment->payment_amount = $arrPaymentResult['amount_paid'];
                $objPayment->datetime_posted = isset($retVal['payment_date']) ? date("Y-m-d H:i:s", strtotime($retVal['payment_date'])) : new CDbExpression('NOW()');
                $objPayment->save();
                if (isset($arrPaymentResult['success']) && $arrPaymentResult['success']) {
                    Yii::log("Payment Success! Wrapping up processing", 'info', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    //We have successful payment, so close out the order and show the receipt
                    $objCart->printed_notes .= $model->orderNotes;
                    $this->completeUpdatePromoCode();
                    self::EmailReceipts($objCart);
                    Yii::log('Receipt e-mails added to the queue', 'info', __CLASS__ . '.' . __FUNCTION__);
                    self::FinalizeCheckout($objCart);
                    return;
                } else {
                    Yii::app()->user->setFlash('error', isset($arrPaymentResult['result']) ? $arrPaymentResult['result'] : "UNKNOWN ERROR");
                }
            } else {
                Yii::log("Error submitting form " . print_r($model->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                Yii::app()->user->setFlash('error', Yii::t('cart', 'Please check your form for errors.'));
                if (YII_DEBUG) {
                    Yii::app()->user->setFlash('error', "DEBUG: " . _xls_convert_errors_display(_xls_convert_errors($model->getErrors())));
                }
            }
        } else {
            if (isset(Yii::app()->session['checkout.cache'])) {
                $model = Yii::app()->session['checkout.cache'];
                $model->clearErrors();
            } else {
                //If this is the first time we're displaying the Checkout form, set some defaults
                $model->setScenario('formSubmit');
                $model->billingCountry = _xls_get_conf('DEFAULT_COUNTRY');
                $model->shippingCountry = _xls_get_conf('DEFAULT_COUNTRY');
                $model->billingSameAsShipping = 1;
                $model->billingResidential = 1;
                $model->shippingResidential = 1;
                //Set our default payment module to first on the list
                $obj = new CheckoutForm();
                $data = array_keys($obj->getPaymentMethods());
                if (count($data) > 0) {
                    $model->paymentProvider = $data[0];
                }
                if (!Yii::app()->user->isGuest) {
                    //For logged in users, preset to customer account information
                    $objCustomer = Customer::GetCurrent();
                    if (!$objCustomer instanceof Customer) {
                        //somehow we're logged in without a valid Customer object
                        Yii::app()->user->logout();
                        $url = Yii::app()->createUrl('site/index');
                        $this->redirect($url);
                    }
                    $model->contactFirstName = $objCustomer->first_name;
                    $model->contactLastName = $objCustomer->last_name;
                    $model->contactPhone = $objCustomer->mainphone;
                    $model->contactEmail = $objCustomer->email;
                    if (!empty($objCustomer->defaultBilling)) {
                        $model->intBillingAddress = $objCustomer->default_billing_id;
                    }
                    if (!empty($objCustomer->defaultShipping)) {
                        $model->intShippingAddress = $objCustomer->default_shipping_id;
                    }
                } else {
                    //Set some defaults for guest checkouts
                    $model->receiveNewsletter = Yii::app()->params['DISABLE_ALLOW_NEWSLETTER'] == 1 ? 0 : 1;
                }
            }
        }
        $this->objCart = Yii::app()->shoppingcart;
        // When CheckoutForm is initialized the shippingProvider and
        // shippingPriority are null.  The AJAX validation sends empty
        // strings for these fields until a shipping option is selected.
        if (is_null($model->shippingProvider) || $model->shippingProvider === '') {
            // Use -1 to indicate that the shipping provider has not been chosen.
            $model->shippingProvider = '-1';
        }
        if (is_null($model->shippingPriority) || $model->shippingPriority === '') {
            // Use -1 to indicate that the shipping priority has not been chosen.
            $model->shippingPriority = '-1';
        }
        //If we have a default shipping address on, hide our Shipping box
        if (!empty($model->intShippingAddress) && count($model->objAddresses) > 0) {
            Yii::app()->clientScript->registerScript('shipping', '$(document).ready(function(){
				$("#CustomerContactShippingAddress").hide();
				});');
            // These need to go at POS_END because they need to be ran after
            // SinglePageCheckout has been instantiated. Further granularity in
            // the load order can be achieved by passing an integer to the
            // $position parameter. @See CClientScript::registerScript.
            Yii::app()->clientScript->registerScript('shippingforceclick', '$(document).ready(function(){
				singlePageCheckout.calculateShipping();
				});', CClientScript::POS_END);
        }
        //If we have a default billing address on, hide our Billing box
        if (!empty($model->intBillingAddress) && count($model->objAddresses) > 0) {
            Yii::app()->clientScript->registerScript('billingadd', '$(document).ready(function(){
				$("#CustomerContactBillingAddressAdd").hide();
				});');
        }
        //If Same as Billing checkbox is on, hide our Billing box
        if ($model->billingSameAsShipping) {
            Yii::app()->clientScript->registerScript('billing', 'if ($("#CheckoutForm_billingSameAsShipping:checked").length>0)
				$("#CustomerContactBillingAddress").hide();');
        }
        $paymentForms = $model->getAlternativePaymentMethodsThatUseSubForms();
        // If we have chosen a payment provider (indicating this is a refresh),
        // repick here.
        if ($model->paymentProvider > 0) {
            $objPaymentModule = Modules::model()->findByPk($model->paymentProvider);
            if ($objPaymentModule instanceof Modules) {
                $objModule = Yii::app()->getComponent($objPaymentModule->module);
                if (!$objModule) {
                    Yii::log("Error missing module " . $objPaymentModule->module, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__);
                    $model->paymentProvider = null;
                } else {
                    $subForm = $objModule->subform;
                    if (isset($subForm)) {
                        if (isset($_POST[$subForm])) {
                            $paymentForms[$objPaymentModule->id]->attributes = $_POST[$subForm];
                            $paymentForms[$objPaymentModule->id]->validate();
                        }
                    }
                    Yii::app()->clientScript->registerScript('payment', sprintf('$(document).ready(function(){
							singlePageCheckout.changePayment(%s)
							});', CJSON::encode($model->paymentProvider)), CClientScript::POS_END);
                }
            } else {
                $model->paymentProvider = null;
            }
        }
        // Disable button on Submit to prevent double-clicking.
        $cs = Yii::app()->clientScript;
        $cs->registerScript('submit', '$("checkout:submit").mouseup(function() {
			$(this).attr("disabled",true);
			$(this).parents("form").submit();
			})', CClientScript::POS_READY);
        // This registers a backwards-compatibility shim for the pre-3.2.2
        // single-page checkout. 3.2.2 moved much of the JavaScript out of
        // checkout.php and _cartjs.php into WsSinglePageCheckout.js to
        // improve testability. This shim exists to support stores with a
        // customized checkout that is based on a version before 3.2.2. At
        // some point, we should find a way to move customers customers forward
        // and remove this shim.
        $cs->registerScript('compatibility-shim', '$(document).ready(function(){
				if (typeof singlePageCheckout === "undefined" && typeof updateShippingPriority === "function") {
					singlePageCheckout = {
						calculateShipping: function() { $("#btnCalculate").click(); },
						changePayment: function(paymentProviderId) { changePayment(paymentProviderId); },
						pickShippingProvider: function(providerId) { updateShippingPriority(providerId); },
						updateCart: function(priorityId) { updateCart(priorityId); }
					};
				}
			})', CClientScript::POS_BEGIN);
        // Clear out anything we don't to survive the round trip.
        $model->cardNumber = null;
        $model->cardCVV = null;
        $this->render('checkout', array('model' => $model, 'paymentForms' => $paymentForms));
    }