public function parseResults(LoopResult $loopResult)
 {
     $this->container->get('thelia.condition.factory');
     if (null !== ($order = OrderQuery::create()->findPk($this->getOrder()))) {
         $oneDayInSeconds = 86400;
         /** @var \Thelia\Model\OrderCoupon $orderCoupon */
         foreach ($loopResult->getResultDataCollection() as $orderCoupon) {
             $loopResultRow = new LoopResultRow($orderCoupon);
             $now = time();
             $datediff = $orderCoupon->getExpirationDate()->getTimestamp() - $now;
             $daysLeftBeforeExpiration = floor($datediff / $oneDayInSeconds);
             $freeShippingForCountriesIds = [];
             /** @var OrderCouponCountry $couponCountry */
             foreach ($orderCoupon->getFreeShippingForCountries() as $couponCountry) {
                 $freeShippingForCountriesIds[] = $couponCountry->getCountryId();
             }
             $freeShippingForModulesIds = [];
             /** @var OrderCouponModule $couponModule */
             foreach ($orderCoupon->getFreeShippingForModules() as $couponModule) {
                 $freeShippingForModulesIds[] = $couponModule->getModuleId();
             }
             $loopResultRow->set("ID", $orderCoupon->getId())->set("CODE", $orderCoupon->getCode())->set("DISCOUNT_AMOUNT", $orderCoupon->getAmount())->set("TITLE", $orderCoupon->getTitle())->set("SHORT_DESCRIPTION", $orderCoupon->getShortDescription())->set("DESCRIPTION", $orderCoupon->getDescription())->set("EXPIRATION_DATE", $orderCoupon->getExpirationDate($order->getLangId()))->set("IS_CUMULATIVE", $orderCoupon->getIsCumulative())->set("IS_REMOVING_POSTAGE", $orderCoupon->getIsRemovingPostage())->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $orderCoupon->getIsAvailableOnSpecialOffers())->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration)->set("FREE_SHIPPING_FOR_COUNTRIES_LIST", implode(',', $freeShippingForCountriesIds))->set("FREE_SHIPPING_FOR_MODULES_LIST", implode(',', $freeShippingForModulesIds))->set("PER_CUSTOMER_USAGE_COUNT", $orderCoupon->getPerCustomerUsageCount())->set("IS_USAGE_CANCELED", $orderCoupon->getUsageCanceled());
             $this->addOutputFields($loopResultRow, $orderCoupon);
             $loopResult->addRow($loopResultRow);
         }
     }
     return $loopResult;
 }
 public function current()
 {
     do {
         $order = parent::current();
         $getNext = false;
         if ($this->rangeDate !== null && ($order[OrderTableMap::CREATED_AT] < $this->rangeDate['start'] || $order[OrderTableMap::CREATED_AT] > $this->rangeDate['end'])) {
             $this->next();
             $getNext = true;
         }
     } while ($getNext && $this->valid());
     $locale = $this->language->getLocale();
     $query = OrderQuery::create()->useCurrencyQuery()->addAsColumn('currency_CODE', CurrencyTableMap::CODE)->endUse()->useCustomerQuery()->addAsColumn('customer_REF', CustomerTableMap::REF)->endUse()->useOrderProductQuery()->useOrderProductTaxQuery(null, Criteria::LEFT_JOIN)->addAsColumn('product_TAX', 'IF(' . OrderProductTableMap::WAS_IN_PROMO . ',' . 'SUM(' . OrderProductTaxTableMap::PROMO_AMOUNT . '),' . 'SUM(' . OrderProductTaxTableMap::AMOUNT . ')' . ')')->addAsColumn('tax_TITLE', OrderProductTableMap::TAX_RULE_TITLE)->endUse()->addAsColumn('product_TITLE', OrderProductTableMap::TITLE)->addAsColumn('product_PRICE', 'IF(' . OrderProductTableMap::WAS_IN_PROMO . ',' . OrderProductTableMap::PROMO_PRICE . ',' . OrderProductTableMap::PRICE . ')')->addAsColumn('product_QUANTITY', OrderProductTableMap::QUANTITY)->addAsColumn('product_WAS_IN_PROMO', OrderProductTableMap::WAS_IN_PROMO)->groupById()->endUse()->orderById()->groupById()->useOrderCouponQuery(null, Criteria::LEFT_JOIN)->addAsColumn('coupon_COUPONS', 'GROUP_CONCAT(' . OrderCouponTableMap::TITLE . ')')->groupBy(OrderCouponTableMap::ORDER_ID)->endUse()->useModuleRelatedByPaymentModuleIdQuery('payment_module')->addAsColumn('payment_module_TITLE', '`payment_module`.CODE')->endUse()->useModuleRelatedByDeliveryModuleIdQuery('delivery_module')->addAsColumn('delivery_module_TITLE', '`delivery_module`.CODE')->endUse()->useOrderAddressRelatedByDeliveryOrderAddressIdQuery('delivery_address_join')->useCustomerTitleQuery('delivery_address_customer_title_join')->useCustomerTitleI18nQuery('delivery_address_customer_title_i18n_join')->addAsColumn('delivery_address_TITLE', '`delivery_address_customer_title_i18n_join`.SHORT')->endUse()->endUse()->useCountryQuery('delivery_address_country_join')->useCountryI18nQuery('delivery_address_country_i18n_join')->addAsColumn('delivery_address_country_TITLE', '`delivery_address_country_i18n_join`.TITLE')->endUse()->addAsColumn('delivery_address_COMPANY', '`delivery_address_join`.COMPANY')->addAsColumn('delivery_address_FIRSTNAME', '`delivery_address_join`.FIRSTNAME')->addAsColumn('delivery_address_LASTNAME', '`delivery_address_join`.LASTNAME')->addAsColumn('delivery_address_ADDRESS1', '`delivery_address_join`.ADDRESS1')->addAsColumn('delivery_address_ADDRESS2', '`delivery_address_join`.ADDRESS2')->addAsColumn('delivery_address_ADDRESS3', '`delivery_address_join`.ADDRESS3')->addAsColumn('delivery_address_ZIPCODE', '`delivery_address_join`.ZIPCODE')->addAsColumn('delivery_address_CITY', '`delivery_address_join`.CITY')->addAsColumn('delivery_address_PHONE', '`delivery_address_join`.PHONE')->endUse()->endUse()->useOrderAddressRelatedByInvoiceOrderAddressIdQuery('invoice_address_join')->useCustomerTitleQuery('invoice_address_customer_title_join')->useCustomerTitleI18nQuery('invoice_address_customer_title_i18n_join')->addAsColumn('invoice_address_TITLE', '`invoice_address_customer_title_i18n_join`.SHORT')->endUse()->endUse()->useCountryQuery('invoice_address_country_join')->useCountryI18nQuery('invoice_address_country_i18n_join')->addAsColumn('invoice_address_country_TITLE', '`invoice_address_country_i18n_join`.TITLE')->endUse()->endUse()->addAsColumn('invoice_address_COMPANY', '`invoice_address_join`.COMPANY')->addAsColumn('invoice_address_FIRSTNAME', '`invoice_address_join`.FIRSTNAME')->addAsColumn('invoice_address_LASTNAME', '`invoice_address_join`.LASTNAME')->addAsColumn('invoice_address_ADDRESS1', '`invoice_address_join`.ADDRESS1')->addAsColumn('invoice_address_ADDRESS2', '`invoice_address_join`.ADDRESS2')->addAsColumn('invoice_address_ADDRESS3', '`invoice_address_join`.ADDRESS3')->addAsColumn('invoice_address_ZIPCODE', '`invoice_address_join`.ZIPCODE')->addAsColumn('invoice_address_CITY', '`invoice_address_join`.CITY')->addAsColumn('invoice_address_PHONE', '`invoice_address_join`.PHONE')->endUse()->useOrderStatusQuery()->useOrderStatusI18nQuery()->addAsColumn('order_status_TITLE', OrderStatusI18nTableMap::TITLE)->endUse()->endUse()->select([OrderTableMap::REF, 'customer_REF', 'product_TITLE', 'product_PRICE', 'product_TAX', 'tax_TITLE', 'product_QUANTITY', 'product_WAS_IN_PROMO', OrderTableMap::DISCOUNT, 'coupon_COUPONS', OrderTableMap::POSTAGE, 'payment_module_TITLE', OrderTableMap::INVOICE_REF, OrderTableMap::DELIVERY_REF, 'delivery_module_TITLE', 'delivery_address_TITLE', 'delivery_address_COMPANY', 'delivery_address_FIRSTNAME', 'delivery_address_LASTNAME', 'delivery_address_ADDRESS1', 'delivery_address_ADDRESS2', 'delivery_address_ADDRESS3', 'delivery_address_ZIPCODE', 'delivery_address_CITY', 'delivery_address_country_TITLE', 'delivery_address_PHONE', 'invoice_address_TITLE', 'invoice_address_COMPANY', 'invoice_address_FIRSTNAME', 'invoice_address_LASTNAME', 'invoice_address_ADDRESS1', 'invoice_address_ADDRESS2', 'invoice_address_ADDRESS3', 'invoice_address_ZIPCODE', 'invoice_address_CITY', 'invoice_address_country_TITLE', 'invoice_address_PHONE', 'order_status_TITLE', 'currency_CODE', OrderTableMap::CREATED_AT])->orderByCreatedAt(Criteria::DESC);
     I18n::addI18nCondition($query, CustomerTitleI18nTableMap::TABLE_NAME, '`delivery_address_customer_title_join`.ID', CustomerTitleI18nTableMap::ID, '`delivery_address_customer_title_i18n_join`.LOCALE', $locale);
     I18n::addI18nCondition($query, CustomerTitleI18nTableMap::TABLE_NAME, '`invoice_address_customer_title_join`.ID', CustomerTitleI18nTableMap::ID, '`invoice_address_customer_title_i18n_join`.LOCALE', $locale);
     I18n::addI18nCondition($query, CountryI18nTableMap::TABLE_NAME, '`delivery_address_country_join`.ID', CountryI18nTableMap::ID, '`delivery_address_country_i18n_join`.LOCALE', $locale);
     I18n::addI18nCondition($query, CountryI18nTableMap::TABLE_NAME, '`invoice_address_country_join`.ID', CountryI18nTableMap::ID, '`invoice_address_country_i18n_join`.LOCALE', $locale);
     I18n::addI18nCondition($query, OrderStatusI18nTableMap::TABLE_NAME, OrderStatusI18nTableMap::ID, OrderStatusTableMap::ID, OrderStatusI18nTableMap::LOCALE, $locale);
     $data = $query->filterById($order[OrderTableMap::ID])->findOne();
     $order = (new Order())->setId($order[OrderTableMap::ID]);
     $order->setNew(false);
     $tax = 0;
     $data['order_TOTAL_TTC'] = $order->getTotalAmount($tax, false, false);
     $data['order_TOTAL_WITH_DISCOUNT'] = $order->getTotalAmount($tax, false, true);
     $data['order_TOTAL_WITH_DISCOUNT_AND_POSTAGE'] = $order->getTotalAmount($tax, true, true);
     return $data;
 }
