<?php
namespace App\Controller\Order;
use App\Entity\Addressing\Country;
use App\Entity\Addressing\County;
use App\Entity\Customer\Customer;
use App\Entity\Order\Order;
use App\Entity\Partner\Partner;
use App\Entity\Shipping\Shipment;
use App\Entity\VignetteInvoice\VignetteInvoice;
use App\Entity\VignettePaymentMethod\VignettePaymentMethod;
use App\Manager\Order\OrderManager;
use App\Model\AddressModel;
use App\Model\FilterOrderModel;
use App\Model\OrderModel;
use App\Model\ShopUserModel;
use App\Model\VignetteInvoiceModel;
use App\Service\CustomerService;
use App\Service\ExportService;
use App\Service\InvoiceApiService;
use App\Service\InvoiceService;
use App\Service\Order\AdminGridService;
use App\Service\OrderService;
use App\Service\SystemService;
use App\Service\VignetteApiService;
use Doctrine\Common\Persistence\ObjectManager;
use FOS\RestBundle\View\View;
use \Sylius\Bundle\CoreBundle\Controller\OrderController as BaseOrderController;
use Sylius\Bundle\ResourceBundle\Controller\AuthorizationCheckerInterface;
use Sylius\Bundle\ResourceBundle\Controller\EventDispatcherInterface;
use Sylius\Bundle\ResourceBundle\Controller\FlashHelperInterface;
use Sylius\Bundle\ResourceBundle\Controller\NewResourceFactoryInterface;
use Sylius\Bundle\ResourceBundle\Controller\RedirectHandlerInterface;
use Sylius\Bundle\ResourceBundle\Controller\RequestConfigurationFactoryInterface;
use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface;
use Sylius\Bundle\ResourceBundle\Controller\ResourceFormFactoryInterface;
use Sylius\Bundle\ResourceBundle\Controller\ResourcesCollectionProviderInterface;
use Sylius\Bundle\ResourceBundle\Controller\ResourceUpdateHandlerInterface;
use Sylius\Bundle\ResourceBundle\Controller\SingleResourceProviderInterface;
use Sylius\Bundle\ResourceBundle\Controller\StateMachineInterface;
use Sylius\Bundle\ResourceBundle\Controller\ViewHandlerInterface;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Sylius\Component\Core\OrderPaymentStates;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Exception\UpdateHandlingException;
use Sylius\Component\Resource\Factory\FactoryInterface;
use Sylius\Component\Resource\Metadata\MetadataInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Resource\ResourceActions;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
class OrderController extends BaseOrderController
{
public function __construct(MetadataInterface $metadata,
RequestConfigurationFactoryInterface $requestConfigurationFactory,
ViewHandlerInterface $viewHandler, RepositoryInterface $repository,
FactoryInterface $factory, NewResourceFactoryInterface $newResourceFactory,
ObjectManager $manager, SingleResourceProviderInterface $singleResourceProvider,
ResourcesCollectionProviderInterface $resourcesFinder,
ResourceFormFactoryInterface $resourceFormFactory,
RedirectHandlerInterface $redirectHandler,
FlashHelperInterface $flashHelper,
AuthorizationCheckerInterface $authorizationChecker,
EventDispatcherInterface $eventDispatcher,
StateMachineInterface $stateMachine,
ResourceUpdateHandlerInterface $resourceUpdateHandler,
ResourceDeleteHandlerInterface $resourceDeleteHandler)
{
parent::__construct($metadata, $requestConfigurationFactory, $viewHandler, $repository, $factory, $newResourceFactory, $manager, $singleResourceProvider, $resourcesFinder, $resourceFormFactory, $redirectHandler, $flashHelper, $authorizationChecker, $eventDispatcher, $stateMachine, $resourceUpdateHandler, $resourceDeleteHandler);
}
public function showAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::SHOW);
$resource = $this->findOr404($configuration);
$this->eventDispatcher->dispatch(ResourceActions::SHOW, $configuration, $resource);
$view = View::create($resource);
if ($configuration->isHtmlRequest()) {
$view
->setTemplate($configuration->getTemplate(ResourceActions::SHOW . '.html'))
->setTemplateVar($this->metadata->getName())
->setData([
'configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
$this->metadata->getName() => $resource,
])
;
}
return $this->viewHandler->handle($configuration, $view);
}
public function changeOrderPaymentStatus(Request $request)
{
$message = 'Fail';
$orderId = $request->get('orderId');
$paymentStatus = $request->get('orderPaymentStatusSelected');
if ($orderId && $paymentStatus) {
$order = $this->getDoctrine()->getRepository(Order::class)->find($orderId);
if ($order) {
$orderModel = new OrderModel($this->getDoctrine()->getManager(), $this->container);
$orderModel->updatePaymentStatus($order, $paymentStatus);
if ($paymentStatus == OrderPaymentStates::STATE_PAID) {
$ipnService = $this->container->get('app.service.payment.ipn');
$ipnService->issueManually($order);
$message = 'Status updatat cu succes. Se incearca emiterea produselor';
} else {
$message = 'Succes';
}
}
}
return new Response(json_encode($message));
}
public function changeCustomer(Request $request)
{
$orderId = $request->request->get('order_id');
$customerId = $request->request->get('customer_id');
if (!$orderId || !$customerId) {
return new Response('error');
}
$order = $this->getDoctrine()->getRepository(Order::class)->find($orderId);
$customer = $this->getDoctrine()->getRepository(Customer::class)->find($customerId);
OrderService::changeOrderCustomer($this->getDoctrine()->getManager(), $order, $customer);
return new Response('ok');
}
public function getAvailableCustomers(Request $request)
{
$searchTerm = $request->request->has('search') ? $request->request->get('search') : null;
$order = $this->getDoctrine()->getRepository(Customer::class)->createQueryBuilder('o')->where('o.email LIKE :search')->orWhere('o.firstName LIKE :search')->orWhere('o.lastName LIKE :search')->setParameter(':search', '%'. $searchTerm .'%')->getQuery()->getArrayResult();
return new Response(json_encode($order));
}
public function exportOrderBySmsView()
{
return $this->render('@templates/AdminCustom/Order/export-order-sms.html.twig');
}
public function exportShipment(Request $request)
{
$shipmentId = $request->get('shipment_id');
if ($shipmentId) {
$shipment = $this->getDoctrine()->getRepository(Shipment::class)->find($shipmentId);
if ($shipment) {
$exportService = new ExportService($this->repository ,$request, $this->manager);
$exportService->exportShipment($shipment);
}
}
echo "<script>window.close();</script>";
return new Response('success');
}
public function exportShipments(Request $request)
{
$repository = $this->getDoctrine()->getRepository(Shipment::class);
$exportService = new ExportService($repository, $request, $this->manager);
$shipments = $exportService->getData();
$exportService->exportShipments($shipments);
echo "<script>window.close();</script>";
return new Response('success');
}
public function exportOrderBySmsAction(Request $request)
{
$params = $request->request->all();
$exportService = new ExportService($this->repository ,$request, $this->manager);
$result = $exportService->exportOrdersBySms($params);
if ($result) {
$this->addFlash('export-order-sms', 'success');
} else {
$this->addFlash('export-order-sms', 'fail');
}
return $this->redirectToRoute('app_admin_export_order_by_sms_view');
}
public function updateAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::UPDATE);
$resource = $this->findOr404($configuration);
$form = $this->resourceFormFactory->create($configuration, $resource);
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true) && $form->handleRequest($request)->isValid()) {
$resource = $form->getData();
/** @var ResourceControllerEvent $event */
$event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
$eventResponse = $event->getResponse();
if (null !== $eventResponse) {
return $eventResponse;
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
try {
$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
} catch (UpdateHandlingException $exception) {
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle(
$configuration,
View::create($form, $exception->getApiResponseCode())
);
}
$this->flashHelper->addErrorFlash($configuration, $exception->getFlash());
return $this->redirectHandler->redirectToReferer($configuration);
}
if ($configuration->isHtmlRequest()) {
$this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
}
$postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
if (!$configuration->isHtmlRequest()) {
$view = $configuration->getParameters()->get('return_content', false) ? View::create($resource, Response::HTTP_OK) : View::create(null, Response::HTTP_NO_CONTENT);
return $this->viewHandler->handle($configuration, $view);
}
$postEventResponse = $postEvent->getResponse();
if (null !== $postEventResponse) {
return $postEventResponse;
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($form, Response::HTTP_BAD_REQUEST));
}
$initializeEvent = $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE, $configuration, $resource);
$initializeEventResponse = $initializeEvent->getResponse();
if (null !== $initializeEventResponse) {
return $initializeEventResponse;
}
$data = null;
$country = null;
if ($resource instanceof OrderInterface) {
$data = AddressModel::getAddressData($resource->getBillingAddress(), $this->getDoctrine()->getManager());
$country = $this->getDoctrine()->getRepository(Country::class)->findOneBy(array('code' => $resource->getBillingAddress()->getCountryCode()));
}
$view = View::create()
->setData([
'configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
$this->metadata->getName() => $resource,
'form' => $form->createView(),
'data' => $data,
'countries' => $this->getDoctrine()->getRepository(Country::class)->findAll(),
'counties' => $this->getDoctrine()->getRepository(County::class)->findAllCountiesByCountry($country),
])
->setTemplate($configuration->getTemplate(ResourceActions::UPDATE . '.html'))
;
return $this->viewHandler->handle($configuration, $view);
}
public function indexAction(Request $request): Response
{
$sendInvoiceStatus = $request->get('sendInvoiceStatus');
$orderId = $request->get('orderId');
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::INDEX);
$resources = $this->resourcesCollectionProvider->get($configuration, $this->repository);
$this->eventDispatcher->dispatchMultiple(ResourceActions::INDEX, $configuration, $resources);
$view = View::create($resources);
if ($configuration->isHtmlRequest()) {
$view
->setTemplate($configuration->getTemplate(ResourceActions::INDEX . '.html'))
->setTemplateVar($this->metadata->getPluralName())
->setData([
'configuration' => $configuration,
'metadata' => $this->metadata,
'resources' => $resources,
'orderId' => $orderId,
'sendInvoiceStatus' => $sendInvoiceStatus,
$this->metadata->getPluralName() => $resources,
]);
}
return $this->viewHandler->handle($configuration, $view);
}
public function shopIndexAction(Request $request): Response
{
if (!CustomerService::retrieveCustomerFromShopUser($this->getUser())) {
return $this->redirectToRoute('app_shop_old_homepage');
}
$paymentMethods = array();
$allPaymentMethods = $this->getDoctrine()->getRepository(VignettePaymentMethod::class)->findAll();
foreach ($allPaymentMethods as $paymentMethod) {
$paymentMethods[$paymentMethod->getId()] = $paymentMethod->getName();
}
return $this->render('@templates/Account/Order/list.html.twig',
[
'paymentMethods' => $paymentMethods,
'states' => OrderManager::getAllOrderStates(),
'paymentStates' => OrderManager::getAllOrderPaymentStates()
]);
}
public function retrieveShopData(Request $request)
{
$customer = CustomerService::retrieveCustomerFromShopUser($this->getUser());
$adminGridService = $this->container->get('app.service.order.shop_grid');
if ($customer) {
return new Response(json_encode($adminGridService->retrieveOrderGridData($customer)));
} else {
return $this->redirectToRoute('sylius_shop_homepage');
}
}
public function retrieveData(Request $request): JsonResponse
{
$partnerId = SystemService::retrievePartnerId($this->getUser());
$userId = SystemService::retrieveUserId($this->getUser());
/** @var AdminGridService $adminGridService */
$adminGridService = $this->container->get('app.service.order.admin_grid');
return new JsonResponse($adminGridService->retrieveOrderGridData($partnerId, $userId));
}
public function exportWithDateRanges(Request $request): RedirectResponse
{
$adminGridService = $this->container->get('app.service.order.admin_grid');
$from = $request->get('from');
$to = $request->get('to');
if ($data = $adminGridService->retrieveAllOrderWithDateRanges($from, $to)) {
ExportService::exportArray($data);
} else {
$this->addFlash('error', 'A intervenit o eroare. Verificati intervalul de date selectat.');
}
return $this->redirectToRoute('sylius_admin_order_index');
}
public function retrieveProducts(Request $request)
{
$order = $this->getOrderRepository()->find($request->get('id'));
return new Response(json_encode(OrderService::retrieveProductsForGridOrder($order)));
}
public function filterOrders(Request $request)
{
$result = json_encode('fail');
$exportService = new ExportService($this->repository, $request, $this->manager);
$orders = $exportService->getDataForExportOrders($request->request->all());
if ($orders) {
$result = $exportService->exportOrdersJs($orders);
}
return new Response(json_encode($result));
}
public function exportAction(Request $request)
{
$exportService = new ExportService($this->repository, $request, $this->manager);
$orders = $exportService->getData();
if ($orders && !empty($orders)) {
$exportService->exportOrders($orders);
}
echo "<script>window.close();</script>";
return new Response('success');
}
/**
* @param Request $request
* @return Response
*/
public function exportOrderAction(Request $request)
{
$filterOderModel = new FilterOrderModel($this->manager, $this);
$response = new Response('success');
$orders = $filterOderModel->filterOrders($request->request->all());
$exportService = new ExportService($this->repository, $request, $this->manager);
if ($orders) {
$exportService->exportOrdersWithSqlData($orders);
} else {
$response = new Response('fail');
}
return $response;
}
public function exportOpOrder(Request $request)
{
$orderId = $request->get('orderId');
$exportService = new ExportService($this->repository, $request, $this->getDoctrine()->getManager());
$order = $this->getDoctrine()->getRepository(Order::class)->find($orderId);
if ($order) {
$exportService->exportOpOrder($order);
}
echo "<script>window.close();</script>";
return new Response('success');
}
public function cancelAction(Request $request): Response
{
$orderId = $request->get('orderId');
if (ShopUserModel::checkIfUserIsAdmin($this->getUser(), $this->getDoctrine()->getManager())) {
$order = $this->getDoctrine()->getRepository(Order::class)->find($orderId);
if (OrderModel::checkIfOrderCanBeCanceled($order)) {
OrderModel::cancelOrder($order, $this->getDoctrine()->getManager());
$this->addFlash('success', 'Comanda anulata cu succes');
}
} else {
$this->addFlash('error', 'A intervenit o eroare');
}
return $this->redirectToRoute('sylius_admin_order_show', [
'id' => $orderId
]);
}
public function showDetailsModal(Request $request)
{
$order = $this->getOrderRepository()->find($request->get('orderId'));
$orderData = OrderService::retrieveProductsForGridOrder($order);
$render = $this->get('twig')->render('@templates/Account/Order/Modal/_order_details.html.twig', ['orderData' => $orderData]);
return new Response($render);
}
public function partnerIndexAction(Request $request)
{
$partnerId = SystemService::retrievePartnerId($this->getUser());
$userId = SystemService::retrieveUserId($this->getUser());
$paymentMethods = array();
$allPaymentMethods = $this->getDoctrine()->getRepository(VignettePaymentMethod::class)->findAll();
foreach ($allPaymentMethods as $paymentMethod) {
$paymentMethods[$paymentMethod->getId()] = $paymentMethod->getName();
}
return $this->render('@templates/AdminCustom/Grid/Order/index.html.twig',
[
'paymentMethods' => $paymentMethods,
'states' => OrderManager::getAllOrderStates(),
'paymentStates' => OrderManager::getAllOrderPaymentStates(),
'partnerId' => $partnerId,
'userId' => $userId,
]);
}
public function checkIframeOrderItemsStatus(Request $request): Response
{
$token = $request->get('token');
$orderId = $request->get('ext_order_id');
$partner = $this->getDoctrine()->getRepository(Partner::class)->findOneBy(array('publicToken' => $token));
$order = $this->getOrderRepository()->find($orderId);
if (!$order || !$order->hasPartner()) {
return new JsonResponse([
'message' => 'Invalid order id',
'code' => 403
]);
} elseif (!$partner || !$partner->getId() == $order->getPartner()->getId()) {
return new JsonResponse([
'message' => 'Invalid token or order partner missmatch',
'code' => 402
]);
} else {
return new JsonResponse(OrderService::retrieveProductsStatusByOrder($order, $this->container->get('router')));
}
}
}