public function handleRequest(SS_HTTPRequest $request, DataModel $model) { $this->pushCurrent(); $this->urlParams = $request->allParams(); $this->request = $request; $this->response = new SS_HTTPResponse(); $this->setDataModel($model); $urlsegment = $request->param('URLSegment'); $this->extend('onBeforeInit'); $this->init(); $this->extend('onAfterInit'); // First check products against URL segment if ($product = Product::get()->filter(array('URLSegment' => $urlsegment, 'Disabled' => 0))->first()) { $controller = Catalogue_Controller::create($product); } elseif ($category = ProductCategory::get()->filter('URLSegment', $urlsegment)->first()) { $controller = Catalogue_Controller::create($category); } else { // If CMS is installed if (class_exists('ModelAsController')) { $controller = ModelAsController::create(); } } $result = $controller->handleRequest($request, $model); $this->popCurrent(); return $result; }
/** * Recursively generate a product menu, starting from the topmost category. * * @return DataList */ public function GroupsMenu() { if ($this->Parent() instanceof ProductCategory) { return $this->Parent()->GroupsMenu(); } return ProductCategory::get()->filter("ParentID", $this->ID); }
public function getDefaultSearchContext() { $context = parent::getDefaultSearchContext(); $fields = $context->getFields(); $fields->push(CheckboxField::create("HasBeenUsed")); //add date range filtering $fields->push(ToggleCompositeField::create("StartDate", "Start Date", array(DateField::create("q[StartDateFrom]", "From")->setConfig('showcalendar', true), DateField::create("q[StartDateTo]", "To")->setConfig('showcalendar', true)))); $fields->push(ToggleCompositeField::create("EndDate", "End Date", array(DateField::create("q[EndDateFrom]", "From")->setConfig('showcalendar', true), DateField::create("q[EndDateTo]", "To")->setConfig('showcalendar', true)))); //must be enabled in config, because some sites may have many products = slow load time, or memory maxes out //future solution is using an ajaxified field if (self::config()->filter_by_product) { $fields->push(ListboxField::create("Products", "Products", Product::get()->map()->toArray())->setMultiple(true)); } if (self::config()->filter_by_category) { $fields->push(ListboxField::create("Categories", "Categories", ProductCategory::get()->map()->toArray())->setMultiple(true)); } if ($field = $fields->fieldByName("Code")) { $field->setDescription("This can be a partial match."); } //get the array, to maniplulate name, and fullname seperately $filters = $context->getFilters(); $filters['StartDateFrom'] = GreaterThanOrEqualFilter::create('StartDate'); $filters['StartDateTo'] = LessThanOrEqualFilter::create('StartDate'); $filters['EndDateFrom'] = GreaterThanOrEqualFilter::create('EndDate'); $filters['EndDateTo'] = LessThanOrEqualFilter::create('EndDate'); $context->setFilters($filters); return $context; }
public function __construct($controller, $name) { $product = new Product(); $title = new TextField('Title', _t('Product.PAGETITLE', 'Product Title')); $urlSegment = new TextField('URLSegment', 'URL Segment'); $menuTitle = new TextField('MenuTitle', 'Navigation Title'); $sku = TextField::create('InternalItemID', _t('Product.CODE', 'Product Code/SKU'), '', 30); $categories = DropdownField::create('ParentID', _t("Product.CATEGORY", "Category"), $product->categoryoptions())->setDescription(_t("Product.CATEGORYDESCRIPTION", "This is the parent page or default category.")); $otherCategories = ListBoxField::create('ProductCategories', _t("Product.ADDITIONALCATEGORIES", "Additional Categories"), ProductCategory::get()->filter("ID:not", $product->getAncestors()->map('ID', 'ID'))->map('ID', 'NestedTitle')->toArray())->setMultiple(true); $model = TextField::create('Model', _t('Product.MODEL', 'Model'), '', 30); $featured = CheckboxField::create('Featured', _t('Product.FEATURED', 'Featured Product')); $allow_purchase = CheckboxField::create('AllowPurchase', _t('Product.ALLOWPURCHASE', 'Allow product to be purchased'), 1, 'Content'); $price = TextField::create('BasePrice', _t('Product.PRICE', 'Price'))->setDescription(_t('Product.PRICEDESC', "Base price to sell this product at."))->setMaxLength(12); $image = UploadField::create('Image', _t('Product.IMAGE', 'Product Image')); $content = new HtmlEditorField('Content', 'Content'); $fields = new FieldList(); $fields->add($title); //$fields->add($urlSegment); //$fields->add($menuTitle); //$fields->add($sku); $fields->add($categories); //$fields->add($otherCategories); $fields->add($model); $fields->add($featured); $fields->add($allow_purchase); $fields->add($price); $fields->add($image); $fields->add($content); //$fields = $product->getFrontEndFields(); $actions = new FieldList(new FormAction('submit', _t("ChefProductForm.ADDPRODUCT", 'Add product'))); $requiredFields = new RequiredFields(array('Title', 'Model', 'Price')); parent::__construct($controller, $name, $fields, $actions, $requiredFields); }
public function getContinueLink() { $maincategory = ProductCategory::get()->sort(array("ParentID" => "ASC", "ID" => "ASC"))->first(); if ($maincategory) { return $maincategory->Link(); } return Director::baseURL(); }
public function getCategoryChildren() { $category = ProductCategory::get()->filter('ID', $this->CategoryID)->first(); if ($category && $category->Children()->exists()) { return $category->Children(); } else { return $category->Products(); } }
public function getCMSFields() { $fields = parent::getCMSFields(); if ($checkouts = CheckoutPage::get()) { $fields->addFieldToTab('Root.Links', DropdownField::create('CheckoutPageID', _t('CartPage.has_one_CheckoutPage', 'Checkout Page'), $checkouts->map("ID", "Title"))); } if ($pgroups = ProductCategory::get()) { $fields->addFieldToTab('Root.Links', DropdownField::create('ContinuePageID', _t('CartPage.has_one_ContinuePage', 'Continue Product Group Page'), $pgroups->map("ID", "Title"))); } return $fields; }
/** * Find the current category via its URL * * @return ProductCategory * */ public static function get_current_category() { $segment = Controller::curr()->request->param('URLSegment'); $return = null; if ($segment) { $return = ProductCategory::get()->filter('URLSegment', $segment)->first(); } if (!$return) { $return = ProductCategory::create(); } return $return; }
public function getContinueLink() { if ($cartPage = CartPage::get()->first()) { if ($cartPage->ContinuePageID) { return $cartPage->ContinuePage()->Link(); } } $maincategory = ProductCategory::get()->sort(array("ParentID" => "ASC", "ID" => "ASC"))->first(); if ($maincategory) { return $maincategory->Link(); } return Director::baseURL(); }
public function updateCMSFields(FieldList $fields) { // set TabSet names to avoid spaces from camel case $fields->addFieldToTab('Root', new TabSet('FoxyStripe', 'FoxyStripe')); // settings tab $fields->addFieldsToTab('Root.FoxyStripe.Settings', array(HeaderField::create('StoreDetails', _t('FoxyStripeSiteConfig.StoreDetails', 'Store Settings'), 3), LiteralField::create('DetailsIntro', _t('FoxyStripeSiteConfig.DetailsIntro', '<p>Maps to data in your <a href="https://admin.foxycart.com/admin.php?ThisAction=EditStore" target="_blank">FoxyCart store settings</a>.')), TextField::create('StoreName')->setTitle(_t('FoxyStripeSiteConfig.StoreName', 'Store Sub Domain'))->setDescription(_t('FoxyStripeSiteConfig.StoreNameDescription', 'the sub domain for your FoxyCart store')), HeaderField::create('AdvanceHeader', _t('FoxyStripeSiteConfig.AdvancedHeader', 'Advanced Settings'), 3), LiteralField::create('AdvancedIntro', _t('FoxyStripeSiteConfig.AdvancedIntro', '<p>Maps to data in your <a href="https://admin.foxycart.com/admin.php?ThisAction=EditAdvancedFeatures" target="_blank">FoxyCart advanced store settings</a>.</p>')), ReadonlyField::create('DataFeedLink', _t('FoxyStripeSiteConfig.DataFeedLink', 'FoxyCart DataFeed URL'), self::getDataFeedLink())->setDescription(_t('FoxyStripeSiteConfig.DataFeedLinkDescription', 'copy/paste to FoxyCart')), CheckboxField::create('CartValidation')->setTitle(_t('FoxyStripeSiteConfig.CartValidation', 'Enable Cart Validation'))->setDescription(_t('FoxyStripeSiteConfig.CartValidationDescription', 'You must <a href="https://admin.foxycart.com/admin.php?ThisAction=EditAdvancedFeatures#use_cart_validation" target="_blank">enable cart validation</a> in the FoxyCart admin.')), ReadonlyField::create('StoreKey')->setTitle(_t('FoxyStripeSiteConfig.StoreKey', 'FoxyCart API Key'))->setDescription(_t('FoxyStripeSiteConfig.StoreKeyDescription', 'copy/paste to FoxyCart')), ReadonlyField::create('SSOLink', _t('FoxyStripeSiteConfig.SSOLink', 'Single Sign On URL'), self::getSSOLink())->setDescription(_t('FoxyStripeSiteConfig.SSOLinkDescription', 'copy/paste to FoxyCart')))); // configuration warning if (FoxyCart::store_name_warning() !== null) { $fields->insertBefore(LiteralField::create("StoreSubDomainHeaderWarning", _t('FoxyStripeSiteConfig.StoreSubDomainHeadingWarning', "<p class=\"message error\">Store sub-domain must be entered in the <a href=\"/admin/settings/\">site settings</a></p>")), 'StoreDetails'); } // products tab $fields->addFieldsToTab('Root.FoxyStripe.Products', array(HeaderField::create('ProductHeader', _t('FoxyStripeSiteConfig.ProductHeader', 'Products'), 3), CheckboxField::create('MultiGroup')->setTitle(_t('FoxyStripeSiteConfig.MultiGroup', 'Multiple Groups'))->setDescription(_t('FoxyStripeSiteConfig.MultiGroupDescription', 'Allows products to be shown in multiple Product Groups')), HeaderField::create('ProductGroupHD', _t('FoxyStripeSiteConfig.ProductGroupHD', 'Product Groups'), 3), NumericField::create('ProductLimit')->setTitle(_t('FoxyStripeSiteConfig.ProductLimit', 'Products per Page'))->setDescription(_t('FoxyStripeSiteConfig.ProductLimitDescription', 'Number of Products to show per page on a Product Group')), HeaderField::create('ProductQuantityHD', _t('FoxyStripeSiteConfig.ProductQuantityHD', 'Product Form Max Quantity'), 3), NumericField::create('MaxQuantity')->setTitle(_t('FoxyStripeSiteConfig.MaxQuantity', 'Max Quantity'))->setDescription(_t('FoxyStripeSiteConfig.MaxQuantityDescription', 'Sets max quantity for product form dropdown (add to cart form - default 10)')))); // categories tab $fields->addFieldsToTab('Root.FoxyStripe.Categories', array(HeaderField::create('CategoryHD', _t('FoxyStripeSiteConfig.CategoryHD', 'FoxyStripe Categories'), 3), LiteralField::create('CategoryDescrip', _t('FoxyStripeSiteConfig.CategoryDescrip', '<p>FoxyCart Categories offer a way to give products additional behaviors that cannot be accomplished by product options alone, including category specific coupon codes, shipping and handling fees, and email receipts. <a href="https://wiki.foxycart.com/v/2.0/categories" target="_blank">Learn More</a></p><p>Categories you\'ve created in FoxyStripe must also be created in your <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">FoxyCart Categories</a> admin panel.</p>')), GridField::create('ProductCategory', _t('FoxyStripeSiteConfig.ProductCategory', 'FoxyCart Categories'), ProductCategory::get(), GridFieldConfig_RecordEditor::create()))); // option groups tab $fields->addFieldsToTab('Root.FoxyStripe.Groups', array(HeaderField::create('OptionGroupsHead', _t('FoxyStripeSiteConfig', 'Product Option Groups'), 3), LiteralField::create('OptionGroupsDescrip', _t('FoxyStripeSiteConfig.OptionGroupsDescrip', '<p>Product Option Groups allow you to name a set of product options.</p>')), GridField::create('OptionGroup', _t('FoxyStripeSiteConfig.OptionGroup', 'Product Option Groups'), OptionGroup::get(), GridFieldConfig_RecordEditor::create()))); }
public function run($request) { $products = 0; $categories = 0; // First load all products $items = Product::get(); foreach ($items as $item) { // Just write product, on before write should deal with the rest $item->write(); $products++; } // Then all categories $items = ProductCategory::get(); foreach ($items as $item) { // Just write category, on before write should deal with the rest $item->write(); $categories++; } echo "Wrote {$products} products and {$categories} categories.\n"; }
/** * Returns an array of categories suitable for a dropdown menu * TODO: cache this * * @param int $parentID [optional] * @param string $prefix [optional] * @param int $maxDepth [optional] * @return array * @static */ public static function get_category_hierarchy($parentID = 0, $prefix = '', $maxDepth = 999) { $out = array(); $cats = ProductCategory::get()->filter(array('ParentID' => $parentID, 'ShowInMenus' => 1))->sort('Sort'); // If there is a single parent category (usually "Products" or something), we // probably don't want that in the hierarchy. if ($parentID == 0 && $cats->count() == 1) { return self::get_category_hierarchy($cats->first()->ID, $prefix, $maxDepth); } foreach ($cats as $cat) { $out[$cat->ID] = $prefix . $cat->Title; if ($maxDepth > 1) { $out += self::get_category_hierarchy($cat->ID, $prefix . $cat->Title . ' > ', $maxDepth - 1); } } return $out; }
// config $manufacturerIds = [23, 75, 97]; $categoryIds = [166]; // validation $manufacturers = array(); foreach ($manufacturerIds as $id) { if (($i = Manufacturer::get($id)) instanceof Manufacturer) { $manufacturers[] = $i; echo 'try to disable all product with manufactuer "' . $i->getName() . '"(' . $i->getId() . ')' . "\n"; } else { throw new Exception('Invalid manufactuer id "' . $id . '" passed in'); } } $manufacturerIds = array_map(create_function('$a', 'return $a->getId();'), $manufacturers); foreach ($categoryIds as $id) { if (($i = ProductCategory::get($id)) instanceof ProductCategory) { $categories[] = $i; echo 'try to disable all product with category "' . $i->getName() . '"(' . $i->getId() . ')' . "\n"; } else { throw new Exception('Invalid category id "' . $id . '" passed in'); } } $categoryIds = array_map(create_function('$a', 'return $a->getId();'), $categories); // run $products = Product::getProducts('', '', array(), $manufacturerIds, $categoryIds); $count = 0; echo 'found total ' . count($products) . ' products' . "\n"; foreach ($products as $product) { if ($product->getStockOnHand() == 0 && $product->getStockOnOrder() == 0 && $product->getStockOnPO() == 0 && $product->getStockInParts() == 0) { $sku = $product->getSku(); disableProduct($sku);
/** * Gets a list of all ProductCategories * * @param Parent the ID of a parent cetegory * @return DataList */ public function getCommerceCategories($ParentID = 0) { return ProductCategory::get()->filter("ParentID", $ParentID); }
function testProductCategoryDeletion() { $this->logInWithPermission('Product_CANCRUD'); $category = $this->objFromFixture('ProductCategory', 'default'); $category->write(); $this->assertFalse($category->canDelete()); $category2 = $this->objFromFixture('ProductCategory', 'apparel'); $category2->write(); $category2ID = $category2->ID; $this->assertTrue($category2->canDelete()); $this->logOut(); $this->logInWithPermission('ADMIN'); $this->assertFalse($category->canDelete()); $this->assertTrue($category2->canDelete()); $this->logOut(); $this->logInWithPermission('Product_CANCRUD'); $category2->delete(); $this->assertFalse(in_array($category2ID, ProductCategory::get()->column('ID'))); }
function updateSearchForm($form) { $fields = $form->Fields(); $cats = ProductCategory::get()->map()->toArray(); $fields->push(DropdownField::create('q[Category]', 'Category', $cats)->setHasEmptyDefault(true)); $form->loadDataFrom($this->owner->request->getVars()); $form->setFields($fields); }
/** * Get all categories that this product appears in. * @return DataList category data list */ public function getCategories() { return ProductCategory::get()->byIDs($this->getCategoryIDs()); }
/** * create/update product via datafeed. * * @param array $params * * @return array */ private function _dataFeedImport($params) { try { Dao::beginTransaction(); $this->_runner->log('dataFeedImport: ', __CLASS__ . '::' . __FUNCTION__); $sku = $this->_getPram($params, 'sku', null, true); $name = $this->_getPram($params, 'name', null, true); $shortDesc = $this->_getPram($params, 'short_description', $name); $fullDesc = $this->_getPram($params, 'description', ''); $price = StringUtilsAbstract::getValueFromCurrency($this->_getPram($params, 'price', null, true)); $supplierName = $this->_getPram($params, 'supplier', null, true); $supplierCode = $this->_getPram($params, 'supplier_code', null, true); $supplier = $this->_getEntityByName($supplierName, 'Supplier'); if (!$supplier instanceof Supplier) { throw new Exception("invalid supplier:" . $supplierName); } $manufacturerId = $this->_getPram($params, 'manufacturer_id', null, true); $manufacturer = Manufacturer::get($manufacturerId); if (!$manufacturer instanceof Manufacturer) { throw new Exception("invalid Manufacturer:" . $manufacturerId); } $statusName = $this->_getPram($params, 'availability', null, true); $status = $this->_getEntityByName($statusName, 'ProductStatus'); if (!$status instanceof ProductStatus) { throw new Exception("invalid ProductStatus:" . $statusName); } $assetAccNo = $this->_getPram($params, 'assetAccNo', null); $revenueAccNo = $this->_getPram($params, 'revenueAccNo', null); $costAccNo = $this->_getPram($params, 'costAccNo', null); $categoryIds = $this->_getPram($params, 'category_ids', array()); $canSupplyQty = $this->_getPram($params, 'qty', 0); $weight = $this->_getPram($params, 'weight', 0); $images = $this->_getPram($params, 'images', array()); $showOnWeb = $this->_getPram($params, 'showonweb', true); $attributesetId = $this->_getPram($params, 'attributesetId', null); $canUpdate = false; //if we have this product already, then skip if (!($product = Product::getBySku($sku)) instanceof Product) { $this->_runner->log('new SKU(' . $sku . ') for import, creating ...', '', APIService::TAB); $product = Product::create($sku, $name, '', null, null, false, $shortDesc, $fullDesc, $manufacturer, $assetAccNo, $revenueAccNo, $costAccNo, null, null, true, $weight, $attributesetId); $this->log_product("NEW", "=== new === sku={$sku}, name={$name}, shortDesc={$shortDesc}, fullDesc={$fullDesc}, category=" . implode(', ', $categoryIds), '', APIService::TAB); $canUpdate = true; } else { //$this->log_product("UPDATE", "=== update === sku=$sku, name=$name, shortDesc=$shortDesc, fullDesc=$fullDesc, category=" . implode(', ', $categoryIds), '', APIService::TAB); //if there is no price matching rule for this product if (($rulesCount = intval(ProductPriceMatchRule::countByCriteria('active = 1 and productId = ?', array($product->getId())))) === 0) { $this->_runner->log('Found SKU(' . $sku . '): ', '', APIService::TAB); $fullAsset = Asset::getAsset($product->getFullDescAssetId()); $this->_runner->log('Finding asset for full description, assetId:' . ($fullAsset instanceof Asset ? $fullAsset->getAssetId() : ''), '', APIService::TAB . APIService::TAB); $fullAssetContent = ''; if ($fullAsset instanceof Asset) { $fullAssetContent = file_get_contents($fullAsset->getPath()); $this->_runner->log('Got full asset content before html_decode: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB); $fullAssetContent = trim(str_replace(' ', '', $fullAssetContent)); $this->_runner->log('Got full asset content after html_code: <' . $fullAssetContent . '>', '', APIService::TAB . APIService::TAB); } if ($fullAssetContent === '') { $this->_runner->log('GOT BLANK FULL DESD. Updating full description.', '', APIService::TAB . APIService::TAB . APIService::TAB); if ($fullAsset instanceof Asset) { Asset::removeAssets(array($fullAsset->getAssetId())); $this->_runner->log('REMOVED old empty asset for full description', '', APIService::TAB . APIService::TAB . APIService::TAB); } $fullAsset = Asset::registerAsset('full_description_for_product.txt', $fullDesc, Asset::TYPE_PRODUCT_DEC); $product->setFullDescAssetId($fullAsset->getAssetId())->save(); $this->_runner->log('Added a new full description with assetId: ' . $fullAsset->getAssetId(), '', APIService::TAB . APIService::TAB); $canUpdate = true; $this->log_product("UPDATE", "=== updating === sku={$sku} Found ", '', APIService::TAB); } else { $this->log_product("SKIP", "=== SKIP updating === sku={$sku} for full description not null", '', APIService::TAB); } } else { $this->_runner->log('SKIP updating. Found ProductPriceMatchRule count:' . $rulesCount, '', APIService::TAB); $this->log_product("SKIP", "=== SKIP updating === sku={$sku} Found ProductPriceMatchRule count:{$rulesCount}", '', APIService::TAB); } } $json = $product->getJson(); //only update categories and status when there is no pricematching rule or created new if ($canUpdate === true) { //short description, name, manufacturer $this->_runner->log('Updating the price to: ' . StringUtilsAbstract::getCurrency($price), '', APIService::TAB . APIService::TAB); $product->setShortDescription($shortDesc)->setName($name)->setManufacturer($manufacturer)->setWeight($weight)->setSellOnWeb($showOnWeb)->clearAllPrice()->addPrice(ProductPriceType::get(ProductPriceType::ID_RRP), $price); //show on web if (is_array($categoryIds) && count($categoryIds) > 0) { $this->_runner->log('Updating the categories: ' . implode(', ', $categoryIds), '', APIService::TAB . APIService::TAB); foreach ($categoryIds as $categoryId) { if (!($category = ProductCategory::get($categoryId)) instanceof ProductCategory) { continue; } if (count($ids = explode(ProductCategory::POSITION_SEPARATOR, trim($category->getPosition()))) > 0) { foreach (ProductCategory::getAllByCriteria('id in (' . implode(',', $ids) . ')') as $cate) { $product->addCategory($cate); $this->_runner->log('Updated Category ID: ' . $cate->getId(), '', APIService::TAB . APIService::TAB . APIService::TAB); } } } } //updating the images if (is_array($images) && count($images) > 0) { $this->_runner->log('Processing ' . count($images) . ' image(s) ...', '', APIService::TAB . APIService::TAB); $exisitingImgsKeys = array(); $this->_runner->log('Checking exsiting images...', '', APIService::TAB . APIService::TAB . APIService::TAB); $exisitingImgs = $product->getImages(); $this->_runner->log('Got ' . count($exisitingImgs) . ' exisiting image(s), keys: ', '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB); foreach ($exisitingImgs as $image) { if (($asset = Asset::getAsset($image->getImageAssetId())) instanceof Asset) { $imgKey = md5($asset->read()); $exisitingImgsKeys[] = $imgKey; $this->_runner->log($imgKey, '', APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB . APIService::TAB); } } $this->_runner->log('Checking ' . count($images) . ' new image(s) ...', '', APIService::TAB . APIService::TAB); foreach ($images as $image) { //if haven't got any content at all if (!isset($image['content'])) { $this->_runner->log('No Content, SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB); continue; } $newImageContent = base64_decode($image['content']); $newImgKey = md5($newImageContent); //if we've got the image already if (in_array($newImgKey, $exisitingImgsKeys)) { $this->_runner->log('Same Image Exists[' . $newImgKey . '], SKIP!', '', APIService::TAB . APIService::TAB . APIService::TAB); continue; } $asset = Asset::registerAsset($image['name'], $newImageContent, Asset::TYPE_PRODUCT_IMG); $this->_runner->log('Registered a new Asset [AssetID=' . $asset->getAssetId() . '].', '', APIService::TAB . APIService::TAB . APIService::TAB); $product->addImage($asset); $this->_runner->log('Added to product(SKU=' . $product->getSku() . ')', '', APIService::TAB . APIService::TAB . APIService::TAB); } } $product->setStatus($status); $this->_runner->log('Updated Status to: ' . $status->getName(), '', APIService::TAB . APIService::TAB); $product->addSupplier($supplier, $supplierCode, $canSupplyQty); $this->_runner->log('Updated Supplier(ID' . $supplier->getId() . ', name=' . $supplier->getName() . ') with code: ' . $supplierCode . 'canSupplyQty=' . $canSupplyQty, '', APIService::TAB . APIService::TAB); $json = $product->save()->getJson(); $this->_runner->log('Saved Product ID: ' . $product->getId(), '', APIService::TAB . APIService::TAB); } Dao::commitTransaction(); return $json; } catch (Exception $e) { Dao::rollbackTransaction(); throw $e; } }
private function createProductCategories() { if (class_exists('ProductCategory')) { $fixture = Injector::inst()->create('YamlFixture', 'swipestripe-builder/tasks/SWSProductCategory.yml'); $fixture->writeInto($this->getFixtureFactory()); $cats = ProductCategory::get(); if ($cats && $cats->exists()) { foreach ($cats as $cat) { $cat->doPublish(); } } $products = Product::get(); if ($products && $products->exists()) { foreach ($products as $product) { $extra = json_decode($product->ExtraMeta); if (is_object($extra)) { //Categories if ($segment = $extra->ProductCategory) { $cat = ProductCategory::get()->where("\"URLSegment\" = '{$segment}'")->first(); if ($cat && $cat->exists()) { $product->ParentID = $cat->ID; $relation = new ProductCategory_Products(); $relation->ProductCategoryID = $cat->ID; $relation->ProductID = $product->ID; $relation->write(); } } } $product->doPublish(); } } } }
private function _updateCategories(Product &$product, $param) { //update categories if (isset($param->CallbackParameter->categoryIds) && count($categoryIds = $param->CallbackParameter->categoryIds) > 0) { Product_Category::deleteByCriteria('productId = ?', array(trim($product->getId()))); foreach ($categoryIds as $categoryId) { if (!($category = ProductCategory::get($categoryId))) { continue; } Product_Category::create($product, $category); } } return $this; }
public function onBeforeWrite() { parent::onBeforeWrite(); // Only call on first creation, ir if title is changed if ($this->ID == 0 || $this->isChanged('Title') || !$this->URLSegment) { // Set the URL Segment, so it can be accessed via the controller $filter = URLSegmentFilter::create(); $t = $filter->filter($this->Title); // Fallback to generic name if path is empty (= no valid, convertable characters) if (!$t || $t == '-' || $t == '-1') { $t = "category-{$this->ID}"; } // Ensure that this object has a non-conflicting URLSegment value. $existing_cats = ProductCategory::get()->filter('URLSegment', $t)->count(); $existing_products = Product::get()->filter('URLSegment', $t)->count(); $existing_pages = class_exists('SiteTree') ? SiteTree::get()->filter('URLSegment', $t)->count() : 0; $count = (int) $existing_cats + (int) $existing_products + (int) $existing_pages; $this->URLSegment = $count ? $t . '-' . ($count + 1) : $t; } }
/** * get category info by magento-b2b productCategory id * * @param string $systemid * * @return string * @soapmethod */ public function getCategory($systemid) { $response = $this->_getResponse(UDate::now()); try { $systemid = intval(trim($systemid)); Core::setUser(UserAccount::get(UserAccount::ID_SYSTEM_ACCOUNT)); //TODO $obj = ProductCategory::get($systemid); if (!$obj instanceof ProductCategory) { throw new Exception('category with system id "' . $systemid . '" does not exist.'); } $response['status'] = self::RESULT_CODE_SUCC; $this->addCData('category', json_encode($obj->getJson()), $response); } catch (Exception $e) { $response['status'] = self::RESULT_CODE_FAIL; $this->addCData('error', $e->getMessage(), $response); } return trim($response->asXML()); }
/** * Perform more complex imports of generic columns * */ public function processRecord($record, $columnMap, &$results, $preview = false) { // Get Current Object $objID = parent::processRecord($record, $columnMap, $results, $preview); $object = DataObject::get_by_id($this->objectClass, $objID); $this->extend("onBeforeProcess", $record, $object); // Loop through all fields and setup associations foreach ($record as $key => $value) { // Find any categories (denoted by a 'CategoryXX' column) if (strpos($key, 'Category') !== false) { $category = ProductCategory::get()->filter("Title", $value)->first(); if ($category) { $object->Categories()->add($category); } } if ($key == 'Categories') { $parts = explode(',', $value); if (!count($parts)) { return false; } // First remove all categories foreach ($object->Categories() as $category) { $object->Categories()->remove($category); } // Now re-add categories foreach ($parts as $part) { $category = ProductCategory::get()->filter("Title", trim($part))->first(); if ($category) { $object->Categories()->add($category); } } } // Find any Images (denoted by a 'ImageXX' column) if (strpos($key, 'Image') !== false && $key != "Images") { $image = Image::get()->filter("Name", $value)->first(); if ($image) { $object->Images()->add($image); } } // Alternativley look for the 'Images' field as a CSV if ($key == "Images") { $parts = explode(',', $value); if (count($parts)) { // First remove all Images foreach ($object->Images() as $image) { $object->Images()->remove($image); } // Now re-add categories foreach ($parts as $part) { $image = Image::get()->filter("Name", trim($part))->first(); if ($image) { $object->Images()->add($image); } } } } } $this->extend("onAfterProcess", $record, $object); $object->destroy(); unset($object); return $objID; }
public function run($request) { if ($request->getVar('createintzone')) { $this->populateInternationalZone(); DB::alteration_message('Created an international zone', 'created'); return; } $this->extend("beforePopulate"); $factory = Injector::inst()->create('FixtureFactory'); $parentid = 0; //create products if (!DataObject::get_one('Product')) { $fixture = new YamlFixture(SHOP_DIR . "/tests/fixtures/dummyproducts.yml"); $fixture->writeInto($factory); //needs to be a data model $shoppage = ProductCategory::get()->filter('URLSegment', 'shop')->first(); $parentid = $shoppage->ID; $categoriestopublish = array('products', 'electronics', 'apparel', 'entertainment', 'music', 'movies', 'drama', 'toys', 'food', 'books', 'jewellery', 'furniture', 'kitchen', 'bedroom', 'stationery'); foreach ($categoriestopublish as $categoryname) { $factory->get("ProductCategory", $categoryname)->publish('Stage', 'Live'); } $productstopublish = array('mp3player', 'hdtv', 'socks', 'tshirt', 'beachball', 'hoop', 'kite', 'genericmovie', 'lemonchicken', 'ring', 'book', 'lamp', 'paper', 'pens'); foreach ($productstopublish as $productname) { $factory->get("Product", $productname)->publish('Stage', 'Live'); } DB::alteration_message('Created dummy products and categories', 'created'); } else { echo "<p style=\"color:orange;\">Products and categories were not created because some already exist.</p>"; } //cart page if (!($page = DataObject::get_one('CartPage'))) { $fixture = new YamlFixture(SHOP_DIR . "/tests/fixtures/pages/Cart.yml"); $fixture->writeInto($factory); $page = $factory->get("CartPage", "cart"); $page->ParentID = $parentid; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); DB::alteration_message('Cart page created', 'created'); } //checkout page if (!($page = DataObject::get_one('CheckoutPage'))) { $fixture = new YamlFixture(SHOP_DIR . "/tests/fixtures/pages/Checkout.yml"); $fixture->writeInto($factory); $page = $factory->get("CheckoutPage", "checkout"); $page->ParentID = $parentid; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); DB::alteration_message('Checkout page created', 'created'); } //account page if (!DataObject::get_one('AccountPage')) { $fixture = new YamlFixture(SHOP_DIR . "/tests/fixtures/pages/Account.yml"); $fixture->writeInto($factory); $page = $factory->get("AccountPage", "account"); $page->ParentID = $parentid; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); DB::alteration_message('Account page \'Account\' created', 'created'); } //terms page if (!($termsPage = DataObject::get_one('Page', "\"URLSegment\" = 'terms-and-conditions'"))) { $fixture = new YamlFixture(SHOP_DIR . "/tests/fixtures/pages/TermsConditions.yml"); $fixture->writeInto($factory); $page = $factory->get("Page", "termsconditions"); $page->ParentID = $parentid; $page->writeToStage('Stage'); $page->publish('Stage', 'Live'); //set terms page id in config $config = SiteConfig::current_site_config(); $config->TermsPageID = $page->ID; $config->write(); DB::alteration_message("Terms and conditions page created", 'created'); } //countries config - removes some countries $siteconfig = SiteConfig::current_site_config(); if (empty($siteconfig->AllowedCountries)) { $siteconfig->AllowedCountries = "AF,AL,DZ,AS,AD,AO,AG,AR,AM,AU,AT,AZ,BS,BH,\n\t\t\tBD,BB,BY,BE,BZ,BJ,BT,BO,BA,BW,BR,BN,BG,BF,BI,\n\t\t\tKH,CM,CA,CV,CF,TD,CL,CN,CO,KM,CG,CR,CI,HR,CU,\n\t\t\tCY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FJ,FI,\n\t\t\tFR,GA,GM,GE,DE,GH,GR,GD,GT,GN,GW,GY,HT,HN,HK,\n\t\t\tHU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KI,\n\t\t\tKP,KR,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MG,MW,\n\t\t\tMY,MV,ML,MT,MH,MR,MU,MX,FM,MD,MC,MN,MS,MA,MZ,\n\t\t\tMM,NA,NR,NP,NL,NZ,NI,NE,NG,NO,OM,PK,PW,PA,PG,\n\t\t\tPY,PE,PH,PL,PT,QA,RO,RU,RW,KN,LC,VC,WS,SM,ST,\n\t\t\tSA,SN,SC,SL,SG,SK,SI,SB,SO,ZA,ES,LK,SD,SR,SZ,\n\t\t\tSE,CH,SY,TJ,TZ,TH,TG,TO,TT,TN,TR,TM,TV,UG,UA,\n\t\t\tAE,GB,US,UY,UZ,VU,VE,VN,YE,YU,ZM,ZW"; $siteconfig->write(); } $this->extend("afterPopulate"); }
public function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->CategoryID) { $default = ProductCategory::get()->filter(array('Code' => 'DEFAULT'))->first(); $this->CategoryID = $default->ID; } //update many_many lists when multi-group is on if (SiteConfig::current_site_config()->MultiGroup) { $holders = $this->ProductHolders(); $product = ProductPage::get()->byID($this->ID); if (isset($product->ParentID)) { $origParent = $product->ParentID; } else { $origParent = null; } $currentParent = $this->ParentID; if ($origParent != $currentParent) { if ($holders->find('ID', $origParent)) { $holders->removeByID($origParent); } } $holders->add($currentParent); } $title = ltrim($this->Title); $title = rtrim($title); $this->Title = $title; }
/** * Finding the products with different params * * @param unknown $sku * @param unknown $name * @param array $supplierIds * @param array $manufacturerIds * @param array $categoryIds * @param array $statusIds * @param string $active * @param string $pageNo * @param unknown $pageSize * @param unknown $orderBy * @param unknown $stats * * @return Ambigous <Ambigous, multitype:, multitype:BaseEntityAbstract > */ public static function getProducts($sku, $name, array $supplierIds = array(), array $manufacturerIds = array(), array $categoryIds = array(), array $statusIds = array(), $active = null, $pageNo = null, $pageSize = DaoQuery::DEFAUTL_PAGE_SIZE, $orderBy = array(), &$stats = array(), $stockLevel = null, &$sumValues = null, $sh_from = null, $sh_to = null, $sellOnWeb = null) { $where = array(1); $params = array(); if (is_array($sumValues)) { $innerJoins = array(); } if (is_array($sku)) { $skus = array(); $keys = array(); foreach ($sku as $index => $value) { $key = 'sku_' . $index; $keys[] = ':' . $key; $skus[$key] = trim($value); } $where[] = 'pro.sku in (' . implode(',', $keys) . ')'; $params = array_merge($params, $skus); } else { if (($sku = trim($sku)) !== '') { $where[] = 'pro.sku like :sku'; $params['sku'] = '%' . $sku . '%'; } } if (($name = trim($name)) !== '') { $where[] = 'pro.name like :proName'; $params['proName'] = '%' . $name . '%'; } if (($active = trim($active)) !== '') { $where[] = 'pro.active = :active'; $params['active'] = intval($active); } if (($sellOnWeb = trim($sellOnWeb)) !== '') { $where[] = 'pro.sellOnWeb = :sellOnWeb'; $params['sellOnWeb'] = intval($sellOnWeb); } if (count($manufacturerIds) > 0) { $ps = array(); $keys = array(); foreach ($manufacturerIds as $index => $value) { $key = 'manf_' . $index; $keys[] = ':' . $key; $ps[$key] = trim($value); } $where[] = 'pro.manufacturerId in (' . implode(',', $keys) . ')'; $params = array_merge($params, $ps); } if (count($statusIds) > 0) { $ps = array(); $keys = array(); foreach ($statusIds as $index => $value) { $key = 'stId_' . $index; $keys[] = ':' . $key; $ps[$key] = trim($value); } $where[] = 'pro.statusId in (' . implode(',', $keys) . ')'; $params = array_merge($params, $ps); } if (count($supplierIds) > 0) { $ps = array(); $keys = array(); foreach ($supplierIds as $index => $value) { $key = 'spId_' . $index; $keys[] = ':' . $key; $ps[$key] = trim($value); } self::getQuery()->eagerLoad('Product.supplierCodes', 'inner join', 'pro_sup_code', 'pro.id = pro_sup_code.productId and pro_sup_code.supplierId in (' . implode(',', $keys) . ')'); if (is_array($sumValues)) { $innerJoins[] = 'inner join suppliercode pro_sup_code on (pro.id = pro_sup_code.productId and pro_sup_code.supplierId in (' . implode(',', $keys) . '))'; } $params = array_merge($params, $ps); } if (count($categoryIds) > 0) { $ps = array(); $keys = array(); foreach ($categoryIds as $index => $value) { if (($category = ProductCategory::get($value)) instanceof ProductCategory) { $key = 'cateId_' . $index; $keys[] = ':' . $key; $ps[$key] = $category->getId(); $parent_category_ids = array(); foreach ($category->getAllChildrenIds() as $child_category_id) { $key = 'cateId_' . $index . '_' . $child_category_id; $keys[] = ':' . $key; $ps[$key] = $child_category_id; } } } var_dump($ps); self::getQuery()->eagerLoad('Product.categories', 'inner join', 'pro_cate', 'pro.id = pro_cate.productId and pro_cate.categoryId in (' . implode(',', $keys) . ')'); if (is_array($sumValues)) { $innerJoins[] = 'inner join product_category pro_cate on (pro.id = pro_cate.productId and pro_cate.categoryId in (' . implode(',', $keys) . '))'; } $params = array_merge($params, $ps); } if (($stockLevel = trim($stockLevel)) !== '') { $where[] = 'pro.stockOnHand <= pro.' . $stockLevel . ' and pro.' . $stockLevel . ' is not null'; } if (($sh_from = trim($sh_from)) !== '') { $where[] = 'pro.stockOnHand >= :stockOnHand_from'; $params['stockOnHand_from'] = intval($sh_from); } if (($sh_to = trim($sh_to)) !== '') { $where[] = 'pro.stockOnHand <= :stockOnHand_to'; $params['stockOnHand_to'] = intval($sh_to); } $products = Product::getAllByCriteria(implode(' AND ', $where), $params, false, $pageNo, $pageSize, $orderBy, $stats); if (is_array($sumValues)) { $sql = 'select sum(pro.stockOnHand) `totalStockOnHand`, sum(pro.totalOnHandValue) `totalOnHandValue` from product pro ' . implode(' ', $innerJoins) . ' where pro.active = 1 and (' . implode(' AND ', $where) . ')'; $sumResult = Dao::getResultsNative($sql, $params); if (count($sumResult) > 0) { $sumValues['totalStockOnHand'] = $sumResult[0]['totalStockOnHand']; $sumValues['totalOnHandValue'] = $sumResult[0]['totalOnHandValue']; } } return $products; }