Ejemplo n.º 1
0
 /**
  * Duplicate the current existing cart. Only the token is changed
  *
  * @param string $token
  * @param Customer $customer
  * @param Currency $currency
  * @param EventDispatcherInterface $dispatcher
  * @return Cart
  * @throws \Exception
  * @throws \Propel\Runtime\Exception\PropelException
  */
 public function duplicate($token, Customer $customer = null, Currency $currency = null, EventDispatcherInterface $dispatcher = null)
 {
     if (!$dispatcher) {
         return false;
     }
     $cartItems = $this->getCartItems();
     $cart = new Cart();
     $cart->setAddressDeliveryId($this->getAddressDeliveryId());
     $cart->setAddressInvoiceId($this->getAddressInvoiceId());
     $cart->setToken($token);
     $discount = 0;
     if (null === $currency) {
         $currencyQuery = CurrencyQuery::create();
         $currency = $currencyQuery->findPk($this->getCurrencyId()) ?: $currencyQuery->findOneByByDefault(1);
     }
     $cart->setCurrency($currency);
     if ($customer) {
         $cart->setCustomer($customer);
         if ($customer->getDiscount() > 0) {
             $discount = $customer->getDiscount();
         }
     }
     $cart->save();
     foreach ($cartItems as $cartItem) {
         $product = $cartItem->getProduct();
         $productSaleElements = $cartItem->getProductSaleElements();
         if ($product && $productSaleElements && $product->getVisible() == 1 && ($productSaleElements->getQuantity() >= $cartItem->getQuantity() || $product->getVirtual() === 1 || !ConfigQuery::checkAvailableStock())) {
             $item = new CartItem();
             $item->setCart($cart);
             $item->setProductId($cartItem->getProductId());
             $item->setQuantity($cartItem->getQuantity());
             $item->setProductSaleElements($productSaleElements);
             $prices = $productSaleElements->getPricesByCurrency($currency, $discount);
             $item->setPrice($prices->getPrice())->setPromoPrice($prices->getPromoPrice())->setPromo($productSaleElements->getPromo());
             $item->save();
             $dispatcher->dispatch(TheliaEvents::CART_ITEM_DUPLICATE, new CartItemDuplicationItem($item, $cartItem));
         }
     }
     try {
         $this->delete();
     } catch (\Exception $e) {
         // just fail silently in some cases
     }
     return $cart;
 }
Ejemplo n.º 2
0
 /**
  * Filter the query by a related \Thelia\Model\Cart object
  *
  * @param \Thelia\Model\Cart|ObjectCollection $cart The related object(s) to use as filter
  * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
  *
  * @return ChildCartItemQuery The current query, for fluid interface
  */
 public function filterByCart($cart, $comparison = null)
 {
     if ($cart instanceof \Thelia\Model\Cart) {
         return $this->addUsingAlias(CartItemTableMap::CART_ID, $cart->getId(), $comparison);
     } elseif ($cart instanceof ObjectCollection) {
         if (null === $comparison) {
             $comparison = Criteria::IN;
         }
         return $this->addUsingAlias(CartItemTableMap::CART_ID, $cart->toKeyValue('PrimaryKey', 'Id'), $comparison);
     } else {
         throw new PropelException('filterByCart() only accepts arguments of type \\Thelia\\Model\\Cart or Collection');
     }
 }
Ejemplo n.º 3
0
 /**
  * Filter the query by a related \Thelia\Model\Cart object
  *
  * @param \Thelia\Model\Cart|ObjectCollection $cart  the related object to use as filter
  * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
  *
  * @return ChildCurrencyQuery The current query, for fluid interface
  */
 public function filterByCart($cart, $comparison = null)
 {
     if ($cart instanceof \Thelia\Model\Cart) {
         return $this->addUsingAlias(CurrencyTableMap::ID, $cart->getCurrencyId(), $comparison);
     } elseif ($cart instanceof ObjectCollection) {
         return $this->useCartQuery()->filterByPrimaryKeys($cart->getPrimaryKeys())->endUse();
     } else {
         throw new PropelException('filterByCart() only accepts arguments of type \\Thelia\\Model\\Cart or Collection');
     }
 }
Ejemplo n.º 4
0
 public function testGetCartWithExistingCartAndCustomerAndReferencesEachOther()
 {
     $session = $this->session;
     //create a fake customer just for test. If not persists test fails !
     $customer = new Customer();
     $customer->setFirstname("john test session");
     $customer->setLastname("doe");
     $customer->setTitleId(1);
     $customer->save();
     $session->setCustomerUser($customer);
     $testCart = new Cart();
     $testCart->setToken(uniqid("testSessionGetCart3", true));
     $testCart->setCustomerId($customer->getId());
     $testCart->save();
     $this->request->cookies->set(ConfigQuery::read("cart.cookie_name", 'thelia_cart'), $testCart->getToken());
     $cart = $session->getSessionCart($this->dispatcher);
     $this->assertNotNull($cart);
     $this->assertInstanceOf("\\Thelia\\Model\\Cart", $cart, '$cart must be an instance of Thelia\\Model\\Cart');
 }
Ejemplo n.º 5
0
 /**
  * A cart is valid if its customer ID is the same as the current logged in user
  *
  * @param Cart $cart The cart to check
  *
  * @return bool true if the cart is valid, false otherwise
  */
 protected function isValidCart(Cart $cart)
 {
     $customer = $this->getCustomerUser();
     return null !== $customer && $cart->getCustomerId() == $customer->getId() || null === $customer && $cart->getCustomerId() === null;
 }
