Пример #1
0
 public function verifyExistingEmail($value, ExecutionContextInterface $context)
 {
     $customer = CustomerQuery::getCustomerByEmail($value);
     if ($customer) {
         $context->addViolation(Translator::getInstance()->trans("This email already exists."));
     }
 }
Пример #2
0
 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"]);
     }
 }
Пример #3
0
 public function loadStatsAjaxAction()
 {
     if (null !== ($response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW))) {
         return $response;
     }
     $data = new \stdClass();
     $data->title = $this->getTranslator()->trans("Stats on %month/%year", array('%month' => $this->getRequest()->query->get('month', date('m')), '%year' => $this->getRequest()->query->get('year', date('Y'))));
     /* sales */
     $saleSeries = new \stdClass();
     $saleSeries->color = $this->getRequest()->query->get('sales_color', '#adadad');
     $saleSeries->data = OrderQuery::getMonthlySaleStats($this->getRequest()->query->get('month', date('m')), $this->getRequest()->query->get('year', date('Y')));
     /* new customers */
     $newCustomerSeries = new \stdClass();
     $newCustomerSeries->color = $this->getRequest()->query->get('customers_color', '#f39922');
     $newCustomerSeries->data = CustomerQuery::getMonthlyNewCustomersStats($this->getRequest()->query->get('month', date('m')), $this->getRequest()->query->get('year', date('Y')));
     /* orders */
     $orderSeries = new \stdClass();
     $orderSeries->color = $this->getRequest()->query->get('orders_color', '#5cb85c');
     $orderSeries->data = OrderQuery::getMonthlyOrdersStats($this->getRequest()->query->get('month', date('m')), $this->getRequest()->query->get('year', date('Y')));
     /* first order */
     $firstOrderSeries = new \stdClass();
     $firstOrderSeries->color = $this->getRequest()->query->get('first_orders_color', '#5bc0de');
     $firstOrderSeries->data = OrderQuery::getFirstOrdersStats($this->getRequest()->query->get('month', date('m')), $this->getRequest()->query->get('year', date('Y')));
     /* cancelled orders */
     $cancelledOrderSeries = new \stdClass();
     $cancelledOrderSeries->color = $this->getRequest()->query->get('cancelled_orders_color', '#d9534f');
     $cancelledOrderSeries->data = OrderQuery::getMonthlyOrdersStats($this->getRequest()->query->get('month', date('m')), $this->getRequest()->query->get('year', date('Y')), array(5));
     $data->series = array($saleSeries, $newCustomerSeries, $orderSeries, $firstOrderSeries, $cancelledOrderSeries);
     $json = json_encode($data);
     return $this->jsonResponse($json);
 }
