public function buildModelCriteria() { $search = OrderStatusQuery::create(); /* manage translations */ $this->configureI18nProcessing($search); if (null !== ($id = $this->getId())) { $search->filterById($id, Criteria::IN); } if (null !== ($code = $this->getCode())) { $search->filterByCode($code, Criteria::EQUAL); } $orders = $this->getOrder(); foreach ($orders as $order) { switch ($order) { case "alpha": $search->addAscendingOrderByColumn('i18n_TITLE'); break; case "alpha_reverse": $search->addDescendingOrderByColumn('i18n_TITLE'); break; case "manual": $search->orderByPosition(Criteria::ASC); break; case "manual_reverse": $search->orderByPosition(Criteria::DESC); break; } } return $search; }
public function updateStatus(OrderEvent $event) { $order = $event->getOrder(); $paidStatusId = OrderStatusQuery::create()->filterByCode(OrderStatus::CODE_PAID)->select('Id')->findOne(); if ($order->hasVirtualProduct() && $event->getStatus() == $paidStatusId) { $contact_email = ConfigQuery::read('store_email'); if ($contact_email) { $message = MessageQuery::create()->filterByName('mail_virtualproduct')->findOne(); if (false === $message) { throw new \Exception("Failed to load message 'mail_virtualproduct'."); } $order = $event->getOrder(); $customer = $order->getCustomer(); $this->parser->assign('customer_id', $customer->getId()); $this->parser->assign('order_id', $order->getId()); $this->parser->assign('order_ref', $order->getRef()); $this->parser->assign('order_date', $order->getCreatedAt()); $this->parser->assign('update_date', $order->getUpdatedAt()); $message->setLocale($order->getLang()->getLocale()); $instance = \Swift_Message::newInstance()->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname())->addFrom($contact_email, ConfigQuery::read('store_name')); // Build subject and body $message->buildMessage($this->parser, $instance); $this->mailer->send($instance); Tlog::getInstance()->debug("Virtual product download message sent to customer " . $customer->getEmail()); } else { $customer = $order->getCustomer(); Tlog::getInstance()->debug("Virtual product download message no contact email customer_id", $customer->getId()); } } }
public function export() { if (null !== ($response = $this->checkAuth([AdminResources::MODULE, AdminResources::ORDER], ['Predict'], AccessManager::VIEW))) { return $response; } $orders = PredictQuery::getOrders(); $export = new PredictExport(); $export_data = ""; /** * Validate the form and checks which order(s) must be exported */ try { $form = new ExportForm($this->getRequest()); $vform = $this->validateForm($form, "post"); $entries = array(); /** @var \Thelia\Model\Order $order */ foreach ($orders as $order) { if ($vform->get("order_" . $order->getId())->getData()) { $entries[] = $entry = new ExportEntry($order, $vform->get("guaranty_" . $order->getId())->getData()); $export->addEntry($entry); } } /** * Be sure that the export is done before updating the order status */ $export_data = $export->doExport(); $status = null; switch ($vform->get("new_status")->getData()) { case "processing": $status = OrderStatus::CODE_PROCESSING; break; case "sent": $status = OrderStatus::CODE_SENT; break; } if ($status !== null) { /** * If the current user doesn't have the right to edit orders, return an error */ if (null !== ($response = $this->checkAuth([AdminResources::ORDER], [], AccessManager::UPDATE))) { return $response; } /** * Get status ID */ $status_id = OrderStatusQuery::create()->findOneByCode($status)->getId(); /** @var ExportEntry $entry */ foreach ($entries as $entry) { $event = new OrderEvent($entry->getOrder()); $event->setStatus($status_id); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } catch (\Exception $e) { return $this->render("module-configure", ["module_code" => "Predict", "tab" => "export", "error_message" => $e->getMessage()]); } return $this->createResponse($export_data); }
public function checkIsRequiredCode($value, ExecutionContextInterface $context) { if ($this->form->has('id')) { if (null !== ($orderStatus = OrderStatusQuery::create()->findOneById($this->form->get('id')->getData()))) { if (!$orderStatus->getProtectedStatus() && empty($this->form->get('code')->getData())) { $context->addViolation(Translator::getInstance()->trans("This value should not be blank.")); } } } }
/** * * in this function you add all the fields you need for your Form. * Form this you have to call add method on $this->formBuilder attribute : * * $this->formBuilder->add("name", "text") * ->add("email", "email", array( * "attr" => array( * "class" => "field" * ), * "label" => "email", * "constraints" => array( * new \Symfony\Component\Validator\Constraints\NotBlank() * ) * ) * ) * ->add('age', 'integer'); * * @return null */ 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(SoColissimo::getModCode())->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()))); } }
/** * @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")); }
public function buildModelCriteria() { $search = OrderStatusQuery::create(); /* manage translations */ $this->configureI18nProcessing($search); $id = $this->getId(); if (null !== $id) { $search->filterById($id, Criteria::IN); } return $search; }
/** * 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++; } } }
public function updateStatus($order_id = null) { if (null !== ($response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE))) { return $response; } $message = null; try { if ($order_id === null) { $order_id = $this->getRequest()->get("order_id"); } $order = OrderQuery::create()->findPk($order_id); $statusId = $this->getRequest()->request->get("status_id"); $status = OrderStatusQuery::create()->findPk($statusId); if (null === $order) { throw new \InvalidArgumentException("The order you want to update status does not exist"); } if (null === $status) { throw new \InvalidArgumentException("The status you want to set to the order does not exist"); } $event = new OrderEvent($order); $event->setStatus($statusId); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } catch (\Exception $e) { $message = $e->getMessage(); } $params = array(); if ($message) { $params["update_status_error_message"] = $message; } $browsedPage = $this->getRequest()->get("order_page"); $currentStatus = $this->getRequest()->get("status"); if ($browsedPage) { $params["order_page"] = $browsedPage; if (null !== $currentStatus) { $params["status"] = $currentStatus; } $response = $this->generateRedirectFromRoute("admin.order.list", $params); } else { $params["tab"] = $this->getRequest()->get("tab", 'cart'); $response = $this->generateRedirectFromRoute("admin.order.update.view", $params, ['order_id' => $order_id]); } return $response; }
public static function getCancelledStatus() { return OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_CANCELED); }
/** * Set paid status to the order * @param OrderEvent $orderEvent * @throws \Propel\Runtime\Exception\PropelException */ public function changeOrderStatus(OrderEvent $orderEvent) { $paidStatusId = OrderStatusQuery::create()->filterByCode('paid')->select('ID')->findOne(); $event = new OrderEvent($orderEvent->getPlacedOrder()); $event->setStatus($paidStatusId); $orderEvent->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); }
/** * @return OrderQuery */ public static function getOrders() { $status = OrderStatusQuery::create()->filterByCode(array(OrderStatus::CODE_PAID, OrderStatus::CODE_PROCESSING), Criteria::IN)->find()->toArray("code"); $query = OrderQuery::create()->filterByDeliveryModuleId((new Colissimo())->getModuleModel()->getId())->filterByStatusId(array($status[OrderStatus::CODE_PAID]['Id'], $status[OrderStatus::CODE_PROCESSING]['Id']), Criteria::IN); return $query; }
protected function changeStatus() { $orderIdList = $this->getRequest()->request->get("order-selection"); if (!is_array($orderIdList)) { $orderIdList = [$orderIdList]; } $statusId = $this->getRequest()->request->get("status-status", null); $message = null; try { $status = OrderStatusQuery::create()->findPk($statusId); if (null === $status) { throw new \InvalidArgumentException("The status you want to set to the order does not exist"); } foreach ($orderIdList as $orderId) { $order = OrderQuery::create()->findPk($orderId); if (null === $order) { throw new \InvalidArgumentException("The order you want to update status does not exist"); } $event = new OrderEvent($order); $event->setStatus($statusId); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } catch (\Exception $e) { $message = $e->getMessage(); } if (null !== $message) { $this->getRequest()->getSession()->getFlashBag()->add('tntfrance-error', $message); } return $this->generateRedirectFromRoute('tntfrance.orders.list'); }
/** * Performs an INSERT on the database, given a OrderStatus or Criteria object. * * @param mixed $criteria Criteria or OrderStatus 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(OrderStatusTableMap::DATABASE_NAME); } if ($criteria instanceof Criteria) { $criteria = clone $criteria; // rename for clarity } else { $criteria = $criteria->buildCriteria(); // build Criteria from OrderStatus object } if ($criteria->containsKey(OrderStatusTableMap::ID) && $criteria->keyContainsValue(OrderStatusTableMap::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . OrderStatusTableMap::ID . ')'); } // Set the correct dbName $query = OrderStatusQuery::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; }
/** * @depends testCreate * * @param OrderModel $order */ public function testModelUpdateStatusCanceledWithHelpers(OrderModel $order) { $order->setCancelled(); $this->assertEquals($order->getStatusId(), OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_CANCELED)->getId()); $this->assertTrue($order->isCancelled()); }
public function exportfile() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('DpdPickup'), AccessManager::UPDATE))) { return $response; } if (is_readable(ExportExaprint::getJSONpath())) { $admici = json_decode(file_get_contents(ExportExaprint::getJSONpath()), true); $keys = array("name", "addr", "zipcode", "city", "tel", "mobile", "mail", "expcode"); $valid = true; foreach ($keys as $key) { $valid &= isset($admici[$key]) && ($key === "assur" ? true : !empty($admici[$key])); } if (!$valid) { return Response::create(Translator::getInstance()->trans("The file DpdPickup/Config/exportdat.json is not valid. Please correct it.", [], DpdPickup::DOMAIN), 500); } } else { return Response::create(Translator::getInstance()->trans("Can't read DpdPickup/Config/exportdat.json. Did you save the export information ?", [], DpdPickup::DOMAIN), 500); } $exp_name = $admici['name']; $exp_address1 = $admici['addr']; $exp_address2 = isset($admici['addr2']) ? $admici['addr2'] : ""; $exp_zipcode = $admici['zipcode']; $exp_city = $admici['city']; $exp_phone = $admici['tel']; $exp_cellphone = $admici['mobile']; $exp_email = $admici['mail']; $exp_code = $admici['expcode']; $res = self::harmonise('$' . "VERSION=110", 'alphanumeric', 12) . "\r\n"; $orders = OrderQuery::create()->filterByDeliveryModuleId(DpdPickup::getModuleId())->find(); // FORM VALIDATION $form = new ExportExaprintSelection($this->getRequest()); $status_id = null; try { $vform = $this->validateForm($form); $status_id = $vform->get("new_status_id")->getData(); if (!preg_match("#^nochange|processing|sent\$#", $status_id)) { throw new \Exception("Invalid status ID. Expecting nochange or processing or sent"); } } catch (\Exception $e) { Tlog::getInstance()->error("Form dpdpickup.selection sent with bad infos. "); return Response::create(Translator::getInstance()->trans("Got invalid data : %err", ['%err' => $e->getMessage()], DpdPickup::DOMAIN), 500); } // For each selected order /** @var Order $order */ foreach ($orders as $order) { $orderRef = str_replace(".", "-", $order->getRef()); $collectionKey = array_search($orderRef, $vform->getData()['order_ref']); if (false !== $collectionKey && array_key_exists($collectionKey, $vform->getData()['order_ref_check']) && $vform->getData()['order_ref_check'][$collectionKey]) { // Get if the package is assured, how many packages there are & their weight $assur_package = array_key_exists($collectionKey, $vform->getData()['assur']) ? $vform->getData()['assur'][$collectionKey] : false; $pkgNumber = array_key_exists($collectionKey, $vform->getData()['pkgNumber']) ? $vform->getData()['pkgNumber'][$collectionKey] : null; $pkgWeight = array_key_exists($collectionKey, $vform->getData()['pkgWeight']) ? $vform->getData()['pkgWeight'][$collectionKey] : null; // Check if status has to be changed if ($status_id == "processing") { $event = new OrderEvent($order); $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_PROCESSING); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } elseif ($status_id == "sent") { $event = new OrderEvent($order); $status = OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_SENT); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } //Get invoice address $address = OrderAddressQuery::create()->findPK($order->getInvoiceOrderAddressId()); //Get Customer object $customer = CustomerQuery::create()->findPK($order->getCustomerId()); //Get OrderAddressDpdPickup object $icirelais_code = OrderAddressIcirelaisQuery::create()->findPK($order->getDeliveryOrderAddressId()); if ($icirelais_code !== null) { // Get Customer's cellphone if (null == ($cellphone = $address->getCellphone())) { $address->getPhone(); } //Weight & price calc $price = 0; $price = $order->getTotalAmount($price, false); // tax = 0 && include postage = flase $pkgWeight = floor($pkgWeight * 100); $assur_price = $assur_package == 'true' ? $price : 0; $date_format = date("d/m/y", $order->getUpdatedAt()->getTimestamp()); $res .= self::harmonise($order->getRef(), 'alphanumeric', 35); // Order ref $res .= self::harmonise("", 'alphanumeric', 2); $res .= self::harmonise($pkgWeight, 'numeric', 8); // Package weight $res .= self::harmonise("", 'alphanumeric', 15); $res .= self::harmonise($address->getLastname(), 'alphanumeric', 35); // Charged customer $res .= self::harmonise($address->getFirstname(), 'alphanumeric', 35); $res .= self::harmonise($address->getAddress2(), 'alphanumeric', 35); // Invoice address info $res .= self::harmonise($address->getAddress3(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 35); $res .= self::harmonise($address->getZipcode(), 'alphanumeric', 10); // Invoice address $res .= self::harmonise($address->getCity(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise($address->getAddress1(), 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise("F", 'alphanumeric', 3); // Default invoice country code $res .= self::harmonise($address->getPhone(), 'alphanumeric', 30); // Invoice phone $res .= self::harmonise("", 'alphanumeric', 15); $res .= self::harmonise($exp_name, 'alphanumeric', 35); // Expeditor name $res .= self::harmonise($exp_address2, 'alphanumeric', 35); // Expeditor address $res .= self::harmonise("", 'alphanumeric', 140); $res .= self::harmonise($exp_zipcode, 'alphanumeric', 10); $res .= self::harmonise($exp_city, 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise($exp_address1, 'alphanumeric', 35); $res .= self::harmonise("", 'alphanumeric', 10); $res .= self::harmonise("F", 'alphanumeric', 3); // Default expeditor country code $res .= self::harmonise($exp_phone, 'alphanumeric', 30); // Expeditor phone $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 1 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 2 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 3 $res .= self::harmonise("", 'alphanumeric', 35); // Order comment 4 $res .= self::harmonise($date_format . ' ', 'alphanumeric', 10); // Date $res .= self::harmonise($exp_code, 'numeric', 8); // Expeditor DPD code $res .= self::harmonise("", 'alphanumeric', 35); // Bar code $res .= self::harmonise($customer->getRef(), 'alphanumeric', 35); // Customer ref $res .= self::harmonise("", 'alphanumeric', 29); $res .= self::harmonise($assur_price, 'float', 9); // Insured value $res .= self::harmonise("", 'alphanumeric', 8); $res .= self::harmonise($customer->getId(), 'alphanumeric', 35); // Customer ID $res .= self::harmonise("", 'alphanumeric', 46); $res .= self::harmonise($exp_email, 'alphanumeric', 80); // Expeditor email $res .= self::harmonise($exp_cellphone, 'alphanumeric', 35); // Expeditor cellphone $res .= self::harmonise($customer->getEmail(), 'alphanumeric', 80); // Customer email $res .= self::harmonise($cellphone, 'alphanumeric', 35); // Invoice cellphone $res .= self::harmonise("", 'alphanumeric', 96); $res .= self::harmonise($icirelais_code->getCode(), 'alphanumeric', 8); // DPD relay ID $res .= "\r\n"; } } } $response = new Response(utf8_decode(mb_strtoupper($res)), 200, array('Content-Type' => 'application/csv-tab-delimited-table;charset=iso-8859-1', 'Content-disposition' => 'filename=export.dat')); return $response; }
public function export() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('FreeShipping'), AccessManager::UPDATE))) { return $response; } $csv = new CSV(self::CSV_SEPARATOR); try { $form = new ExportOrder($this->getRequest()); $vform = $this->validateForm($form); // Check status_id $status_id = $vform->get("new_status_id")->getData(); if (!preg_match("#^nochange|processing|sent\$#", $status_id)) { throw new Exception("Bad value for new_status_id field"); } $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[OrderStatus::CODE_PAID]['Id'], $status[OrderStatus::CODE_PROCESSING]['Id']), Criteria::IN)->find(); // check form && exec csv /** @var \Thelia\Model\Order $order */ foreach ($query as $order) { $value = $vform->get('order_' . $order->getId())->getData(); // If checkbox is checked if ($value) { /** * Retrieve user with the order */ $customer = $order->getCustomer(); /** * Retrieve address with the order */ $address = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId()); if ($address === null) { throw new Exception("Could not find the order's invoice address"); } /** * Retrieve country with the address */ $country = CountryQuery::create()->findPk($address->getCountryId()); if ($country === null) { throw new Exception("Could not find the order's country"); } /** * Retrieve Title */ $title = CustomerTitleI18nQuery::create()->filterById($customer->getTitleId())->findOneByLocale($this->getSession()->getAdminEditionLang()->getLocale()); /** * Get user's phone & cellphone * First get invoice address phone, * If empty, try to get default address' phone. * If still empty, set default value */ $phone = $address->getPhone(); if (empty($phone)) { $phone = $customer->getDefaultAddress()->getPhone(); if (empty($phone)) { $phone = self::DEFAULT_PHONE; } } /** * Cellp */ $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = self::DEFAULT_CELLPHONE; } /** * Compute package weight */ $weight = 0; /** @var \Thelia\Model\OrderProduct $product */ foreach ($order->getOrderProducts() as $product) { $weight += (double) $product->getWeight(); } /** * Get store's name */ $store_name = ConfigQuery::read("store_name"); /** * Write CSV line */ $csv->addLine(CSVLine::create(array($address->getFirstname(), $address->getLastname(), $address->getCompany(), $address->getAddress1(), $address->getAddress2(), $address->getAddress3(), $address->getZipcode(), $address->getCity(), $country->getIsoalpha2(), $phone, $cellphone, $order->getRef(), $title->getShort(), $customer->getEmail(), $weight, $store_name))); /** * Then update order's status if necessary */ if ($status_id == "processing") { $event = new OrderEvent($order); $event->setStatus($status[OrderStatus::CODE_PROCESSING]['Id']); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } elseif ($status_id == "sent") { $event = new OrderEvent($order); $event->setStatus($status[OrderStatus::CODE_SENT]['Id']); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } } catch (\Exception $e) { return Response::create($e->getMessage(), 500); } return Response::create(utf8_decode($csv->parse()), 200, array("Content-Encoding" => "ISO-8889-1", "Content-Type" => "application/csv-tab-delimited-table", "Content-disposition" => "filename=export.csv")); }
/** * @param $event \Thelia\Core\Event\UpdatePositionEvent * @return null|Response */ protected function performAdditionalUpdatePositionAction($event) { $folder = OrderStatusQuery::create()->findPk($event->getObjectId()); if ($folder != null) { return $this->generateRedirectFromRoute('admin.order-status.default'); } else { return null; } }
/** * test order status update position * @covers Thelia\Action\OrderStatus::updatePosition */ public function testUpdatePositionUp() { $orderStatus = OrderStatusQuery::create()->filterByPosition(2)->findOne(); if (null === $orderStatus) { $this->fail('Use fixtures before launching test, there is not enough folder in database'); } $newPosition = $orderStatus->getPosition() - 1; $event = new UpdatePositionEvent($orderStatus->getId(), UpdatePositionEvent::POSITION_UP); $orderStatusAction = new OrderStatusAction(); $orderStatusAction->updatePosition($event, null, $this->getMockEventDispatcher()); $orderStatusUpdated = OrderStatusQuery::create()->findOneById($orderStatus->getId()); $this->assertEquals($newPosition, $orderStatusUpdated->getPosition(), sprintf("new position is %d, new position expected is %d for order status %d", $newPosition, $orderStatusUpdated->getPosition(), $orderStatusUpdated->getCode())); }
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; }
/** * Set the status of the current order to the provided status * * @param string $statusCode the status code, one of OrderStatus::CODE_xxx constants. */ public function setStatusHelper($statusCode) { if (null !== ($ordeStatus = OrderStatusQuery::create()->findOneByCode($statusCode))) { $this->setOrderStatus($ordeStatus)->save(); } }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see OrderStatus::setDeleted() * @see OrderStatus::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(OrderStatusTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildOrderStatusQuery::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; } }
public function import($startRecord = 0) { $count = 0; $errors = 0; $hdl = $this->t1db->query(sprintf("select * from commande order by id asc limit %d, %d", intval($startRecord), $this->getChunkSize())); while ($hdl && ($commande = $this->t1db->fetch_object($hdl))) { $count++; try { $this->order_corresp->getT2($commande->id); Tlog::getInstance()->warning("Order ID={$commande->id} already imported."); continue; } catch (ImportException $ex) { // Okay, the order was not imported. } try { if (null === ($customer = CustomerQuery::create()->findPk($this->cust_corresp->getT2($commande->client)))) { throw new ImportException("Failed to find customer ID={$commande->client}"); } if (null === ($status = OrderStatusQuery::create()->findPk($commande->statut))) { throw new ImportException("Failed to find order status ID={$commande->statut}"); } // Create invoice address if (false == ($adr_livr = $this->t1db->query_obj("select * from venteadr where id=?", array($commande->adrlivr)))) { throw new ImportException("Failed to find delivery adresse ID={$commande->adrlivr}"); } // Create invoice address if (false == ($adr_fact = $this->t1db->query_obj("select * from venteadr where id=?", array($commande->adrfact)))) { throw new ImportException("Failed to find billing adresse ID={$commande->adrfact}"); } $con = Propel::getConnection(OrderTableMap::DATABASE_NAME); $con->beginTransaction(); try { $order = new Order(); $delivery_adr = new OrderAddress(); $delivery_adr->setCustomerTitleId($this->getT2CustomerTitle($adr_livr->raison)->getId())->setCompany(isset($adr_livr->entreprise) ? $adr_livr->entreprise : '')->setFirstname($adr_livr->prenom)->setLastname($adr_livr->nom)->setAddress1($adr_livr->adresse1)->setAddress2($adr_livr->adresse2)->setAddress3($adr_livr->adresse3)->setZipcode($adr_livr->cpostal)->setCity($adr_livr->ville)->setPhone($adr_livr->tel)->setCountryId($this->getT2Country($adr_livr->pays)->getId())->save($con); $billing_adr = new OrderAddress(); $billing_adr->setCustomerTitleId($this->getT2CustomerTitle($adr_fact->raison)->getId())->setCompany(isset($adr_fact->entreprise) ? $adr_fact->entreprise : '')->setFirstname($adr_fact->prenom)->setLastname($adr_fact->nom)->setAddress1($adr_fact->adresse1)->setAddress2($adr_fact->adresse2)->setAddress3($adr_fact->adresse3)->setZipcode($adr_fact->cpostal)->setCity($adr_fact->ville)->setPhone($adr_fact->tel)->setCountryId($this->getT2Country($adr_fact->pays)->getId())->save($con); // Find the first availables delivery and payment modules, that's the best we can do. $deliveryModule = ModuleQuery::create()->findOneByType(BaseModule::DELIVERY_MODULE_TYPE); $paymentModule = ModuleQuery::create()->findOneByType(BaseModule::PAYMENT_MODULE_TYPE); // Create a cart (now required) $cart = new Cart(); $cart->save(); $order->setRef($commande->ref)->setCustomer($customer)->setInvoiceDate($commande->datefact)->setCurrency($this->getT2Currency($commande->devise))->setCurrencyRate($this->getT2Currency($commande->devise)->getRate())->setTransactionRef($commande->transaction)->setDeliveryRef($commande->livraison)->setInvoiceRef($commande->facture)->setPostage($commande->port)->setStatusId($status->getId())->setLang($this->getT2Lang($commande->lang))->setDeliveryOrderAddressId($delivery_adr->getId())->setInvoiceOrderAddressId($billing_adr->getId())->setDeliveryModuleId($deliveryModule->getId())->setPaymentModuleId($paymentModule->getId())->setDiscount($commande->remise)->setCartId($cart->getId())->save($con); // Update the order reference $order->setRef($commande->ref)->setCreatedAt($commande->date)->save(); if ($commande->remise > 0) { $coupon = new OrderCoupon(); $coupon->setOrder($order)->setCode('Not Available')->setType('UNKNOWN')->setAmount($commande->remise)->setTitle('Imported from Thelia 1')->setShortDescription('Imported from Thelia 1')->setDescription('Imported from Thelia 1')->setExpirationDate(time())->setIsCumulative(false)->setIsRemovingPostage(false)->setIsAvailableOnSpecialOffers(false)->setSerializedConditions(new ConditionCollection(array()))->save($con); } $vps = $this->t1db->query_list("select * from venteprod where commande=?", array($commande->id)); foreach ($vps as $vp) { $parent = 0; if (isset($vp->parent) && $vp->parent != 0) { $parent = $this->product_corresp->getT2($vp->parent); } $orderProduct = new OrderProduct(); $orderProduct->setOrder($order)->setProductRef($vp->ref)->setProductSaleElementsRef($vp->ref)->setTitle($vp->titre)->setChapo($vp->chapo)->setDescription($vp->description)->setPostscriptum("")->setQuantity($vp->quantite)->setPrice($vp->prixu / (1 + $vp->tva / 100))->setPromoPrice($vp->prixu / (1 + $vp->tva / 100))->setWasNew(false)->setWasInPromo(false)->setWeight(0)->setEanCode("")->setTaxRuleTitle("")->setTaxRuleDescription("")->setParent($parent)->save($con); $orderProductTax = new OrderProductTax(); $orderProductTax->setAmount($orderProduct->getPrice() * ($vp->tva / 100))->setPromoAmount(0)->setOrderProduct($orderProduct)->setTitle("TVA {$vp->tva} %")->setDescription("TVA {$vp->tva} %")->save($con); } $con->commit(); } catch (\Exception $ex) { $con->rollBack(); throw $ex; } } catch (\Exception $ex) { Tlog::getInstance()->addError("Failed to import order ref {$commande->ref}: ", $ex->getMessage()); $errors++; } } return new ImportChunkResult($count, $errors); }
/** * Get the associated ChildOrderStatus object * * @param ConnectionInterface $con Optional Connection object. * @return ChildOrderStatus The associated ChildOrderStatus object. * @throws PropelException */ public function getOrderStatus(ConnectionInterface $con = null) { if ($this->aOrderStatus === null && $this->id !== null) { $this->aOrderStatus = ChildOrderStatusQuery::create()->findPk($this->id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aOrderStatus->addOrderStatusI18ns($this); */ } return $this->aOrderStatus; }
public function cancel($order_id) { /* * Check if token&order are valid */ $token = null; $order = $this->checkorder($order_id, $token); /* * $logger PaypalApiLogManager used to log transctions with paypal */ $logger = new PaypalApiLogManager('canceled_orders'); $logger->logText("Order canceled: " . $order->getRef()); $event = new OrderEvent($order); $event->setStatus(OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_CANCELED)->getId()); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); return $this->render("order-failed", ["failed_order_id" => $order_id]); }
public function exportAction() { if (null !== ($response = $this->checkAuth(array(AdminResources::MODULE), array('Colissimo'), AccessManager::UPDATE))) { return $response; } $form = new FormExport($this->getRequest()); try { $exportForm = $this->validateForm($form); // Get new status $status_id = $exportForm->get('status_id')->getData(); $status = OrderStatusQuery::create()->filterByCode($status_id)->findOne(); // Get Colissimo orders $orders = ColissimoQuery::getOrders()->find(); $export = ""; $store_name = ConfigQuery::getStoreName(); /** @var $order \Thelia\Model\Order */ foreach ($orders as $order) { $value = $exportForm->get('order_' . $order->getId())->getData(); if ($value) { // Get order information $customer = $order->getCustomer(); $locale = $order->getLang()->getLocale(); $address = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); $country = CountryQuery::create()->findPk($address->getCountryId()); $country->setLocale($locale); $customerTitle = CustomerTitleQuery::create()->findPk($address->getCustomerTitleId()); $customerTitle->setLocale($locale); $weight = $exportForm->get('order_weight_' . $order->getId())->getData(); if ($weight == 0) { /** @var \Thelia\Model\OrderProduct $product */ foreach ($order->getOrderProducts() as $product) { $weight += (double) $product->getWeight(); } } /** * Get user's phone & cellphone * First get invoice address phone, * If empty, try to get default address' phone. * If still empty, set default value */ $phone = $address->getPhone(); if (empty($phone)) { $phone = $customer->getDefaultAddress()->getPhone(); if (empty($phone)) { $phone = self::DEFAULT_PHONE; } } // Cellphone $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = $customer->getDefaultAddress()->getCellphone(); if (empty($cellphone)) { $cellphone = self::DEFAULT_CELLPHONE; } } $export .= "\"" . $order->getRef() . "\";\"" . $address->getLastname() . "\";\"" . $address->getFirstname() . "\";\"" . $address->getAddress1() . "\";\"" . $address->getAddress2() . "\";\"" . $address->getAddress3() . "\";\"" . $address->getZipcode() . "\";\"" . $address->getCity() . "\";\"" . $country->getIsoalpha2() . "\";\"" . $phone . "\";\"" . $cellphone . "\";\"" . $weight . "\";\"" . $customer->getEmail() . "\";\"\";\"" . $store_name . "\";\"DOM\";\r\n"; if ($status) { $event = new OrderEvent($order); $event->setStatus($status->getId()); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); } } } return Response::create(utf8_decode($export), 200, array("Content-Encoding" => "ISO-8889-1", "Content-Type" => "application/csv-tab-delimited-table", "Content-disposition" => "filename=export.csv")); } catch (FormValidationException $e) { $this->setupFormErrorContext(Translator::getInstance()->trans("colissimo expeditor export", [], Colissimo::DOMAIN_NAME), $e->getMessage(), $form, $e); return $this->render("module-configure", array("module_code" => "Colissimo")); } }
public static function getRefundedStatus() { return OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_REFUNDED); }