Ejemplo n.º 6
0
 public function testCreate()
 {
     $validDeliveryAddress = AddressQuery::create()->findOneByCustomerId($this->customer->getId());
     $validInvoiceAddress = AddressQuery::create()->filterById($validDeliveryAddress->getId(), Criteria::NOT_EQUAL)->findOneByCustomerId($this->customer->getId());
     $deliveryModule = ModuleQuery::create()->filterByType(BaseModule::DELIVERY_MODULE_TYPE)->filterByActivate(1)->findOne();
     if (null === $deliveryModule) {
         throw new \Exception('No Delivery Module fixture found');
     }
     $paymentModule = ModuleQuery::create()->filterByType(BaseModule::PAYMENT_MODULE_TYPE)->filterByActivate(1)->findOne();
     if (null === $paymentModule) {
         throw new \Exception('No Payment Module fixture found');
     }
     /* define payment module in container */
     $paymentModuleClass = $paymentModule->getFullNamespace();
     $this->container->set(sprintf('module.%s', $paymentModule->getCode()), new $paymentModuleClass());
     $this->orderEvent->getOrder()->setChoosenDeliveryAddress($validDeliveryAddress->getId());
     $this->orderEvent->getOrder()->setChoosenInvoiceAddress($validInvoiceAddress->getId());
     $this->orderEvent->getOrder()->setDeliveryModuleId($deliveryModule->getId());
     $this->orderEvent->getOrder()->setPostage(20);
     $this->orderEvent->getOrder()->setPaymentModuleId($paymentModule->getId());
     /* memorize current stocks */
     $itemsStock = array();
     foreach ($this->cartItems as $index => $cartItem) {
         $itemsStock[$index] = $cartItem->getProductSaleElements()->getQuantity();
     }
     $this->orderAction->create($this->orderEvent);
     $placedOrder = $this->orderEvent->getPlacedOrder();
     $this->assertNotNull($placedOrder);
     $this->assertNotNull($placedOrder->getId());
     /* check customer */
     $this->assertEquals($this->customer->getId(), $placedOrder->getCustomerId(), 'customer i does not  match');
     /* check delivery address */
     $deliveryOrderAddress = $placedOrder->getOrderAddressRelatedByDeliveryOrderAddressId();
     $this->assertEquals($validDeliveryAddress->getCustomerTitle()->getId(), $deliveryOrderAddress->getCustomerTitleId(), 'delivery address title does not match');
     $this->assertEquals($validDeliveryAddress->getCompany(), $deliveryOrderAddress->getCompany(), 'delivery address company does not match');
     $this->assertEquals($validDeliveryAddress->getFirstname(), $deliveryOrderAddress->getFirstname(), 'delivery address fistname does not match');
     $this->assertEquals($validDeliveryAddress->getLastname(), $deliveryOrderAddress->getLastname(), 'delivery address lastname does not match');
     $this->assertEquals($validDeliveryAddress->getAddress1(), $deliveryOrderAddress->getAddress1(), 'delivery address address1 does not match');
     $this->assertEquals($validDeliveryAddress->getAddress2(), $deliveryOrderAddress->getAddress2(), 'delivery address address2 does not match');
     $this->assertEquals($validDeliveryAddress->getAddress3(), $deliveryOrderAddress->getAddress3(), 'delivery address address3 does not match');
     $this->assertEquals($validDeliveryAddress->getZipcode(), $deliveryOrderAddress->getZipcode(), 'delivery address zipcode does not match');
     $this->assertEquals($validDeliveryAddress->getCity(), $deliveryOrderAddress->getCity(), 'delivery address city does not match');
     $this->assertEquals($validDeliveryAddress->getPhone(), $deliveryOrderAddress->getPhone(), 'delivery address phone does not match');
     $this->assertEquals($validDeliveryAddress->getCountryId(), $deliveryOrderAddress->getCountryId(), 'delivery address country does not match');
     /* check invoice address */
     $invoiceOrderAddress = $placedOrder->getOrderAddressRelatedByInvoiceOrderAddressId();
     $this->assertEquals($validInvoiceAddress->getCustomerTitle()->getId(), $invoiceOrderAddress->getCustomerTitleId(), 'invoice address title does not match');
     $this->assertEquals($validInvoiceAddress->getCompany(), $invoiceOrderAddress->getCompany(), 'invoice address company does not match');
     $this->assertEquals($validInvoiceAddress->getFirstname(), $invoiceOrderAddress->getFirstname(), 'invoice address fistname does not match');
     $this->assertEquals($validInvoiceAddress->getLastname(), $invoiceOrderAddress->getLastname(), 'invoice address lastname does not match');
     $this->assertEquals($validInvoiceAddress->getAddress1(), $invoiceOrderAddress->getAddress1(), 'invoice address address1 does not match');
     $this->assertEquals($validInvoiceAddress->getAddress2(), $invoiceOrderAddress->getAddress2(), 'invoice address address2 does not match');
     $this->assertEquals($validInvoiceAddress->getAddress3(), $invoiceOrderAddress->getAddress3(), 'invoice address address3 does not match');
     $this->assertEquals($validInvoiceAddress->getZipcode(), $invoiceOrderAddress->getZipcode(), 'invoice address zipcode does not match');
     $this->assertEquals($validInvoiceAddress->getCity(), $invoiceOrderAddress->getCity(), 'invoice address city does not match');
     $this->assertEquals($validInvoiceAddress->getPhone(), $invoiceOrderAddress->getPhone(), 'invoice address phone does not match');
     $this->assertEquals($validInvoiceAddress->getCountryId(), $invoiceOrderAddress->getCountryId(), 'invoice address country does not match');
     /* check currency */
     $this->assertEquals($this->cart->getCurrencyId(), $placedOrder->getCurrencyId(), 'currency id does not  match');
     $this->assertEquals($this->cart->getCurrency()->getRate(), $placedOrder->getCurrencyRate(), 'currency rate does not  match');
     /* check delivery module */
     $this->assertEquals(20, $placedOrder->getPostage(), 'postage does not  match');
     $this->assertEquals($deliveryModule->getId(), $placedOrder->getDeliveryModuleId(), 'delivery module does not  match');
     /* check payment module */
     $this->assertEquals($paymentModule->getId(), $placedOrder->getPaymentModuleId(), 'payment module does not  match');
     /* check status */
     $this->assertEquals(OrderStatus::CODE_NOT_PAID, $placedOrder->getOrderStatus()->getCode(), 'status does not  match');
     /* check lang */
     $this->assertEquals($this->request->getSession()->getLang()->getId(), $placedOrder->getLangId(), 'lang does not  match');
     /* check ordered product */
     foreach ($this->cartItems as $index => $cartItem) {
         $orderProduct = OrderProductQuery::create()->filterByOrderId($placedOrder->getId())->filterByProductRef($cartItem->getProduct()->getRef())->filterByProductSaleElementsRef($cartItem->getProductSaleElements()->getRef())->filterByQuantity($cartItem->getQuantity())->filterByPrice($cartItem->getPrice(), Criteria::LIKE)->filterByPromoPrice($cartItem->getPromoPrice(), Criteria::LIKE)->filterByWasNew($cartItem->getProductSaleElements()->getNewness())->filterByWasInPromo($cartItem->getPromo())->filterByWeight($cartItem->getProductSaleElements()->getWeight())->findOne();
         $this->assertNotNull($orderProduct);
         /* check attribute combinations */
         $this->assertEquals($cartItem->getProductSaleElements()->getAttributeCombinations()->count(), $orderProduct->getOrderProductAttributeCombinations()->count());
         if ($orderProduct->getVirtual()) {
             /* check same stock*/
             $this->assertEquals($itemsStock[$index], $cartItem->getProductSaleElements()->getQuantity());
         } else {
             /* check stock decrease */
             $this->assertEquals($itemsStock[$index] - $orderProduct->getQuantity(), $cartItem->getProductSaleElements()->getQuantity());
         }
         /* check tax */
         $orderProductTaxList = $orderProduct->getOrderProductTaxes();
         foreach ($cartItem->getProduct()->getTaxRule()->getTaxDetail($cartItem->getProduct(), $validDeliveryAddress->getCountry(), $cartItem->getPrice(), $cartItem->getPromoPrice()) as $index => $tax) {
             $orderProductTax = $orderProductTaxList[$index];
             $this->assertEquals($tax->getAmount(), $orderProductTax->getAmount());
             $this->assertEquals($tax->getPromoAmount(), $orderProductTax->getPromoAmount());
         }
     }
     return $placedOrder;
 }