Exemple #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);
 }
 public function buildArray()
 {
     $order = OrderQuery::create()->findOneByRef($this->getRef());
     if (null !== $order && $order->getDeliveryModuleId() === DpdClassic::getModuleId()) {
         return [$order->getRef() => $order->getDeliveryRef()];
     }
     return [];
 }
Exemple #5
0
 protected function buildForm()
 {
     $entries = OrderQuery::create()->filterByDeliveryModuleId(DpdClassic::getModuleId())->find();
     $this->formBuilder->add('new_status_id', 'choice', array('label' => Translator::getInstance()->trans('Change order status to', [], DpdClassic::DOMAIN_NAME), 'choices' => array("nochange" => Translator::getInstance()->trans("Do not change", [], DpdClassic::DOMAIN_NAME), "processing" => Translator::getInstance()->trans("Set orders status as processing", [], DpdClassic::DOMAIN_NAME), "sent" => Translator::getInstance()->trans("Set orders status as sent", [], DpdClassic::DOMAIN_NAME)), 'required' => true, 'expanded' => true, 'multiple' => false, 'data' => 'nochange'));
     foreach ($entries as $order) {
         $orderRef = str_replace(".", "-", $order->getRef());
         $this->formBuilder->add($orderRef, 'checkbox', array('label' => $orderRef, 'label_attr' => array('for' => $orderRef)))->add($orderRef . "-assur", 'checkbox')->add($orderRef . "-pkgNumber", 'number')->add($orderRef . "-pkgWeight", 'number');
     }
 }
 protected function buildForm()
 {
     $status = OrderStatusQuery::create()->filterByCode(array(OrderStatus::CODE_PAID, OrderStatus::CODE_PROCESSING, OrderStatus::CODE_SENT), Criteria::IN)->find()->toArray("code");
     $query = OrderQuery::create()->filterByDeliveryModuleId(FreeShipping::getModuleId())->filterByStatusId(array($status['paid']['Id'], $status['processing']['Id']), Criteria::IN)->find();
     $this->formBuilder->add('new_status_id', 'choice', array('label' => Translator::getInstance()->trans('server'), 'choices' => array("nochange" => Translator::getInstance()->trans("Do not change"), "processing" => Translator::getInstance()->trans("Set orders status as processing"), "sent" => Translator::getInstance()->trans("Set orders status as sent")), 'required' => 'true', 'expanded' => true, 'multiple' => false, 'data' => 'nochange'));
     /** @var \Thelia\Model\Order $order */
     foreach ($query as $order) {
         $this->formBuilder->add("order_" . $order->getId(), "checkbox", array('label' => $order->getRef(), 'label_attr' => array('for' => 'export_' . $order->getId())));
     }
 }
 public function buildArray()
 {
     $path = ExportExaprint::getJSONpath();
     if (is_readable($path) && ($order = OrderQuery::create()->findOneByRef($this->getRef())) !== null && $order->getDeliveryModuleId() === DpdPickup::getModuleId()) {
         $json = json_decode(file_get_contents($path), true);
         return array($this->getRef() => $json['expcode']);
     } else {
         return array();
     }
 }
