示例#1
0
 public function testFormatMoneyForceCurrency()
 {
     /********************/
     /*** Test for EUR ***/
     /********************/
     $currency = CurrencyQuery::create()->findOneByCode('EUR');
     // new format_money method, thelia >= 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency' => $currency->getId()]);
     $this->assertEquals("10.00 " . $currency->getSymbol(), $data);
     // old format_money method, thelia < 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency_symbol' => $currency->getSymbol()]);
     $this->assertEquals("10.00 " . $currency->getSymbol(), $data);
     /********************/
     /*** Test for USD ***/
     /********************/
     $currency = CurrencyQuery::create()->findOneByCode('USD');
     // new format_money method, thelia >= 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency' => $currency->getId()]);
     $this->assertEquals($currency->getSymbol() . "10.00", $data);
     // old format_money method, thelia < 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency_symbol' => $currency->getSymbol()]);
     $this->assertEquals($currency->getSymbol() . "10.00", $data);
     /********************/
     /*** Test for GBP ***/
     /********************/
     $currency = CurrencyQuery::create()->findOneByCode('GBP');
     // new format_money method, thelia >= 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency' => $currency->getId()]);
     $this->assertEquals($currency->getSymbol() . "10.00", $data);
     // old format_money method, thelia < 2.3
     $data = $this->render("testFormatMoney.html", ['number' => 9.9999, 'currency_symbol' => $currency->getSymbol()]);
     $this->assertEquals($currency->getSymbol() . "10.00", $data);
 }
 public function importData(array $data)
 {
     $pse = ProductSaleElementsQuery::create()->findPk($data['id']);
     if ($pse === null) {
         return Translator::getInstance()->trans('The product sale element id %id doesn\'t exist', ['%id' => $data['id']]);
     } else {
         $currency = null;
         if (isset($data['currency'])) {
             $currency = CurrencyQuery::create()->findOneByCode($data['currency']);
         }
         if ($currency === null) {
             $currency = Currency::getDefaultCurrency();
         }
         $price = ProductPriceQuery::create()->filterByProductSaleElementsId($pse->getId())->findOneByCurrencyId($currency->getId());
         if ($price === null) {
             $price = new ProductPrice();
             $price->setProductSaleElements($pse)->setCurrency($currency);
         }
         $price->setPrice($data['price']);
         if (isset($data['promo_price'])) {
             $price->setPromoPrice($data['promo_price']);
         }
         if (isset($data['promo'])) {
             $price->getProductSaleElements()->setPromo((int) $data['promo'])->save();
         }
         $price->save();
         $this->importedRows++;
     }
     return null;
 }
 public function checkDuplicateCode($value, ExecutionContextInterface $context)
 {
     $currency = CurrencyQuery::create()->findOneByCode($value);
     if ($currency) {
         $context->addViolation(Translator::getInstance()->trans('A currency with code "%name" already exists.', ['%name' => $value]));
     }
 }
示例#4
0
 /**
  * Generate adapter stub
  *
  * @param int    $cartTotalPrice   Cart total price
  * @param string $checkoutCurrency Checkout currency
  * @param string $i18nOutput       Output from each translation
  *
  * @return \PHPUnit_Framework_MockObject_MockObject
  */
 public function generateFacadeStub($cartTotalPrice = 400, $checkoutCurrency = 'EUR', $i18nOutput = '')
 {
     $stubFacade = $this->getMockBuilder('\\Thelia\\Coupon\\BaseFacade')->disableOriginalConstructor()->getMock();
     $currencies = CurrencyQuery::create();
     $currencies = $currencies->find();
     $stubFacade->expects($this->any())->method('getAvailableCurrencies')->will($this->returnValue($currencies));
     $stubFacade->expects($this->any())->method('getCartTotalPrice')->will($this->returnValue($cartTotalPrice));
     $stubFacade->expects($this->any())->method('getCheckoutCurrency')->will($this->returnValue($checkoutCurrency));
     $stubFacade->expects($this->any())->method('getConditionEvaluator')->will($this->returnValue(new ConditionEvaluator()));
     $stubTranslator = $this->getMockBuilder('\\Thelia\\Core\\Translation\\Translator')->disableOriginalConstructor()->getMock();
     $stubTranslator->expects($this->any())->method('trans')->will($this->returnValue($i18nOutput));
     $stubFacade->expects($this->any())->method('getTranslator')->will($this->returnValue($stubTranslator));
     $stubDispatcher = $this->getMockBuilder('\\Symfony\\Component\\EventDispatcher\\EventDispatcher')->disableOriginalConstructor()->getMock();
     $stubDispatcher->expects($this->any())->method('dispatch')->will($this->returnCallback(function ($dummy, $cartEvent) {
         $ci = new CartItem();
         $ci->setId(3)->setPrice(123)->setPromo(0);
         $cartEvent->setCartItem($ci);
     }));
     $stubFacade->expects($this->any())->method('getDispatcher')->will($this->returnValue($stubDispatcher));
     $stubSession = $this->getMockBuilder('\\Thelia\\Core\\HttpFoundation\\Session\\Session')->disableOriginalConstructor()->getMock();
     $stubSession->expects($this->any())->method('get')->will($this->onConsecutiveCalls(-1, 3));
     $stubRequest = $this->getMockBuilder('\\Thelia\\Core\\HttpFoundation\\Request')->disableOriginalConstructor()->getMock();
     $stubRequest->expects($this->any())->method('getSession')->will($this->returnValue($stubSession));
     $stubFacade->expects($this->any())->method('getRequest')->will($this->returnValue($stubRequest));
     return $stubFacade;
 }
 /**
  * Get the untaxed price and, if the product is in sale, promo price of a product.
  *
  * @param ProductGetPricesEvent $event
  */
 public function getPrices(ProductGetPricesEvent $event)
 {
     $product = ProductQuery::create()->findPk($event->getProductId());
     if (null === $product) {
         throw new \InvalidArgumentException('No product given');
     }
     $currency = CurrencyQuery::create()->findPk($event->getCurrencyId());
     if (null === $currency) {
         $currency = CurrencyQuery::create()->findOneByByDefault(true);
     }
     // get the base prices given in the event
     // or, by default, the prices of the product's default PSE
     if (null !== $event->getBasePrices()) {
         $price = $event->getBasePrices()->getPrice();
         $promoPrice = $event->getBasePrices()->getPromoPrice();
     } else {
         $prices = $product->getDefaultSaleElements()->getPricesByCurrency($currency);
         $price = $prices->getPrice();
         $promoPrice = $prices->getPromoPrice();
     }
     // adjust the prices with the configured price delta from legacy attributes
     $legacyProductAttributeValues = LegacyProductAttributeValueQuery::create()->filterByProductId($product->getId())->filterByAttributeAvId(array_values($event->getLegacyProductAttributes()), Criteria::IN)->find();
     /** @var LegacyProductAttributeValue $legacyProductAttributeValue */
     foreach ($legacyProductAttributeValues as $legacyProductAttributeValue) {
         $legacyProductAttributeValuePrice = $legacyProductAttributeValue->getPriceForCurrency($event->getCurrencyId());
         if ($legacyProductAttributeValuePrice === null) {
             continue;
         }
         $price += $legacyProductAttributeValuePrice->getDelta();
         $promoPrice += $legacyProductAttributeValuePrice->getDelta();
     }
     $event->setPrices(new ProductPriceTools($price, $promoPrice));
 }
示例#6
0
 protected function getExistingObject()
 {
     $currency = CurrencyQuery::create()->findOneById($this->getRequest()->get('currency_id'));
     if (null !== $currency) {
         $currency->setLocale($this->getCurrentEditionLocale());
     }
     return $currency;
 }
示例#7
0
 /**
  * @since 2.3
  * @param float $number
  * @param int $decimals
  * @param string $decPoint
  * @param string $thousandsSep
  * @param int|null $currencyId
  * @return string
  */
 public function formatByCurrency($number, $decimals = null, $decPoint = null, $thousandsSep = null, $currencyId = null)
 {
     $number = parent::format($number, $decimals, $decPoint, $thousandsSep);
     $currency = $currencyId !== null ? CurrencyQuery::create()->findPk($currencyId) : $this->request->getSession()->getCurrency();
     if ($currency !== null && strpos($currency->getFormat(), '%n') !== false) {
         return str_replace(['%n', '%s', '%c'], [$number, $currency->getSymbol(), $currency->getCode()], $currency->getFormat());
     }
     return $number;
 }
