<?php
namespace App\Application\Controller;
use App\Admin\Document\Counterparty;
use App\Admin\Document\Draft;
use App\Admin\Document\Embedded\DraftItem;
use App\Admin\Document\Product;
use App\Admin\Document\PromoCode;
use App\Admin\Document\Supplier;
use App\Application\Cart\Cart;
use AvenueAdminBundle\Util\DateUtil;
use AvenueAdminBundle\Util\NumberUtil;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use \Symfony\Component\Routing\Annotation\Route;
class CartController extends AbstractController
{
/**
* @Route("/cart", name="cart")
*/
public function index(Request $request, Cart $cart): Response
{
return $this->render(
'application/cart/index.html.twig', $this->getCartParams($cart)
);
}
private function getCartParams(Cart $cart) {
$relatedProducts = [];
foreach ($cart->getItems() as $cartItem) {
foreach ($cartItem->product->getActiveProducts() as $product) {
if (!$cart->has($product->getId())) {
$relatedProducts[$product->getId()] = $product;
}
}
}
return ['relatedProducts' => array_values($relatedProducts)];
}
/**
* @Route("/cart-add-ajax", name="cart-add-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function add(Request $request, Cart $cart)
{
$id = $request->get('id');
$this->checkProduct($id);
$count = $cart->add($id, $request->get('count'));
return new JsonResponse([
'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
'count' => $count
]);
}
/**
* @Route("/compare-ajax", name="compare-ajax")
*/
public function compareAjax(Request $request, Cart $cart)
{
$id = $request->get('id');
$this->checkProduct($id);
$cart->addInCompareList($id);
return new JsonResponse(
[
'html' => $this->renderView('application/partial/compare.html.twig'),
]
);
}
private function checkProduct($id) {
/**
* @var Product $product
*/
$product = $this->getDocumentRepository(Product::class)->find($id);
if (!$product || !$product->getActive()) {
throw $this->createNotFoundException("Product with id {$id} does not exist or not active");
}
}
/**
* @Route("/cart-put-ajax", name="cart-put-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function put(Request $request, Cart $cart)
{
$cart->put($request->get('id'), $request->get('count'));
return new JsonResponse([
'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
'itemsHtml' => $this->renderView('application/cart/items.html.twig', $this->getCartParams($cart)),
]);
}
/**
* @Route("/cart-delete-ajax", name="cart-delete-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function delete(Request $request, Cart $cart)
{
$cart->remove($request->get('id'));
return new JsonResponse([
'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
'itemsHtml' => $this->renderView('application/cart/items.html.twig', $this->getCartParams($cart)),
]);
}
/**
* @Route("/cart-clear-ajax", name="cart-clear-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function clear(Request $request, Cart $cart)
{
$cart->clear();
return new JsonResponse([
'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
'itemsHtml' => $this->renderView('application/cart/items.html.twig'),
]);
}
/**
* @Route("/cart-load-retail-ajax", name="cart-load-retail-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function loadRetail(Request $request, Cart $cart)
{
$user = $this->getLoggedInUser();
if ($user) {
$cart->loadRetail($user);
}
return new JsonResponse([
'cartHtml' => $this->renderView('application/partial/cart.html.twig'),
'itemsHtml' => $this->renderView('application/cart/items.html.twig', $this->getCartParams($cart)),
]);
}
/**
* @Route("/draft-save-ajax", name="draft-save-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function draftSave(Request $request, Cart $cart)
{
$user = $this->getLoggedInUser();
$draft = new Draft();
$this->getDocumentManager()->persist($draft);
$draft->setUserAccount($user);
$draft->setCounterparty($cart->getCounterparty());
$items = [];
foreach ($cart->getItems() as $cartItem) {
$item = new DraftItem();
$item->setProduct($cartItem->product);
$item->setQuantity($cartItem->quantity);
$item->setCounterparty($draft->getCounterparty());
$items[] = $item;
}
$draft->setItems($items);
$this->getDocumentManager()->flush();
return new JsonResponse();
}
/**
* @Route("/cart-set-counterparty-ajax", name="cart-set-counterparty-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function setCounterpartyAjax(Request $request, Cart $cart)
{
$user = $this->getLoggedInUser();
if ($user) {
$id = $request->get('id');
if ($id) {
$counterparty = $this->getDocumentManager()->getRepository(Counterparty::class)->findOneBy([
'_id' => $id,
'client' => $user->getClient()->getId()
]);
if (!$counterparty) {
throw new \Exception('no Counterparty ' . $id . ' for client ' . $user->getClient()->getId());
}
} else {
$counterparty = null;
}
$user->setCartItemsByCounterparty($cart->getCounterpartyId(), $cart->getSessionItems());
$this->getDocumentManager()->flush();
$cart->setCounterparty($counterparty, $user->getCartItemsByCounterparty($id));
}
return new JsonResponse();
}
/**
* @Route("/clear-promo-ajax", name="clear-promo-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function clearPromo(Request $request, Cart $cart)
{
$cart->clearPromoCode();
return new JsonResponse();
}
/**
* @Route("/apply-promo-ajax", name="apply-promo-ajax")
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function applyPromoAjax(Request $request, Cart $cart)
{
$success = false;
$code = trim($request->get('promo'));
if ($code && $request->isMethod(Request::METHOD_POST)) {
$code = mb_ereg_replace('[^\d]', '', $code);
if ($code) {
if (strlen($code) == 11 && substr($code, 0, 1) == '7') {
$code = '8' . substr($code, 1);
}
/**
* @var PromoCode $promoCode
*/
$promoCode = $this->getDocumentRepository(PromoCode::class)->findOneBy(['code' => $code]);
if ($promoCode) {
if ($cart->setPromoCode($promoCode)) {
$success = true;
}
}
}
}
return new JsonResponse(['success' => $success]);
}
/**
* @Route("/cart/proposal", name="cart-proposal")
*/
public function proposal(Request $request, Cart $cart) {
if (!$this->getLoggedInUser()) {
return $this->redirectToRoute('login');
}
$type = $request->get('type');
$html = $this->renderView(
'application/pdf/order.html.twig', [
'supplier' => $this->getDocumentRepository(Supplier::class)->findOneBy(['internalCode' => $type]),
'user' => $this->getLoggedInUser(),
'date' => new \DateTime(),
]
);
$this->printPdf('Заказ', $html);
}
/**
* @Route("/cart/proposal-excel", name="cart-proposal-excel")
*/
public function proposalExcel(Request $request, Cart $cart) {
$user = $this->getLoggedInUser();
if (!$user) {
return $this->redirectToRoute('login');
}
/**
* @var Supplier $supplier
*/
$supplier = $this->getDocumentRepository(Supplier::class)->findOneBy(['internalCode' => $type]);
$filePath = tempnam(sys_get_temp_dir(), 'AvenueAdminExport');
$reader = new Xlsx();
$spreadsheet = $reader->load(__DIR__ . '/../../../excel/invoice.xlsx');
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue('Заказ клиента от ' . DateUtil::ruDate(new \DateTime(), 'j F Y') . ' г.');
$a = [$supplier->getName()];
if ($supplier->getInn()) {
$a[] = 'ИНН ' . $supplier->getInn();
}
if ($supplier->getAddress()) {
$a[] = $supplier->getAddress();
}
$sheet->getCell('C2')->setValue(implode(', ', $a));
$a = [$user->getFullName()];
if ($user->getPhone()) {
$a[] = $user->getPhone();
}
$sheet->getCell('C3')->setValue(implode(', ', $a));
$sheet->getCell('G6')->setValue($cart->getAmount());
$sheet->getCell('H6')->setValue($cart->getDiscountAmount());
$sheet->getCell('I6')->setValue($cart->getAmountWithDiscount());
$items = $cart->getItems();
$sheet->getCell('B8')->setValue('Всего наименований ' . count($items)
. ', на сумму ' . number_format($cart->getAmountWithDiscount(), 2, ',', ' ')
. ' руб.');
$sheet->getCell('B9')->setValue(NumberUtil::formatMoneyToWords($cart->getAmountWithDiscount()));
if ($cart->getVat()) {
$sheet->insertNewRowBefore(7, 1);
$sheet->mergeCellsByColumnAndRow(1, 7, 6, 7);
$sheet->getCell('A7')->setValue('В т.ч. НДС (' . $cart->getVat() . '%):');
$sheet->getCell('I7')->setValue($cart->getVatAmount());
$sheet->getCell('A8')->setValue('Итого с НДС:');
$sheet->getCell('I8')->setValue($cart->getAmountWithDiscount());
} else {
$sheet->getCell('A7')->setValue('Без налога (НДС)');
$sheet->getCell('I7')->setValue('-');
}
$firstRow = 5;
$rowIndex = $firstRow;
if (count($items) > 1) {
$sheet->insertNewRowBefore($rowIndex + 1, count($items) - 1);
}
for ($i = 0; $i < count($items); $i++) {
$item = $items[$i];
$sheet->getCell('A' . $rowIndex)->setValue($i + 1);
$sheet->getCell('B' . $rowIndex)->setValue($item->product->getSku());
$sheet->getCell('C' . $rowIndex)->setValue($item->product->getName());
$sheet->getCell('D' . $rowIndex)->setValue($item->quantity);
$sheet->getCell('E' . $rowIndex)->setValue('шт.');
$sheet->getCell('F' . $rowIndex)->setValue($item->getPrice());
$sheet->getCell('G' . $rowIndex)->setValue($item->getAmount());
$sheet->getCell('H' . $rowIndex)->setValue($item->getDiscountAmount());
$sheet->getCell('I' . $rowIndex)->setValue($item->getAmountWithDiscount());
$rowIndex++;
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($filePath);
$fileName = 'Заказ';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $fileName . '.xlsx"');
echo file_get_contents($filePath);
unlink($filePath);
exit;
}
}