Exemple #8
0
 public function preImport()
 {
     // Delete table before proceeding
     OrderQuery::create()->deleteAll();
     // Delete custom order status
     OrderStatusQuery::create()->filterById(5, Criteria::GREATER_THAN)->delete();
     // Create T1 <-> T2 IDs correspondance tables
     $this->order_corresp->reset();
     $this->importCustomOrderStatus();
 }
Exemple #9
0
 /**
  * @throws \Exception
  */
 public function receiveResponse()
 {
     $request = $this->getRequest();
     $order_id = $request->get('reference');
     if (is_numeric($order_id)) {
         $order_id = (int) $order_id;
     }
     /*
      * Configure log output
      */
     $log = Tlog::getInstance();
     $log->setDestinations("\\Thelia\\Log\\Destination\\TlogDestinationFile");
     $log->setConfig("\\Thelia\\Log\\Destination\\TlogDestinationFile", 0, THELIA_ROOT . "log" . DS . "log-cmcic.txt");
     $log->info("accessed");
     $order = OrderQuery::create()->findPk($order_id);
     /*
      * Retrieve HMac for CGI2
      */
     $config = Config::read(CmCIC::JSON_CONFIG_PATH);
     $hashable = sprintf(CmCIC::CMCIC_CGI2_FIELDS, $config['CMCIC_TPE'], $request->get('date'), $request->get('montant'), $request->get('reference'), $request->get('texte-libre'), $config['CMCIC_VERSION'], $request->get('code-retour'), $request->get('cvx'), $request->get('vld'), $request->get('brand'), $request->get('status3ds'), $request->get('numauto'), $request->get('motifrefus'), $request->get('originecb'), $request->get('bincb'), $request->get('hpancb'), $request->get('ipclient'), $request->get('originetr'), $request->get('veres'), $request->get('pares'));
     $mac = CmCIC::computeHmac($hashable, CmCIC::getUsableKey($config["CMCIC_KEY"]));
     $response = CmCIC::CMCIC_CGI2_MACNOTOK . $hashable;
     if ($mac === strtolower($request->get('MAC'))) {
         $code = $request->get("code-retour");
         $msg = null;
         $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_PAID);
         $event = new OrderEvent($order);
         $event->setStatus($status->getId());
         switch ($code) {
             case "payetest":
                 $msg = "The test payment of the order " . $order->getRef() . " has been successfully released. ";
                 $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
                 break;
             case "paiement":
                 $msg = "The payment of the order " . $order->getRef() . " has been successfully released. ";
                 $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
                 break;
             case "Annulation":
                 $msg = "Error during the paiement: " . $this->getRequest()->get("motifrefus");
                 break;
             default:
                 $log->error("Error while receiving response from CMCIC: code-retour not valid");
                 throw new \Exception(Translator::getInstance()->trans("An error occured, no valid code-retour"));
         }
         if (!empty($msg)) {
             $log->info($msg);
         }
         $response = CmCIC::CMCIC_CGI2_MACOK;
     }
     /*
      * Get log back to previous state
      */
     $log->setDestinations("\\Thelia\\Log\\Destination\\TlogDestinationRotatingFile");
     return Response::create(sprintf(CmCIC::CMCIC_CGI2_RECEIPT, $response), 200, array("Content-type" => "text/plain", "Pragma" => "nocache"));
 }
