/** * Setup a default ShopConfig record if none exists */ public function requireDefaultRecords() { parent::requireDefaultRecords(); if (!self::current_shop_config()) { $shopConfig = new ShopConfig(); $shopConfig->write(); DB::alteration_message('Added default shop config', 'created'); } }
public function setData(Order $order, array $data) { if (!isset($data[$this->addresstype . 'ToSameAddress'])) { parent::setData($order, $data); } else { $order->{$this->addresstype . "AddressID"} = $order->{$this->useAddressType . "AddressID"}; if (!$order->BillingAddressID) { $order->BillingAddressID = $order->{$this->useAddressType . "AddressID"}; } } // FIX for missing name fields $fields = array_intersect_key($data, array_flip(['FirstName', 'Surname', 'Name', 'Email'])); $changed = false; foreach ($fields as $field => $value) { if (!$order->{$this->addresstype . "Address"}()->{$field}) { $order->{$this->addresstype . "Address"}()->{$field} = $value; $changed = true; } } if ($country = ShopConfig::current()->SingleCountry) { $order->{$this->addresstype . "Address"}()->Country = $country; } if ($changed || $order->{$this->addresstype . "Address"}()->isChanged()) { $order->{$this->addresstype . "Address"}()->write(); } }
function _promoMethodList() { $conds = array(); $methods = array(); if (ShopConfig::load('promo.complexBehavior') || ShopConfig::load('promo.complexConditions')) { App::import('Lib', 'Shop.ClassCollection'); $all = ClassCollection::getList('promo', 'flat'); foreach ($all as $name => $label) { $class = ClassCollection::getClass('promo', $name); if (!method_exists($class, 'isAvailable') || call_user_func(array($class, 'isAvailable'))) { $obj = new $class(); if (method_exists($class, 'beforeForm')) { $obj->beforeForm($this); } if (!empty($obj->type) && ($obj->type = 'condition')) { $conds[$name] = $obj; } else { $methods[$name] = $obj; } } } } if (!ShopConfig::load('promo.complexConditions')) { $conds = array(); } if (!ShopConfig::load('promo.complexBehavior')) { App::import('Lib', 'Shop.ClassCollection'); $class = ClassCollection::getClass('promo', 'Shop.operation'); $obj = new $class(); $methods = array('Shop.operation' => $obj); } return array('methods' => $methods, 'conds' => $conds); }
public function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->Currency) { $this->Currency = ShopConfig::current_shop_config()->BaseCurrency; } }
public function run($request) { $gp = ShopConfig::current()->CustomerGroup(); if (empty($gp)) { return false; } $allCombos = DB::query("SELECT \"ID\", \"MemberID\", \"GroupID\" FROM \"Group_Members\" WHERE \"Group_Members\".\"GroupID\" = " . $gp->ID . ";"); //make an array of all combos $alreadyAdded = array(); $alreadyAdded[-1] = -1; if ($allCombos) { foreach ($allCombos as $combo) { $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"]; } } $unlistedMembers = DataObject::get("Member", $where = "\"Member\".\"ID\" NOT IN (" . implode(",", $alreadyAdded) . ")", $sort = null, $join = "INNER JOIN \"Order\" ON \"Order\".\"MemberID\" = \"Member\".\"ID\""); //add combos if ($unlistedMembers) { $existingMembers = $gp->Members(); foreach ($unlistedMembers as $member) { $existingMembers->add($member); echo "."; } } else { echo "no new members added"; } }
/** * 返回建筑的配置数据 * * @param string $name 建筑名 * @param int $level 等级 * @param string $attr 配置属性名 */ public static function getBuildingConfig($name, $attr, $level) { switch ($name) { case 'hall': return HallConfig::getLevelData($attr, $level); break; case 'wall': return WallConfig::getLevelData($attr, $level); break; case 'gate': return GateConfig::getLevelData($attr, $level); break; case 'shop': return ShopConfig::getLevelData($attr, $level); break; case 'golder': return GolderConfig::getLevelData($attr, $level); break; case 'fooder': return FooderConfig::getLevelData($attr, $level); break; case 'farmar': return FarmarConfig::getLevelData($attr, $level); break; case 'foodar': return FooderConfig::getLevelData($attr, $level); break; default: break; } }
/** * Create the new notification email. * * @param Member $customer * @param Order $order * @param String $from * @param String $to * @param String $subject * @param String $body * @param String $bounceHandlerURL * @param String $cc * @param String $bcc */ public function __construct(Member $customer, Order $order, $from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null) { $siteConfig = ShopConfig::get()->first(); if ($siteConfig->NotificationTo) { $this->to = $siteConfig->NotificationTo; } if ($siteConfig->NotificationSubject) { $this->subject = $siteConfig->NotificationSubject . ' - Order #' . $order->ID; } if ($siteConfig->NotificationBody) { $this->body = $siteConfig->NotificationBody; } if ($customer->Email) { $this->from = $customer->Email; } elseif (Email::getAdminEmail()) { $this->from = Email::getAdminEmail(); } else { $this->from = 'no-reply@' . $_SERVER['HTTP_HOST']; } $this->signature = ''; $adminLink = Director::absoluteURL('/admin/shop/'); //Get css for Email by reading css file and put css inline for emogrification $this->setTemplate('Order_NotificationEmail'); if (file_exists(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'))) { $css = file_get_contents(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css')); } else { $css = file_get_contents(Director::getAbsFile('swipestripe/css/ShopEmail.css')); } $this->populateTemplate(array('Message' => $this->Body(), 'Order' => $order, 'Customer' => $customer, 'InlineCSS' => "<style>{$css}</style>", 'Signature' => $this->signature, 'AdminLink' => $adminLink)); parent::__construct($from, null, $subject, $body, $bounceHandlerURL, $cc, $bcc); }
/** * Convert a numeric price to the shop currency * @param mixed $price the price to convert * @return Money the price wrapped in a Money DBField to be used for templates or similar */ public static function price_for_display($price) { $currency = ShopConfig::get_site_currency(); $field = Money::create("Price"); $field->setAmount($price); $field->setCurrency($currency); return $field; }
/** * Convert ISO abbreviation to full, translated country name */ public function Nice() { $val = ShopConfig::countryCode2name($this->value); if (!$val) { $val = $this->value; } return _t("ShopCountry." . $this->value, $val); }
function __construct() { App::import('Lib', 'Shop.ShopConfig'); $this->settings = ShopConfig::load('payment.' . $this->name); if (!isset($this->ShopPayment)) { $this->ShopPayment = ClassRegistry::init(array('class' => 'Shop.ShopPayment', 'alias' => 'ShopPayment')); } //debug('Shop.payment.'.$this->name); }
function beforeRender() { App::import('Lib', 'Shop.ShopConfig'); if (ShopConfig::load('cart.qtyInNbItem')) { $this->controller->params['Shop']['nbItem'] = $this->getTotalQty(); } else { $this->controller->params['Shop']['nbItem'] = $this->nbItem(); } $this->controller->params['Shop']['qtys'] = $this->qtysByProduct(); }
/** * Set value of the field with explicitly formatted numbers. * * @param mixed $val */ public function setValue($val) { if (!$val) { $val = 0.0; } $shopConfig = ShopConfig::current_shop_config(); $precision = $shopConfig->BaseCurrencyPrecision; $this->value = number_format((double) preg_replace('/[^0-9.\\-]/', '', $val), $precision); return $this; }
function beforeFilter() { parent::beforeFilter(); App::import('Lib', 'Shop.ShopConfig'); $enabled = ShopConfig::load('enabled'); if (!$enabled) { $this->log('Shop is disabled', LOG_DEBUG); $this->redirect(array('plugin' => 'auth', 'controller' => 'users', 'action' => 'permission_denied', 'admin' => false)); } }
public function run($request) { $zone = Zone::create(); $zone->Name = "International"; $zone->Description = "All countries"; $zone->write(); $countries = ShopConfig::current()->getCountriesList(); foreach ($countries as $code => $country) { $zoneregion = ZoneRegion::create(array('ZoneID' => $zone->ID, 'Country' => $code)); $zoneregion->write(); echo "."; } }
/** * @param string $template * @param string $subject * * @return Email */ private function buildEmail($template, $subject) { $from = ShopConfig::config()->email_from ? ShopConfig::config()->email_from : Email::config()->admin_email; $to = $this->order->getLatestEmail(); $checkoutpage = CheckoutPage::get()->first(); $completemessage = $checkoutpage ? $checkoutpage->PurchaseComplete : ''; $email = Email::create(); $email->setTemplate($template); $email->setFrom($from); $email->setTo($to); $email->setSubject($subject); $email->populateTemplate(array('PurchaseCompleteMessage' => $completemessage, 'Order' => $this->order, 'BaseURL' => Director::absoluteBaseURL())); return $email; }
/** * Returns amount reduced by $this->Measure. * * @param Price|number $amount * @param $discount * @return Price */ public function discountedAmount($forAmount) { if ($this->owner->UsePriceColumn) { $price = new Price(); $price->setCurrency(ShopConfig::current_shop_config()->BaseCurrency); if ($forAmount instanceof Money) { $price->setAmount($forAmount->getAmount()); } else { $price->setAmount($forAmount); } $price->setAmount(Zend_Locale_Math::Sub($price->getAmount(), $this->owner->Measure, 10)); return $price; } return null; }
/** * Get the form fields for the OrderForm. * * @return FieldList List of fields */ public function getFormFields() { $fields = new FieldList(); $field = new XeroTaxModifierField($this, _t('Xero.TAX', 'Tax')); $shopConfig = ShopConfig::current_shop_config(); $amount = new Price(); $amount->setAmount($this->Price); $amount->setCurrency($shopConfig->BaseCurrency); $amount->setSymbol($shopConfig->BaseCurrencySymbol); $field->setAmount($amount); $fields->push($field); if (!$fields->exists()) { Requirements::javascript('swipestripe-flatfeetax/javascript/FlatFeeTaxModifierField.js'); } return $fields; }
/** * Send a mail of the order to the client (and another to the admin). * * @param $template - the class name of the email you wish to send * @param $subject - subject of the email * @param $copyToAdmin - true by default, whether it should send a copy to the admin */ public function sendEmail($template, $subject, $copyToAdmin = true) { $from = ShopConfig::config()->email_from ? ShopConfig::config()->email_from : Email::config()->admin_email; $to = $this->order->getLatestEmail(); $checkoutpage = CheckoutPage::get()->first(); $completemessage = $checkoutpage ? $checkoutpage->PurchaseComplete : ""; $email = new Email(); $email->setTemplate($template); $email->setFrom($from); $email->setTo($to); $email->setSubject($subject); if ($copyToAdmin) { $email->setBcc(Email::config()->admin_email); } $email->populateTemplate(array('PurchaseCompleteMessage' => $completemessage, 'Order' => $this->order, 'BaseURL' => Director::absoluteBaseURL())); return $email->send(); }
public function actionDel() { $res = array('statusCode' => 200, 'message' => '删除成功!'); try { if (empty($_REQUEST['id'])) { throw new Exception("数据错误,id不能为空!", 1); } $flag = ShopConfig::model()->deleteByPk($_REQUEST['id']); if (!$flag) { throw new exception('删除失败'); } } catch (Exception $e) { $res['statusCode'] = 300; $res['message'] = '删除失败【' . $e->getMessage() . '】'; } $res['callbackType'] = 'reloadTab'; $res['forwardUrl'] = '/manage/shopConfig/index'; $this->ajaxDwzReturn($res); }
/** * Iterate through extensions to ask them to calculate the new amount. * * @param $forAmount * @return mixed|Price */ public function discountedAmount($forAmount) { $price = new Price(); if ($values = $this->extend('discountedAmount', $forAmount)) { $price = reset($values); if (!$price->getCurrency()) { $price->setCurrency(ShopConfig::current_shop_config()->BaseCurrency); } } else { if ($forAmount instanceof Money) { $price->setAmount($forAmount->getAmount()); $price->setCurrency($forAmount->getCurrency()); } else { $price->setAmount($forAmount); $price->setCurrency(ShopConfig::current_shop_config()->BaseCurrency); } } return $price; }
function setup(&$Model, $settings) { if (!isset($this->settings[$Model->alias])) { $this->settings[$Model->alias] = $this->defaultSettings; } $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], (array) $settings); if (empty($Model->productOptions)) { $Model->productOptions = array(); } $Model->productOptions = array_merge($Model->productOptions, $this->settings[$Model->alias]); $Model->Behaviors->attach('Shop.AssociationEvent'); $Model->bindModel(array('hasOne' => array('ShopProduct' => array('className' => 'Shop.ShopProduct', 'foreignKey' => 'foreign_id', 'conditions' => array('ShopProduct.model' => $Model->alias), 'dependent' => true))), false); if (Configure::read('admin') == true) { App::import('Lib', 'Shop.ShopConfig'); $types = ShopConfig::getSubProductTypes(); if (!empty($types)) { $this->productContain($Model); } } }
/** * Returns the amount minus percentage from Measure. * * @param Price $forAmount * @return Price */ public function discountedAmount($forAmount) { if ($this->owner->UsePercentageColumn) { $price = new Price(); if ($forAmount instanceof Money) { $price->setAmount($forAmount->getAmount()); $price->setCurrency($forAmount->getCurrency()); } else { $price->setAmount($forAmount); $price->setCurrency(ShopConfig::current_shop_config()->BaseCurrency); } // only recalculate if there is a percentage if ($this->owner->Measure != 0) { $original = $price->getAmount(); $percentage = Zend_Locale_Math::Div($this->owner->Measure, self::OneHundred, 10); $difference = Zend_Locale_Math::Mul($original, $percentage, 10); $price->setAmount(Zend_Locale_Math::Sub($original, $difference, 10)); } return $price; } return null; }
/** * Calculate the tax component based on tax rates for the items and modifications in the order * * @param Order $order * @return Price The tax amount for the order */ public function calculate(Order $order) { $taxAmount = 0; $shopConfig = ShopConfig::current_shop_config(); $items = $order->Items(); if ($items && $items->exists()) { foreach ($items as $item) { $taxAmount += $item->Total()->getAmount() * ($item->XeroTaxRate / 100); } } $mods = $order->Modifications(); if ($mods && $mods->exists()) { foreach ($mods as $mod) { $taxAmount += $mod->Amount()->getAmount() * ($mod->XeroTaxRate / 100); } } $amount = new Price(); $amount->setAmount($taxAmount); $amount->setCurrency($shopConfig->BaseCurrency); $amount->setSymbol($shopConfig->BaseCurrencySymbol); return $amount; }
public function setData(Order $order, array $data) { if (!isset($data['Use'])) { parent::setData($order, $data); return; } $member = Member::currentUser() ?: $order->Member(); if (strpos($data['Use'], 'address-') === 0) { $address = Address::get()->byID(substr($data['Use'], 8)); if (!$address) { throw new ValidationException('That address does not exist'); } if (isset($data[$data['Use']]) && isset($data[$data['Use']]['saveAsNew']) && $data[$data['Use']]['saveAsNew']) { if (!$address->canCreate()) { throw new ValidationException('You do not have permission to add a new address'); } $address = $address->duplicate(); } else { if (isset($data[$data['Use']]) && !$address->canEdit() && $address->MemberID != $member->ID) { throw new ValidationException('You do not have permission to use this address'); } } } else { if (!singleton('Address')->canCreate()) { throw new ValidationException('You do not have permission to add a new address'); } $address = Address::create(); } if (isset($data[$data['Use']])) { $address->castedUpdate($data[$data['Use']]); // FIX for missing name fields $fields = array_intersect_key($data, array_flip(['FirstName', 'Surname', 'Name', 'Email'])); foreach ($fields as $field => $value) { if (!$address->{$field}) { $address->{$field} = $value; } } if ($country = ShopConfig::current()->SingleCountry) { $address->Country = $country; } if ($this->addtoaddressbook) { $address->MemberID = $member->ID; } $address->write(); if (isset($data[$data['Use']]['useAsDefaultShipping']) && $data[$data['Use']]['useAsDefaultShipping']) { $member->DefaultShippingAddressID = $address->ID; } if (isset($data[$data['Use']]['useAsDefaultBilling']) && $data[$data['Use']]['useAsDefaultBilling']) { $member->DefaultBillingAddressID = $address->ID; } if ($member->isChanged()) { $member->write(); } } if ($address->exists()) { if ($this->addresstype === 'Shipping') { ShopUserInfo::singleton()->setAddress($address); Zone::cache_zone_ids($address); } $order->{$this->addresstype . 'AddressID'} = $address->ID; if (!$order->BillingAddressID) { $order->BillingAddressID = $address->ID; } $order->write(); $order->extend('onSet' . $this->addresstype . 'Address', $address); } }
public function CountriesForm() { $shopConfig = ShopConfig::get()->First(); $fields = new FieldList($rootTab = new TabSet("Root", $tabMain = new Tab('Shipping', new HiddenField('ShopConfigSection', null, 'Countries'), new GridField('ShippingCountries', 'Shipping Countries', $shopConfig->ShippingCountries(), GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldFilterHeader')->removeComponentsByType('GridFieldAddExistingAutocompleter'))), new Tab('Billing', new GridField('BillingCountries', 'Billing Countries', $shopConfig->BillingCountries(), GridFieldConfig_RecordEditor::create()->removeComponentsByType('GridFieldFilterHeader')->removeComponentsByType('GridFieldAddExistingAutocompleter'))))); $actions = new FieldList(); $form = new Form($this, 'EditForm', $fields, $actions); $form->setTemplate('ShopAdminSettings_EditForm'); $form->setAttribute('data-pjax-fragment', 'CurrentForm'); $form->addExtraClass('cms-content cms-edit-form center ss-tabset'); if ($form->Fields()->hasTabset()) { $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet'); } $form->setFormAction(Controller::join_links($this->Link($this->sanitiseClassName($this->modelClass)), 'Countries/CountriesForm')); $form->loadDataFrom($shopConfig); return $form; }
function cartLink($options = array()) { App::import('Lib', 'Shop.ShopConfig'); $enabled = ShopConfig::load('enabled'); if (!$enabled) { return ''; } $defaultOptions = array('label' => __("Your cart (%nbItem%)", true), 'class' => array('cart')); if (!empty($options) && !is_array($options)) { $options = array('label' => $options); } $opt = array_merge($defaultOptions, $options); $label = $opt['label']; if (!empty($this->params['Shop'])) { foreach ($this->params['Shop'] as $key => $val) { if (!is_array($val)) { $label = str_replace('%' . $key . '%', $val, $label); } } } return $this->Html->link($label, array('plugin' => 'shop', 'controller' => 'shop_cart', 'action' => 'index'), $this->O2form->normalizeAttributesOpt($opt, array('label'))); }
/** * Takes an order from being a cart to awaiting payment. * * @param Member $member - assign a member to the order * * @return boolean - success/failure */ public function placeOrder() { if (!$this->order) { $this->error(_t("OrderProcessor.NULL", "A new order has not yet been started.")); return false; } if (!$this->canPlace($this->order)) { //final cart validation return false; } if ($this->order->Locale) { ShopTools::install_locale($this->order->Locale); } //remove from session $cart = ShoppingCart::curr(); if ($cart && $cart->ID == $this->order->ID) { ShoppingCart::singleton()->clear(); } //update status if ($this->order->TotalOutstanding()) { $this->order->Status = 'Unpaid'; } else { $this->order->Status = 'Paid'; } if (!$this->order->Placed) { $this->order->Placed = SS_Datetime::now()->Rfc2822(); //record placed order datetime if ($request = Controller::curr()->getRequest()) { $this->order->IPAddress = $request->getIP(); //record client IP } } //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again $items = $this->order->Items(); if ($items->exists()) { foreach ($items as $item) { $item->onPlacement(); $item->write(); } } $modifiers = $this->order->Modifiers(); if ($modifiers->exists()) { foreach ($modifiers as $modifier) { $modifier->write(); } } //add member to order & customers group if ($member = Member::currentUser()) { if (!$this->order->MemberID) { $this->order->MemberID = $member->ID; } $cgroup = ShopConfig::current()->CustomerGroup(); if ($cgroup->exists()) { $member->Groups()->add($cgroup); } } //allow decorators to do stuff when order is saved. $this->order->extend('onPlaceOrder'); $this->order->write(); //send confirmation if configured and receipt hasn't been sent if (self::config()->send_confirmation && !$this->order->ReceiptSent) { $this->notifier->sendConfirmation(); } //notify admin, if configured if (self::config()->send_admin_notification) { $this->notifier->sendAdminNotification(); } // Save order reference to session OrderManipulation::add_session_order($this->order); return true; //report success }
/** * Calculates the value of the fedex shipping modifier. If the order information has changed or is not present in the session a call is made to the api to request the rates. * @return {float} Cost of the shipping */ public function value($subtotal = 0) { if ($this->Order()->Items()->count() == 0) { return 0; } $orderItems = implode(',', $this->Order()->Items()->column('ID')); $orderItemsCount = implode(',', $this->Order()->Items()->column('Quantity')); $shippingAddress = array(); $shippingAddressStr = ''; if ($this->Order()) { if ($this->Order()->ShippingAddress && $this->Order()->ShippingAddress->exists()) { $destination = $this->Order()->ShippingAddress; $shippingAddress = array('StreetLines' => array($destination->Address), 'City' => $destination->City, 'StateOrProvinceCode' => $destination->State, 'PostalCode' => $destination->PostalCode, 'CountryCode' => $destination->Country); $addrLine2 = $destination->AddressLine2; $shippingAddressStr = $shippingAddress; $shippingAddressStr['StreetLines'] = implode(' ', $shippingAddressStr['StreetLines']); $shippingAddressStr = implode(',', $shippingAddressStr); } else { if ($this->Order()->Member()->DefaultShippingAddress() && $this->Order()->Member()->DefaultShippingAddress()->exists()) { $destination = $this->Order()->Member()->DefaultShippingAddress(); $shippingAddress = array('StreetLines' => array($destination->Address), 'City' => $destination->City, 'StateOrProvinceCode' => $destination->State, 'PostalCode' => $destination->PostalCode, 'CountryCode' => $destination->Country); $addrLine2 = $destination->AddressLine2; $shippingAddressStr = $shippingAddress; $shippingAddressStr['StreetLines'] = implode(' ', $shippingAddressStr['StreetLines']); $shippingAddressStr = implode(',', $shippingAddressStr); } } } if ($this->Amount > 0 && $orderItems . '|' . $orderItemsCount . '|' . $shippingAddressStr == Session::get('FedExShipping_' . $this->Order()->ID . '.orderhash')) { return $this->Amount; } //Store the default charge in case something goes wrong $this->Amount = self::config()->default_charge; if (!isset($destination)) { return $this->Amount; } $packageItems = array(); foreach ($this->Order()->Items() as $item) { if ($item instanceof Product_OrderItem) { $packageItems[] = new ComplexType\RequestedPackageLineItem(array('Weight' => new ComplexType\Weight(array('Units' => new SimpleType\WeightUnits(SimpleType\WeightUnits::_KG), 'Value' => $item->Product()->Weight)), 'Dimensions' => new ComplexType\Dimensions(array('Length' => $item->Product()->Depth, 'Width' => $item->Product()->Width, 'Height' => $item->Product()->Height, 'Units' => new SimpleType\LinearUnits(SimpleType\LinearUnits::_CM))), 'GroupPackageCount' => $item->Quantity)); } } $rateRequest = $this->getRateRequestAPI(); //RequestedShipment $rateRequest->setRequestedShipment(new ComplexType\RequestedShipment(array('DropoffType' => new SimpleType\DropoffType(SimpleType\DropoffType::_REGULAR_PICKUP), 'ShipTimestamp' => date('c'), 'Shipper' => new ComplexType\Party(array('Address' => new ComplexType\Address($this->getOriginAddress()))), 'Recipient' => new ComplexType\Party(array('Address' => new ComplexType\Address($shippingAddress))), 'PreferredCurrency' => ShopConfig::config()->base_currency, 'RateRequestType' => new SimpleType\RateRequestType(SimpleType\RateRequestType::_LIST), 'PackageCount' => $this->Order()->Items()->count(), 'RequestedPackageLineItems' => $packageItems))); //Allow extensions to modify the $this->extend('updateRateRequest', $rateRequest); //Initialize the request $validateShipmentRequest = new RateService\Request(); if (!$this->config()->test_mode) { $validateShipmentRequest->getSoapClient()->__setLocation('https://ws.fedex.com:443/web-services/rate'); } //Call the api and look through the response $response = $validateShipmentRequest->getGetRatesReply($rateRequest); if (property_exists($response, 'RateReplyDetails') && count($response->RateReplyDetails) > 0) { foreach ($response->RateReplyDetails as $rates) { if ($rates->ServiceType == self::config()->service_type) { foreach ($rates->RatedShipmentDetails as $rate) { if (property_exists($rate, 'TotalNetCharge')) { $charge = $rate->TotalNetCharge; if ($charge->Currency != ShopConfig::get_base_currency() && property_exists($rate, 'CurrencyExchangeRate')) { $charge->Amount = (1 - $rate->CurrencyExchangeRate->Rate + 1) * $charge->Amount; } $this->Amount = $charge->Amount; } } } } } Session::set('FedExShipping_' . $this->Order()->ID . '.orderhash', $orderItems . '|' . $orderItemsCount . '|' . $shippingAddressStr); return $this->Amount; }
/** * 获取免运费金额 */ public function getFreeShippingAmount() { $map = array(); $map['attribute'] = 'FREE_SHIP_AMOUNT'; $info = ShopConfig::model()->findByAttributes($map); if (empty($info)) { return 200; } return $info->value; }
/** * Takes an order from being a cart to awaiting payment. * * @param Member $member - assign a member to the order * * @return boolean - success/failure */ public function placeOrder() { if (!$this->order) { $this->error(_t("OrderProcessor.NoOrderStarted", "A new order has not yet been started.")); return false; } if (!$this->canPlace($this->order)) { //final cart validation return false; } if ($this->order->Locale) { ShopTools::install_locale($this->order->Locale); } // recalculate order to be sure we have the correct total $this->order->calculate(); if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionStart(); } //update status if ($this->order->TotalOutstanding(false)) { $this->order->Status = 'Unpaid'; } else { $this->order->Status = 'Paid'; } if (!$this->order->Placed) { $this->order->Placed = SS_Datetime::now()->Rfc2822(); //record placed order datetime if ($request = Controller::curr()->getRequest()) { $this->order->IPAddress = $request->getIP(); //record client IP } } // Add an error handler that throws an exception upon error, so that we can catch errors as exceptions // in the following block. set_error_handler(function ($severity, $message, $file, $line) { throw new ErrorException($message, 0, $severity, $file, $line); }, E_ALL & ~(E_STRICT | E_NOTICE)); try { //re-write all attributes and modifiers to make sure they are up-to-date before they can't be changed again $items = $this->order->Items(); if ($items->exists()) { foreach ($items as $item) { $item->onPlacement(); $item->write(); } } $modifiers = $this->order->Modifiers(); if ($modifiers->exists()) { foreach ($modifiers as $modifier) { $modifier->write(); } } //add member to order & customers group if ($member = Member::currentUser()) { if (!$this->order->MemberID) { $this->order->MemberID = $member->ID; } $cgroup = ShopConfig::current()->CustomerGroup(); if ($cgroup->exists()) { $member->Groups()->add($cgroup); } } //allow decorators to do stuff when order is saved. $this->order->extend('onPlaceOrder'); $this->order->write(); } catch (Exception $ex) { // Rollback the transaction if an error occurred if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionRollback(); } $this->error($ex->getMessage()); return false; } finally { // restore the error handler, no matter what restore_error_handler(); } // Everything went through fine, complete the transaction if (ShopTools::DBConn()->supportsTransactions()) { ShopTools::DBConn()->transactionEnd(); } //remove from session $cart = ShoppingCart::curr(); if ($cart && $cart->ID == $this->order->ID) { // clear the cart, but don't write the order in the process (order is finalized and should NOT be overwritten) ShoppingCart::singleton()->clear(false); } //send confirmation if configured and receipt hasn't been sent if (self::config()->send_confirmation && !$this->order->ReceiptSent) { $this->notifier->sendConfirmation(); } //notify admin, if configured if (self::config()->send_admin_notification) { $this->notifier->sendAdminNotification(); } // Save order reference to session OrderManipulation::add_session_order($this->order); return true; //report success }