/** * Save the attribute combinations for the order from our cart item attribute combinations. * * @param OrderEvent $event * * @throws PropelException */ public function createOrderProductAttributeCombinations(OrderEvent $event) { $legacyCartItemAttributeCombinations = LegacyCartItemAttributeCombinationQuery::create()->findByCartItemId($event->getCartItemId()); // works with Thelia 2.2 if (method_exists($event, 'getId')) { $orderProductId = $event->getId(); } else { // Thelia 2.1 however does not provides the order product id in the event // Since the order contains potentially identical (for Thelia) cart items that are only differentiated // by the cart item attribute combinations that we are storing ourselves, we cannot use information // such as PSE id to cross reference the cart item we are given to the order product that was created from // it (as far as I can tell). // So we will ASSUME that the order product with the higher id is the one created from this cart item. // This is PROBABLY TRUE on a basic Thelia install with no modules messing with the cart and orders in a way // that create additional order products, BUT NOT IN GENERAL ! // This also assumes that ids are generated incrementally, which is NOT GUARANTEED (but true for MySQL // with default settings). // The creation date was previously used but is even less reliable. // FIXME: THIS IS NOT A SANE WAY TO DO THIS $orderProductId = OrderProductQuery::create()->orderById(Criteria::DESC)->findOne()->getId(); } $lang = $this->request->getSession()->getLang(); /** @var LegacyCartItemAttributeCombination $legacyCartItemAttributeCombination */ foreach ($legacyCartItemAttributeCombinations as $legacyCartItemAttributeCombination) { /** @var Attribute $attribute */ $attribute = I18n::forceI18nRetrieving($lang->getLocale(), 'Attribute', $legacyCartItemAttributeCombination->getAttributeId()); /** @var AttributeAv $attributeAv */ $attributeAv = I18n::forceI18nRetrieving($lang->getLocale(), 'AttributeAv', $legacyCartItemAttributeCombination->getAttributeAvId()); (new OrderProductAttributeCombination())->setOrderProductId($orderProductId)->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(); } }
/** * Send email to notify customer that files for virtual products are available * * @param OrderEvent $event * @throws \Exception */ public function sendEmail(OrderEvent $event) { $order = $event->getOrder(); // Be sure that we have a document to download $virtualProductCount = OrderProductQuery::create()->filterByOrderId($order->getId())->filterByVirtual(true)->filterByVirtualDocument(null, Criteria::NOT_EQUAL)->count(); if ($virtualProductCount > 0) { $customer = $order->getCustomer(); $this->mailer->sendEmailToCustomer('mail_virtualproduct', $customer, ['customer_id' => $customer->getId(), 'order_id' => $order->getId(), 'order_ref' => $order->getRef(), 'order_date' => $order->getCreatedAt(), 'update_date' => $order->getUpdatedAt()]); } else { Tlog::getInstance()->warning("Virtual product download message not sent to customer: there's nothing to downnload"); } }
public function orderTotalWeight($params, $template = null) { $totalWeight = 0; if (null != ($orderId = $this->getParam($params, "order_id", null))) { $orderProducts = OrderProductQuery::create()->filterByOrderId($orderId)->find(); /** @var \Thelia\Model\OrderProduct $orderProduct */ foreach ($orderProducts as $orderProduct) { $totalWeight += $orderProduct->getQuantity() * $orderProduct->getWeight(); } } return round($totalWeight, 2); }
public function buildModelCriteria() { $search = OrderProductQuery::create(); $search->joinOrderProductTax('opt', Criteria::LEFT_JOIN)->withColumn('SUM(`opt`.AMOUNT)', 'TOTAL_TAX')->withColumn('SUM(`opt`.PROMO_AMOUNT)', 'TOTAL_PROMO_TAX')->groupById(); $order = $this->getOrder(); $search->filterByOrderId($order, Criteria::EQUAL); $virtual = $this->getVirtual(); if ($virtual !== BooleanOrBothType::ANY) { if ($virtual) { $search->filterByVirtual(1, Criteria::EQUAL)->filterByVirtualDocument(null, Criteria::NOT_EQUAL); } else { $search->filterByVirtual(0); } } if (null !== $this->getId()) { $search->filterById($this->getId(), Criteria::IN); } $search->orderById(Criteria::ASC); return $search; }
public function buildModelCriteria() { $search = OrderProductQuery::create(); $search->joinOrderProductTax('opt', Criteria::LEFT_JOIN)->withColumn('SUM(`opt`.AMOUNT)', 'TOTAL_TAX')->withColumn('SUM(`opt`.PROMO_AMOUNT)', 'TOTAL_PROMO_TAX')->groupById(); // new join to get the product id if it exists $pseJoin = new Join(OrderProductTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductSaleElementsTableMap::ID, Criteria::LEFT_JOIN); $search->addJoinObject($pseJoin)->addAsColumn("product_id", ProductSaleElementsTableMap::PRODUCT_ID); $order = $this->getOrder(); $search->filterByOrderId($order, Criteria::EQUAL); $virtual = $this->getVirtual(); if ($virtual !== BooleanOrBothType::ANY) { if ($virtual) { $search->filterByVirtual(1, Criteria::EQUAL)->filterByVirtualDocument(null, Criteria::NOT_EQUAL); } else { $search->filterByVirtual(0); } } if (null !== $this->getId()) { $search->filterById($this->getId(), Criteria::IN); } $search->orderById(Criteria::ASC); return $search; }
/** * Check if the current order contains at less 1 virtual product with a file to download * * @return bool true if this order have at less 1 file to download, false otherwise. */ public function hasVirtualProduct() { $virtualProductCount = OrderProductQuery::create()->filterByOrderId($this->getId())->filterByVirtual(1, Criteria::EQUAL)->count(); return $virtualProductCount !== 0; }
/** * Removes this object from datastore and sets delete attribute. * * @param ConnectionInterface $con * @return void * @throws PropelException * @see OrderProduct::setDeleted() * @see OrderProduct::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(OrderProductTableMap::DATABASE_NAME); } $con->beginTransaction(); try { $deleteQuery = ChildOrderProductQuery::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 testCreate() { $validDeliveryAddress = AddressQuery::create()->findOneByCustomerId($this->customer->getId()); $validInvoiceAddress = AddressQuery::create()->filterById($validDeliveryAddress->getId(), Criteria::NOT_EQUAL)->findOneByCustomerId($this->customer->getId()); $deliveryModule = ModuleQuery::create()->filterByType(BaseModule::DELIVERY_MODULE_TYPE)->filterByActivate(1)->findOne(); if (null === $deliveryModule) { throw new \Exception('No Delivery Module fixture found'); } $paymentModule = ModuleQuery::create()->filterByType(BaseModule::PAYMENT_MODULE_TYPE)->filterByActivate(1)->findOne(); if (null === $paymentModule) { throw new \Exception('No Payment Module fixture found'); } /* define payment module in container */ $paymentModuleClass = $paymentModule->getFullNamespace(); $this->container->set(sprintf('module.%s', $paymentModule->getCode()), new $paymentModuleClass()); $this->orderEvent->getOrder()->setChoosenDeliveryAddress($validDeliveryAddress->getId()); $this->orderEvent->getOrder()->setChoosenInvoiceAddress($validInvoiceAddress->getId()); $this->orderEvent->getOrder()->setDeliveryModuleId($deliveryModule->getId()); $this->orderEvent->getOrder()->setPostage(20); $this->orderEvent->getOrder()->setPaymentModuleId($paymentModule->getId()); /* memorize current stocks */ $itemsStock = array(); foreach ($this->cartItems as $index => $cartItem) { $itemsStock[$index] = $cartItem->getProductSaleElements()->getQuantity(); } $this->orderAction->create($this->orderEvent); $placedOrder = $this->orderEvent->getPlacedOrder(); $this->assertNotNull($placedOrder); $this->assertNotNull($placedOrder->getId()); /* check customer */ $this->assertEquals($this->customer->getId(), $placedOrder->getCustomerId(), 'customer i does not match'); /* check delivery address */ $deliveryOrderAddress = $placedOrder->getOrderAddressRelatedByDeliveryOrderAddressId(); $this->assertEquals($validDeliveryAddress->getCustomerTitle()->getId(), $deliveryOrderAddress->getCustomerTitleId(), 'delivery address title does not match'); $this->assertEquals($validDeliveryAddress->getCompany(), $deliveryOrderAddress->getCompany(), 'delivery address company does not match'); $this->assertEquals($validDeliveryAddress->getFirstname(), $deliveryOrderAddress->getFirstname(), 'delivery address fistname does not match'); $this->assertEquals($validDeliveryAddress->getLastname(), $deliveryOrderAddress->getLastname(), 'delivery address lastname does not match'); $this->assertEquals($validDeliveryAddress->getAddress1(), $deliveryOrderAddress->getAddress1(), 'delivery address address1 does not match'); $this->assertEquals($validDeliveryAddress->getAddress2(), $deliveryOrderAddress->getAddress2(), 'delivery address address2 does not match'); $this->assertEquals($validDeliveryAddress->getAddress3(), $deliveryOrderAddress->getAddress3(), 'delivery address address3 does not match'); $this->assertEquals($validDeliveryAddress->getZipcode(), $deliveryOrderAddress->getZipcode(), 'delivery address zipcode does not match'); $this->assertEquals($validDeliveryAddress->getCity(), $deliveryOrderAddress->getCity(), 'delivery address city does not match'); $this->assertEquals($validDeliveryAddress->getPhone(), $deliveryOrderAddress->getPhone(), 'delivery address phone does not match'); $this->assertEquals($validDeliveryAddress->getCountryId(), $deliveryOrderAddress->getCountryId(), 'delivery address country does not match'); /* check invoice address */ $invoiceOrderAddress = $placedOrder->getOrderAddressRelatedByInvoiceOrderAddressId(); $this->assertEquals($validInvoiceAddress->getCustomerTitle()->getId(), $invoiceOrderAddress->getCustomerTitleId(), 'invoice address title does not match'); $this->assertEquals($validInvoiceAddress->getCompany(), $invoiceOrderAddress->getCompany(), 'invoice address company does not match'); $this->assertEquals($validInvoiceAddress->getFirstname(), $invoiceOrderAddress->getFirstname(), 'invoice address fistname does not match'); $this->assertEquals($validInvoiceAddress->getLastname(), $invoiceOrderAddress->getLastname(), 'invoice address lastname does not match'); $this->assertEquals($validInvoiceAddress->getAddress1(), $invoiceOrderAddress->getAddress1(), 'invoice address address1 does not match'); $this->assertEquals($validInvoiceAddress->getAddress2(), $invoiceOrderAddress->getAddress2(), 'invoice address address2 does not match'); $this->assertEquals($validInvoiceAddress->getAddress3(), $invoiceOrderAddress->getAddress3(), 'invoice address address3 does not match'); $this->assertEquals($validInvoiceAddress->getZipcode(), $invoiceOrderAddress->getZipcode(), 'invoice address zipcode does not match'); $this->assertEquals($validInvoiceAddress->getCity(), $invoiceOrderAddress->getCity(), 'invoice address city does not match'); $this->assertEquals($validInvoiceAddress->getPhone(), $invoiceOrderAddress->getPhone(), 'invoice address phone does not match'); $this->assertEquals($validInvoiceAddress->getCountryId(), $invoiceOrderAddress->getCountryId(), 'invoice address country does not match'); /* check currency */ $this->assertEquals($this->cart->getCurrencyId(), $placedOrder->getCurrencyId(), 'currency id does not match'); $this->assertEquals($this->cart->getCurrency()->getRate(), $placedOrder->getCurrencyRate(), 'currency rate does not match'); /* check delivery module */ $this->assertEquals(20, $placedOrder->getPostage(), 'postage does not match'); $this->assertEquals($deliveryModule->getId(), $placedOrder->getDeliveryModuleId(), 'delivery module does not match'); /* check payment module */ $this->assertEquals($paymentModule->getId(), $placedOrder->getPaymentModuleId(), 'payment module does not match'); /* check status */ $this->assertEquals(OrderStatus::CODE_NOT_PAID, $placedOrder->getOrderStatus()->getCode(), 'status does not match'); /* check lang */ $this->assertEquals($this->request->getSession()->getLang()->getId(), $placedOrder->getLangId(), 'lang does not match'); /* check ordered product */ foreach ($this->cartItems as $index => $cartItem) { $orderProduct = OrderProductQuery::create()->filterByOrderId($placedOrder->getId())->filterByProductRef($cartItem->getProduct()->getRef())->filterByProductSaleElementsRef($cartItem->getProductSaleElements()->getRef())->filterByQuantity($cartItem->getQuantity())->filterByPrice($cartItem->getPrice(), Criteria::LIKE)->filterByPromoPrice($cartItem->getPromoPrice(), Criteria::LIKE)->filterByWasNew($cartItem->getProductSaleElements()->getNewness())->filterByWasInPromo($cartItem->getPromo())->filterByWeight($cartItem->getProductSaleElements()->getWeight())->findOne(); $this->assertNotNull($orderProduct); /* check attribute combinations */ $this->assertEquals($cartItem->getProductSaleElements()->getAttributeCombinations()->count(), $orderProduct->getOrderProductAttributeCombinations()->count()); if ($orderProduct->getVirtual()) { /* check same stock*/ $this->assertEquals($itemsStock[$index], $cartItem->getProductSaleElements()->getQuantity()); } else { /* check stock decrease */ $this->assertEquals($itemsStock[$index] - $orderProduct->getQuantity(), $cartItem->getProductSaleElements()->getQuantity()); } /* check tax */ $orderProductTaxList = $orderProduct->getOrderProductTaxes(); foreach ($cartItem->getProduct()->getTaxRule()->getTaxDetail($cartItem->getProduct(), $validDeliveryAddress->getCountry(), $cartItem->getPrice(), $cartItem->getPromoPrice()) as $index => $tax) { $orderProductTax = $orderProductTaxList[$index]; $this->assertEquals($tax->getAmount(), $orderProductTax->getAmount()); $this->assertEquals($tax->getPromoAmount(), $orderProductTax->getPromoAmount()); } } return $placedOrder; }
/** * Returns the number of related OrderProduct objects. * * @param Criteria $criteria * @param boolean $distinct * @param ConnectionInterface $con * @return int Count of related OrderProduct objects. * @throws PropelException */ public function countOrderProducts(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null) { $partial = $this->collOrderProductsPartial && !$this->isNew(); if (null === $this->collOrderProducts || null !== $criteria || $partial) { if ($this->isNew() && null === $this->collOrderProducts) { return 0; } if ($partial && !$criteria) { return count($this->getOrderProducts()); } $query = ChildOrderProductQuery::create(null, $criteria); if ($distinct) { $query->distinct(); } return $query->filterByOrder($this)->count($con); } return count($this->collOrderProducts); }
public function downloadVirtualProduct($order_product_id) { if (null !== ($orderProduct = OrderProductQuery::create()->findPk($order_product_id))) { $order = $orderProduct->getOrder(); if ($order->isPaid(false)) { // check customer $this->checkOrderCustomer($order->getId()); $virtualProductEvent = new VirtualProductOrderDownloadResponseEvent($orderProduct); $this->getDispatcher()->dispatch(TheliaEvents::VIRTUAL_PRODUCT_ORDER_DOWNLOAD_RESPONSE, $virtualProductEvent); $response = $virtualProductEvent->getResponse(); if (!$response instanceof BaseResponse) { throw new \RuntimeException('A Response must be added in the event TheliaEvents::VIRTUAL_PRODUCT_ORDER_DOWNLOAD_RESPONSE'); } return $response; } } throw new AccessDeniedHttpException(); }
protected function createExpedition() { $orderIdList = $this->getRequest()->request->get("order-selection"); $orderAllInOne = $this->getRequest()->request->get("order-all-in-one"); $orderPackage = $this->getRequest()->request->get("order-package"); $orderProductPackage = $this->getRequest()->request->get("order-product-package"); if (!is_array($orderIdList)) { $orderIdList = [$orderIdList]; } $shippingDate = $this->getRequest()->request->get("create-date", null); $message = null; try { foreach ($orderIdList as $orderId) { $order = OrderQuery::create()->findPk($orderId); $orderProductIdList = $this->getRequest()->request->get("order-product-selection", null); if (null === $order) { throw new \InvalidArgumentException("The order you want to create expedition does not exist"); } $event = new TNTFranceCreateExpeditionEvent(); $order->clearOrderProducts(); $order->setOrderProducts(OrderProductQuery::create()->findPks($orderProductIdList[$orderId])); //Order Package if (array_key_exists($orderId, $orderPackage)) { $order->setVirtualColumn(TNTFranceCreateExpeditionEvent::PACKAGE, $orderPackage[$orderId]); } if (array_key_exists($orderId, $orderAllInOne) && $orderAllInOne[$orderId] == 0) { $event->setAllInOne(false); foreach ($order->getOrderProducts() as $orderProduct) { if (array_key_exists($orderProduct->getId(), $orderProductPackage)) { $orderProduct->setVirtualColumn(TNTFranceCreateExpeditionEvent::PACKAGE, $orderProductPackage[$orderProduct->getId()]); } } } $event->setShippingDate($shippingDate)->setOrder($order); $this->dispatch(TNTFranceEvents::TNT_FRANCE_CREATE_EXPEDITION, $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 OrderProduct or Criteria object. * * @param mixed $criteria Criteria or OrderProduct 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(OrderProductTableMap::DATABASE_NAME); } if ($criteria instanceof Criteria) { $criteria = clone $criteria; // rename for clarity } else { $criteria = $criteria->buildCriteria(); // build Criteria from OrderProduct object } if ($criteria->containsKey(OrderProductTableMap::ID) && $criteria->keyContainsValue(OrderProductTableMap::ID)) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . OrderProductTableMap::ID . ')'); } // Set the correct dbName $query = OrderProductQuery::create()->mergeWith($criteria); try { // use transaction because $criteria could contain info // for more than one table (I guess, conceivably) $con->beginTransaction(); $pk = $query->doInsert($con); $con->commit(); } catch (PropelException $e) { $con->rollBack(); throw $e; } return $pk; }
public function testQuery() { $container = new Container(); new Translator($container); $handler = new OrderExport($container); $lang = Lang::getDefaultLanguage(); $locale = $lang->getLocale(); $data = $handler->buildData($lang)->getData(); $ordersProductQuery = OrderProductQuery::create(); $orders = OrderQuery::create()->find(); $count = $ordersProductQuery->count(); $this->assertEquals(count($data), $count); /** * For the rest of the test, 50 orders are much enough */ if ($count > 50) { $count = 50; } $current = 0; for ($i = 0; $i < $count; ++$current) { $row = $data[$i]; /** @var \Thelia\Model\Order $order */ $order = $orders->get($current); $this->assertEquals($ref = $order->getRef(), $row["ref"]); $this->assertEquals($order->getCustomer()->getRef(), $row["customer_ref"]); $coupons = OrderCouponQuery::create()->filterByOrder($order)->select(OrderCouponTableMap::TITLE)->find()->toArray(); $coupons = implode(",", $coupons); $this->assertTrue(empty($coupons) ? empty($row["coupons"]) : $coupons === $row["coupons"]); $this->assertEquals($order->getCreatedAt()->format($lang->getDatetimeFormat()), $row["date"]); $this->assertEquals($order->getCurrency()->getCode(), $row["currency"]); $this->assertEquals($order->getCustomer()->getRef(), $row["customer_ref"]); $this->assertEquals($order->getOrderStatus()->setLocale($locale)->getTitle(), $row["status"]); $this->assertEquals($order->getDeliveryRef(), $row["delivery_ref"]); $this->assertEquals($order->getModuleRelatedByDeliveryModuleId()->getCode(), $row["delivery_module"]); $this->assertEquals($order->getInvoiceRef(), $row["invoice_ref"]); $this->assertEquals($order->getModuleRelatedByPaymentModuleId()->getCode(), $row["payment_module"]); $this->assertEquals($order->getTotalAmount($tax, false, false), $row["total_including_taxes"]); $this->assertEquals($order->getTotalAmount($tax, false, true), $row["total_with_discount"]); $this->assertEquals($order->getTotalAmount($tax, true, true), $row["total_discount_and_postage"]); $invoiceAddress = $order->getOrderAddressRelatedByInvoiceOrderAddressId(); $deliveryAddress = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); $addresses = ["delivery" => $deliveryAddress, "invoice" => $invoiceAddress]; /** @var \Thelia\Model\OrderAddress $address */ foreach ($addresses as $prefix => $address) { $this->assertEquals($address->getCustomerTitle()->setLocale($locale)->getShort(), $row[$prefix . "_title"]); $this->assertEquals($address->getAddress1(), $row[$prefix . "_address1"]); $this->assertEquals($address->getAddress2(), $row[$prefix . "_address2"]); $this->assertEquals($address->getAddress3(), $row[$prefix . "_address3"]); $this->assertEquals($address->getCity(), $row[$prefix . "_city"]); $this->assertEquals($address->getZipcode(), $row[$prefix . "_zip_code"]); $this->assertEquals($address->getCompany(), $row[$prefix . "_company"]); $this->assertEquals($address->getFirstname(), $row[$prefix . "_first_name"]); $this->assertEquals($address->getLastname(), $row[$prefix . "_last_name"]); $this->assertEquals($address->getCountry()->setLocale($locale)->getTitle(), $row[$prefix . "_country"]); $this->assertEquals($address->getPhone(), $row[$prefix . "_phone"]); } while ($data[$i]["ref"] === $ref) { /** @var \Thelia\Model\OrderProduct $product */ $product = OrderProductQuery::create()->filterByTitle($data[$i]["product_title"])->filterByTaxRuleTitle($data[$i]["tax_title"])->filterByWasInPromo($data[$i]["was_in_promo"])->_if((bool) (int) $data[$i]["was_in_promo"])->filterByPromoPrice($data[$i]["price"])->_else()->filterByPrice($data[$i]["price"])->_endif()->filterByQuantity($data[$i]["quantity"])->findOne(); $this->assertNotNull($product); $sum = 0; foreach ($product->getOrderProductTaxes() as $tax) { $sum += $product->getWasInPromo() ? $tax->getPromoAmount() : $tax->getAmount(); } $this->assertEquals($sum, $data[$i++]["tax_amount"]); } } }
/** * Get the associated ChildOrderProduct object * * @param ConnectionInterface $con Optional Connection object. * @return ChildOrderProduct The associated ChildOrderProduct object. * @throws PropelException */ public function getOrderProduct(ConnectionInterface $con = null) { if ($this->aOrderProduct === null && $this->order_product_id !== null) { $this->aOrderProduct = ChildOrderProductQuery::create()->findPk($this->order_product_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->aOrderProduct->addOrderProductAttributeCombinations($this); */ } return $this->aOrderProduct; }
public function downloadVirtualProduct($order_product_id) { if (null !== ($orderProduct = OrderProductQuery::create()->findPk($order_product_id))) { $order = $orderProduct->getOrder(); if ($order->isPaid()) { // check customer $this->checkOrderCustomer($order->getId()); if ($orderProduct->getVirtualDocument()) { // try to get the file $path = THELIA_ROOT . ConfigQuery::read('documents_library_path', 'local/media/documents') . DS . "product" . DS . $orderProduct->getVirtualDocument(); if (!is_file($path) || !is_readable($path)) { throw new \ErrorException(Translator::getInstance()->trans("The file [%file] does not exist", ["%file" => $order_product_id])); } $data = file_get_contents($path); $mime = MimeTypeGuesser::getInstance()->guess($path); return new Response($data, 200, ["Content-Type" => $mime]); } } } throw new AccessDeniedHttpException(); }
public function requestCustomerDemand(CommentCheckOrderEvent $event) { $config = \Comment\Comment::getConfig(); $nbDays = $config["request_customer_ttl"]; if (0 !== $nbDays) { $endDate = new DateTime('NOW'); $endDate->setTime(0, 0, 0); $endDate->sub(new DateInterval('P' . $nbDays . 'D')); $startDate = clone $endDate; $startDate->sub(new DateInterval('P1D')); $pseJoin = new Join(OrderProductTableMap::PRODUCT_SALE_ELEMENTS_ID, ProductSaleElementsTableMap::ID, Criteria::INNER_JOIN); $products = OrderProductQuery::create()->useOrderQuery()->filterByInvoiceDate($startDate, Criteria::GREATER_EQUAL)->filterByInvoiceDate($endDate, Criteria::LESS_THAN)->addAsColumn('customerId', OrderTableMap::CUSTOMER_ID)->addAsColumn('orderId', OrderTableMap::ID)->endUse()->addJoinObject($pseJoin)->addAsColumn('pseId', OrderProductTableMap::PRODUCT_SALE_ELEMENTS_ID)->addAsColumn('productId', ProductSaleElementsTableMap::PRODUCT_ID)->select(['customerId', 'orderId', 'pseId', 'productId'])->find()->toArray(); if (empty($products)) { return; } $customerProducts = array_reduce($products, function ($result, $item) { if (!array_key_exists($item['customerId'], $result)) { $result[$item['customerId']] = []; } if (!in_array($item['productId'], $result[$item['customerId']])) { $result[$item['customerId']][] = $item['productId']; } return $result; }, []); $customerIds = array_keys($customerProducts); // check if comments already exists $comments = CommentQuery::create()->filterByCustomerId($customerIds)->filterByRef(MetaData::PRODUCT_KEY)->addAsColumn('customerId', CommentTableMap::CUSTOMER_ID)->addAsColumn('productId', CommentTableMap::REF_ID)->select(['customerId', 'productId'])->find()->toArray(); $customerComments = array_reduce($comments, function ($result, $item) { if (!array_key_exists($item['customerId'], $result)) { $result[$item['customerId']] = []; } $result[$item['customerId']][] = $item['productId']; return $result; }, []); foreach ($customerIds as $customerId) { $send = false; if (!array_key_exists($customerId, $customerComments)) { $send = true; } else { $noCommentsPosted = array_intersect($customerComments[$customerId], $customerProducts[$customerId]); if (empty($noCommentsPosted)) { $send = true; } } if ($send) { try { $this->sendCommentRequestCustomerMail($customerId, $customerProducts[$customerId]); } catch (\Exception $ex) { Tlog::getInstance()->error($ex->getMessage()); } } } } }