Ejemplo n.º 7
0
 /**
  *
  *
  * @param  \Thelia\Model\Cart                     $cart
  * @throws \Thelia\Exception\InvalidCartException
  */
 protected function verifyValidCart(Cart $cart)
 {
     $customer = $this->getCustomerUser();
     if ($customer && $cart->getCustomerId() != $customer->getId()) {
         throw new InvalidCartException("customer in session and customer_id in cart are not the same");
     } elseif ($customer === null && $cart->getCustomerId() !== null) {
         throw new InvalidCartException("Customer exists in cart and not in session");
     }
 }
 /**
  * @return string
  */
 public function doExport()
 {
     /**
      * Define the cache
      */
     $cache = [];
     $cache["brand"] = [];
     $cache["category"] = [];
     $cache["breadcrumb"] = [];
     $cache["feature"]["title"] = [];
     $cache["feature"]["value"] = [];
     $cache["attribute"]["title"] = [];
     $cache["attribute"]["value"] = [];
     $fakeCartItem = new CartItem();
     $fakeCart = new Cart();
     $fakeCart->addCartItem($fakeCartItem);
     /** @var \Thelia\Model\Country $country */
     $country = CountryQuery::create()->findOneById(ConfigQuery::create()->read('store_country', null));
     $deliveryModuleModelId = ShoppingFluxConfigQuery::getDeliveryModuleId();
     $deliveryModuleModel = ModuleQuery::create()->findPk($deliveryModuleModelId);
     /** @var \Thelia\Module\AbstractDeliveryModule $deliveryModule */
     $deliveryModule = $deliveryModuleModel->getModuleInstance($this->container);
     /**
      * Build fake Request to inject in the module
      */
     $fakeRequest = new Request();
     $fakeRequest->setSession((new FakeSession())->setCart($fakeCart));
     $deliveryModule->setRequest($fakeRequest);
     /**
      * Currency
      */
     $currency = Currency::getDefaultCurrency();
     /**
      * Load ecotax
      */
     $ecotax = TaxQuery::create()->findPk(ShoppingFluxConfigQuery::getEcotaxRuleId());
     /**
      * If there's a problem in the configuration, load a fake tax
      */
     if ($ecotax === null) {
         $ecotax = new Tax();
         $ecotax->setType('\\Thelia\\TaxEngine\\TaxType\\FixAmountTaxType')->setRequirements(array('amount' => 0));
     }
     /**
      * Load the tax instance
      */
     $ecotaxInstance = $ecotax->getTypeInstance();
     // Compatibility with Thelia <= 2.0.2
     $ecotaxInstance->loadRequirements($ecotax->getRequirements());
     // We can pass any product as Argument, it is not used
     $ecotax = $ecotaxInstance->fixAmountRetriever(new Product());
     /** @var \Thelia\Model\Product $product */
     foreach ($this->getData() as $product) {
         $product->setLocale($this->locale);
         $node = $this->xml->addChild("produit");
         /**
          * Parent id
          */
         $node->addChild("id", $product->getId());
         $node->addChild("nom", $product->getTitle());
         $node->addChild("url", URL::getInstance()->absoluteUrl("/", ["view" => "product", "product_id" => $product->getId()]));
         $node->addChild("description-courte", $product->getChapo());
         $node->addChild("description", $product->getDescription());
         /**
          * Images URL
          */
         $imagesNode = $node->addChild("images");
         /** @var \Thelia\Model\ProductImage $productImage */
         foreach ($product->getProductImages() as $productImage) {
             $imagesNode->addChild("image", URL::getInstance()->absoluteUrl("/shoppingflux/image/" . $productImage->getId()));
         }
         /**
          * Product Brand
          */
         if ($product->getBrand()) {
             $brand = $product->getBrand();
             $brand->setLocale($this->locale);
             if (!array_key_exists($brandId = $brand->getId(), $cache["brand"])) {
                 $cache["brand"][$brandId] = $brand->getTitle();
             }
             $node->addChild("marque", $cache["brand"][$brandId]);
         } else {
             $node->addChild("marque", null);
         }
         $node->addChild("url-marque");
         /**
          * Compute breadcrumb
          */
         $category = $product->getCategories()[0];
         $category->setLocale($this->locale);
         if (!array_key_exists($categoryId = $category->getId(), $cache["category"])) {
             $cache["category"][$categoryId] = $category->getTitle();
             $breadcrumb = [];
             do {
                 $category->setLocale($this->locale);
                 $breadcrumb[] = $category->getTitle();
             } while (null !== ($category = CategoryQuery::create()->findPk($category->getParent())));
             $reversedBreadcrumb = array_reverse($breadcrumb);
             $reversedBreadcrumb[] = $product->getTitle();
             $cache["breadcrumb"][$categoryId] = implode(" > ", $reversedBreadcrumb);
         }
         $node->addChild("rayon", $cache["category"][$categoryId]);
         $node->addChild("fil-ariane", $cache["breadcrumb"][$categoryId]);
         /**
          * Features
          */
         $featuresNode = $node->addChild("caracteristiques");
         foreach ($product->getFeatureProducts() as $featureProduct) {
             if ($featureProduct->getFeatureAv() !== null && $featureProduct->getFeature() !== null) {
                 if (!array_key_exists($featureId = $featureProduct->getFeature()->getId(), $cache["feature"]["title"])) {
                     $featureProduct->getFeatureAv()->setLocale($this->locale);
                     $featureProduct->getFeature()->setLocale($this->locale);
                     $cache["feature"]["title"][$featureId] = trim(preg_replace("#[^a-z0-9_\\-]#i", "_", $featureProduct->getFeature()->getTitle()), "_");
                     $cache["feature"]["value"][$featureId] = $featureProduct->getFeatureAv()->getTitle();
                 }
                 $featuresNode->addChild($cache["feature"]["title"][$featureId], $cache["feature"]["value"][$featureId]);
             }
         }
         /**
          * Compute VAT
          */
         $taxRuleCountry = TaxRuleCountryQuery::create()->filterByTaxRule($product->getTaxRule())->findOne();
         $tax = $taxRuleCountry->getTax();
         /** @var \Thelia\TaxEngine\TaxType\PricePercentTaxType $taxType*/
         $taxType = $tax->getTypeInstance();
         if (array_key_exists("percent", $taxRequirements = $taxType->getRequirements())) {
             $node->addChild("tva", $taxRequirements["percent"]);
         }
         /**
          * Compute product sale elements
          */
         $productSaleElements = $product->getProductSaleElementss();
         $psesNode = $node->addChild("declinaisons");
         /** @var \Thelia\Model\ProductSaleElements $pse */
         foreach ($productSaleElements as $pse) {
             /**
              * Fake the cart so that module::getPostage() returns the price
              * for only one object
              */
             $fakeCartItem->setProductSaleElements($pse);
             /**
              * If the object is too heavy, don't export it
              */
             try {
                 $shipping_price = $deliveryModule->getPostage($country);
             } catch (DeliveryException $e) {
                 continue;
             }
             $productPrice = $pse->getPricesByCurrency($currency);
             $pse->setVirtualColumn("price_PRICE", $productPrice->getPrice());
             $pse->setVirtualColumn("price_PROMO_PRICE", $productPrice->getPromoPrice());
             $deliveryTimeMin = null;
             $deliveryTimeMax = null;
             $pseNode = $psesNode->addChild("declinaison");
             /**
              * Child id
              */
             $pseNode->addChild("id", $product->getId() . "_" . $pse->getId());
             $pseNode->addChild("prix-ttc", $pse->getPromo() ? $pse->getPromoPrice() : $pse->getPrice());
             $pseNode->addChild("prix-ttc-barre", $pse->getPromo() ? $pse->getPrice() : null);
             $pseNode->addChild("quantite", $pse->getQuantity());
             $pseNode->addChild("ean", $pse->getEanCode());
             $pseNode->addChild("poids", $pse->getWeight());
             $pseNode->addChild("ecotaxe", $ecotax);
             $pseNode->addChild("frais-de-port", $shipping_price);
             $pseNode->addChild("delai-livraison-mini", $deliveryTimeMin);
             $pseNode->addChild("delai-livraison-maxi", $deliveryTimeMax);
             $pseAttrNode = $pseNode->addChild("attributs");
             /** @var \Thelia\Model\AttributeCombination $attr */
             foreach ($pse->getAttributeCombinations() as $attr) {
                 if ($attr->getAttribute() !== null && $attr->getAttributeAv() !== null) {
                     if (!array_key_exists($attributeId = $attr->getAttribute()->getId(), $cache["attribute"]["title"])) {
                         $attr->getAttribute()->setLocale($this->locale);
                         $attr->getAttributeAv()->setLocale($this->locale);
                         $cache["attribute"]["title"][$attributeId] = trim(preg_replace("#[^a-z0-9_\\-]#i", "_", $attr->getAttribute()->getTitle()), "_");
                         $cache["attribute"]["value"][$attributeId] = $attr->getAttributeAv()->getTitle();
                     }
                     $pseAttrNode->addChild($cache["attribute"]["title"][$attributeId], $cache["attribute"]["value"][$attributeId]);
                 }
             }
             $pseNode->addChild("promo-de");
             $pseNode->addChild("promo-a");
         }
     }
     /**
      * Then return a well formed string
      */
     $dom = new \DOMDocument("1.0");
     $dom->preserveWhiteSpace = false;
     $dom->formatOutput = true;
     $dom->loadXML($this->xml->asXML());
     return $dom->saveXML();
 }
