/** * When the user logs in, their session cart should override their db-stored cart. * Current actions take precedence * * @param $user * @param $options * @return unknown_type */ private function doLoginUser($user, $options = array()) { $session = JFactory::getSession(); $old_sessionid = $session->get('old_sessionid'); $user['id'] = intval(JUserHelper::getUserId($user['username'])); // Should check that Tienda is installed first before executing if (!$this->_isInstalled()) { return; } Tienda::load('TiendaHelperCarts', 'helpers.carts'); $helper = new TiendaHelperCarts(); if (!empty($old_sessionid)) { $helper->mergeSessionCartWithUserCart($old_sessionid, $user['id']); JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); $wishlist_model = JModel::getInstance('WishlistItems', 'TiendaModel'); $wishlist_model->setUserForSessionItems($old_sessionid, $user['id']); } else { $helper->updateUserCartItemsSessionId($user['id'], $session->getId()); } $this->checkUserGroup(); return true; }
function getCart() { Tienda::load('TiendaHelperCarts', 'helpers.carts'); JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); JModel::addIncludePath(JPATH_SITE . '/components/com_tienda/models'); // determine whether we're working with a session or db cart $suffix = TiendaHelperCarts::getSuffix(); $model = JModel::getInstance('Carts', 'TiendaModel'); $session = JFactory::getSession(); $user = JFactory::getUser(); $model->setState('filter_user', $user->id); if (empty($user->id)) { $model->setState('filter_session', $session->getId()); } $list = $model->getList(false, false); Tienda::load('Tienda', 'defines'); $config = Tienda::getInstance(); $show_tax = $config->get('display_prices_with_tax'); $this->using_default_geozone = false; if ($show_tax) { Tienda::load('TiendaHelperUser', 'helpers.user'); $geozones = TiendaHelperUser::getGeoZones(JFactory::getUser()->id); if (empty($geozones)) { // use the default $this->using_default_geozone = true; $table = JTable::getInstance('Geozones', 'TiendaTable'); $table->load(array('geozone_id' => Tienda::getInstance()->get('default_tax_geozone'))); $geozones = array($table); } Tienda::load("TiendaHelperProduct", 'helpers.product'); foreach ($list as &$item) { $taxtotal = TiendaHelperProduct::getTaxTotal($item->product_id, $geozones); $item->product_price = $item->product_price + $taxtotal->tax_total; $item->taxtotal = $taxtotal; } } return $list; }
/** * Processes the payment form * and returns HTML to be displayed to the user * generally with a success/failed message * * @param $data array form post data * @return string HTML to display */ function _postPayment($data) { // Process the payment $vars = new JObject(); $orderpayment_id = !empty($data['orderpayment_id']) ? $data['orderpayment_id'] : JRequest::getVar('orderpayment_id'); $cardtype = !empty($data['cardtype']) ? $data['cardtype'] : JRequest::getVar('cardtype'); $cardnum = !empty($data['cardnum']) ? $data['cardnum'] : JRequest::getVar('cardnum'); $cardexp = !empty($data['cardexp']) ? $data['cardexp'] : JRequest::getVar('cardexp'); $cardcvv = !empty($data['cardcvv']) ? $data['cardcvv'] : JRequest::getVar('cardcvv'); $formatted = array('cardtype' => $cardtype, 'cardnum' => $cardnum, 'cardexp' => $cardexp, 'cardcvv' => $cardcvv); JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $orderpayment = JTable::getInstance('OrderPayments', 'TiendaTable'); $orderpayment->load($orderpayment_id); $orderpayment->transaction_details = implode("\n", $formatted); if ($orderpayment->save()) { // Don't remove order quantities until payment is actually received? if ($this->params->get('remove_quantities')) { Tienda::load('TiendaHelperOrder', 'helpers.order'); TiendaHelperOrder::updateProductQuantities($orderpayment->order_id, '-'); } // remove items from cart Tienda::load('TiendaHelperCarts', 'helpers.carts'); TiendaHelperCarts::removeOrderItems($orderpayment->order_id); // send notice of new order Tienda::load("TiendaHelperBase", 'helpers._base'); $helper = TiendaHelperBase::getInstance('Email'); $model = Tienda::getClass("TiendaModelOrders", "models.orders"); $model->setId($orderpayment->order_id); $order = $model->getItem(); $helper->sendEmailNotices($order, 'new_order'); } // display the layout $html = $this->_getLayout('postpayment', $vars); // append the article with offline payment information $html .= $this->_displayArticle(); return $html; }
/** * Verifies the fields in a submitted form. * Then adds the item to the users cart * * @return unknown_type */ function addChildrenToCart() { JRequest::checkToken() or jexit('Invalid Token'); $product_id = JRequest::getInt('product_id'); $quantities = JRequest::getVar('quantities', array(0), 'request', 'array'); $filter_category = JRequest::getInt('filter_category'); Tienda::load("TiendaHelperRoute", 'helpers.route'); $router = new TiendaHelperRoute(); if (!($itemid = $router->product($product_id, $filter_category, true))) { $itemid = $router->category(1, true); } // set the default redirect URL $redirect = "index.php?option=com_tienda&view=products&task=view&id={$product_id}&filter_category={$filter_category}&Itemid=" . $itemid; $redirect = JRoute::_($redirect, false); Tienda::load('TiendaHelperBase', 'helpers._base'); $helper = TiendaHelperBase::getInstance(); if (!Tienda::getInstance()->get('shop_enabled', '1')) { $this->messagetype = 'notice'; $this->message = JText::_('COM_TIENDA_SHOP_DISABLED'); $this->setRedirect($redirect, $this->message, $this->messagetype); return; } $items = array(); // this will collect the items to add to the cart // convert elements to array that can be binded $values = JRequest::get('post'); $attributes_csv = ''; $user = JFactory::getUser(); $cart_id = $user->id; $id_type = "user_id"; if (empty($user->id)) { $session = JFactory::getSession(); $cart_id = $session->getId(); $id_type = "session"; } Tienda::load('TiendaHelperCarts', 'helpers.carts'); $carthelper = new TiendaHelperCarts(); $cart_recurs = $carthelper->hasRecurringItem($cart_id, $id_type); // TODO get the children // loop thru each child, // get the list JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); $model = JModel::getInstance('ProductRelations', 'TiendaModel'); $model->setState('filter_product', $product_id); $model->setState('filter_relation', 'parent'); if ($children = $model->getList()) { foreach ($children as $child) { $product_qty = $quantities[$child->product_id_to]; // Integrity checks on quantity being added if ($product_qty < 0) { $product_qty = '1'; } // using a helper file to determine the product's information related to inventory $availableQuantity = Tienda::getClass('TiendaHelperProduct', 'helpers.product')->getAvailableQuantity($child->product_id_to, $attributes_csv); if ($availableQuantity->product_check_inventory && $product_qty > $availableQuantity->quantity) { $this->messagetype = 'notice'; $this->message = JText::_(JText::sprintf("COM_TIENDA_NOT_AVAILABLE_QUANTITY", $availableQuantity->product_name, $product_qty)); $this->setRedirect($redirect, $this->message, $this->messagetype); return; } // do the item's charges recur? does the cart already have a subscription in it? if so, fail with notice $product = JTable::getInstance('Products', 'TiendaTable'); $product->load(array('product_id' => $child->product_id_to)); // if product notforsale, fail if ($product->product_notforsale) { $this->messagetype = 'notice'; $this->message = JText::_('COM_TIENDA_PRODUCT_NOT_FOR_SALE'); $this->setRedirect($redirect, $this->message, $this->messagetype); return; } if ($product->product_recurs && $cart_recurs) { $this->messagetype = 'notice'; $this->message = JText::_('COM_TIENDA_CART_ALREADY_RECURS'); $this->setRedirect($redirect, $this->message, $this->messagetype); return; } if ($product->product_recurs) { $product_qty = '1'; } // create cart object out of item properties $item = new JObject(); $item->user_id = JFactory::getUser()->id; $item->product_id = (int) $child->product_id_to; $item->product_qty = (int) $product_qty; $item->product_attributes = $attributes_csv; $item->vendor_id = '0'; // vendors only in enterprise version // does the user/cart match all dependencies? $canAddToCart = $carthelper->canAddItem($item, $cart_id, $id_type); if (!$canAddToCart) { $this->messagetype = 'notice'; $this->message = JText::_('COM_TIENDA_CANNOT_ADD_ITEM_TO_CART') . " - " . $carthelper->getError(); $this->setRedirect($redirect, $this->message, $this->messagetype); return; } // no matter what, fire this validation plugin event for plugins that extend the checkout workflow $results = array(); $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger("onBeforeAddToCart", array($item, $values)); for ($i = 0; $i < count($results); $i++) { $result = $results[$i]; if (!empty($result->error)) { $this->messagetype = 'notice'; $this->message = $result->message; $this->setRedirect($redirect, $this->message, $this->messagetype); return; } } // if here, add to cart $items[] = $item; } } if (!empty($items)) { Tienda::load('TiendaHelperCarts', 'helpers.carts'); foreach ($items as $item) { // add the item to the cart $cart_helper = new TiendaHelperCarts(); $cartitem = $cart_helper->addItem($item); // fire plugin event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onAfterAddToCart', array($cartitem, $values)); } $this->messagetype = 'message'; $this->message = JText::_('COM_TIENDA_ITEMS_ADDED_TO_YOUR_CART'); } // After login, session_id is changed by Joomla, so store this for reference $session = JFactory::getSession(); $session->set('old_sessionid', $session->getId()); // get the 'success' redirect url // TODO Enable redirect via base64_encoded urls? switch (Tienda::getInstance()->get('addtocartaction', 'redirect')) { case "redirect": $returnUrl = base64_encode($redirect); $itemid = $router->findItemid(array('view' => 'checkout')); $redirect = JRoute::_("index.php?option=com_tienda&view=carts&Itemid=" . $itemid, false); if (strpos($redirect, '?') === false) { $redirect .= "?return=" . $returnUrl; } else { $redirect .= "&return=" . $returnUrl; } break; case "0": case "none": break; case "lightbox": default: // TODO Figure out how to get the lightbox to display even after a redirect break; } $this->setRedirect($redirect, $this->message, $this->messagetype); return; }
/** * Validate Coupon Code * * @return unknown_type */ function validateCouponCode() { JLoader::import('com_tienda.library.json', JPATH_ADMINISTRATOR . '/components'); $elements = json_decode(preg_replace('/[\\n\\r]+/', '\\n', JRequest::getVar('elements', '', 'post', 'string'))); // convert elements to array that can be binded Tienda::load('TiendaHelperBase', 'helpers._base'); $helper = TiendaHelperBase::getInstance(); $values = $helper->elementsToArray($elements); $coupon_code = JRequest::getVar('coupon_code', ''); $response = array(); $response['msg'] = ''; $response['error'] = ''; // check if coupon code is valid $user_id = JFactory::getUser()->id; Tienda::load('TiendaHelperCoupon', 'helpers.coupon'); $helper_coupon = new TiendaHelperCoupon(); $coupon = $helper_coupon->isValid($coupon_code, 'code', $user_id); if (!$coupon) { $response['error'] = '1'; $response['msg'] = $helper->generateMessage($helper_coupon->getError()); echo json_encode($response); return; } if (!empty($values['coupons']) && in_array($coupon->coupon_id, $values['coupons'])) { $response['error'] = '1'; $response['msg'] = $helper->generateMessage(JText::_('COM_TIENDA_THIS_COUPON_ALREADY_ADDED_TO_THE_ORDER')); echo json_encode($response); return; } // TODO Check that the user can add this coupon to the order $can_add = true; if (!$can_add) { $response['error'] = '1'; $response['msg'] = $helper->generateMessage(JText::_('COM_TIENDA_CANNOT_ADD_THIS_COUPON_TO_ORDER')); echo json_encode($response); return; } // Check per product coupon code $ids = array(); $items = TiendaHelperCarts::getProductsInfo(); foreach ($items as $item) { $ids[] = $item->product_id; } if ($coupon->coupon_type == '1') { $check = $helper_coupon->checkByProductIds($coupon->coupon_id, $ids); if (!$check) { $response['error'] = '1'; $response['msg'] = $helper->generateMessage(JText::_('COM_TIENDA_THIS_COUPON_NOT_RELATED_TO_PRODUCT_IN_YOUR_CART')); echo json_encode($response); return; } } // if valid, return the html for the coupon $response['msg'] = " <input type='hidden' name='coupons[]' value='{$coupon->coupon_id}'>"; echo json_encode($response); return; }
} require_once dirname(__FILE__) . '/helper.php'; // include lang files $lang = JFactory::getLanguage(); $lang->load('com_tienda', JPATH_BASE); $lang->load('com_tienda', JPATH_ADMINISTRATOR); $mainframe = JFactory::getApplication(); $document = JFactory::getDocument(); // params $display_null = $params->get('display_null', '1'); $null_text = $params->get('null_text', 'No Items in Your Cart'); $isAjax = $mainframe->getUserState('mod_usercart.isAjax'); $ajax = $isAjax == '1'; // Grab the cart Tienda::load('TiendaHelperCarts', 'helpers.carts'); $items = TiendaHelperCarts::getProductsInfo(); $num = count($items); // Convert the cart to a "fake" order, to show totals and others things JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $orderTable = JTable::getInstance('Orders', 'TiendaTable'); foreach ($items as $item) { $orderTable->addItem($item); } $items = $orderTable->getItems(); Tienda::load('Tienda', 'defines'); $config = Tienda::getInstance(); $show_tax = $config->get('display_prices_with_tax'); if ($show_tax) { Tienda::load('TiendaHelperUser', 'helpers.user'); $geozones = TiendaHelperUser::getGeoZones(JFactory::getUser()->id); if (empty($geozones)) {
/** * Validates the credit amount and applies it to the order * @return unknown_type */ function validateApplyCredit() { JLoader::import('com_tienda.library.json', JPATH_ADMINISTRATOR . '/components'); $elements = json_decode(preg_replace('/[\\n\\r]+/', '\\n', JRequest::getVar('elements', '', 'post', 'string'))); // convert elements to array that can be binded Tienda::load('TiendaHelperBase', 'helpers._base'); $helper = TiendaHelperBase::getInstance(); $values = $helper->elementsToArray($elements); $user_id = $this->user->id; $apply_credit_amount = (double) JRequest::getVar('apply_credit_amount', ''); $response = array(); $response['msg'] = ''; $response['error'] = ''; // is the credit amount valid (i.e. greater than 0, if ($apply_credit_amount < (double) '0.00') { $response['error'] = '1'; $response['msg'] = $helper->generateMessage(JText::_('COM_TIENDA_PLEASE_SPECIFY_VALID_CREDIT_AMOUNT')); echo json_encode($response); return; } // less than/== their available amount & order amount? $userinfo = JTable::getInstance('UserInfo', 'TiendaTable'); $userinfo->load(array('user_id' => $user_id)); $userinfo->credits_total = (double) $userinfo->credits_total; if ($apply_credit_amount > $userinfo->credits_total) { $apply_credit_amount = $userinfo->credits_total; } // get the order object so we can populate it $order = $this->_order; // a TableOrders object (see constructor) // bind what you can from the post $order->bind($values); // unset the order credit because it may have been set by the bind $order->order_credit = '0'; // set the currency Tienda::load('TiendaHelperCurrency', 'helpers.currency'); $order->currency_id = TiendaHelperCurrency::getCurrentCurrency(); // USD is default if no currency selected // set the shipping method $order->shipping = new JObject(); $order->shipping->shipping_price = @$values['shipping_price']; $order->shipping->shipping_extra = @$values['shipping_extra']; $order->shipping->shipping_name = @$values['shipping_name']; $order->shipping->shipping_tax = @$values['shipping_tax']; // set the addresses $this->setAddresses($values, false, true); // get the items and add them to the order Tienda::load('TiendaHelperCarts', 'helpers.carts'); $items = TiendaHelperCarts::getProductsInfo(); foreach ($items as $item) { $order->addItem($item); } // get all coupons and add them to the order if (!empty($values['coupons'])) { foreach ($values['coupons'] as $coupon_id) { $coupon = JTable::getInstance('Coupons', 'TiendaTable'); $coupon->load(array('coupon_id' => $coupon_id)); $order->addCoupon($coupon); } } $this->addAutomaticCoupons(); // get the order totals $order->calculateTotals(); if ($apply_credit_amount > $order->order_total) { $apply_credit_amount = $order->order_total; } // if valid, return the html for the credit $response['msg'] = "<input type='hidden' name='order_credit' value='{$apply_credit_amount}'>"; echo json_encode($response); return; }
/** * Given an order_id, will remove the order's items from the user's cart * * @param unknown_type $order_id * @return unknown_type */ function removeOrderItemsFromCart($order_id) { Tienda::load('TiendaHelperCarts', 'helpers.carts'); TiendaHelperCarts::removeOrderItems($order_id); }
/** * This method for after an orderpayment has been received when the admin click on the * that performs acts such as: * enabling file downloads * * @param $order_id * @return unknown_type */ public static function doCompletedOrderTasks($order_id) { $errors = array(); $error = false; JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($order_id); if (empty($order->order_id)) { // TODO we must make sure this class is always instantiated $this->setError(JText::_('COM_TIENDA_INVALID_ORDER_ID')); return false; } // Fire an doCompletedOrderTasks event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('doCompletedOrderTasks', array($order_id)); // 0. Enable One-Time Purchase Subscriptions TiendaHelperOrder::enableNonRecurringSubscriptions($order_id); // 1. Update quantities TiendaHelperOrder::updateProductQuantities($order_id, '-'); // 2. remove items from cart Tienda::load('TiendaHelperCarts', 'helpers.carts'); TiendaHelperCarts::removeOrderItems($order_id); // 3. add productfiles to product downloads TiendaHelperOrder::enableProductDownloads($order_id); // 4. do SQL queries $helper = TiendaHelperBase::getInstance('Sql'); $helper->processOrder($order_id); // register commission if amigos is installed $helper = TiendaHelperBase::getInstance('Amigos'); $helper->createCommission($order_id); // change ticket limits if billets is installed $helper = TiendaHelperBase::getInstance('Billets'); $helper->processOrder($order_id); // add to JUGA Groups if JUGA installed $helper = TiendaHelperBase::getInstance('Juga'); $helper->processOrder($order_id); // change core ACL if set $helper = TiendaHelperBase::getInstance('User'); $helper->processOrder($order_id); // do Ambra Subscriptions Integration processes $helper = TiendaHelperBase::getInstance('Ambrasubs'); $helper->processOrder($order_id); // increase the hit counts for coupons in the order $helper = TiendaHelperBase::getInstance('Coupon'); $helper->processOrder($order_id); if ($error) { $this->setError(implode('<br/>', $errors)); return false; } else { $order->completed_tasks = '1'; $order->store(); return true; } }
function getProductsInfo() { Tienda::load("TiendaHelperProduct", 'helpers.product'); $product_helper = TiendaHelperBase::getInstance('Product'); DSCModel::addIncludePath(JPATH_SITE . DS . 'components/com_tienda/models'); DSCModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $model = DSCModel::getInstance('Carts', 'TiendaModel'); $session = JFactory::getSession(); $user_id = $session->get('user_id', '', 'tienda_pos'); $model->setState('filter_user', $user_id); Tienda::load("TiendaHelperBase", 'helpers._base'); Tienda::load("TiendaHelperCarts", 'helpers.carts'); $user_helper = TiendaHelperBase::getInstance('User'); $filter_group = $user_helper->getUserGroup($user_id); $model->setState('filter_group', $filter_group); $cartitems = $model->getList(); $productitems = array(); foreach ($cartitems as $cartitem) { //echo Tienda::dump($cartitem); unset($productModel); $productModel = DSCModel::getInstance('Products', 'TiendaModel'); $filter_group = $user_helper->getUserGroup($user_id, $cartitem->product_id); $productModel->setState('filter_group', $filter_group); $productModel->setId($cartitem->product_id); if ($productItem = $productModel->getItem(false)) { $productItem->price = $productItem->product_price = !$cartitem->product_price_override->override ? $cartitem->product_price : $productItem->price; //we are not overriding the price if its a recurring && price if (!$productItem->product_recurs && $cartitem->product_price_override->override) { // at this point, ->product_price holds the default price for the product, // but the user may qualify for a discount based on volume or date, so let's get that price override // TODO Shouldn't we remove this? Is it necessary? $cartitem has already done this in the carts model! $productItem->product_price_override = $product_helper->getPrice($productItem->product_id, $cartitem->product_qty, $filter_group, JFactory::getDate()->toMySQL()); if (!empty($productItem->product_price_override)) { $productItem->product_price = $productItem->product_price_override->product_price; } } if ($productItem->product_check_inventory) { // using a helper file,To determine the product's information related to inventory $availableQuantity = $product_helper->getAvailableQuantity($productItem->product_id, $cartitem->product_attributes); if ($availableQuantity->product_check_inventory && $cartitem->product_qty > $availableQuantity->quantity && $availableQuantity->quantity >= 1) { JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_TIENDA_CART_QUANTITY_ADJUSTED', $productItem->product_name, $cartitem->product_qty, $availableQuantity->quantity)); $cartitem->product_qty = $availableQuantity->quantity; } // removing the product from the cart if it's not available if ($availableQuantity->quantity == 0) { if (empty($cartitem->user_id)) { TiendaHelperCarts::removeCartItem($session_id, $cartitem->user_id, $cartitem->product_id); } else { TiendaHelperCarts::removeCartItem($cartitem->session_id, $cartitem->user_id, $cartitem->product_id); } JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_TIENDA_NOT_AVAILABLE') . " " . $productItem->product_name); continue; } } // TODO Push this into the orders object->addItem() method? $orderItem = JTable::getInstance('OrderItems', 'TiendaTable'); $orderItem->product_id = $productItem->product_id; $orderItem->orderitem_sku = $cartitem->product_sku; $orderItem->orderitem_name = $productItem->product_name; $orderItem->orderitem_quantity = $cartitem->product_qty; $orderItem->orderitem_price = $productItem->product_price; $orderItem->orderitem_attributes = $cartitem->product_attributes; $orderItem->orderitem_attribute_names = $cartitem->attributes_names; $orderItem->orderitem_attributes_price = $cartitem->orderitem_attributes_price; $orderItem->orderitem_final_price = ($orderItem->orderitem_price + $orderItem->orderitem_attributes_price) * $orderItem->orderitem_quantity; $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger("onGetAdditionalOrderitemKeyValues", array($cartitem)); foreach ($results as $result) { foreach ($result as $key => $value) { $orderItem->set($key, $value); } } // TODO When do attributes for selected item get set during admin-side order creation? array_push($productitems, $orderItem); } } return $productitems; }
/** * * Enter description here ... * @param unknown_type $values * @param unknown_type $files * @return return_type */ function addToCart($values = array(), $files = array()) { // create cart object out of item properties $item = new JObject(); $item->user_id = $this->user_id; $item->product_id = (int) $this->product_id; $item->product_qty = !empty($this->product_quantity) ? $this->product_quantity : '1'; $item->product_attributes = $this->product_attributes; $item->vendor_id = $this->vendor_id; $item->cartitem_params = $this->wishlistitem_params; // onAfterCreateItemForAddToCart: plugin can add values to the item before it is being validated /added // once the extra field(s) have been set, they will get automatically saved $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger("onAfterCreateItemForAddToCart", array($item, $values, $files)); foreach ($results as $result) { foreach ($result as $key => $value) { $item->set($key, $value); } } if (!$this->isAvailable()) { return false; } Tienda::load('TiendaHelperProduct', 'helpers.product'); $product_helper = new TiendaHelperProduct(); $availableQuantity = $product_helper->getAvailableQuantity($this->product_id, $this->product_attributes); if ($availableQuantity->product_check_inventory && $item->product_qty > $availableQuantity->quantity) { $this->setError(JText::_(JText::sprintf("COM_TIENDA_NOT_AVAILABLE_QUANTITY", $availableQuantity->product_name, $item->product_qty))); return false; } Tienda::load('TiendaHelperCarts', 'helpers.carts'); $carthelper = new TiendaHelperCarts(); // does the user/cart match all dependencies? $canAddToCart = $carthelper->canAddItem($item, $this->user_id, 'user_id'); if (!$canAddToCart) { $this->setError(JText::_('COM_TIENDA_CANNOT_ADD_ITEM_TO_CART') . " - " . $carthelper->getError()); return false; } // no matter what, fire this validation plugin event for plugins that extend the checkout workflow $results = array(); $dispatcher = JDispatcher::getInstance(); $results = $dispatcher->trigger("onBeforeAddToCart", array(&$item, $values)); for ($i = 0; $i < count($results); $i++) { $result = $results[$i]; if (!empty($result->error)) { $this->setError(JText::_('COM_TIENDA_CANNOT_ADD_ITEM_TO_CART') . " - " . $result->message); return false; } } // if here, add to cart // After login, session_id is changed by Joomla, so store this for reference $session = JFactory::getSession(); $session->set('old_sessionid', $session->getId()); // add the item to the cart $cartitem = $carthelper->addItem($item); // fire plugin event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onAfterAddToCart', array($cartitem, $values)); return $cartitem; }
public function prepare($values, $options = array(), &$order = null) { if (empty($order)) { $order = $this->getTable(); } $this->_order =& $order; $this->_values = $values; $this->_options = $options; if (empty($options['skip_adjust_credits'])) { $order->_adjustCredits = true; // this is not a POS order, so adjust the user's credits (if any used) } $order->bind($values); $order->user_id = $values['user_id']; $order->ip_address = $values['ip_address']; //$_SERVER['REMOTE_ADDR']; // set the currency if (empty($values['currency_id'])) { Tienda::load('TiendaHelperCurrency', 'helpers.currency'); $order->currency_id = TiendaHelperCurrency::getCurrentCurrency(); } // Store the text verion of the currency for order integrity Tienda::load('TiendaHelperOrder', 'helpers.order'); $order->order_currency = TiendaHelperOrder::currencyToParameters($order->currency_id); $saveAddressesToDB = empty($options["save_addresses"]) ? false : true; $this->setAddresses($values, $saveAddressesToDB); // set the shipping method if (@$values['shippingrequired'] || !empty($values['shipping_plugin'])) { $order->shipping = new JObject(); $order->shipping->shipping_price = $values['shipping_price']; $order->shipping->shipping_extra = $values['shipping_extra']; $order->shipping->shipping_name = $values['shipping_name']; $order->shipping->shipping_tax = $values['shipping_tax']; } if (empty($options['skip_add_items'])) { //get the items from the current user's cart and add them to the order Tienda::load('TiendaHelperCarts', 'helpers.carts'); $reviewitems = TiendaHelperCarts::getProductsInfo(); foreach ($reviewitems as $reviewitem) { $order->addItem($reviewitem); } } if (empty($options['skip_add_coupons'])) { $this->addCoupons($values); } if (empty($options['skip_add_credit']) && !empty($values['order_credit'])) { $order->addCredit($values['order_credit']); } $order->order_state_id = empty($values['orderstate_id']) ? $this->initial_order_state : $values['orderstate_id']; $order->calculateTotals(); $order->getShippingTotal(); $order->getInvoiceNumber(); return $order; }
/** * Processes the payment form * and returns HTML to be displayed to the user * generally with a success/failed message * * IMPORTANT: It is the responsibility of each payment plugin * to tell clear the user's cart (if the payment status warrants it) by using: * * $this->removeOrderItemsFromCart( $order_id ); * * @param $data array form post data * @return string HTML to display */ function _postPayment($data) { // Process the payment $orderpayment_type = JRequest::getVar('orderpayment_type'); if ($orderpayment_type == $this->_element) { $paction = JRequest::getVar('paction'); $html = ""; switch ($paction) { case "message": $user = JFactory::getUser(); $checkout = JRequest::getInt('checkout'); // check if cart has recurring item and if checkout variable is set to '1' Tienda::load("TiendaHelperCarts", 'helpers.carts'); $carts_helper = new TiendaHelperCarts(); if ($carts_helper->hasRecurringItem($user->id) && $checkout == '1') { // check if the cart has only 1 item JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); $model = JModel::getInstance('Carts', 'TiendaModel'); $model->setState('filter_user', $user->id); $items = $model->getList(); if (count($items) == '1') { // check if the item in the cart is recurring product $model = JModel::getInstance('Products', 'TiendaModel'); $model->setId($items[0]->product_id); $product = $model->getItem(); if ($product->product_recurs) { // get the order_id from the session set by the prePayment $mainframe = JFactory::getApplication(); $order_id = (int) $mainframe->getUserState('tienda.order_id'); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($order_id); $items = $order->getItems(); // prepare payment for the recurring item Click Here to View and Print an Invoice //$html = $this->_secondPrePayment($order_id); $html = $this->_secondPrePayment(); } } } else { $text = JText::_('TIENDA MONEYBOOKERS MESSAGE PAYMENT SUCCESS'); $html .= "<div align='center'><strong>" . $this->_renderHtml($text) . "<strong></div>"; $html .= $this->_displayArticle(); } break; case "process": $html = $this->_process(); $app = JFactory::getApplication(); $app->close(); break; case "cancel": $text = JText::_('TIENDA MONEYBOOKERS MESSAGE CANCEL'); $html .= $this->_renderHtml($text); break; default: $text = JText::_('TIENDA MONEYBOOKERS MESSAGE INVALID ACTION'); $html .= $this->_renderHtml($text); break; } return $html; } }
/** * Checks the integrity of a cart * to make sure all dependencies are met * * @param $cart_id * @param $id_type * @return unknown_type */ function checkIntegrity($cart_id, $id_type = 'user_id') { $user_id = 0; $session_id = ''; JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/models'); // get the cart's items as well as user info (if logged in) $model = JModel::getInstance('Carts', 'TiendaModel'); switch ($id_type) { case "session": case "session_id": $model->setState('filter_session', $cart_id); $session_id = $cart_id; break; case "user": case "user_id": default: $model->setState('filter_user', $cart_id); $user_id = $cart_id; break; } $carthelper = new TiendaHelperCarts(); // get the cart items $cart_items = $model->getList(false, false); if (!empty($cart_items)) { // foreach foreach ($cart_items as $citem) { if (!$carthelper->canAddItem($citem, $cart_id, $id_type)) { JFactory::getApplication()->enqueueMessage(JText::_('COM_TIENDA_REMOVING_ITEM_FROM_CART_FOR_FAILED_DEPENDENCIES') . " - " . $citem->product_name, 'message'); $carthelper->removeCartItem($session_id, $user_id, $citem->product_id); } } } return true; }
/** * Processes the sale payment * * @param array $data IPN data * @return boolean Did the IPN Validate? * @access protected */ function _processSale($data, $ipnValidationFailed = '') { $send_email = false; /* * validate the payment data */ $errors = array(); if (!empty($ipnValidationFailed)) { $errors[] = $ipnValidationFailed; } // is the recipient correct? if (empty($data['receiver_email']) || $data['receiver_email'] != $this->_getParam('merchant_email')) { $errors[] = JText::_('PAYPAL MESSAGE RECEIVER INVALID'); } // load the orderpayment record and set some values JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $orderpayment = JTable::getInstance('OrderPayments', 'TiendaTable'); $orderpayment->load($data['custom']); $orderpayment->transaction_details = $data['transaction_details']; $orderpayment->transaction_id = $data['txn_id']; $orderpayment->transaction_status = $data['payment_status']; // check the stored amount against the payment amount Tienda::load('TiendaHelperBase', 'helpers._base'); $stored_amount = TiendaHelperBase::number($orderpayment->get('orderpayment_amount'), array('thousands' => '')); $respond_amount = TiendaHelperBase::number($data['mc_gross'], array('thousands' => '')); if ($stored_amount != $respond_amount) { $errors[] = JText::_('PAGSEGURO MESSAGE PAYMENT AMOUNT INVALID'); $errors[] = $stored_amount . " != " . $respond_amount; } // check the payment status if (empty($data['payment_status']) || $data['payment_status'] != 'Completed' && $data['payment_status'] != 'Pending') { $errors[] = JText::sprintf('PAYPAL MESSAGE STATUS INVALID', @$data['payment_status']); } // set the order's new status and update quantities if necessary JLoader::import('com_tienda.helpers.order', JPATH_ADMINISTRATOR . '/components'); JLoader::import('com_tienda.helpers.carts', JPATH_ADMINISTRATOR . '/components'); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($orderpayment->order_id); if (count($errors)) { // if an error occurred $order->order_state_id = $this->params->get('failed_order_state', '10'); // FAILED } elseif (@$data['payment_status'] == 'Pending') { // if the transaction has the "pending" status, $order->order_state_id = Tienda::getInstance('pending_order_state', '1'); // PENDING // Update quantities for echeck payments TiendaHelperOrder::updateProductQuantities($orderpayment->order_id, '-'); // remove items from cart TiendaHelperCarts::removeOrderItems($orderpayment->order_id); } else { $order->order_state_id = $this->params->get('payment_received_order_state', '17'); // PAYMENT RECEIVED // do post payment actions $setOrderPaymentReceived = true; // send email $send_email = true; } // save the order if (!$order->save()) { $errors[] = $order->getError(); } // save the orderpayment if (!$orderpayment->save()) { $errors[] = $orderpayment->getError(); } if (!empty($setOrderPaymentReceived)) { $this->setOrderPaymentReceived($orderpayment->order_id); } if ($send_email) { // send notice of new order Tienda::load("TiendaHelperBase", 'helpers._base'); $helper = TiendaHelperBase::getInstance('Email'); $model = Tienda::getClass("TiendaModelOrders", "models.orders"); $model->setId($orderpayment->order_id); $order = $model->getItem(); $helper->sendEmailNotices($order, 'new_order'); } return count($errors) ? implode("\n", $errors) : ''; }
/** * this is updating the transaction id with the Google Order id * */ function _saveTransaction($data, $error = '') { $errors = array(); JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $orderpayment = JTable::getInstance('OrderPayments', 'TiendaTable'); $oredrPaymentId = $data['shopping-cart']['merchant-private-data']['orderPaymentId']['VALUE']; $orderpayment->load($oredrPaymentId); if (empty($orderpayment->orderpayment_id)) { $errors[] = JText::_('COM_TIENDA_GOOGLECHECKOUT_CHECKOUT_INVALID_ORDERPAYMENTID'); return count($errors) ? implode("\n", $errors) : ''; } $orderpayment->transaction_id = $data['google-order-number']['VALUE']; // update the orderpayment if (!$orderpayment->save()) { $errors[] = $orderpayment->getError(); } // set the order's new status and update quantities if necessary Tienda::load('TiendaHelperOrder', 'helpers.order'); Tienda::load('TiendaHelperCarts', 'helpers.carts'); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($orderpayment->order_id); // if the transaction has the "pending" status, $order->order_state_id = Tienda::getInstance('pending_order_state', '1'); // PENDING // Update quantities for echeck payments TiendaHelperOrder::updateProductQuantities($orderpayment->order_id, '-'); // remove items from cart TiendaHelperCarts::removeOrderItems($orderpayment->order_id); // send email $send_email = true; if ($send_email) { // send notice of new order Tienda::load("TiendaHelperBase", 'helpers._base'); $helper = TiendaHelperBase::getInstance('Email'); $model = Tienda::getClass("TiendaModelOrders", "models.orders"); $model->setId($orderpayment->order_id); $order = $model->getItem(); $helper->sendEmailNotices($order, 'new_order'); } return count($errors) ? implode("\n", $errors) : ''; }
/** * * @return unknown_type */ function update() { $model = $this->getModel(strtolower(TiendaHelperCarts::getSuffix())); $this->_setModelState(); $user = JFactory::getUser(); $session = JFactory::getSession(); $cids = JRequest::getVar('cid', array(0), '', 'ARRAY'); $product_attributes = JRequest::getVar('product_attributes', array(0), '', 'ARRAY'); $quantities = JRequest::getVar('quantities', array(0), '', 'ARRAY'); $post = JRequest::get('post'); $msg = JText::_('COM_TIENDA_QUANTITIES_UPDATED'); $remove = JRequest::getVar('remove'); if ($remove) { foreach ($cids as $cart_id => $product_id) { // $keynames = explode('.', $key); // $attributekey = $keynames[0].'.'.$keynames[1]; // $index = $keynames[2]; $row = $model->getTable(); //main cartitem keys $ids = array('user_id' => $user->id, 'cart_id' => $cart_id); // fire plugin event: onGetAdditionalCartKeyValues //this event allows plugins to extend the multiple-column primary key of the carts table $additionalKeyValues = TiendaHelperCarts::getAdditionalKeyValues(null, $post, $index); if (!empty($additionalKeyValues)) { $ids = array_merge($ids, $additionalKeyValues); } if (empty($user->id)) { $ids['session_id'] = $session->getId(); } if ($return = $row->delete(array('cart_id' => $cart_id))) { $item = new JObject(); $item->product_id = $product_id; $item->product_attributes = $product_attributes[$cart_id]; $item->vendor_id = '0'; // vendors only in enterprise version // fire plugin event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onRemoveFromCart', array($item)); } } } else { foreach ($quantities as $cart_id => $value) { $carts = JTable::getInstance('Carts', 'TiendaTable'); $carts->load(array('cart_id' => $cart_id)); $product_id = $carts->product_id; $value = (int) $value; // $keynames = explode('.', $key); // $product_id = $keynames[0]; // $attributekey = $product_id.'.'.$keynames[1]; // $index = $keynames[2]; $vals = array(); $vals['user_id'] = $user->id; $vals['session_id'] = $session->getId(); $vals['product_id'] = $product_id; // fire plugin event: onGetAdditionalCartKeyValues //this event allows plugins to extend the multiple-column primary key of the carts table // $additionalKeyValues = TiendaHelperCarts::getAdditionalKeyValues( null, $post, $index ); // if (!empty($additionalKeyValues)) // { // $vals = array_merge($vals, $additionalKeyValues); // } // using a helper file,To determine the product's information related to inventory $availableQuantity = Tienda::getClass('TiendaHelperProduct', 'helpers.product')->getAvailableQuantity($product_id, $product_attributes[$cart_id]); if ($availableQuantity->product_check_inventory && $value > $availableQuantity->quantity) { JFactory::getApplication()->enqueueMessage(JText::sprintf("COM_TIENDA_NOT_AVAILABLE_QUANTITY", $availableQuantity->product_name, $value)); continue; } if ($value > 1) { $product = JTable::getInstance('Products', 'TiendaTable'); $product->load(array('product_id' => $product_id)); if ($product->quantity_restriction) { $min = $product->quantity_min; $max = $product->quantity_max; if ($max) { if ($value > $max) { $msg = JText::_('COM_TIENDA_REACHED_MAXIMUM_QUANTITY_FOR_THIS_OBJECT') . $max; $value = $max; } } if ($min) { if ($value < $min) { $msg = JText::_('COM_TIENDA_REACHED_MAXIMUM_QUANTITY_FOR_THIS_OBJECT') . $min; $value = $min; } } } if ($product->product_recurs) { $value = 1; } } $row = $model->getTable(); $vals['product_attributes'] = $product_attributes[$cart_id]; $vals['product_qty'] = $value; if (empty($vals['product_qty']) || $vals['product_qty'] < 1) { // remove it if ($return = $row->delete($cart_id)) { $item = new JObject(); $item->product_id = $product_id; $item->product_attributes = $product_attributes[$cart_id]; $item->vendor_id = '0'; // vendors only in enterprise version // fire plugin event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onRemoveFromCart', array($item)); } } else { $row->load($cart_id); $row->product_qty = $vals['product_qty']; $row->save(); } } } $carthelper = new TiendaHelperCarts(); $carthelper->fixQuantities(); if (empty($user->id)) { $carthelper->checkIntegrity($session->getId(), 'session_id'); } else { $carthelper->checkIntegrity($user->id); } Tienda::load("TiendaHelperRoute", 'helpers.route'); $router = new TiendaHelperRoute(); $redirect = JRoute::_("index.php?option=com_tienda&view=carts&Itemid=" . $router->findItemid(array('view' => 'carts')), false); $this->setRedirect($redirect, $msg); }
function _process($data) { $errors = array(); // load the orderpayment record and set some values JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tienda/tables'); $orderpayment = JTable::getInstance('OrderPayments', 'TiendaTable'); $orderpayment->load($data['reference']); $orderpayment->transaction_details = $data['key']; $orderpayment->transaction_id = $data['txn_id']; // set the order's new status and update quantities if necessary Tienda::load('TiendaHelperOrder', 'helpers.order'); Tienda::load('TiendaHelperCarts', 'helpers.carts'); $order = JTable::getInstance('Orders', 'TiendaTable'); $order->load($orderpayment->order_id); if ($data['txn_status'] == '2') { $order->order_state_id = $this->params->get('payment_received_order_state', '17'); // PAYMENT RECEIVED // do post payment actions $setOrderPaymentReceived = true; } else { $orderpayment->transaction_status = 'Failed'; $order->order_state_id = $this->params->get('failed_order_state', '10'); // FAILED } // save the order if (!$order->save()) { $errors[] = $order->getError(); } // save the orderpayment if (!$orderpayment->save()) { $errors[] = $orderpayment->getError(); } if (!empty($setOrderPaymentReceived)) { $this->setOrderPaymentReceived($orderpayment->order_id); } $html = ""; if ($data['txn_status'] == '2') { // clear the shopping cart Tienda::load('TiendaHelperCarts', 'helpers.carts'); TiendaHelperCarts::removeOrderItems($orderpayment->order_id); $html = "<dl id='system-message'><dt class='message'>message</dt><dd class='message fade'><ul><li>Your order has been completed successfully. Your transaction no. is <strong>" . $data['txn_id'] . "</strong> and your receipt no. is <strong>" . $data['receipt_no'] . "</strong> <br />( <a href='index.php?option=com_tienda&view=orders&task=view&id=" . $orderpayment->order_id . "'>view invoice</a> )</li></ul></dd></dl>"; } else { $html = "<div style='padding-top: 10px;' id='validationmessage'><dl id='system-message'><dt class='notice'>notice</dt><dd class='notice message fade'><ul><li>Unable to complete order because : <i>" . $data['response_text'] . "</i></li></ul></dd></dl></div><style type='text/css'>.postpayment_article{display:none!important;visibility:hidden!important;}</style>"; } return $html; }