示例#8
0
 /**
  * Generate adapter stub
  *
  * @param int    $cartTotalPrice   Cart total price
  * @param string $checkoutCurrency Checkout currency
  * @param string $i18nOutput       Output from each translation
  *
  * @return \PHPUnit_Framework_MockObject_MockObject
  */
 public function generateFacadeStub($cartTotalPrice = 400, $checkoutCurrency = 'EUR', $i18nOutput = '')
 {
     $stubFacade = $this->getMockBuilder('\\Thelia\\Coupon\\BaseFacade')->disableOriginalConstructor()->getMock();
     $currencies = CurrencyQuery::create()->find();
     $stubFacade->expects($this->any())->method('getAvailableCurrencies')->will($this->returnValue($currencies));
     $stubFacade->expects($this->any())->method('getCartTotalTaxPrice')->will($this->returnValue($cartTotalPrice));
     $stubFacade->expects($this->any())->method('getCheckoutCurrency')->will($this->returnValue($checkoutCurrency));
     $stubFacade->expects($this->any())->method('getConditionEvaluator')->will($this->returnValue(new ConditionEvaluator()));
     $stubTranslator = $this->getMockBuilder('\\Thelia\\Core\\Translation\\Translator')->disableOriginalConstructor()->getMock();
     $stubTranslator->expects($this->any())->method('trans')->will($this->returnValue($i18nOutput));
     $stubFacade->expects($this->any())->method('getTranslator')->will($this->returnValue($stubTranslator));
     return $stubFacade;
 }
 public function testCheckCurrency()
 {
     $listener = $this->getRequestListener();
     $event = $this->getGetResponseEvent();
     /** @var Session $session */
     $session = $event->getRequest()->getSession();
     // Test with a session that has no currency
     $listener->checkCurrency($event);
     $currentCurrency = $session->getCurrency();
     $this->assertInstanceOf('Thelia\\Model\\Currency', $currentCurrency);
     // Test change currency
     $newCurrency = CurrencyQuery::create()->filterById($currentCurrency->getId(), Criteria::NOT_IN)->findOne();
     $event->getRequest()->query->set('currency', $newCurrency->getCode());
     $listener->checkCurrency($event);
     $this->assertEquals($session->getCurrency()->getId(), $newCurrency->getId());
 }
示例#10
0
 public function testCreateAction()
 {
     $client = static::createClient();
     $category = CategoryQuery::create()->addAscendingOrderByColumn('RAND()')->findOne();
     $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(1);
     $taxRule = TaxRuleQuery::create()->findOneByIsDefault(1);
     $product = ['ref' => uniqid('testCreateProduct'), 'locale' => 'en_US', 'title' => 'product create from api', 'description' => 'product description from api', 'default_category' => $category->getId(), 'visible' => 1, 'price' => '10', 'currency' => $defaultCurrency->getId(), 'tax_rule' => $taxRule->getId(), 'weight' => 10, 'brand_id' => 0];
     $requestContent = json_encode($product);
     $servers = $this->getServerParameters();
     $servers['CONTENT_TYPE'] = 'application/json';
     $client->request('POST', '/api/products?&sign=' . $this->getSignParameter($requestContent), [], [], $servers, $requestContent);
     $this->assertEquals(201, $client->getResponse()->getStatusCode(), 'Http status code must be 201');
     $content = json_decode($client->getResponse()->getContent(), true);
     $this->assertEquals('en_US', $content[0]['LOCALE']);
     return $content['0']['ID'];
 }
 public function testPrices()
 {
     $container = new Container();
     new Translator($container);
     $handler = new ProductTaxedPricesExport($container);
     $lang = Lang::getDefaultLanguage();
     $data = $handler->buildData($lang)->getData();
     foreach ($data as $line) {
         $product = ProductSaleElementsQuery::create()->findOneByRef($line["ref"]);
         $currency = CurrencyQuery::create()->findOneByCode($line["currency"]);
         $this->assertNotNull($product);
         $prices = $product->getPricesByCurrency($currency);
         $this->assertEquals($prices->getPrice(), $line["price"]);
         $this->assertEquals($prices->getPromoPrice(), $line["promo_price"]);
     }
 }
 public function testPrices()
 {
     new Translator(new Container());
     $export = new ProductTaxedPricesExport(new Container());
     $data = $export->buildData(Lang::getDefaultLanguage());
     $keys = ["attributes", "currency", "ean", "id", "price", "product_id", "promo", "promo_price", "tax_id", "tax_title", "title"];
     $rawData = $data->getData();
     $max = count($rawData);
     /**
      * If there are more than 50 entries, a test on 50 entries will be as efficient
      * and quicker than a test on all the entries
      */
     if ($max > 50) {
         $max = 50;
     }
     for ($i = 0; $i < $max; ++$i) {
         $row = $rawData[$i];
         $rowKeys = array_keys($row);
         $this->assertTrue(sort($rowKeys));
         $this->assertEquals($keys, $rowKeys);
         $pse = ProductSaleElementsQuery::create()->findPk($row["id"]);
         $this->assertNotNull($pse);
         $this->assertEquals($pse->getEanCode(), $row["ean"]);
         $this->assertEquals($pse->getPromo(), $row["promo"]);
         $currency = CurrencyQuery::create()->findOneByCode($row["currency"]);
         $this->assertNotNull($currency);
         $price = $pse->getPricesByCurrency($currency);
         $this->assertEquals(round($price->getPrice(), 3), round($row["price"], 3));
         $this->assertEquals(round($price->getPromoPrice(), 3), round($row["promo_price"], 3));
         $this->assertEquals($pse->getProduct()->getTitle(), $row["title"]);
         $attributeCombinations = $pse->getAttributeCombinations();
         $attributes = [];
         foreach ($attributeCombinations as $attributeCombination) {
             if (!in_array($attributeCombination->getAttributeAv()->getTitle(), $attributes)) {
                 $attributes[] = $attributeCombination->getAttributeAv()->getTitle();
             }
         }
         $rowAttributes = !empty($row["attributes"]) ? explode(",", $row["attributes"]) : [];
         sort($rowAttributes);
         sort($attributes);
         $this->assertEquals($attributes, $rowAttributes);
         $taxId = $pse->getProduct()->getTaxRule()->getId();
         $this->assertEquals($taxId, $row["tax_id"]);
         $taxTitle = $pse->getProduct()->getTaxRule()->getTitle();
         $this->assertEquals($taxTitle, $row["tax_title"]);
     }
 }
