protected function processSet(ARSet $set)
 {
     if (isset($this->params['price'])) {
         ProductPrice::loadPricesForRecordSet($set);
     }
     return parent::processSet($set);
 }
 protected static function _getData()
 {
     if (count(self::$_dateRange) === 0) {
         $yesterdayLocal = new UDate('now', 'Australia/Melbourne');
         $yesterdayLocal->modify('-1 day');
         $fromDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 00:00:00', 'Australia/Melbourne');
         $fromDate->setTimeZone('UTC');
         $toDate = new UDate($yesterdayLocal->format('Y-m-d') . ' 23:59:59', 'Australia/Melbourne');
         $toDate->setTimeZone('UTC');
     } else {
         $fromDate = self::$_dateRange['start'];
         $toDate = self::$_dateRange['end'];
     }
     $productPrices = ProductPrice::getAllByCriteria('updated >= :fromDate and updated < :toDate', array('fromDate' => trim($fromDate), 'toDate' => trim($toDate)));
     $return = array();
     foreach ($productPrices as $productPrice) {
         if (!($product = $productPrice->getProduct()) instanceof Product) {
             continue;
         }
         if (!isset($return[trim($product->getSku())])) {
             $return[trim($product->getSku())] = self::_getDefaultData($product);
         }
         if (trim($productPrice->getType()->getId()) === trim(ProductPriceType::ID_RRP)) {
             $return[trim($product->getSku())]['price'] = $productPrice->getPrice();
         } else {
             if (trim($productPrice->getType()->getId()) === trim(ProductPriceType::ID_CASUAL_SPECIAL)) {
                 $return[trim($product->getSku())]['special_price'] = $productPrice->getPrice();
                 $return[trim($product->getSku())]['special_from_date'] = trim($productPrice->getStart());
                 $return[trim($product->getSku())]['special_to_date'] = trim($productPrice->getEnd());
             }
         }
     }
     return $return;
 }
Example #3
0
 protected function postProcessData()
 {
     ProductPrice::loadPricesForRecordSetArray($this->data);
     ProductSpecification::loadSpecificationForRecordSetArray($this->data, true);
     Product::loadCategoryPathsForArray($this->data);
     foreach ($this->data as $key => $product) {
         $this->data[$key]['name_lang_utf8'] = $this->getFixedUtf8($product['name_lang']);
         $this->data[$key]['shortDescription_lang_utf8'] = $this->getFixedUtf8($product['shortDescription_lang']);
         $this->data[$key]['name_lang_safe'] = $this->getSafeEncoding($product['name_lang']);
         $this->data[$key]['shortDescription_lang_safe'] = $this->getSafeEncoding($product['shortDescription_lang']);
     }
 }
Example #4
0
 public function process()
 {
     $this->application->getRouter()->removeAutoAppendVariable('currency');
     if (!$this->response instanceof ActionResponse) {
         return;
     }
     $products = $this->response->get('products');
     $parents = $variations = array();
     foreach ($products as $key => $product) {
         if ($product['parentID']) {
             $parents[$product['parentID']] = true;
             $variations[$key] = $product;
         }
     }
     if (!$parents) {
         return;
     }
     $loadedParents = array();
     foreach (ActiveRecordModel::getRecordSetArray('Product', select(in(f('Product.ID'), array_keys($parents))), array('Manufacturer', 'DefaultImage' => 'ProductImage', 'Category')) as $parent) {
         $loadedParents[$parent['ID']] = $parent;
     }
     ProductSpecification::loadSpecificationForRecordSetArray($loadedParents);
     ProductPrice::loadPricesForRecordSetArray($loadedParents);
     foreach ($products as $key => $product) {
         if ($product['parentID']) {
             $parent = $loadedParents[$product['parentID']];
             foreach ($parent as $field => $value) {
                 if (empty($product[$field])) {
                     $product[$field] = $parent[$field];
                 }
             }
             foreach (array('price_USD', 'price_CAD', 'formattedPrice', 'formattedListPrice') as $field) {
                 if (isset($parent[$field])) {
                     $product[$field] = $parent[$field];
                 }
             }
             ///var_dump($parent);exit;
             $products[$key] = $product;
         }
     }
     ProductSet::loadVariationsForProductArray($variations);
     foreach ($variations as $key => $variation) {
         $vars = array();
         foreach ($variation['variationTypes'] as $type) {
             $vars[] = $type['name_lang'];
         }
         if ($vars) {
             $products[$key]['name_lang'] .= ' (' . implode(' / ', $vars) . ')';
         }
     }
     $this->response->set('products', $products);
 }
 /**
  * This function generates the ProductData for a product to be used for inser/update of product on Magento
  * @param Product $product
  * @param unknown $linkedCategories
  * @return multitype:string number unknown multitype:number
  */
 private function _generateProductData(Product $product, array $linkedCategories)
 {
     $productDescription = '';
     $productDescAssetId = trim($product->getFullDescAssetId());
     if ($productDescAssetId !== '') {
         $asset = Asset::getAsset($productDescAssetId);
         if ($asset instanceof Asset && ($assetPath = trim($asset->getPath())) !== '') {
             $productDescription = Asset::readAssetFile($assetPath);
         }
     }
     $price = '0';
     $productPrices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
     if (count($productPrices) > 0) {
         $price = $productPrices[0]->getPrice();
     }
     $urlKey = strtolower(str_replace(' ', '-', trim($product->getName())));
     return array('categories' => $linkedCategories, 'websites' => array(1), 'name' => trim($product->getName()), 'description' => $productDescription, 'short_description' => trim($product->getShortDescription()), 'weight' => method_exists($product, 'getWeight') ? trim($product->getWeight()) : '1', 'status' => trim($product->getStatus()), 'url_key' => $urlKey, 'url_path' => $urlKey, 'visibility' => '4', 'price' => $price, 'tax_class_id' => 1, 'meta_title' => trim($product->getName()), 'meta_keyword' => trim($product->getSku()), 'meta_description' => trim($product->getShortDescription()));
 }