Ejemplo n.º 9
0
 /**
  * @depends testCreate
  * @param OrderModel $order
  * @return OrderModel
  */
 public function testCreateManual(OrderModel $order)
 {
     $orderCopy = $order->copy();
     $validDeliveryAddress = AddressQuery::create()->findOneByCustomerId($this->customer->getId());
     $validInvoiceAddress = AddressQuery::create()->filterById($validDeliveryAddress->getId(), Criteria::NOT_EQUAL)->findOneByCustomerId($this->customer->getId());
     $orderManuelEvent = new OrderManualEvent($orderCopy, $this->cart->getCurrency(), $this->requestStack->getCurrentRequest()->getSession()->getLang(), $this->cart, $this->customer);
     $orderManuelEvent->getOrder()->setChoosenDeliveryAddress($validDeliveryAddress->getId());
     $orderManuelEvent->getOrder()->setChoosenInvoiceAddress($validInvoiceAddress->getId());
     $deliveryModuleId = $orderCopy->getDeliveryModuleId();
     $paymentModuleId = $orderCopy->getPaymentModuleId();
     $this->orderAction->createManual($orderManuelEvent, null, $this->getMockEventDispatcher());
     $placedOrder = $orderManuelEvent->getPlacedOrder();
     $this->assertNotNull($placedOrder);
     $this->assertNotNull($placedOrder->getId());
     /* check customer */
     $this->assertEquals($this->customer->getId(), $placedOrder->getCustomerId(), 'customer i does not  match');
     /* check delivery address */
     $deliveryOrderAddress = $placedOrder->getOrderAddressRelatedByDeliveryOrderAddressId();
     $this->assertEquals($validDeliveryAddress->getCustomerTitle()->getId(), $deliveryOrderAddress->getCustomerTitleId(), 'delivery address title does not match');
     $this->assertEquals($validDeliveryAddress->getCompany(), $deliveryOrderAddress->getCompany(), 'delivery address company does not match');
     $this->assertEquals($validDeliveryAddress->getFirstname(), $deliveryOrderAddress->getFirstname(), 'delivery address fistname does not match');
     $this->assertEquals($validDeliveryAddress->getLastname(), $deliveryOrderAddress->getLastname(), 'delivery address lastname does not match');
     $this->assertEquals($validDeliveryAddress->getAddress1(), $deliveryOrderAddress->getAddress1(), 'delivery address address1 does not match');
     $this->assertEquals($validDeliveryAddress->getAddress2(), $deliveryOrderAddress->getAddress2(), 'delivery address address2 does not match');
     $this->assertEquals($validDeliveryAddress->getAddress3(), $deliveryOrderAddress->getAddress3(), 'delivery address address3 does not match');
     $this->assertEquals($validDeliveryAddress->getZipcode(), $deliveryOrderAddress->getZipcode(), 'delivery address zipcode does not match');
     $this->assertEquals($validDeliveryAddress->getCity(), $deliveryOrderAddress->getCity(), 'delivery address city does not match');
     $this->assertEquals($validDeliveryAddress->getPhone(), $deliveryOrderAddress->getPhone(), 'delivery address phone does not match');
     $this->assertEquals($validDeliveryAddress->getCountryId(), $deliveryOrderAddress->getCountryId(), 'delivery address country does not match');
     /* check invoice address */
     $invoiceOrderAddress = $placedOrder->getOrderAddressRelatedByInvoiceOrderAddressId();
     $this->assertEquals($validInvoiceAddress->getCustomerTitle()->getId(), $invoiceOrderAddress->getCustomerTitleId(), 'invoice address title does not match');
     $this->assertEquals($validInvoiceAddress->getCompany(), $invoiceOrderAddress->getCompany(), 'invoice address company does not match');
     $this->assertEquals($validInvoiceAddress->getFirstname(), $invoiceOrderAddress->getFirstname(), 'invoice address fistname does not match');
     $this->assertEquals($validInvoiceAddress->getLastname(), $invoiceOrderAddress->getLastname(), 'invoice address lastname does not match');
     $this->assertEquals($validInvoiceAddress->getAddress1(), $invoiceOrderAddress->getAddress1(), 'invoice address address1 does not match');
     $this->assertEquals($validInvoiceAddress->getAddress2(), $invoiceOrderAddress->getAddress2(), 'invoice address address2 does not match');
     $this->assertEquals($validInvoiceAddress->getAddress3(), $invoiceOrderAddress->getAddress3(), 'invoice address address3 does not match');
     $this->assertEquals($validInvoiceAddress->getZipcode(), $invoiceOrderAddress->getZipcode(), 'invoice address zipcode does not match');
     $this->assertEquals($validInvoiceAddress->getCity(), $invoiceOrderAddress->getCity(), 'invoice address city does not match');
     $this->assertEquals($validInvoiceAddress->getPhone(), $invoiceOrderAddress->getPhone(), 'invoice address phone does not match');
     $this->assertEquals($validInvoiceAddress->getCountryId(), $invoiceOrderAddress->getCountryId(), 'invoice address country does not match');
     /* check currency */
     $this->assertEquals($this->cart->getCurrencyId(), $placedOrder->getCurrencyId(), 'currency id does not  match');
     $this->assertEquals($this->cart->getCurrency()->getRate(), $placedOrder->getCurrencyRate(), 'currency rate does not  match');
     /* check delivery module */
     $this->assertEquals(20, $placedOrder->getPostage(), 'postage does not  match');
     $this->assertEquals($deliveryModuleId, $placedOrder->getDeliveryModuleId(), 'delivery module does not  match');
     /* check payment module */
     $this->assertEquals($paymentModuleId, $placedOrder->getPaymentModuleId(), 'payment module does not  match');
     /* check status */
     $this->assertEquals(OrderStatus::CODE_NOT_PAID, $placedOrder->getOrderStatus()->getCode(), 'status does not  match');
     /* check lang */
     $this->assertEquals($this->requestStack->getCurrentRequest()->getSession()->getLang()->getId(), $placedOrder->getLangId(), 'lang does not  match');
     // without address duplication
     $copyOrder = $order->copy();
     $orderManuelEvent->setOrder($copyOrder)->setUseOrderDefinedAddresses(true);
     $validDeliveryAddressId = $orderCopy->getDeliveryOrderAddressId();
     $validInvoiceAddressId = $orderCopy->getInvoiceOrderAddressId();
     $this->orderAction->createManual($orderManuelEvent, null, $this->getMockEventDispatcher());
     $placedOrder = $orderManuelEvent->getPlacedOrder();
     $this->assertNotNull($placedOrder);
     $this->assertNotNull($placedOrder->getId());
     /* check delivery address */
     $deliveryOrderAddress = $placedOrder->getOrderAddressRelatedByDeliveryOrderAddressId();
     $this->assertEquals($validDeliveryAddressId, $deliveryOrderAddress->getId(), 'delivery address title does not match');
     /* check invoice address */
     $invoiceOrderAddress = $placedOrder->getOrderAddressRelatedByInvoiceOrderAddressId();
     $this->assertEquals($validInvoiceAddressId, $invoiceOrderAddress->getId(), 'invoice address title does not match');
     return $placedOrder;
 }
Ejemplo n.º 10
0
 /**
  * @inheritdoc
  *
  * Adjust the item price depending on the selected attributes.
  * Save the attribute combinations for the item.
  */
 protected function doAddItem(EventDispatcherInterface $dispatcher, CartModel $cart, $productId, ProductSaleElements $productSaleElements, $quantity, ProductPriceTools $productPrices)
 {
     // get the adjusted price
     $productGetPricesEvent = (new ProductGetPricesEvent($productId))->setCurrencyId($cart->getCurrencyId())->setBasePrices($productPrices)->setLegacyProductAttributes($this->legacyProductAttributes);
     $dispatcher->dispatch(LegacyProductAttributesEvents::PRODUCT_GET_PRICES, $productGetPricesEvent);
     if (null !== $productGetPricesEvent->getPrices()) {
         $productPrices = $productGetPricesEvent->getPrices();
     }
     $cartItem = parent::doAddItem($dispatcher, $cart, $productId, $productSaleElements, $quantity, $productPrices);
     foreach ($this->legacyProductAttributes as $attributeId => $attributeAvId) {
         (new LegacyCartItemAttributeCombination())->setCartItemId($cartItem->getId())->setAttributeId($attributeId)->setAttributeAvId($attributeAvId)->save();
     }
     return $cartItem;
 }