示例#13
0
 public function testQuery()
 {
     new Translator(new Container());
     $export = new ProductPricesExport(new Container());
     $data = $export->buildData(Lang::getDefaultLanguage());
     $keys = ["attributes", "currency", "ean", "id", "price", "product_id", "promo", "promo_price", "title"];
     $rawData = $data->getData();
     $max = count($rawData);
     /**
      * If there's more that 50 entries,
      * just pick 50, it would be faster and as tested as if we test 1000 entries.
      */
     if ($max > 50) {
         $max = 50;
     }
     for ($i = 0; $i < $max; ++$i) {
         $row = $rawData[$i];
         $rowKeys = array_keys($row);
         $this->assertTrue(sort($rowKeys));
         $this->assertEquals($keys, $rowKeys);
         $pse = ProductSaleElementsQuery::create()->findPk($row["id"]);
         $this->assertNotNull($pse);
         $this->assertEquals($pse->getEanCode(), $row["ean"]);
         $this->assertEquals($pse->getPromo(), $row["promo"]);
         $currency = CurrencyQuery::create()->findOneByCode($row["currency"]);
         $this->assertNotNull($currency);
         $price = $pse->getPricesByCurrency($currency);
         // The substr is a patch for php 5.4 float round
         $this->assertEquals(round($price->getPrice(), 3), round($row["price"], 3));
         $this->assertEquals(round($price->getPromoPrice(), 3), round($row["promo_price"], 3));
         $this->assertEquals($pse->getProduct()->getTitle(), $row["title"]);
         $attributeCombinations = $pse->getAttributeCombinations();
         $attributes = [];
         foreach ($attributeCombinations as $attributeCombination) {
             if (!in_array($attributeCombination->getAttributeAv()->getTitle(), $attributes)) {
                 $attributes[] = $attributeCombination->getAttributeAv()->getTitle();
             }
         }
         $rowAttributes = explode(",", $row["attributes"]);
         sort($rowAttributes);
         sort($attributes);
         $this->assertEquals($attributes, $rowAttributes);
     }
 }
 protected function buildForm()
 {
     $this->formBuilder->add('product_id', 'integer', ['label' => Translator::getInstance()->trans('Product'), 'required' => true, 'constraints' => [new NotBlank()]])->add('currency_id', 'integer', ['label' => Translator::getInstance()->trans('Currency'), 'required' => true, 'constraints' => [new NotBlank()]]);
     $productId = $this->request->get('product_id');
     if ($productId === null) {
         $productId = $this->request->get($this->getName())['product_id'];
     }
     $product = ProductQuery::create()->findPk($productId);
     if ($product->getTemplate() === null) {
         return;
     }
     $currencyId = $this->request->get('edit_currency_id');
     if ($currencyId === null) {
         $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(true);
         if ($defaultCurrency !== null) {
             $currencyId = $defaultCurrency->getId();
         }
     }
     $productAttributeAvs = AttributeAvQuery::create()->useAttributeQuery()->filterByTemplate($product->getTemplate())->endUse()->find();
     $formData = ['price_delta' => [], 'price_delta_with_tax' => []];
     /** @var TaxEngine $taxEngine */
     $taxEngine = $this->container->get('thelia.taxEngine');
     $taxCalculator = (new Calculator())->load($product, $taxEngine->getDeliveryCountry());
     /** @var AttributeAv $productAttributeAv */
     foreach ($productAttributeAvs as $productAttributeAv) {
         $legacyProductAttributeValuePrice = LegacyProductAttributeValuePriceQuery::create()->findPk([$product->getId(), $productAttributeAv->getId(), $currencyId]);
         $priceDelta = 0;
         $priceDeltaWithTax = 0;
         if (null !== $legacyProductAttributeValuePrice) {
             $priceDelta = $legacyProductAttributeValuePrice->getDelta();
             $priceDeltaWithTax = $taxCalculator->getTaxedPrice($legacyProductAttributeValuePrice->getDelta());
         }
         $numberFormatter = NumberFormat::getInstance($this->getRequest());
         $formData['price_delta'][$productAttributeAv->getId()] = $numberFormatter->formatStandardNumber($priceDelta);
         $formData['price_delta_with_tax'][$productAttributeAv->getId()] = $numberFormatter->formatStandardNumber($priceDeltaWithTax);
     }
     $this->formBuilder->add('legacy_product_attribute_value_price_delta', 'collection', ['label' => Translator::getInstance()->trans('Price difference excluding taxes', [], LegacyProductAttributes::MESSAGE_DOMAIN_BO), 'type' => 'number', 'allow_add' => true, 'allow_delete' => true, 'data' => $formData['price_delta']])->add('legacy_product_attribute_value_price_delta_with_tax', 'collection', ['label' => Translator::getInstance()->trans('Price difference including taxes', [], LegacyProductAttributes::MESSAGE_DOMAIN_BO), 'type' => 'number', 'allow_add' => true, 'allow_delete' => true, 'data' => $formData['price_delta_with_tax']]);
 }
 public function buildDataSet(Lang $lang)
 {
     /** @var \Thelia\Model\AttributeCombinationQuery $query */
     $query = parent::buildDataSet($lang);
     $pseJoin = new Join(AttributeCombinationTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductSaleElementsTableMap::ID);
     $pseJoin->setRightTableAlias("pse_tax_join");
     $productJoin = new Join(ProductSaleElementsTableMap::ID, ProductTableMap::ID);
     $productJoin->setRightTableAlias("product_tax_join");
     $taxJoin = new Join("`product_tax_join`.TAX_RULE_ID", TaxRuleTableMap::ID, Criteria::LEFT_JOIN);
     $taxI18nJoin = new Join(TaxRuleTableMap::ID, TaxRuleI18nTableMap::ID, Criteria::LEFT_JOIN);
     $query->addJoinObject($pseJoin, "pse_tax_join")->addJoinObject($productJoin, "product_tax_join")->addJoinObject($productJoin)->addJoinObject($taxJoin)->addJoinObject($taxI18nJoin)->addAsColumn("product_TAX_TITLE", TaxRuleI18nTableMap::TITLE)->addAsColumn("tax_ID", TaxRuleTableMap::ID)->select($query->getSelect() + ["product_TAX_TITLE", "tax_ID"]);
     I18n::addI18nCondition($query, TaxRuleI18nTableMap::TABLE_NAME, TaxRuleTableMap::ID, TaxRuleI18nTableMap::ID, TaxRuleI18nTableMap::LOCALE, $lang->getLocale());
     $dataSet = $query->keepQuery(true)->find()->toArray();
     $productSaleElements = ProductSaleElementsQuery::create()->find()->toKeyIndex("Id");
     $currencies = CurrencyQuery::create()->find()->toKeyIndex("Code");
     foreach ($dataSet as &$line) {
         /** @var \Thelia\Model\ProductSaleElements $pse */
         $pse = $productSaleElements[$line["product_sale_elements_ID"]];
         $pricesTools = $pse->getPricesByCurrency($currencies[$line["currency_CODE"]]);
         $line["price_PRICE"] = $pricesTools->getPrice();
         $line["price_PROMO_PRICE"] = $pricesTools->getPromoPrice();
     }
     return $dataSet;
 }
示例#16
0
 /**
  * @param \Thelia\Core\FileFormat\Formatting\FormatterData
  * @return string|array error messages
  *
  * The method does the import routine from a FormatterData
  */
 public function retrieveFromFormatterData(FormatterData $data)
 {
     $errors = [];
     $translator = Translator::getInstance();
     while (null !== ($row = $data->popRow())) {
         $this->checkMandatoryColumns($row);
         $obj = ProductSaleElementsQuery::create()->findOneByRef($row["ref"]);
         if ($obj === null) {
             $errorMessage = $translator->trans("The product sale element reference %ref doesn't exist", ["%ref" => $row["ref"]]);
             $errors[] = $errorMessage;
         } else {
             $currency = null;
             if (isset($row["currency"])) {
                 $currency = CurrencyQuery::create()->findOneByCode($row["currency"]);
             }
             if ($currency === null) {
                 $currency = Currency::getDefaultCurrency();
             }
             $price = ProductPriceQuery::create()->filterByProductSaleElementsId($obj->getId())->findOneByCurrencyId($currency->getId());
             if ($price === null) {
                 $price = new ProductPrice();
                 $price->setProductSaleElements($obj)->setCurrency($currency);
             }
             $price->setPrice($row["price"]);
             if (isset($row["promo_price"])) {
                 $price->setPromoPrice($row["promo_price"]);
             }
             if (isset($row["promo"])) {
                 $price->getProductSaleElements()->setPromo((int) $row["promo"])->save();
             }
             $price->save();
             $this->importedRows++;
         }
     }
     return $errors;
 }
示例#17
0
文件: faker.php 项目: hadesain/thelia
         $product = $pse->getProduct();
         $orderProduct = new \Thelia\Model\OrderProduct();
         $orderProduct->setOrderId($placedOrder->getId())->setProductRef($product->getRef())->setProductSaleElementsRef($pse->getRef())->setProductSaleElementsId($pse->getId())->setTitle($product->getTitle())->setChapo($product->getChapo())->setDescription($product->getDescription())->setPostscriptum($product->getPostscriptum())->setQuantity(mt_rand(1, 10))->setPrice($price = mt_rand(1, 100))->setPromoPrice(mt_rand(1, $price))->setWasNew($pse->getNewness())->setWasInPromo(rand(0, 1) == 1)->setWeight($pse->getWeight())->setTaxRuleTitle(getRealText(20))->setTaxRuleDescription(getRealText(50))->setEanCode($pse->getEanCode())->save($con);
     }
 }
 echo "Generating coupons fixtures\n";
 generateCouponFixtures($thelia);
 echo "Generating sales\n";
 for ($idx = 1; $idx <= 5; $idx++) {
     $sale = new \Thelia\Model\Sale();
     $start = new \DateTime();
     $end = new \DateTime();
     $sale->setActive(0)->setStartDate($start->setTimestamp(strtotime("today - 1 month")))->setEndDate($end->setTimestamp(strtotime("today + 1 month")))->setPriceOffsetType(\Thelia\Model\Sale::OFFSET_TYPE_PERCENTAGE)->setDisplayInitialPrice(true);
     setI18n($sale, ['SaleLabel' => 20, 'Title' => 20, 'Chapo' => 30, 'Postscriptum' => 30, 'Description' => 50]);
     $sale->save();
     $currencies = \Thelia\Model\CurrencyQuery::create()->find();
     foreach ($currencies as $currency) {
         $saleOffset = new \Thelia\Model\SaleOffsetCurrency();
         $saleOffset->setCurrencyId($currency->getId())->setSaleId($sale->getId())->setPriceOffsetValue($faker->numberBetween(10, 70))->save();
     }
     $products = \Thelia\Model\ProductQuery::create()->addAscendingOrderByColumn('RAND()')->find();
     $count = $faker->numberBetween(5, 20);
     foreach ($products as $product) {
         if (--$count < 0) {
             break;
         }
         $saleProduct = new \Thelia\Model\SaleProduct();
         $saleProduct->setSaleId($sale->getId())->setProductId($product->getId())->setAttributeAvId(null)->save();
     }
 }
 $con->commit();
