Ejemplo n.º 1
0
 public function postActivation(ConnectionInterface $con = null)
 {
     /**
      * Create a fake customer for shopping flux orders
      */
     ShoppingFluxConfigQuery::createShoppingFluxCustomer();
 }
Ejemplo n.º 2
0
 /**
  * @param  InputInterface  $input
  * @param  OutputInterface $output
  * @return void
  *
  * Create a new
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $token = ShoppingFluxConfigQuery::getToken();
     $mode = ShoppingFluxConfigQuery::getProd();
     $txt_mode = $mode ? GetOrders::REQUEST_MODE_PRODUCTION : GetOrders::REQUEST_MODE_SANDBOX;
     $api = new GetOrders($token, $txt_mode);
     /** @var \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */
     $dispatcher = $this->getContainer()->get('event_dispatcher');
     $dispatcher->dispatch(ShoppingFluxEvents::GET_ORDERS_EVENT, new ApiCallEvent($api));
 }
 protected function save(Form $form)
 {
     try {
         ShoppingFluxConfigQuery::setToken($form->get("token")->getData());
         ShoppingFluxConfigQuery::setDefaultLangId($form->get("lang_id")->getData());
         ShoppingFluxConfigQuery::setDeliveryModule($form->get("delivery_module_id")->getData());
         ShoppingFluxConfigQuery::setProd($form->get("prod")->getData());
         ShoppingFluxConfigQuery::setEcotaxRule($form->get("ecotax_id")->getData());
     } catch (\Exception $e) {
         return "An error occured during the recording of the values (" . $e->getMessage() . ")";
     }
     return true;
 }
 public function getOrders()
 {
     $token = ShoppingFluxConfigQuery::getToken();
     $mode = ShoppingFluxConfigQuery::getProd() ? GetOrders::REQUEST_MODE_PRODUCTION : GetOrders::REQUEST_MODE_SANDBOX;
     $event = new ApiCallEvent(new GetOrders($token, $mode));
     try {
         $this->getDispatcher()->dispatch(ShoppingFluxEvents::GET_ORDERS_EVENT, $event);
         $this->getParserContext()->set("success_message", Translator::getInstance()->trans("Orders successfully integrated", [], ShoppingFlux::MESSAGE_DOMAIN));
     } catch (BadResponseException $e) {
         $this->getParserContext()->set("error_message", $e->getMessage());
     }
     return $this->render("module-configure", ["module_code" => "ShoppingFlux"]);
 }
Ejemplo n.º 5
0
 /**
  *
  * in this function you add all the fields you need for your Form.
  * Form this you have to call add method on $this->formBuilder attribute :
  *
  * $this->formBuilder->add("name", "text")
  *   ->add("email", "email", array(
  *           "attr" => array(
  *               "class" => "field"
  *           ),
  *           "label" => "email",
  *           "constraints" => array(
  *               new \Symfony\Component\Validator\Constraints\NotBlank()
  *           )
  *       )
  *   )
  *   ->add('age', 'integer');
  *
  * @return null
  */
 protected function buildForm()
 {
     /**
      * Get information
      */
     if (ShoppingFluxConfigQuery::getDefaultLang() !== null) {
         $langId = ShoppingFluxConfigQuery::getDefaultLang()->getId();
     } else {
         $langId = Lang::getDefaultLanguage()->getId();
     }
     $langsId = LangQuery::create()->select("Id")->find()->toArray();
     $langsId = array_flip($langsId);
     $deliveryModulesId = ModuleQuery::create()->filterByType(AbstractDeliveryModule::DELIVERY_MODULE_TYPE)->filterByActivate(1)->select("Id")->find()->toArray();
     $deliveryModulesId = array_flip($deliveryModulesId);
     $taxesId = TaxQuery::create()->filterByType("Thelia\\TaxEngine\\TaxType\\FixAmountTaxType")->select("Id")->find()->toArray();
     $taxesId = array_flip($taxesId);
     $translator = Translator::getInstance();
     /**
      * Then build the form
      */
     $this->formBuilder->add("token", "text", array("label" => $translator->trans("ShoppingFlux Token", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_token"], "constraints" => [], "required" => true, "data" => ShoppingFluxConfigQuery::getToken()))->add("prod", "checkbox", array("label" => $translator->trans("In production", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_prod"], "required" => false, "data" => ShoppingFluxConfigQuery::getProd()))->add("delivery_module_id", "choice", array("label" => $translator->trans("Delivery module", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_delivery_module_id"], "required" => true, "multiple" => false, "choices" => $deliveryModulesId, "data" => ShoppingFluxConfigQuery::getDeliveryModuleId()))->add("lang_id", "choice", array("label" => $translator->trans("Language", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_lang"], "required" => true, "multiple" => false, "choices" => $langsId, "data" => $langId))->add("ecotax_id", "choice", array("label" => $translator->trans("Ecotax rule", [], ShoppingFlux::MESSAGE_DOMAIN), "label_attr" => ["for" => "shopping_flux_ecotax"], "required" => true, "choices" => $taxesId, "multiple" => false, "data" => ShoppingFluxConfigQuery::getEcotaxRuleId()))->add("action_type", "choice", array("required" => true, "choices" => ["save" => 0, "export" => 1], "multiple" => false));
 }