Ejemplo n.º 11
0
 protected function createOrder(EventDispatcherInterface $dispatcher, ModelOrder $sessionOrder, CurrencyModel $currency, LangModel $lang, CartModel $cart, CustomerModel $customer)
 {
     $con = \Propel\Runtime\Propel::getConnection(OrderTableMap::DATABASE_NAME);
     $con->beginTransaction();
     $placedOrder = $sessionOrder->copy();
     $placedOrder->setDispatcher($dispatcher);
     $deliveryAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenDeliveryAddress());
     $taxCountry = $deliveryAddress->getCountry();
     $invoiceAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenInvoiceAddress());
     $cartItems = $cart->getCartItems();
     /* fulfill order */
     $placedOrder->setCustomerId($customer->getId());
     $placedOrder->setCurrencyId($currency->getId());
     $placedOrder->setCurrencyRate($currency->getRate());
     $placedOrder->setLangId($lang->getId());
     /* hard save the delivery and invoice addresses */
     $deliveryOrderAddress = new OrderAddress();
     $deliveryOrderAddress->setCustomerTitleId($deliveryAddress->getTitleId())->setCompany($deliveryAddress->getCompany())->setFirstname($deliveryAddress->getFirstname())->setLastname($deliveryAddress->getLastname())->setAddress1($deliveryAddress->getAddress1())->setAddress2($deliveryAddress->getAddress2())->setAddress3($deliveryAddress->getAddress3())->setZipcode($deliveryAddress->getZipcode())->setCity($deliveryAddress->getCity())->setPhone($deliveryAddress->getPhone())->setCountryId($deliveryAddress->getCountryId())->save($con);
     $invoiceOrderAddress = new OrderAddress();
     $invoiceOrderAddress->setCustomerTitleId($invoiceAddress->getTitleId())->setCompany($invoiceAddress->getCompany())->setFirstname($invoiceAddress->getFirstname())->setLastname($invoiceAddress->getLastname())->setAddress1($invoiceAddress->getAddress1())->setAddress2($invoiceAddress->getAddress2())->setAddress3($invoiceAddress->getAddress3())->setZipcode($invoiceAddress->getZipcode())->setCity($invoiceAddress->getCity())->setPhone($invoiceAddress->getPhone())->setCountryId($invoiceAddress->getCountryId())->save($con);
     $placedOrder->setDeliveryOrderAddressId($deliveryOrderAddress->getId());
     $placedOrder->setInvoiceOrderAddressId($invoiceOrderAddress->getId());
     $placedOrder->setStatusId(OrderStatusQuery::getNotPaidStatus()->getId());
     $placedOrder->setCart($cart);
     /* memorize discount */
     $placedOrder->setDiscount($cart->getDiscount());
     $placedOrder->save($con);
     /* fulfill order_products and decrease stock */
     foreach ($cartItems as $cartItem) {
         $product = $cartItem->getProduct();
         /* get translation */
         $productI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'Product', $product->getId());
         $pse = $cartItem->getProductSaleElements();
         /* check still in stock */
         if ($cartItem->getQuantity() > $pse->getQuantity() && true === ConfigQuery::checkAvailableStock() && 0 === $product->getVirtual()) {
             throw new TheliaProcessException("Not enough stock", TheliaProcessException::CART_ITEM_NOT_ENOUGH_STOCK, $cartItem);
         }
         if (0 === $product->getVirtual()) {
             /* decrease stock for non virtual product */
             $allowNegativeStock = intval(ConfigQuery::read('allow_negative_stock', 0));
             $newStock = $pse->getQuantity() - $cartItem->getQuantity();
             //Forbid negative stock
             if ($newStock < 0 && 0 === $allowNegativeStock) {
                 $newStock = 0;
             }
             $pse->setQuantity($newStock);
             $pse->save($con);
         }
         /* get tax */
         $taxRuleI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'TaxRule', $product->getTaxRuleId());
         $taxDetail = $product->getTaxRule()->getTaxDetail($product, $taxCountry, $cartItem->getPrice(), $cartItem->getPromoPrice(), $lang->getLocale());
         // get the virtual document path
         $virtualDocumentPath = null;
         if ($product->getVirtual() === 1) {
             // try to find the associated document
             if (null !== ($documentId = MetaDataQuery::getVal('virtual', MetaDataModel::PSE_KEY, $pse->getId()))) {
                 $productDocument = ProductDocumentQuery::create()->findPk($documentId);
                 if (null !== $productDocument) {
                     $virtualDocumentPath = $productDocument->getFile();
                 }
             }
         }
         $orderProduct = new OrderProduct();
         $orderProduct->setOrderId($placedOrder->getId())->setProductRef($product->getRef())->setProductSaleElementsRef($pse->getRef())->setProductSaleElementsId($pse->getId())->setTitle($productI18n->getTitle())->setChapo($productI18n->getChapo())->setDescription($productI18n->getDescription())->setPostscriptum($productI18n->getPostscriptum())->setVirtual($product->getVirtual())->setVirtualDocument($virtualDocumentPath)->setQuantity($cartItem->getQuantity())->setPrice($cartItem->getPrice())->setPromoPrice($cartItem->getPromoPrice())->setWasNew($pse->getNewness())->setWasInPromo($cartItem->getPromo())->setWeight($pse->getWeight())->setTaxRuleTitle($taxRuleI18n->getTitle())->setTaxRuleDescription($taxRuleI18n->getDescription())->setEanCode($pse->getEanCode())->setCartIemId($cartItem->getId())->setDispatcher($dispatcher)->save($con);
         /* fulfill order_product_tax */
         foreach ($taxDetail as $tax) {
             $tax->setOrderProductId($orderProduct->getId());
             $tax->save($con);
         }
         /* fulfill order_attribute_combination and decrease stock */
         foreach ($pse->getAttributeCombinations() as $attributeCombination) {
             $attribute = I18n::forceI18nRetrieving($lang->getLocale(), 'Attribute', $attributeCombination->getAttributeId());
             $attributeAv = I18n::forceI18nRetrieving($lang->getLocale(), 'AttributeAv', $attributeCombination->getAttributeAvId());
             $orderAttributeCombination = new OrderProductAttributeCombination();
             $orderAttributeCombination->setOrderProductId($orderProduct->getId())->setAttributeTitle($attribute->getTitle())->setAttributeChapo($attribute->getChapo())->setAttributeDescription($attribute->getDescription())->setAttributePostscriptum($attribute->getPostscriptum())->setAttributeAvTitle($attributeAv->getTitle())->setAttributeAvChapo($attributeAv->getChapo())->setAttributeAvDescription($attributeAv->getDescription())->setAttributeAvPostscriptum($attributeAv->getPostscriptum())->save($con);
         }
     }
     $con->commit();
     return $placedOrder;
 }
Ejemplo n.º 12
0
 /**
  * Customer is connected but cart not associated to him
  *
  * A new cart must be created (duplicated) containing customer id
  */
 public function testGetCartWithExistingCartAndCustomerButNotSameCustomerId()
 {
     $cartTrait = $this->cartTrait;
     $request = $this->request;
     //create a fake customer just for test. If not persists test fails !
     $customer = new Customer();
     $customer->setFirstname("john");
     $customer->setLastname("doe");
     $customer->setTitleId(1);
     $customer->save();
     $uniqid = uniqid("test3", true);
     //create a fake cart in database;
     $cart = new Cart();
     $cart->setToken($uniqid);
     $cart->save();
     $request->cookies->set("thelia_cart", $uniqid);
     $request->getSession()->setCustomerUser($customer);
     $getCart = $cartTrait->getCart($this->dispatcher, $request);
     $this->assertInstanceOf("Thelia\\Model\\Cart", $getCart, '$cart must be an instance of cart model Thelia\\Model\\Cart');
     $this->assertNotNull($getCart->getCustomerId());
     $this->assertNull($getCart->getAddressDeliveryId());
     $this->assertNull($getCart->getAddressInvoiceId());
     $this->assertNotEquals($cart->getToken(), $getCart->getToken(), "token must be different");
     $this->assertEquals($customer->getId(), $getCart->getCustomerId());
 }