示例#18
0
 public function fillCart()
 {
     $currency = CurrencyQuery::create()->findOne();
     //create a fake cart in database;
     $cart = new Cart();
     $cart->setToken(uniqid("createorder", true))->setCustomer($this->customer)->setCurrency($currency)->save();
     /* add 3 items */
     $productList = array();
     for ($i = 0; $i < 3; $i++) {
         $pse = ProductSaleElementsQuery::create()->filterByProduct(ProductQuery::create()->filterByVisible(1)->filterById($productList, Criteria::NOT_IN)->find())->filterByQuantity(5, Criteria::GREATER_EQUAL)->joinProductPrice('pp', Criteria::INNER_JOIN)->addJoinCondition('pp', 'currency_id = ?', $currency->getId(), null, \PDO::PARAM_INT)->withColumn('`pp`.price', 'price_PRICE')->withColumn('`pp`.promo_price', 'price_PROMO_PRICE')->findOne();
         $productList[] = $pse->getProductId();
         $cartItem = new CartItem();
         $cartItem->setCart($cart)->setProduct($pse->getProduct())->setProductSaleElements($pse)->setQuantity($i + 1)->setPrice($pse->getPrice())->setPromoPrice($pse->getPromoPrice())->setPromo($pse->getPromo())->setPriceEndOfLife(time() + 60 * 60 * 24 * 30)->save();
         $this->cartItems[] = $cartItem;
     }
     $this->request->getSession()->setCart($cart->getId());
     return $cart;
 }
示例#19
0
 /**
  * Removes this object from datastore and sets delete attribute.
  *
  * @param      ConnectionInterface $con
  * @return void
  * @throws PropelException
  * @see Currency::setDeleted()
  * @see Currency::isDeleted()
  */
 public function delete(ConnectionInterface $con = null)
 {
     if ($this->isDeleted()) {
         throw new PropelException("This object has already been deleted.");
     }
     if ($con === null) {
         $con = Propel::getServiceContainer()->getWriteConnection(CurrencyTableMap::DATABASE_NAME);
     }
     $con->beginTransaction();
     try {
         $deleteQuery = ChildCurrencyQuery::create()->filterByPrimaryKey($this->getPrimaryKey());
         $ret = $this->preDelete($con);
         if ($ret) {
             $deleteQuery->delete($con);
             $this->postDelete($con);
             $con->commit();
             $this->setDeleted(true);
         } else {
             $con->commit();
         }
     } catch (Exception $e) {
         $con->rollBack();
         throw $e;
     }
 }
示例#20
0
 /**
  * Calculate all prices
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function loadConvertedPrices()
 {
     $product_sale_element_id = intval($this->getRequest()->get('product_sale_element_id', 0));
     $currency_id = intval($this->getRequest()->get('currency_id', 0));
     $price_with_tax = $price_without_tax = $sale_price_with_tax = $sale_price_without_tax = 0;
     if (null !== ($pse = ProductSaleElementsQuery::create()->findPk($product_sale_element_id))) {
         if ($currency_id > 0 && $currency_id != Currency::getDefaultCurrency()->getId() && null !== ($currency = CurrencyQuery::create()->findPk($currency_id))) {
             // Get the default currency price
             $productPrice = ProductPriceQuery::create()->filterByCurrency(Currency::getDefaultCurrency())->filterByProductSaleElementsId($product_sale_element_id)->findOne();
             // Calculate the converted price
             if (null !== $productPrice) {
                 $price_without_tax = $productPrice->getPrice() * $currency->getRate();
                 $sale_price_without_tax = $productPrice->getPromoPrice() * $currency->getRate();
             }
         }
         if (null !== ($product = $pse->getProduct())) {
             $price_with_tax = $this->computePrice($price_without_tax, 'with_tax', $product);
             $sale_price_with_tax = $this->computePrice($sale_price_without_tax, 'with_tax', $product);
         }
     }
     return new JsonResponse(array('price_with_tax' => $this->formatPrice($price_with_tax), 'price_without_tax' => $this->formatPrice($price_without_tax), 'sale_price_with_tax' => $this->formatPrice($sale_price_with_tax), 'sale_price_without_tax' => $this->formatPrice($sale_price_without_tax)));
 }
示例#21
0
文件: Order.php 项目: shirone/thelia
 /**
  * Get the associated ChildCurrency object
  *
  * @param      ConnectionInterface $con Optional Connection object.
  * @return                 ChildCurrency The associated ChildCurrency object.
  * @throws PropelException
  */
 public function getCurrency(ConnectionInterface $con = null)
 {
     if ($this->aCurrency === null && $this->currency_id !== null) {
         $this->aCurrency = ChildCurrencyQuery::create()->findPk($this->currency_id, $con);
         /* The following can be used additionally to
               guarantee the related object contains a reference
               to this object.  This level of coupling may, however, be
               undesirable since it could result in an only partially populated collection
               in the referenced object.
               $this->aCurrency->addOrders($this);
            */
     }
     return $this->aCurrency;
 }
 public function addProduct($id)
 {
     if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('GoogleShopping'), AccessManager::CREATE))) {
         return $response;
     }
     $request = $this->getRequest()->request;
     $con = Propel::getConnection(GoogleshoppingProductSynchronisationTableMap::DATABASE_NAME);
     $con->beginTransaction();
     try {
         $eventArgs = [];
         //Get local and lang by admin config flag selected
         $eventArgs['ignoreGtin'] = $request->get('gtin') === "on" ? true : false;
         $eventArgs['lang'] = LangQuery::create()->findOneById($request->get("lang"));
         $eventArgs['targetCountry'] = CountryQuery::create()->findOneById($request->get('country'));
         $merchantId = $request->get('account');
         $locale = $eventArgs['lang']->getLocale();
         $currencyId = $request->get('currency');
         $currency = CurrencyQuery::create()->findOneById($currencyId);
         if (null === $currency) {
             $currency = Currency::getDefaultCurrency();
         }
         if (!$eventArgs['targetCountry']) {
             $eventArgs['targetCountry'] = Country::getDefaultCountry();
         }
         //If the authorisation is not set yet or has expired
         if (false === $this->checkGoogleAuth()) {
             $this->getSession()->set('google_action_url', "/admin/module/googleshopping/add/{$id}?locale={$locale}&gtin=" . $eventArgs['ignoreGtin']);
             return $this->generateRedirect('/googleshopping/oauth2callback');
         }
         $googleShoppingHandler = new GoogleShoppingHandler($this->container, $this->getRequest());
         //Init google client
         $client = $googleShoppingHandler->createGoogleClient();
         $googleShoppingService = new \Google_Service_ShoppingContent($client);
         //Get the product
         $theliaProduct = ProductQuery::create()->joinWithI18n($eventArgs['lang']->getLocale())->findOneById($id);
         /** @var ProductSaleElements $productSaleElement */
         $googleProductEvent = new GoogleProductEvent($theliaProduct, null, $googleShoppingService, $eventArgs);
         $googleProductEvent->setMerchantId($merchantId)->setCurrency($currency);
         $this->getDispatcher()->dispatch(GoogleShoppingEvents::GOOGLE_PRODUCT_CREATE_PRODUCT, $googleProductEvent);
         $googleAccountId = GoogleshoppingAccountQuery::create()->findOneByMerchantId($merchantId);
         //Add auomatically product to sync
         $productSync = GoogleshoppingProductSynchronisationQuery::create()->filterByProductId($theliaProduct->getId())->filterByLang($eventArgs['lang']->getCode())->filterByTargetCountry($eventArgs['targetCountry']->getIsoalpha2())->filterByGoogleshoppingAccountId($googleAccountId)->findOneOrCreate();
         $productSync->setSyncEnable(true)->save();
         $con->commit();
         return JsonResponse::create(["message" => "Success"], 200);
     } catch (\Exception $e) {
         $con->rollBack();
         //            $deleteResponse = $this->deleteProduct($id);
         return JsonResponse::create($e->getMessage(), 500);
     }
 }
 /**
  * Provides access to an attribute of the current currency
  *
  * @param  array $params
  * @param  \Smarty $smarty
  * @return string the value of the requested attribute
  */
 public function currencyDataAccess($params, $smarty)
 {
     $currency = $this->getSession()->getCurrency();
     if ($currency) {
         return $this->dataAccessWithI18n("Currency", $params, CurrencyQuery::create()->filterByPrimaryKey($currency->getId()), array("NAME"));
     }
     return '';
 }
