public function verifyTitle($value, ExecutionContextInterface $context) { $address = CustomerTitleQuery::create()->findPk($value); if (null === $address) { $context->addViolation(Translator::getInstance()->trans("Title ID not found")); } }
public function buildModelCriteria() { $search = CustomerTitleQuery::create(); /* manage translations */ $this->configureI18nProcessing($search, array('SHORT', 'LONG')); $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $search->orderByPosition(); return $search; }
public function testListActionWithLocale() { $client = static::createClient(); $client->request('GET', '/api/title?lang=fr_FR&sign=' . $this->getSignParameter(''), [], [], $this->getServerParameters()); $maxCount = CustomerTitleQuery::create()->count(); if ($maxCount > 10) { $maxCount = 10; } $this->assertEquals(200, $client->getResponse()->getStatusCode(), 'Http status code must be 200'); $content = json_decode($client->getResponse()->getContent(), true); $this->assertCount($maxCount, $content, sprintf('reponse must contains %d results', $maxCount)); $firstResult = $content[0]; $this->assertEquals('fr_FR', $firstResult['LOCALE'], 'the returned locale must be fr_FR'); }
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")); } }
/** * Get the associated ChildCustomerTitle object * * @param ConnectionInterface $con Optional Connection object. * @return ChildCustomerTitle The associated ChildCustomerTitle object. * @throws PropelException */ public function getCustomerTitle(ConnectionInterface $con = null) { if ($this->aCustomerTitle === null && $this->id !== null) { $this->aCustomerTitle = ChildCustomerTitleQuery::create()->findPk($this->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->aCustomerTitle->addCustomerTitleI18ns($this); */ } return $this->aCustomerTitle; }
/** * Performs an INSERT on the database, given a CustomerTitle or Criteria object. * * @param mixed $criteria Criteria or CustomerTitle object containing data that is used to create the INSERT statement. * @param ConnectionInterface $con the ConnectionInterface connection to use * @return mixed The new primary key. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ public static function doInsert($criteria, ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(CustomerTitleTableMap::DATABASE_NAME); } if ($criteria instanceof Criteria) { $criteria = clone $criteria; // rename for clarity } else { $criteria = $criteria->buildCriteria(); // build Criteria from CustomerTitle object } if ($criteria->containsKey(CustomerTitleTableMap::ID) && $criteria->keyContainsValue(CustomerTitleTableMap::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . CustomerTitleTableMap::ID . ')'); } // Set the correct dbName $query = CustomerTitleQuery::create()->mergeWith($criteria); try { // use transaction because $criteria could contain info // for more than one table (I guess, conceivably) $con->beginTransaction(); $pk = $query->doInsert($con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } return $pk; }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see CustomerTitle::setDeleted() * @see CustomerTitle::isDeleted() */ public function delete(ConnectionInterface $con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getServiceContainer()->getWriteConnection(CustomerTitleTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildCustomerTitleQuery::create()->filterByPrimaryKey($this->getPrimaryKey()); $ret = $this->preDelete($con); if ($ret) { $deleteQuery->delete($con); $this->postDelete($con); $con->commit(); $this->setDeleted(true); } else { $con->commit(); } } catch (Exception $e) { $con->rollBack(); throw $e; } }
/** * @return Customer */ public static function createShoppingFluxCustomer() { $shoppingFluxCustomer = CustomerQuery::create()->findOneByRef("ShoppingFlux"); if (null === $shoppingFluxCustomer) { $shoppingFluxCustomer = new Customer(); $shoppingFluxCustomer->setRef("ShoppingFlux")->setCustomerTitle(CustomerTitleQuery::create()->findOne())->setLastname("ShoppingFlux")->setFirstname("ShoppingFlux")->save(); } return $shoppingFluxCustomer; }
/** * @param FormEvent $event * * This methods loads current title data into the update form. * It uses an event to load only needed ids. */ public function hydrateUpdateForm(FormEvent $event) { $data = $event->getData(); $title = CustomerTitleQuery::create()->findPk($data["title_id"]); if (null === $title) { $this->entityNotFound($data["title_id"]); } $data["default"] |= (bool) $title->getByDefault(); $titleI18ns = CustomerTitleI18nQuery::create()->filterById($data["title_id"])->find()->toKeyIndex('Locale'); $i18n =& $data["i18n"]; foreach ($data["i18n"] as $key => $value) { $i18n[$value["locale"]] = $value; unset($i18n[$key]); } /** @var \Thelia\Model\CustomerTitleI18n $titleI18n */ foreach ($titleI18ns as $titleI18n) { $row = array(); $row["locale"] = $locale = $titleI18n->getLocale(); $row["short"] = $titleI18n->getShort(); $row["long"] = $titleI18n->getLong(); if (!isset($i18n[$locale])) { $i18n[$locale] = array(); } $i18n[$locale] = array_merge($row, $i18n[$locale]); } $event->setData($data); }
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()); } }
public function testQuery() { new Translator(new Container()); $handler = new CustomerExport(new Container()); $lang = Lang::getDefaultLanguage(); $data = $handler->buildData($lang); $keys = ["ref", "title", "last_name", "first_name", "email", "label", "discount", "is_registered_to_newsletter", "sign_up_date", "total_orders", "last_order_amount", "last_order_date", "address_first_name", "address_last_name", "company", "address1", "address2", "address3", "zipcode", "city", "country", "phone", "cellphone", "is_default_address", "address_title"]; sort($keys); $rawData = $data->getData(); $max = CustomerQuery::create()->count(); /** * 30 customers that has more than 1 addresses or enough */ if (30 < $max) { $max = 30; } for ($i = 0; $i < $max;) { $row = $rawData[$i]; $rowKeys = array_keys($row); sort($rowKeys); $this->assertEquals($rowKeys, $keys); $customer = CustomerQuery::create()->findOneByRef($row["ref"]); $this->assertNotNull($customer); $this->assertEquals($customer->getFirstname(), $row["first_name"]); $this->assertEquals($customer->getLastname(), $row["last_name"]); $this->assertEquals($customer->getEmail(), $row["email"]); $this->assertEquals($customer->getCreatedAt()->format($lang->getDatetimeFormat()), $row["sign_up_date"]); $this->assertEquals($customer->getDiscount(), $row["discount"]); $title = CustomerTitleQuery::create()->findPk($customer->getTitleId()); $this->assertEquals($title->getShort(), $row["title"]); $total = 0; foreach ($customer->getOrders() as $order) { $amount = $order->getTotalAmount($tax); if (0 < ($rate = $order->getCurrencyRate())) { $amount = round($amount / $rate, 2); } $total += $amount; } $defaultCurrencyCode = Currency::getDefaultCurrency()->getCode(); $this->assertEquals($total . " " . $defaultCurrencyCode, $row["total_orders"]); $lastOrder = OrderQuery::create()->filterByCustomer($customer)->orderByCreatedAt(Criteria::DESC)->orderById(Criteria::DESC)->findOne(); if (null !== $lastOrder) { $expectedPrice = $lastOrder->getTotalAmount($tax_) . " " . $lastOrder->getCurrency()->getCode(); $expectedDate = $lastOrder->getCreatedAt()->format($lang->getDatetimeFormat()); } else { $expectedPrice = ""; $expectedDate = ""; } $this->assertEquals($expectedPrice, $row["last_order_amount"]); $this->assertEquals($expectedDate, $row["last_order_date"]); $newsletter = NewsletterQuery::create()->findOneByEmail($customer->getEmail()); $this->assertEquals($newsletter === null ? 0 : 1, $row["is_registered_to_newsletter"]); do { $address = AddressQuery::create()->filterByCustomer($customer)->filterByAddress1($rawData[$i]["address1"])->filterByAddress2($rawData[$i]["address2"])->filterByAddress3($rawData[$i]["address3"])->filterByFirstname($rawData[$i]["address_first_name"])->filterByLastname($rawData[$i]["address_last_name"])->filterByCountryId(CountryI18nQuery::create()->filterByLocale($lang->getLocale())->findOneByTitle($rawData[$i]["country"])->getId())->filterByCompany($rawData[$i]["company"])->_if(empty($rawData[$i]["company"]))->_or()->filterByCompany(null, Criteria::ISNULL)->_endif()->filterByZipcode($rawData[$i]["zipcode"])->filterByCity($rawData[$i]["city"])->filterByIsDefault($rawData[$i]["is_default_address"])->filterByCellphone($rawData[$i]["cellphone"])->_if(empty($rawData[$i]["cellphone"]))->_or()->filterByCellphone(null, Criteria::ISNULL)->_endif()->filterByPhone($rawData[$i]["phone"])->_if(empty($rawData[$i]["phone"]))->_or()->filterByPhone(null, Criteria::ISNULL)->_endif()->filterByLabel($rawData[$i]["label"])->_if(empty($rawData[$i]["label"]))->_or()->filterByLabel(null, Criteria::ISNULL)->_endif()->filterByTitleId(CustomerTitleI18nQuery::create()->filterByLocale($lang->getLocale())->findOneByShort($rawData[$i]["address_title"])->getId())->findOne(); $this->assertNotNull($address); $rowKeys = array_keys($rawData[$i]); sort($rowKeys); $this->assertEquals($rowKeys, $keys); } while (isset($rawData[++$i]["ref"]) && $rawData[$i - 1]["ref"] === $rawData[$i]["ref"] && ++$max); } }
public function importCustomerTitle() { $con = Propel::getConnection(CustomerTitleTableMap::DATABASE_NAME); $con->beginTransaction(); try { CustomerTitleQuery::create()->deleteAll(); $hdl = $this->t1db->query("select * from raison order by classement"); while ($hdl && ($raison = $this->t1db->fetch_object($hdl))) { $ct = new CustomerTitle(); $descs = $this->t1db->query_list("select * from raisondesc where raison = ? order by lang asc", array($raison->id)); foreach ($descs as $desc) { $lang = $this->getT2Lang($desc->lang); $ct->setLocale($lang->getLocale())->setByDefault($raison->defaut ? true : false)->setPosition($raison->classement)->setLong($desc->long)->setShort($desc->court)->save(); } } $con->commit(); } catch (\Exception $ex) { $con->rollBack(); Tlog::getInstance()->error("Failed to import Thelia 1 customer titles (not a problem for Thelia 1.4.x). Cause: " . $ex->getMessage()); } }