Ejemplo n.º 13
0
 /**
  * @param Cart $cart
  * @param $areaId
  * @return |null
  */
 protected function getSlicePostage(Cart $cart, Country $country)
 {
     $config = self::getConfig();
     $currency = $cart->getCurrency();
     $areaId = $country->getAreaId();
     $query = CustomDeliverySliceQuery::create()->filterByAreaId($areaId);
     if ($config['method'] != CustomDelivery::METHOD_PRICE) {
         $query->filterByWeightMax($cart->getWeight(), Criteria::GREATER_THAN);
         $query->orderByWeightMax(Criteria::ASC);
     }
     if ($config['method'] != CustomDelivery::METHOD_WEIGHT) {
         $total = $cart->getTotalAmount();
         // convert amount to the default currency
         if (0 == $currency->getByDefault()) {
             $total = $total / $currency->getRate();
         }
         $query->filterByPriceMax($total, Criteria::GREATER_THAN);
         $query->orderByPriceMax(Criteria::ASC);
     }
     $slice = $query->findOne();
     $postage = null;
     if (null !== $slice) {
         $postage = new OrderPostage();
         if (0 == $currency->getByDefault()) {
             $price = $slice->getPrice() * $currency->getRate();
         } else {
             $price = $slice->getPrice();
         }
         $price = round($price, 2);
         $postage->setAmount($price);
         $postage->setAmountTax(0);
         // taxed amount
         if (0 !== $config['tax']) {
             $taxRuleI18N = I18n::forceI18nRetrieving($this->getRequest()->getSession()->getLang()->getLocale(), 'TaxRule', $config['tax']);
             $taxRule = TaxRuleQuery::create()->findPk($config['tax']);
             if (null !== $taxRule) {
                 $taxCalculator = new Calculator();
                 $taxCalculator->loadTaxRuleWithoutProduct($taxRule, $country);
                 $postage->setAmount(round($taxCalculator->getTaxedPrice($price), 2));
                 $postage->setAmountTax($postage->getAmount() - $price);
                 $postage->setTaxRuleTitle($taxRuleI18N->getTitle());
             }
         }
     }
     return $postage;
 }
Ejemplo n.º 14
0
 /**
  * Declares an association between this object and a ChildCart object.
  *
  * @param                  ChildCart $v
  * @return                 \Thelia\Model\Order The current object (for fluent API support)
  * @throws PropelException
  */
 public function setCart(ChildCart $v = null)
 {
     if ($v === null) {
         $this->setCartId(NULL);
     } else {
         $this->setCartId($v->getId());
     }
     $this->aCart = $v;
     // Add binding for other direction of this n:n relationship.
     // If this object has already been added to the ChildCart object, it will not be re-added.
     if ($v !== null) {
         $v->addOrder($this);
     }
     return $this;
 }
Ejemplo n.º 15
0
 /**
  * @param EventDispatcherInterface $dispatcher
  * @param ModelOrder $sessionOrder
  * @param CurrencyModel $currency
  * @param LangModel $lang
  * @param CartModel $cart
  * @param UserInterface $customer
  * @param bool $manageStock decrement stock when order is created if true
  * @return ModelOrder
  * @throws \Exception
  * @throws \Propel\Runtime\Exception\PropelException
  */
 protected function createOrder(EventDispatcherInterface $dispatcher, ModelOrder $sessionOrder, CurrencyModel $currency, LangModel $lang, CartModel $cart, UserInterface $customer, $manageStock)
 {
     $con = Propel::getConnection(OrderTableMap::DATABASE_NAME);
     $con->beginTransaction();
     $placedOrder = $sessionOrder->copy();
     $placedOrder->setDispatcher($dispatcher);
     $deliveryAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenDeliveryAddress());
     $taxCountry = $deliveryAddress->getCountry();
     $invoiceAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenInvoiceAddress());
     $cartItems = $cart->getCartItems();
     /* fulfill order */
     $placedOrder->setCustomerId($customer->getId());
     $placedOrder->setCurrencyId($currency->getId());
     $placedOrder->setCurrencyRate($currency->getRate());
     $placedOrder->setLangId($lang->getId());
     /* hard save the delivery and invoice addresses */
     $deliveryOrderAddress = new OrderAddress();
     $deliveryOrderAddress->setCustomerTitleId($deliveryAddress->getTitleId())->setCompany($deliveryAddress->getCompany())->setFirstname($deliveryAddress->getFirstname())->setLastname($deliveryAddress->getLastname())->setAddress1($deliveryAddress->getAddress1())->setAddress2($deliveryAddress->getAddress2())->setAddress3($deliveryAddress->getAddress3())->setZipcode($deliveryAddress->getZipcode())->setCity($deliveryAddress->getCity())->setPhone($deliveryAddress->getPhone())->setCountryId($deliveryAddress->getCountryId())->save($con);
     $invoiceOrderAddress = new OrderAddress();
     $invoiceOrderAddress->setCustomerTitleId($invoiceAddress->getTitleId())->setCompany($invoiceAddress->getCompany())->setFirstname($invoiceAddress->getFirstname())->setLastname($invoiceAddress->getLastname())->setAddress1($invoiceAddress->getAddress1())->setAddress2($invoiceAddress->getAddress2())->setAddress3($invoiceAddress->getAddress3())->setZipcode($invoiceAddress->getZipcode())->setCity($invoiceAddress->getCity())->setPhone($invoiceAddress->getPhone())->setCountryId($invoiceAddress->getCountryId())->save($con);
     $placedOrder->setDeliveryOrderAddressId($deliveryOrderAddress->getId());
     $placedOrder->setInvoiceOrderAddressId($invoiceOrderAddress->getId());
     $placedOrder->setStatusId(OrderStatusQuery::getNotPaidStatus()->getId());
     $placedOrder->setCartId($cart->getId());
     /* memorize discount */
     $placedOrder->setDiscount($cart->getDiscount());
     $placedOrder->save($con);
     /* fulfill order_products and decrease stock */
     foreach ($cartItems as $cartItem) {
         $product = $cartItem->getProduct();
         /* get translation */
         /** @var ProductI18n $productI18n */
         $productI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'Product', $product->getId());
         $pse = $cartItem->getProductSaleElements();
         // get the virtual document path
         $virtualDocumentEvent = new VirtualProductOrderHandleEvent($placedOrder, $pse->getId());
         // essentially used for virtual product. modules that handles virtual product can
         // allow the use of stock even for virtual products
         $useStock = true;
         $virtual = 0;
         // if the product is virtual, dispatch an event to collect information
         if ($product->getVirtual() === 1) {
             $dispatcher->dispatch(TheliaEvents::VIRTUAL_PRODUCT_ORDER_HANDLE, $virtualDocumentEvent);
             $useStock = $virtualDocumentEvent->isUseStock();
             $virtual = $virtualDocumentEvent->isVirtual() ? 1 : 0;
         }
         /* check still in stock */
         if ($cartItem->getQuantity() > $pse->getQuantity() && true === ConfigQuery::checkAvailableStock() && $useStock) {
             throw new TheliaProcessException("Not enough stock", TheliaProcessException::CART_ITEM_NOT_ENOUGH_STOCK, $cartItem);
         }
         if ($useStock && $manageStock) {
             /* decrease stock for non virtual product */
             $allowNegativeStock = intval(ConfigQuery::read('allow_negative_stock', 0));
             $newStock = $pse->getQuantity() - $cartItem->getQuantity();
             //Forbid negative stock
             if ($newStock < 0 && 0 === $allowNegativeStock) {
                 $newStock = 0;
             }
             $pse->setQuantity($newStock);
             $pse->save($con);
         }
         /* get tax */
         /** @var TaxRuleI18n $taxRuleI18n */
         $taxRuleI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'TaxRule', $product->getTaxRuleId());
         $taxDetail = $product->getTaxRule()->getTaxDetail($product, $taxCountry, $cartItem->getPrice(), $cartItem->getPromoPrice(), $lang->getLocale());
         $orderProduct = new OrderProduct();
         $orderProduct->setOrderId($placedOrder->getId())->setProductRef($product->getRef())->setProductSaleElementsRef($pse->getRef())->setProductSaleElementsId($pse->getId())->setTitle($productI18n->getTitle())->setChapo($productI18n->getChapo())->setDescription($productI18n->getDescription())->setPostscriptum($productI18n->getPostscriptum())->setVirtual($virtual)->setVirtualDocument($virtualDocumentEvent->getPath())->setQuantity($cartItem->getQuantity())->setPrice($cartItem->getPrice())->setPromoPrice($cartItem->getPromoPrice())->setWasNew($pse->getNewness())->setWasInPromo($cartItem->getPromo())->setWeight($pse->getWeight())->setTaxRuleTitle($taxRuleI18n->getTitle())->setTaxRuleDescription($taxRuleI18n->getDescription())->setEanCode($pse->getEanCode())->setCartItemId($cartItem->getId())->setDispatcher($dispatcher)->save($con);
         /* fulfill order_product_tax */
         /** @var OrderProductTax $tax */
         foreach ($taxDetail as $tax) {
             $tax->setOrderProductId($orderProduct->getId());
             $tax->save($con);
         }
         /* fulfill order_attribute_combination and decrease stock */
         foreach ($pse->getAttributeCombinations() as $attributeCombination) {
             /** @var \Thelia\Model\Attribute $attribute */
             $attribute = I18n::forceI18nRetrieving($lang->getLocale(), 'Attribute', $attributeCombination->getAttributeId());
             /** @var \Thelia\Model\AttributeAv $attributeAv */
             $attributeAv = I18n::forceI18nRetrieving($lang->getLocale(), 'AttributeAv', $attributeCombination->getAttributeAvId());
             $orderAttributeCombination = new OrderProductAttributeCombination();
             $orderAttributeCombination->setOrderProductId($orderProduct->getId())->setAttributeTitle($attribute->getTitle())->setAttributeChapo($attribute->getChapo())->setAttributeDescription($attribute->getDescription())->setAttributePostscriptum($attribute->getPostscriptum())->setAttributeAvTitle($attributeAv->getTitle())->setAttributeAvChapo($attributeAv->getChapo())->setAttributeAvDescription($attributeAv->getDescription())->setAttributeAvPostscriptum($attributeAv->getPostscriptum())->save($con);
         }
     }
     $con->commit();
     return $placedOrder;
 }