示例#24
0
 /**
  * Test condition serialization if collection is empty
  *
  * @covers Thelia\Condition\ConditionFactory::serializeConditionCollection
  */
 public function testSerializeConditionCollectionEmpty()
 {
     $stubTranslator = $this->getMockBuilder('\\Thelia\\Core\\Translation\\Translator')->disableOriginalConstructor()->getMock();
     /** @var FacadeInterface $stubFacade */
     $stubFacade = $this->getMockBuilder('\\Thelia\\Coupon\\BaseFacade')->disableOriginalConstructor()->getMock();
     $stubFacade->expects($this->any())->method('getTranslator')->will($this->returnValue($stubTranslator));
     $stubFacade->expects($this->any())->method('getConditionEvaluator')->will($this->returnValue(new ConditionEvaluator()));
     $currencies = CurrencyQuery::create();
     $currencies = $currencies->find();
     $stubFacade->expects($this->any())->method('getAvailableCurrencies')->will($this->returnValue($currencies));
     $stubContainer = $this->getMockBuilder('\\Symfony\\Component\\DependencyInjection\\Container')->disableOriginalConstructor()->getMock();
     $stubContainer->expects($this->any())->method('get')->will($this->returnValue(new MatchForEveryone($stubFacade)));
     $stubContainer->expects($this->any())->method('has')->will($this->returnValue(true));
     $stubFacade->expects($this->any())->method('getContainer')->will($this->returnValue($stubContainer));
     $conditions = new ConditionCollection();
     $conditionFactory = new ConditionFactory($stubContainer);
     $conditionNone = new MatchForEveryone($stubFacade);
     $expectedCollection = new ConditionCollection();
     $expectedCollection[] = $conditionNone;
     $expected = $conditionFactory->serializeConditionCollection($expectedCollection);
     $actual = $conditionFactory->serializeConditionCollection($conditions);
     $this->assertEquals($expected, $actual);
 }
示例#25
0
 /**
  * currency global data
  *
  * @param $params
  * @param $smarty
  */
 public function currencyDataAccess($params, $smarty)
 {
     $currency = $this->request->getSession()->getCurrency();
     if ($currency) {
         $currencyQuery = CurrencyQuery::create()->filterById($currency->getId());
         return $this->dataAccessWithI18n("Currency", $params, $currencyQuery, array("NAME"));
     }
 }
