Exemplo n.º 1
0
 public function setUp()
 {
     ActiveRecordModel::getApplication()->clearCachedVars();
     ActiveRecordModel::beginTransaction();
     if (empty($this->autoincrements)) {
         foreach ($this->getUsedSchemas() as $table) {
             $res = $this->db->executeQuery("SHOW TABLE STATUS LIKE '{$table}'");
             $res->next();
             $this->autoincrements[$table] = (int) $res->getInt("Auto_increment");
         }
     }
     if ($this instanceof BackendControllerTestCase) {
         ClassLoader::import('application.model.user.SessionUser');
         ClassLoader::import('application.model.user.UserGroup');
         // set up user
         $group = UserGroup::getNewInstance('Unit tester');
         $group->save();
         $group->setAllRoles();
         $group->save();
         $user = User::getNewInstance('*****@*****.**', null, $group);
         $user->save();
         SessionUser::setUser($user);
     }
     if ($this instanceof ControllerTestCase) {
         $this->request = self::getApplication()->getRequest();
     }
 }
Exemplo n.º 2
0
 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();
 }
Exemplo n.º 4
0
 public function setUp()
 {
     parent::setUp();
     $this->config = ActiveRecordModel::getApplication()->getConfig();
     ActiveRecordModel::beginTransaction();
     ActiveRecordModel::executeUpdate('DELETE FROM Tax');
     ActiveRecordModel::executeUpdate('DELETE FROM TaxRate');
     ActiveRecordModel::executeUpdate('DELETE FROM Currency');
     ActiveRecordModel::executeUpdate('DELETE FROM DiscountCondition');
     ActiveRecordModel::executeUpdate('DELETE FROM DiscountAction');
     ActiveRecordModel::executeUpdate('DELETE FROM DeliveryZone');
     $this->getApplication()->clearCachedVars();
 }
Exemplo n.º 5
0
 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();
 }
Exemplo n.º 6
0
 /**
  *  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();
     }
 }
Exemplo n.º 7
0
 /**
  * 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;
     }
 }
Exemplo n.º 8
0
 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');
 }
Exemplo n.º 9
0
 /**
  * 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;
     }
 }
Exemplo n.º 10
0
 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');
     }
 }
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
0
 public function __construct()
 {
     parent::__construct('Test Product class');
     ActiveRecordModel::beginTransaction();
 }
Exemplo n.º 13
0
 protected function initAnonUser()
 {
     if ($this->user->isAnonymous()) {
         ActiveRecordModel::beginTransaction();
         $this->anonTransactionInitiated = true;
     }
 }
Exemplo n.º 14
0
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include '../application/Initialize.php';
ClassLoader::import('application.LiveCart');
$application = new LiveCart();
define('BUFFER', 50);
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;
                    }
                }
            }
Exemplo n.º 15
0
 /**
  *	@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;
 }
Exemplo n.º 16
0
 /**
  * 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;
 }