Ejemplo n.º 16
0
 public function processGetOrders(ApiCallEvent $event)
 {
     $api = $event->getApi();
     $response = $api->getResponse();
     if ($response->isInError()) {
         $this->logger->error($response->getFormattedError());
         throw new BadResponseException($response->getFormattedError());
     }
     $dispatcher = $event->getDispatcher();
     $orders = $response->getGroup("Orders");
     $validOrders = [];
     /** @var \Thelia\Model\Country $country */
     $shopCountry = CountryQuery::create()->findOneByShopCountry(true);
     $calculator = new Calculator();
     /**
      * Check if there is only one order: reformat the array in that case
      */
     if (array_key_exists("IdOrder", $orders["Order"])) {
         $orders = array("Order" => [$orders["Order"]]);
     }
     $notImportedOrders = [];
     /**
      * Then treat the orders
      */
     foreach ($orders["Order"] as $orderArray) {
         /**
          * I) create the addresses
          */
         /**
          * Get delivery address, and format empty fields
          */
         $deliveryAddressArray =& $orderArray["ShippingAddress"];
         $deliveryCountryId = CountryQuery::create()->findOneByIsoalpha2(strtolower($deliveryAddressArray["Country"]))->getId();
         foreach ($deliveryAddressArray as &$value) {
             if (is_array($value)) {
                 $value = "";
             }
         }
         /**
          * Same for invoice address
          */
         $invoiceAddressArray =& $orderArray["BillingAddress"];
         $invoiceCountry = CountryQuery::create()->findOneByIsoalpha2(strtolower($invoiceAddressArray["Country"]));
         $invoiceCountryId = $invoiceCountry->getId();
         foreach ($invoiceAddressArray as &$value) {
             if (is_array($value)) {
                 $value = "";
             }
         }
         $title = CustomerTitleQuery::create()->findOne()->getId();
         /**
          * Create the order addresses
          */
         $deliveryAddressEvent = new AddressCreateOrUpdateEvent("Delivery address", $title, $deliveryAddressArray["FirstName"], $deliveryAddressArray["LastName"], $deliveryAddressArray["Street"], $deliveryAddressArray["Street1"], $deliveryAddressArray["Street2"], $deliveryAddressArray["PostalCode"], $deliveryAddressArray["Town"], $deliveryCountryId, $deliveryAddressArray["PhoneMobile"], $deliveryAddressArray["Phone"], $deliveryAddressArray["Company"]);
         $deliveryAddressEvent->setCustomer($this->shoppingFluxCustomer);
         $dispatcher->dispatch(TheliaEvents::ADDRESS_CREATE, $deliveryAddressEvent);
         $invoiceAddressEvent = new AddressCreateOrUpdateEvent("Invoice address", $title, $invoiceAddressArray["FirstName"], $invoiceAddressArray["LastName"], $invoiceAddressArray["Street"], $invoiceAddressArray["Street1"], $invoiceAddressArray["Street2"], $invoiceAddressArray["PostalCode"], $invoiceAddressArray["Town"], $deliveryCountryId, $invoiceAddressArray["PhoneMobile"], $invoiceAddressArray["Phone"], $invoiceAddressArray["Company"]);
         $invoiceAddressEvent->setCustomer($this->shoppingFluxCustomer);
         $dispatcher->dispatch(TheliaEvents::ADDRESS_CREATE, $invoiceAddressEvent);
         /**
          * II) Add the products to a cart
          */
         /**
          * Format the products array
          */
         if ($orderArray["NumberOfProducts"] == "1") {
             $orderArray["Products"] = array("Product" => [$orderArray["Products"]["Product"]]);
         }
         $productsArray =& $orderArray["Products"]["Product"];
         /**
          * Create a fake cart
          */
         $cart = new Cart();
         /**
          * And fulfil it with the products
          */
         foreach ($productsArray as &$productArray) {
             $ids = explode("_", $productArray["SKU"]);
             $cartPse = ProductSaleElementsQuery::create()->findPk($ids[1]);
             $calculator->load($cartPse->getProduct(), $shopCountry);
             $price = $calculator->getUntaxedPrice((double) $productArray["Price"]);
             $cart->addCartItem((new CartItem())->setProductSaleElements($cartPse)->setProduct($cartPse->getProduct())->setQuantity($productArray["Quantity"])->setPrice($price)->setPromoPrice(0)->setPromo(0));
         }
         /**
          * III) Create/Save the order
          */
         /**
          * Construct order model
          */
         $lang = LangQuery::create()->findOneByLocale($invoiceCountry->getLocale());
         $currency = CurrencyQuery::create()->findOneByCode("EUR");
         $order = OrderQuery::create()->findOneByRef($orderArray["IdOrder"]);
         if ($order !== null) {
             $order->delete();
         }
         $order = new Order();
         $order->setPostage($orderArray["TotalShipping"])->setChoosenDeliveryAddress($deliveryAddressEvent->getAddress()->getId())->setChoosenInvoiceAddress($invoiceAddressEvent->getAddress()->getId())->setDeliveryModuleId(ShoppingFluxConfigQuery::getDeliveryModuleId())->setPaymentModuleId($this->shoppingFluxPaymentModuleId)->setTransactionRef($orderArray["Marketplace"]);
         /**
          * Construct event
          */
         $orderEvent = new OrderManualEvent($order, $currency, $lang, $cart, $this->shoppingFluxCustomer);
         $orderEvent->setDispatcher($dispatcher);
         $dispatcher->dispatch(TheliaEvents::ORDER_CREATE_MANUAL, $orderEvent);
         $placedOrder = $orderEvent->getPlacedOrder();
         $placedOrder->setRef($orderArray["IdOrder"])->setPaid();
         $validOrders[] = ["IdOrder" => $placedOrder->getRef(), "Marketplace" => $placedOrder->getTransactionRef()];
     }
     /**
      * IV) Valid the orders to Shopping Flux
      */
     $request = new Request("ValidOrders");
     foreach ($validOrders as $validOrder) {
         $request->addOrder($validOrder);
     }
     $validOrdersApi = new ValidOrders($response->getToken(), $response->getMode());
     $validOrdersApi->setRequest($request);
     $validOrdersResponse = $validOrdersApi->getResponse();
     if ($validOrdersResponse->isInError()) {
         $this->logger->error($response->getFormattedError());
     }
 }
Ejemplo n.º 17
0
 /**
  * Exclude object from result
  *
  * @param   ChildCart $cart Object to remove from the list of results
  *
  * @return ChildCartQuery The current query, for fluid interface
  */
 public function prune($cart = null)
 {
     if ($cart) {
         $this->addUsingAlias(CartTableMap::ID, $cart->getId(), Criteria::NOT_EQUAL);
     }
     return $this;
 }