示例#26
0
 public function buildModelCriteria()
 {
     Tlog::getInstance()->debug("-- Starting new product build criteria");
     $currencyId = $this->getCurrency();
     if (null !== $currencyId) {
         $currency = CurrencyQuery::create()->findOneById($currencyId);
         if (null === $currency) {
             throw new \InvalidArgumentException('Cannot found currency id: `' . $currency . '` in product_sale_elements loop');
         }
     } else {
         $currency = $this->request->getSession()->getCurrency();
     }
     $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(1);
     $defaultCurrencySuffix = '_default_currency';
     $priceToCompareAsSQL = '';
     $isPSELeftJoinList = [];
     $isProductPriceFirstLeftJoin = [];
     $search = ProductQuery::create();
     $complex = $this->getComplex();
     if (!$complex) {
         $search->innerJoinProductSaleElements('pse');
         $search->addJoinCondition('pse', '`pse`.IS_DEFAULT=1');
         $search->innerJoinProductSaleElements('pse_count');
         $priceJoin = new Join();
         $priceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'pse', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'price');
         $priceJoin->setJoinType(Criteria::LEFT_JOIN);
         $search->addJoinObject($priceJoin, 'price_join')->addJoinCondition('price_join', '`price`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT);
         if ($defaultCurrency->getId() != $currency->getId()) {
             $priceJoinDefaultCurrency = new Join();
             $priceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'pse', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'price' . $defaultCurrencySuffix);
             $priceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN);
             $search->addJoinObject($priceJoinDefaultCurrency, 'price_join' . $defaultCurrencySuffix)->addJoinCondition('price_join' . $defaultCurrencySuffix, '`price' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT);
             /**
              * rate value is checked as a float in overloaded getRate method.
              */
             $priceToCompareAsSQL = 'CASE WHEN ISNULL(`price`.PRICE) OR `price`.FROM_DEFAULT_CURRENCY = 1 THEN
                 CASE WHEN `pse`.PROMO=1 THEN `price' . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `price' . $defaultCurrencySuffix . '`.PRICE END * ' . $currency->getRate() . '
             ELSE
                 CASE WHEN `pse`.PROMO=1 THEN `price`.PROMO_PRICE ELSE `price`.PRICE END
             END';
             $search->withColumn('ROUND(' . $priceToCompareAsSQL . ', 2)', 'real_price');
             $search->withColumn('CASE WHEN ISNULL(`price`.PRICE) OR `price`.FROM_DEFAULT_CURRENCY = 1 THEN `price' . $defaultCurrencySuffix . '`.PRICE * ' . $currency->getRate() . ' ELSE `price`.PRICE END', 'price');
             $search->withColumn('CASE WHEN ISNULL(`price`.PRICE) OR `price`.FROM_DEFAULT_CURRENCY = 1 THEN `price' . $defaultCurrencySuffix . '`.PROMO_PRICE * ' . $currency->getRate() . ' ELSE `price`.PROMO_PRICE END', 'promo_price');
         } else {
             $priceToCompareAsSQL = 'CASE WHEN `pse`.PROMO=1 THEN `price`.PROMO_PRICE ELSE `price`.PRICE END';
             $search->withColumn('ROUND(' . $priceToCompareAsSQL . ', 2)', 'real_price');
             $search->withColumn('`price`.PRICE', 'price');
             $search->withColumn('`price`.PROMO_PRICE', 'promo_price');
         }
     }
     /* manage translations */
     $this->configureI18nProcessing($search, ['TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM', 'META_TITLE', 'META_DESCRIPTION', 'META_KEYWORDS']);
     $id = $this->getId();
     if (!is_null($id)) {
         $search->filterById($id, Criteria::IN);
     }
     $ref = $this->getRef();
     if (!is_null($ref)) {
         $search->filterByRef($ref, Criteria::IN);
     }
     $title = $this->getTitle();
     if (!is_null($title)) {
         $search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END " . Criteria::LIKE . " ?", "%" . $title . "%", \PDO::PARAM_STR);
     }
     $manualOrderAllowed = false;
     if (null !== ($categoryDefault = $this->getCategoryDefault())) {
         // Select the products which have $categoryDefault as the default category.
         $search->useProductCategoryQuery('DefaultCategorySelect')->filterByDefaultCategory(true)->filterByCategoryId($categoryDefault, Criteria::IN)->endUse();
         // We can only sort by position if we have a single category ID
         $manualOrderAllowed = 1 == count($categoryDefault);
     }
     if (null !== ($categoryIdList = $this->getCategory())) {
         // Select all products which have one of the required categories as the default one, or an associated one
         $depth = $this->getDepth();
         $allCategoryIDs = CategoryQuery::getCategoryTreeIds($categoryIdList, $depth);
         $search->useProductCategoryQuery('CategorySelect')->filterByCategoryId($allCategoryIDs, Criteria::IN)->endUse();
         // We can only sort by position if we have a single category ID, with a depth of 1
         $manualOrderAllowed = 1 == $depth && 1 == count($categoryIdList);
     }
     $current = $this->getCurrent();
     if ($current === true) {
         $search->filterById($this->request->get("product_id"), Criteria::EQUAL);
     } elseif ($current === false) {
         $search->filterById($this->request->get("product_id"), Criteria::NOT_IN);
     }
     $brand_id = $this->getBrand();
     if ($brand_id !== null) {
         $search->filterByBrandId($brand_id, Criteria::IN);
     }
     $sale_id = $this->getSale();
     if ($sale_id !== null) {
         $search->useSaleProductQuery("SaleProductSelect")->filterBySaleId($sale_id)->groupByProductId()->endUse();
     }
     $current_category = $this->getCurrent_category();
     if ($current_category === true) {
         $search->filterByCategory(CategoryQuery::create()->filterByProduct(ProductCategoryQuery::create()->findPk($this->request->get("product_id")), Criteria::IN)->find(), Criteria::IN);
     } elseif ($current_category === false) {
         $search->filterByCategory(CategoryQuery::create()->filterByProduct(ProductCategoryQuery::create()->findPk($this->request->get("product_id")), Criteria::IN)->find(), Criteria::NOT_IN);
     }
     $visible = $this->getVisible();
     if ($visible !== Type\BooleanOrBothType::ANY) {
         $search->filterByVisible($visible ? 1 : 0);
     }
     $virtual = $this->getVirtual();
     if ($virtual !== Type\BooleanOrBothType::ANY) {
         $search->filterByVirtual($virtual ? 1 : 0);
     }
     $exclude = $this->getExclude();
     if (!is_null($exclude)) {
         $search->filterById($exclude, Criteria::NOT_IN);
     }
     $exclude_category = $this->getExclude_category();
     if (!is_null($exclude_category)) {
         $search->useProductCategoryQuery('ExcludeCategorySelect')->filterByCategoryId($exclude_category, Criteria::NOT_IN)->endUse();
     }
     $new = $this->getNew();
     $promo = $this->getPromo();
     $min_stock = $this->getMin_stock();
     $min_weight = $this->getMin_weight();
     $max_weight = $this->getMax_weight();
     $min_price = $this->getMin_price();
     $max_price = $this->getMax_price();
     if ($complex) {
         if ($new === true) {
             $isPSELeftJoinList[] = 'is_new';
             $search->joinProductSaleElements('is_new', Criteria::LEFT_JOIN)->where('`is_new`.NEWNESS' . Criteria::EQUAL . '1')->where('NOT ISNULL(`is_new`.ID)');
         } elseif ($new === false) {
             $isPSELeftJoinList[] = 'is_new';
             $search->joinProductSaleElements('is_new', Criteria::LEFT_JOIN)->where('`is_new`.NEWNESS' . Criteria::EQUAL . '0')->where('NOT ISNULL(`is_new`.ID)');
         }
         if ($promo === true) {
             $isPSELeftJoinList[] = 'is_promo';
             $search->joinProductSaleElements('is_promo', Criteria::LEFT_JOIN)->where('`is_promo`.PROMO' . Criteria::EQUAL . '1')->where('NOT ISNULL(`is_promo`.ID)');
         } elseif ($promo === false) {
             $isPSELeftJoinList[] = 'is_promo';
             $search->joinProductSaleElements('is_promo', Criteria::LEFT_JOIN)->where('`is_promo`.PROMO' . Criteria::EQUAL . '0')->where('NOT ISNULL(`is_promo`.ID)');
         }
         if (null != $min_stock) {
             $isPSELeftJoinList[] = 'is_min_stock';
             $search->joinProductSaleElements('is_min_stock', Criteria::LEFT_JOIN)->where('`is_min_stock`.QUANTITY' . Criteria::GREATER_THAN . '?', $min_stock, \PDO::PARAM_INT)->where('NOT ISNULL(`is_min_stock`.ID)');
         }
         if (null != $min_weight) {
             $isPSELeftJoinList[] = 'is_min_weight';
             $search->joinProductSaleElements('is_min_weight', Criteria::LEFT_JOIN)->where('`is_min_weight`.WEIGHT' . Criteria::GREATER_THAN . '?', $min_weight, \PDO::PARAM_STR)->where('NOT ISNULL(`is_min_weight`.ID)');
         }
         if (null != $max_weight) {
             $isPSELeftJoinList[] = 'is_max_weight';
             $search->joinProductSaleElements('is_max_weight', Criteria::LEFT_JOIN)->where('`is_max_weight`.WEIGHT' . Criteria::LESS_THAN . '?', $max_weight, \PDO::PARAM_STR)->where('NOT ISNULL(`is_max_weight`.ID)');
         }
         $attributeNonStrictMatch = $this->getAttribute_non_strict_match();
         if ($attributeNonStrictMatch != '*') {
             if ($attributeNonStrictMatch == 'none') {
                 $actuallyUsedAttributeNonStrictMatchList = $isPSELeftJoinList;
             } else {
                 $actuallyUsedAttributeNonStrictMatchList = array_values(array_intersect($isPSELeftJoinList, $attributeNonStrictMatch));
             }
             foreach ($actuallyUsedAttributeNonStrictMatchList as $key => $actuallyUsedAttributeNonStrictMatch) {
                 if ($key == 0) {
                     continue;
                 }
                 $search->where('`' . $actuallyUsedAttributeNonStrictMatch . '`.ID=' . '`' . $actuallyUsedAttributeNonStrictMatchList[$key - 1] . '`.ID');
             }
         }
         if (null !== $min_price) {
             if (false === ConfigQuery::useTaxFreeAmounts()) {
                 // @todo
             }
             $isPSELeftJoinList[] = 'is_min_price';
             $isProductPriceFirstLeftJoin = ['is_min_price', 'min_price_data'];
             $minPriceJoin = new Join();
             $minPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_min_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'min_price_data');
             $minPriceJoin->setJoinType(Criteria::LEFT_JOIN);
             $search->joinProductSaleElements('is_min_price', Criteria::LEFT_JOIN)->addJoinObject($minPriceJoin, 'is_min_price_join')->addJoinCondition('is_min_price_join', '`min_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT);
             if ($defaultCurrency->getId() != $currency->getId()) {
                 $minPriceJoinDefaultCurrency = new Join();
                 $minPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_min_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'min_price_data' . $defaultCurrencySuffix);
                 $minPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN);
                 $search->addJoinObject($minPriceJoinDefaultCurrency, 'is_min_price_join' . $defaultCurrencySuffix)->addJoinCondition('is_min_price_join' . $defaultCurrencySuffix, '`min_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT);
                 /**
                  * In propel we trust : $currency->getRate() always returns a float.
                  * Or maybe not : rate value is checked as a float in overloaded getRate method.
                  */
                 $MinPriceToCompareAsSQL = 'CASE WHEN ISNULL(CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END) OR `min_price_data`.FROM_DEFAULT_CURRENCY = 1 THEN
                 CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data' . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `min_price_data' . $defaultCurrencySuffix . '`.PRICE END * ' . $currency->getRate() . '
             ELSE
                 CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END
             END';
             } else {
                 $MinPriceToCompareAsSQL = 'CASE WHEN `is_min_price`.PROMO=1 THEN `min_price_data`.PROMO_PRICE ELSE `min_price_data`.PRICE END';
             }
             $search->where('ROUND(' . $MinPriceToCompareAsSQL . ', 2)>=?', $min_price, \PDO::PARAM_STR);
         }
         if (null !== $max_price) {
             $isPSELeftJoinList[] = 'is_max_price';
             $isProductPriceFirstLeftJoin = ['is_max_price', 'max_price_data'];
             $maxPriceJoin = new Join();
             $maxPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_max_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'max_price_data');
             $maxPriceJoin->setJoinType(Criteria::LEFT_JOIN);
             $search->joinProductSaleElements('is_max_price', Criteria::LEFT_JOIN)->addJoinObject($maxPriceJoin, 'is_max_price_join')->addJoinCondition('is_max_price_join', '`max_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT);
             if ($defaultCurrency->getId() != $currency->getId()) {
                 $maxPriceJoinDefaultCurrency = new Join();
                 $maxPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', 'is_max_price', ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'max_price_data' . $defaultCurrencySuffix);
                 $maxPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN);
                 $search->addJoinObject($maxPriceJoinDefaultCurrency, 'is_max_price_join' . $defaultCurrencySuffix)->addJoinCondition('is_max_price_join' . $defaultCurrencySuffix, '`max_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT);
                 /**
                  * In propel we trust : $currency->getRate() always returns a float.
                  * Or maybe not : rate value is checked as a float in overloaded getRate method.
                  */
                 $MaxPriceToCompareAsSQL = 'CASE WHEN ISNULL(CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END) OR `min_price_data`.FROM_DEFAULT_CURRENCY = 1 THEN
                 CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data' . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `max_price_data' . $defaultCurrencySuffix . '`.PRICE END * ' . $currency->getRate() . '
             ELSE
                 CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END
             END';
             } else {
                 $MaxPriceToCompareAsSQL = 'CASE WHEN `is_max_price`.PROMO=1 THEN `max_price_data`.PROMO_PRICE ELSE `max_price_data`.PRICE END';
             }
             $search->where('ROUND(' . $MaxPriceToCompareAsSQL . ', 2)<=?', $max_price, \PDO::PARAM_STR);
         }
         /*
          * for ordering and outputs, the product will be :
          * - new if at least one the criteria matching PSE is new
          * - in promo if at least one the criteria matching PSE is in promo
          */
         /* if we don't have any join yet, let's make a global one */
         if (empty($isProductPriceFirstLeftJoin)) {
             if (count($isPSELeftJoinList) == 0) {
                 $joiningTable = "global";
                 $isPSELeftJoinList[] = $joiningTable;
                 $search->joinProductSaleElements('global', Criteria::LEFT_JOIN);
             } else {
                 $joiningTable = $isPSELeftJoinList[0];
             }
             $isProductPriceFirstLeftJoin = [$joiningTable, 'global_price_data'];
             $globalPriceJoin = new Join();
             $globalPriceJoin->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', $joiningTable, ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'global_price_data');
             $globalPriceJoin->setJoinType(Criteria::LEFT_JOIN);
             $search->addJoinObject($globalPriceJoin, 'global_price_join')->addJoinCondition('global_price_join', '`global_price_data`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT);
             if ($defaultCurrency->getId() != $currency->getId()) {
                 $globalPriceJoinDefaultCurrency = new Join();
                 $globalPriceJoinDefaultCurrency->addExplicitCondition(ProductSaleElementsTableMap::TABLE_NAME, 'ID', $joiningTable, ProductPriceTableMap::TABLE_NAME, 'PRODUCT_SALE_ELEMENTS_ID', 'global_price_data' . $defaultCurrencySuffix);
                 $globalPriceJoinDefaultCurrency->setJoinType(Criteria::LEFT_JOIN);
                 $search->addJoinObject($globalPriceJoinDefaultCurrency, 'global_price_join' . $defaultCurrencySuffix)->addJoinCondition('global_price_join' . $defaultCurrencySuffix, '`global_price_data' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT);
             }
         }
         /*
          * we need to test all promo field from our previous conditions. Indeed ie:
          * product P0, attributes color : red
          * P0red is in promo and is the only attribute combinaton availability.
          * so the product might be consider as in promo (in outputs and ordering)
          * We got the following loop to display in promo AND new product but we don't care it's the same attribute which is new and in promo :
          * {loop type="product" promo="1" new="1" attribute_non_strict_match="promo,new"} {/loop}
          * our request will so far returns 1 line
          *
          * is_promo.ID | is_promo.PROMO | is_promo.NEWNESS | is_new.ID | is_new.PROMO | is_new.NEWNESS
          *      NULL            NULL              NULL        red_id         1               0
          *
          * So that we can say the product is in global promo only with is_promo.PROMO, we must acknowledge it with (is_promo.PROMO OR is_new.PROMO)
          */
         $booleanMatchedPromoList = [];
         $booleanMatchedNewnessList = [];
         foreach ($isPSELeftJoinList as $isPSELeftJoin) {
             $booleanMatchedPromoList[] = '`' . $isPSELeftJoin . '`.PROMO';
             $booleanMatchedNewnessList[] = '`' . $isPSELeftJoin . '`.NEWNESS';
         }
         $search->withColumn('ROUND(MAX(' . implode(' OR ', $booleanMatchedPromoList) . '), 2)', 'main_product_is_promo');
         $search->withColumn('ROUND(MAX(' . implode(' OR ', $booleanMatchedNewnessList) . '), 2)', 'main_product_is_new');
         $booleanMatchedPrice = 'CASE WHEN `' . $isProductPriceFirstLeftJoin[0] . '`.PROMO=1 THEN `' . $isProductPriceFirstLeftJoin[1] . '`.PROMO_PRICE ELSE `' . $isProductPriceFirstLeftJoin[1] . '`.PRICE END';
         $booleanMatchedPriceDefaultCurrency = 'CASE WHEN `' . $isProductPriceFirstLeftJoin[0] . '`.PROMO=1 THEN `' . $isProductPriceFirstLeftJoin[1] . $defaultCurrencySuffix . '`.PROMO_PRICE ELSE `' . $isProductPriceFirstLeftJoin[1] . $defaultCurrencySuffix . '`.PRICE END';
         if ($defaultCurrency->getId() != $currency->getId()) {
             /**
              * In propel we trust : $currency->getRate() always returns a float.
              * Or maybe not : rate value is checked as a float in overloaded getRate method.
              */
             $priceToCompareAsSQL = 'CASE WHEN ISNULL(' . $booleanMatchedPrice . ') THEN ' . $booleanMatchedPriceDefaultCurrency . ' * ' . $currency->getRate() . ' ELSE ' . $booleanMatchedPrice . ' END';
         } else {
             $priceToCompareAsSQL = $booleanMatchedPrice;
         }
         $search->withColumn('ROUND(MAX(' . $priceToCompareAsSQL . '), 2)', 'real_highest_price');
         $search->withColumn('ROUND(MIN(' . $priceToCompareAsSQL . '), 2)', 'real_lowest_price');
     } else {
         if ($new === true) {
             $search->where('`pse`.NEWNESS' . Criteria::EQUAL . '1');
         } elseif ($new === false) {
             $search->where('`pse`.NEWNESS' . Criteria::EQUAL . '0');
         }
         if ($promo === true) {
             $search->where('`pse`.PROMO' . Criteria::EQUAL . '1');
         } elseif ($promo === false) {
             $search->where('`pse`.PROMO' . Criteria::EQUAL . '0');
         }
         if (null != $min_stock) {
             $search->where('`pse`.QUANTITY' . Criteria::GREATER_THAN . '?', $min_stock, \PDO::PARAM_INT);
         }
         if (null != $min_weight) {
             $search->where('`pse`.WEIGHT' . Criteria::GREATER_THAN . '?', $min_weight, \PDO::PARAM_STR);
         }
         if (null != $max_weight) {
             $search->where('`is_max_weight`.WEIGHT' . Criteria::LESS_THAN . '?', $max_weight, \PDO::PARAM_STR);
         }
         if (null !== $min_price) {
             if (false === ConfigQuery::useTaxFreeAmounts()) {
                 // @todo
             }
             $search->where('ROUND(' . $priceToCompareAsSQL . ', 2)>=?', $min_price, \PDO::PARAM_STR);
         }
         if (null !== $max_price) {
             if (false === ConfigQuery::useTaxFreeAmounts()) {
                 // @todo
             }
             $search->where('ROUND(' . $priceToCompareAsSQL . ', 2)<=?', $max_price, \PDO::PARAM_STR);
         }
     }
     // First join sale_product table...
     $search->leftJoinSaleProduct('SaleProductPriceDisplay');
     // ... then the sale table...
     $salesJoin = new Join();
     $salesJoin->addExplicitCondition('SaleProductPriceDisplay', 'SALE_ID', null, SaleTableMap::TABLE_NAME, 'ID', 'SalePriceDisplay');
     $salesJoin->setJoinType(Criteria::LEFT_JOIN);
     $search->addJoinObject($salesJoin, 'SalePriceDisplay')->addJoinCondition('SalePriceDisplay', '`SalePriceDisplay`.`active` = 1');
     // ... to get the DISPLAY_INITIAL_PRICE column !
     $search->withColumn('`SalePriceDisplay`.DISPLAY_INITIAL_PRICE', 'display_initial_price');
     $feature_availability = $this->getFeature_availability();
     $this->manageFeatureAv($search, $feature_availability);
     $feature_values = $this->getFeature_values();
     $this->manageFeatureValue($search, $feature_values);
     $search->groupBy(ProductTableMap::ID);
     if (!$complex) {
         $search->withColumn('`pse`.ID', 'pse_id');
         $search->withColumn('`pse`.NEWNESS', 'is_new');
         $search->withColumn('`pse`.PROMO', 'is_promo');
         $search->withColumn('`pse`.QUANTITY', 'quantity');
         $search->withColumn('`pse`.WEIGHT', 'weight');
         $search->withColumn('`pse`.EAN_CODE', 'ean_code');
         $search->withColumn('COUNT(`pse_count`.ID)', 'pse_count');
     }
     $orders = $this->getOrder();
     foreach ($orders as $order) {
         switch ($order) {
             case "id":
                 $search->orderById(Criteria::ASC);
                 break;
             case "id_reverse":
                 $search->orderById(Criteria::DESC);
                 break;
             case "alpha":
                 $search->addAscendingOrderByColumn('i18n_TITLE');
                 break;
             case "alpha_reverse":
                 $search->addDescendingOrderByColumn('i18n_TITLE');
                 break;
             case "min_price":
                 if ($complex) {
                     $search->addAscendingOrderByColumn('real_lowest_price', Criteria::ASC);
                 } else {
                     $search->addAscendingOrderByColumn('real_price');
                 }
                 break;
             case "max_price":
                 if ($complex) {
                     $search->addDescendingOrderByColumn('real_lowest_price');
                 } else {
                     $search->addDescendingOrderByColumn('real_price');
                 }
                 break;
             case "manual":
                 if (!$manualOrderAllowed) {
                     throw new \InvalidArgumentException('Manual order require a *single* category ID or category_default ID, and a depth <= 1');
                 }
                 $search->orderByPosition(Criteria::ASC);
                 break;
             case "manual_reverse":
                 if (!$manualOrderAllowed) {
                     throw new \InvalidArgumentException('Manual reverse order require a *single* category ID or category_default ID, and a depth <= 1');
                 }
                 $search->orderByPosition(Criteria::DESC);
                 break;
             case "ref":
                 $search->orderByRef(Criteria::ASC);
                 break;
             case "ref_reverse":
                 $search->orderByRef(Criteria::DESC);
                 break;
             case "promo":
                 if ($complex) {
                     $search->addDescendingOrderByColumn('main_product_is_promo');
                 } else {
                     $search->addDescendingOrderByColumn('is_promo');
                 }
                 break;
             case "new":
                 if ($complex) {
                     $search->addDescendingOrderByColumn('main_product_is_new');
                 } else {
                     $search->addDescendingOrderByColumn('is_new');
                 }
                 break;
             case "created":
                 $search->addAscendingOrderByColumn('created_at');
                 break;
             case "created_reverse":
                 $search->addDescendingOrderByColumn('created_at');
                 break;
             case "updated":
                 $search->addAscendingOrderByColumn('updated_at');
                 break;
             case "updated_reverse":
                 $search->addDescendingOrderByColumn('updated_at');
                 break;
             case "given_id":
                 if (null === $id) {
                     throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
                 }
                 foreach ($id as $singleId) {
                     $givenIdMatched = 'given_id_matched_' . $singleId;
                     $search->withColumn(ProductTableMap::ID . "='{$singleId}'", $givenIdMatched);
                     $search->orderBy($givenIdMatched, Criteria::DESC);
                 }
                 break;
             case "random":
                 $search->clearOrderByColumns();
                 $search->addAscendingOrderByColumn('RAND()');
                 break 2;
         }
     }
     return $search;
 }
 public function buildModelCriteria()
 {
     $search = ProductSaleElementsQuery::create();
     $id = $this->getId();
     $product = $this->getProduct();
     $ref = $this->getRef();
     if (!is_null($id)) {
         $search->filterById($id, Criteria::IN);
     } elseif (!is_null($product)) {
         $search->filterByProductId($product, Criteria::EQUAL);
     } elseif (!is_null($ref)) {
         $search->filterByRef($ref, Criteria::EQUAL);
     } else {
         $searchTerm = $this->getArgValue('search_term');
         $searchIn = $this->getArgValue('search_in');
         if (null === $searchTerm || null === $searchIn) {
             throw new \InvalidArgumentException("Either 'id', 'product', 'ref', 'search_term/search_in' argument should be present");
         }
     }
     $promo = $this->getPromo();
     if (null !== $promo) {
         $search->filterByPromo($promo);
     }
     $new = $this->getNew();
     if (null !== $new) {
         $search->filterByNewness($new);
     }
     $default = $this->getDefault();
     if (null !== $default) {
         $search->filterByIsDefault($default);
     }
     $orders = $this->getOrder();
     foreach ($orders as $order) {
         switch ($order) {
             case "quantity":
                 $search->orderByQuantity(Criteria::ASC);
                 break;
             case "quantity_reverse":
                 $search->orderByQuantity(Criteria::DESC);
                 break;
             case "min_price":
                 $search->addAscendingOrderByColumn('price_FINAL_PRICE', Criteria::ASC);
                 break;
             case "max_price":
                 $search->addDescendingOrderByColumn('price_FINAL_PRICE');
                 break;
             case "promo":
                 $search->orderByPromo(Criteria::DESC);
                 break;
             case "new":
                 $search->orderByNewness(Criteria::DESC);
                 break;
             case "random":
                 $search->clearOrderByColumns();
                 $search->addAscendingOrderByColumn('RAND()');
                 break 2;
         }
     }
     $currencyId = $this->getCurrency();
     if (null !== $currencyId) {
         $currency = CurrencyQuery::create()->findPk($currencyId);
         if (null === $currency) {
             throw new \InvalidArgumentException('Cannot found currency id: `' . $currency . '` in product_sale_elements loop');
         }
     } else {
         $currency = $this->request->getSession()->getCurrency();
     }
     $defaultCurrency = CurrencyQuery::create()->findOneByByDefault(1);
     $defaultCurrencySuffix = '_default_currency';
     $search->joinProductPrice('price', Criteria::LEFT_JOIN)->addJoinCondition('price', '`price`.`currency_id` = ?', $currency->getId(), null, \PDO::PARAM_INT);
     $search->joinProductPrice('price' . $defaultCurrencySuffix, Criteria::LEFT_JOIN)->addJoinCondition('price_default_currency', '`price' . $defaultCurrencySuffix . '`.`currency_id` = ?', $defaultCurrency->getId(), null, \PDO::PARAM_INT);
     /**
      * rate value is checked as a float in overloaded getRate method.
      */
     $priceSelectorAsSQL = 'ROUND(CASE WHEN ISNULL(`price`.PRICE) OR `price`.FROM_DEFAULT_CURRENCY = 1 THEN `price_default_currency`.PRICE * ' . $currency->getRate() . ' ELSE `price`.PRICE END, 2)';
     $promoPriceSelectorAsSQL = 'ROUND(CASE WHEN ISNULL(`price`.PRICE) OR `price`.FROM_DEFAULT_CURRENCY = 1 THEN `price_default_currency`.PROMO_PRICE  * ' . $currency->getRate() . ' ELSE `price`.PROMO_PRICE END, 2)';
     $search->withColumn($priceSelectorAsSQL, 'price_PRICE')->withColumn($promoPriceSelectorAsSQL, 'price_PROMO_PRICE')->withColumn('CASE WHEN ' . ProductSaleElementsTableMap::PROMO . ' = 1 THEN ' . $promoPriceSelectorAsSQL . ' ELSE ' . $priceSelectorAsSQL . ' END', 'price_FINAL_PRICE');
     $search->groupById();
     return $search;
 }