Пример #4
0
 /**
  * @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;
         }
     }
 }
Пример #5
0
 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;
 }
Пример #6
0
 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 $value
  * @param ExecutionContextInterface $context
  */
 public function verifyExistingEmail($value, ExecutionContextInterface $context)
 {
     $customer = CustomerQuery::getCustomerByEmail($value);
     // If there is already a customer for this email address and if the customer is different from the current user, do a violation
     if ($customer && $customer->getId() != $this->getRequest()->getSession()->getCustomerUser()->getId()) {
         $context->addViolation(Translator::getInstance()->trans("This email already exists."));
     }
 }
 /**
  * @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;
 }
Пример #9
0
 /**
  * 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."));
     }
 }
Пример #11
0
 public function loadStatsAjaxAction()
 {
     if (null !== ($response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW))) {
         return $response;
     }
     $cacheExpire = ConfigQuery::getAdminCacheHomeStatsTTL();
     $cacheContent = false;
     $month = (int) $this->getRequest()->query->get('month', date('m'));
     $year = (int) $this->getRequest()->query->get('year', date('Y'));
     if ($cacheExpire) {
         $context = "_" . $month . "_" . $year;
         $cacheKey = self::STATS_CACHE_KEY . $context;
         $cacheDriver = new FilesystemCache($this->getCacheDir());
         if (!$this->getRequest()->query->get('flush', "0")) {
             $cacheContent = $cacheDriver->fetch($cacheKey);
         } else {
             $cacheDriver->delete($cacheKey);
         }
     }
     if ($cacheContent === false) {
         $data = new \stdClass();
         $data->title = $this->getTranslator()->trans("Stats on %month/%year", ['%month' => $month, '%year' => $year]);
         /* sales */
         $saleSeries = new \stdClass();
         $saleSeries->color = self::testHexColor('sales_color', '#adadad');
         $saleSeries->data = OrderQuery::getMonthlySaleStats($month, $year);
         /* new customers */
         $newCustomerSeries = new \stdClass();
         $newCustomerSeries->color = self::testHexColor('customers_color', '#f39922');
         $newCustomerSeries->data = CustomerQuery::getMonthlyNewCustomersStats($month, $year);
         /* orders */
         $orderSeries = new \stdClass();
         $orderSeries->color = self::testHexColor('orders_color', '#5cb85c');
         $orderSeries->data = OrderQuery::getMonthlyOrdersStats($month, $year);
         /* first order */
         $firstOrderSeries = new \stdClass();
         $firstOrderSeries->color = self::testHexColor('first_orders_color', '#5bc0de');
         $firstOrderSeries->data = OrderQuery::getFirstOrdersStats($month, $year);
         /* cancelled orders */
         $cancelledOrderSeries = new \stdClass();
         $cancelledOrderSeries->color = self::testHexColor('cancelled_orders_color', '#d9534f');
         $cancelledOrderSeries->data = OrderQuery::getMonthlyOrdersStats($month, $year, array(5));
         $data->series = array($saleSeries, $newCustomerSeries, $orderSeries, $firstOrderSeries, $cancelledOrderSeries);
         $cacheContent = json_encode($data);
         if ($cacheExpire) {
             $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire);
         }
     }
     return $this->jsonResponse($cacheContent);
 }
Пример #12
0
 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());
 }
Пример #14
0
 protected function getExistingObject()
 {
     return CustomerQuery::create()->findPk($this->getRequest()->get('customer_id', 0));
 }
Пример #15
0
 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);
 }
Пример #16
0
 /**
  * Checks whether the current state must be recorded as a version
  *
  * @return  boolean
  */
 public function isVersioningNecessary($con = null)
 {
     if ($this->alreadyInSave) {
         return false;
     }
     if ($this->enforceVersion) {
         return true;
     }
     if (ChildCustomerQuery::isVersioningEnabled() && ($this->isNew() || $this->isModified()) || $this->isDeleted()) {
         return true;
     }
     // to avoid infinite loops, emulate in save
     $this->alreadyInSave = true;
     foreach ($this->getOrders(null, $con) as $relatedObject) {
         if ($relatedObject->isVersioningNecessary($con)) {
             $this->alreadyInSave = false;
             return true;
         }
     }
     $this->alreadyInSave = false;
     return false;
 }
Пример #17
0
 /**
  * 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;
 }
Пример #18
0
 /**
  * @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());
 }
Пример #19
0
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";
}
Пример #20
0
 public static function setUpBeforeClass()
 {
     CustomerQuery::create()->filterByRef('testRef')->delete();
 }
Пример #21
0
 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));
 }
Пример #22
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();
 }
Пример #23
0
 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;
 }
Пример #24
0
 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]);
     }
 }
Пример #25
0
 /**
  * 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;
 }
Пример #26
0
 /**
  * @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;
 }
Пример #27
0
 public function loadCustomer()
 {
     $customer = CustomerQuery::create()->findOne();
     if (null === $customer) {
         return null;
     }
     $this->securityContext->setCustomerUser($customer);
     return $customer;
 }
Пример #28
0
 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;
 }
Пример #29
0
 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();
Пример #30
0
 /**
  * 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;
 }