public function verifyExistingEmail($value, ExecutionContextInterface $context) { $customer = CustomerQuery::create()->findOneByEmail($value); if (null === $customer) { $context->addViolation(Translator::getInstance()->trans("This email does not exists")); } }
/** * @param OrderQuery $search * @param $searchTerm * @param $searchIn * @param $searchCriteria */ public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria) { $search->_and(); foreach ($searchIn as $index => $searchInElement) { if ($index > 0) { $search->_or(); } switch ($searchInElement) { case 'ref': $search->filterByRef($searchTerm, $searchCriteria); break; case 'invoice_ref': $search->filterByInvoiceRef($searchTerm, $searchCriteria); break; case 'customer_ref': $search->filterByCustomer(CustomerQuery::create()->filterByRef($searchTerm, $searchCriteria)->find()); break; case 'customer_firstname': $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(OrderAddressQuery::create()->filterByFirstname($searchTerm, $searchCriteria)->find()); break; case 'customer_lastname': $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(OrderAddressQuery::create()->filterByLastname($searchTerm, $searchCriteria)->find()); break; case 'customer_email': $search->filterByCustomer(CustomerQuery::create()->filterByEmail($searchTerm, $searchCriteria)->find()); break; } } }
public function loginAction() { $customerController = new BaseCustomerController(); $customerController->setContainer($this->container); $response = $customerController->loginAction(); if (!$this->getSecurityContext()->hasCustomerUser()) { $request = $this->getRequest(); $customerLoginForm = new CustomerLogin($request); try { $form = $this->validateForm($customerLoginForm, "post"); $request = CustomerTempQuery::create(); $customerTemp = $request->where('`customer_temp`.email = ?', $form->get('email')->getData(), \PDO::PARAM_STR)->where('`customer_temp`.password = PASSWORD(?)', $form->get('password')->getData(), \PDO::PARAM_STR)->where('`customer_temp`.processed = 0')->findOne(); if (null !== $customerTemp) { $customer = CustomerQuery::create()->findOneByEmail($form->get('email')->getData()); $customer->setPassword($form->get('password')->getData())->save(); $customerTemp->setProcessed(true)->save(); $this->dispatch(TheliaEvents::CUSTOMER_LOGIN, new CustomerLoginEvent($customer)); $successUrl = $customerLoginForm->getSuccessUrl(); $response = RedirectResponse::create($successUrl); } } catch (\Exception $e) { } } return $response; }
public function testRenderLoop() { $customerId = CustomerQuery::create()->findOne()->getId(); $this->handler->expects($this->any())->method("buildDataSet")->willReturn($this->handler->renderLoop("address", ["customer" => $customerId])); $lang = Lang::getDefaultLanguage(); $loop = $this->handler->buildDataSet($lang); $this->assertInstanceOf("Thelia\\Core\\Template\\Loop\\Address", $loop); $data = $this->handler->buildData($lang); $addresses = AddressQuery::create()->filterByCustomerId($customerId)->find()->toArray("Id"); foreach ($data->getData() as $row) { $this->assertArrayHasKey("id", $row); $this->assertArrayHasKey($row["id"], $addresses); $this->assertEquals(count($addresses), $row["loop_total"]); $address = $addresses[$row["id"]]; $this->assertEquals($row["address1"], $address["Address1"]); $this->assertEquals($row["address2"], $address["Address2"]); $this->assertEquals($row["address3"], $address["Address3"]); $this->assertEquals($row["cellphone"], $address["Cellphone"]); $this->assertEquals($row["city"], $address["City"]); $this->assertEquals($row["company"], $address["Company"]); $this->assertEquals($row["country"], $address["CountryId"]); $this->assertEquals($row["create_date"], $address["CreatedAt"]); $this->assertEquals($row["update_date"], $address["UpdatedAt"]); $this->assertEquals($row["firstname"], $address["Firstname"]); $this->assertEquals($row["lastname"], $address["Lastname"]); $this->assertEquals($row["id"], $address["Id"]); $this->assertEquals($row["label"], $address["Label"]); $this->assertEquals($row["phone"], $address["Phone"]); $this->assertEquals($row["title"], $address["TitleId"]); $this->assertEquals($row["zipcode"], $address["Zipcode"]); } }
/** * @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; }
/** * If the user select "I'am a new customer", we make sure is email address does not exit in the database. */ public function verifyExistingEmail($value, ExecutionContextInterface $context) { $data = $context->getRoot()->getData(); if ($data["account"] == 0) { $customer = CustomerQuery::create()->findOneByEmail($value); if ($customer) { $context->addViolation(Translator::getInstance()->trans("A user already exists with this email address. Please login or if you've forgotten your password, go to Reset Your Password.")); } } }
public function verifyCurrentPasswordField($value, ExecutionContextInterface $context) { /** * Retrieve the user recording, because after the login action, the password is deleted in the session */ $userId = $this->getRequest()->getSession()->getCustomerUser()->getId(); $user = CustomerQuery::create()->findPk($userId); // Check if value of the old password match the password of the current user if (!password_verify($value, $user->getPassword())) { $context->addViolation(Translator::getInstance()->trans("Your current password does not match.")); } }
public function preImport() { // Empty address, customer and customer title table OrderQuery::create()->deleteAll(); AddressQuery::create()->deleteAll(); OrderAddressQuery::create()->deleteAll(); CustomerQuery::create()->deleteAll(); // Also empty url rewriting table $con = Propel::getConnection(RewritingUrlTableMap::DATABASE_NAME); $con->exec('SET FOREIGN_KEY_CHECKS=0'); RewritingUrlQuery::create()->deleteAll(); $con->exec('SET FOREIGN_KEY_CHECKS=1'); $this->cust_corresp->reset(); if ($this->thelia_version > 150) { $this->importCustomerTitle(); } }
public function addAmount() { if (null !== ($response = $this->checkAuth(array(AdminResources::CUSTOMER), array('CreditAccount'), AccessManager::UPDATE))) { return $response; } $form = new CreditAccountForm($this->getRequest()); try { $creditForm = $this->validateForm($form); $customer = CustomerQuery::create()->findPk($creditForm->get('customer_id')->getData()); $event = new CreditAccountEvent($customer, $creditForm->get('amount')->getData()); /** @var Admin $admin */ $admin = $this->getSession()->getAdminUser(); $event->setWhoDidIt($admin->getFirstname() . " " . $admin->getLastname()); $this->dispatch(CreditAccount::CREDIT_ACCOUNT_ADD_AMOUNT, $event); } catch (\Exception $ex) { $this->setupFormErrorContext($this->getTranslator()->trans("Add amount to credit account"), $ex->getMessage(), $form, $ex); } return $this->generateRedirect($form->getSuccessUrl()); }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see Customer::setDeleted() * @see Customer::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(CustomerTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildCustomerQuery::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; } }
/** * Creates the creation event with the provided form data * * @param unknown $formData */ protected function getCreationEvent($formData) { $event = $this->getCreateOrUpdateEvent($formData); $customer = CustomerQuery::create()->findPk($this->getRequest()->get("customer_id")); $event->setCustomer($customer); return $event; }
/** * @covers \Thelia\Controller\Api\CustomerController::checkLoginAction */ public function testCheckLoginWithWrongPassword() { $logins = ['email' => CustomerQuery::create()->findPk(1)->getEmail(), 'password' => 'notthis']; $requestContent = json_encode($logins); $client = static::createClient(); $servers = $this->getServerParameters(); $servers['CONTENT_TYPE'] = 'application/json'; $client->request('POST', '/api/customers/checkLogin?&sign=' . $this->getSignParameter($requestContent), [], [], $servers, $requestContent); $this->assertEquals(404, $client->getResponse()->getStatusCode()); }
public function parseResults(LoopResult $loopResult) { /** @var \Thelia\Model\Customer $customer */ foreach ($loopResult->getResultDataCollection() as $customer) { $loopResultRow = new LoopResultRow($customer); $loopResultRow->set("ID", $customer->getId())->set("REF", $customer->getRef())->set("TITLE", $customer->getTitleId())->set("FIRSTNAME", $customer->getFirstname())->set("LASTNAME", $customer->getLastname())->set("EMAIL", $customer->getEmail())->set("RESELLER", $customer->getReseller())->set("SPONSOR", $customer->getSponsor())->set("DISCOUNT", $customer->getDiscount())->set("NEWSLETTER", $customer->getVirtualColumn("is_registered_to_newsletter")); if ($this->getWithPrevNextInfo()) { // Find previous and next category $previousQuery = CustomerQuery::create()->filterById($customer->getId(), Criteria::LESS_THAN); $previous = $previousQuery->orderById(Criteria::DESC)->findOne(); $nextQuery = CustomerQuery::create()->filterById($customer->getId(), Criteria::GREATER_THAN); $next = $nextQuery->orderById(Criteria::ASC)->findOne(); $loopResultRow->set("HAS_PREVIOUS", $previous != null ? 1 : 0)->set("HAS_NEXT", $next != null ? 1 : 0)->set("PREVIOUS", $previous != null ? $previous->getId() : -1)->set("NEXT", $next != null ? $next->getId() : -1); } $this->addOutputFields($loopResultRow, $customer); $loopResult->addRow($loopResultRow); } return $loopResult; }
public function getUser($dataArray) { return CustomerQuery::create()->filterByEmail($dataArray['username'], Criteria::EQUAL)->filterByRememberMeSerial($dataArray['serial'], Criteria::EQUAL)->filterByRememberMeToken($dataArray['token'], Criteria::EQUAL)->findOne(); }
public static function setUpBeforeClass() { CustomerQuery::create()->filterByRef('testRef')->delete(); }
/** * Get the associated ChildCustomer object * * @param ConnectionInterface $con Optional Connection object. * @return ChildCustomer The associated ChildCustomer object. * @throws PropelException */ public function getCustomer(ConnectionInterface $con = null) { if ($this->aCustomer === null && $this->customer_id !== null) { $this->aCustomer = ChildCustomerQuery::create()->findPk($this->customer_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->aCustomer->addOrders($this); */ } return $this->aCustomer; }
echo "Creating orders\n"; $colissimo_id = ModuleQuery::create()->filterByCode("Colissimo")->findOne()->getId(); $cheque_id = ModuleQuery::create()->filterByCode("Cheque")->findOne()->getId(); for ($i = 0; $i < 50; ++$i) { $placedOrder = new \Thelia\Model\Order(); $deliveryOrderAddress = new OrderAddress(); $deliveryOrderAddress->setCustomerTitleId(mt_rand(1, 3))->setCompany(getRealText(15))->setFirstname($faker->firstname)->setLastname($faker->lastname)->setAddress1($faker->streetAddress)->setAddress2($faker->streetAddress)->setAddress3($faker->streetAddress)->setPhone($faker->phoneNumber)->setZipcode($faker->postcode)->setCity($faker->city)->setCountryId(64)->save($con); $invoiceOrderAddress = new OrderAddress(); $invoiceOrderAddress->setCustomerTitleId(mt_rand(1, 3))->setCompany(getRealText(15))->setFirstname($faker->firstname)->setLastname($faker->lastname)->setAddress1($faker->streetAddress)->setAddress2($faker->streetAddress)->setAddress3($faker->streetAddress)->setPhone($faker->phoneNumber)->setZipcode($faker->postcode)->setCity($faker->city)->setCountryId(64)->save($con); /** * Create a cart for the order */ $cart = new \Thelia\Model\Cart(); $cart->save(); $currency = \Thelia\Model\CurrencyQuery::create()->addAscendingOrderByColumn('RAND()')->findOne(); $placedOrder->setDeliveryOrderAddressId($deliveryOrderAddress->getId())->setInvoiceOrderAddressId($invoiceOrderAddress->getId())->setDeliveryModuleId($colissimo_id)->setPaymentModuleId($cheque_id)->setStatusId(mt_rand(1, 5))->setCurrencyRate($currency->getRate())->setCurrencyId($currency->getId())->setCustomer(\Thelia\Model\CustomerQuery::create()->addAscendingOrderByColumn('RAND()')->findOne())->setDiscount(mt_rand(0, 10))->setLang(\Thelia\Model\LangQuery::create()->addAscendingOrderByColumn('RAND()')->findOne())->setPostage(mt_rand(1, 50))->setCartId($cart->getId()); $placedOrder->save($con); for ($j = 0; $j < mt_rand(1, 10); ++$j) { $pse = \Thelia\Model\ProductSaleElementsQuery::create()->addAscendingOrderByColumn('RAND()')->findOne(); $product = $pse->getProduct(); $orderProduct = new \Thelia\Model\OrderProduct(); $orderProduct->setOrderId($placedOrder->getId())->setProductRef($product->getRef())->setProductSaleElementsRef($pse->getRef())->setProductSaleElementsId($pse->getId())->setTitle($product->getTitle())->setChapo($product->getChapo())->setDescription($product->getDescription())->setPostscriptum($product->getPostscriptum())->setQuantity(mt_rand(1, 10))->setPrice($price = mt_rand(1, 100))->setPromoPrice(mt_rand(1, $price))->setWasNew($pse->getNewness())->setWasInPromo(rand(0, 1) == 1)->setWeight($pse->getWeight())->setTaxRuleTitle(getRealText(20))->setTaxRuleDescription(getRealText(50))->setEanCode($pse->getEanCode())->save($con); } } echo "Generating coupons fixtures\n"; generateCouponFixtures($thelia); echo "Generating sales\n"; for ($idx = 1; $idx <= 5; $idx++) { $sale = new \Thelia\Model\Sale(); $start = new \DateTime(); $end = new \DateTime();
/** * @inheritdoc */ public function getSummary() { $i18nOperator = Operators::getI18n($this->translator, $this->operators[self::CUSTOMERS_LIST]); $custStrList = ''; $custIds = $this->values[self::CUSTOMERS_LIST]; if (null !== ($custList = CustomerQuery::create()->findPks($custIds))) { /** @var Customer $cust */ foreach ($custList as $cust) { $custStrList .= $cust->getLastname() . ' ' . $cust->getFirstname() . ' (' . $cust->getRef() . '), '; } $custStrList = rtrim($custStrList, ', '); } $toolTip = $this->translator->trans('Customer is %op% <strong>%customer_list%</strong>', ['%customer_list%' => $custStrList, '%op%' => $i18nOperator]); return $toolTip; }
/** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this CustomerTitle is new, it will return * an empty collection; or if this CustomerTitle has previously * been saved, it will retrieve related Customers from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in CustomerTitle. * * @param Criteria $criteria optional Criteria object to narrow the query * @param ConnectionInterface $con optional connection object * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return Collection|ChildCustomer[] List of ChildCustomer objects */ public function getCustomersJoinLangModel($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildCustomerQuery::create(null, $criteria); $query->joinWith('LangModel', $joinBehavior); return $this->getCustomers($query, $con); }
function clearTables($con) { echo "Clearing tables\n"; $productAssociatedContent = Thelia\Model\ProductAssociatedContentQuery::create()->find($con); $productAssociatedContent->delete($con); $categoryAssociatedContent = Thelia\Model\CategoryAssociatedContentQuery::create()->find($con); $categoryAssociatedContent->delete($con); $featureProduct = Thelia\Model\FeatureProductQuery::create()->find($con); $featureProduct->delete($con); $attributeCombination = Thelia\Model\AttributeCombinationQuery::create()->find($con); $attributeCombination->delete($con); $feature = Thelia\Model\FeatureQuery::create()->find($con); $feature->delete($con); $feature = Thelia\Model\FeatureI18nQuery::create()->find($con); $feature->delete($con); $featureAv = Thelia\Model\FeatureAvQuery::create()->find($con); $featureAv->delete($con); $featureAv = Thelia\Model\FeatureAvI18nQuery::create()->find($con); $featureAv->delete($con); $attribute = Thelia\Model\AttributeQuery::create()->find($con); $attribute->delete($con); $attribute = Thelia\Model\AttributeI18nQuery::create()->find($con); $attribute->delete($con); $attributeAv = Thelia\Model\AttributeAvQuery::create()->find($con); $attributeAv->delete($con); $attributeAv = Thelia\Model\AttributeAvI18nQuery::create()->find($con); $attributeAv->delete($con); $brand = Thelia\Model\BrandQuery::create()->find($con); $brand->delete($con); $brand = Thelia\Model\BrandI18nQuery::create()->find($con); $brand->delete($con); $category = Thelia\Model\CategoryQuery::create()->find($con); $category->delete($con); $category = Thelia\Model\CategoryI18nQuery::create()->find($con); $category->delete($con); $product = Thelia\Model\ProductQuery::create()->find($con); $product->delete($con); $product = Thelia\Model\ProductI18nQuery::create()->find($con); $product->delete($con); $folder = Thelia\Model\FolderQuery::create()->find($con); $folder->delete($con); $folder = Thelia\Model\FolderI18nQuery::create()->find($con); $folder->delete($con); $content = Thelia\Model\ContentQuery::create()->find($con); $content->delete($con); $content = Thelia\Model\ContentI18nQuery::create()->find($con); $content->delete($con); $accessory = Thelia\Model\AccessoryQuery::create()->find($con); $accessory->delete($con); $stock = \Thelia\Model\ProductSaleElementsQuery::create()->find($con); $stock->delete($con); $productPrice = \Thelia\Model\ProductPriceQuery::create()->find($con); $productPrice->delete($con); \Thelia\Model\ProductImageQuery::create()->find($con)->delete($con); $customer = \Thelia\Model\CustomerQuery::create()->find($con); $customer->delete($con); $sale = \Thelia\Model\SaleQuery::create()->find($con); $sale->delete($con); $saleProduct = \Thelia\Model\SaleProductQuery::create()->find($con); $saleProduct->delete($con); echo "Tables cleared with success\n"; }
/** * Performs an INSERT on the database, given a Customer or Criteria object. * * @param mixed $criteria Criteria or Customer 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(CustomerTableMap::DATABASE_NAME); } if ($criteria instanceof Criteria) { $criteria = clone $criteria; // rename for clarity } else { $criteria = $criteria->buildCriteria(); // build Criteria from Customer object } if ($criteria->containsKey(CustomerTableMap::ID) && $criteria->keyContainsValue(CustomerTableMap::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . CustomerTableMap::ID . ')'); } // Set the correct dbName $query = CustomerQuery::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; }
public function lostPassword(LostPasswordEvent $event) { if (null !== ($customer = CustomerQuery::create()->filterByEmail($event->getEmail())->findOne())) { $password = Password::generateRandom(8); $customer->setPassword($password)->save(); $this->mailer->sendEmailToCustomer('lost_password', $customer, ['password' => $password]); } }
/** * @param Lang $lang * @return array|\Propel\Runtime\ActiveQuery\ModelCriteria * * The tax engine of Thelia is in PHP, so we can't compute orders for each customers * directly in SQL, we need two SQL queries, and some computing to get the last order amount and total amount. */ public function buildDataSet(Lang $lang) { $locale = $lang->getLocale(); /** * This first query get each customer info and addresses. */ $newsletterJoin = new Join(CustomerTableMap::EMAIL, NewsletterTableMap::EMAIL, Criteria::LEFT_JOIN); $query = CustomerQuery::create()->useCustomerTitleQuery("customer_title_")->useCustomerTitleI18nQuery("customer_title_i18n_")->addAsColumn("title_TITLE", "customer_title_i18n_.SHORT")->endUse()->endUse()->useAddressQuery()->useCountryQuery()->useCountryI18nQuery()->addAsColumn("address_COUNTRY", CountryI18nTableMap::TITLE)->endUse()->endUse()->useCustomerTitleQuery("address_title")->useCustomerTitleI18nQuery("address_title_i18n")->addAsColumn("address_TITLE", "address_title_i18n.SHORT")->endUse()->endUse()->addAsColumn("address_LABEL", AddressTableMap::LABEL)->addAsColumn("address_FIRST_NAME", AddressTableMap::FIRSTNAME)->addAsColumn("address_LAST_NAME", AddressTableMap::LASTNAME)->addAsColumn("address_COMPANY", AddressTableMap::COMPANY)->addAsColumn("address_ADDRESS1", AddressTableMap::ADDRESS1)->addAsColumn("address_ADDRESS2", AddressTableMap::ADDRESS2)->addAsColumn("address_ADDRESS3", AddressTableMap::ADDRESS3)->addAsColumn("address_ZIPCODE", AddressTableMap::ZIPCODE)->addAsColumn("address_CITY", AddressTableMap::CITY)->addAsColumn("address_PHONE", AddressTableMap::PHONE)->addAsColumn("address_CELLPHONE", AddressTableMap::CELLPHONE)->addAsColumn("address_IS_DEFAULT", AddressTableMap::IS_DEFAULT)->endUse()->addJoinObject($newsletterJoin)->addAsColumn("newsletter_IS_REGISTRED", "IF(NOT ISNULL(" . NewsletterTableMap::EMAIL . "),1,0)")->select([CustomerTableMap::ID, CustomerTableMap::REF, CustomerTableMap::LASTNAME, CustomerTableMap::FIRSTNAME, CustomerTableMap::EMAIL, CustomerTableMap::DISCOUNT, CustomerTableMap::CREATED_AT, "title_TITLE", "address_TITLE", "address_LABEL", "address_COMPANY", "address_FIRST_NAME", "address_LAST_NAME", "address_ADDRESS1", "address_ADDRESS2", "address_ADDRESS3", "address_ZIPCODE", "address_CITY", "address_COUNTRY", "address_PHONE", "address_CELLPHONE", "address_IS_DEFAULT", "newsletter_IS_REGISTRED"])->orderById(); I18n::addI18nCondition($query, CountryI18nTableMap::TABLE_NAME, CountryTableMap::ID, CountryI18nTableMap::ID, CountryI18nTableMap::LOCALE, $locale); I18n::addI18nCondition($query, CustomerTitleI18nTableMap::TABLE_NAME, "`customer_title_`.ID", "`customer_title_i18n_`.ID", "`customer_title_i18n_`.LOCALE", $locale); I18n::addI18nCondition($query, CustomerTitleI18nTableMap::TABLE_NAME, "`address_title`.ID", "`address_title_i18n`.ID", "`address_title_i18n`.LOCALE", $locale); /** @var CustomerQuery $query */ $results = $query->find()->toArray(); /** * Then get the orders */ $orders = OrderQuery::create()->useCustomerQuery()->orderById()->endUse()->find(); /** * And add them info the array */ $orders->rewind(); $arrayLength = count($results); $previousCustomerId = null; for ($i = 0; $i < $arrayLength; ++$i) { $currentCustomer =& $results[$i]; $currentCustomerId = $currentCustomer[CustomerTableMap::ID]; unset($currentCustomer[CustomerTableMap::ID]); if ($currentCustomerId === $previousCustomerId) { $currentCustomer["title_TITLE"] = ""; $currentCustomer[CustomerTableMap::LASTNAME] = ""; $currentCustomer[CustomerTableMap::FIRSTNAME] = ""; $currentCustomer[CustomerTableMap::EMAIL] = ""; $currentCustomer["address_COMPANY"] = ""; $currentCustomer["newsletter_IS_REGISTRED"] = ""; $currentCustomer[CustomerTableMap::CREATED_AT] = ""; $currentCustomer[CustomerTableMap::DISCOUNT] = ""; $currentCustomer += ["order_TOTAL" => "", "last_order_AMOUNT" => "", "last_order_DATE" => ""]; } else { /** * Reformat created_at date */ $date = $currentCustomer[CustomerTableMap::CREATED_AT]; $dateTime = new \DateTime($date); $currentCustomer[CustomerTableMap::CREATED_AT] = $dateTime->format($lang->getDatetimeFormat()); /** * Then compute everything about the orders */ $total = 0; $lastOrderAmount = 0; $lastOrderDate = null; $lastOrder = null; $lastOrderCurrencyCode = null; $lastOrderId = 0; $defaultCurrency = Currency::getDefaultCurrency(); $defaultCurrencyCode = $defaultCurrency->getCode(); if (empty($defaultCurrencyCode)) { $defaultCurrencyCode = $defaultCurrency->getCode(); } $formattedDate = null; /** @var \Thelia\Model\Order $currentOrder */ while (false !== ($currentOrder = $orders->current())) { if ($currentCustomerId != $currentOrder->getCustomerId()) { break; } $amount = $currentOrder->getTotalAmount($tax); if (0 < ($rate = $currentOrder->getCurrencyRate())) { $amount = round($amount / $rate, 2); } $total += $amount; /** @var \DateTime $date */ $date = $currentOrder->getCreatedAt(); if (null === $lastOrderDate || $date >= $lastOrderDate && $lastOrderId < $currentOrder->getId()) { $lastOrder = $currentOrder; $lastOrderDate = $date; $lastOrderId = $currentOrder->getId(); } $orders->next(); } if ($lastOrderDate !== null) { $formattedDate = $lastOrderDate->format($lang->getDatetimeFormat()); $orderCurrency = $lastOrder->getCurrency(); $lastOrderCurrencyCode = $orderCurrency->getCode(); if (empty($lastOrderCurrencyCode)) { $lastOrderCurrencyCode = $orderCurrency->getCode(); } $lastOrderAmount = $lastOrder->getTotalAmount($tax_); } $currentCustomer += ["order_TOTAL" => $total . " " . $defaultCurrencyCode, "last_order_AMOUNT" => $lastOrderAmount === 0 ? "" : $lastOrderAmount . " " . $lastOrderCurrencyCode, "last_order_DATE" => $formattedDate]; } $previousCustomerId = $currentCustomerId; } return $results; }
public function deleteAction($entityId) { $query = CustomerQuery::create()->joinOrder()->filterById($entityId)->findOne(); if (null !== $query) { throw new HttpException(403, json_encode(["error" => sprintf("You can't delete the customer %d as he has orders", $entityId)])); } return parent::deleteAction($entityId); }
protected function getExistingObject() { return CustomerQuery::create()->findPk($this->getRequest()->get('customer_id', 0)); }
/** * Bug found in Thelia 2.0.2 */ public function testUpdateDefaultAddress() { /** * Disable propel cache in order to get a new instance of the * active record in $updatedAddress */ Propel::disableInstancePooling(); /** * Get a customer and it's default address */ $customer = CustomerQuery::create()->findOne(); $defaultAddress = $customer->getDefaultAddress(); $addressId = $defaultAddress->getId(); /** * Try to update the address, and set the isDefault argument, * that should keep this address as the default one. */ $addressEvent = new AddressCreateOrUpdateEvent("", 1, "Thelia modif", "Thelia modif", "cour des étoiles", "rue des miracles", "", "63000", "clermont-ferrand", 64, "0102030405", "", "", 1); $addressEvent->setAddress($defaultAddress); $addressEvent->setDispatcher($this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface")); /** * Do the update */ $actionAddress = new Address(); $actionAddress->update($addressEvent); $updatedAddress = AddressQuery::create()->findPk($addressId); /** * This address should still be the default address */ $this->assertEquals(1, $updatedAddress->getIsDefault()); /** * Renable it after */ Propel::enableInstancePooling(); }
public function loadCustomer() { $customer = CustomerQuery::create()->findOne(); if (null === $customer) { return null; } $this->securityContext->setCustomerUser($customer); return $customer; }
protected function generateRef() { $lastCustomer = CustomerQuery::create()->orderById(Criteria::DESC)->findOne(); $id = 1; if (null !== $lastCustomer) { $id = $lastCustomer->getId() + 1; } return sprintf('CUS%s', str_pad($id, 12, 0, STR_PAD_LEFT)); }
public function buildModelCriteria() { $search = CustomerQuery::create(); $current = $this->getCurrent(); if ($current === true) { $currentCustomer = $this->securityContext->getCustomerUser(); if ($currentCustomer === null) { return null; } else { $search->filterById($currentCustomer->getId(), Criteria::EQUAL); } } $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $ref = $this->getRef(); if (null !== $ref) { $search->filterByRef($ref, Criteria::IN); } $reseller = $this->getReseller(); if ($reseller === true) { $search->filterByReseller(1, Criteria::EQUAL); } elseif ($reseller === false) { $search->filterByReseller(0, Criteria::EQUAL); } $sponsor = $this->getSponsor(); if ($sponsor !== null) { $search->filterBySponsor($sponsor, Criteria::EQUAL); } $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 'reference': $search->orderByRef(Criteria::ASC); break; case 'reference_reverse': $search->orderByRef(Criteria::DESC); break; case 'lastname': $search->orderByLastname(Criteria::ASC); break; case 'lastname_reverse': $search->orderByLastname(Criteria::DESC); break; case 'firstname': $search->orderByFirstname(Criteria::ASC); break; case 'firstname_reverse': $search->orderByFirstname(Criteria::DESC); break; case 'registration_date': $search->orderByCreatedAt(Criteria::ASC); break; case 'registration_date_reverse': $search->orderByCreatedAt(Criteria::DESC); break; } } return $search; }
public function buildModelCriteria() { $search = CustomerQuery::create(); // Join newsletter $newsletter = $this->getNewsletter(); // if newsletter === "*" or false, it'll be a left join $join = new Join(CustomerTableMap::EMAIL, NewsletterTableMap::EMAIL, true === $newsletter ? Criteria::INNER_JOIN : Criteria::LEFT_JOIN); $search->addJoinObject($join)->withColumn("IF(ISNULL(" . NewsletterTableMap::EMAIL . "), 0, 1)", "is_registered_to_newsletter"); // If "*" === $newsletter, no filter will be applied, so it won't change anything if (false === $newsletter) { $search->having("is_registered_to_newsletter = 0"); } $current = $this->getCurrent(); if ($current === true) { $currentCustomer = $this->securityContext->getCustomerUser(); if ($currentCustomer === null) { return null; } else { $search->filterById($currentCustomer->getId(), Criteria::EQUAL); } } $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } $ref = $this->getRef(); if (null !== $ref) { $search->filterByRef($ref, Criteria::IN); } $reseller = $this->getReseller(); if ($reseller === true) { $search->filterByReseller(1, Criteria::EQUAL); } elseif ($reseller === false) { $search->filterByReseller(0, Criteria::EQUAL); } $sponsor = $this->getSponsor(); if ($sponsor !== null) { $search->filterBySponsor($sponsor, Criteria::EQUAL); } $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 'reference': $search->orderByRef(Criteria::ASC); break; case 'reference_reverse': $search->orderByRef(Criteria::DESC); break; case 'lastname': $search->orderByLastname(Criteria::ASC); break; case 'lastname_reverse': $search->orderByLastname(Criteria::DESC); break; case 'firstname': $search->orderByFirstname(Criteria::ASC); break; case 'firstname_reverse': $search->orderByFirstname(Criteria::DESC); break; case 'registration_date': $search->orderByCreatedAt(Criteria::ASC); break; case 'registration_date_reverse': $search->orderByCreatedAt(Criteria::DESC); break; } } return $search; }