Exemple #10
0
 public function onInvoiceAfterDeliveryModule(HookRenderEvent $event)
 {
     // No So Colissimo information if the delivery module is not SoColissimo
     if (SoColissimo::getModuleId() == $event->getArgument('module_id')) {
         return;
     }
     $order = OrderQuery::create()->findOneById($event->getArgument('order'));
     if (!is_null($order)) {
         $event->add($this->render('delivery_mode_infos.html', ['delivery_address_id' => $order->getDeliveryOrderAddressId()]));
     }
 }
Exemple #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);
 }
Exemple #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();
     }
 }
Exemple #13
0
 public function orderNumberPackage($params, $template = null)
 {
     $numberOfPackage = 1;
     $maxWeightPackage = TNTFrance::getConfigValue(TNTFranceConfigValue::MAX_WEIGHT_PACKAGE, 25);
     if (null != ($orderId = $this->getParam($params, "order_id", null))) {
         if (null != ($order = OrderQuery::create()->findPk($orderId))) {
             $orderTotalWeight = 0;
             foreach ($order->getOrderProducts() as $orderProduct) {
                 //Be sure that this orderProduct has no package already
                 if (null == ($tntResponse = TntOrderParcelResponseQuery::create()->findOneByOrderProductId($orderProduct->getId()))) {
                     $orderTotalWeight += $orderProduct->getQuantity() * $orderProduct->getWeight();
                 }
             }
             $numberOfPackage = ceil($orderTotalWeight / $maxWeightPackage);
         }
     }
     return $numberOfPackage;
 }
 /**
  * Update order's delivery ref
  *
  * @param string    $deliveryRef
  * @param string    $orderRef
  * @param int       $i
  */
 public function importDeliveryRef($deliveryRef, $orderRef, &$i)
 {
     // Check if the order exists
     if (null !== ($order = OrderQuery::create()->findOneByRef($orderRef))) {
         $event = new OrderEvent($order);
         // Check if delivery refs are different
         if ($order->getDeliveryRef() != $deliveryRef) {
             $event->setDeliveryRef($deliveryRef);
             $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_DELIVERY_REF, $event);
             $sentStatusId = OrderStatusQuery::create()->filterByCode('sent')->select('ID')->findOne();
             // Set 'sent' order status if not already sent
             if ($sentStatusId != null && $order->getStatusId() != $sentStatusId) {
                 $event->setStatus($sentStatusId);
                 $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
             }
             $i++;
         }
     }
 }
 /**
  * Update order's delivery ref
  *
  * @param string    $deliveryRef
  * @param string    $orderRef
  * @param int       $i
  */
 public function importDeliveryRef($deliveryRef, $orderRef, &$i)
 {
     // Get order
     $order = OrderQuery::create()->findOneByRef($orderRef);
     // Check if the order exists
     if ($order !== null) {
         $event = new OrderEvent($order);
         // Check if delivery refs are different
         if ($order->getDeliveryRef() != $deliveryRef) {
             $event->setDeliveryRef($deliveryRef);
             $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_DELIVERY_REF, $event);
             // Set 'sent' order status if not already sent
             if ($order->getStatusId() != DpdPickup::STATUS_SENT) {
                 $event->setStatus(DpdPickup::STATUS_SENT);
                 $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
             }
             $i++;
         }
     }
 }
