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; }
/** * * add an article in the current cart * @param \Thelia\Core\Event\Cart\CartEvent $event */ public function addItem(CartEvent $event) { $cart = $event->getCart(); $newness = $event->getNewness(); $append = $event->getAppend(); $quantity = $event->getQuantity(); $currency = $cart->getCurrency(); $customer = $cart->getCustomer(); $discount = 0; if (null !== $customer && $customer->getDiscount() > 0) { $discount = $customer->getDiscount(); } $productSaleElementsId = $event->getProductSaleElementsId(); $productId = $event->getProduct(); $cartItem = $this->findItem($cart->getId(), $productId, $productSaleElementsId); if ($cartItem === null || $newness) { $productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId); if (null !== $productSaleElements) { $productPrices = $productSaleElements->getPricesByCurrency($currency, $discount); $event->setCartItem($this->doAddItem($event->getDispatcher(), $cart, $productId, $productSaleElements, $quantity, $productPrices)); } } if ($append && $cartItem !== null) { $cartItem->addQuantity($quantity)->save(); $event->setCartItem($cartItem); } }
public function testImport() { $currency = Currency::getDefaultCurrency(); $query = ProductSaleElementsQuery::create()->addAscendingOrderByColumn('RAND()')->limit(3)->find(); $jsonData = []; $data = []; /** @var \Thelia\Model\ProductSaleElements $pse */ foreach ($query as $pse) { $entry = []; $entry["ref"] = $pse->getRef(); /** * Be sure to get a different value. */ while ($pse->getPricesByCurrency($currency)->getPrice() === ($entry["price"] = rand(0, 1000))) { } while ($pse->getPricesByCurrency($currency)->getPromoPrice() === ($entry["promo_price"] = rand(0, 1000))) { } while ($pse->getPromo() === ($entry["promo_price"] = rand(0, 1000))) { } $data[$pse->getId()] = $entry; $jsonData[] = $entry; } $jsonString = json_encode($jsonData); $this->assertEquals("Import successfully done, 3 row(s) have been changed", $this->controller->processImport($jsonString, $this->import, new JsonFormatter(), null)); $query = ProductSaleElementsQuery::create()->findPks(array_keys($data)); /** @var \Thelia\Model\ProductSaleElements $entry */ foreach ($query as $entry) { $this->assertEquals($data[$entry->getId()], ["price" => $entry->getPricesByCurrency($currency)->getPrice(), "promo_price" => $entry->getPricesByCurrency($currency)->getPromoPrice(), "ref" => $entry->getRef()]); } }
public function testUpdateStock() { $query = ProductSaleElementsQuery::create()->addAscendingOrderByColumn('RAND()')->limit(3)->find(); $jsonData = []; $data = []; /** @var \Thelia\Model\ProductSaleElements $pse */ foreach ($query as $pse) { $entry = []; $entry["id"] = $pse->getId(); /** * Be sure to get a different value. */ while ($pse->getQuantity() === ($entry["stock"] = rand(0, 1000))) { } $data[$pse->getId()] = $entry["stock"]; $jsonData[] = $entry; } $jsonString = json_encode($jsonData); $this->assertEquals("Import successfully done, 3 row(s) have been changed", $this->controller->processImport($jsonString, $this->import, new JsonFormatter(), null)); $query = ProductSaleElementsQuery::create()->findPks(array_keys($data)); /** @var \Thelia\Model\ProductSaleElements $entry */ foreach ($query as $entry) { $this->assertEquals($data[$entry->getId()], $entry->getQuantity()); } }
/** Todo Remove this function replaced by statusBatch()*/ public function getGoogleProduct($id) { $query = $this->getRequest()->query; $merchantId = $query->get('account'); $targetCountry = CountryQuery::create()->findOneById($query->get('country')); if ($targetCountry) { $isoAlpha2 = $targetCountry->getIsoalpha2(); } else { $isoAlpha2 = Country::getDefaultCountry()->getIsoalpha2(); } $lang = LangQuery::create()->findOneById($query->get('lang')); if ($lang) { $langCode = $lang->getCode(); } else { $langCode = Lang::getDefaultLanguage()->getCode(); } $productSaleElements = ProductSaleElementsQuery::create()->findOneByProductId($id); $googleProductId = "online:" . $langCode . ":" . $isoAlpha2 . ":" . $productSaleElements->getId(); try { $googleShoppingHandler = new GoogleShoppingHandler($this->container, $this->getRequest()); $client = $googleShoppingHandler->createGoogleClient(); $googleShoppingService = new \Google_Service_ShoppingContent($client); $googleProduct = $googleShoppingService->products->get($merchantId, $googleProductId); $response = ["id" => $googleProduct->getOfferId(), "identifier" => $googleProduct->getIdentifierExists()]; return new JsonResponse($response); } catch (\Exception $e) { return new JsonResponse(); } }
/** * @param Lang $lang * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria|\Thelia\Core\Template\Element\BaseLoop */ public function buildDataSet(Lang $lang) { $locale = $lang->getLocale(); $productJoin = new Join(ProductTableMap::ID, ProductI18nTableMap::ID, Criteria::LEFT_JOIN); $attributeAvJoin = new Join(AttributeAvTableMap::ID, AttributeAvI18nTableMap::ID, Criteria::LEFT_JOIN); $query = ProductSaleElementsQuery::create()->useProductPriceQuery()->useCurrencyQuery()->addAsColumn("currency_CODE", CurrencyTableMap::CODE)->endUse()->addAsColumn("price_PRICE", ProductPriceTableMap::PRICE)->addAsColumn("price_PROMO_PRICE", ProductPriceTableMap::PROMO_PRICE)->endUse()->useProductQuery()->addJoinObject($productJoin, "product_join")->addJoinCondition("product_join", ProductI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR)->addAsColumn("product_TITLE", ProductI18nTableMap::TITLE)->addAsColumn("product_ID", ProductTableMap::ID)->endUse()->useAttributeCombinationQuery(null, Criteria::LEFT_JOIN)->useAttributeAvQuery(null, Criteria::LEFT_JOIN)->addJoinObject($attributeAvJoin, "attribute_av_join")->addJoinCondition("attribute_av_join", AttributeAvI18nTableMap::LOCALE . " = ?", $locale, null, \PDO::PARAM_STR)->addAsColumn("attribute_av_i18n_ATTRIBUTES", "GROUP_CONCAT(DISTINCT " . AttributeAvI18nTableMap::TITLE . ")")->endUse()->endUse()->addAsColumn("product_sale_elements_ID", ProductSaleElementsTableMap::ID)->addAsColumn("product_sale_elements_EAN_CODE", ProductSaleElementsTableMap::EAN_CODE)->addAsColumn("product_sale_elements_PROMO", ProductSaleElementsTableMap::PROMO)->select(["product_sale_elements_ID", "product_sale_elements_EAN_CODE", "product_sale_elements_PROMO", "price_PRICE", "price_PROMO_PRICE", "currency_CODE", "product_TITLE", "attribute_av_i18n_ATTRIBUTES"])->orderBy("product_sale_elements_ID")->groupBy("product_sale_elements_ID"); return $query; }
protected function getData() { $locale = $this->language->getLocale(); $productJoin = new Join(ProductTableMap::ID, ProductI18nTableMap::ID, Criteria::LEFT_JOIN); $attributeAvJoin = new Join(AttributeAvTableMap::ID, AttributeAvI18nTableMap::ID, Criteria::LEFT_JOIN); $query = ProductSaleElementsQuery::create()->addSelfSelectColumns()->useProductPriceQuery()->useCurrencyQuery()->withColumn(CurrencyTableMap::CODE)->endUse()->withColumn(ProductPriceTableMap::PRICE)->withColumn(ProductPriceTableMap::PROMO_PRICE)->endUse()->useProductQuery()->addJoinObject($productJoin, 'product_join')->addJoinCondition('product_join', ProductI18nTableMap::LOCALE . ' = ?', $locale, null, \PDO::PARAM_STR)->withColumn(ProductI18nTableMap::TITLE)->withColumn(ProductTableMap::ID)->endUse()->useAttributeCombinationQuery(null, Criteria::LEFT_JOIN)->useAttributeAvQuery(null, Criteria::LEFT_JOIN)->addJoinObject($attributeAvJoin, 'attribute_av_join')->addJoinCondition('attribute_av_join', AttributeAvI18nTableMap::LOCALE . ' = ?', $locale, null, \PDO::PARAM_STR)->addAsColumn('attribute_av_i18n_ATTRIBUTES', 'GROUP_CONCAT(DISTINCT ' . AttributeAvI18nTableMap::TITLE . ')')->endUse()->endUse()->orderBy(ProductSaleElementsTableMap::ID)->groupBy(ProductSaleElementsTableMap::ID); return $query; }
public function checkStock($value, ExecutionContextInterface $context) { $data = $context->getRoot()->getData(); if (null === $data["product_sale_elements_id"]) { $context->addViolationAt("quantity", Translator::getInstance()->trans("Invalid product_sale_elements")); } else { $productSaleElements = ProductSaleElementsQuery::create()->filterById($data["product_sale_elements_id"])->filterByProductId($data["product"])->findOne(); $product = $productSaleElements->getProduct(); if ($productSaleElements->getQuantity() < $value && $product->getVirtual() === 0 && ConfigQuery::checkAvailableStock()) { $context->addViolation(Translator::getInstance()->trans("quantity value is not valid")); } } }
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 { $pse->setQuantity($data['stock']); if (isset($data['ean']) && !empty($data['ean'])) { $pse->setEanCode($data['ean']); } $pse->save(); $this->importedRows++; } return null; }
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"]); } }
public function testAssociatePSEDocument() { /** * Get a product sale elements which has a related product image */ $pse = ProductSaleElementsQuery::create()->useProductQuery()->joinProductDocument()->endUse()->findOne(); if (null === $pse) { $this->markTestSkipped("You must have at least one product_sale_elements which has a product_image related to it's product"); } /** * Get this image and check if they are associated */ $productDocument = ProductDocumentQuery::create()->findOneByProductId($pse->getProductId()); $association = ProductSaleElementsProductDocumentQuery::create()->filterByProductSaleElements($pse)->findOneByProductDocumentId($productDocument->getId()); $isAssociated = $association !== null; $this->controller->getAssociationResponseData($pse->getId(), "document", $productDocument->getId()); $newAssociation = ProductSaleElementsProductDocumentQuery::create()->filterByProductSaleElements($pse)->findOneByProductDocumentId($productDocument->getId()); $isNowAssociated = $newAssociation !== null; $this->assertFalse($isAssociated === $isNowAssociated); }
/** * @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 = []; while (null !== ($row = $data->popRow())) { /** * Check for mandatory columns */ $this->checkMandatoryColumns($row); $obj = ProductSaleElementsQuery::create()->findPk($row["id"]); if ($obj === null) { $errors[] = $this->translator->trans("The product sale element reference %id doesn't exist", ["%id" => $row["id"]]); } else { $obj->setQuantity($row["stock"]); if (isset($row["ean"]) && !empty($row["ean"])) { $obj->setEanCode($row["ean"]); } $obj->save(); $this->importedRows++; } } return $errors; }
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; }
/** * @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; }
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; }
/** * Get the associated ChildProductSaleElements object * * @param ConnectionInterface $con Optional Connection object. * @return ChildProductSaleElements The associated ChildProductSaleElements object. * @throws PropelException */ public function getProductSaleElements(ConnectionInterface $con = null) { if ($this->aProductSaleElements === null && $this->product_sale_elements_id !== null) { $this->aProductSaleElements = ChildProductSaleElementsQuery::create()->findPk($this->product_sale_elements_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->aProductSaleElements->addProductSaleElementsProductDocuments($this); */ } return $this->aProductSaleElements; }
/** * @covers \Thelia\Action\ProductSaleElement::updateClonePSE * @depends testCreateClonePSE * @param array $params * @return array */ public function testUpdateClonePSE(array $params) { $event = $params['event']; $originalPSE = $params['originalPSE']; $clonePSE = $params['clonePSE']; // Call function to test $action = new ProductSaleElement(); $action->updateClonePSE($event, $clonePSE->getId(), $originalPSE, 1); // Get updated PSE $clonePSE = ProductSaleElementsQuery::create()->findOneById($clonePSE->getId()); // Check clone PSE information $this->assertInstanceOf('Thelia\\Model\\ProductSaleElements', $clonePSE, 'Instance of clone PSE must be Thelia\\Model\\ProductSaleElements'); $this->assertStringStartsWith($event->getClonedProduct()->getRef(), $clonePSE->getRef(), 'PSE\'s ref must start with product\'s ref'); $this->assertEquals($originalPSE->getQuantity(), $clonePSE->getQuantity(), 'Quantity must be equal'); $this->assertEquals($originalPSE->getPromo(), $clonePSE->getPromo(), 'Promo must be equal'); $this->assertEquals($originalPSE->getNewness(), $clonePSE->getNewness(), 'Newness must be equal'); $this->assertEquals($originalPSE->getWeight(), $clonePSE->getWeight(), 'Weight must be equal'); $this->assertEquals($originalPSE->getIsDefault(), $clonePSE->getIsDefault(), 'IsDefault must be equal'); $this->assertEquals($originalPSE->getEanCode(), $clonePSE->getEanCode(), 'EAN code must be equal'); // Get PSE's product price $originalProductPrice = ProductPriceQuery::create()->findOneByProductSaleElementsId($originalPSE->getId()); $cloneProductPrice = ProductPriceQuery::create()->findOneByProductSaleElementsId($clonePSE->getId()); // Check clone PSE's product price $this->assertInstanceOf('Thelia\\Model\\ProductPrice', $cloneProductPrice, 'Instance of clone product price must be Thelia\\Model\\ProductPrice'); $this->assertEquals($originalProductPrice->getCurrencyId(), $cloneProductPrice->getCurrencyId(), 'CurrencyID must be equal'); $this->assertEquals($originalProductPrice->getPrice(), $cloneProductPrice->getPrice(), 'Price must be equal'); $this->assertEquals($originalProductPrice->getPromoPrice(), $cloneProductPrice->getPromoPrice(), 'Promo price must be equal'); $this->assertEquals(0, $cloneProductPrice->getFromDefaultCurrency(), 'From default currency must be equal to 0'); return ['event' => $event, 'cloneProductId' => $event->getClonedProduct()->getId(), 'clonePSEId' => $clonePSE->getId(), 'originalPSE' => $originalPSE]; }
public function tntCalculCartWeight(CartEvent $event) { $event->getCart()->setVirtualColumn('total_weight', $event->getCart()->getWeight()); $maxWeightPackage = TNTFrance::getConfigValue(TNTFranceConfigValue::MAX_WEIGHT_PACKAGE, 25); $totalPackage = 0; //If packages are separated per product if (1 == TNTFrance::getConfigValue(TNTFranceConfigValue::SEPARATE_PRODUCT_IN_PACKAGE, 0)) { /** @var \Thelia\Model\CartItem $cartItem */ foreach ($event->getCart()->getCartItems() as $cartItem) { if (null != ($pse = ProductSaleElementsQuery::create()->findPk($cartItem->getProductSaleElementsId()))) { $totalPackage += ceil($cartItem->getQuantity() * $pse->getWeight() / $maxWeightPackage); } } } else { $totalPackage += ceil($event->getCart()->getVirtualColumn('total_weight') / $maxWeightPackage); } $event->getCart()->setVirtualColumn('total_package', $totalPackage); }
/** * Update product quantity if new status is canceled or if old status is canceled. * * @param ModelOrder $order * @param $newStatus * @param $canceledStatus * @throws \Exception * @throws \Propel\Runtime\Exception\PropelException */ protected function updateQuantityForCanceledOrder(ModelOrder $order, $newStatus, $canceledStatus) { $orderProductList = $order->getOrderProducts(); /** @var OrderProduct $orderProduct */ foreach ($orderProductList as $orderProduct) { $productSaleElementsId = $orderProduct->getProductSaleElementsId(); /** @var ProductSaleElements $productSaleElements */ if (null !== ($productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId))) { if ($newStatus == $canceledStatus) { $productSaleElements->setQuantity($productSaleElements->getQuantity() + $orderProduct->getQuantity()); } else { /* check still in stock */ if ($orderProduct->getQuantity() > $productSaleElements->getQuantity() && true === ConfigQuery::checkAvailableStock()) { throw new TheliaProcessException($productSaleElements->getRef() . " : Not enough stock"); } $productSaleElements->setQuantity($productSaleElements->getQuantity() - $orderProduct->getQuantity()); } $productSaleElements->save(); } } }
public function sendEmail(RestockingAlert $subscriber) { $contactEmail = ConfigQuery::read('store_email'); if ($contactEmail) { $message = MessageQuery::create()->filterByName('stockalert_customer')->findOne(); if (null === $message) { throw new \Exception("Failed to load message 'stockalert_customer'."); } $pse = ProductSaleElementsQuery::create()->findPk($subscriber->getProductSaleElementsId()); $this->parser->assign('locale', $subscriber->getLocale()); $this->parser->assign('pse_id', $pse->getId()); $this->parser->assign('product_id', $pse->getProductId()); $message->setLocale($subscriber->getLocale()); $instance = \Swift_Message::newInstance()->addTo($subscriber->getEmail(), ConfigQuery::read('store_name'))->addFrom($contactEmail, ConfigQuery::read('store_name')); // Build subject and body $message->buildMessage($this->parser, $instance); $this->mailer->send($instance); Tlog::getInstance()->debug("Restocking Alert sent to customer " . $subscriber->getEmail()); } else { Tlog::getInstance()->debug("Restocking Alert message no contact email Restocking Alert id", $subscriber->getId()); } }
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; }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see ProductSaleElements::setDeleted() * @see ProductSaleElements::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(ProductSaleElementsTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildProductSaleElementsQuery::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; } }
for ($i = 0; $i < 50; ++$i) { $placedOrder = new \Thelia\Model\Order(); $deliveryOrderAddress = new OrderAddress(); $deliveryOrderAddress->setCustomerTitleId(mt_rand(1, 3))->setCompany(getRealText(15))->setFirstname($faker->firstname)->setLastname($faker->lastname)->setAddress1($faker->streetAddress)->setAddress2($faker->streetAddress)->setAddress3($faker->streetAddress)->setPhone($faker->phoneNumber)->setZipcode($faker->postcode)->setCity($faker->city)->setCountryId(64)->save($con); $invoiceOrderAddress = new OrderAddress(); $invoiceOrderAddress->setCustomerTitleId(mt_rand(1, 3))->setCompany(getRealText(15))->setFirstname($faker->firstname)->setLastname($faker->lastname)->setAddress1($faker->streetAddress)->setAddress2($faker->streetAddress)->setAddress3($faker->streetAddress)->setPhone($faker->phoneNumber)->setZipcode($faker->postcode)->setCity($faker->city)->setCountryId(64)->save($con); /** * Create a cart for the order */ $cart = new \Thelia\Model\Cart(); $cart->save(); $currency = \Thelia\Model\CurrencyQuery::create()->addAscendingOrderByColumn('RAND()')->findOne(); $placedOrder->setDeliveryOrderAddressId($deliveryOrderAddress->getId())->setInvoiceOrderAddressId($invoiceOrderAddress->getId())->setDeliveryModuleId($colissimo_id)->setPaymentModuleId($cheque_id)->setStatusId(mt_rand(1, 5))->setCurrencyRate($currency->getRate())->setCurrencyId($currency->getId())->setCustomer(\Thelia\Model\CustomerQuery::create()->addAscendingOrderByColumn('RAND()')->findOne())->setDiscount(mt_rand(0, 10))->setLang(\Thelia\Model\LangQuery::create()->addAscendingOrderByColumn('RAND()')->findOne())->setPostage(mt_rand(1, 50))->setCartId($cart->getId()); $placedOrder->save($con); for ($j = 0; $j < mt_rand(1, 10); ++$j) { $pse = \Thelia\Model\ProductSaleElementsQuery::create()->addAscendingOrderByColumn('RAND()')->findOne(); $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();
function clearTables($con) { echo "Clearing tables\n"; $productAssociatedContent = Thelia\Model\ProductAssociatedContentQuery::create()->find($con); $productAssociatedContent->delete($con); $categoryAssociatedContent = Thelia\Model\CategoryAssociatedContentQuery::create()->find($con); $categoryAssociatedContent->delete($con); $featureProduct = Thelia\Model\FeatureProductQuery::create()->find($con); $featureProduct->delete($con); $attributeCombination = Thelia\Model\AttributeCombinationQuery::create()->find($con); $attributeCombination->delete($con); $feature = Thelia\Model\FeatureQuery::create()->find($con); $feature->delete($con); $feature = Thelia\Model\FeatureI18nQuery::create()->find($con); $feature->delete($con); $featureAv = Thelia\Model\FeatureAvQuery::create()->find($con); $featureAv->delete($con); $featureAv = Thelia\Model\FeatureAvI18nQuery::create()->find($con); $featureAv->delete($con); $attribute = Thelia\Model\AttributeQuery::create()->find($con); $attribute->delete($con); $attribute = Thelia\Model\AttributeI18nQuery::create()->find($con); $attribute->delete($con); $attributeAv = Thelia\Model\AttributeAvQuery::create()->find($con); $attributeAv->delete($con); $attributeAv = Thelia\Model\AttributeAvI18nQuery::create()->find($con); $attributeAv->delete($con); $brand = Thelia\Model\BrandQuery::create()->find($con); $brand->delete($con); $brand = Thelia\Model\BrandI18nQuery::create()->find($con); $brand->delete($con); $category = Thelia\Model\CategoryQuery::create()->find($con); $category->delete($con); $category = Thelia\Model\CategoryI18nQuery::create()->find($con); $category->delete($con); $product = Thelia\Model\ProductQuery::create()->find($con); $product->delete($con); $product = Thelia\Model\ProductI18nQuery::create()->find($con); $product->delete($con); $folder = Thelia\Model\FolderQuery::create()->find($con); $folder->delete($con); $folder = Thelia\Model\FolderI18nQuery::create()->find($con); $folder->delete($con); $content = Thelia\Model\ContentQuery::create()->find($con); $content->delete($con); $content = Thelia\Model\ContentI18nQuery::create()->find($con); $content->delete($con); $accessory = Thelia\Model\AccessoryQuery::create()->find($con); $accessory->delete($con); $stock = \Thelia\Model\ProductSaleElementsQuery::create()->find($con); $stock->delete($con); $productPrice = \Thelia\Model\ProductPriceQuery::create()->find($con); $productPrice->delete($con); \Thelia\Model\ProductImageQuery::create()->find($con)->delete($con); $customer = Thelia\Model\CustomerQuery::create()->find($con); $customer->delete($con); echo "Tables cleared with success\n"; }
/** * Clear all sales * * @param SaleClearStatusEvent $event * @throws \Propel\Runtime\Exception\PropelException */ public function clearStatus(SaleClearStatusEvent $event) { $con = Propel::getWriteConnection(SaleTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Set the active status of all Sales to false SaleQuery::create()->filterByActive(true)->update(['Active' => false], $con); // Reset all sale status on PSE ProductSaleElementsQuery::create()->filterByPromo(true)->update(['Promo' => false], $con); $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } }
/** * Gets the number of ChildProductSaleElements objects related by a many-to-many relationship * to the current object by way of the product_sale_elements_product_image cross-reference table. * * @param Criteria $criteria Optional query object to filter the query * @param boolean $distinct Set to true to force count distinct * @param ConnectionInterface $con Optional connection object * * @return int the number of related ChildProductSaleElements objects */ public function countProductSaleElementss($criteria = null, $distinct = false, ConnectionInterface $con = null) { if (null === $this->collProductSaleElementss || null !== $criteria) { if ($this->isNew() && null === $this->collProductSaleElementss) { return 0; } else { $query = ChildProductSaleElementsQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query->filterByProductImage($this)->count($con); } } else { return count($this->collProductSaleElementss); } }
/** * @param FormEvent $event * * Loads initial pse data into a form. * It is used in for a form event on pse update */ public function loadProductSaleElements(FormEvent $event) { $productSaleElementIds = array(); $data = array(); foreach ($event->getData()["pse"] as $entry) { $productSaleElementIds[$entry["id"]] = $entry; } $productSaleElements = ProductSaleElementsQuery::create()->findPks(array_keys($productSaleElementIds)); /** @var ProductSaleElements $productSaleElement */ foreach ($productSaleElements as $productSaleElement) { $product = $productSaleElement->getProduct(); list($price, $salePrice, $currencyId, $fromDefaultCurrency) = $this->retrievePrices($productSaleElement); $data["pse"][$productSaleElement->getId()] = array_merge(["id" => $productSaleElement->getId(), "reference" => $productSaleElement->getRef(), "tax_rule_id" => $product->getTaxRuleId(), "ean_code" => $productSaleElement->getEanCode(), "onsale" => $productSaleElement->getPromo(), "isdefault" => $productSaleElement->getIsDefault(), "isnew" => $productSaleElement->getNewness(), "quantity" => $productSaleElement->getQuantity(), "weight" => $productSaleElement->getWeight(), "price" => $price, "sale_price" => $salePrice, "currency_id" => $currencyId, "use_exchange_rate" => $fromDefaultCurrency], $productSaleElementIds[$productSaleElement->getId()]); } $event->setData($data); }
public function preImport() { // Delete table before proceeding ProductQuery::create()->deleteAll(); ProductImageQuery::create()->deleteAll(); ProductDocumentQuery::create()->deleteAll(); TaxRuleQuery::create()->deleteAll(); TaxQuery::create()->deleteAll(); ProductSaleElementsQuery::create()->deleteAll(); ProductPriceQuery::create()->deleteAll(); // Create T1 <-> T2 IDs correspondance tables $this->product_corresp->reset(); $this->tax_corresp->reset(); // Importer les taxes $this->importTaxes(); }
public function getAjaxProductSaleElementsImagesDocuments($id, $type) { if (null !== $this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW)) { return JsonResponse::createAuthError(AccessManager::VIEW); } $this->checkXmlHttpRequest(); $pse = ProductSaleElementsQuery::create()->findPk($id); $errorMessage = $this->checkFileType($type); if (null === $pse && null === $errorMessage) { $type = null; $errorMessage = $this->getTranslator()->trans("The product sale elements id %id doesn't exist", ["%id" => $pse->getId()]); } switch ($type) { case "image": $modalTitle = $this->getTranslator()->trans("Associate images"); $data = $this->getPSEImages($pse); break; case "document": $modalTitle = $this->getTranslator()->trans("Associate documents"); $data = $this->getPSEDocuments($pse); break; case "virtual": $modalTitle = $this->getTranslator()->trans("Select the virtual document"); $data = $this->getPSEVirtualDocument($pse); break; case null: default: $modalTitle = $this->getTranslator()->trans("Unsupported type"); $data = []; } if (empty($data) && null === $errorMessage) { $errorMessage = $this->getTranslator()->trans("There are no files to associate."); if ($type === "virtual") { $errorMessage .= $this->getTranslator()->trans(" note: only non-visible documents can be associated."); } } $this->getParserContext()->set("items", $data)->set("type", $type)->set("error_message", $errorMessage)->set("modal_title", $modalTitle); return $this->render("ajax/pse-image-document-assoc-modal"); }