/** * @role create */ public function create() { $request = $this->getRequest(); $rpp = RecurringProductPeriod::getNewInstance(Product::getInstanceByID((int) $request->get('productID'), ActiveRecord::LOAD_DATA)); $rpp->position->set(1000); return $this->save($rpp); }
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); }
protected function getKeywordsString($array) { if (isset($array['Product'])) { $array = $array['Product']; } if (empty($array['sku'])) { return null; } if (is_string($array['name'])) { $array['name_lang'] = $array['name']; } if (isset($array['DefaultImage']) && is_array($array['DefaultImage']['Product']['name']) && !empty($array['DefaultImage']['Product']['name']['en'])) { $array['name_lang'] = $array['DefaultImage']['Product']['name']['en']; } if (!empty($array['parentID']) && empty($array['Parent'])) { $array['Parent'] = Product::getInstanceByID($array['parentID'], true)->toArray(); } if (!empty($array['Parent']['name_lang']) && empty($array['name_lang'])) { $array['name_lang'] = $array['Parent']['name_lang']; } $name = isset($array['name_lang']) ? $array['name_lang'] : array_shift($array['name']); //if (!$name) { var_dump($array); exit; } $str = $name . '-' . $array['sku']; //var_dump($str); if ($str) { $str = preg_replace('/[^a-zA-Z0-9_\\-]/', '', urldecode(createHandleString($str))); } return $str && strlen($str) > 0 ? $str : null; }
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(); }
public function delete() { $product = Product::getInstanceByID($this->request->get('id'), ActiveRecord::LOAD_DATA, array('Category')); $category = Category::getInstanceByID($this->request->get('categoryId'), ActiveRecord::LOAD_DATA); $relation = ActiveRecordModel::getInstanceById('ProductCategory', array('productID' => $product->getID(), 'categoryID' => $category->getID())); $relation->delete(); return new JSONResponse(array('data' => $relation->toFlatArray())); }
public function specification() { $request = $this->application->getRequest(); $productID = $request->get('ID'); $product = Product::getInstanceByID($productID, Product::LOAD_DATA, Product::LOAD_REFERENCES); $product->load(); throw new Exception(' product ' . json_encode($product->getSpecification())); }
public function process() { $custom = $this->request->get('custom'); foreach (json_decode($this->request->get('items')) as $key => $id) { $prod = Product::getInstanceByID($id, true); $prod->custom->set($custom[$key]); $prod->save(); } }
public function create() { $parentId = $this->request->get('parentID', false); if (substr($parentId, 0, 1) == 'c') { $parent = Category::getInstanceByID(substr($parentId, 1)); } else { $parent = Product::getInstanceByID($parentId); } $productOption = ProductOption::getNewInstance($parent); return $this->save($productOption); }
public function index() { $productID = (int) $this->request->get('id'); $product = Product::getInstanceByID($productID, ActiveRecord::LOAD_DATA); $response = new ActionResponse(); $response->set('ownerID', $productID); $response->set('categoryID', $product->category->get()->getID()); $response->set('items', ProductBundle::getBundledProductArray($product)); $currency = $this->application->getDefaultCurrency(); $response->set('total', $currency->getFormattedPrice(ProductBundle::getTotalBundlePrice($product, $currency))); return $response; }
/** * @role update */ public function create() { $product = Product::getInstanceByID((int) $this->request->get('productID')); if ($uploadFile = $this->request->get('uploadFile')) { $tmpPath = $uploadFile['tmp_name']; $name = $uploadFile['name']; } else { $tmpPath = null; $name = basename($this->request->get('filePath')); } $productFile = ProductFile::getNewInstance($product, $tmpPath, $name, $this->request->get('filePath')); return $this->save($productFile); }
public function index() { //error_reporting(E_ALL);ini_set('display_errors', 1); $product = Product::getInstanceByID($this->request->get('id'), true); $mirror = null; foreach ($product->getRelatedRecordSetArray('ProductImage', select()) as $image) { if ($image['title_lang'] == 'Virtual Mirror') { $mirror = $image['urls'][3]; } } if ($mirror) { $response = new BlockResponse(); $response->set('mirror', $mirror); return $response; } }
/** * Creates new relationship * * @role update */ public function add() { $productID = $this->request->get('relatedownerID'); $ownerID = $this->request->get('id'); $list = ActiveRecordModel::getInstanceById('ProductList', $ownerID, ActiveRecordModel::LOAD_DATA); $product = Product::getInstanceByID($productID, Product::LOAD_DATA, array('ProductImage')); if (!$list->contains($product)) { $list->addProduct($product); $response = new ActionResponse(); $response->set('product', $product->toArray()); $response->set('added', true); return $response; } else { return new JSONResponse(array('error' => $this->translate('_err_multiple'))); } }
private function getBestsellerData($sql, $order = 'DESC') { $this->setChartType(self::TABLE); $q = $this->getQuery($sql); $f = $q->getFilter(); $f->resetOrder(); $f->resetGrouping(); $f->setOrder(new ARExpressionHandle('cnt'), $order); $q->addField('OrderedItem.productID'); $f->setGrouping(new ARExpressionHandle('OrderedItem.productID')); $f->mergeCondition(new EqualsCond(new ARFieldHandle('CustomerOrder', 'isFinalized'), 1)); $f->setLimit(self::TABLE_LIMIT); $q->joinTable('CustomerOrder', 'OrderedItem', 'ID', 'customerOrderID'); $this->getReportData($q); $ids = array(); foreach ($this->values as $product) { $ids[$product['productID']] = $product['cnt']; } // fetch product details $fields = array_flip(array('sku', 'name', 'cnt')); $products = ActiveRecordModel::getRecordSetArray('Product', new ARSelectFilter(new INCond(new ARFieldHandle('Product', 'ID'), array_keys($ids))), array('Parent')); ProductSet::loadVariationsForProductArray($products); foreach ($products as $product) { $product['cnt'] = $ids[$product['ID']]; if (empty($product['name'])) { if (!empty($product['parentID'])) { $parent = Product::getInstanceByID($product['parentID'], true); $product['name'] = $parent->getValueByLang('name'); } else { $product['name'] = ''; } } if (isset($product['variationValues'])) { $product['name'] .= ' (' . implode(' / ', $product['variationValues']) . ')'; } // array_merge to put all array values in the same order $ids[$product['ID']] = array_merge($fields, array_intersect_key($product, $fields)); } $this->values = $ids; }
/** * Creates new relationship * * @role update */ public function add() { $productID = $this->request->get('relatedownerID'); $ownerID = $this->request->get('id'); $owner = Product::getInstanceByID($ownerID, Product::LOAD_DATA); $product = Product::getInstanceByID($productID, Product::LOAD_DATA, array('ProductImage')); if ($product->isBundle()) { return new JSONResponse(array('error' => $this->translate('_err_bundle_with_bundle'))); } if (!ProductBundle::hasRelationship($owner, $product)) { $instance = ProductBundle::getNewInstance($owner, $product); if (!$instance) { return new JSONResponse(array('error' => $this->translate('_err_add_to_itself'))); } $instance->save(); $response = new ActionResponse(); $response->set('product', $product->toArray()); $response->set('added', true); $response->set('total', $this->getTotal($owner)); return $response; } else { return new JSONResponse(array('error' => $this->translate('_err_multiple'))); } }
public function countTabsItems() { ClassLoader::import('application.model.product.*'); $product = Product::getInstanceByID((int) $this->request->get('id'), ActiveRecord::LOAD_DATA); return new JSONResponse(array('tabProductBundle' => count(ProductBundle::getBundledProductArray($product)), 'tabProductRelationship' => $product->getRelationships(ProductRelationship::TYPE_CROSS)->getTotalRecordCount(), 'tabProductUpsell' => $product->getRelationships(ProductRelationship::TYPE_UP)->getTotalRecordCount(), 'tabProductFiles' => $product->getFiles(false)->getTotalRecordCount(), 'tabProductImages' => count($product->getImageArray()), 'tabProductOptions' => $product->getOptions()->getTotalRecordCount(), 'tabProductReviews' => $product->getRelatedRecordCount('ProductReview'), 'tabProductCategories' => $product->getRelatedRecordCount('ProductCategory') + 1, 'tabProductVariations' => $product->getRelatedRecordCount('Product', new ARSelectFilter(new EqualsCond(new ARFieldHandle('Product', 'isEnabled'), true))))); }
public function generateTestInvoices() { return; ClassLoader::import('application.model.category.*'); ClassLoader::import('application.model.product.*'); $config = ActiveRecordModel::getApplication()->getConfig(); $config->set('RECURRING_BILLING_PAYMENT_DUE_DATE_DAYS', 7); $config->save(); // data $userID = 110; $product1ID = 339; $recurringProductPeriodID = 19; // ~ // create first order $user = User::getInstanceByID($userID, true); $product1 = Product::getInstanceByID($product1ID, true); $order = CustomerOrder::getNewInstance($user); $order->save(true); $rpp = RecurringProductPeriod::getInstanceByID($recurringProductPeriodID); $item = $order->addProduct($product1, 1, true); $item->save(); $recurringItem = RecurringItem::getNewInstance($rpp, $item); $recurringItem->setupPrice->set(100); $recurringItem->periodPrice->set(25); $recurringItem->save(); $order->finalize(); // generate invoices echo '<pre>Invoices for {CustomerOrder ID:' . $order->getID() . '}:', "\n"; $now = time(); for ($ts = $now; $ts < strtotime('+20 months', $now); $ts = $ts + 60 * 60 * 24) { $z = CustomerOrder::generateRecurringInvoices(date('Y-m-d', $ts)); foreach ($z as $id) { echo '{CustomerOrder ID:' . $id . '}', "\n"; } } die('-done-</pre>'); }
private function getCategory(CsvImportProfile $profile, $record) { $fields = $this->getSortedFields($profile); // detect product category if (isset($fields['Product']['parentID']) && !empty($record[$fields['Product']['parentID']])) { $cat = Product::getInstanceByID($record[$fields['Product']['parentID']], true); } else { if (isset($fields['Parent']['parentSKU']) && !empty($record[$fields['Parent']['parentSKU']])) { $cat = Product::getInstanceBySKU($record[$fields['Parent']['parentSKU']]); } else { if (isset($fields['Category']['ID'])) { try { $cat = Category::getInstanceById($record[$fields['Category']['ID']], Category::LOAD_DATA); } catch (ARNotFoundException $e) { $failed++; continue; } } else { if (isset($fields['Categories']['Categories'])) { $index = $fields['Categories']['Categories']; $categories = explode('; ', $record[$index]); $cat = $this->getCategoryByPath($profile, array_shift($categories)); $extraCategories = $categories; } else { if (isset($fields['Category'])) { $path = array(); foreach ($fields['Category'] as $level => $csvIndex) { if ($record[$csvIndex]) { $path[] = $record[$csvIndex]; } } $cat = $this->getCategoryByPath($profile, $path); } else { return $this->getRoot($profile); } } } } } return $cat; }
<?php $_from = $this->_tpl_vars['images']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array'); } if (count($_from)) { foreach ($_from as $this->_tpl_vars['image']) { ?> <?php if ($this->_tpl_vars['image']['productID'] != $this->_tpl_vars['product']['ID']) { ?> <?php $this->assign('varID', $this->_tpl_vars['image']['productID']); ?> <?php $this->assign("varProduct", Product::getInstanceByID($this->get_template_vars("varID"))->toArray()); ?> <?php ob_start(); echo smarty_function_productUrl(array('product' => $this->_tpl_vars['varProduct']), $this); $this->_smarty_vars['capture']['default'] = ob_get_contents(); $this->assign('imgLink', ob_get_contents()); ob_end_clean(); ?> <?php $this->assign('isVariation', 1); ?> <?php } else { ?>
public function getNextCustomerOrder() { if (!($data = $this->loadRecord('SELECT * FROM ' . $this->getTablePrefix() . 'orders WHERE customerID > 0'))) { return null; } $user = ActiveRecordModel::getInstanceByIDIfExists('User', $this->getRealId('User', $data['customerID'], false)); if (!$user || !$user->isExistingRecord()) { return $this->getNextCustomerOrder(); } $currCode = $data['currency_code']; if (!($currency = ActiveRecordModel::getInstanceByIDIfExists('Currency', $currCode, false))) { $currency = Currency::getNewInstance($currCode); $currency->save(); } $order = CustomerOrder::getNewInstance($user); $order->currency->set($currency); $order->dateCompleted->set($data['order_time']); // products foreach ($this->getDataBySql('SELECT * FROM ' . $this->getTablePrefix() . 'ordered_carts WHERE orderID=' . $data['orderID']) as $item) { $product = null; // try to identify product by SKU preg_match('/\\[(.*)\\]/', $item['name'], $sku); if (isset($sku[1])) { $product = Product::getInstanceBySKU($sku[1]); } // if that doesn't work, then try to match the exact name if (!$product) { $productData = array_shift($this->getDataBySQL('SELECT productID FROM ' . $this->getTablePrefix() . 'products WHERE name="' . addslashes($item['name']) . '"')); if ($productData && is_array($productData)) { $product = Product::getInstanceByID($this->getRealId('Product', $productData['productID']), Product::LOAD_DATA); } } if ($product) { $order->addProduct($product, $item['Quantity'], true); $orderedItem = array_shift($order->getItemsByProduct($product)); $orderedItem->price->set($item['Price']); } } // addresses $order->shippingAddress->set($this->getUserAddress($data, 'shipping_')); $order->billingAddress->set($this->getUserAddress($data, 'billing_')); $order->status->set($this->getOrderStatus($data['statusID'])); if ($order->status->get() == CustomerOrder::STATUS_SHIPPED) { $order->isPaid->set(true); } $order->rawData = $data; return $order; }
/** * @role update */ public function create() { $product = Product::getInstanceByID((int) $this->request->get('productID')); $fileGroup = ProductFileGroup::getNewInstance($product); return $this->save($fileGroup); }
/** * 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 testReloadedVariationPricing() { $variation = $this->products[0]->createChildProduct(); $variation->isEnabled->set(true); $variation->setChildSetting('price', Product::CHILD_OVERRIDE); $variation->setPrice('USD', 0); $variation->save(); // clear pool and reload only variation instance ActiveRecordModel::clearPool(); $reloadedVar = Product::getInstanceByID($variation->getID(), true); $order = CustomerOrder::getNewInstance($this->user); $order->addProduct($reloadedVar, 1, true); $this->assertEquals($order->getTotal(true), 100); }
public function previous($diff = -1) { $product = Product::getInstanceByID($this->request->get('id'), true, array('Category')); $this->category = !$this->request->get('category') ? $product->category->get() : Category::getInstanceByID($this->request->get('category'), true); $this->getAppliedFilters(); $this->getSelectFilter(); if ($this->request->get('quickShopSequence')) { $ids = json_decode($this->request->get('quickShopSequence')); } else { $ids = array(); foreach (ActiveRecordModel::getFieldValues('Product', $this->productFilter->getSelectFilter(), array('ID'), array('Category')) as $row) { $ids[] = $row['ID']; } } $index = array_search($product->getID(), $ids); $prevIndex = $index + $diff; if ($prevIndex < 0) { $prevIndex = count($ids) - 1; } else { if ($prevIndex == count($ids)) { $prevIndex = 0; } } include_once ClassLoader::getRealPath('application.helper.smarty') . '/function.productUrl.php'; if ('quickShop' == $this->request->get('originalAction')) { return new ActionRedirectResponse('product', 'quickShop', array('id' => $ids[$prevIndex], 'query' => $this->getContext())); } else { return new RedirectResponse(createProductUrl(array('product' => Product::getInstanceByID($ids[$prevIndex], true)->toArray(), 'query' => $this->getContext()), $this->application)); } }
public function copy() { $original = Product::getInstanceByID($this->request->get('id'), true); $cloned = clone $original; $cloned->isEnabled->set(false); $cloned->sku->set($cloned->sku->get() . ' (copy)'); $cloned->save(); return new JSONResponse($cloned->toFlatArray()); }
public function sendContactForm() { $product = Product::getInstanceByID($this->request->get('id'), Product::LOAD_DATA); $redirect = new ActionRedirectResponse('product', 'index', array('id' => $product->getID())); $validator = $this->buildContactValidator(); if ($validator->isValid()) { $email = new Email($this->application); $email->setTemplate('contactForm/productInquiry'); $email->setFrom($this->request->get('email'), $this->request->get('name')); $email->setTo($this->config->get('NOTIFICATION_EMAIL'), $this->config->get('STORE_NAME')); $email->set('message', $this->request->get('msg')); $email->set('product', $product->toArray()); $email->send(); $msg = $this->translate('_inquiry_form_sent'); if ($this->isAjax()) { $response = new JSONResponse(array('message' => $msg), 'success'); } else { $this->setMessage($msg); $response = $redirect; } return $response; } else { if ($this->isAjax()) { return new JSONResponse(array('errors' => $validator->getErrorList())); } else { return $redirect; } } }
public function testClone() { $image = ActiveRecordModel::getNewInstance('ProductImage'); $image->product->set($this->product); $image->save(); $this->assertSame($image, $this->product->defaultImage->get()); $numField = SpecField::getNewInstance($this->productCategory, SpecField::DATATYPE_NUMBERS, SpecField::TYPE_NUMBERS_SIMPLE); $numField->save(); $this->product->setAttributeValue($numField, 100); $this->product->save(); $option = ProductOption::getNewInstance($this->product); $option->type->set(ProductOption::TYPE_SELECT); $option->setValueByLang('name', 'en', 'test'); $option->save(); $related = Product::getNewInstance($this->productCategory, 'related'); $related->save(); $relGroup = ProductRelationshipGroup::getNewInstance($this->product, ProductRelationship::TYPE_CROSS); $relGroup->save(); $rel = ProductRelationship::getNewInstance($this->product, $related, $relGroup); $rel->save(); $this->assertEquals(1, $this->product->getRelationships()->size()); $cloned = clone $this->product; $this->assertEquals(100, $cloned->getSpecification()->getAttribute($numField)->value->get()); $cloned->setAttributeValue($numField, 200); $cloned->setPrice($this->usd, 80); $cloned->save(); $this->assertNotEquals($cloned->getID(), $this->product->getID()); ActiveRecordModel::clearPool(); $reloaded = Product::getInstanceByID($cloned->getID(), true); $reloaded->loadPricing(); $this->assertEquals(80, $reloaded->getPrice($this->usd)); $reloaded->loadSpecification(); $this->assertEquals(200, $reloaded->getSpecification()->getAttribute($numField)->value->get()); // related products $rel = $reloaded->getRelationships(); $this->assertEquals(1, $rel->size()); $this->assertSame($reloaded, $rel->get(0)->productRelationshipGroup->get()->product->get()); // options $clonedOpts = ProductOption::getProductOptions($reloaded); $this->assertEquals(1, $clonedOpts->size()); // image $this->assertTrue(is_object($reloaded->defaultImage->get())); $this->assertNotEquals($reloaded->defaultImage->get()->getID(), $this->product->defaultImage->get()->getID()); }
/** * @role update */ public function sort() { $target = $this->request->get('target'); if (!$target) { foreach ($this->request->toArray() as $key => $value) { if (is_array($value)) { $target = $key; break; } } } $product = Product::getInstanceByID($this->request->get('id')); $type = $this->request->get('type'); preg_match('/_(\\d+)$/', $target, $match); // Get group. if (substr($target, 0, 8) == 'noGroup_') { $match = array(); } foreach ($this->request->get($target, array()) as $position => $key) { if (empty($key)) { continue; } $relationship = ProductRelationship::getInstance($product, Product::getInstanceByID((int) $key), $type); $relationship->position->set((int) $position); if (isset($match[1])) { $relationship->productRelationshipGroup->set(ProductRelationshipGroup::getInstanceByID((int) $match[1])); } else { $relationship->productRelationshipGroup->setNull(); } $relationship->save(); } return new JSONResponse(false, 'success'); }
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 getVariationFromRequest(array $variations) { $ids = array(); foreach ($variations['variations'] as $variation) { $ids[] = $this->request->get('variation_' . $variation['ID']); } $hash = implode('-', $ids); if (!isset($variations['products'][$hash])) { return $productRedirect; } return Product::getInstanceByID($variations['products'][$hash]['ID'], Product::LOAD_DATA); }
public static function transformArray($array, ARSchema $schema) { $array = parent::transformArray($array, $schema); $currency = Currency::getInstanceByID($array['currencyID']); $array['serializedRules'] = unserialize($array['serializedRules']); if ($array['serializedRules'] && !is_array($array['serializedRules'])) { $array['serializedRules'] = array(); } if ($array['serializedRules'] && is_array($array['serializedRules'])) { $ruleController = self::getApplication()->getBusinessRuleController(); $quantities = array_keys($array['serializedRules']); $nextQuant = array(); foreach ($quantities as $key => $quant) { $nextQuant[$quant] = isset($quantities[$key + 1]) ? $quantities[$key + 1] - 1 : null; } foreach ($array['serializedRules'] as $quantity => $prices) { foreach ($prices as $group => $price) { $originalPrice = $currency->roundPrice($price); $product = isset($array['Product']) ? $array['Product'] : Product::getInstanceByID($array['productID']); $price = $ruleController->getProductPrice($product, $originalPrice); $array['quantityPrices'][$group][$quantity] = array('originalPrice' => $originalPrice, 'price' => $price, 'originalFormattedPrice' => $currency->getFormattedPrice($originalPrice), 'formattedPrice' => $currency->getFormattedPrice($price), 'from' => $quantity, 'to' => $nextQuant[$quantity]); } } } return $array; }