Exemple #16
0
 public function processAtosRequest()
 {
     $this->getLog()->addInfo($this->getTranslator()->trans("Atos-SIPS platform request received.", [], Atos::MODULE_DOMAIN));
     $binResponse = Atos::getBinDirectory() . 'response';
     if (!empty($_POST['DATA'])) {
         $data = escapeshellcmd($_POST['DATA']);
         $pathfile = Atos::getPathfilePath();
         $resultRaw = exec(sprintf("%s message=%s pathfile=%s", $binResponse, $data, $pathfile));
         if (!empty($resultRaw)) {
             $result = explode('!', $resultRaw);
             $result = $this->parseResult($result);
             $this->getLog()->addInfo($this->getTranslator()->trans('Response parameters : %resp', ['%resp' => print_r($result, true)], Atos::MODULE_DOMAIN));
             if ($result['code'] == '' && $result['error'] == '') {
                 $this->getLog()->addError($this->getTranslator()->trans('Response request not found in %response', ['%response' => $binResponse], Atos::MODULE_DOMAIN));
             } elseif (intval($result['code']) != 0) {
                 $this->getLog()->addError($this->getTranslator()->trans('Error %code while processing response, with message %message', ['%code' => intval($result['code']), '%message' => $result['error']], Atos::MODULE_DOMAIN));
             } elseif ($result['response_code'] == '00') {
                 $atos = new Atos();
                 $order = OrderQuery::create()->filterByTransactionRef($result['transaction_id'])->filterByPaymentModuleId($atos->getModuleModel()->getId())->findOne();
                 if ($order) {
                     $this->confirmPayment($order->getId());
                     $this->getLog()->addInfo($this->getTranslator()->trans("Order ID %id is confirmed.", ['%id' => $order->getId()], Atos::MODULE_DOMAIN));
                 } else {
                     $this->getLog()->addError($this->getTranslator()->trans('Cannot find an order for transaction ID "%trans"', ['%trans' => $result['transaction_id']], Atos::MODULE_DOMAIN));
                 }
             } else {
                 $this->getLog()->addError($this->getTranslator()->trans('Cannot validate order. Response code is %resp', ['%resp' => $result['response_code']], Atos::MODULE_DOMAIN));
             }
         } else {
             $this->getLog()->addError($this->getTranslator()->trans('Got empty response from executable %binary, check path and permissions', ['%binary' => $binResponse], Atos::MODULE_DOMAIN));
         }
     } else {
         $this->getLog()->addError($this->getTranslator()->trans('Request does not contains any data', [], Atos::MODULE_DOMAIN));
     }
     $this->getLog()->info($this->getTranslator()->trans("Atos platform request processing terminated.", [], Atos::MODULE_DOMAIN));
     return Response::create();
 }
Exemple #17
0
 /**
  * @param int $order_id
  * @param string $fileName
  * @param bool $checkOrderStatus
  * @param bool $checkAdminUser
  * @return \Symfony\Component\HttpFoundation\Response
  */
 protected function generateOrderPdf($order_id, $fileName, $checkOrderStatus = true, $checkAdminUser = true, $browser = false)
 {
     $order = OrderQuery::create()->findPk($order_id);
     // check if the order has the paid status
     if ($checkAdminUser && !$this->getSecurityContext()->hasAdminUser()) {
         if ($checkOrderStatus && !$order->isPaid(false)) {
             throw new NotFoundHttpException();
         }
     }
     $html = $this->renderRaw($fileName, array('order_id' => $order_id), $this->getTemplateHelper()->getActivePdfTemplate());
     try {
         $pdfEvent = new PdfEvent($html);
         $this->dispatch(TheliaEvents::GENERATE_PDF, $pdfEvent);
         if ($pdfEvent->hasPdf()) {
             return $this->pdfResponse($pdfEvent->getPdf(), $order->getRef(), 200, $browser);
         }
     } catch (\Exception $e) {
         Tlog::getInstance()->error(sprintf('error during generating invoice pdf for order id : %d with message "%s"', $order_id, $e->getMessage()));
     }
     throw new TheliaProcessException($this->getTranslator()->trans("We're sorry, this PDF invoice is not available at the moment."));
 }
