public function buildModelCriteria() { $search = CountryQuery::create(); /* manage translations */ $this->configureI18nProcessing($search); $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $area = $this->getArea(); if (null !== $area) { $search->filterByAreaId($area, Criteria::IN); } $withArea = $this->getWith_area(); if (true === $withArea) { $search->filterByAreaId(null, Criteria::ISNOTNULL); } elseif (false === $withArea) { $search->filterByAreaId(null, Criteria::ISNULL); } $exclude = $this->getExclude(); if (!is_null($exclude)) { $search->filterById($exclude, Criteria::NOT_IN); } $search->addAscendingOrderByColumn('i18n_TITLE'); return $search; }
public function buildModelCriteria() { $search = CountryQuery::create(); /* manage translations */ $this->configureI18nProcessing($search); $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $area = $this->getArea(); if (null !== $area) { $search->useCountryAreaQuery('with_area')->filterByAreaId($area, Criteria::IN)->endUse(); } $excludeArea = $this->getExcludeArea(); if (null !== $excludeArea) { // FIXME : did not find a way to do this in a single request :( // select * from country where id not in (select country_id from country_area where area in (...)) $countries = CountryAreaQuery::create()->filterByAreaId($excludeArea, Criteria::IN)->select(['country_id'])->find(); $search->filterById($countries->toArray(), Criteria::NOT_IN); } $withArea = $this->getWithArea(); if (true === $withArea) { $search->joinCountryArea('with_area', Criteria::LEFT_JOIN)->where('`with_area`.country_id ' . Criteria::ISNOTNULL); } elseif (false === $withArea) { $search->joinCountryArea('with_area', Criteria::LEFT_JOIN)->where('`with_area`.country_id ' . Criteria::ISNULL); } $exclude = $this->getExclude(); if (!is_null($exclude)) { $search->filterById($exclude, Criteria::NOT_IN); } $search->addAscendingOrderByColumn('i18n_TITLE'); return $search; }
/** * Generate adapter stub * * @param int $cartTotalPrice Cart total price * @param string $checkoutCurrency Checkout currency * @param string $i18nOutput Output from each translation * * @return \PHPUnit_Framework_MockObject_MockObject */ public function generateFacadeStub($cartTotalPrice = 400, $checkoutCurrency = 'EUR', $i18nOutput = '') { $stubFacade = $this->getMockBuilder('\\Thelia\\Coupon\\BaseFacade')->disableOriginalConstructor()->getMock(); $currencies = CurrencyQuery::create(); $currencies = $currencies->find(); $stubFacade->expects($this->any())->method('getAvailableCurrencies')->will($this->returnValue($currencies)); $stubFacade->expects($this->any())->method('getCartTotalPrice')->will($this->returnValue($cartTotalPrice)); $stubFacade->expects($this->any())->method('getCheckoutCurrency')->will($this->returnValue($checkoutCurrency)); $stubFacade->expects($this->any())->method('getConditionEvaluator')->will($this->returnValue(new ConditionEvaluator())); $stubTranslator = $this->getMockBuilder('\\Thelia\\Core\\Translation\\Translator')->disableOriginalConstructor()->getMock(); $stubTranslator->expects($this->any())->method('trans')->will($this->returnValue($i18nOutput)); $stubFacade->expects($this->any())->method('getTranslator')->will($this->returnValue($stubTranslator)); $stubDispatcher = $this->getMockBuilder('\\Symfony\\Component\\EventDispatcher\\EventDispatcher')->disableOriginalConstructor()->getMock(); $stubDispatcher->expects($this->any())->method('dispatch')->will($this->returnCallback(function ($dummy, $cartEvent) { $ci = new CartItem(); $ci->setId(3)->setPrice(123)->setPromo(0)->setProductId($this->freeProduct->getId()); $cartEvent->setCartItem($ci); })); $stubFacade->expects($this->any())->method('getDispatcher')->will($this->returnValue($stubDispatcher)); $stubSession = $this->getMockBuilder('\\Thelia\\Core\\HttpFoundation\\Session\\Session')->disableOriginalConstructor()->getMock(); $stubSession->expects($this->any())->method('get')->will($this->onConsecutiveCalls(-1, 3)); $stubRequest = $this->getMockBuilder('\\Thelia\\Core\\HttpFoundation\\Request')->disableOriginalConstructor()->getMock(); $stubRequest->expects($this->any())->method('getSession')->will($this->returnValue($stubSession)); $stubFacade->expects($this->any())->method('getRequest')->will($this->returnValue($stubRequest)); $country = CountryQuery::create()->findOneByByDefault(1); $stubFacade->expects($this->any())->method('getDeliveryCountry')->will($this->returnValue($country)); return $stubFacade; }
public function toggleDefault(CountryToggleDefaultEvent $event) { if (null !== ($country = CountryQuery::create()->findPk($event->getCountryId()))) { $country->toggleDefault(); $event->setCountry($country); } }
public function verifyCountry($value, ExecutionContextInterface $context) { $address = CountryQuery::create()->findPk($value); if (null === $address) { $context->addViolation(Translator::getInstance()->trans("Country ID not found")); } }
public function testFormatAddress() { // Test for address in France $countryFR = CountryQuery::create()->filterByIsoalpha2('FR')->findOne(); $address = AddressQuery::create()->findOne(); $address->setCountryId($countryFR->getId())->save(); $data = $this->renderString('{format_address address=$address locale="fr_FR"}', ['address' => $address->getId()]); $title = $address->getCustomerTitle()->setLocale('fr_FR')->getShort(); $expected = ['<p >', sprintf('<span class="recipient">%s %s %s</span><br>', $title, $address->getLastname(), $address->getFirstname()), sprintf('<span class="address-line1">%s</span><br>', $address->getAddress1()), sprintf('<span class="postal-code">%s</span> <span class="locality">%s</span><br>', $address->getZipcode(), $address->getCity()), '<span class="country">France</span>', '</p>']; $this->assertEquals($data, implode("\n", $expected)); // Test for address in USA $stateDC = StateQuery::create()->filterByIsocode('DC')->findOne(); $countryUS = $stateDC->getCountry(); $address->setCountryId($countryUS->getId())->setStateId($stateDC->getId())->save(); $data = $this->renderString('{format_address address=$address locale="en_US"}', ['address' => $address->getId()]); $title = $address->getCustomerTitle()->setLocale('en_US')->getShort(); $expected = ['<p >', sprintf('<span class="recipient">%s %s %s</span><br>', $title, $address->getLastname(), $address->getFirstname()), sprintf('<span class="address-line1">%s</span><br>', $address->getAddress1()), sprintf('<span class="locality">%s</span>, <span class="administrative-area">%s</span> <span class="postal-code">%s</span><br>', $address->getCity(), $stateDC->getIsocode(), $address->getZipcode()), '<span class="country">United States</span>', '</p>']; $this->assertEquals($data, implode("\n", $expected)); // Test html tag $data = $this->renderString('{format_address html_tag="address" html_class="a_class" html_id="an_id" address=$address}', ['address' => $address->getId()]); $this->assertTrue(strpos($data, '<address class="a_class" id="an_id">') !== false); // Test plain text $data = $this->renderString('{format_address html="0" address=$address locale="en_US"}', ['address' => $address->getId()]); $expected = [sprintf('%s %s %s', $title, $address->getLastname(), $address->getFirstname()), sprintf('%s', $address->getAddress1()), sprintf('%s, %s %s', $address->getCity(), $stateDC->getIsocode(), $address->getZipcode()), 'United States']; $this->assertEquals($data, implode("\n", $expected)); }
public function update_status(OrderEvent $event) { if ($event->getOrder()->getDeliveryModuleId() === LocalPickup::getModCode()) { if ($event->getOrder()->isSent()) { $contact_email = ConfigQuery::read('store_email'); if ($contact_email) { $message = MessageQuery::create()->filterByName('order_confirmation_localpickup')->findOne(); if (false === $message) { throw new \Exception("Failed to load message 'order_confirmation_localpickup'."); } $order = $event->getOrder(); $customer = $order->getCustomer(); $store = ConfigQuery::create(); $country = CountryQuery::create()->findPk($store->read("store_country")); $country = CountryI18nQuery::create()->filterById($country->getId())->findOneByLocale($order->getLang()->getLocale())->getTitle(); $this->parser->assign('order_id', $order->getId()); $this->parser->assign('order_ref', $order->getRef()); $this->parser->assign('store_name', $store->read("store_name")); $this->parser->assign('store_address1', $store->read("store_address1")); $this->parser->assign('store_address2', $store->read("store_address2")); $this->parser->assign('store_address3', $store->read("store_address3")); $this->parser->assign('store_zipcode', $store->read("store_zipcode")); $this->parser->assign('store_city', $store->read("store_city")); $this->parser->assign('store_country', $country); $message->setLocale($order->getLang()->getLocale()); $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name')); // Build subject and body $message->buildMessage($this->parser, $instance); $this->getMailer()->send($instance); } } } }
public function migrateSystemAction() { $response = $this->checkAuth(AdminResources::COUNTRY, array(), AccessManager::UPDATE); if (null !== $response) { return $response; } // load country not migrated $dataForm = []; $migratedCountries = json_decode(ConfigQuery::read('thelia_country_state_migration', '[]'), true); $countries = CountryQuery::create()->filterByHasStates(1); /** @var Country $country */ foreach ($countries as $country) { $oldCountries = CountryQuery::create()->filterByHasStates(0)->filterByIsocode($country->getIsoCode())->find(); /** @var Country $oldCountry */ foreach ($oldCountries as $oldCountry) { if (!isset($migratedCountries[$oldCountry->getId()])) { $dataForm[] = ['migrate' => false, 'country' => $oldCountry->getId(), 'new_country' => $country->getId(), 'new_state' => null]; } } } // prepare form $form = $this->createForm('thelia.admin.country.state.migration', 'form', ['migrations' => $dataForm]); $this->getParserContext()->addForm($form); return $this->render('countries-migrate', ['countriesMigrated' => $migratedCountries, 'showForm' => count($dataForm) != 0]); }
public function removeCountry(AreaRemoveCountryEvent $event) { if (null !== ($country = CountryQuery::create()->findPk($event->getCountryId()))) { $event->setArea($country->getArea()); $country->setDispatcher($event->getDispatcher()); $country->setAreaId(null)->save(); } }
protected function buildForm() { $countryList = array(); foreach (CountryQuery::create()->find() as $country) { $countryList[$country->getId()] = $country->getId(); } $this->formBuilder->add("id", "hidden", array("required" => true, "constraints" => array(new Constraints\NotBlank(), new Constraints\Callback(array("methods" => array(array($this, "verifyTaxRuleId")))))))->add("tax_list", "hidden", array("required" => true, "attr" => array("id" => 'tax_list'), "constraints" => array(new Constraints\Callback(array("methods" => array(array($this, "verifyTaxList")))))))->add("country_list", "choice", array("choices" => $countryList, "required" => true, "multiple" => true, "constraints" => array(new Constraints\NotBlank()))); }
/** * @return array|mixed|\Thelia\Model\Country * @throws \UnexpectedValueException */ public function getDeliveryOrderCountry() { $country_id = $this->getDeliveryOrderAddress()->getCountryId(); $country = CountryQuery::create()->findPK($country_id); if ($country === null) { throw new \UnexpectedValueException("The country doesn't exist"); } return $country; }
/** * @param AreaModel $area * @depends testAddCountry * @return AreaModel */ public function testRemoveCountry(AreaModel $area) { $country = CountryQuery::create()->filterByArea($area)->find()->getFirst(); $event = new AreaRemoveCountryEvent($area->getId(), $country->getId()); $areaAction = new Area(); $areaAction->removeCountry($event); $updatedCountry = CountryAreaQuery::create()->filterByCountryId($country->getId())->filterByStateId(null)->filterByAreaId($area->getId())->findOne(); $updatedArea = $event->getArea(); $this->assertInstanceOf('Thelia\\Model\\Area', $updatedArea); $this->assertNull($updatedCountry); return $event->getArea(); }
public function socolissimoDeliveryPrice($params, $smarty) { $deliveryMode = $params["delivery-mode"]; $country = CountryQuery::create()->findOneById($params["country"]); $cartWeight = $this->request->getSession()->getSessionCart($this->dispatcher)->getWeight(); $cartAmount = $this->request->getSession()->getSessionCart($this->dispatcher)->getTaxedAmount($country); try { $price = SoColissimo::getPostageAmount($country->getAreaId(), $cartWeight, $cartAmount, $deliveryMode); } catch (DeliveryException $ex) { $smarty->assign('isValidMode', false); } $smarty->assign('deliveryModePrice', $price); }
/** * @param AreaModel $area * @depends testAddCountry */ public function testRemoveCountry(AreaModel $area) { $country = CountryQuery::create()->filterByArea($area)->find()->getFirst(); $event = new AreaRemoveCountryEvent($area->getId(), $country->getId()); $event->setDispatcher($this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface")); $areaAction = new Area(); $areaAction->removeCountry($event); $updatedCountry = CountryQuery::create()->findPk($country->getId()); $updatedArea = $event->getArea(); $this->assertInstanceOf('Thelia\\Model\\Area', $updatedArea); $this->assertNull($updatedCountry->getAreaId()); return $event->getArea(); }
/** * @inheritdoc */ public function getSummary() { $i18nOperator = Operators::getI18n($this->translator, $this->operators[self::COUNTRIES_LIST]); $cntryStrList = ''; $cntryIds = $this->values[self::COUNTRIES_LIST]; if (null !== ($cntryList = CountryQuery::create()->findPks($cntryIds))) { /** @var Country $cntry */ foreach ($cntryList as $cntry) { $cntryStrList .= $cntry->getTitle() . ', '; } $cntryStrList = rtrim($cntryStrList, ', '); } return $this->getSummaryLabel($cntryStrList, $i18nOperator); }
public function testLoad() { $productQuery = ProductQuery::create()->findOne(); $countryQuery = CountryQuery::create()->findOneById(64); $calculator = new Calculator(); $taxRuleQuery = $this->getMock('\\Thelia\\Model\\TaxRuleQuery', array('getTaxCalculatorCollection')); $taxRuleQuery->expects($this->once())->method('getTaxCalculatorCollection')->with($productQuery->getTaxRule(), $countryQuery)->will($this->returnValue('foo')); $rewritingUrlQuery = $this->getProperty('taxRuleQuery'); $rewritingUrlQuery->setValue($calculator, $taxRuleQuery); $calculator->load($productQuery, $countryQuery); $this->assertEquals($productQuery, $this->getProperty('product')->getValue($calculator)); $this->assertEquals($countryQuery, $this->getProperty('country')->getValue($calculator)); $this->assertEquals('foo', $this->getProperty('taxRulesCollection')->getValue($calculator)); }
public function verifyState($value, ExecutionContextInterface $context) { $data = $context->getRoot()->getData(); if (null !== ($country = CountryQuery::create()->findPk($data['country']))) { if ($country->getHasStates()) { if (null !== ($state = StateQuery::create()->findPk($data['state']))) { if ($state->getCountryId() !== $country->getId()) { $context->addViolation(Translator::getInstance()->trans("This state doesn't belong to this country.")); } } else { $context->addViolation(Translator::getInstance()->trans("You should select a state for this country.")); } } } }
/** * Generate adapter stub * * @param int $cartTotalPrice Cart total price * @param string $checkoutCurrency Checkout currency * @param string $i18nOutput Output from each translation * * @return \PHPUnit_Framework_MockObject_MockObject */ public function generateFacadeStub($cartTotalPrice = 400, $checkoutCurrency = 'EUR', $i18nOutput = '') { $stubFacade = $this->getMockBuilder('\\Thelia\\Coupon\\BaseFacade')->disableOriginalConstructor()->getMock(); $defaultCountry = CountryQuery::create()->filterByByDefault(1)->findOne(); $currencies = CurrencyQuery::create(); $currencies = $currencies->find(); $stubFacade->expects($this->any())->method('getAvailableCurrencies')->will($this->returnValue($currencies)); $stubFacade->expects($this->any())->method('getCartTotalPrice')->will($this->returnValue($cartTotalPrice)); $stubFacade->expects($this->any())->method('getDeliveryCountry')->will($this->returnValue($defaultCountry)); $stubFacade->expects($this->any())->method('getCheckoutCurrency')->will($this->returnValue($checkoutCurrency)); $stubFacade->expects($this->any())->method('getConditionEvaluator')->will($this->returnValue(new ConditionEvaluator())); $stubTranslator = $this->getMockBuilder('\\Thelia\\Core\\Translation\\Translator')->disableOriginalConstructor()->getMock(); $stubTranslator->expects($this->any())->method('trans')->will($this->returnValue($i18nOutput)); $stubFacade->expects($this->any())->method('getTranslator')->will($this->returnValue($stubTranslator)); return $stubFacade; }
public function testCreate() { $country = CountryQuery::create()->filterByHasStates(1)->findOne(); $event = new StateCreateEvent(); $event->setVisible(1)->setCountry($country->getId())->setIsocode('AA')->setLocale('en_US')->setTitle('State1'); $action = new State(); $action->create($event); $createdState = $event->getState(); $this->assertInstanceOf('Thelia\\Model\\State', $createdState); $this->assertFalse($createdState->isNew()); $this->assertEquals($country->getId(), $createdState->getCountryId()); $this->assertEquals('AA', $createdState->getIsocode()); $this->assertEquals('en_US', $createdState->getLocale()); $this->assertEquals('State1', $createdState->getTitle()); return $createdState; }
/** * Build Coupon form * * @return void */ protected function buildForm() { // Create countries and shipping modules list $countries = [0 => ' ']; $list = CountryQuery::create()->find(); /** @var Country $item */ foreach ($list as $item) { $countries[$item->getId()] = $item->getTitle(); } asort($countries); $countries[0] = Translator::getInstance()->trans("All countries"); $modules = [0 => ' ']; $list = ModuleQuery::create()->filterByActivate(BaseModule::IS_ACTIVATED)->filterByType(BaseModule::DELIVERY_MODULE_TYPE)->find(); /** @var Module $item */ foreach ($list as $item) { $modules[$item->getId()] = $item->getTitle(); } asort($modules); $modules[0] = Translator::getInstance()->trans("All shipping methods"); $this->formBuilder->add('code', 'text', array('constraints' => array(new NotBlank())))->add('title', 'text', array('constraints' => array(new NotBlank())))->add('shortDescription', 'text')->add('description', 'textarea')->add('type', 'text', array('constraints' => array(new NotBlank(), new NotEqualTo(array('value' => -1)))))->add('isEnabled', 'text', array())->add('expirationDate', 'text', array('constraints' => array(new NotBlank(), new Callback(array("methods" => array(array($this, "checkLocalizedDate")))))))->add('isCumulative', 'text', array())->add('isRemovingPostage', 'text', array())->add('freeShippingForCountries', 'choice', array('multiple' => true, 'choices' => $countries))->add('freeShippingForModules', 'choice', array('multiple' => true, 'choices' => $modules))->add('isAvailableOnSpecialOffers', 'text', array())->add('maxUsage', 'text', array('constraints' => array(new NotBlank(), new GreaterThanOrEqual(['value' => -1]))))->add('perCustomerUsageCount', 'choice', array('multiple' => false, 'required' => true, 'choices' => [1 => Translator::getInstance()->trans('Per customer'), 0 => Translator::getInstance()->trans('Overall')]))->add('locale', 'hidden', array('constraints' => array(new NotBlank())))->add('coupon_specific', 'collection', array('allow_add' => true, 'allow_delete' => true)); }
public function parseResults(LoopResult $loopResult) { $countryId = $this->getCountry(); if (null !== $countryId) { $country = CountryQuery::create()->findPk($countryId); if (null === $country) { throw new \InvalidArgumentException('Cannot found country id: `' . $countryId . '` in delivery loop'); } } else { $country = $this->container->get('thelia.taxEngine')->getDeliveryCountry(); } $virtual = $this->request->getSession()->getSessionCart($this->dispatcher)->isVirtual(); /** @var Module $deliveryModule */ foreach ($loopResult->getResultDataCollection() as $deliveryModule) { $areaDeliveryModule = AreaDeliveryModuleQuery::create()->findByCountryAndModule($country, $deliveryModule); if (null === $areaDeliveryModule && false === $virtual) { continue; } /** @var DeliveryModuleInterface $moduleInstance */ $moduleInstance = $deliveryModule->getDeliveryModuleInstance($this->container); if (true === $virtual && false === $moduleInstance->handleVirtualProductDelivery() && false === $this->getBackendContext()) { continue; } $loopResultRow = new LoopResultRow($deliveryModule); try { // Check if module is valid, by calling isValidDelivery(), // or catching a DeliveryException. if ($moduleInstance->isValidDelivery($country)) { $postage = OrderPostage::loadFromPostage($moduleInstance->getPostage($country)); $loopResultRow->set('ID', $deliveryModule->getId())->set('TITLE', $deliveryModule->getVirtualColumn('i18n_TITLE'))->set('CHAPO', $deliveryModule->getVirtualColumn('i18n_CHAPO'))->set('DESCRIPTION', $deliveryModule->getVirtualColumn('i18n_DESCRIPTION'))->set('POSTSCRIPTUM', $deliveryModule->getVirtualColumn('i18n_POSTSCRIPTUM'))->set('POSTAGE', $postage->getAmount())->set('POSTAGE_TAX', $postage->getAmountTax())->set('POSTAGE_UNTAXED', $postage->getAmount() - $postage->getAmountTax())->set('POSTAGE_TAX_RULE_TITLE', $postage->getTaxRuleTitle()); $this->addOutputFields($loopResultRow, $deliveryModule); $loopResult->addRow($loopResultRow); } } catch (DeliveryException $ex) { // Module is not available } } return $loopResult; }
public function buildModelCriteria() { $search = TaxRuleCountryQuery::create(); $ask = $this->getAsk(); $country = $this->getCountry(); $taxRule = $this->getTaxRule(); if ($ask === 'countries') { $this->taxCountForOriginCountry = TaxRuleCountryQuery::create()->filterByCountryId($country)->count(); if ($this->taxCountForOriginCountry > 0) { $search->groupByCountryId(); $originalCountryJoin = new Join(); $originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'TAX_RULE_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'TAX_RULE_ID', 'origin'); $originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'TAX_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'TAX_ID', 'origin'); $originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'POSITION', null, TaxRuleCountryTableMap::TABLE_NAME, 'POSITION', 'origin'); $originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'COUNTRY_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'COUNTRY_ID', 'origin', Criteria::NOT_EQUAL); $originalCountryJoin->setJoinType(Criteria::LEFT_JOIN); $search->addJoinObject($originalCountryJoin, 's_to_o'); $search->where('`origin`.`COUNTRY_ID`' . Criteria::EQUAL . '?', $country, \PDO::PARAM_INT); //$search->having('COUNT(*)=?', $this->taxCountForOriginCountry, \PDO::PARAM_INT); $search->filterByTaxRuleId($taxRule); /* manage tax translation */ $this->configureI18nProcessing($search, array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), CountryTableMap::TABLE_NAME, 'COUNTRY_ID'); $search->addAscendingOrderByColumn('`' . CountryTableMap::TABLE_NAME . '_i18n_TITLE`'); } else { $search = CountryQuery::create()->joinTaxRuleCountry('trc', Criteria::LEFT_JOIN); /* manage tax translation */ $this->configureI18nProcessing($search); $search->where('ISNULL(`trc`.`COUNTRY_ID`)'); $search->addAscendingOrderByColumn('i18n_TITLE'); } } elseif ($ask === 'taxes') { $search->filterByCountryId($country); /* manage tax translation */ $this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION'), TaxTableMap::TABLE_NAME, 'TAX_ID'); $search->filterByTaxRuleId($taxRule); $search->orderByPosition(Criteria::ASC); } return $search; }
public function verifyCountryList($value, ExecutionContextInterface $context) { $countryList = is_array($value) ? $value : [$value]; foreach ($countryList as $countryItem) { $item = explode('-', $countryItem); if (count($item) == 2) { $country = CountryQuery::create()->findPk($item[0]); if (null === $country) { $context->addViolation(Translator::getInstance()->trans("Country ID %id not found", ['%id' => $item[0]])); } if ($item[1] == "0") { continue; } $state = StateQuery::create()->findPk($item[1]); if (null === $state) { $context->addViolation(Translator::getInstance()->trans("State ID %id not found", ['%id' => $item[1]])); } } else { $context->addViolation(Translator::getInstance()->trans("Wrong country definition")); } } }
public function parseResults(LoopResult $loopResult) { $countryId = $this->getCountry(); if (null !== $countryId) { $country = CountryQuery::create()->findPk($countryId); if (null === $country) { throw new \InvalidArgumentException('Cannot found country id: `' . $countryId . '` in delivery loop'); } } else { $country = $this->container->get('thelia.taxEngine')->getDeliveryCountry(); } /** @var Module $deliveryModule */ foreach ($loopResult->getResultDataCollection() as $deliveryModule) { $areaDeliveryModule = AreaDeliveryModuleQuery::create()->findByCountryAndModule($country, $deliveryModule); if (null === $areaDeliveryModule) { continue; } $loopResultRow = new LoopResultRow($deliveryModule); /** @var DeliveryModuleInterface $moduleInstance */ $moduleInstance = $deliveryModule->getModuleInstance($this->container); if (false === $moduleInstance instanceof DeliveryModuleInterface) { throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\\Module\\DeliveryModuleInterface", $deliveryModule->getCode())); } try { // Check if module is valid, by calling isValidDelivery(), // or catching a DeliveryException. if ($moduleInstance->isValidDelivery($country)) { $postage = $moduleInstance->getPostage($country); $loopResultRow->set('ID', $deliveryModule->getId())->set('TITLE', $deliveryModule->getVirtualColumn('i18n_TITLE'))->set('CHAPO', $deliveryModule->getVirtualColumn('i18n_CHAPO'))->set('DESCRIPTION', $deliveryModule->getVirtualColumn('i18n_DESCRIPTION'))->set('POSTSCRIPTUM', $deliveryModule->getVirtualColumn('i18n_POSTSCRIPTUM'))->set('POSTAGE', $postage); $loopResult->addRow($loopResultRow); } } catch (DeliveryException $ex) { // Module is not available } } return $loopResult; }
public function exportAction() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('Colissimo'), AccessManager::UPDATE))) { return $response; } $form = new FormExport($this->getRequest()); try { $exportForm = $this->validateForm($form); // Get new status $status_id = $exportForm->get('status_id')->getData(); $status = OrderStatusQuery::create()->filterByCode($status_id)->findOne(); // Get Colissimo orders $orders = ColissimoQuery::getOrders()->find(); $export = ""; $store_name = ConfigQuery::getStoreName(); /** @var $order \Thelia\Model\Order */ foreach ($orders as $order) { $value = $exportForm->get('order_' . $order->getId())->getData(); if ($value) { // Get order information $customer = $order->getCustomer(); $locale = $order->getLang()->getLocale(); $address = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); $country = CountryQuery::create()->findPk($address->getCountryId()); $country->setLocale($locale); $customerTitle = CustomerTitleQuery::create()->findPk($address->getCustomerTitleId()); $customerTitle->setLocale($locale); $weight = $exportForm->get('order_weight_' . $order->getId())->getData(); if ($weight == 0) { /** @var \Thelia\Model\OrderProduct $product */ foreach ($order->getOrderProducts() as $product) { $weight += (double) $product->getWeight(); } } /** * Get user's phone & cellphone * First get invoice address phone, * If empty, try to get default address' phone. * If still empty, set default value */ $phone = $address->getPhone(); if (empty($phone)) { $phone = $customer->getDefaultAddress()->getPhone(); if (empty($phone)) { $phone = self::DEFAULT_PHONE; } } // Cellphone $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = self::DEFAULT_CELLPHONE; } } $export .= "\"" . $order->getRef() . "\";\"" . $address->getLastname() . "\";\"" . $address->getFirstname() . "\";\"" . $address->getAddress1() . "\";\"" . $address->getAddress2() . "\";\"" . $address->getAddress3() . "\";\"" . $address->getZipcode() . "\";\"" . $address->getCity() . "\";\"" . $country->getIsoalpha2() . "\";\"" . $phone . "\";\"" . $cellphone . "\";\"" . $weight . "\";\"" . $customer->getEmail() . "\";\"\";\"" . $store_name . "\";\"DOM\";\r\n"; if ($status) { $event = new OrderEvent($order); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } return Response::create(utf8_decode($export), 200, array("Content-Encoding" => "ISO-8889-1", "Content-Type" => "application/csv-tab-delimited-table", "Content-disposition" => "filename=export.csv")); } catch (FormValidationException $e) { $this->setupFormErrorContext(Translator::getInstance()->trans("colissimo expeditor export", [], Colissimo::DOMAIN_NAME), $e->getMessage(), $form, $e); return $this->render("module-configure", array("module_code" => "Colissimo")); } }
/** * Retrieve the delivery country for a customer * * The rules : * - the country of the delivery address of the customer related to the * cart if it exists * - the country saved in cookie if customer have changed * the default country * - the default country for the shop if it exists * * * @param \Thelia\Model\Customer $customer * @return \Thelia\Model\Country */ protected function getDeliveryCountry(Customer $customer = null) { // get country from customer addresses if (null !== $customer) { $address = AddressQuery::create()->filterByCustomerId($customer->getId())->filterByIsDefault(1)->findOne(); if (null !== $address) { $this->isCustomizable = false; return $address->getCountry(); } } // get country from cookie $cookieName = ConfigQuery::read('front_cart_country_cookie_name', 'fcccn'); if ($this->request->cookies->has($cookieName)) { $cookieVal = $this->request->cookies->getInt($cookieName, 0); if (0 !== $cookieVal) { $country = CountryQuery::create()->findPk($cookieVal); if (null !== $country) { return $country; } } } // get default country for store. try { $country = Country::getDefaultCountry(); return $country; } catch (\LogicException $e) { } return null; }
/** * Provides access to an attribute of the default country * * @param array $params * @param \Smarty $smarty * @return string the value of the requested attribute */ public function countryDataAccess($params, $smarty) { switch ($params["ask"]) { case "default": return $this->dataAccessWithI18n("defaultCountry", $params, CountryQuery::create()->filterByByDefault(1)->limit(1)); } return ''; }
/** * Get the associated ChildCountry object * * @param ConnectionInterface $con Optional Connection object. * @return ChildCountry The associated ChildCountry object. * @throws PropelException */ public function getCountry(ConnectionInterface $con = null) { if ($this->aCountry === null && $this->country_id !== null) { $this->aCountry = ChildCountryQuery::create()->findPk($this->country_id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aCountry->addOrderAddresses($this); */ } return $this->aCountry; }
public function toggleProductSync($id) { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('GoogleShopping'), AccessManager::UPDATE))) { return $response; } if ($this->getRequest()->query->get('target_country')) { $targetCountry = CountryQuery::create()->findOneByIsoalpha2($this->getRequest()->get('target_country')); } else { $targetCountry = Country::getDefaultCountry(); } if ($this->getRequest()->query->get('locale')) { $lang = LangQuery::create()->findOneByLocale($this->getRequest()->query->get('locale')); } else { $lang = Lang::getDefaultLanguage(); } $product = ProductQuery::create()->findPk($id); $googleProductEvent = new GoogleProductEvent($product); $googleProductEvent->setTargetCountry($targetCountry)->setLang($lang); $this->getDispatcher()->dispatch(GoogleShoppingEvents::GOOGLE_PRODUCT_TOGGLE_SYNC, $googleProductEvent); }
public function buildModelCriteria() { $search = CountryQuery::create(); /* manage translations */ $this->configureI18nProcessing($search); $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $area = $this->getArea(); if (null !== $area) { $search->useCountryAreaQuery('with_area')->filterByAreaId($area, Criteria::IN)->endUse(); } $excludeArea = $this->getExcludeArea(); if (null !== $excludeArea) { // FIXME : did not find a way to do this in a single request :( // select * from country where id not in (select country_id from country_area where area in (...)) $countries = CountryAreaQuery::create()->filterByAreaId($excludeArea, Criteria::IN)->select(['country_id'])->find(); $search->filterById($countries->toArray(), Criteria::NOT_IN); } $withArea = $this->getWithArea(); if (true === $withArea) { $search->distinct()->joinCountryArea('with_area', Criteria::LEFT_JOIN)->where('`with_area`.country_id ' . Criteria::ISNOTNULL); } elseif (false === $withArea) { $search->joinCountryArea('with_area', Criteria::LEFT_JOIN)->where('`with_area`.country_id ' . Criteria::ISNULL); } $exclude = $this->getExclude(); if (!is_null($exclude)) { $search->filterById($exclude, Criteria::NOT_IN); } $hasStates = $this->getHasStates(); if ($hasStates !== BooleanOrBothType::ANY) { $search->filterByHasStates($hasStates ? 1 : 0); } $visible = $this->getVisible(); if ($visible !== BooleanOrBothType::ANY) { $search->filterByVisible($visible ? 1 : 0); } $orders = $this->getOrder(); foreach ($orders as $order) { switch ($order) { case "id": $search->orderById(Criteria::ASC); break; case "id_reverse": $search->orderById(Criteria::DESC); break; case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); break; case "alpha_reverse": $search->addDescendingOrderByColumn('i18n_TITLE'); break; case "visible": $search->orderByVisible(Criteria::ASC); break; case "visible_reverse": $search->orderByVisible(Criteria::DESC); break; case "random": $search->clearOrderByColumns(); $search->addAscendingOrderByColumn('RAND()'); break 2; break; } } return $search; }