public function buildModelCriteria() { $search = OrderAddressQuery::create(); $id = $this->getId(); $search->filterById($id, Criteria::IN); return $search; }
/** * @param OrderQuery $search * @param $searchTerm * @param $searchIn * @param $searchCriteria */ public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria) { $search->_and(); foreach ($searchIn as $index => $searchInElement) { if ($index > 0) { $search->_or(); } switch ($searchInElement) { case 'ref': $search->filterByRef($searchTerm, $searchCriteria); break; case 'invoice_ref': $search->filterByInvoiceRef($searchTerm, $searchCriteria); break; case 'customer_ref': $search->filterByCustomer(CustomerQuery::create()->filterByRef($searchTerm, $searchCriteria)->find()); break; case 'customer_firstname': $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(OrderAddressQuery::create()->filterByFirstname($searchTerm, $searchCriteria)->find()); break; case 'customer_lastname': $search->filterByOrderAddressRelatedByInvoiceOrderAddressId(OrderAddressQuery::create()->filterByLastname($searchTerm, $searchCriteria)->find()); break; case 'customer_email': $search->filterByCustomer(CustomerQuery::create()->filterByEmail($searchTerm, $searchCriteria)->find()); break; } } }
public function verifyId($value, ExecutionContextInterface $context) { $address = OrderAddressQuery::create()->findPk($value); if (null === $address) { $context->addViolation(Translator::getInstance()->trans("Order address ID not found")); } }
/** * @return array|mixed|OrderAddress * @throws \UnexpectedValueException */ public function getDeliveryOrderAddress() { $delivery_order_address_id = $this->order->getDeliveryOrderAddressId(); $delivery_order_address = OrderAddressQuery::create()->findPk($delivery_order_address_id); if ($delivery_order_address === null) { throw new \UnexpectedValueException("The delivery address doesn't exist"); } return $delivery_order_address; }
public static function getFromOrder(Order $order) { $translator = Translator::getInstance(); if ($order->getDeliveryModuleId() !== TNTFrance::getModuleId()) { throw new \InvalidArgumentException($translator->trans("The order %id does not use the", ['id' => $order->getId()], TNTFrance::MESSAGE_DOMAIN)); } $data = TNTFrance::getExtraOrderData($order->getId(), false); if (empty($data)) { throw new \InvalidArgumentException($translator->trans("No TNT data for order %id", ['id' => $order->getId()], TNTFrance::MESSAGE_DOMAIN)); } $receiver = new TNTReceiver(); $receiver->setType($data['tnt_service']); $receiver->setEmailAddress($order->getCustomer()->getEmail()); if (array_key_exists('tnt_instructions', $data)) { $receiver->setInstructions($data['tnt_instructions']); } if (array_key_exists('tnt_phoneNumber', $data)) { $phoneNumber = str_replace(" ", "", $data['tnt_phoneNumber']); $receiver->setPhoneNumber($phoneNumber); } //todo : $receiver->setSendNotification(TNTFrance::getConfigValue(TNTFranceConfigValue::NOTIFICATION_USER)); switch ($data['tnt_service']) { case 'INDIVIDUAL': case 'ENTERPRISE': $address = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId()); if (null !== $address) { $receiver->setName($address->getCompany())->setAddress1($address->getAddress1())->setAddress2($address->getAddress2())->setZipCode($address->getZipcode())->setCity($address->getCity())->setContactLastName($address->getLastname())->setContactFirstName($address->getFirstname()); if (array_key_exists('tnt_accessCode', $data)) { $receiver->setAccessCode($data['tnt_accessCode']); } if (array_key_exists('tnt_floorNumber', $data)) { $receiver->setAccessCode($data['tnt_floorNumber']); } if (array_key_exists('tnt_buildingId', $data)) { $receiver->setAccessCode($data['tnt_buildingId']); } } break; case 'DEPOT': $receiver->setTypeId($data['tnt_pexcode'])->setCity($data['tnt_depot_address']['city']); break; case 'DROPOFFPOINT': $receiver->setTypeId($data['tnt_exttcode']); break; default: throw new \InvalidArgumentException($translator->trans("TNT service %service is not valid for order %id", ['id' => $order->getId(), 'service' => $data['tnt_service']], TNTFrance::MESSAGE_DOMAIN)); } return $receiver; }
/** * @param OrderEvent $event * @throws \Exception */ public function update_address(OrderEvent $event) { if ($event->getOrder()->getDeliveryModuleId() === LocalPickup::getModCode()) { $address_id = $event->getOrder()->getDeliveryOrderAddressId(); $address = OrderAddressQuery::create()->findPk($address_id); if ($address !== null) { $config = new ConfigQuery(); $address1 = $config->read("store_address1"); $address2 = $config->read("store_address2"); $address3 = $config->read("store_address3"); $zipcode = $config->read("store_zipcode"); $city = $config->read("store_city"); $country = $config->read("store_country"); $name = $config->read("store_name"); if ($address1 !== null && $zipcode !== null && $city !== null && $country !== null) { $address_event = new OrderAddressEvent($address->getCustomerTitleId(), $address->getFirstname(), $address->getLastname(), $address1, $address2, $address3, $zipcode, $city, $country, $address->getPhone(), $name); $address_event->setOrderAddress($address); $event->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_ADDRESS, $address_event); } } else { throw new \Exception("Error: order deliery address doesn't exists"); } } }
/** * @param EventDispatcherInterface $dispatcher * @param ModelOrder $sessionOrder * @param CurrencyModel $currency * @param LangModel $lang * @param CartModel $cart * @param UserInterface $customer * @param bool $manageStock decrement stock when order is created if true * @param bool $useOrderDefinedAddresses if true, the delivery and invoice OrderAddresses will be used instead of creating new OrderAdresses using Order::getChoosenXXXAddress() * @return ModelOrder * @throws \Exception * @throws \Propel\Runtime\Exception\PropelException */ protected function createOrder(EventDispatcherInterface $dispatcher, ModelOrder $sessionOrder, CurrencyModel $currency, LangModel $lang, CartModel $cart, UserInterface $customer, $manageStock, $useOrderDefinedAddresses = false) { $con = Propel::getConnection(OrderTableMap::DATABASE_NAME); $con->beginTransaction(); $placedOrder = $sessionOrder->copy(); // Be sure to create a brand new order, as copy raises the modified flag for all fields // and will also copy order reference and id. $placedOrder->setId(null)->setRef(null)->setNew(true); // Dates should be marked as not updated so that Propel will update them. $placedOrder->resetModified(OrderTableMap::CREATED_AT); $placedOrder->resetModified(OrderTableMap::UPDATED_AT); $placedOrder->resetModified(OrderTableMap::VERSION_CREATED_AT); $placedOrder->setDispatcher($dispatcher); $cartItems = $cart->getCartItems(); /* fulfill order */ $placedOrder->setCustomerId($customer->getId()); $placedOrder->setCurrencyId($currency->getId()); $placedOrder->setCurrencyRate($currency->getRate()); $placedOrder->setLangId($lang->getId()); if ($useOrderDefinedAddresses) { $taxCountry = OrderAddressQuery::create()->findPk($placedOrder->getDeliveryOrderAddressId())->getCountry(); } else { $deliveryAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenDeliveryAddress()); $invoiceAddress = AddressQuery::create()->findPk($sessionOrder->getChoosenInvoiceAddress()); /* hard save the delivery and invoice addresses */ $deliveryOrderAddress = new OrderAddress(); $deliveryOrderAddress->setCustomerTitleId($deliveryAddress->getTitleId())->setCompany($deliveryAddress->getCompany())->setFirstname($deliveryAddress->getFirstname())->setLastname($deliveryAddress->getLastname())->setAddress1($deliveryAddress->getAddress1())->setAddress2($deliveryAddress->getAddress2())->setAddress3($deliveryAddress->getAddress3())->setZipcode($deliveryAddress->getZipcode())->setCity($deliveryAddress->getCity())->setPhone($deliveryAddress->getPhone())->setCellphone($deliveryAddress->getCellphone())->setCountryId($deliveryAddress->getCountryId())->setStateId($deliveryAddress->getStateId())->save($con); $invoiceOrderAddress = new OrderAddress(); $invoiceOrderAddress->setCustomerTitleId($invoiceAddress->getTitleId())->setCompany($invoiceAddress->getCompany())->setFirstname($invoiceAddress->getFirstname())->setLastname($invoiceAddress->getLastname())->setAddress1($invoiceAddress->getAddress1())->setAddress2($invoiceAddress->getAddress2())->setAddress3($invoiceAddress->getAddress3())->setZipcode($invoiceAddress->getZipcode())->setCity($invoiceAddress->getCity())->setPhone($invoiceAddress->getPhone())->setCellphone($invoiceAddress->getCellphone())->setCountryId($invoiceAddress->getCountryId())->setStateId($deliveryAddress->getStateId())->save($con); $placedOrder->setDeliveryOrderAddressId($deliveryOrderAddress->getId()); $placedOrder->setInvoiceOrderAddressId($invoiceOrderAddress->getId()); $taxCountry = $deliveryAddress->getCountry(); } $placedOrder->setStatusId(OrderStatusQuery::getNotPaidStatus()->getId()); $placedOrder->setCartId($cart->getId()); /* memorize discount */ $placedOrder->setDiscount($cart->getDiscount()); $placedOrder->save($con); /* fulfill order_products and decrease stock */ foreach ($cartItems as $cartItem) { $product = $cartItem->getProduct(); /* get translation */ /** @var ProductI18n $productI18n */ $productI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'Product', $product->getId()); $pse = $cartItem->getProductSaleElements(); // get the virtual document path $virtualDocumentEvent = new VirtualProductOrderHandleEvent($placedOrder, $pse->getId()); // essentially used for virtual product. modules that handles virtual product can // allow the use of stock even for virtual products $useStock = true; $virtual = 0; // if the product is virtual, dispatch an event to collect information if ($product->getVirtual() === 1) { $dispatcher->dispatch(TheliaEvents::VIRTUAL_PRODUCT_ORDER_HANDLE, $virtualDocumentEvent); $useStock = $virtualDocumentEvent->isUseStock(); $virtual = $virtualDocumentEvent->isVirtual() ? 1 : 0; } /* check still in stock */ if ($cartItem->getQuantity() > $pse->getQuantity() && true === ConfigQuery::checkAvailableStock() && $useStock) { throw new TheliaProcessException("Not enough stock", TheliaProcessException::CART_ITEM_NOT_ENOUGH_STOCK, $cartItem); } if ($useStock && $manageStock) { /* decrease stock for non virtual product */ $allowNegativeStock = intval(ConfigQuery::read('allow_negative_stock', 0)); $newStock = $pse->getQuantity() - $cartItem->getQuantity(); //Forbid negative stock if ($newStock < 0 && 0 === $allowNegativeStock) { $newStock = 0; } $pse->setQuantity($newStock); $pse->save($con); } /* get tax */ /** @var TaxRuleI18n $taxRuleI18n */ $taxRuleI18n = I18n::forceI18nRetrieving($lang->getLocale(), 'TaxRule', $product->getTaxRuleId()); $taxDetail = $product->getTaxRule()->getTaxDetail($product, $taxCountry, $cartItem->getPrice(), $cartItem->getPromoPrice(), $lang->getLocale()); $orderProduct = new OrderProduct(); $orderProduct->setOrderId($placedOrder->getId())->setProductRef($product->getRef())->setProductSaleElementsRef($pse->getRef())->setProductSaleElementsId($pse->getId())->setTitle($productI18n->getTitle())->setChapo($productI18n->getChapo())->setDescription($productI18n->getDescription())->setPostscriptum($productI18n->getPostscriptum())->setVirtual($virtual)->setVirtualDocument($virtualDocumentEvent->getPath())->setQuantity($cartItem->getQuantity())->setPrice($cartItem->getPrice())->setPromoPrice($cartItem->getPromoPrice())->setWasNew($pse->getNewness())->setWasInPromo($cartItem->getPromo())->setWeight($pse->getWeight())->setTaxRuleTitle($taxRuleI18n->getTitle())->setTaxRuleDescription($taxRuleI18n->getDescription())->setEanCode($pse->getEanCode())->setCartItemId($cartItem->getId())->setDispatcher($dispatcher)->save($con); /* fulfill order_product_tax */ /** @var OrderProductTax $tax */ foreach ($taxDetail as $tax) { $tax->setOrderProductId($orderProduct->getId()); $tax->save($con); } /* fulfill order_attribute_combination and decrease stock */ foreach ($pse->getAttributeCombinations() as $attributeCombination) { /** @var \Thelia\Model\Attribute $attribute */ $attribute = I18n::forceI18nRetrieving($lang->getLocale(), 'Attribute', $attributeCombination->getAttributeId()); /** @var \Thelia\Model\AttributeAv $attributeAv */ $attributeAv = I18n::forceI18nRetrieving($lang->getLocale(), 'AttributeAv', $attributeCombination->getAttributeAvId()); $orderAttributeCombination = new OrderProductAttributeCombination(); $orderAttributeCombination->setOrderProductId($orderProduct->getId())->setAttributeTitle($attribute->getTitle())->setAttributeChapo($attribute->getChapo())->setAttributeDescription($attribute->getDescription())->setAttributePostscriptum($attribute->getPostscriptum())->setAttributeAvTitle($attributeAv->getTitle())->setAttributeAvChapo($attributeAv->getChapo())->setAttributeAvDescription($attributeAv->getDescription())->setAttributeAvPostscriptum($attributeAv->getPostscriptum())->save($con); } } $con->commit(); return $placedOrder; }
public function testAddValidEntry() { $delivery_address_id = $this->order->getDeliveryOrderAddressId(); $delivery_address = OrderAddressQuery::create()->findPk($delivery_address_id); $delivery_address->setCountryId(CountryQuery::create()->findOneByIsoalpha3("FRA")->getId()); // France metropolitan $this->export->addEntry($this->instance); }
/** * Get the associated ChildOrderAddress object * * @param ConnectionInterface $con Optional Connection object. * @return ChildOrderAddress The associated ChildOrderAddress object. * @throws PropelException */ public function getOrderAddressRelatedByDeliveryOrderAddressId(ConnectionInterface $con = null) { if ($this->aOrderAddressRelatedByDeliveryOrderAddressId === null && $this->delivery_order_address_id !== null) { $this->aOrderAddressRelatedByDeliveryOrderAddressId = ChildOrderAddressQuery::create()->findPk($this->delivery_order_address_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->aOrderAddressRelatedByDeliveryOrderAddressId->addOrdersRelatedByDeliveryOrderAddressId($this); */ } return $this->aOrderAddressRelatedByDeliveryOrderAddressId; }
/** * Performs an INSERT on the database, given a OrderAddress or Criteria object. * * @param mixed $criteria Criteria or OrderAddress 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(OrderAddressTableMap::DATABASE_NAME); } if ($criteria instanceof Criteria) { $criteria = clone $criteria; // rename for clarity } else { $criteria = $criteria->buildCriteria(); // build Criteria from OrderAddress object } if ($criteria->containsKey(OrderAddressTableMap::ID) && $criteria->keyContainsValue(OrderAddressTableMap::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . OrderAddressTableMap::ID . ')'); } // Set the correct dbName $query = OrderAddressQuery::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; }
/** * If this collection has already been initialized with * an identical criteria, it returns the collection. * Otherwise if this CustomerTitle is new, it will return * an empty collection; or if this CustomerTitle has previously * been saved, it will retrieve related OrderAddresses from storage. * * This method is protected by default in order to keep the public * api reasonable. You can provide public methods for those you * actually need in CustomerTitle. * * @param Criteria $criteria optional Criteria object to narrow the query * @param ConnectionInterface $con optional connection object * @param string $joinBehavior optional join type to use (defaults to Criteria::LEFT_JOIN) * @return Collection|ChildOrderAddress[] List of ChildOrderAddress objects */ public function getOrderAddressesJoinState($criteria = null, $con = null, $joinBehavior = Criteria::LEFT_JOIN) { $query = ChildOrderAddressQuery::create(null, $criteria); $query->joinWith('State', $joinBehavior); return $this->getOrderAddresses($query, $con); }
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")); }
/** * * display an address in expected format * * available parameters : * address => the id of the address to display * order_address => the id of the order address to display * from_country_id => the country id * dec_point => separator for the decimal point * thousands_sep => thousands separator * symbol => Currency symbol * * ex : {format_money number="1246.12" decimals="1" dec_point="," thousands_sep=" " symbol="€"} will output "1 246,1 €" * * @param $params * @param null $template * @throws \TheliaSmarty\Template\Exception\SmartyPluginException * @return string the expected number formatted */ public function formatAddress($params, $template = null) { $postal = filter_var($this->getParam($params, "postal", null), FILTER_VALIDATE_BOOLEAN); $html = filter_var($this->getParam($params, "html", true), FILTER_VALIDATE_BOOLEAN); $htmlTag = $this->getParam($params, "html_tag", "p"); $originCountry = $this->getParam($params, "origin_country", null); $locale = $this->getParam($params, "locale", $this->request->getSession()->getLang()->getLocale()); // extract html attributes $htmlAttributes = []; foreach ($params as $k => $v) { if (strpos($k, 'html_') !== false && $k !== 'html_tag') { $htmlAttributes[substr($k, 5)] = $v; } } // get address or order address $address = null; if (null !== ($id = $this->getParam($params, "address", null))) { if (null === ($address = AddressQuery::create()->findPk($id))) { return ''; } } elseif (null !== ($id = $this->getParam($params, "order_address", null))) { if (null === ($address = OrderAddressQuery::create()->findPk($id))) { return ''; } } else { // try to parse arguments to build address $address = $this->getAddressFormParams($params); } if (null === $address) { throw new SmartyPluginException("Either address, order_address or full list of address fields should be provided"); } $addressFormat = AddressFormat::getInstance(); if ($postal) { if ($address instanceof Address) { $formattedAddress = $addressFormat->postalLabelFormat($address, $locale, $originCountry); } else { $formattedAddress = $addressFormat->postalLabelFormatTheliaAddress($address, $locale, $originCountry); } } else { if ($address instanceof Address) { $formattedAddress = $addressFormat->format($address, $locale, $html, $htmlTag, $htmlAttributes); } else { $formattedAddress = $addressFormat->formatTheliaAddress($address, $locale, $html, $htmlTag, $htmlAttributes); } } return $formattedAddress; }
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]); }
public function go($order_id) { /* * vars used for setExpressCheckout * $order Order The order object, which is used to get products and prices * $config ConfigInterface Object that contains configuration * $api PaypalApiCredentials Class used by the library to store and use 3T login(username, password, signature) * $redirect_api PaypalApiManager Instance of PaypalApiManager, only used to get checkout url ( and redirect to paypal ) * $sandbox bool true if sandbox is enabled * $products array(array) 2D array that stores products in usable NVP format. * $i int counter * $logger PaypalApiLogManager used to log transactions with paypal */ $order = OrderQuery::create()->findPk($order_id); $config = new PaypalConfig(); $config->pushValues(); $api = new PaypalApiCredentials($config); $redirect_api = new PaypalApiManager($config); $sandbox = $api->getConfig()->getSandbox(); $products = array(array()); $i = 0; $logger = new PaypalApiLogManager(); /* * Store products into 2d array $products */ $products_amount = 0; foreach ($order->getOrderProducts() as $product) { if ($product !== null) { $amount = floatval($product->getWasInPromo() ? $product->getPromoPrice() : $product->getPrice()); foreach ($product->getOrderProductTaxes() as $tax) { $amount += $product->getWasInPromo() ? $tax->getPromoAmount() : $tax->getAmount(); } $products_amount += $amount * $product->getQuantity(); $products[0]["NAME" . $i] = urlencode($product->getTitle()); $products[0]["AMT" . $i] = urlencode(round($amount, 2)); $products[0]["QTY" . $i] = urlencode($product->getQuantity()); $i++; } } /* * Compute difference between prodcts total and cart amount * -> get Coupons. */ $delta = round($products_amount - $order->getTotalAmount($useless, false), 2); if ($delta > 0) { $products[0]["NAME" . $i] = Translator::getInstance()->trans("Discount"); $products[0]["AMT" . $i] = -$delta; $products[0]["QTY" . $i] = 1; } /* * Create setExpressCheckout request */ $setExpressCheckout = new PaypalNvpOperationsSetExpressCheckout($api, round($order->getTotalAmount(), 2), $order->getCurrency()->getCode(), Paypal::getPaypalURL('paiement', $order_id), Paypal::getPaypalURL('cancel', $order_id), 0, array("L_PAYMENTREQUEST" => $products, "PAYMENTREQUEST" => array(array("SHIPPINGAMT" => round($order->getPostage(), 2), "ITEMAMT" => round($order->getTotalAmount($useless, false), 2))))); /* * Try to get customer's delivery address */ $address = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId()); if ($address !== null) { /* * If address is found, set address in setExpressCheckout request */ $setExpressCheckout->setCustomerDeliveryAddress($address->getLastname(), $address->getAddress1(), $address->getAddress2(), $address->getCity(), "", $address->getZipcode(), CountryQuery::create()->findPk($address->getCountryId())->getIsoalpha2()); /* * $sender PaypalNvpMessageSender Instance of the class that sends requests * $response string NVP response of paypal for setExpressCheckout request * $req array array cast of NVP response */ $sender = new PaypalNvpMessageSender($setExpressCheckout, $sandbox); $response = $sender->send(); $logger->logTransaction($response); $response = PaypalApiManager::nvpToArray($response); /* * if setExpressCheckout is correct, store values in the session & redirect to paypal checkout page * else print error. ( return $this->render ... ) */ if (isset($response['ACK']) && $response['ACK'] === "Success" && isset($response['TOKEN']) && !empty($response['TOKEN'])) { $sess = $this->getRequest()->getSession(); $sess->set("Paypal.token", $response['TOKEN']); return new RedirectResponse($redirect_api->getExpressCheckoutUrl($response['TOKEN'])); } } return $this->render("gotopaypalfail", array(), 500); }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see OrderAddress::setDeleted() * @see OrderAddress::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(OrderAddressTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildOrderAddressQuery::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 updateDeliveryAddress(OrderEvent $event) { if ($this->check_module($event->getOrder()->getDeliveryModuleId())) { $request = $this->getRequest(); $tmp_address = AddressIcirelaisQuery::create()->findPk($request->getSession()->get('DpdPickupDeliveryId')); if ($tmp_address === null) { throw new \ErrorException("Got an error with DpdPickup module. Please try again to checkout."); } $savecode = new OrderAddressIcirelais(); $savecode->setId($event->getOrder()->getDeliveryOrderAddressId())->setCode($tmp_address->getCode())->save(); $update = OrderAddressQuery::create()->findPK($event->getOrder()->getDeliveryOrderAddressId())->setCompany($tmp_address->getCompany())->setAddress1($tmp_address->getAddress1())->setAddress2($tmp_address->getAddress2())->setAddress3($tmp_address->getAddress3())->setZipcode($tmp_address->getZipcode())->setCity($tmp_address->getCity())->save(); $tmp_address->delete(); } }
/** * @depends testCreate * * @param OrderModel $order */ public function testUpdateAddress(OrderModel $order) { $deliveryRef = uniqid('DELREF'); $orderAddress = OrderAddressQuery::create()->findPk($order->getDeliveryOrderAddressId()); $title = $orderAddress->getCustomerTitleId() == 3 ? 1 : 3; $country = $orderAddress->getCountryId() == 64 ? 1 : 64; $orderAddressEvent = new OrderAddressEvent($title, 'B', 'C', 'D', 'E', 'F', 'G', 'H', $country, 'J', 'K'); $orderAddressEvent->setOrderAddress($orderAddress); $orderAddressEvent->setOrder($order); $this->orderAction->updateAddress($orderAddressEvent); $newOrderAddress = OrderAddressQuery::create()->findPk($orderAddress->getId()); $this->assertEquals($title, $orderAddressEvent->getOrderAddress()->getCustomerTitleId()); $this->assertEquals('B', $orderAddressEvent->getOrderAddress()->getFirstname()); $this->assertEquals('C', $orderAddressEvent->getOrderAddress()->getLastname()); $this->assertEquals('D', $orderAddressEvent->getOrderAddress()->getAddress1()); $this->assertEquals('E', $orderAddressEvent->getOrderAddress()->getAddress2()); $this->assertEquals('F', $orderAddressEvent->getOrderAddress()->getAddress3()); $this->assertEquals('G', $orderAddressEvent->getOrderAddress()->getZipcode()); $this->assertEquals('H', $orderAddressEvent->getOrderAddress()->getCity()); $this->assertEquals($country, $orderAddressEvent->getOrderAddress()->getCountryId()); $this->assertEquals('J', $orderAddressEvent->getOrderAddress()->getPhone()); $this->assertEquals('K', $orderAddressEvent->getOrderAddress()->getCompany()); $this->assertEquals($title, $newOrderAddress->getCustomerTitleId()); $this->assertEquals('B', $newOrderAddress->getFirstname()); $this->assertEquals('C', $newOrderAddress->getLastname()); $this->assertEquals('D', $newOrderAddress->getAddress1()); $this->assertEquals('E', $newOrderAddress->getAddress2()); $this->assertEquals('F', $newOrderAddress->getAddress3()); $this->assertEquals('G', $newOrderAddress->getZipcode()); $this->assertEquals('H', $newOrderAddress->getCity()); $this->assertEquals($country, $newOrderAddress->getCountryId()); $this->assertEquals('J', $newOrderAddress->getPhone()); $this->assertEquals('K', $newOrderAddress->getCompany()); }
public function updateDeliveryAddress(OrderEvent $event) { if ($this->check_module($event->getOrder()->getDeliveryModuleId())) { $request = $this->getRequest(); if ($request->getSession()->get('SoColissimoDomicile') == 1) { $tmp_address = AddressSoColissimoQuery::create()->findPk($request->getSession()->get('SoColissimoDeliveryId')); if ($tmp_address === null) { throw new \ErrorException("Got an error with So Colissimo module. Please try again to checkout."); } $savecode = new OrderAddressSocolissimo(); $savecode->setId($event->getOrder()->getDeliveryOrderAddressId())->setCode(0)->setType($tmp_address->getType())->save(); $update = OrderAddressQuery::create()->findPK($event->getOrder()->getDeliveryOrderAddressId())->setCompany($tmp_address->getCompany())->setAddress1($tmp_address->getAddress1())->setAddress2($tmp_address->getAddress2())->setAddress3($tmp_address->getAddress3())->setZipcode($tmp_address->getZipcode())->setCity($tmp_address->getCity())->save(); } elseif ($request->getSession()->get('SoColissimoRdv') == 1) { $tmp_address = AddressSoColissimoQuery::create()->findPk($request->getSession()->get('SoColissimoDeliveryId')); if ($tmp_address === null) { throw new \ErrorException("Got an error with So Colissimo module. Please try again to checkout."); } $savecode = new OrderAddressSocolissimo(); $savecode->setId($event->getOrder()->getDeliveryOrderAddressId())->setCode(0)->setType($tmp_address->getType())->save(); $update = OrderAddressQuery::create()->findPK($event->getOrder()->getDeliveryOrderAddressId())->setCompany($tmp_address->getCompany())->setAddress1($tmp_address->getAddress1())->setAddress2($tmp_address->getAddress2())->setAddress3($tmp_address->getAddress3())->setZipcode($tmp_address->getZipcode())->setCity($tmp_address->getCity())->setPhone($tmp_address->getCellphone())->save(); } else { $tmp_address = AddressSoColissimoQuery::create()->findPk($request->getSession()->get('SoColissimoDeliveryId')); if ($tmp_address === null) { throw new \ErrorException("Got an error with So Colissimo module. Please try again to checkout."); } $savecode = new OrderAddressSocolissimo(); $savecode->setId($event->getOrder()->getDeliveryOrderAddressId())->setCode($tmp_address->getCode())->setType($tmp_address->getType())->save(); $update = OrderAddressQuery::create()->findPK($event->getOrder()->getDeliveryOrderAddressId())->setCompany($tmp_address->getCompany())->setAddress1($tmp_address->getAddress1())->setAddress2($tmp_address->getAddress2())->setAddress3($tmp_address->getAddress3())->setZipcode($tmp_address->getZipcode())->setCity($tmp_address->getCity())->save(); } } }