Ejemplo n.º 6
0
 public function processUpdateOrders(OrderEvent $event)
 {
     if ($event->getOrder()->getPaymentModuleId() == $this->shoppingFluxPaymentModuleId) {
         $status = $event->getStatus();
         $allowedStatus = [$sentStatusId = OrderStatusQuery::getSentStatus()->getId(), OrderStatusQuery::getCancelledStatus()->getId()];
         if (in_array($status, $allowedStatus)) {
             $order = $event->getOrder();
             $mode = ShoppingFluxConfigQuery::getProd() ? UpdateOrders::REQUEST_MODE_PRODUCTION : UpdateOrders::REQUEST_MODE_SANDBOX;
             $api = new UpdateOrders(ShoppingFluxConfigQuery::getToken(), $mode);
             $request = new Request("UpdateOrders");
             $request->addOrder(["IdOrder" => $order->getRef(), "Marketplace" => $order->getTransactionRef(), "Status" => $status === $sentStatusId ? "Shipped" : "Canceled"]);
             $response = $api->setRequest($request)->getResponse();
             if ($response->isInError()) {
                 $this->logger->error($response->getFormattedError());
             }
             if (!$api->compareResponseRequest()) {
                 $errorMessage = "Bad response from ShoppingFlux: " . $response->getGroup("UpdateOrders")->C14N();
                 $this->logger->error($errorMessage);
             }
         }
     }
 }
 /**
  * @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 getExport($generateOnly = false)
 {
     $env = $this->container->getParameter("kernel.environment");
     $theliaCacheDirectory = THELIA_CACHE_DIR . $env . DS;
     $generateFile = true;
     $writeCache = false;
     /**
      * Error logging tools
      */
     $logger = Tlog::getNewInstance();
     $logger->setDestinations(static::LOG_CLASS);
     $logger->setConfig(self::LOG_CLASS, 0, THELIA_ROOT . "log" . DS . "log-shopping-flux.txt");
     $translator = Translator::getInstance();
     $cacheDirectory = $theliaCacheDirectory . static::SHOPPING_FLUX_CACHE_DIR . DS;
     $cacheFile = $cacheDirectory . static::CACHE_FILE_NAME;
     /**
      * Check if the file exists, if it is readable and if
      * we have to get the cache or save it.
      */
     if (file_exists($cacheFile)) {
         if (!is_readable($cacheFile)) {
             $logger->warning($translator->trans("The file %file is not readable, the cache can't be used", ["%file" => $cacheFile], ShoppingFlux::MESSAGE_DOMAIN));
         } else {
             $time = @filemtime($cacheFile);
             if (false === $time) {
                 $logger->error($translator->trans("Unknown error while getting %file update time", ["%file" => $cacheFile], ShoppingFlux::MESSAGE_DOMAIN));
             } elseif ($time < ($limitTime = time() - static::CACHE_TIME_HOUR * 3600)) {
                 /**
                  * If the cache is too old
                  */
                 if (!is_writable($cacheFile)) {
                     $logger->warning($translator->trans("The file %file is not writable, the cache can't be saved", ["%file" => $cacheFile], ShoppingFlux::MESSAGE_DOMAIN));
                 } else {
                     $writeCache = true;
                 }
             } elseif ($time >= $limitTime) {
                 $generateFile = false;
             }
         }
     } else {
         /**
          * Check if the cache directory exists,
          * if not, create it.
          */
         if (!file_exists($cacheDirectory)) {
             if (!@mkdir($cacheDirectory)) {
                 $logger->warning($translator->trans("Unable to create the cache directory %dir", ["%dir" => $cacheDirectory], ShoppingFlux::MESSAGE_DOMAIN));
             } else {
                 $writeCache = true;
             }
         }
     }
     if (is_file($cacheDirectory) && !unlink($cacheDirectory)) {
         $logger->warning($translator->trans("Unable to create the cache directory, a file named %dir exists and can't be deleted", ["%dir" => $cacheDirectory], ShoppingFlux::MESSAGE_DOMAIN));
     } elseif (is_dir($cacheDirectory)) {
         if (!is_writable($cacheDirectory)) {
             $logger->warning($translator->trans("The directory %dir is not writable, the cache file can't be saved", ["%dir" => $cacheDirectory], ShoppingFlux::MESSAGE_DOMAIN));
         } elseif (!file_exists($cacheFile)) {
             $writeCache = true;
         }
     }
     /**
      * Then when everything's ok ( directory created if not ) go.
      */
     if ($generateFile) {
         $content = ShoppingFluxConfigQuery::exportXML($this->container);
     } elseif (!$generateOnly) {
         $content = file_get_contents($cacheFile);
     } else {
         $content = null;
     }
     if ($writeCache && $content !== null) {
         file_put_contents($cacheFile, $content);
     }
     if ($generateOnly) {
         return !($generateFile ^ $writeCache) && is_writable($cacheFile);
     }
     return new Response($content, 200, ["Content-type" => "application/xml"]);
 }