Example #6
0
 function actionProductPriceSave()
 {
     $this->checkLogin();
     if (!empty($_POST)) {
         $product_code = Util::input($_POST['product_code']);
         $product_prices = str_replace(",", "", Util::input($_POST['product_price']));
         $product_price_sends = str_replace(",", "", Util::input($_POST['product_price_send']));
         $qtys = Util::input($_POST['qty']);
         $qty_ends = Util::input($_POST['qty_end']);
         $i = 0;
         ProductPrice::model()->deleteAllByAttributes(array("product_barcode" => $product_code));
         foreach ($product_prices as $product_price) {
             $price = $product_price;
             $price_send = $product_price_sends[$i];
             $qty = $qtys[$i];
             $qty_end = $qty_ends[$i];
             if ($qty > 0 && $price > 0) {
                 $productPrice = new ProductPrice();
                 $productPrice->product_barcode = $product_code;
                 $productPrice->price = $price;
                 $productPrice->price_send = $price_send;
                 $productPrice->qty = $qty;
                 $productPrice->qty_end = $qty_end;
                 $productPrice->order_field = $i + 1;
                 $productPrice->save();
             }
             $i++;
         }
         echo 'success';
     }
 }
Example #7
0
    {
        echo 'Product Price = ' . $price . '<br>';
        echo 'discount rate = ' . $discount . '%<br>';
        $discount = $price * ($discount / 100);
        $price = $price - $discount;
        echo 'After Discount  = $' . $price . '<br>';
    }
}
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <?php 
$john = new Profile('John Doe', 'Web Developer', 'Male', '23');
$mamun = new Profile('Mamun Hossain', 'Front End Developer', 'Male', '30');
?>

    <h2>Price in Discount</h2>
    <?php 
$price = new ProductPrice();
$price->price(100, 10);
?>


</body>
</html>
Example #8
0
 /**
  * (non-PHPdoc)
  * @see BaseEntityAbstract::preSave()
  */
 public function preSave()
 {
     if ($this->getStart()->afterOrEqualTo($this->getEnd())) {
         throw new EntityException('Error: Price(ID=' . $this->getId() . ') start(=' . $this->getStart() . ') must be earlier than end(=' . $this->getEnd() . ')!');
     }
     $where = 'active = 1 AND productId = :pId AND typeId = :typeId AND ( (start <= :start and :end <= end) or (:start <= start and :end <= end) or (start <= :start and end <= :end) or (:start <= start and end <= :end))';
     $params = array('pId' => $this->getProduct()->getId(), 'typeId' => $this->getType()->getId(), 'start' => trim($this->getStart()), 'end' => trim($this->getEnd()));
     if (($id = trim($this->getId())) !== '') {
         $where .= ' AND id != :id';
         $params['id'] = $id;
     }
     if (ProductPrice::countByCriteria($where, $params) > 0) {
         throw new EntityException('There is already a price for this product that covers time from "' . $this->getStart() . '" to "' . $this->getEnd() . '"');
     }
 }
Example #9
0
 /**
  * Getting price matching information
  *
  * @param unknown $sender
  * @param unknown $param
  */
 public function priceMatching($sender, $param)
 {
     $results = $errors = array();
     try {
         $id = isset($param->CallbackParameter->id) ? $param->CallbackParameter->id : '';
         $product = Product::get($id);
         $prices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
         $companies = PriceMatcher::getAllCompaniesForPriceMatching();
         $prices = PriceMatcher::getPrices($companies, $product->getSku(), count($prices) === 0 ? 0 : $prices[0]->getPrice());
         $myPrice = $prices['myPrice'];
         $minPrice = $prices['minPrice'];
         $msyPrice = $prices['companyPrices']['MSY'];
         $prices['id'] = $id;
         $results = $prices;
     } catch (Exception $ex) {
         $errors[] = $ex->getMessage();
     }
     $param->ResponseData = StringUtilsAbstract::getJson($results, $errors);
 }
Example #10
0
 private function getComparedProducts()
 {
     $filter = Category::getRootNode()->getProductFilter(select(IN('Product.ID', $this->getComparedProductIDs())));
     $products = ActiveRecord::getRecordSetArray('Product', $filter, array('Category', 'ProductImage'));
     ProductSpecification::loadSpecificationForRecordSetArray($products, true);
     ProductPrice::loadPricesForRecordSetArray($products);
     return $products;
 }
Example #11
0
 protected function processDataArray($productArray, $displayedColumns)
 {
     // load price data
     ProductPrice::loadPricesForRecordSetArray($productArray, false);
     // load child products
     //		if (isset($displayedColumns['Product.parentID']))
     //{
     ProductSet::loadVariationTypesForProductArray($productArray);
     ProductSet::loadChildrenForProductArray($productArray);
     //}
     ProductSpecification::loadSpecificationForRecordSetArray($productArray, true);
     foreach ($productArray as &$product) {
         if (!empty($product['children'])) {
             foreach ($product['children'] as &$child) {
                 if (!empty($product['attributes'])) {
                     $child['attributes'] = $product['attributes'];
                 }
                 if (!empty($product['Manufacturer'])) {
                     $child['Manufacturer'] = $product['Manufacturer'];
                 }
                 foreach (array('definedPrices', 'definedListPrices', 'price_USD', 'price_CAD', 'listPrice_USD', 'listPrice_CAD') as $key) {
                     if (!empty($product[$key])) {
                         $child[$key] = $product[$key];
                     }
                 }
                 foreach ($child as $key => $value) {
                     if (empty($value) && !empty($product[$key])) {
                         $child[$key] = $product[$key];
                     }
                 }
                 $variation = null;
                 if (!empty($child['variationValues'])) {
                     $variation = array_shift($child['variationValues']);
                 }
                 $name = $child['name'];
                 $child['URL'] = $product['URL'];
                 $child['name_lang'] = $name . ' ' . $child['sku'];
                 $child['xParent'] = $child['Parent'];
                 unset($child['Parent']);
                 $child['URL'] = $this->router->createFullUrl(createProductUrl(array('product' => $child), $this->application));
                 $child['Parent'] = $child['xParent'];
                 $child['name'] = $name;
                 if ($variation) {
                     $child['name'] .= ' (' . $variation . ')';
                     $child['name_lang'] = $child['name'];
                 }
                 $child['id'] = $child['ID'];
             }
             $product['URL'] = $this->router->createFullUrl(createProductUrl(array('product' => $product), $this->application));
             if (empty($product['ProductImage']['ID'])) {
                 if (!empty($product['children'][0]['ProductImage'])) {
                     $product['ProductImage'] = $product['children'][0]['ProductImage'];
                     $product['DefaultImage'] = $product['children'][0]['DefaultImage'];
                 }
             }
         }
         $product['id'] = $product['ID'];
     }
     $defCurrency = $this->application->getDefaultCurrencyCode();
     foreach ($productArray as &$product) {
         foreach ($this->getUserGroups() as $groupID => $groupName) {
             if (isset($product['priceRules'][$defCurrency][1][$groupID])) {
                 $product['GroupPrice'][$groupID] = $product['priceRules'][$defCurrency][1][$groupID];
             }
         }
     }
     return $productArray;
 }