Exemple #18
0
 /**
  * Get the associated ChildOrder object
  *
  * @param      ConnectionInterface $con Optional Connection object.
  * @return                 ChildOrder The associated ChildOrder object.
  * @throws PropelException
  */
 public function getOrder(ConnectionInterface $con = null)
 {
     if ($this->aOrder === null && $this->order_id !== null) {
         $this->aOrder = ChildOrderQuery::create()->findPk($this->order_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->aOrder->addOrderProducts($this);
            */
     }
     return $this->aOrder;
 }
Exemple #19
0
 /**
  * @depends testCreate
  *
  * @param OrderModel $order
  */
 public function testUpdateDeliveryRef(OrderModel $order)
 {
     $deliveryRef = uniqid('DELREF');
     $this->orderEvent->setDeliveryRef($deliveryRef);
     $this->orderEvent->setOrder($order);
     $this->orderAction->updateDeliveryRef($this->orderEvent);
     $this->assertEquals($deliveryRef, $this->orderEvent->getOrder()->getDeliveryRef());
     $this->assertEquals($deliveryRef, OrderQuery::create()->findPk($order->getId())->getDeliveryRef());
 }
Exemple #20
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 (ChildOrderQuery::isVersioningEnabled() && ($this->isNew() || $this->isModified()) || $this->isDeleted()) {
         return true;
     }
     if (null !== ($object = $this->getCustomer($con)) && $object->isVersioningNecessary($con)) {
         return true;
     }
     return false;
 }
Exemple #21
0
 private function checkOrderCustomer($order_id)
 {
     $this->checkAuth();
     $order = OrderQuery::create()->findPk($order_id);
     $valid = true;
     if ($order) {
         $customerOrder = $order->getCustomer();
         $customer = $this->getSecurityContext()->getCustomerUser();
         if ($customerOrder->getId() != $customer->getId()) {
             $valid = false;
         }
     } else {
         $valid = false;
     }
     if (false === $valid) {
         throw new AccessDeniedHttpException();
     }
 }
 /**
  * Provides access to sales statistics
  *
  * @param  array $params
  * @param  \Smarty $smarty
  * @return string the value of the requested attribute
  */
 public function statsAccess($params, $smarty)
 {
     if (false === array_key_exists("key", $params)) {
         throw new \InvalidArgumentException(sprintf("missing key attribute in stats access function"));
     }
     if (false === array_key_exists("startDate", $params) || $params['startDate'] === '') {
         throw new \InvalidArgumentException(sprintf("missing startDate attribute in stats access function"));
     }
     if (false === array_key_exists("endDate", $params) || $params['endDate'] === '') {
         throw new \InvalidArgumentException(sprintf("missing endDate attribute in stats access function"));
     }
     if (false !== array_key_exists("includeShipping", $params) && $params['includeShipping'] == 'false') {
         $includeShipping = false;
     } else {
         $includeShipping = true;
     }
     if ($params['startDate'] == 'today') {
         $startDate = new \DateTime();
         $startDate->setTime(0, 0, 0);
     } elseif ($params['startDate'] == 'yesterday') {
         $startDate = new \DateTime();
         $startDate->setTime(0, 0, 0);
         $startDate->modify('-1 day');
     } elseif ($params['startDate'] == 'this_month') {
         $startDate = new \DateTime();
         $startDate->modify('first day of this month');
         $startDate->setTime(0, 0, 0);
     } elseif ($params['startDate'] == 'last_month') {
         $startDate = new \DateTime();
         $startDate->modify('first day of last month');
         $startDate->setTime(0, 0, 0);
     } elseif ($params['startDate'] == 'this_year') {
         $startDate = new \DateTime();
         $startDate->modify('first day of January this year');
         $startDate->setTime(0, 0, 0);
     } elseif ($params['startDate'] == 'last_year') {
         $startDate = new \DateTime();
         $startDate->modify('first day of January last year');
         $startDate->setTime(0, 0, 0);
     } else {
         try {
             $startDate = new \DateTime($params['startDate']);
         } catch (\Exception $e) {
             throw new \InvalidArgumentException(sprintf("invalid startDate attribute '%s' in stats access function", $params['startDate']));
         }
     }
     if ($params['endDate'] == 'today') {
         $endDate = new \DateTime();
         $endDate->setTime(0, 0, 0);
     } elseif ($params['endDate'] == 'yesterday') {
         $endDate = new \DateTime();
         $endDate->setTime(0, 0, 0);
         $endDate->modify('-1 day');
     } elseif ($params['endDate'] == 'this_month') {
         $endDate = new \DateTime();
         $endDate->modify('last day of this month');
         $endDate->setTime(0, 0, 0);
     } elseif ($params['endDate'] == 'last_month') {
         $endDate = new \DateTime();
         $endDate->modify('last day of last month');
         $endDate->setTime(0, 0, 0);
     } elseif ($params['endDate'] == 'this_year') {
         $endDate = new \DateTime();
         $endDate->modify('last day of December this year');
         $endDate->setTime(0, 0, 0);
     } elseif ($params['endDate'] == 'last_year') {
         $endDate = new \DateTime();
         $endDate->modify('last day of December last year');
         $endDate->setTime(0, 0, 0);
     } else {
         try {
             $endDate = new \DateTime($params['endDate']);
         } catch (\Exception $e) {
             throw new \InvalidArgumentException(sprintf("invalid endDate attribute '%s' in stats access function", $params['endDate']));
         }
     }
     switch ($params['key']) {
         case 'sales':
             return OrderQuery::getSaleStats($startDate, $endDate, $includeShipping);
             break;
         case 'orders':
             return OrderQuery::getOrderStats($startDate, $endDate, array(1, 2, 3, 4));
             break;
     }
     throw new \InvalidArgumentException(sprintf("invalid key attribute '%s' in stats access function", $params['key']));
 }