示例#28
0
 public static function tearDownAfterClass()
 {
     CurrencyQuery::create()->addAscendingOrderByColumn('RAND()')->limit(1)->update(array('ByDefault' => true));
 }
示例#29
0
 /**
  * Get the current edition currency ID, checking if a change was requested in the current request.
  */
 protected function getCurrentEditionCurrency()
 {
     // Return the new language if a change is required.
     if (null !== ($edit_currency_id = $this->getRequest()->get('edit_currency_id', null))) {
         if (null !== ($edit_currency = CurrencyQuery::create()->findOneById($edit_currency_id))) {
             return $edit_currency;
         }
     }
     // Otherwise return the lang stored in session.
     return $this->getSession()->getAdminEditionCurrency();
 }
 protected function defineCurrency(Request $request)
 {
     $currency = null;
     if ($request->query->has("currency")) {
         $currency = CurrencyQuery::create()->findOneByCode($request->query->get("currency"));
         if ($currency) {
             if (false === $this->app->getContainer()->isScopeActive('request')) {
                 $this->app->getContainer()->enterScope('request');
                 $this->app->getContainer()->set('request', $request, 'request');
             }
             $this->eventDispatcher->dispatch(TheliaEvents::CHANGE_DEFAULT_CURRENCY, new CurrencyChangeEvent($currency, $request));
         }
     } else {
         $currency = $request->getSession()->getCurrency(false);
     }
     if (null === $currency) {
         $currency = Currency::getDefaultCurrency();
     }
     return $currency;
 }