Ejemplo n.º 18
0
 /**
  *
  * Refresh article's price
  *
  * @param \Thelia\Model\Cart     $cart
  * @param \Thelia\Model\Currency $currency
  */
 public function updateCartPrices(\Thelia\Model\Cart $cart, \Thelia\Model\Currency $currency)
 {
     $customer = $cart->getCustomer();
     $discount = 0;
     if (null !== $customer && $customer->getDiscount() > 0) {
         $discount = $customer->getDiscount();
     }
     // cart item
     foreach ($cart->getCartItems() as $cartItem) {
         $productSaleElements = $cartItem->getProductSaleElements();
         $productPrice = $productSaleElements->getPricesByCurrency($currency, $discount);
         $cartItem->setPrice($productPrice->getPrice())->setPromoPrice($productPrice->getPromoPrice());
         $cartItem->save();
     }
     // update the currency cart
     $cart->setCurrencyId($currency->getId());
     $cart->save();
 }
Ejemplo n.º 19
0
 /**
  * Duplicate an existing Cart. If a customer ID is provided the created cart will be attached to this customer.
  *
  * @param EventDispatcherInterface $dispatcher
  * @param CartModel $cart
  * @param CustomerModel $customer
  * @return CartModel
  */
 protected function duplicateCart(EventDispatcherInterface $dispatcher, CartModel $cart, CustomerModel $customer = null)
 {
     $newCart = $cart->duplicate($this->generateCartCookieIdentifier(), $customer, $this->session->getCurrency(), $dispatcher);
     $cartEvent = new CartEvent($newCart);
     $dispatcher->dispatch(TheliaEvents::CART_DUPLICATE, $cartEvent);
     return $cartEvent->getCart();
 }
Ejemplo n.º 20
0
 public function import($startRecord = 0)
 {
     $count = 0;
     $errors = 0;
     $hdl = $this->t1db->query(sprintf("select * from commande order by id asc limit %d, %d", intval($startRecord), $this->getChunkSize()));
     while ($hdl && ($commande = $this->t1db->fetch_object($hdl))) {
         $count++;
         try {
             $this->order_corresp->getT2($commande->id);
             Tlog::getInstance()->warning("Order ID={$commande->id} already imported.");
             continue;
         } catch (ImportException $ex) {
             // Okay, the order was not imported.
         }
         try {
             if (null === ($customer = CustomerQuery::create()->findPk($this->cust_corresp->getT2($commande->client)))) {
                 throw new ImportException("Failed to find customer ID={$commande->client}");
             }
             if (null === ($status = OrderStatusQuery::create()->findPk($commande->statut))) {
                 throw new ImportException("Failed to find order status ID={$commande->statut}");
             }
             // Create invoice address
             if (false == ($adr_livr = $this->t1db->query_obj("select * from venteadr where id=?", array($commande->adrlivr)))) {
                 throw new ImportException("Failed to find delivery adresse ID={$commande->adrlivr}");
             }
             // Create invoice address
             if (false == ($adr_fact = $this->t1db->query_obj("select * from venteadr where id=?", array($commande->adrfact)))) {
                 throw new ImportException("Failed to find billing adresse ID={$commande->adrfact}");
             }
             $con = Propel::getConnection(OrderTableMap::DATABASE_NAME);
             $con->beginTransaction();
             try {
                 $order = new Order();
                 $delivery_adr = new OrderAddress();
                 $delivery_adr->setCustomerTitleId($this->getT2CustomerTitle($adr_livr->raison)->getId())->setCompany(isset($adr_livr->entreprise) ? $adr_livr->entreprise : '')->setFirstname($adr_livr->prenom)->setLastname($adr_livr->nom)->setAddress1($adr_livr->adresse1)->setAddress2($adr_livr->adresse2)->setAddress3($adr_livr->adresse3)->setZipcode($adr_livr->cpostal)->setCity($adr_livr->ville)->setPhone($adr_livr->tel)->setCountryId($this->getT2Country($adr_livr->pays)->getId())->save($con);
                 $billing_adr = new OrderAddress();
                 $billing_adr->setCustomerTitleId($this->getT2CustomerTitle($adr_fact->raison)->getId())->setCompany(isset($adr_fact->entreprise) ? $adr_fact->entreprise : '')->setFirstname($adr_fact->prenom)->setLastname($adr_fact->nom)->setAddress1($adr_fact->adresse1)->setAddress2($adr_fact->adresse2)->setAddress3($adr_fact->adresse3)->setZipcode($adr_fact->cpostal)->setCity($adr_fact->ville)->setPhone($adr_fact->tel)->setCountryId($this->getT2Country($adr_fact->pays)->getId())->save($con);
                 // Find the first availables delivery and payment modules, that's the best we can do.
                 $deliveryModule = ModuleQuery::create()->findOneByType(BaseModule::DELIVERY_MODULE_TYPE);
                 $paymentModule = ModuleQuery::create()->findOneByType(BaseModule::PAYMENT_MODULE_TYPE);
                 // Create a cart (now required)
                 $cart = new Cart();
                 $cart->save();
                 $order->setRef($commande->ref)->setCustomer($customer)->setInvoiceDate($commande->datefact)->setCurrency($this->getT2Currency($commande->devise))->setCurrencyRate($this->getT2Currency($commande->devise)->getRate())->setTransactionRef($commande->transaction)->setDeliveryRef($commande->livraison)->setInvoiceRef($commande->facture)->setPostage($commande->port)->setStatusId($status->getId())->setLang($this->getT2Lang($commande->lang))->setDeliveryOrderAddressId($delivery_adr->getId())->setInvoiceOrderAddressId($billing_adr->getId())->setDeliveryModuleId($deliveryModule->getId())->setPaymentModuleId($paymentModule->getId())->setDiscount($commande->remise)->setCartId($cart->getId())->save($con);
                 // Update the order reference
                 $order->setRef($commande->ref)->setCreatedAt($commande->date)->save();
                 if ($commande->remise > 0) {
                     $coupon = new OrderCoupon();
                     $coupon->setOrder($order)->setCode('Not Available')->setType('UNKNOWN')->setAmount($commande->remise)->setTitle('Imported from Thelia 1')->setShortDescription('Imported from Thelia 1')->setDescription('Imported from Thelia 1')->setExpirationDate(time())->setIsCumulative(false)->setIsRemovingPostage(false)->setIsAvailableOnSpecialOffers(false)->setSerializedConditions(new ConditionCollection(array()))->save($con);
                 }
                 $vps = $this->t1db->query_list("select * from venteprod where commande=?", array($commande->id));
                 foreach ($vps as $vp) {
                     $parent = 0;
                     if (isset($vp->parent) && $vp->parent != 0) {
                         $parent = $this->product_corresp->getT2($vp->parent);
                     }
                     $orderProduct = new OrderProduct();
                     $orderProduct->setOrder($order)->setProductRef($vp->ref)->setProductSaleElementsRef($vp->ref)->setTitle($vp->titre)->setChapo($vp->chapo)->setDescription($vp->description)->setPostscriptum("")->setQuantity($vp->quantite)->setPrice($vp->prixu / (1 + $vp->tva / 100))->setPromoPrice($vp->prixu / (1 + $vp->tva / 100))->setWasNew(false)->setWasInPromo(false)->setWeight(0)->setEanCode("")->setTaxRuleTitle("")->setTaxRuleDescription("")->setParent($parent)->save($con);
                     $orderProductTax = new OrderProductTax();
                     $orderProductTax->setAmount($orderProduct->getPrice() * ($vp->tva / 100))->setPromoAmount(0)->setOrderProduct($orderProduct)->setTitle("TVA {$vp->tva} %")->setDescription("TVA {$vp->tva} %")->save($con);
                 }
                 $con->commit();
             } catch (\Exception $ex) {
                 $con->rollBack();
                 throw $ex;
             }
         } catch (\Exception $ex) {
             Tlog::getInstance()->addError("Failed to import order ref {$commande->ref}: ", $ex->getMessage());
             $errors++;
         }
     }
     return new ImportChunkResult($count, $errors);
 }