public function add_to_cart() { $request = $this->application->getRequest(); $productID = $request->get('productID'); $customerOrderID = $request->get('customerOrderID'); $count = $request->get('count'); if (!isset($customerOrderID) && intval($customerOrderID == 0)) { throw new Exception('Order ID is required'); } $order = CustomerOrder::getInstanceById($customerOrderID); $order->load(true); $order->loadAll(); //throw new Exception('order : ' . $order->getTotal(true)); $product = Product::getInstanceByID($productID, true, true); $product->load(true); //$variations = !$product->parent->get() ? $product->getVariationData($this->application) : array('1','2'); //throw new Exception('variation ' . json_encode($variations) . ' parent : ' . $product->getID() . ' productID ' . $productID); if (!$product->isAvailable()) { throw new Exception('Product ' . $productID . ' is not Available '); } else { if ($count < $product->getMinimumQuantity()) { $count = $product->getMinimumQuantity(); } ActiveRecordModel::beginTransaction(); $item = $order->addProduct($product, $count); if ($item instanceof OrderedItem) { if ($order->isMultiAddress->get()) { $item->save(); } } if ($product->parent->get()) { $order->mergeItems(); } else { $item->save(); } //$order->mergeItems(); $order->getTotal(true); $order->totalAmount->set($order->getTotal(true)); $order->getTaxAmount(); $order->save(true); ActiveRecordModel::commit(); } $response = new LiveCartSimpleXMLElement('<response datetime="' . date('c') . '"></response>'); if ($item->getID() > 0) { $parser = $this->getParser(); $apiFieldNames = $parser->getApiFieldNames(); $selFilter = new ARSelectFilter(); $selFilter->mergeCondition(new EqualsCond(new ARFieldHandle('OrderedItem', 'ID'), $item->getID())); $orderedItem = OrderedItem::getRecordSetArray('OrderedItem', $selFilter); while ($item = array_shift($orderedItem)) { $orderedItemXml = $response->addChild('ordered_item'); foreach ($item as $k => $v) { if (in_array($k, $apiFieldNames)) { $orderedItemXml->addChild($k, htmlentities($v)); } } } } return new SimpleXMLResponse($response); }
public function buildIndex($id = null) { // if (self::getSearchableItemCount($this->limitToLocales) == 0) // { // $id = null; // with id null will reindex all // } ActiveRecordModel::beginTransaction(); $this->_values = $this->config->getValues(); SearchableItem::bulkClearIndex($id); $this->buildList(null, $id); ActiveRecordModel::commit(); }
private function completeCallback($array) { ActiveRecordModel::beginTransaction(); $order = $this->createOrder($array); $email = null; $address = null; if (isset($array['BUYER-BILLING-ADDRESS'])) { $order->billingAddress->set($this->getUserAddress($array['BUYER-BILLING-ADDRESS'][0])); if (isset($array['BUYER-BILLING-ADDRESS'][0]['EMAIL'])) { $email = $array['BUYER-BILLING-ADDRESS'][0]['EMAIL'][0]['VALUE']; } } if (isset($array['BUYER-SHIPPING-ADDRESS'])) { $order->shippingAddress->set($this->getUserAddress($array['BUYER-SHIPPING-ADDRESS'][0])); if (isset($array['BUYER-SHIPPING-ADDRESS'][0]['EMAIL'])) { $email = $array['BUYER-SHIPPING-ADDRESS'][0]['EMAIL'][0]['VALUE']; } } if (isset($array['ORDER-ADJUSTMENT'][0]['SHIPPING'][0]['MERCHANT-CALCULATED-SHIPPING-ADJUSTMENT'][0])) { $shipping = $array['ORDER-ADJUSTMENT'][0]['SHIPPING'][0]['MERCHANT-CALCULATED-SHIPPING-ADJUSTMENT'][0]; $shippingName = $shipping['SHIPPING-NAME'][0]['VALUE']; $shipment = $order->getShipments()->get(0); foreach ($shipment->getAvailableRates() as $rate) { $rate = $rate->toArray(); if ($rate['serviceName'] == $shippingName || !empty($rate['ShippingService']) && $rate['ShippingService']['name_lang'] == $shippingName) { $shipment->setRateId($rate['serviceID']); } } } if (!$email) { $email = $array['BUYER-ID'][0]['VALUE'] . '@googlecheckout.com'; } $user = User::getInstanceByEmail($email); if (!$user) { $address = $order->billingAddress->get(); $user = User::getNewInstance($email); foreach (array('firstName', 'lastName', 'companyName') as $field) { $user->{$field}->set($address->{$field}->get()); } $user->save(); } $order->setUser($user); $order->save(); $this->order = $order; $handler = $this->application->getPaymentHandler('GoogleCheckout'); $this->registerPayment($handler->extractTransactionResult($array), $handler); ActiveRecordModel::commit(); }
/** * Add a new product to shopping cart */ public function addToCart() { // avoid search engines adding items to cart... if ($this->request->get('csid') && $this->request->get('csid') != session_id()) { return new RawResponse(); } ActiveRecordModel::beginTransaction(); if (!$this->request->get('count')) { $this->request->set('count', 1); } if ($id = $this->request->get('id')) { $res = $this->addProductToCart($id); if ($res instanceof ActionRedirectResponse) { if ($this->isAjax()) { return new JSONResponse(array('__redirect' => $this->application->getActionRedirectResponseUrl($res))); } else { return $res; } } $this->setMessage($this->makeText('_added_to_cart', array(Product::getInstanceByID($id)->getName($this->getRequestLanguage())))); } if ($ids = $this->request->get('productIDs')) { $added = false; foreach ($ids as $id) { $res = $this->addProductToCart($id, 'product_' . $id . '_'); if ($res instanceof ActionRedirectResponse) { return $res; } if ($res) { $added = true; } } if ($added) { $this->setMessage($this->translate('_selected_to_cart')); } } if (!$this->user->isAnonymous()) { $this->order->setUser($this->user); } $this->order->mergeItems(); SessionOrder::save($this->order); ActiveRecordModel::commit(); if (!$this->isAjax()) { if ($this->config->get('SKIP_CART')) { return new ActionRedirectResponse('checkout', 'index'); } else { return new ActionRedirectResponse('order', 'index', array('query' => 'return=' . $this->request->get('return'))); } } else { return $this->cartUpdate(); } }
/** * Removes a product from a database * * @param int $recordID * @return bool * @throws Exception */ public static function deleteByID($recordID) { ActiveRecordModel::beginTransaction(); try { $product = Product::getInstanceByID($recordID, Product::LOAD_DATA); $filter = $product->getCountUpdateFilter(true); if ($product->category->get()) { $product->updateCategoryCounters($filter, $product->category->get()); } foreach ($product->getAdditionalCategories() as $category) { $product->updateCategoryCounters($filter, $category); } parent::deleteByID(__CLASS__, $recordID); ActiveRecordModel::commit(); return true; } catch (Exception $e) { ActiveRecordModel::rollback(); throw $e; } }
public function setAdmin() { if (!$this->buildAdminValidator()->isValid()) { return new ActionRedirectResponse('install', 'admin'); } ClassLoader::import('application.model.user.UserGroup'); ClassLoader::import('application.model.user.User'); ClassLoader::import('application.model.user.SessionUser'); ActiveRecordModel::beginTransaction(); // create user group for administrators $group = UserGroup::getNewInstance('Administrators'); $group->setAllRoles(); $group->save(); // create administrator account $user = User::getNewInstance($this->request->get('email'), null, $group); $user->loadRequestData($this->request); $user->setPassword($this->request->get('password')); $user->isEnabled->set(true); $user->save(); ActiveRecordModel::commit(); // log in SessionUser::setUser($user); // set store email $this->config->set('MAIN_EMAIL', $this->request->get('email')); $this->config->set('NOTIFICATION_EMAIL', $this->request->get('email')); $this->config->set('NEWSLETTER_EMAIL', $this->request->get('email')); $this->config->save(); return new ActionRedirectResponse('install', 'config'); }
/** * Removes category by ID and fixes data in parent categories * (updates activeProductCount and totalProductCount) * * @param int $recordID */ public function delete() { ActiveRecordModel::beginTransaction(); try { $activeProductCount = $this->activeProductCount->get(); $totalProductCount = $this->totalProductCount->get(); $availableProductCount = $this->availableProductCount->get(); foreach ($this->getPathNodeSet(true) as $node) { $node->setFieldValue("activeProductCount", "activeProductCount - " . $activeProductCount); $node->setFieldValue("totalProductCount", "totalProductCount - " . $totalProductCount); $node->setFieldValue("availableProductCount", "availableProductCount - " . $availableProductCount); $node->save(); } ActiveRecordModel::commit(); parent::delete(); } catch (Exception $e) { ActiveRecordModel::rollback(); throw $e; } }
public function processCheckoutRegistration() { ActiveRecordModel::beginTransaction(); $validator = $this->buildValidator(); if (!$validator->isValid()) { $action = $this->request->get('regType') == 'register' ? 'registerAddress' : 'checkout'; return new ActionRedirectResponse('user', $action, array('query' => array('return' => $this->request->get('return')))); } // create user account $user = $this->createUser($this->request->get('password'), 'billing_'); // create billing and shipping address $address = $this->createAddress('billing_'); $billingAddress = BillingAddress::getNewInstance($user, $address); $billingAddress->save(); $shippingAddress = ShippingAddress::getNewInstance($user, $this->request->get('sameAsBilling') ? clone $address : $this->createAddress('shipping_')); $shippingAddress->save(); $user->defaultShippingAddress->set($shippingAddress); $user->defaultBillingAddress->set($billingAddress); $user->save(); // set order addresses $this->order->billingAddress->set($billingAddress->userAddress->get()); $this->order->loadItems(); if ($this->order->isShippingRequired()) { $this->order->shippingAddress->set($shippingAddress->userAddress->get()); } $this->order->save(); $this->order->setUser($user); SessionOrder::save($this->order); ActiveRecordModel::commit(); if ($return = $this->request->get('return')) { return new RedirectResponse($this->router->createUrlFromRoute($return)); } else { return new ActionRedirectResponse('checkout', 'shipping'); } }
public function save() { ActiveRecordModel::beginTransaction(); $parent = Product::getInstanceByID($this->request->get('id'), true); $items = json_decode($this->request->get('items'), true); $types = json_decode($this->request->get('types'), true); $variations = json_decode($this->request->get('variations'), true); $existingTypes = $existingVariations = $existingItems = array(); $currency = $this->application->getDefaultCurrencyCode(); // deleted types foreach ($types as $id) { if (is_numeric($id)) { $existingTypes[] = $id; } } $parent->deleteRelatedRecordSet('ProductVariationType', new ARDeleteFilter(new NotINCond(new ARFieldHandle('ProductVariationType', 'ID'), $existingTypes))); // deleted variations foreach ($variations as $type => $typeVars) { foreach ($typeVars as $id) { if (is_numeric($id)) { $existingVariations[] = $id; } } } $f = new ARDeleteFilter(new INCond(new ARFieldHandle('ProductVariation', 'typeID'), $existingTypes)); $f->mergeCondition(new NotINCond(new ARFieldHandle('ProductVariation', 'ID'), $existingVariations)); ActiveRecordModel::deleteRecordSet('ProductVariation', $f); // deleted items foreach ($items as $id) { if (is_numeric($id)) { $existingItems[] = $id; } } $parent->deleteRelatedRecordSet('Product', new ARDeleteFilter(new NotINCond(new ARFieldHandle('Product', 'ID'), $existingItems))); // load existing records foreach (array('Types' => 'ProductVariationType', 'Variations' => 'ProductVariation', 'Items' => 'Product') as $arr => $class) { $var = 'existing' . $arr; $array = ${$var}; if ($array) { ActiveRecordModel::getRecordSet($class, new ARSelectFilter(new INCond(new ARFieldHandle($class, 'ID'), $array))); } } $idMap = array(); // save types $request = $this->request->toArray(); foreach ($types as $index => $id) { if (!is_numeric($id)) { $type = ProductVariationType::getNewInstance($parent); $idMap[$id] = $type; } else { $type = ActiveRecordModel::getInstanceByID('ProductVariationType', $id); } $type->setValueByLang('name', null, $request['variationType'][$index]); $type->position->set($index); if (!empty($request['typeLang_' . $id])) { foreach ($request['typeLang_' . $id] as $field => $value) { list($field, $lang) = explode('_', $field, 2); $type->setValueByLang($field, $lang, $value); } } $type->save(); } // save variations $tree = array(); $typeIndex = -1; foreach ($variations as $typeID => $typeVars) { $type = is_numeric($typeID) ? ActiveRecordModel::getInstanceByID('ProductVariationType', $typeID) : $idMap[$typeID]; $typeIndex++; foreach ($typeVars as $index => $id) { if (!is_numeric($id)) { $variation = ProductVariation::getNewInstance($type); $idMap[$id] = $variation; } else { $variation = ActiveRecordModel::getInstanceByID('ProductVariation', $id); } $variation->position->set($index); $variation->setValueByLang('name', null, $request['variation'][$id]); if (!empty($request['variationLang_' . $id])) { foreach ($request['variationLang_' . $id] as $field => $value) { list($field, $lang) = explode('_', $field, 2); $variation->setValueByLang($field, $lang, $value); } } $variation->save(); $tree[$typeIndex][] = $variation; } } $images = array(); // save items foreach ($items as $index => $id) { if (!is_numeric($id)) { $item = $parent->createChildProduct(); $idMap[$id] = $item; } else { $item = ActiveRecordModel::getInstanceByID('Product', $id); } $item->isEnabled->set(!empty($request['isEnabled'][$id])); if (!$request['sku'][$index]) { $request['sku'][$index] = $item->sku->get(); } foreach (array('sku', 'stockCount', 'shippingWeight') as $field) { if ($item->{$field}->get() || $request[$field][$index]) { $item->{$field}->set($request[$field][$index]); } } $item->setChildSetting('weight', $request['shippingWeightType'][$index]); $item->setChildSetting('price', $request['priceType'][$index]); if (!strlen($request['priceType'][$index])) { $request['price'][$index] = ''; } $item->setPrice($currency, $request['price'][$index]); $item->save(); // assign variations $currentVariationValues = $currentVariations = array(); foreach ($item->getRelatedRecordSet('ProductVariationValue') as $variationValue) { $currentVariations[$variationValue->variation->get()->getID()] = $variationValue->variation->get(); $currentVariationValues[$variationValue->variation->get()->getID()] = $variationValue; } foreach ($this->getItemVariations($tree, $index) as $variation) { if (!isset($currentVariations[$variation->getID()])) { ProductVariationValue::getNewInstance($item, $variation)->save(); } unset($currentVariations[$variation->getID()]); } foreach ($currentVariations as $deletedVariation) { $currentVariationValues[$deletedVariation->getID()]->delete(); } // set image if ($_FILES['image']['tmp_name'][$index]) { if ($item->defaultImage->get()) { $item->defaultImage->get()->load(); $image = $item->defaultImage->get(); } else { $image = ProductImage::getNewInstance($item); } $image->save(); $image->setFile($_FILES['image']['tmp_name'][$index]); $image->save(); $images[$item->getID()] = $image->toArray(); unset($images[$item->getID()]['Product']); } } ActiveRecordModel::commit(); // pass ID's for newly created records $ids = array(); foreach ($idMap as $id => $instance) { $ids[$id] = $instance->getID(); } $response = new ActionResponse('ids', $ids); $response->set('parent', $parent->getID()); $response->set('images', $images); $response->set('variationCount', $parent->getRelatedRecordCount('Product', new ARSelectFilter(new EqualsCond(new ARFieldHandle('Product', 'isEnabled'), true)))); return $response; }
public function doSelectShippingAddress() { $sameAddress = $this->config->get('REQUIRE_SAME_ADDRESS'); $this->config->setRuntime('REQUIRE_SAME_ADDRESS', false); $this->order->loadAll(); $this->request->set('step', 'shipping'); $this->initAnonUser(); if ($this->user->isAnonymous()) { $billingAddress = $this->order->billingAddress->get(); $this->request->set('sameAsBilling', true); foreach ($this->switchArrayPrefixes($this->request->toArray(), 'shipping_', 'billing_') as $key => $value) { $this->request->set($key, $value); } $controller = $this->getUserController(); $response = $controller->processCheckoutRegistration(); $user = $controller->getUser(); if ($billingAddress && !$this->request->get('sameAsShipping')) { $this->order->billingAddress->set($billingAddress); $this->order->billingAddress->resetModifiedStatus(); $user->defaultBillingAddress->get()->userAddress->set($billingAddress); } ActiveRecordModel::rollback(); $this->order->getSpecification()->loadRequestData($this->request, 'order_'); $this->order->getSpecification()->save(); if ($this->order->getSpecification()->hasValues()) { if (!$this->order->eavObject->get()->getID()) { $this->order->eavObject->get()->save(); } $this->order->eavObject->setAsModified(true); } $this->order->save(); ActiveRecordModel::commit(); if ($response->getActionName() == 'checkout') { $errorResponse = $controller->checkout(); $errors = $errorResponse->get('form')->getValidator()->getErrorList(); return new JSONResponse(array('errorList' => $this->switchArrayPrefixes($errors, 'billing_', 'shipping_'))); } $this->saveAnonUser($user); } else { $this->separateBillingAndShippingAddresses(); $parentResponse = parent::doSelectAddress(); // UserAddress::toString() uses old data otherwise if ($this->order->shippingAddress->get()) { $this->order->shippingAddress->get()->resetArrayData(); if ($sameAddress) { $this->order->billingAddress->set($this->order->shippingAddress->get()); $this->order->save(); } else { if ($this->request->get('sameAsShipping') && (!$this->order->billingAddress->get() && $this->order->shippingAddress->get() && $this->order->isShippingRequired() || $this->order->billingAddress->get() && $this->order->shippingAddress->get() && $this->order->billingAddress->get()->toString() != $this->order->shippingAddress->get()->toString())) { $this->order->billingAddress->set(clone $this->order->shippingAddress->get()); $this->order->billingAddress->get()->save(); $this->order->save(); } } } } // attempt to pre-select a shipping method /* ActiveRecord::clearPool(); $this->config->resetRuntime('DELIVERY_TAX_CLASS'); $this->order = CustomerOrder::getInstanceById($this->order->getID(), true); // @todo: needs to be called twice for the auto-selection to get saved $this->init(); $this->shippingMethods(); $this->shippingMethods(); */ $this->config->setRuntime('REQUIRE_SAME_ADDRESS', $sameAddress); return new ActionRedirectResponse('onePageCheckout', 'update'); }
public function doSelectBillingAddress() { $this->order->loadAll(); $this->request->set('step', 'billing'); $this->initAnonUser(); $shipments = $this->order->getShipments(); if ($this->user->isAnonymous()) { $shipping = $this->user->defaultShippingAddress->get(); $this->session->set('newsletter', $this->request->get('newsletter')); $this->request->set('sameAsBilling', true); $controller = $this->getUserController(); $response = $controller->processCheckoutRegistration(); $user = $controller->getUser(); $this->order->shippingAddress->setNull(); $user->defaultShippingAddress->setNull(); if ($shipping) { $this->order->shippingAddress->set($shipping->userAddress->get()); $this->order->shippingAddress->resetModifiedStatus(); $user->defaultShippingAddress->set($shipping); } ActiveRecordModel::rollback(); $this->order->getSpecification()->loadRequestData($this->request, 'order_'); $this->order->getSpecification()->save(); if ($this->order->getSpecification()->hasValues()) { if (!$this->order->eavObject->get()->getID()) { $this->order->eavObject->get()->save(); } $this->order->eavObject->setAsModified(true); } $this->order->save(); ActiveRecordModel::commit(); $this->anonTransactionInitiated = false; if ($response->getActionName() == 'checkout') { $errorResponse = $controller->checkout(); $errors = $errorResponse->get('form')->getValidator()->getErrorList(); return new JSONResponse(array('errorList' => $errors)); } $this->saveAnonUser($user); } else { if ($res = $this->setAddress('shipping')) { return $res; } } return new ActionRedirectResponse('onePageCheckout', 'update'); //return $this->getUpdateResponse('shippingAddress', 'billingAddress'); }
ClassLoader::import('application.model.product.Product'); $languages = $application->getLanguageArray(); $default = $application->getDefaultLanguageCode(); if (!$languages) { die('No additional languages enabled'); } $count = ActiveRecordModel::getRecordCount('Product', new ARSelectFilter()); $parts = ceil($count / BUFFER); $fields = array('name', 'shortDescription', 'longDescription'); ActiveRecordModel::beginTransaction(); for ($k = 0; $k < $parts; $k++) { $filter = new ARSelectFilter(); $filter->setLimit(BUFFER, BUFFER * $k); $filter->setOrder(new ARFieldHandle('Product', 'ID')); $products = ActiveRecordModel::getRecordSet('Product', $filter); foreach ($products as $product) { foreach ($fields as $field) { if (!$product->getValueByLang($field, $default)) { foreach ($languages as $lang) { if ($value = $product->getValueByLang($field, $lang)) { $product->setValueByLang($field, $default, $value); break; } } } } $product->save(); } } ActiveRecordModel::commit();
/** * @role login */ public function payOffline() { ActiveRecordModel::beginTransaction(); $method = $this->request->get('id'); if (!OfflineTransactionHandler::isMethodEnabled($method) || !$this->getOfflinePaymentValidator($method)->isValid()) { return new ActionRedirectResponse('checkout', 'pay'); } $order = $this->order; $this->order->setPaymentMethod($method); $response = $this->finalizeOrder(); $transaction = Transaction::getNewOfflineTransactionInstance($order, 0); $transaction->setOfflineHandler($method); $transaction->save(); $eavObject = EavObject::getInstance($transaction); $eavObject->setStringIdentifier($method); $eavObject->save(); $transaction->getSpecification()->loadRequestData($this->request); $transaction->save(); ActiveRecordModel::commit(); return $response; }
/** * Delete this node with subtree * * @return bool * * @throws Exception If failed to commit the transaction */ public function delete() { $className = get_class($this); $this->load(); $t_r = $this->getFieldValue(self::RIGHT_NODE_FIELD_NAME); $t_l = $this->getFieldValue(self::LEFT_NODE_FIELD_NAME); $width = $this->getWidth(); ActiveRecordModel::beginTransaction(); try { $updates[] = "UPDATE {$className} SET " . self::RIGHT_NODE_FIELD_NAME . " = " . self::RIGHT_NODE_FIELD_NAME . " - {$width} WHERE " . self::RIGHT_NODE_FIELD_NAME . " >= {$t_r}"; $updates[] = "UPDATE {$className} SET " . self::LEFT_NODE_FIELD_NAME . " = " . self::LEFT_NODE_FIELD_NAME . " - {$width} WHERE " . self::LEFT_NODE_FIELD_NAME . " >= {$t_l}"; foreach ($updates as $update) { self::getLogger()->logQuery($update); self::getDBConnection()->executeUpdate($update); } $result = parent::delete(); ActiveRecordModel::commit(); foreach (ActiveRecord::retrieveFromPool(get_class($this)) as $instance) { if ($instance->getFieldValue(self::RIGHT_NODE_FIELD_NAME) >= $t_r) { $instance->setFieldValue(self::RIGHT_NODE_FIELD_NAME, $instance->getFieldValue(self::RIGHT_NODE_FIELD_NAME) - $width); } if ($instance->getFieldValue(self::LEFT_NODE_FIELD_NAME) >= $t_l) { $instance->setFieldValue(self::LEFT_NODE_FIELD_NAME, $instance->getFieldValue(self::LEFT_NODE_FIELD_NAME) - $width); } } } catch (Exception $e) { ActiveRecordModel::rollback(); throw $e; } $this->setID(false); $this->markAsNotLoaded(); return $result; }