Example #12
0
 public function actionSale()
 {
     if (!empty($_POST)) {
         $product_name;
         $qty_sub_stock;
         $old_price;
         // find product
         $product = Product::model()->findByAttributes(array('product_code' => Util::input($_POST['product_code'])));
         // not found find from barcode_price
         if (empty($product)) {
             $barcodePrice = BarcodePrice::model()->findByAttributes(array('barcode' => Util::input($_POST['product_code'])));
             if (!empty($barcodePrice)) {
                 $product = $barcodePrice->getProduct();
                 $product_name = $product->product_name . " ( {$barcodePrice->name} )";
                 $qty_sub_stock = $barcodePrice->qty_sub_stock;
                 $old_price = $barcodePrice->price_before;
             }
         } else {
             $product_name = $product->product_name;
             $qty_sub_stock = $product->product_total_per_pack;
         }
         // found product
         if (!empty($product)) {
             // find price
             $price = $product->product_price;
             $old_price = $product->product_price_buy;
             // find default price and send price
             $sale_condition = Util::input($_POST['sale_condition']);
             if ($sale_condition == 'one') {
                 // ขายปลีก
                 $price = $product->product_price;
             } else {
                 // ขายส่ง
                 $price = $product->product_price_send;
             }
             // find by barcode price
             $barcodePrice = BarcodePrice::model()->findByAttributes(array('barcode' => Util::input($_POST['product_code'])));
             if (!empty($barcodePrice)) {
                 $price = $barcodePrice->price;
                 $old_price = $barcodePrice->price_before;
                 $product_name = $product->product_name . " ( {$barcodePrice->name} )";
                 $qty_sub_stock = $barcodePrice->qty_sub_stock;
             }
             // find between price
             $productPrice = ProductPrice::model()->find(array('condition' => '
         product_barcode = :product_barcode
         AND 
         (qty <= :qty AND :qty <= qty_end)
       ', 'params' => array('qty' => (int) Util::input($_POST['qty']), 'product_barcode' => Util::input($_POST['product_code']))));
             if (!empty($productPrice)) {
                 if ($sale_condition == 'one') {
                     $price = $productPrice->price;
                 } else {
                     $price = $productPrice->price_send;
                 }
             }
             // find qty_sub_stock
             $qty_sub_stock = $product->product_total_per_pack;
             if (!empty($barcodePrice)) {
                 $qty_sub_stock = $barcodePrice->qty_sub_stock;
             }
             // default qty_sub_stock
             if ($qty_sub_stock == 0) {
                 $qty_sub_stock = 1;
             }
             // check condition
             $configSoftware = ConfigSoftware::model()->find();
             $is_sale = false;
             if ($configSoftware->sale_out_of_stock == 'yes') {
                 $is_sale = true;
             } else {
                 if ($product->product_quantity > 0) {
                     $is_sale = true;
                 }
             }
             if ($is_sale) {
                 // save to temp
                 $saleTemp = new SaleTemp();
                 $saleTemp->barcode = Util::input($_POST['product_code']);
                 $saleTemp->name = $product_name;
                 $saleTemp->serial = Util::input($_POST['serial']);
                 $saleTemp->price = str_replace(',', '', $price);
                 $saleTemp->qty = str_replace(',', '', $_POST['qty']);
                 $saleTemp->qty_per_pack = $qty_sub_stock;
                 $saleTemp->user_id = Yii::app()->request->cookies['user_id']->value;
                 $saleTemp->branch_id = (int) Util::input($_POST['branch_id']);
                 $saleTemp->pk_temp = rand(1, 99999);
                 $saleTemp->created_at = new CDbExpression('NOW()');
                 $saleTemp->old_price = $old_price;
                 // save and update stock
                 if ($saleTemp->save()) {
                     Yii::app()->session['branch_id'] = (int) Util::input($_POST['branch_id']);
                     echo 'success';
                 }
             } else {
                 echo Yii::t("lang", "product_out_of_stock");
             }
         }
     }
 }
Example #13
0
 public function unserialize($serialized)
 {
     parent::unserialize($serialized);
     // load products
     $productIds = array();
     foreach ($this->orderedItems as $item) {
         $productIds[] = $item->getProduct()->getID();
     }
     $products = ActiveRecordModel::getInstanceArray('Product', $productIds, Product::LOAD_REFERENCES);
     // load product prices
     $set = new ARSet();
     foreach ($products as $product) {
         $set->add($product);
     }
     ProductPrice::loadPricesForRecordSet($set);
 }
Example #14
0
 /**
  * Convert current product prices to array
  *
  * @param string $part Which part of array prices you want to get ('defined', 'calculated' or 'both')
  */
 public function toArray($part = null, $listPrice = false)
 {
     if (!in_array($part, array('defined', 'calculated', 'both'))) {
         $part = 'both';
     }
     $field = $listPrice ? 'listPrice' : 'price';
     $ruleController = $this->application->getBusinessRuleController();
     $defined = array();
     foreach ($this->prices as $inst) {
         $defPrice = $inst->{$field}->get();
         $curr = $inst->currency->get()->getID();
         if ('price' == $field) {
             $defined[$curr] = $inst->getPriceByGroup($ruleController->getContext()->getUserGroupID());
             if ($defined[$curr] != $defPrice) {
                 $this->setListPrice($curr, $defPrice);
             }
         } else {
             $defined[$curr] = $defPrice;
         }
     }
     if ($listPrice) {
         $defined = array_merge($defined, $this->listPrices);
     }
     $baseCurrency = $this->application->getDefaultCurrencyCode();
     $basePrice = isset($defined[$baseCurrency]) ? $defined[$baseCurrency] : 0;
     $formattedPrice = $calculated = array();
     $parent = $this->product->parent->get();
     $setting = $this->product->getChildSetting('price');
     foreach ($this->application->getCurrencySet() as $id => $currency) {
         if (!empty($defined[$id])) {
             $calculated[$id] = $defined[$id];
         } else {
             $calculated[$id] = ProductPrice::calculatePrice($this->product, $currency, $basePrice);
         }
         if (!$calculated[$id] && $listPrice) {
             continue;
         }
         if ($parent && ($setting != Product::CHILD_OVERRIDE || !$calculated[$id])) {
             $parentPrice = $parent->getPrice($id);
             $calculated[$id] += $parentPrice * ($setting != Product::CHILD_ADD ? 1 : -1);
         }
         if (!$listPrice) {
             $calculated[$id] = $this->application->getDisplayTaxPrice($calculated[$id], $this->product);
             $discountedPrice = $ruleController->getProductPrice($this->product, $calculated[$id], $currency->getID());
             if ($discountedPrice != $calculated[$id]) {
                 $this->setListPrice($currency->getID(), $calculated[$id]);
                 $calculated[$id] = $discountedPrice;
             }
         }
         if ((double) $calculated[$id] || !$listPrice) {
             $formattedPrice[$id] = $currency->getFormattedPrice($calculated[$id]);
         }
     }
     $return = array('defined' => $defined, 'calculated' => $calculated, 'formattedPrice' => $formattedPrice);
     return 'both' == $part ? $return : $return[$part];
 }
Example #15
0
            <?php echo $form->textFieldGroup($model, 'sku', array('widgetOptions' => array('htmlOptions' => array('class' => 'span5', 'maxlength' => 128)))); ?>
        </div>
    </div>
    <div class="form-actions">
        <?php
        $this->widget('booster.widgets.TbButton', array(
            'buttonType' => 'submit',
            'context' => 'primary',
            'label' => 'Search',
        ));
        ?>
    </div>
    <?php $this->endWidget(); ?>
<?php endif; ?>
<?php
$model = new ProductPrice();
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $model->StockReport(),
    'id' => 'stockreport-grid',
    'columns' => array(
        array(
            'header' => 'CODE',
            'value' => 'strip_tags($data[\'CODE\'])',
            'type' => 'raw',
            'name' => 'CODE',
            'htmlOptions'=>array('width'=>'200'),
        ),
        array(
            'header' => 'SKU',
            'value' => 'strip_tags($data[\'SKU\'])',
            'type' => 'raw',
Example #16
0
 public function getPriceDiff($currencyCode, $basePrice = false)
 {
     $basePrice = false === $basePrice ? $this->priceDiff->get() : $basePrice;
     return ProductPrice::convertPrice(Currency::getInstanceByID($currencyCode), $basePrice);
 }
Example #17
0
 /**
  * getting the data
  *
  * @param string $preFix
  * @param string $debug
  *
  * @return array
  */
 private static function _getData(UDate $lastUpdatedTime, $preFix = '', $debug = false)
 {
     self::_log('== Trying to get all the updated price for products:', __CLASS__ . '::' . __FUNCTION__, $preFix);
     //product prices
     $productPrices = ProductPrice::getAllByCriteria('updated > ?', array(trim($lastUpdatedTime)));
     self::_log('GOT ' . count($productPrices) . ' Price(s) that has changed after "' . trim($lastUpdatedTime) . '".', '', $preFix);
     $products = array();
     foreach ($productPrices as $productPrice) {
         if (!$productPrice->getProduct() instanceof Product || array_key_exists($productPrice->getProduct()->getId(), $products)) {
             continue;
         }
         $products[$productPrice->getProduct()->getId()] = $productPrice->getProduct();
     }
     //products
     $productArr = Product::getAllByCriteria('updated > ?', array(trim($lastUpdatedTime)), true);
     self::_log('GOT ' . count($productArr) . ' Product(s) that has changed after "' . trim($lastUpdatedTime) . '".', '', $preFix);
     foreach ($productArr as $product) {
         if (array_key_exists($product->getId(), $products)) {
             continue;
         }
         $products[$product->getId()] = $product;
     }
     //Product_Category
     $productCates = Product_Category::getAllByCriteria('updated > ?', array(trim($lastUpdatedTime)));
     self::_log('GOT ' . count($productCates) . ' Product_Category(s) that has changed after "' . trim($lastUpdatedTime) . '".', '', $preFix);
     foreach ($productCates as $productCate) {
         if (!$productCate->getProduct() instanceof Product || array_key_exists($productCate->getProduct()->getId(), $products)) {
             continue;
         }
         $products[$productCate->getProduct()->getId()] = $productCate->getProduct();
     }
     //ProductImage
     $productImages = ProductImage::getAllByCriteria('updated > ? and active = 1', array(trim($lastUpdatedTime)));
     self::_log('GOT ' . count($productCates) . ' ProductImage(s) that has changed after "' . trim($lastUpdatedTime) . '".', '', $preFix);
     foreach ($productImages as $productImage) {
         if (!$productImage->getProduct() instanceof Product || array_key_exists($productImage->getProduct()->getId(), $products)) {
             continue;
         }
         $products[$productCate->getProduct()->getId()] = $productCate->getProduct();
     }
     return $products;
 }
Example #18
0
?>
</th>
        </tr>
      </thead>
      <tbody>

      <?php 
if (!empty($_GET['id'])) {
    ?>

      <?php 
    $id = $_GET['id'];
    $product = Product::model()->findByPk($id);
    $productPrices = null;
    if (!empty($product)) {
        $productPrices = ProductPrice::model()->findAll(array('condition' => 'product_barcode = :product_barcode', 'params' => array('product_barcode' => $product->product_code), 'order' => 'order_field ASC'));
        $n = 1;
    }
    ?>
        <!-- Update Record -->
        <?php 
    if (!empty($productPrices)) {
        ?>
        <?php 
        foreach ($productPrices as $productPrice) {
            ?>
        <tr>
          <td><?php 
            echo $n++;
            ?>
</td>
Example #19
0
 protected function processDataArray($productArray, $displayedColumns)
 {
     // load specification data
     foreach ($displayedColumns as $column => $type) {
         list($class, $field) = explode('.', $column, 2);
         if ('specField' == $class) {
             ProductSpecification::loadSpecificationForRecordSetArray($productArray, true);
             break;
         }
     }
     // load price data
     ProductPrice::loadPricesForRecordSetArray($productArray, false);
     // load child products
     if (isset($displayedColumns['Product.parentID'])) {
         ProductSet::loadVariationTypesForProductArray($productArray);
         ProductSet::loadChildrenForProductArray($productArray);
     }
     $defCurrency = $this->application->getDefaultCurrencyCode();
     foreach ($productArray as &$product) {
         foreach ($this->getUserGroups() as $groupID => $groupName) {
             if (isset($product['priceRules'][$defCurrency][1][$groupID])) {
                 $product['GroupPrice'][$groupID] = $product['priceRules'][$defCurrency][1][$groupID];
             }
         }
     }
     return $productArray;
 }
Example #20
0
 public static function getTotalBundlePrice(Product $product, Currency $currency)
 {
     $products = new ARSet();
     $bundle = self::getBundledProductSet($product);
     foreach ($bundle as $item) {
         $products->add($item->relatedProduct->get());
     }
     ProductPrice::loadPricesForRecordSet($products);
     $total = 0;
     foreach ($bundle as $item) {
         $itemTotal = $item->relatedProduct->get()->getPrice($currency) * $item->getCount();
         $total += $itemTotal;
     }
     return $total;
 }
Example #21
0
 private function getRelatedProducts(Product $product, $type = 0)
 {
     // get related products
     $related = $product->getRelatedProductsWithGroupsArray($type);
     $rel = array();
     foreach ($related as $r) {
         if (!isset($r['RelatedProduct'])) {
             continue;
         }
         $p = $r['RelatedProduct'];
         // @todo: make ActiveRecord automatically recognize the correct parent object
         $p['DefaultImage'] = $r['DefaultImage'];
         if (isset($r['ProductRelationshipGroup'])) {
             $p['ProductRelationshipGroup'] = $r['ProductRelationshipGroup'];
         }
         $rel[] = $p;
     }
     ProductPrice::loadPricesForRecordSetArray($rel);
     // sort related products into groups
     $byGroup = array();
     foreach ($rel as $r) {
         $groupID = isset($r['ProductRelationshipGroup']) ? $r['ProductRelationshipGroup']['ID'] : 0;
         $byGroup[$groupID][] = $r;
     }
     return $byGroup;
 }
Example #22
0
 /**
  * Create a basic product sale element attached to this product.
  */
 public function createProductSaleElement(ConnectionInterface $con, $weight, $basePrice, $salePrice, $currencyId, $isDefault, $isPromo = false, $isNew = false, $quantity = 0, $eanCode = '', $ref = false)
 {
     // Create an empty product sale element
     $saleElements = new ProductSaleElements();
     $saleElements->setProduct($this)->setRef($ref == false ? $this->getRef() : $ref)->setPromo($isPromo)->setNewness($isNew)->setWeight($weight)->setIsDefault($isDefault)->setEanCode($eanCode)->setQuantity($quantity)->save($con);
     // Create an empty product price in the provided currency
     $productPrice = new ProductPrice();
     $productPrice->setProductSaleElements($saleElements)->setPromoPrice($salePrice)->setPrice($basePrice)->setCurrencyId($currencyId)->setFromDefaultCurrency(false)->save($con);
     return $saleElements;
 }
 private function _getNewPrice($updateMagento)
 {
     $result = null;
     $sku = $this->sku;
     $updateMagento = $updateMagento === true ? true : false;
     $product = Product::getBySku($sku);
     if (!$product instanceof Product) {
         throw new Exception('Invalid sku passed in, "' . $sku . '" given');
     }
     $min = PriceMatchMin::getBySku($sku);
     $rule = ProductPriceMatchRule::getByProduct($product);
     $prices = ProductPrice::getPrices($product, ProductPriceType::get(ProductPriceType::ID_RRP));
     if (count($prices) === 0) {
         $newPrice = ProductPrice::create($product, ProductPriceType::get(ProductPriceType::ID_RRP), 0);
         $prices = array($newPrice);
     }
     // 		if(($magePrice = $this->_getMagentoProductPrice($sku)) !== null)
     // 			$prices[0]->setPrice($magePrice)->save();
     $myPrice = $prices[0]->getPrice();
     if (!$min instanceof PriceMatchMin) {
         $min = PriceMatchMin::create($this->sku);
     }
     if ($rule instanceof ProductPriceMatchRule) {
         $company = $rule->getCompany();
         $price_from = $rule->getPrice_from();
         $price_to = $rule->getPrice_to();
         $offset = $rule->getOffset();
         $where = array(1);
         $params = array();
         $where[] = "minId = ? ";
         $params[] = $min->getId();
         $from_date = UDate::now('Australia/Melbourne')->setTime(0, 0, 0)->setTimeZone('UTC');
         $to_date = UDate::now('Australia/Melbourne')->setTime(23, 59, 59)->setTimeZone('UTC');
         $where[] = "created >= ? ";
         $params[] = $from_date;
         $where[] = "created <= ? ";
         $params[] = $to_date;
         $companies = $company->getAllAlias();
         $companyIds = array_map(create_function('$a', 'return $a->getId();'), $companies);
         $where[] = 'companyId IN (' . implode(", ", array_fill(0, count($companyIds), "?")) . ')';
         $params = array_merge($params, $companyIds);
         //calculate target compatitor price
         $records = PriceMatchRecord::getAllByCriteria(implode(' AND ', $where), $params, true, null, DaoQuery::DEFAUTL_PAGE_SIZE, array('price' => 'asc'));
         $base_price = null;
         foreach ($records as $record) {
             if ($base_price === null || doubleval($record->getPrice()) !== doubleval(0) && doubleval($record->getPrice()) < doubleval($base_price)) {
                 $base_price = doubleval($record->getPrice());
             }
         }
         if ($base_price !== null) {
             if ($price_from !== null) {
                 if (strpos($price_from, '%') !== false) {
                     $price_from = $base_price - $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_from)));
                 } else {
                     $price_from = $base_price - doubleval($price_from);
                 }
                 if (doubleval($price_from) <= doubleval(0)) {
                     $price_from = doubleval(0);
                 }
             }
             if ($price_to !== null) {
                 if (strpos($price_to, '%') !== false) {
                     $price_to = $base_price + $base_price * doubleval(0.01 * doubleval(str_replace('%', '', $price_to)));
                 } else {
                     $price_to = $base_price + doubleval($price_to);
                 }
             }
             // check if in range
             if (($price_from === null || $myPrice >= $price_from) && ($price_to === null || $myPrice <= $price_to)) {
                 $result = $base_price;
                 // apply offset
                 if ($offset !== null) {
                     if (strpos($offset, '%') !== false) {
                         $result = $result + $result * doubleval(0.01 * doubleval(str_replace('%', '', $offset)));
                     } else {
                         $result = $result + doubleval($offset);
                     }
                 }
                 // set product price
                 if (isset($prices[0]) && $prices[0] instanceof ProductPrice) {
                     $newmatchprice = doubleval($result);
                     if ($newmatchprice > 0) {
                         $oldPrice = $prices[0]->getPrice();
                         echo 'update price from old price : ' . $oldPrice . ' to new price :' . $newmatchprice . "\n";
                         $prices[0]->setPrice(doubleval($result))->save()->addLog('PriceMatch change price from $' . $oldPrice . 'to new price $' . $result, Log::TYPE_SYSTEM);
                         // 						if($updateMagento === true)
                         // 							$this->updateMagentoPrice(doubleval($result));
                     } else {
                         echo 'not update price because new match price is 0 ( ' . $newmatchprice . ' )' . "\n";
                     }
                 }
             }
         } else {
             if ($this->debug === true) {
                 echo "cannot find price for PriceMatchCompany " . $company->getCompanyName() . ', ' . $product->getSku() . '(id=' . $product->getId() . ', min(id=' . $min->getId() . '), records found:' . count($records) . "\n";
             }
         }
         if ($this->debug === true) {
             echo 'new price= ' . ($result === null ? 'N/A' : $result) . ', my price= ' . (isset($myPrice) ? $myPrice : 'N/A') . ', ' . $company->getCompanyName() . ' price= ' . $base_price . ', matching range=[' . $price_from . ',' . $price_to . '], offset=' . ($offset === null ? 'null' : $offset) . "\n";
         }
     } elseif ($this->debug === true) {
         echo ($min instanceof PriceMatchMin ? '' : 'Cannot find result on StaticIce for all known PriceMatchCompanies') . ($rule instanceof ProductPriceMatchRule ? '' : 'cannot find ProductPriceMatchRule for product ' . $product->getSku() . '(id=' . $product->getId() . ')') . "\n";
     }
     return $result;
 }
Example #24
0
 public function actionSale()
 {
     $this->checkLogin();
     $model = new BillSale();
     if (!empty($_POST)) {
         Yii::app()->session['sessionBillSale'] = $_POST;
         // BILL SALE DETAIL
         $arrayBillSaleDetail = Yii::app()->session['billSaleDetail'];
         if (empty($arrayBillSaleDetail)) {
             $arrayBillSaleDetail = array();
         }
         $size = count($arrayBillSaleDetail);
         // ADD bill_sale_detail ITEMS
         $productCode = Util::input($_POST['product_code']);
         $productQty = Util::input($_POST['product_qty']);
         $code = "";
         $price = 0;
         $qty_per_pack = 0;
         $product = Product::model()->findByAttributes(array('product_code' => $productCode));
         $sale_condition = Util::input($_POST['sale_condition']);
         if (empty($product)) {
             $product = Product::model()->findByAttributes(array('product_pack_barcode' => $productCode));
             if (!empty($product)) {
                 $code = $product->product_pack_barcode;
                 $price = $product->product_price_per_pack;
                 $qty_per_pack = $product->product_total_per_pack;
             }
         } else {
             // FIND PRICE OF PRODUCT
             if ($sale_condition == 'many') {
                 // กรณีขายส่ง
                 $price = $product->product_price_send;
                 // ค้นหาราคา ที่กำหนดไว้ใน product_prices
                 $productPrice = ProductPrice::model()->find(array("condition" => "\n              product_barcode = :productCode\n              AND (qty <= :productQty AND qty_end >= :productQty)\n            ", "params" => array("productCode" => $productCode, "productQty" => $productQty)));
                 if (!empty($productPrice)) {
                     $price = $productPrice->price_send;
                 }
             } else {
                 // กรณีขายปลีก
                 $price = $product->product_price;
                 // ค้นหาราคา ที่กำหนดไว้ใน product_prices
                 $productPrice = ProductPrice::model()->find(array("condition" => "\n              product_barcode = :productCode\n              AND (qty <= :productQty AND qty_end >= :productQty)\n            ", "params" => array("productCode" => $productCode, "productQty" => $productQty)));
                 if (!empty($productPrice)) {
                     $price = $productPrice->price;
                 }
             }
             $code = $product->product_code;
             $qty_per_pack = 1;
         }
         // หาราคา ตามตาราง barcode_prices
         $barcodePrice = BarcodePrice::model()->findByAttributes(array('barcode' => $productCode));
         if (!empty($barcodePrice)) {
             $price = $barcodePrice->price;
             $product = $barcodePrice->getProduct();
             $qty_per_pack = $barcodePrice->qty_sub_stock;
             $product->product_name = $product->product_name . ' ( ' . $barcodePrice->name . ' )';
         }
         // FOUND PRODUCT
         if (!empty($product)) {
             if (!empty($_POST['hidden_product_codes'])) {
                 // second item
                 $hidden_product_codes = Util::input($_POST['hidden_product_codes']);
                 $hidden_product_name = Util::input($_POST['hidden_product_name']);
                 $hidden_qty_per_pack = Util::input($_POST['hidden_qty_per_pack']);
                 $serials = Util::input($_POST['serials']);
                 $prices = Util::input($_POST['prices']);
                 $qtys = Util::input($_POST['qtys']);
                 $arr = array();
                 // old item
                 for ($i = 0; $i < count($hidden_product_codes); $i++) {
                     $arr[] = array('product_qty' => $qtys[$i], 'product_code' => $hidden_product_codes[$i], 'product_name' => $hidden_product_name[$i], 'product_price' => $prices[$i], 'product_serial_no' => $serials[$i], 'product_expire_date' => Util::input($_POST['product_expire_date']), 'product_qty_per_pack' => $hidden_qty_per_pack[$i], 'sale_status' => Util::input($_POST['sale_status']), 'sale_condition' => Util::input($_POST['sale_condition']), 'has_bonus' => 'normal', 'bill_sale_created_date' => Util::input($_POST['BillSale']['bill_sale_created_date']));
                 }
                 // add item
                 $arr[] = array('product_qty' => Util::input($_POST['product_qty']), 'product_code' => Util::input($_POST['product_code']), 'product_name' => $product->product_name, 'product_price' => $price, 'product_serial_no' => Util::input($_POST['product_serial_no']), 'product_expire_date' => Util::input($_POST['product_expire_date']), 'product_qty_per_pack' => $qty_per_pack, 'sale_status' => Util::input($_POST['sale_status']), 'sale_condition' => Util::input($_POST['sale_condition']), 'has_bonus' => 'normal', 'bill_sale_created_date' => Util::input($_POST['BillSale']['bill_sale_created_date']));
             } else {
                 // add item
                 $arr[] = array('product_qty' => Util::input($_POST['product_qty']), 'product_code' => Util::input($_POST['product_code']), 'product_name' => $product->product_name, 'product_price' => $price, 'product_serial_no' => Util::input($_POST['product_serial_no']), 'product_expire_date' => Util::input($_POST['product_expire_date']), 'product_qty_per_pack' => $qty_per_pack, 'sale_status' => Util::input($_POST['sale_status']), 'sale_condition' => Util::input($_POST['sale_condition']), 'has_bonus' => 'normal', 'bill_sale_created_date' => Util::input($_POST['BillSale']['bill_sale_created_date']));
             }
             Yii::app()->session['billSaleDetail'] = $arr;
             Yii::app()->session['billSaleCreatedDate'] = Util::input($_POST['BillSale']['bill_sale_created_date']);
             $this->redirect(array('Sale'));
         }
     }
     // RENDER
     $this->render('//Basic/Sale', array('model' => $model));
 }
Example #25
0
 public function bestsellingProductsBlock()
 {
     ClassLoader::import('application.model.product.ProductFilter');
     $cache = $this->application->getCache();
     $key = array('bestsellers', $this->getCategory()->getID() . '_' . $days);
     if (!$cache->get($key)) {
         $category = $this->getCategory();
         $filter = new ProductFilter($category, new ARSelectFilter());
         $filter->includeSubcategories();
         $filter->setEnabledOnly();
         $selectFilter = $filter->getSelectFilter();
         $selectFilter->setLimit($this->config->get('BESTSELLING_ITEMS_COUNT'));
         $selectFilter->setOrder(new ARExpressionHandle('cnt'), 'DESC');
         $q = new ARSelectQueryBuilder();
         $q->includeTable('Product');
         $q->joinTable('Category', 'Product', 'ID', 'categoryID');
         $q->addField('Product.ID');
         $q->addField(new ARExpressionHandle('(SELECT SUM(count) FROM OrderedItem LEFT JOIN CustomerOrder ON OrderedItem.customerOrderID=CustomerOrder.ID WHERE productID=Product.ID AND CustomerOrder.isPaid=1 AND CustomerOrder.dateCompleted > "' . ARSerializableDateTime::createFromTimeStamp(strtotime('-' . $this->config->get('BESTSELLING_ITEMS_DAYS') . ' days')) . '")'), null, 'cnt');
         $q->setFilter($selectFilter);
         $cache->set($key, ActiveRecord::getDataByQuery($q));
     }
     $products = $cache->get($key);
     if (!$products) {
         return;
     }
     $ids = array();
     foreach ($products as $id) {
         $ids[] = $id['ID'];
     }
     $products = ActiveRecord::getRecordSetArray('Product', select(IN('Product.ID', $ids)), array('DefaultImage' => 'ProductImage'));
     ProductPrice::loadPricesForRecordSetArray($products);
     if ($products) {
         return new BlockResponse('products', $products);
     }
 }
Example #26
0
 private function getFeaturedMainCategoryProducts(&$categories)
 {
     $cache = $this->application->getCache();
     $namespace = 'category_featured';
     $products = array();
     foreach ((array) $categories as $category) {
         $key = array($namespace, $category['ID']);
         if ($product = $cache->get($key)) {
             $products[] = $product;
             continue;
         }
         $cat = Category::getInstanceByID($category['ID'], Category::LOAD_DATA);
         $pf = new ProductFilter($cat, new ARSelectFilter());
         $pf->includeSubcategories();
         $f = $cat->getProductsFilter($pf);
         $f->mergeCondition(new EqualsCond(new ARFieldHandle('Product', 'isFeatured'), true));
         $f->setLimit(1);
         $f->setOrder(new ARExpressionHandle('RAND()'));
         $product = array_pop(ActiveRecordModel::getRecordSetArray('Product', $f, array('ProductImage', 'Category', 'Manufacturer')));
         if (!$product) {
             $product = array('ID' => 0);
         }
         $cache->set($key, $product, 1800);
         $products[] = $product;
     }
     ProductPrice::loadPricesForRecordSetArray($products);
     foreach ($products as $key => $product) {
         $categories[$key]['featuredProduct'] = $product;
     }
 }
 public function toArray($currencyID = null)
 {
     $array = parent::toArray();
     $rs = ProductPrice::getRecurringProductPeriodPrices($this, $currencyID);
     $currencies = array();
     if ($rs && $rs->size()) {
         $mapping = array(ProductPrice::TYPE_PERIOD_PRICE => 'ProductPrice_period', ProductPrice::TYPE_SETUP_PRICE => 'ProductPrice_setup');
         while (false != ($item = $rs->shift())) {
             $itemArray = $item->toArray();
             if ($itemArray['type'] == ProductPrice::TYPE_SETUP_PRICE || $itemArray['type'] == ProductPrice::TYPE_PERIOD_PRICE) {
                 $array[$mapping[$itemArray['type']]][$itemArray['currencyID']] = $itemArray;
                 if (array_key_exists($itemArray['currencyID'], $currencies) == false) {
                     $currencies[$itemArray['currencyID']] = Currency::getInstanceByID($itemArray['currencyID']);
                 }
                 $array[$mapping[$itemArray['type']]]['formated_price'][$itemArray['currencyID']] = $currencies[$itemArray['currencyID']]->getFormattedPrice($itemArray['price']);
             }
         }
     }
     return $array;
 }
Example #28
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getProductPrices()
 {
     return $this->hasMany(ProductPrice::className(), ['product_id' => 'id']);
 }
Example #29
0
    public function getProductsPurchasedTogether($limit = null, $enabledOnly = false)
    {
        if (0 === $limit) {
            return array();
        }
        if (is_null($limit)) {
            $limit = 0;
        }
        $sql = 'SELECT
					COUNT(*) AS cnt, COALESCE(ParentProduct.ID, OtherItem.productID) AS ID FROM OrderedItem
				LEFT JOIN
					CustomerOrder ON OrderedItem.customerOrderID=CustomerOrder.ID
				LEFT JOIN
					OrderedItem AS OtherItem ON OtherItem.customerOrderID=CustomerOrder.ID
				LEFT JOIN
					Product ON OtherItem.productID=Product.ID
				LEFT JOIN
					Product AS ParentProduct ON Product.parentID=ParentProduct.ID
				WHERE
					CustomerOrder.isFinalized=1 AND OrderedItem.productID=' . $this->getID() . ' AND OtherItem.productID!=' . $this->getID() . ($enabledOnly ? ' AND Product.isEnabled=1' : '') . '
				GROUP
					BY OtherItem.productID
				ORDER BY
					cnt DESC
				LIMIT ' . (int) $limit;
        $products = ActiveRecord::getDataBySql($sql);
        $ids = array();
        $cnt = array();
        foreach ($products as $key => $prod) {
            $ids[] = $prod['ID'];
            $cnt[$prod['ID']] = empty($cnt[$prod['ID']]) ? $prod['cnt'] : $prod['cnt'] + $cnt[$prod['ID']];
        }
        $products = array();
        if ($ids) {
            $products = ActiveRecord::getRecordSetArray('Product', new ARSelectFilter(new INCond(new ARFieldHandle('Product', 'ID'), $ids)), array('DefaultImage' => 'ProductImage'));
            foreach ($products as &$prod) {
                $prod['count'] = $cnt[$prod['ID']];
            }
            usort($products, array($this, 'togetherStatsSort'));
            ProductPrice::loadPricesForRecordSetArray($products);
        }
        return $products;
    }
 private function save(RecurringProductPeriod $rpp)
 {
     $request = $this->getRequest();
     $validator = $this->createFormValidator($rpp->toArray());
     if ($validator->isValid()) {
         $rpp->loadRequestData($this->request);
         // null value is not set by loadRequestData()..
         $rebillCount = $this->request->get('rebillCount');
         $rebillCount = floor($rebillCount);
         $rpp->rebillCount->set(is_numeric($rebillCount) && $rebillCount <= 0 ? $rebillCount : NULL);
         $rpp->save();
         $product = $rpp->product->get();
         $currencies = array();
         foreach ($this->application->getCurrencyArray(true) as $currency) {
             if (array_key_exists($currency, $currencies) == false) {
                 $currencies[$currency] = Currency::getInstanceByID($currency);
             }
             foreach (array(ProductPrice::TYPE_SETUP_PRICE => $request->get('ProductPrice_setup_price_' . $currency), ProductPrice::TYPE_PERIOD_PRICE => $request->get('ProductPrice_period_price_' . $currency)) as $type => $value) {
                 $price = ProductPrice::getInstance($product, $currencies[$currency], $rpp, $type);
                 if (strlen($value) == 0 && $price->isExistingRecord()) {
                     $price->delete();
                 } else {
                     $price->price->set($value);
                     $price->save();
                 }
             }
         }
         return new JSONResponse(array('rpp' => $rpp->toArray()), 'success');
     } else {
         return new JSONResponse(array('errors' => $validator->getErrorList()), 'failure', $this->translate('_could_not_save_recurring_product_period_entry'));
     }
 }