Exemple #23
0
 /**
  * If this collection has already been initialized with
  * an identical criteria, it returns the collection.
  * Otherwise if this Customer is new, it will return
  * an empty collection; or if this Customer has previously
  * been saved, it will retrieve related Orders 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 Customer.
  *
  * @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|ChildOrder[] List of ChildOrder objects
  */
 public function getOrdersJoinLang($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN)
 {
     $query = ChildOrderQuery::create(null, $criteria);
     $query->joinWith('Lang', $joinBehavior);
     return $this->getOrders($query, $con);
 }
Exemple #24
0
 public function updateAddress($order_id)
 {
     if (null !== ($response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE))) {
         return $response;
     }
     $message = null;
     $orderUpdateAddress = new OrderUpdateAddress($this->getRequest());
     try {
         $order = OrderQuery::create()->findPk($order_id);
         if (null === $order) {
             throw new \InvalidArgumentException("The order you want to update does not exist");
         }
         $form = $this->validateForm($orderUpdateAddress, "post");
         $orderAddress = OrderAddressQuery::create()->findPk($form->get("id")->getData());
         if ($orderAddress->getId() !== $order->getInvoiceOrderAddressId() && $orderAddress->getId() !== $order->getDeliveryOrderAddressId()) {
             throw new \InvalidArgumentException("The order address you want to update does not belong to the current order not exist");
         }
         $event = new OrderAddressEvent($form->get("title")->getData(), $form->get("firstname")->getData(), $form->get("lastname")->getData(), $form->get("address1")->getData(), $form->get("address2")->getData(), $form->get("address3")->getData(), $form->get("zipcode")->getData(), $form->get("city")->getData(), $form->get("country")->getData(), $form->get("phone")->getData(), $form->get("company")->getData());
         $event->setOrderAddress($orderAddress);
         $event->setOrder($order);
         $this->dispatch(TheliaEvents::ORDER_UPDATE_ADDRESS, $event);
     } catch (\Exception $e) {
         $message = $e->getMessage();
     }
     $params = array();
     if ($message) {
         $params["update_status_error_message"] = $message;
     }
     $params["tab"] = $this->getRequest()->get("tab", 'bill');
     return $this->generateRedirectFromRoute("admin.order.update.view", $params, ['order_id' => $order_id]);
 }
Exemple #25
0
 /**
  * Performs an INSERT on the database, given a Order or Criteria object.
  *
  * @param mixed               $criteria Criteria or Order 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(OrderTableMap::DATABASE_NAME);
     }
     if ($criteria instanceof Criteria) {
         $criteria = clone $criteria;
         // rename for clarity
     } else {
         $criteria = $criteria->buildCriteria();
         // build Criteria from Order object
     }
     if ($criteria->containsKey(OrderTableMap::ID) && $criteria->keyContainsValue(OrderTableMap::ID)) {
         throw new PropelException('Cannot insert a value for auto-increment primary key (' . OrderTableMap::ID . ')');
     }
     // Set the correct dbName
     $query = OrderQuery::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;
 }
Exemple #26
0
 /**
  * If this collection has already been initialized with
  * an identical criteria, it returns the collection.
  * Otherwise if this Lang is new, it will return
  * an empty collection; or if this Lang has previously
  * been saved, it will retrieve related Orders 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 Lang.
  *
  * @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|ChildOrder[] List of ChildOrder objects
  */
 public function getOrdersJoinModuleRelatedByDeliveryModuleId($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN)
 {
     $query = ChildOrderQuery::create(null, $criteria);
     $query->joinWith('ModuleRelatedByDeliveryModuleId', $joinBehavior);
     return $this->getOrders($query, $con);
 }
 public function buildModelCriteria()
 {
     $status = OrderStatusQuery::create()->filterByCode(array(OrderStatus::CODE_PAID, OrderStatus::CODE_PROCESSING), Criteria::IN)->find()->toArray("code");
     $query = OrderQuery::create()->filterByDeliveryModuleId(FreeShipping::getModuleId())->filterByStatusId(array($status[OrderStatus::CODE_PAID]['Id'], $status[OrderStatus::CODE_PROCESSING]['Id']), Criteria::IN);
     return $query;
 }
