/** * @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(); }
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()); } }
/** * Declares an association between this object and a ChildCart object. * * @param ChildCart $v * @return \Thelia\Model\CartItem 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->addCartItem($this); } return $this; }