private function reloadOrder(CustomerOrder $order) { ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceById($order->getID(), true); $order->loadAll(); return $order; }
function testTransactionCurrencyConverting() { $eur = Currency::getNewInstance('EUR'); $eur->rate->set('3.4528'); $eur->save(); $this->products[0]->setPrice($this->usd, '9.99'); $this->order->addProduct($this->products[0], 1); $this->order->save(); $this->order->changeCurrency($this->usd); //$this->order->finalize(); ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $details = new LiveCartTransaction($order, $eur); ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $this->assertEquals($details->amount->get(), '2.89'); $result = new TransactionResult(); $result->amount->set($details->amount->get()); $result->currency->set($details->currency->get()); $transaction = Transaction::getNewInstance($order, $result); $transaction->type->set(Transaction::TYPE_SALE); $this->assertEquals($transaction->amount->get(), '9.99'); $this->assertEquals($transaction->realAmount->get(), '2.89'); $transaction->save(); $this->assertFalse((bool) $order->isFinalized->get()); $order->finalize(); $this->assertTrue((bool) $order->isFinalized->get()); $this->assertEquals($order->getPaidAmount(), '9.99'); $this->assertEquals($order->totalAmount->get(), '9.99'); $this->assertTrue((bool) $order->isPaid->get()); }
public function process() { AddRatingFieldToSchema::process(); $main = Product::getInstanceByID($this->request->get('id'), true); if ($main->parent->get()) { $main->parent->get()->load(); $var = $main->toArray(); $var['custom'] = $main->custom->get(); $this->request->set('variation', $var); $this->request->set('activeVariationID', $this->request->get('id')); $main = $main->parent->get(); $this->request->set('id', $main->getID()); $productArray = $main->toArray(); $handle = empty($productArray['URL']) ? $productArray['name_lang'] : $productArray['URL']; $this->request->set('producthandle', $handle); } ActiveRecord::clearPool(); $variations = $main->getRelatedRecordSet('Product', select()); $handle = $main->URL->get() ? $main->URL->get() : $main->getValueByLang('name', 'en'); foreach ($variations as $variation) { $variation->setValueByLang('name', 'en', $main->getValueByLang('name', 'en') . ' ' . $variation->sku->get()); $variation->URL->set($handle . ' ' . $variation->sku->get()); $variation->parent->set(null); } $variations->toArray(); }
function testUpdate() { $page = StaticPage::getNewInstance(); $page->setValueByLang('title', 'en', 'test title'); $page->save(); $page->setValueByLang('title', 'en', 'changed'); $page->save(); ActiveRecord::clearPool(); $instance = StaticPage::getInstanceById($page->getID()); $this->assertEqual($page->getValueByLang('title', 'en'), 'changed'); // test deleting a page $this->assertTrue(file_exists($page->getFileName())); $page->delete(); $this->assertFalse(file_exists($page->getFileName())); }
public function testDeleteCategory() { ActiveRecord::clearPool(); $startingPositions = array(); $nodes = $this->root->getChildNodes(false, true); $nodes->add($this->root); $this->root->reload(); foreach ($nodes as $category) { $startingPositions[$category->getID()] = array('lft' => $category->getFieldValue(ActiveTreeNode::LEFT_NODE_FIELD_NAME), 'rgt' => $category->getFieldValue(ActiveTreeNode::RIGHT_NODE_FIELD_NAME), 'parent' => $category == $this->root ? '0' : $category->getFieldValue(ActiveTreeNode::PARENT_NODE_FIELD_NAME)->getID()); } // new node $newCategory = Category::getNewInstance($this->root); $newCategory->setValueByLang("name", 'en', 'NEWNODE'); $newCategory->save(); // nested nodes $nestedNodes = array(); $lastNode = $newCategory; foreach (array() as $i) { $nestedNodes[$i] = Category::getNewInstance($lastNode); $nestedNodes[$i]->setValueByLang("name", 'en', 'TEST ' . rand(1, 1000)); $nestedNodes[$i]->save(); $lastNode = $nestedNodes[$i]; } $newCategory->reload(); // Delete child node $newCategory->delete(); $this->assertFalse($newCategory->isExistingRecord()); $this->assertFalse($newCategory->isLoaded()); // Check to see if everything is back to starting values $activeTreeNodes = ActiveRecord::retrieveFromPool(get_class($newCategory)); foreach ($activeTreeNodes as $category) { try { $category->reload(); } catch (ARNotFoundException $e) { continue; } if (!$category->getID()) { continue; } $this->assertEqual($category->getFieldValue(ActiveTreeNode::LEFT_NODE_FIELD_NAME), $startingPositions[$category->getID()]['lft']); $this->assertEqual($category->getFieldValue(ActiveTreeNode::RIGHT_NODE_FIELD_NAME), $startingPositions[$category->getID()]['rgt']); if (!$category->isRoot()) { $this->assertEqual($category->getFieldValue(ActiveTreeNode::PARENT_NODE_FIELD_NAME)->getID(), $startingPositions[$category->getID()]['parent']); } } }
protected function &fetch($pos) { if (!($pos >= $this->from && $pos < $this->to)) { $this->from = $pos; $this->to = $pos + $this->getChunkSize(); ActiveRecord::clearPool(); $this->filter->setLimit($this->getChunkSize(), $this->from); $this->loadData(); $this->postProcessData(); } if ($this->flush) { //echo '|' . round(memory_get_usage() / (1024*1024), 1) . "\n"; flush(); ob_flush(); } $offset = $pos - $this->from; return $this->data[$offset]; }
protected function processSet(ARSet $set) { foreach ($set as $record) { $this->processRecord($record); //echo round(memory_get_usage() / (1024*1024), 1) . "MB \n"; if ('delete' == $this->getAction()) { $this->deleteRecord($record); } else { $this->saveRecord($record); } $record->__destruct(); unset($record); if (connection_aborted()) { $this->cancel(); } } $set->__destruct(); unset($set); ActiveRecord::clearPool(); }
public function testSerializeSpeed() { for ($k = 1; $k <= 10; $k++) { $record = ActiveRecord::getNewInstance('SerializedModel'); $record->setID($k); $record->name->set('some name ' . $k); $record->save(); } ActiveRecord::clearPool(); // fetch from database $fetchTime = microtime(true); $set = ActiveRecord::getRecordSet('SerializedModel', new ARSelectFilter()); $fetchTime = microtime(true) - $fetchTime; $serialized = serialize($set); ActiveRecord::clearPool(); // unserialize $serTime = microtime(true); $set = unserialize($serialized); $serTime = microtime(true) - $serTime; $this->assertTrue($serTime < $fetchTime); }
function testSerializingValuesWithQuotes() { // two quotes $testValue = 'This is a value with "quotes" :)'; $root = Category::getInstanceByID(1); $new = Category::getNewInstance($root); $new->setValueByLang('name', 'en', $testValue); $new->save(); ActiveRecord::clearPool(); $restored = Category::getInstanceByID($new->getID(), Category::LOAD_DATA); $array = $restored->toArray(); $this->assertEqual($testValue, $restored->getValueByLang('name', 'en')); // one quote $testValue = 'NX9420 C2D T7400 17" WSXGA+ WVA BRIGHT VIEW 1024MB 120GB DVD+/-RW DL ATI MOBILITY RADEON X1600 256MB WLAN BT TPM XPPKeyb En'; $restored->setValueByLang('name', 'en', $testValue); $restored->save(); ActiveRecord::clearPool(); $restored->totalProductCount->set(333); $another = Category::getInstanceByID($restored->getID(), Category::LOAD_DATA); $this->assertEqual($testValue, $another->getValueByLang('name', 'en')); }
protected function clear($instance) { if (method_exists($instance, '__destruct')) { $instance->__destruct(); } if (method_exists($instance, 'destruct')) { $instance->destruct(true); } ActiveRecord::clearPool(); }
public function import() { $options = unserialize(base64_decode($this->request->get('options'))); $response = new JSONResponse(null); if (file_exists($this->getCancelFile())) { unlink($this->getCancelFile()); } if (!$this->request->get('continue')) { $this->clearCacheProgress(); } $import = $this->getImportInstance(); set_time_limit(0); ignore_user_abort(true); $profile = new CsvImportProfile($import->getClassName()); // map CSV fields to LiveCart fields $params = $this->request->get('params'); foreach ($this->request->get('column') as $key => $value) { if ($value) { $fieldParams = !empty($params[$key]) ? $params[$key] : array(); $profile->setField($key, $value, array_filter($fieldParams)); } } $profile->setParam('isHead', $this->request->get('firstHeader')); if ($this->request->get('saveProfile')) { $path = $this->getProfileDirectory($import) . $this->request->get('profileName') . '.ini'; $profile->setFileName($path); $profile->save(); } // get import root category if ($import->isRootCategory()) { $profile->setParam('category', $this->request->get('category')); } $import->beforeImport($profile); $csv = new CsvFile($this->request->get('file'), $this->request->get('delimiter')); $total = $csv->getRecordCount(); if ($this->request->get('firstHeader')) { $total -= 1; } if ($this->request->get('firstHeader')) { $import->skipHeader($csv); $import->skipHeader($csv); } $progress = 0; $processed = 0; if ($this->request->get('continue')) { $import->setImportPosition($csv, $this->getCacheProgress() + 1); $progress = $this->getCacheProgress(); } else { if (!empty($options['transaction'])) { ActiveRecord::beginTransaction(); } } if (empty($options['transaction'])) { $this->request->set('continue', true); } $import->setOptions($options); if ($uid = $this->request->get('uid')) { $import->setUID($uid); } do { $progress += $import->importFileChunk($csv, $profile, 1); // continue timed-out import if ($this->request->get('continue')) { $this->setCacheProgress($progress); } ActiveRecord::clearPool(); if ($progress % self::PROGRESS_FLUSH_INTERVAL == 0 || $total == $progress) { $response->flush($this->getResponse(array('progress' => $progress, 'total' => $total, 'uid' => $import->getUID(), 'lastName' => $import->getLastImportedRecordName()))); //echo '|' . round(memory_get_usage() / (1024*1024), 1) . '|' . count($categories) . "\n"; } // test non-transactional mode //if (!$this->request->get('continue')) exit; if (connection_aborted()) { if ($this->request->get('continue')) { exit; } else { $this->cancel(); } } } while (!$import->isCompleted($csv)); if (!empty($options['missing']) && 'keep' != $options['missing']) { $filter = $import->getMissingRecordFilter($profile); if ('disable' == $options['missing']) { $import->disableRecords($filter); } else { if ('delete' == $options['missing']) { $import->deleteRecords($filter); } } } $import->afterImport(); if (!$this->request->get('continue')) { //ActiveRecord::rollback(); ActiveRecord::commit(); } $response->flush($this->getResponse(array('progress' => 0, 'total' => $total))); //echo '|' . round(memory_get_usage() / (1024*1024), 1); exit; }
private function apiActionGetOrdersBySelectFilter($ARSelectFilter, $allowEmptyResponse = false) { set_time_limit(0); $ARSelectFilter->setOrder(new ARExpressionHandle('CustomerOrder.ID'), 'DESC'); $customerOrders = ActiveRecordModel::getRecordSet('CustomerOrder', $ARSelectFilter, array('User')); if ($allowEmptyResponse == false && count($customerOrders) == 0) { throw new Exception('Order not found'); } $response = new LiveCartSimpleXMLElement('<response datetime="' . date('c') . '"></response>'); foreach ($customerOrders as $order) { $order->loadAll(); $transactions = $order->getTransactions(); $this->fillResponseItem($response->addChild('order'), $order->toArray()); unset($order); ActiveRecord::clearPool(); } return new SimpleXMLResponse($response); }
public function importInstance($record, CsvImportProfile $profile) { $this->className = 'Product'; $impReq = new Request(); $defLang = $this->application->getDefaultLanguageCode(); $references = array('DefaultImage' => 'ProductImage', 'Manufacturer', 'ShippingClass', 'TaxClass'); $cat = $this->getCategory($profile, $record); $extraCategories = null; $fields = $profile->getSortedFields(); if (isset($fields['Categories']['ExtraCategories'])) { $extraCategories = explode('; ', $record[$fields['Categories']['ExtraCategories']]); } if (isset($fields['Product']) && $cat) { $product = null; if (isset($fields['Product']['ID']) && !empty($record[$fields['Product']['ID']])) { $id = $record[$fields['Product']['ID']]; if (ActiveRecord::objectExists('Product', $id)) { $product = Product::getInstanceByID($id, Product::LOAD_DATA, $references); } } else { if (isset($fields['Product']['sku']) && !empty($record[$fields['Product']['sku']])) { $product = Product::getInstanceBySku($record[$fields['Product']['sku']], $references); } } if ($product && $product->getID()) { $this->registerImportedID($product->getID()); } if (!$product && 'update' == $this->options['action'] || $product && 'add' == $this->options['action']) { return false; } if ($product) { $product->loadSpecification(); $product->loadPricing(); } else { if ($cat instanceof Category) { $product = Product::getNewInstance($cat); } else { $product = $cat->createChildProduct(); } $product->isEnabled->set(true); } // product information $impReq->clearData(); foreach ($profile->getFields() as $csvIndex => $field) { $column = $field['name']; $params = $field['params']; if (!isset($record[$csvIndex]) || empty($column)) { continue; } $value = $record[$csvIndex]; list($className, $field) = explode('.', $column, 2); if (isset($params['language'])) { $lang = $params['language']; if ($lang != $defLang) { $field .= '_' . $lang; } } if ($value) { if ('Product.parentID' == $column) { $product->parent->set(); continue; } if ('Product.parentSKU' == $column) { $product->parent->set(Product::getInstanceBySKU($value)); continue; } } if ('Product.taxClass' == $column) { $product->taxClass->set(TaxClass::findByName($value)); } if ('Product.shippingClass' == $column) { $product->shippingClass->set(ShippingClass::findByName($value)); } if ('Product' == $className) { if ('shippingWeight' == $field) { if ($this->application->getConfig()->get('UNIT_SYSTEM') == 'ENGLISH') { $value = $value / 0.45359237; } } if ('shippingWeight' == $field && $product->parent->get()) { $value = $this->setChildSetting($product, 'weight', $value); } $impReq->set($field, $value); } else { if ('Manufacturer' == $className) { $impReq->set('manufacturer', $value); } else { if ('ProductPrice.price' == $column) { if ($product->parent->get()) { $value = $this->setChildSetting($product, 'price', $value); } $value = preg_replace('/,([0-9]{3})/', '\\1', $value); $value = (double) preg_replace('/[^\\.0-9]/', '', str_replace(',', '.', $value)); $currency = isset($params['currency']) ? $params['currency'] : $this->application->getDefaultCurrencyCode(); $quantityLevel = isset($params['quantityLevel']) ? $params['quantityLevel'] : ''; $group = isset($params['group']) ? $params['group'] : ''; $price = $product->getPricingHandler()->getPriceByCurrencyCode($currency); $product->getPricingHandler()->setPrice($price); if ($group || $quantityLevel) { if ($value > 0) { $quantity = $quantityLevel ? $record[$fields['ProductPrice'][$quantityLevel]] : 1; $group = $group ? UserGroup::getInstanceByID($group) : null; $price->setPriceRule($quantity, $group, $value); } } else { $price->price->set($value); } } else { if ('ProductPrice.listPrice' == $column) { $value = (double) preg_replace('/[^\\.0-9]/', '', str_replace(',', '.', $value)); $currency = $params['currency']; $price = $product->getPricingHandler()->getPriceByCurrencyCode($currency); $price->listPrice->set($value); $product->getPricingHandler()->setPrice($price); } else { if ('ProductVariation' == $className) { if ($parent = $product->parent->get()) { $this->importProductVariationValue($product, $field, $value); } else { $this->importVariationType($product, $field, $value); } } } } } } } $product->loadRequestData($impReq); $product->save(); $this->importAttributes($product, $record, $fields, 'specField'); $this->setLastImportedRecordName($product->getValueByLang('name')); if (isset($fields['ProductImage']['mainurl'])) { if (!($image = $product->defaultImage->get())) { $image = ProductImage::getNewInstance($product); } $image->setOwner($product); // this is needed when ProductApi imports default ProductImage. $this->importImage($image, $record[$fields['ProductImage']['mainurl']]); unset($image); } if (isset($fields['ProductAdditionalImage'])) { foreach ($fields['ProductAdditionalImage'] as $index) { $this->importImage(ProductImage::getNewInstance($product), $record[$index]); } } if (isset($fields['ProductImage']['Images'])) { $images = explode('; ', $record[$fields['ProductImage']['Images']]); if ($images) { $product->deleteRelatedRecordSet('ProductImage'); foreach ($images as $path) { $image = ProductImage::getNewInstance($product); $this->importImage($image, $path); unset($image); } } } if (isset($fields['ProductOption']['options'])) { $options = explode('; ', $record[$fields['ProductOption']['options']]); if ($options) { $product->deleteRelatedRecordSet('ProductOption'); foreach ($options as $option) { $parts = explode(':', $option, 2); if (count($parts) < 2) { continue; } $optionInstance = ProductOption::getNewInstance($product); $optionInstance->setValueByLang('name', null, trim($parts[0])); $optionInstance->type->set(ProductOption::TYPE_SELECT); $optionInstance->isDisplayed->set(true); $optionInstance->save(); foreach (explode(',', $parts[1]) as $choice) { $choiceInstance = ProductOptionChoice::getNewInstance($optionInstance); $choiceInstance->setValueByLang('name', null, trim($choice)); $choiceInstance->save(); } } } } // create variation by name if ((isset($fields['Product']['parentID']) || isset($fields['Parent']['parentSKU'])) && !isset($fields['ProductVariation']) && $product->parent->get()) { $this->importProductVariationValue($product, 1, $product->getValueByLang('name', 'en')); } // additional categories if (is_array($extraCategories)) { $this->importAdditionalCategories($profile, $product, $extraCategories); } if ($this->callback) { call_user_func($this->callback, $product); } $product->__destruct(); $product->destruct(true); ActiveRecord::clearPool(); return true; } }
/** * @role login */ public function completed() { if ($this->request->isValueSet('id')) { return new ActionRedirectResponse('checkout', 'completeExternal', array('id' => $this->request->get('id'))); } ActiveRecord::clearPool(); ActiveRecord::clearArrayData(); $order = CustomerOrder::getInstanceByID((int) $this->session->get('completedOrderID'), CustomerOrder::LOAD_DATA); $order->getTaxAmount(); $order->loadAll(); $order->getTaxAmount(); ActiveRecord::clearArrayData(); $arr = $order->toArray(); $response = new ActionResponse(); $response->set('order', $arr); $response->set('url', $this->router->createUrl(array('controller' => 'user', 'action' => 'viewOrder', 'id' => $this->session->get('completedOrderID')), true)); if (!$order->isPaid->get()) { $transactions = $order->getTransactions()->toArray(); $response->set('transactions', $transactions); } else { $response->set('files', ProductFile::getOrderFiles(select(eq('CustomerOrder.ID', $order->getID())))); } return $response; }
protected function getUpdateResponse() { /////// @todo - should be a better way for recalculating taxes... ActiveRecord::clearPool(); $this->config->resetRuntime('DELIVERY_TAX_CLASS'); $this->order = CustomerOrder::getInstanceById($this->order->getID(), true); /////// $this->order->loadAll(); $this->restoreShippingMethodSelection(); ActiveRecordModel::clearArrayData(); if ($paymentMethod = $this->session->get('OrderPaymentMethod_' . $this->order->getID())) { $this->order->setPaymentMethod($paymentMethod); $this->order->getTotal(true); } $this->setAnonAddresses(); // @todo: sometimes the shipping address disappears (for registered users that might already have the shipping address entered before) if (!$this->order->shippingAddress->get() && $this->isShippingRequired($this->order) && $this->user->defaultShippingAddress->get()) { $this->user->defaultShippingAddress->get()->load(); $this->order->shippingAddress->set($this->user->defaultShippingAddress->get()->userAddress->get()); $this->order->shippingAddress->get()->load(); } $response = new CompositeJSONResponse(); $response->addAction('overview', 'onePageCheckout', 'overview'); $response->addAction('cart', 'onePageCheckout', 'cart'); if ($this->request->getActionName() != 'setPaymentMethod') { $response->addAction('payment', 'onePageCheckout', 'payment'); } $response->set('order', $this->getOrderValues($this->order)); foreach (func_get_args() as $arg) { $response->addAction($arg, 'onePageCheckout', $arg); } $this->session->unsetValue('noJS'); $response = $this->postProcessResponse($response); return $response; }
public function importInstance($record, CsvImportProfile $profile, $instance = null) { try { $instance = is_null($instance) ? $this->getInstance($record, $profile) : $instance; } catch (ARNotFoundException $e) { $instance = null; } if (is_null($instance)) { return; } $this->className = get_class($instance); $defLang = $this->application->getDefaultLanguageCode(); if ($instance->getID()) { $this->registerImportedID($instance->getID()); } if (!$instance->isExistingRecord() && 'update' == $this->options['action'] || $instance->isExistingRecord() && 'add' == $this->options['action']) { return false; } foreach ($profile->getFields() as $csvIndex => $field) { $column = $field['name']; $params = $field['params']; $lang = null; if (isset($params['language'])) { $lang = $params['language']; } if (!isset($record[$csvIndex]) || empty($column)) { continue; } $value = $record[$csvIndex]; list($className, $field) = explode('.', $column, 2); if (method_exists($this, 'set_' . $className . '_' . $field)) { $method = 'set_' . $className . '_' . $field; $this->{$method}($instance, $value, $record, $profile); } else { if (method_exists($this, 'set_' . $field)) { $method = 'set_' . $field; $this->{$method}($instance, $value, $record, $profile); } else { if (isset($instance->{$field}) && $instance->{$field} instanceof ARValueMapper && $className == $this->getClassName($className, $this->className)) { if (!$lang) { $instance->{$field}->set($value); } else { $instance->setValueByLang($field, $lang, $value); } } } } } $idBeforeSave = $instance->getID(); $instance->save(); $this->importAttributes($instance, $record, $profile->getSortedFields()); foreach ($this->getReferencedData() as $section) { $method = 'import_' . $section; if (method_exists($this, $method)) { $subProfile = $profile->extractSection($section); if ($subProfile->getFields()) { $this->{$method}($instance, $record, $subProfile); } } } $this->afterSave($instance, $record); $id = $instance->getID(); if ($this->callback) { call_user_func($this->callback, $instance); } $instance->__destruct(); $instance->destruct(true); ActiveRecord::clearPool(); return $id; }
public function resizeImages() { set_time_limit(0); $class = $this->getModelClass(); $f = select(); $count = ActiveRecord::getRecordCount($class, $f); $offset = 0; $chunk = 100; ob_flush(); ob_end_clean(); do { $f->setLimit($chunk, $offset); $set = ActiveRecordModel::getRecordSet($class, $f); foreach ($set as $image) { foreach (array($image->getPath('original'), $image->getPath(4)) as $path) { if (file_exists($path)) { $image->setFile($path); echo $image->getID() . '|'; flush(); break; } } } $offset += $chunk; ActiveRecord::clearPool(); } while ($set->size() > 0); }
public function testTaxAmountChange() { $tax = Tax::getNewInstance('GST'); $tax->save(); // shipment delivery zone $zone = DeliveryZone::getNewInstance(); $zone->name->set('Canada'); $zone->isEnabled->set(true); $zone->save(); $country = DeliveryZoneCountry::getNewInstance($zone, 'US'); $country->save(); // taxes TaxRate::getNewInstance($zone, $tax, 10)->save(); $this->order->save(true); $shipment = Shipment::getNewInstance($this->order); $shipment->save(); $this->order->addShipment($shipment); $item = $this->order->addProduct($this->products[0], 1, false, $shipment); // $100 $shipment->recalculateAmounts(); $this->order->save(); $this->assertEqual($shipment->taxAmount->get(), 10); $this->order->updateCount($item, 2); $shipment->recalculateAmounts(); $this->assertEqual($shipment->taxAmount->get(), 20); $this->order->save(); $shipment->save(); // there should only be one ShipmentTax instance for this shipment $this->assertEqual($shipment->getRelatedRecordSet('ShipmentTax')->size(), 1); // reload order and add more items ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID(), true); $order->loadAll(); $shipment = $order->getShipments()->get(0); $order->addProduct($this->products[1], 1, false, $shipment); // $200 $shipment->recalculateAmounts(false); $shipment->save(); // @todo: fix failing assertion // 2 ShipmentTax records are created for the same tax type (1st is not deleted, before the 2nd is created) $this->assertEquals(1, $shipment->getRelatedRecordSet('ShipmentTax')->size(), 'expecting one ShipmentTax'); $order->save(); $this->order->finalize(); /* debug echo "\n Order is finalized!\n"; foreach($shipment->getRelatedRecordSet('ShipmentTax') as $item) { echo 'shipment tax id:', $item->getID(), ', type:', $item->type->get(), ', amount:', $item->getAmount(), ' ('. $item->shipmentID->get()->getTaxAmount() .')', ', shipment id:', $item->shipmentID->get()->getID(), ', taxRate id:', $item->taxRateID->get()->getID(), ', taxClass:', implode(';', $item->taxRateID->get()->taxID->get()->name->get()).'('. $item->taxRateID->get()->taxID->get()->getID() .')', ', zone:', $item->taxRateID->get()->deliveryZoneID->get()->name->get(),'(', $item->taxRateID->get()->deliveryZoneID->get()->getID() ,')', // blame canada!! "\n"; } */ $this->assertEquals(1, $order->getShipments()->size(), 'expecting one shipment'); $this->assertEqual(40, $shipment->getRelatedRecordSet('ShipmentTax')->get(0)->shipmentID->get()->getTaxAmount(), 40); // @todo: fix failing assertion $this->assertEquals(1, $shipment->getRelatedRecordSet('ShipmentTax')->size(), 'expecting one ShipmentTax'); $this->assertEqual($shipment->getRelatedRecordSet('ShipmentTax')->get(0)->amount->get(), 40); }
public function testPastOrdersInQuantityPrices() { ActiveRecordModel::getApplication()->getConfig()->setRuntime('INVENTORY_TRACKING', 'DISABLE'); $condition = DiscountCondition::getNewInstance(); $condition->isEnabled->set(true); $condition->save(); $action = DiscountAction::getNewInstance($condition); $action->actionClass->set('RuleActionIncludePastOrdersInQuantityPrices'); $action->isEnabled->set(true); $action->save(); $this->product1->isEnabled->set(true); $this->product1->stockCount->set(10); $this->product1->save(); // price = 10 $price = $this->product1->getPricingHandler()->getPrice($this->usd); $price->setPriceRule(3, null, 5); $price->setPriceRule(4, null, 4); $price->save(); $this->order->addProduct($this->product1, 2, true); $this->order->save(); $this->assertEquals(20, $this->order->getTotal(true)); $this->order->finalize(); $this->order->isPaid->set(true); $this->order->save(); $this->order->reload(); ActiveRecord::clearPool(); // new order, purchase 1 item, but receive discount like for 3 items $this->validatePastOrderQtPriceOrderTotal(1, 5); $this->validatePastOrderQtPriceOrderTotal(2, 8); // test with date range $action->setParamValue('days', 3); $action->save(); $this->order->dateCompleted->set(strtotime('now -4 days')); $this->order->save(); $this->validatePastOrderQtPriceOrderTotal(1, 10); $action->setParamValue('days', 4); $action->save(); $this->validatePastOrderQtPriceOrderTotal(1, 5); $this->order->dateCompleted->set(strtotime('now -2 days')); $this->order->save(); $action->save(); $this->validatePastOrderQtPriceOrderTotal(1, 5); $this->order->dateCompleted->set(strtotime('now -20 days')); $this->order->save(); $action->save(); $this->validatePastOrderQtPriceOrderTotal(1, 10); }
public function testDeletedProductsInCompletedOrders() { $this->products[0]->setValueByLang('name', 'xx', 'test'); $this->products[0]->save(); $sku = $this->products[0]->sku->get(); $this->order->addProduct($this->products[0], 1); $this->order->addProduct($this->products[1], 1); $this->order->save(); $this->order->finalize(); $total = $this->order->getTotal(); $this->assertEqual($total, 300); $this->products[0]->delete(); ActiveRecord::clearPool(); $order = CustomerOrder::getInstanceByID($this->order->getID()); $order->loadAll(); $this->assertEqual($order->getShoppingCartItemCount(), 2); $this->assertEqual($total, $order->getTotal()); $deletedItem = array_shift($order->getShoppingCartItems()); $deleted = $deletedItem->toArray(); $this->assertEqual($deleted['Product']['nameData']['xx'], 'test'); $this->assertEqual($deleted['Product']['sku'], $sku); // change quantities $this->config->setRuntime('INVENTORY_TRACKING', 'ENABLE_AND_HIDE'); $deletedItem->count->set(2); $order->save(); $this->assertEqual(400, $order->getTotal()); }
/** * Processes data import - one type of data at a time * * Data size is limited to 50 records per call */ public function process() { $type = $this->getCurrentType(); // import completed if (is_null($type)) { return null; } $total = $this->getCurrentRecordCount(); $offsets = $this->getIdOffsets(); $offset = isset($offsets[$type]) ? $offsets[$type] : null; for ($k = 1; $k <= self::MAX_RECORDS; $k++) { $id = $this->getCurrentProgress(); try { $record = call_user_func_array(array($this->driver, 'getNext' . $type), array($id)); } catch (Exception $e) { var_dump($e); } // import completed? if (null == $record) { $this->setNextType(); break; } // apply ID offset if (is_numeric($record->getID())) { $record->setID($record->getID() + $offset); } try { // call custom save routine if defined if (method_exists($this->driver, 'save' . $type)) { call_user_func_array(array($this->driver, 'save' . $type), array($record)); } else { //$record->save(ActiveRecord::PERFORM_INSERT); $record->save(); } } catch (Exception $e) { var_dump($e); throw $e; } ActiveRecord::clearPool(); $record->__destruct(); $record->destruct(); unset($record); $this->setProgress($this->getCurrentProgress() + 1); } return array('type' => $type, 'progress' => $this->getCurrentProgress(), 'total' => $total); }
public function testRatingTypes() { $type = ProductRatingType::getNewInstance(Category::getRootNode()); $type->save(); $rating = ProductRating::getNewInstance($this->product, $type); $rating->rating->set(6); $rating->save(); $this->product->reload(); $this->assertEqual($this->product->ratingCount->get(), 1); $this->assertEqual($this->product->ratingSum->get(), 6); $this->assertEqual($this->product->rating->get(), 6); ActiveRecord::clearPool(); $summary = ProductRatingSummary::getInstance($this->product, $type); $summary->reload(); $this->assertEqual($summary->ratingCount->get(), 1); $this->assertEqual($summary->ratingSum->get(), 6); $this->assertEqual($summary->rating->get(), 6); $type2 = ProductRatingType::getNewInstance(Category::getRootNode()); $type2->save(); $rating = ProductRating::getNewInstance($this->product, $type2); $rating->rating->set(4); $rating->save(); $this->product->reload(); $this->assertEqual($this->product->ratingCount->get(), 2); $this->assertEqual($this->product->ratingSum->get(), 10); $this->assertEqual($this->product->rating->get(), 5); ActiveRecord::clearPool(); $summary = ProductRatingSummary::getInstance($this->product, $type2); $summary->reload(); $this->assertEqual($summary->ratingCount->get(), 1); $this->assertEqual($summary->ratingSum->get(), 4); $this->assertEqual($summary->rating->get(), 4); }
private function send(NewsletterMessage $newsletter) { set_time_limit(0); $response = new JSONResponse(null); $data = $this->getRecipientData($this->request->toArray()); $total = count($data); $subscribers = $users = array(); foreach ($data as $row) { if ($row['userID']) { $users[] = $row['userID']; } else { $subscribers[] = $row['subscriberID']; } } $progress = 0; foreach (array('User' => $users, 'NewsletterSubscriber' => $subscribers) as $table => $ids) { foreach (array_chunk($ids, self::PROGRESS_FLUSH_INTERVAL) as $chunk) { foreach (ActiveRecordModel::getRecordSet($table, new ARSelectFilter(new InCond(new ARFieldHandle($table, 'ID'), $chunk))) as $recipient) { $progress++; $newsletter->send($recipient, $this->application); if ($progress % self::PROGRESS_FLUSH_INTERVAL == 0 || $total == $progress) { $response->flush($this->getJsonResponse(array('progress' => $progress, 'total' => $total))); } } ActiveRecord::clearPool(); } } $newsletter->markAsSent(); $response->flush($this->getJsonResponse(array('progress' => 0, 'total' => $total))); exit; }
public function testDefaultZoneVATWithAnotherZone() { TaxRate::getNewInstance(DeliveryZone::getDefaultZoneInstance(), $this->tax, 10)->save(); TaxRate::getNewInstance($this->deliveryZone, $this->tax, 10)->save(); DeliveryZoneCountry::getNewInstance($this->deliveryZone, 'US')->save(); $order = CustomerOrder::getNewInstance($this->user); $order->addProduct($this->product, 1, true); $order->currency->set($this->currency); $order->shippingAddress->set($this->address); $order->save(); $this->assertEqual($order->getTotal($this->currency), 100); $order->finalize(); $this->assertDefaultZoneOrder($order, $this->currency); ActiveRecord::clearPool(); $reloaded = CustomerOrder::getInstanceById($order->getID(), true); $this->assertDefaultZoneOrder($reloaded, $this->currency); }