Exemple #28
0
 /**
  * @param  Lang                         $lang
  * @return ModelCriteria|array|BaseLoop
  */
 public function buildDataSet(Lang $lang)
 {
     $query = $this->getQuery($lang);
     $dataSet = $query->find()->toArray();
     $orders = OrderQuery::create()->orderById()->find();
     $current = 0;
     $previous = null;
     foreach ($dataSet as &$line) {
         /**
          * Add computed columns
          */
         $line["order_TOTAL_TTC"] = "";
         $line["order_TOTAL_WITH_DISCOUNT"] = "";
         $line["order_TOTAL_WITH_DISCOUNT_AND_POSTAGE"] = "";
         if (null === $previous || $previous !== $line[OrderTableMap::REF]) {
             $previous = $line[OrderTableMap::REF];
             /** @var \Thelia\Model\Order $order */
             $order = $orders->get($current);
             $line["order_TOTAL_TTC"] = $order->getTotalAmount($tax, false, false);
             $line["order_TOTAL_WITH_DISCOUNT"] = $order->getTotalAmount($tax, false, true);
             $line["order_TOTAL_WITH_DISCOUNT_AND_POSTAGE"] = $order->getTotalAmount($tax, true, true);
             /**
              * Format the date
              */
             $date = new \DateTime($line[OrderTableMap::CREATED_AT]);
             $line[OrderTableMap::CREATED_AT] = $date->format($lang->getDatetimeFormat());
             $current++;
         } else {
             /**
              * Remove all the information of the order
              * for each line that only contains a product.
              */
             $line["customer_REF"] = "";
             $line[OrderTableMap::DISCOUNT] = "";
             $line["coupon_COUPONS"] = "";
             $line[OrderTableMap::POSTAGE] = "";
             $line["payment_module_TITLE"] = "";
             $line[OrderTableMap::INVOICE_REF] = "";
             $line["delivery_module_TITLE"] = "";
             $line["delivery_address_TITLE"] = "";
             $line["delivery_address_COMPANY"] = "";
             $line["delivery_address_FIRSTNAME"] = "";
             $line["delivery_address_LASTNAME"] = "";
             $line["delivery_address_ADDRESS1"] = "";
             $line["delivery_address_ADDRESS2"] = "";
             $line["delivery_address_ADDRESS3"] = "";
             $line["delivery_address_ZIPCODE"] = "";
             $line["delivery_address_CITY"] = "";
             $line["delivery_address_country_TITLE"] = "";
             $line["delivery_address_PHONE"] = "";
             $line["invoice_address_TITLE"] = "";
             $line["invoice_address_COMPANY"] = "";
             $line["invoice_address_FIRSTNAME"] = "";
             $line["invoice_address_LASTNAME"] = "";
             $line["invoice_address_ADDRESS1"] = "";
             $line["invoice_address_ADDRESS2"] = "";
             $line["invoice_address_ADDRESS3"] = "";
             $line["invoice_address_ZIPCODE"] = "";
             $line["invoice_address_CITY"] = "";
             $line["invoice_address_country_TITLE"] = "";
             $line["invoice_address_PHONE"] = "";
             $line["order_status_TITLE"] = "";
             $line[OrderTableMap::CREATED_AT] = "";
         }
         $line["product_TAXED_PRICE"] = $line["product_PRICE"] + $line["product_TAX"];
     }
     return $dataSet;
 }
Exemple #29
0
 protected function generateOrderPdf($order_id, $fileName)
 {
     $order = OrderQuery::create()->findPk($order_id);
     // check if the order has the paid status
     if (!$this->getSecurityContext()->hasAdminUser()) {
         if (!$order->isPaid()) {
             throw new NotFoundHttpException();
         }
     }
     $html = $this->renderRaw($fileName, array('order_id' => $order_id), TemplateHelper::getInstance()->getActivePdfTemplate());
     try {
         $pdfEvent = new PdfEvent($html);
         $this->dispatch(TheliaEvents::GENERATE_PDF, $pdfEvent);
         if ($pdfEvent->hasPdf()) {
             return $this->pdfResponse($pdfEvent->getPdf(), $order->getRef());
         }
     } catch (\Exception $e) {
         \Thelia\Log\Tlog::getInstance()->error(sprintf('error during generating invoice pdf for order id : %d with message "%s"', $order_id, $e->getMessage()));
     }
 }
Exemple #30
0
 public function hasOrder()
 {
     $order = OrderQuery::create()->filterByCustomerId($this->getId())->count();
     return $order > 0;
 }