<?php
namespace App\AtechNet\CoreBundle\Controller;
use App\AtechNet\CoreBundle\AtechNetCoreBundle;
use App\AtechNet\CoreBundle\Entity\Attribute;
use App\AtechNet\CoreBundle\Entity\CategoryPage;
use App\AtechNet\CoreBundle\Entity\CategoryPageFilterAttribute;
use App\AtechNet\CoreBundle\Entity\CategoryPagesPriorityProducts;
use App\AtechNet\CoreBundle\Entity\ClaimMedia;
use App\AtechNet\CoreBundle\Entity\Dashboard;
use App\AtechNet\CoreBundle\Entity\Document;
use App\AtechNet\CoreBundle\Entity\DocumentGroup;
use App\AtechNet\CoreBundle\Entity\Domain;
use App\AtechNet\CoreBundle\Entity\ExternalInvoiceValue;
use App\AtechNet\CoreBundle\Entity\Meal;
use App\AtechNet\CoreBundle\Entity\Photo;
use App\AtechNet\CoreBundle\Entity\Product;
use App\AtechNet\CoreBundle\Entity\ProductTag;
use App\AtechNet\CoreBundle\Entity\ProductType;
use App\AtechNet\CoreBundle\Entity\SeoUrl;
use App\AtechNet\CoreBundle\Entity\StockItem;
use App\AtechNet\CoreBundle\Entity\StockMovement;
use App\AtechNet\CoreBundle\Entity\User;
use App\AtechNet\CoreBundle\Entity\Vendor;
use App\AtechNet\CoreBundle\Form\SettingsType;
use App\AtechNet\CoreBundle\Helper\DeliveryUtil;
use App\AtechNet\CoreBundle\Service\Stock\StockItemService;
use App\AtechNet\CoreBundle\Helper\DigitalOceanSpaces;
use App\AtechNet\CoreBundle\Helper\Furbify\Image;
use App\AtechNet\CoreBundle\Translation\DatabaseTranslator;
use Doctrine\ORM\EntityManager;
use Mpdf\Container\NotFoundException;
use Phinx\Console\PhinxApplication;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
/**
* Default controller.
*/
class DefaultController extends BaseController
{
/**
* @return RedirectResponse
*/
public function homeAction(): RedirectResponse
{
if (!$this->isGranted('ROLE_ADMIN')) {
return $this->redirectToRoute('atech_net_core_login');
}
return $this->redirectToRoute('atech_net_core_product_all_list');
}
/**
* @param $current_page
* @return Response
*/
public function navigationAction($current_page): Response
{
$menuItems = [];
return $this->render('AtechNetCoreBundle/Default/navigation.html.twig', [
'menuItems' => $menuItems,
'current_page' => $current_page,
]);
}
/**
* @Route("/login", name="atech_net_core_login")
* @param AuthenticationUtils $authenticationUtils
* @return Response
*/
public function loginAction(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'AtechNetCoreBundle/Default/page_login.html.twig',
[
'last_username' => $lastUsername,
'error' => $error,
]
);
}
/**
* @Route("/logout", name="atech_net_core_logout", methods={"GET"})
*/
public function logout(): void
{
}
/**
* @return Response
*/
public function settingsShowAction(): Response
{
return $this->render('AtechNetCoreBundle/Default/page_settings_show.html.twig', [
'settings' => $this->getSettings(),
'languages' => AtechNetCoreBundle::$languages,
]);
}
/**
* @return Response
*/
public function settingsEditAction(): Response
{
$settings = $this->getSettings();
$editForm = $this->createEditForm($settings);
return $this->render('AtechNetCoreBundle/Default/page_settings_edit.html.twig', [
'settings' => $settings,
'languages' => AtechNetCoreBundle::$languages,
'edit_form' => $editForm->createView(),
]);
}
/**
* @param Request $request
* @return RedirectResponse|Response
*/
public function settingsUpdateAction(Request $request): RedirectResponse|Response
{
$settings = $this->getSettings();
if (!$settings) {
throw $this->createNotFoundException('Unable to find Settings entity.');
}
$editForm = $this->createEditForm($settings);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$entityManager = $this->getEntityManager();
$entityManager->persist($settings);
$entityManager->flush();
return $this->redirectToRoute('atech_net_core_settings_show');
}
return $this->render('AtechNetCoreBundle/Default/page_settings_edit.html.twig', [
'settings' => $settings,
'languages' => AtechNetCoreBundle::$languages,
'edit_form' => $editForm->createView(),
]);
}
/**
* @param $settings
* @return FormInterface
*/
private function createEditForm($settings): FormInterface
{
$form = $this->createForm(new SettingsType(), $settings, [
'action' => $this->generateUrl('atech_net_core_settings_update'),
'method' => 'POST',
]);
$form->add('submit', 'submit', [
'label' => 'admin.save',
'attr' => [
'class' => 'action-button',
],
]);
return $form;
}
/**
* @Route("/add-variable-to-session", name="atech_net_core_add_variable_to_session")
*
* @param Request $request
* @return Response
*/
public function addVariableToSessionAction(Request $request): Response
{
$session = $request->getSession();
$posts = $request->request->all();
if (count($posts) > 0) {
foreach ($posts as $name => $value) {
$session->set($name, $value);
}
}
return new Response('yeah');
}
/**
* @Route("/live-search", name="atech_net_core_live_search")
*
* @param Request $request
* @return JsonResponse
*/
public function liveSearchAction(Request $request): JsonResponse
{
$entityCode = $request->request->get('entityCode');
/** @var array $fields */
$fields = $request->request->get('fields', []);
$otherSelects = $request->request->get('otherSelects');
$otherLeftJoins = $request->request->get('otherLeftJoins');
$searchString = trim($request->request->get('searchString'));
$limit = $request->request->get('limit');
$orderBy = $request->request->get('orderBy');
$destPath = $request->request->get('destPath');
$selects = implode(',', $fields);
$selects .= ',' . $entityCode . '.id';
$likes = '';
foreach ($otherSelects as $otherSelect) {
$selects .= ',' . $otherSelect;
$selectSeparated = explode(' ', $otherSelect);
if ($likes == '') {
$likes .= ' ' . $selectSeparated[0] . " LIKE '%" . $searchString . "%' ";
} else {
$likes .= ' OR ' . $selectSeparated[0] . " LIKE '%" . $searchString . "%' ";
}
}
$leftJoins = '';
$addedParameters = [];
foreach ($fields as $field) {
$parameters = explode('.', $field);
if ($parameters[0] != $entityCode && !in_array($parameters[0], $addedParameters)) {
$leftJoins .= ' LEFT JOIN ' . $entityCode . '.' . strtolower($this->getLiveSearchEntityList()[$parameters[0]]) . ' ' . $parameters[0];
$addedParameters[] = $parameters[0];
}
if ($likes == '') {
$likes .= ' ' . $field . " LIKE '%" . $searchString . "%' ";
} else {
$likes .= ' OR ' . $field . " LIKE '%" . $searchString . "%' ";
}
}
if (in_array('c.firstName', $fields) && in_array('c.lastName', $fields)) {
if ($likes == '') {
$likes .= " CONCAT(c.firstName, ' ', c.lastName) LIKE '%" . $searchString . "%' OR CONCAT(c.lastName, ' ', c.firstName) LIKE '%" . $searchString . "%' ";
} else {
$likes .= " OR CONCAT(c.firstName, ' ', c.lastName) LIKE '%" . $searchString . "%' OR CONCAT(c.lastName, ' ', c.firstName) LIKE '%" . $searchString . "%' ";
}
}
foreach ($otherLeftJoins as $otherLeftJoin) {
$leftJoins .= ' LEFT JOIN ' . $otherLeftJoin;
}
$query = 'SELECT ' . $selects . '
FROM AtechNetCoreBundle:' . $this->getLiveSearchEntityList()[$entityCode] . ' ' . $entityCode . '
' . $leftJoins . '
WHERE ' . $likes . '
ORDER BY ' . $orderBy;
$results = $this->getEntityManager()
->createQuery($query)
->setMaxResults($limit)
->getResult();
foreach ($results as $key => $result) {
$results[$key]['link'] = $this->generateUrl($destPath, [
'id' => $result['id'],
]);
}
return (new JsonResponse())->setData([
'data' => $results,
]);
}
/**
* @return array
*/
protected function getLiveSearchEntityList(): array
{
return [
'd' => 'Domain',
'v' => 'Vendor',
'p' => 'Product',
'pm' => 'ProductMeta',
'pc' => 'ProductCommission',
'c' => 'Customer',
'o' => 'Order',
'oi' => 'OrderItem',
'ioao' => 'OrderItemAttributeOption',
];
}
/**
* @Route("/auto-complete-search", name="atech_net_core_auto_complete_search")
*
* @param Request $request
* @return JsonResponse
*/
public function autoCompleteSearchAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$creditNoteOnly = $request->request->getBoolean('creditNoteOnly');
$entityName = trim($request->request->get('entityName'));
$searchFor = trim($request->request->get('searchFor'));
$searchIn = $request->request->get('searchIn');
$searchInIndex = $request->request->get('searchInIndex');
$searchResultsContain = $request->request->get('searchResultsContain');
$searchArchived = $request->request->get('searchArchived');
$groupBy = $request->request->get('groupBy');
$queryLimit = $request->request->get('queryLimit');
$exactMatch = $request->request->getBoolean('exactMatch', false);
$isV2Search = $request->request->getBoolean('isV2Search', false);
if($entityName == 'User') {
$query = "SELECT DISTINCT u.firstName,u.lastName, u.id FROM AtechNetCoreBundle:User u WHERE u.isActive = 1 AND (u.firstName LIKE '%$searchFor%' OR u.lastName LIKE '%$searchFor%')";
$results = $entityManager->createQuery($query)
->setMaxResults($queryLimit)
->getResult();
return (new JsonResponse())->setData([
'data' => $results,
]);
}
if ($entityName == 'Product') {
$filterOnlyInStock = $request->query->get('filterOnlyInStock');
$filterProductId = $request->query->get('filterProductId');
$filterProductType = $request->request->get('filterProductType');
$filterVendor = $request->request->get('filterVendor');
} else {
$filterOnlyInStock = $filterProductId = $filterProductType = $filterVendor = null;
}
$leftJoin = '';
$where = '1=1';
$searchInFields = $this->parseSearchInColumns($searchIn, 'e.');
$searchInIndexFields = $this->parseSearchInColumns($searchInIndex, 'e.');
if ($entityName == 'Product') {
$selectFields = [
'e.id', 'e.code', 'pt.title', 'pt.id AS __productTypeId', 'pmpt.title model_product_type',
'v.name AS vendor', 'pmv.name model_product_vendor', 'e.name',
'e.cacheDescription', 'e.avgPrice AS __avgPrice',
'e.scannable AS __scannable', 'pt.scannable AS __typeScannable', 'pmpt.scannable AS __typeScannableModel',
'e.available', 'e.inStock, pm.isProductV2', 'pm.id AS productModelId',
'e.sparePartCard AS __sparePartCard', 'e.sparePartPrice AS __sparePartPrice',
];
$leftJoin = 'LEFT JOIN e.type pt LEFT JOIN e.vendor v ';
//V2
$leftJoin .= 'LEFT JOIN e.productModel pm LEFT JOIN pm.type pmpt LEFT JOIN pm.vendor pmv ';
if ($isV2Search) {
$where .= ' AND pm.isProductV2 = 1 ';
}
if ($creditNoteOnly) {
$leftJoin .= 'LEFT JOIN e.group pg ';
$where .= 'AND pg.id = '. DocumentGroup::TYPE_INVOICE_CREDIT_NOTE . ' ';
}
if (!is_null($searchArchived)) {
if ((int)$searchArchived > -1) {
$where .= " AND e.archived = " . (int)$searchArchived . " AND e.container = 0";
} else {
$where .= " AND e.container = 0";
}
} else {
$where .= " AND e.archived = 0 AND e.container = 0";
}
if ($filterOnlyInStock == 'not-scannable') {
if ((int)$filterProductId > 0) {
$where .= " AND (( e.inStock > 0 OR e.scannable = 1 ) OR e.id = " . (int)$filterProductId . ")";
} else {
$where .= " AND ( e.inStock > 0 OR e.scannable = 1 )";
}
}
if (is_array($filterProductType)) {
$where .= " AND pt.id IN (" . implode(',', array_map(function ($value) {
return (int)$value;
}, $filterProductType)) . ")";
} elseif ((int)$filterProductType > 0) {
$where .= " AND pt.id = " . (int)$filterProductType;
}
if ((int)$filterVendor > 0) {
$where .= " AND v.id = " . (int)$filterVendor;
}
array_push($searchInFields, 'pt.title', 'v.name');
if ($request->request->has('origin') && $request->request->get('origin') == 'statistics-product-sales') {
// Decodes URL-encoded searchFor
$searchFor = urldecode($searchFor);
// Search in selected fields
$whereOr = [];
foreach ($searchInFields as $field) {
$whereOr[] = "$field LIKE '%$searchFor%'";
}
// Search in field combinations
$whereOr[] = "CONCAT(v.name, ' ', pt.title, ' ', e.name) LIKE '%$searchFor%'";
$whereOr[] = "CONCAT(pt.title, ' ', v.name, ' ', e.name) LIKE '%$searchFor%'";
// Search by expressions
$expressions = $hits = [];
// Split search string
$expression = strtok($searchFor, ' ');
while ($expression !== false) {
$_expression = trim($expression);
if (strlen($_expression) == 1) {
$_expression = ' ' . $_expression;
}
$expressions[] = $_expression;
$expression = strtok(' ');
}
if (count($expressions) > 1) {
foreach ($expressions as $expression) {
$hits[] = "( CASE WHEN ( e.name LIKE '%$expression%' OR v.name LIKE '%$expression%' OR pt.title LIKE '%$expression%' ) THEN 1 ELSE 0 END )";
}
$whereOr[] = "( " . implode(' + ', $hits) . " ) >= " . count($expressions);
}
// Add where
$where .= " AND (" . implode(" OR ", $whereOr) . ")";
} else {
$searchWords = $searchInIndex != 'serialNumber' ? explode(' ', $searchFor) : [
0 => $searchFor,
];
if (count($searchInFields) > 0) {
$concatedColumns = $this->prepareSearchInColumns($searchInFields);
$searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
$where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
}
if (count($searchInIndexFields) > 0) {
$concatedColumns = $this->prepareSearchInColumns($searchInIndexFields);
$searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '", "%'"); // search all words in the concatenated string
$where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
}
}
} else {
$selectColumns = explode(',', $searchResultsContain);
if (!in_array('id', $selectColumns)) {
array_unshift($selectColumns, 'id');
}
$selectFields = $this->wrapElements($selectColumns, 'e.');
if ( $entityName == 'Order' && in_array('domain', $selectColumns) ) {
$key = array_search('e.domain', $selectFields);
if ( $key !== false ) {
$selectFields[$key] = 'IDENTITY(e.domain) AS domainId';
}
}
$productId = $request->request->get('productId');
if ($isV2Search && $entityName == 'ProductModel') {
$where .= ' AND e.isProductV2 = 1';
}
if ($entityName == 'StockItem' && $productId != null && $productId != 0 && is_numeric($productId)) {
$leftJoin = 'LEFT JOIN e.movementItems mi LEFT JOIN mi.product p ';
$where .= " AND p.id = " . $productId;
}
if ($entityName == 'Customer') {
$leftJoin = 'LEFT JOIN e.domain d ';
// remove invalid field name if present
$selectColumns = array_filter($selectColumns, fn($col) => $col !== 'currency');
$selectFields = $this->wrapElements($selectColumns, 'e.');
$selectFields[] = "CONCAT('(', d.name, ')') AS domain";
$selectFields[] = "d.currency AS currency";
}
$searchWords = $searchInIndex != 'serialNumber' && !$exactMatch ? explode(' ', $searchFor) : [
0 => $searchFor,
];
if (count($searchInFields) > 0) {
if ($exactMatch) {
$concatedColumns = $searchInFields[0];
$where .= " AND (" . "$concatedColumns Like '%" . $searchWords[0]."%'" . ')';
} else {
$concatedColumns = $this->prepareSearchInColumns($searchInFields);
$searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
$where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
}
}
if (count($searchInIndexFields) > 0) {
$concatedColumns = $this->prepareSearchInColumns($searchInIndexFields);
$searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '", "%'"); // search all words in the concatenated string
$where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
}
}
$querySelect = implode(',', $selectFields);
$query = "SELECT DISTINCT $querySelect FROM AtechNetCoreBundle:$entityName e $leftJoin WHERE $where";
if ($entityName == 'Product' && $groupBy == 'name') {
$query .= " GROUP BY e.name";
}
if ($entityName == 'ProductModel') {
$query .= " ORDER BY e.isProductV2 DESC";
}
$results = $entityManager->createQuery($query)
->setMaxResults($queryLimit)
->getResult();
if ($entityName == 'Product') {
foreach ($results as $key =>$result) {
if (is_null($result['title'])) {
$results[$key]['title'] = $result['model_product_type'];
}
if (is_null($result['vendor'])) {
$results[$key]['vendor'] = $result['model_product_vendor'];
}
}
}
if ($entityName == 'StockItem') { // add last stock movement type
$stockItemRepo = $entityManager->getRepository(StockItem::class);
foreach ($results as $key => $result) {
$si = null;
$si = $stockItemRepo->find($result['id']);
if ($si && $si->getLastMovement()) {
$results[$key]['last_stock_movement_type'] = $si->getLastMovement()->getType();
$results[$key]['last_stock_movement_id'] = $si->getLastMovement()->getId();
$results[$key]['lastPrice'] = $si->getLastMovementItem()->getTotalPricePerItem();
$results[$key]['__lastPrice'] = $si->getLastMovementItem()->getPricePerItem(true);
}
/**
* @var StockItem $si
* @var StockMovement $sm
*/
foreach ($si->getMovements() as $sm) {
$createDate = $sm->getCreated()->format('YmdHi');
$results[$key]['movements'][$createDate]['id'] = $sm->getId();
$results[$key]['movements'][$createDate]['type'] = $sm->getType();
$results[$key]['movements'][$createDate]['date'] = $createDate;
}
$results[$key]['errorCodes'] = [];
if (isset($si) && !is_null($si)) {
$results[$key]['errorCodes'] = $this->errorCodesToErrorText($si->getErrorCodes());
}
$lastMovementItem = $si->getLastMovementItem();
if ($lastMovementItem !== null) {
$results[$key]['quality'] = StockItemService::determineQuality($lastMovementItem->getProduct()->getQualityStatus());
}
}
}
return (new JsonResponse())->setData([
'data' => $results,
]);
}
/**
* @Route("/auto-complete-search-coupon", name="atech_net_core_auto_complete_search_coupon")
*
* @param Request $request
* @return JsonResponse
*/
public function autoCompleteSearchCouponAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$searchFilterCoupon = $request->request->get('filterCoupon');
$results = $entityManager->createQuery("SELECT c.code
FROM AtechNetCoreBundle:Coupon c
Where c.code Like '%" . $searchFilterCoupon . "%'
Group by c.code")
->getResult();
return (new JsonResponse())->setData([
'data' => $results,
]);
}
/**
* @param $searchInStr
* @param $prefix
* @return array
*/
private function parseSearchInColumns($searchInStr, $prefix)
{
$searchInStr = trim($searchInStr != null ? $searchInStr : "");
if ($searchInStr != "") {
return $this->wrapElements(explode(',', $searchInStr), $prefix);
} else {
return [];
}
}
/**
* @param array $searchInField
* @return array|mixed|string
*/
private function prepareSearchInColumns(array $searchInField)
{
$count = count($searchInField);
if ($count > 1) {
$searchInFieldsWrapped = $this->wrapElements($searchInField, "COALESCE(", ",' ')"); // fix for null values
return 'CONCAT(' . implode(', \' \',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
} elseif ($count == 1) {
return $searchInField[0];
} else {
return [];
}
}
/**
* @Route("/auto-complete-product", name="atech_net_core_auto_complete_product")
*
* @param Request $request
* @return JsonResponse
*/
public function autoCompleteProductAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$searchInFields = ['e.code', 'e.name', 'pt.title', 'v.name'];
$searchInFieldsWrapped = $this->wrapElements($searchInFields, "COALESCE(", ",' ')"); // fix for null values
$concatedColumns = 'CONCAT(' . implode(',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
$searchFor = $request->query->get('term');
$searchWords = explode(' ', $searchFor);
$searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
$query = "SELECT DISTINCT e.id, e.code, pt.title, pt.id AS typeId, v.name AS vendor, e.name, e.cacheDescription, e.scannable AS scannable, pt.scannable AS typeScannable, e.inStock, e.available
FROM AtechNetCoreBundle:Product e LEFT JOIN e.type pt LEFT JOIN e.vendor v WHERE e.archived = 0 AND e.container = 0 AND (" . implode(' AND ', $searchQueries) . ")";
$results = $entityManager->createQuery($query)
->setMaxResults(10)
->getResult();
if (count($results) > 0) {
$productIds = array_column($results, 'id');
$metaResults = $entityManager->createQuery("SELECT m, PARTIAL p.{id}, PARTIAL d.{id} FROM AtechNetCoreBundle:ProductMeta m
JOIN m.product p JOIN m.domain d WHERE p.id IN (:prodIds)")
->setParameter("prodIds", $productIds)
->getScalarResult();
$metas = [];
foreach ($metaResults as $key => $mr) {
$prodId = $mr['p_id'];
$domainId = $mr['d_id'];
$metas[$prodId][$domainId]['price'] = $mr['m_price'];
$metas[$prodId][$domainId]['discount'] = $mr['m_discount'];
}
foreach ($results as $key => $result) {
$prodId = $result['id'];
$results[$key]['metas'] = $metas[$prodId];
}
}
return new JsonResponse($results);
}
/**
* @Route("/auto-complete-product-tag", name="atech_net_core_auto_complete_product_tag")
*
* @param Request $request
* @return JsonResponse
*/
public function autoCompleteProductTagAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$searchInFields = ['productTag.title'];
$searchInFieldsWrapped = $this->wrapElements($searchInFields, "COALESCE(", ",' ')"); // fix for null values
$concatedColumns = 'CONCAT(' . implode(',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
$searchFor = $request->query->get('term');
$searchWords = explode(' ', $searchFor);
$searchQueries = $this->wrapElements($searchWords, "productTag.title LIKE '%", "%'"); // search all words in the concatenated string
$query = "SELECT DISTINCT productTag.id, productTag.title
FROM AtechNetCoreBundle:ProductTag productTag
WHERE (" . implode(' AND ', $searchQueries) . ")";
$results = $entityManager->createQuery($query)
->setMaxResults(10)
->getResult();
return new JsonResponse($results);
}
/**
* @param $arr
* @param $prefix
* @param string $suffix
* @return array
*/
private function wrapElements($arr, $prefix, string $suffix = ''): array
{
$result = [];
foreach ($arr as $e) {
$result[] = $prefix . str_replace("'", "", $e) . $suffix;
}
return $result;
}
/**
* @Route("/clear-cache", name="atech_net_core_clear_cache")
*
* @return Response
*/
public function clearCacheAction(): Response
{
ini_set("memory_limit", '1000M');
$application = new Application($this->kernel);
$application->setAutoExit(false);
$input = new StringInput('cache:clear --env=prod');
$output = new BufferedOutput();
$resultCode = $application->run($input, $output);
$response = $output->fetch();
return new Response('Result code: ' . $resultCode . '<br/><code>' . nl2br($response) . '</code>');
}
/**
* @Route("/create-stock-movement/{id}", name="atech_net_core_create_stock_movement")
*
* @param int $id
* @return Response
* @throws \Exception
*/
public function createStockMovementFromOrderAction(int $id): Response
{
$application = new Application($this->kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'centralis:create-stock-movement-from-domain',
'orderId' => $id,
'--env' => $this->kernel->getEnvironment(),
]);
$output = new BufferedOutput();
$application->run($input, $output);
return new Response($output->fetch());
}
/**
* @Route("/create-controlling-product-list", name="create_controlling_product_list")
*
* @return Response
* @throws \Exception
*/
public function createControllingProductListAction(): Response
{
$application = new Application($this->kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'centralis:export-product-list-for-controlling',
'--env' => $this->kernel->getEnvironment(),
]);
$output = new BufferedOutput();
$application->run($input, $output);
return new Response($output->fetch());
}
/**
* @Route("/migrate-db", name="atech_net_core_migrate_db")
*
* @param Request $request
* @return Response
* @throws \Exception
*/
public function migrateDbAction(Request $request): Response
{
$phinx = new PhinxApplication();
$phinx->setAutoExit(false);
$input = new ArrayInput([
'command' => 'migrate',
'-c' => $this->getParameter('kernel.project_dir') . '/phinx.yml',
'-e' => $this->kernel->getEnvironment(),
]);
$output = new BufferedOutput();
$phinx->run($input, $output);
$output = preg_replace('/^.+\n/', '', $output->fetch());
if (!empty($request->headers->get('User-Agent'))
&& strstr($request->headers->get('User-Agent'), 'curl') === false
) {
$output = nl2br($output);
}
return new Response($output);
}
/**
* @Route("/check-scannable-products", name="atech_net_core_check_scannable_products")
*
* @param Request $request
* @return JsonResponse
*/
public function checkScannedProductsAction(Request $request): JsonResponse
{
$productsRepo = $this->getEntityManager()->getRepository(Product::class);
$products = $request->request->get('products');
foreach ($products as $key => $prodId) {
$product = $productsRepo->find($prodId);
if (!$product) {
unset($products[$key]);
}
if (!$product->isScannable() || !$product->getType()->isScannable()) {
unset($products[$key]);
}
}
return (new JsonResponse())->setData([
'data' => $products,
]);
}
/**
* @Route("/export-vat-values", name="export_vat_values")
*
* @throws \Exception
*/
public function exportVatValuesAction(): Response
{
$data = [];
$entityManager = $this->getEntityManager();
$documents = $entityManager->createQuery("SELECT PARTIAL d.{id,code,vat,createdDate,chargeabilityDate,group,totalPrice,totalVatPrice,updatedByTime,relatedDocument,externalNumber},
PARTIAL dg.{id,title,type,prefix,language}
FROM AtechNetCoreBundle:Document d
LEFT JOIN d.group dg
WHERE dg.type = :invoiceIn OR dg.type = :invoiceOut OR dg.type = :creditNote
ORDER BY dg.prefix ASC, d.code DESC")
->setParameters([
'invoiceIn' => DocumentGroup::TYPE_INVOICE_IN,
'invoiceOut' => DocumentGroup::TYPE_INVOICE_OUT,
'creditNote' => DocumentGroup::TYPE_INVOICE_CREDIT_NOTE,
])
->getResult();
$documentGroups = $entityManager->createQuery("SELECT dg
FROM AtechNetCoreBundle:DocumentGroup dg
WHERE dg.type = :invoiceIn OR dg.type = :invoiceOut OR dg.type = :creditNote")
->setParameters([
'invoiceIn' => DocumentGroup::TYPE_INVOICE_IN,
'invoiceOut' => DocumentGroup::TYPE_INVOICE_OUT,
'creditNote' => DocumentGroup::TYPE_INVOICE_CREDIT_NOTE,
])
->getResult();
$dataSum = [];
$exchangeRateService = $this->getHistoricalEuroRate();
foreach ($documents as $doc) {
if ($doc->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_IN) {
$year = $doc->getCreatedDate()->format('Y');
$yearShort = $doc->getCreatedDate()->format('y');
$month = $doc->getCreatedDate()->format('m');
} else {
$year = $doc->getChargeabilityDate()->format('Y');
$yearShort = $doc->getChargeabilityDate()->format('y');
$month = $doc->getChargeabilityDate()->format('m');
}
switch ($doc->getGroup()->getLanguage()) {
case 'SK':
case 'EN':
$currency = 'EUR';
break;
case 'HU':
$currency = 'HUF';
break;
case 'CZ':
$currency = 'CZK';
break;
default:
$currency = 'EUR';
}
switch ($doc->getGroup()->getType()) {
case DocumentGroup::TYPE_INVOICE_IN:
case DocumentGroup::TYPE_INVOICE_CREDIT_NOTE:
$negative = true;
break;
case DocumentGroup::TYPE_INVOICE_OUT:
$negative = false;
break;
}
$vatValue = $doc->getTotalVatPrice() - $doc->getTotalPrice();
/**
* @var Document $doc
*/
if ($doc->getGroup()->getPrefix() == '30') {
$documentCode = $doc->getExternalNumber();
} else {
$documentCode = $doc->getCode();
}
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['code'] = $documentCode;
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['vat'] = $doc->getVat();
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['vatValue'] = $negative ? -$vatValue : $vatValue;
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['eurValue'] = 0;
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['currency'] = $currency;
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['updated'] = $doc->getUpdatedByTime();
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['updatedLater'] = $doc->getUpdatedByTime()->format('Y-m') != $year . '-' . $month ? true : false;
if (!isset($dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort])) {
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['currency'] = $currency;
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['value'] = 0;
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['eurValue'] = 0;
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['groupTitle'] = $doc->getGroup()->getTitle();
}
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['value'] += $negative ? -$vatValue : $vatValue;
if ($currency != 'EUR' && $vatValue != 0) {
$exchangeRate = 1;
if ($currency != '') {
if ($doc->getExchangeRate() == 0) {
if ($doc->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_CREDIT_NOTE && !is_null($doc->getRelatedDocument())) {
$date1DayBefore = $doc->getRelatedDocument()->getCreatedDate()->format('Y-m-d');
} else {
$date1DayBefore = $doc->getCreatedDate()->sub(new \DateInterval('P1D'))->format('Y-m-d');
}
$exchangeRate = $exchangeRateService->getRate($currency, $date1DayBefore);
} else {
$exchangeRate = $doc->getExchangeRate();
}
}
$eurValue = number_format($vatValue / $exchangeRate, 2, '.', '');
$data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['eurValue'] = $negative ? -$eurValue : $eurValue;
$dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['eurValue'] += $negative ? -$eurValue : $eurValue;
}
}
$externalInvoiceValues = $entityManager->getRepository(ExternalInvoiceValue::class)->findAll();
$extInvVTypes = ExternalInvoiceValue::getTypeChoices();
foreach ($externalInvoiceValues as $extInvV) {
foreach ($extInvVTypes as $extInvVType) {
$groupCode = $extInvVType . $extInvV->getTargetDate()->format('Y');
$dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['groupTitle'] = $groupCode;
$dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['eurValue'] = 0;
$dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['currency'] = 'EUR';
$dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['value'] = $extInvV->{'getValue' . $extInvVType}();
}
}
/**
* @var DocumentGroup $dg
*/
foreach ($dataSum as $sumDate => $dt) {
$sumDateYear = substr($sumDate, 0, 4);
foreach ($documentGroups as $dg) {
$year = $dg->getYear()->getYear();
if ($year != $sumDateYear) {
continue;
}
$shortYear = substr($year, -2);
if (!isset($dt[$dg->getPrefix() . $shortYear])) {
$dataSum[$sumDate][$dg->getPrefix() . $shortYear]['groupTitle'] = $dg->getTitle();
$dataSum[$sumDate][$dg->getPrefix() . $shortYear]['eurValue'] = 0;
$dataSum[$sumDate][$dg->getPrefix() . $shortYear]['currency'] = 'EUR';
$dataSum[$sumDate][$dg->getPrefix() . $shortYear]['value'] = 0;
}
}
foreach ($extInvVTypes as $extInvVType) {
if (!isset($dt[$extInvVType . $sumDateYear])) {
$dataSum[$sumDate][$extInvVType . $sumDateYear]['groupTitle'] = $extInvVType . $sumDateYear;
$dataSum[$sumDate][$extInvVType . $sumDateYear]['eurValue'] = 0;
$dataSum[$sumDate][$extInvVType . $sumDateYear]['currency'] = 'EUR';
$dataSum[$sumDate][$extInvVType . $sumDateYear]['value'] = 0;
}
}
}
foreach ($dataSum as $key => $date) {
ksort($date);
$dataSum[$key] = $date;
}
krsort($data);
return $this->render('AtechNetCoreBundle/Default/vatValues.html.twig', [
'data' => $data,
'dataSum' => $dataSum,
]);
}
/**
* @Route("/links", name="atech_net_core_links")
*
* @return Response
*/
public function linksAction(): Response
{
return $this->render('AtechNetCoreBundle/Default/links.html.twig', []);
}
/**
* @Route("/deliveryData", name="atech_net_core_delivery_data")
*
* @param Request $request
* @return JsonResponse
*/
public function deliveryDataAction(Request $request): JsonResponse
{
try {
$domainId = $request->get('domainId');
if ($domainId == null || trim($domainId) == '') {
return new JsonResponse([
'error' => 'Empty domainId',
]);
}
return new JsonResponse([
'deliveryDates' => DeliveryUtil::getAvailableDeliveryDates($domainId),
'holidays' => DeliveryUtil::getHolidays($domainId),
]);
} catch (\Exception $exception) {
return new JsonResponse([
'error' => $exception->getMessage(),
]);
}
}
/**
* @Route("/sales-goal", name="sales_goal")
*
* @param Breadcrumbs $breadcrumbs
* @return Response
*/
public function salesGoalAction(Breadcrumbs $breadcrumbs): Response
{
$this->getBreadcrumbs($breadcrumbs)->addItem('Sales goal');
$dashboardRepo = $this->getEntityManager()->getRepository(Dashboard::class);
$goal = 100000;
$data = $dashboardRepo->getSalesStatistics($goal);
return $this->render('AtechNetCoreBundle/Default/sales-goal.html.twig', [
'data' => $data,
]);
}
/**
* @Route("/discount-rss/{domainId}", name="atech_net_core_discount_rss")
*
* @param int $domainId
* @return Response
* @throws \Exception
*/
public function discountRssAction(int $domainId): Response
{
/** @var EntityManager $entityManager */
$entityManager = $this->getEntityManager();
$domain = $entityManager->getRepository(Domain::class)->find($domainId);
$language = $domain->getLanguage();
$discountedProducts = $entityManager->createQuery('SELECT p FROM AtechNetCoreBundle:Product p
LEFT JOIN p.metas pm
LEFT JOIN p.type pt
WHERE p.available > 0 AND pm.product = p AND pm.domain = ' . $domainId . ' AND pm.discount > 0 AND pm.discounted = 1 AND pm.active = 1 AND pm.listed = 1 AND pm.orderable = 1 AND (pt.id = 60 OR pt.id = 52 OR pt.id = 44)
ORDER BY pm.discount ASC')
->getResult();
$translator = new DatabaseTranslator($entityManager, $domainId);
if ($domain->getLanguage()->getCode() == 'hu') {
$oldPriceTxt = 'Eredeti ár:';
} else {
$oldPriceTxt = 'Pôvodná cena:';
}
$rss = '<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">';
foreach ($discountedProducts as $dp) {
if ($domainId == 5) {
$pageName = $dp->getPageFileName($translator);
$link = $domain->getUrl() . '/eshop/' . $pageName;
} else {
$query = 'product_id=' . $dp->getId();
$url = $entityManager->getRepository(SeoUrl::class)->findOneBy([
'query' => $query,
'language' => $language,
]);
$link = 'https://www.furbify.' . $language->getCode() . '/';
if ($url) {
$link .= $url->getKeyword();
} else {
$link .= $query;
}
}
$utm = '?utm_source=ActiveCampaign&utm_medium=email&utm_campaign=autofeed';
$pm = $dp->getDomainMeta($domain);
if ($dp->getAlbum()->getPhotos()->count() > 0) {
$image = $dp->getAlbum()->getPhotos()->first()->getCdnUrl('ProductViewPop');
$rss .= '<channel>
<title>' . $dp->getVendor()->getName() . ' ' . $dp->getName() . '</title>
<link>' . $link . '</link>
<description>' . $dp->getDescription() . '</description>
<item>
<title>' . $dp->getVendor()->getName() . ' ' . $dp->getName() . '</title>
<link><![CDATA[' . $link . $utm . ']]></link>
<description>' . $dp->getDescription() . '</description>
<price>' . $domain->createVatPrice($pm->getDiscount()) . ' ' . $domain->getCurrency() . '</price>
<old_price>' . $oldPriceTxt . ' ' . $domain->createVatPrice($pm->getPrice()) . ' ' . $domain->getCurrency() . '</old_price>
<image>
<url>' . $image . '</url>
</image>
</item>
</channel>';
}
}
$rss .= '</rss>';
$response = new Response($rss);
$response->headers->set('Content-Type', 'rss+xml');
return $response;
}
/**
* @Route("/automatization", name="atech_net_core_automatizations")
*
* @param Breadcrumbs $breadcrumbs
* @return Response
*/
public function automatizationAction(Breadcrumbs $breadcrumbs): Response
{
$this->hasPermission(User::PERMISSION_AUTOMATIZATIONS, User::MODULE_OTHER);
$this->getBreadcrumbs($breadcrumbs)->addItem('Automatizations');
$data = [
[
'time' => 'Every day at 00:01',
'command' => 'update-document-status',
'title' => 'Update document status',
'desc' => '',
],
[
'time' => 'Every day at 23:50',
'command' => 'create-stock-status-snapshot',
'title' => 'Create stock status snapshot',
'desc' => '',
],
[
'time' => 'Every day at 23:55',
'command' => 'create-commitment-receivable-snapshot',
'title' => 'Create commitment receivable snapshot',
'desc' => '',
],
[
'time' => 'Every day at 00:30',
'command' => 'update-exchange-rate-files',
'title' => 'Update exchange rate files',
'desc' => '',
],
[
'time' => 'Every day at 15:00',
'command' => 'notify-past-due-date',
'title' => 'Notify past due date',
'desc' => '',
],
[
'time' => 'Every day at 21:55',
'command' => 'create-out-invoice-for-achu',
'title' => 'Create out invoice for AC HU',
'desc' => '',
],
[
'time' => 'Every Saturday at 23:30',
'command' => 'archive-products',
'title' => 'Archive products',
'desc' => '',
],
[
'time' => 'Every day at 23:40',
'command' => 'convert-shipment-config-change-create',
'title' => 'Convert shipment config change create',
'desc' => '',
],
[
'time' => 'Every day at 23:45',
'command' => 'create-in-stock-day-stats',
'title' => 'Create in stock day stats',
'desc' => '',
],
[
'time' => 'Every day at 23:46',
'command' => 'create-quality-status-stats',
'title' => 'Create quality status stats',
'desc' => '',
],
[
'time' => 'Every day at 08:30 (0), 09:00 (1), 09:30 (2), 07:45 (3), 09:20 (5)',
'command' => 'remind-meal-group',
'title' => 'Remind meal group',
'desc' => 'Arg = meal group id',
],
[
'time' => 'At 14:00 on Sunday',
'command' => 'remind-about-next-week-absences',
'title' => 'Remind about next week absences',
'desc' => '',
],
[
'time' => 'Every hour at :00',
'command' => 'service-manager-sync',
'title' => 'Service manager sync',
'desc' => '',
],
[
'time' => 'Every weekday at 20:00, 22:00',
'command' => 'set-ready-to-ship-orders-to-completed',
'title' => 'Set ready to ship orders to completed',
'desc' => '',
],
[
'time' => 'Every weekday at 19:00, 21:00',
'command' => 'finalize-marketplace-orders',
'title' => 'Finalize marketplace orders',
'desc' => '',
],
[
'time' => 'Every day at 04:00',
'command' => 'arukereso-feed',
'title' => 'Arukereso.hu XML feed update',
'desc' => '',
],
[
'time' => 'Every day at 04:01',
'command' => 'argep-feed',
'title' => 'Argep.hu XML feed update',
'desc' => '',
],
[
'time' => 'Every day at 23:40',
'command' => 'import-gls-pickup-points',
'title' => 'Import GLS pickup points',
'desc' => '',
],
[
'time' => 'Every hour at :00',
'command' => 'update-timed-sale-product-states',
'title' => 'Update timed sale product states',
'desc' => '',
],
[
'time' => 'Every day at 07:30, 10:00, 12:00, 15:00, 16:30 (1), 07:46 (2), 07:47 (3)',
'command' => 'remind-unfinished-stock-movements',
'title' => 'Remind unfinished stock movements',
'desc' => 'Arg = reminder level',
],
[
'time' => 'Every day at 23:51',
'command' => 'create-daily-product-statistics',
'title' => 'Create daily product statistics',
'desc' => '',
],
[
'time' => 'Every day at 23:52',
'command' => 'update-stock-movements-exchange-rates',
'title' => 'Update stock movements exchange rates',
'desc' => '',
],
[
'time' => 'Every weekday 06:05–17:05 hourly; weekend at 08:05',
'command' => 'export-in-production-products',
'title' => 'Export in production products',
'desc' => '',
],
[
'time' => '1st of month at 10:00 (2), 12:00 (3)',
'command' => 'export-furbify-not-paid-documents',
'title' => 'Export Furbify not paid documents',
'desc' => 'Arg = company',
],
[
'time' => 'Every hour at :30',
'command' => 'price-monitor-notification',
'title' => 'Price monitor notification',
'desc' => '',
],
[
'time' => '1st of month at 00:05',
'command' => 'create-in-invoice-from-hu',
'title' => 'Create in invoice from HU',
'desc' => '',
],
[
'time' => 'Every day at :05 and :35 between 05:00–21:00',
'command' => 'update-product-positions',
'title' => 'Update product positions',
'desc' => '',
],
[
'time' => 'Every day at 22:50',
'command' => 'create-old-stock-items-snapshot',
'title' => 'Create old stock items snapshot',
'desc' => '',
],
[
'time' => 'Every day at 05:xx, 15:xx and 06:xx, 16:xx (staggered per domain)',
'command' => 'generate-cache-for-domain',
'title' => 'Generate cache for domain',
'desc' => 'RT_SK, WS_SK, RT_HU, WS_HU, RT_CZ, WS_CZ, RT_EU, WS_EU',
],
[
'time' => '1st of month at 00:05',
'command' => 'export-incoming-cards-table',
'title' => 'Export incoming cards table',
'desc' => '',
],
[
'time' => 'Every day at :10 of 07, 09, 11, 13, 15, 16, 17',
'command' => 'repair-order-stock-movement-exchange-rate',
'title' => 'Repair order stock movement exchange rate',
'desc' => '',
],
[
'time' => 'Every day at 20:02',
'command' => 'update-price-monitor-connected-orders',
'title' => 'Update price monitor connected orders',
'desc' => '',
],
[
'time' => 'Every 15 minutes (:02, :17, :32, :47)',
'command' => 'import-marketplace-orders',
'title' => 'Import marketplace orders',
'desc' => '',
],
[
'time' => 'Every 15 minutes (:08, :23, :38, :53)',
'command' => 'check-canceled-marketplace-orders',
'title' => 'Check canceled marketplace orders',
'desc' => '',
],
[
'time' => 'Every day at 20:05',
'command' => 'repair-product-last-and-averages-prices',
'title' => 'Repair product last and average prices',
'desc' => '',
],
[
'time' => 'Every minute during hour 00 and 15',
'command' => 'chown -R www-data:www-data var/cache',
'title' => 'Fix cache ownership',
'desc' => 'System command (not a console command)',
],
[
'time' => 'Every day at 22:20',
'command' => 'update-products-with-over-limit-stock-movements',
'title' => 'Update products with over limit stock movements',
'desc' => '',
],
[
'time' => 'Every day at 22:10',
'command' => 'export-orders-to-controlling-db',
'title' => 'Export orders to controlling DB',
'desc' => '',
],
[
'time' => 'Every day at 03:40',
'command' => 'correction-job-create',
'title' => 'Correction job create',
'desc' => '',
],
[
'time' => 'Every day at 17:00',
'command' => 'export-sales-manager-orders-for-controlling',
'title' => 'Export sales manager orders for controlling',
'desc' => '',
],
[
'time' => 'Every weekday at 09:00',
'command' => 'notify-for-low-available-stock',
'title' => 'Notify for low available stock',
'desc' => '',
],
[
'time' => 'Every day at 22:59, 02:59, 11:59',
'command' => 'update-backmarket-pbh-tracking-and-confirm-order',
'title' => 'Update Backmarket PBH tracking and confirm order',
'desc' => '',
],
[
'time' => 'Every day at 20:10',
'command' => 'notify-for-finished-backmarket-orders-with-manually-created-shipment',
'title' => 'Notify for finished Backmarket orders with manual shipment',
'desc' => '',
],
[
'time' => 'Every day at 20:12',
'command' => 'export-invoices-to-pastpay',
'title' => 'Export invoices to PastPay',
'desc' => '',
],
[
'time' => 'Every hour at :02',
'command' => 'create-order-product-changelog',
'title' => 'Create order product changelog',
'desc' => '',
],
[
'time' => 'Every day at 20:17',
'command' => 'update-product-sold-during-timeframe',
'title' => 'Update product sold during timeframe',
'desc' => '',
],
[
'time' => 'Every day at 21:13',
'command' => 'create-attributes',
'title' => 'Create attributes',
'desc' => '',
],
[
'time' => 'Every 15 minutes (:04, :19, :34, :49)',
'command' => 'check-prepare-and-run-marketplace-jobs',
'title' => 'Check, prepare and run marketplace jobs',
'desc' => '',
],
[
'time' => 'Every 15 minutes (:12, :27, :42, :57)',
'command' => 'check-price-change-jobs',
'title' => 'Check price change jobs',
'desc' => '',
],
[
'time' => 'Every day at 19:55',
'command' => 'b2c-credit-note-send',
'title' => 'B2C credit note send',
'desc' => '',
],
[
'time' => 'Every day at 20:14',
'command' => 'check-category-pages-with-product-tags',
'title' => 'Check category pages with product tags',
'desc' => '',
],
[
'time' => 'Every weekday, every 15 minutes (:09, :24, :39, :54)',
'command' => 'finalize-refurbed-orders',
'title' => 'Finalize Refurbed orders',
'desc' => '',
],
[
'time' => 'Every 2 hours at :10',
'command' => 'update-bnpl-orders-status-after-certain-time',
'title' => 'Update BNPL orders status after certain time',
'desc' => '',
],
[
'time' => 'Every hour at :30',
'command' => 'import-vub-transactions',
'title' => 'Import VUB transactions',
'desc' => '',
],
[
'time' => 'Every 15 minutes (:09, :24, :39, :54)',
'command' => 'sync-unas-stock-from-centralis',
'title' => 'Sync UNAS stock from Centralis',
'desc' => '',
],
[
'time' => 'Every day at 03:15',
'command' => 'sync-unas-from-centralis',
'title' => 'Sync UNAS from Centralis',
'desc' => '',
],
[
'time' => 'Every day at 01:30',
'command' => 'product-listing-stats',
'title' => 'Product listing stats',
'desc' => '',
],
[
'time' => 'Every 15 minutes',
'command' => 'create-pre-invoice-for-rt-ws',
'title' => 'Create pre invoice for RT/WS',
'desc' => 'Runs as www-data',
],
[
'time' => 'Every 15 minutes',
'command' => 'check-credit-note-stock-movement-prices',
'title' => 'Check credit note stock movement prices',
'desc' => 'Runs as www-data',
],
[
'time' => 'Every day at 20:20',
'command' => 'sync-centralis-customer-with-daktela',
'title' => 'Sync Centralis customer with Daktela',
'desc' => 'Runs as www-data',
],
[
'time' => 'Every day at 20:30',
'command' => 'stock-position-stats',
'title' => 'Stock position stats',
'desc' => 'Runs as www-data',
],
[
'time' => 'Every 5 minutes',
'command' => 'create-order-invoices',
'title' => 'Create order invoices',
'desc' => '',
],
[
'time' => 'Every day at 16:05',
'command' => 'update-carrier-setting',
'title' => 'Update carrier setting',
'desc' => '',
],
[
'time' => 'Every day at 08:00, 20:00',
'command' => 'check_not_paid_orders_klaviyo',
'title' => 'Check not paid orders Klaviyo',
'desc' => '',
],
[
'time' => 'Every 15 minutes',
'command' => 'send-shipment-change-notifications',
'title' => 'Send shipment change notifications',
'desc' => '',
],
[
'time' => 'Every day at 21:10',
'command' => 'fix-illegal-stock-movements',
'title' => 'Fix illegal stock movements',
'desc' => '',
],
[
'time' => 'Every day at 21:10',
'command' => 'update-customer-order-dates',
'title' => 'Update customer order dates',
'desc' => '',
],
[
'time' => 'Every hour at :00',
'command' => 'messenger:consume async --time-limit=3600',
'title' => 'Consume async messages',
'desc' => '',
],
[
'time' => 'Every day at 00:05',
'command' => 'create-daily-order-snapshot',
'title' => 'Create daily order snapshot',
'desc' => '',
],
[
'time' => 'Every weekday at 09:15 (0), 09:30 (1), 09:45 (2)',
'command' => 'remind-shipment-payment',
'title' => 'Remind shipment payment',
'desc' => 'Arg = reminder level',
],
];
return $this->render('AtechNetCoreBundle/Default/automatization.html.twig', [
'data' => $data,
]);
}
/**
* @Route("/product-type-search", name="product_type_search")
*
* @param Request $request
* @return JsonResponse
*/
public function productTypeSearchAction(Request $request): JsonResponse
{
$searchQuery = $request->query->get('term');
$results = $this->getEntityManager()->createQuery("SELECT pt.id, pt.title
FROM AtechNetCoreBundle:ProductType pt
WHERE pt.title LIKE '%" . $searchQuery . "%'
ORDER BY pt.title ASC")
->setMaxResults(10)
->getResult()
;
return new JsonResponse($results);
}
/**
* @Route("/add-product-type-to-category", name="add_product_type_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function addProductTypeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$productTypeId = $request->request->get('productTypeId');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && is_numeric($productTypeId)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$productType = $entityManager->getRepository(ProductType::class)->find($productTypeId);
if ($category && $productType) {
$category->addProductType($productType);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/remove-product-type-to-category", name="remove_product_type_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function removeProductTypeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$productTypeId = $request->request->get('productTypeId');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && is_numeric($productTypeId)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$productType = $entityManager->getRepository(ProductType::class)->find($productTypeId);
if ($category && $productType) {
$category->removeProductType($productType);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/product-search", name="product_search")
*
* @param Request $request
* @return JsonResponse
*/
public function productSearchAction(Request $request): JsonResponse
{
$searchQuery = $request->query->get('term');
$results = $this->getEntityManager()->createQuery("SELECT p.id, p.code, p.name
FROM AtechNetCoreBundle:Product p
WHERE p.code LIKE '%" . $searchQuery . "%' OR p.name LIKE '%" . $searchQuery . "%'")
->setMaxResults(5)
->getResult();
return new JsonResponse($results);
}
/**
* @Route("/add-product-to-category", name="add_product_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function addProductToCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_NORMAL, $categoryId, $productId),
]);
}
/**
* @Route("/add-priority-product-to-category", name="add_priority_product_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function addPriorityProductToCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_PRIORITY, $categoryId, $productId),
]);
}
/**
* @Route("/add-popular-product-to-category", name="add_popular_product_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function addPopularProductToCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_POPULAR, $categoryId, $productId),
]);
}
/**
* @Route("/remove-product-to-category", name="remove_product_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function removeProductToCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_NORMAL, $categoryId, $productId),
]);
}
/**
* @Route("/remove-priority-product-to-category", name="remove_priority_product_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function removePriorityProductToCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_PRIORITY, $categoryId, $productId),
]);
}
/**
* @Route("/remove-popular-product-from-category", name="remove_popular_product_from_category")
*
* @param Request $request
* @return JsonResponse
*/
public function removePopularProductFromCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$productId = (int)$request->request->get('productId');
return new JsonResponse([
'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_POPULAR, $categoryId, $productId),
]);
}
/**
* @param bool $remove
* @param int $type
* @param int $categoryId
* @param int $productId
* @return string
*/
private function processProductToCategory(bool $remove, int $type, int $categoryId, int $productId): string
{
$entityManager = $this->getEntityManager();
$result = 'error';
/**
* @var CategoryPage $category
*/
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$product = $entityManager->getRepository(Product::class)->find($productId);
if ($category && $product) {
if ($type == CategoryPage::PRODUCT_TYPE_POPULAR) {
if ($remove) {
$category->removePopularProduct($product);
} else {
$category->addPopularProduct($product);
}
} elseif ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
if ($remove) {
$category->removeProduct($product);
} else {
$category->addProduct($product);
}
} elseif ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
if ($remove) {
$this->removePriorityProduct($category, $product);
} else {
$this->addPriorityProduct($category, $product);
}
}
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
return $result;
}
/**
* @param CategoryPage $category
* @param Product $product
* @return void
*/
private function removePriorityProduct(CategoryPage $category, Product $product): void
{
$entityManager = $this->getEntityManager();
$entity = $entityManager->getRepository(CategoryPagesPriorityProducts::class)->findOneBy([
'categoryPage' => $category,
'product' => $product,
]);
if ($entity) {
$entityManager->remove($entity);
$entityManager->flush();
}
}
/**
* @param CategoryPage $category
* @param Product $product
* @return void
*/
private function addPriorityProduct(CategoryPage $category, Product $product): void
{
$entityManager = $this->getEntityManager();
$categoryPagePriorityProduct = new CategoryPagesPriorityProducts();
$categoryPagePriorityProduct->setCategoryPage($category);
$categoryPagePriorityProduct->setProduct($product);
$lastKnownSortIndex = $entityManager->getRepository(CategoryPage::class)
->getLastSortIndexForPriorityProducts($category);
$categoryPagePriorityProduct->setSortIndex($lastKnownSortIndex + 1);
$entityManager->persist($categoryPagePriorityProduct);
$entityManager->flush();
}
/**
* @Route("/remove-all-connected-product-from-category", name="remove_all_connected_product_from_category")
*
* @param Request $request
* @return JsonResponse
*/
public function removeAllProductFromCategoryAction(Request $request): JsonResponse
{
$categoryId = (int)$request->request->get('categoryId');
$type = (int)$request->request->get('type');
$entityManager = $this->getEntityManager();
/**
* @var CategoryPage $category
*/
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
if (!$category) {
return new JsonResponse([
'response' => 'error',
]);
}
$productsToRemove = [
CategoryPage::PRODUCT_TYPE_NORMAL => $category->getProducts(),
CategoryPage::PRODUCT_TYPE_POPULAR => $category->getPopularProducts(),
];
if ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
$allPriorityProducts = $entityManager->getRepository(CategoryPagesPriorityProducts::class)->findBy([
'categoryPage' => $category,
]);
foreach ($allPriorityProducts as $priorityProduct) {
$entityManager->remove($priorityProduct);
}
$entityManager->flush();
$result = 'success';
return new JsonResponse([
'response' => $result,
]);
}
foreach ($productsToRemove[$type] as $product) {
if ($type == CategoryPage::PRODUCT_TYPE_POPULAR) {
$category->removePopularProduct($product);
} elseif ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
$category->removeProduct($product);
}
$entityManager->persist($category);
}
$entityManager->flush();
$result = 'success';
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/add-clipboard-products-to-category", name="add_products_from_clipboard_to_category")
*
* @param Request $request
* @return JsonResponse
*/
public function addClipboardProductsToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
/** @var array $pastedCodes */
$pastedCodes = $request->request->get('pastedCodes', []);
$type = $request->request->get('type');
$productsAdded = $notFoundCodes = [];
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && count($pastedCodes) > 0 && is_numeric($type)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$products = $entityManager->getRepository(Product::class)
->createQueryBuilder('p')
->where('p.code IN (:codes)')
->setParameter('codes', $pastedCodes)
->getQuery()
->getResult();
if ($category) {
if ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
/**
* @var Product $product
*/
foreach ($products as $key => $product) {
if (($removableKey = array_search($product->getCode(), $pastedCodes)) !== false) {
unset($pastedCodes[$removableKey]);
}
$category->addProduct($product);
$entityManager->persist($category);
$entityManager->flush();
$productsAdded[] = [
'id' => $product->getId(),
'code' => $product->getCode(),
'name' => $product->getName(),
];
}
} elseif ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
foreach ($products as $key => $product) {
if (($removableKey = array_search($product->getCode(), $pastedCodes)) !== false) {
unset($pastedCodes[$removableKey]);
}
$priorityProduct = new CategoryPagesPriorityProducts();
$priorityProduct->setCategoryPage($category);
$priorityProduct->setProduct($product);
$priorityProduct->setSortIndex($key);
$entityManager->persist($priorityProduct);
$entityManager->flush();
$productsAdded[] = [
'id' => $product->getId(),
'code' => $product->getCode(),
'name' => $product->getName(),
];
}
}
}
#$notFoundCodes = $pastedCodes;
}
$response = [
'productsAdded' => $productsAdded,
'notFoundCodes' => $notFoundCodes,
];
return new JsonResponse([
'response' => $response,
]);
}
/**
* @Route("/add-products/category-page/from/product-tag", name="add_products_from_product_tag_to_category")
*
* @param Request $request
*
* @return JsonResponse
*/
public function addProductsToCategoryPageFromProductTag(Request $request): JsonResponse
{
$categoryId = $request->request->get('categoryId');
$productTagId = $request->request->get('productTagId');
if (!is_numeric($categoryId) || !is_numeric($productTagId)) {
return new JsonResponse([
'success' => 'false',
]);
}
$entityManager = $this->getEntityManager();
$categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$productTag = $entityManager->getRepository(ProductTag::class)->find($productTagId);
if (!$categoryPage || !$productTag) {
return new JsonResponse([
'success' => 'false',
]);
}
$categoryPage->addProductTag($productTag);
/** @var Product $product */
foreach ($productTag->getProducts() as $product) {
$categoryPage->addProduct($product);
}
$entityManager->flush();
return new JsonResponse([
'success' => 'true',
]);
}
/**
* @Route("/remove-product-tag/remove-tag-products", name="remove_product_tag_remove_tag_products")
*
* @param Request $request
*
* @return JsonResponse
*/
public function removeProductsToCategoryPageFromProductTag(Request $request): JsonResponse
{
$categoryId = $request->request->get('categoryId');
$productTagId = $request->request->get('productTagId');
if (!is_numeric($categoryId) || !is_numeric($productTagId)) {
return new JsonResponse([
'success' => 'false',
]);
}
$entityManager = $this->getEntityManager();
/**
* @var CategoryPage|null $categoryPage
* @var ProductTag|null $productTag
*/
$categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$productTag = $entityManager->getRepository(ProductTag::class)->find($productTagId);
if (!$categoryPage || !$productTag) {
return new JsonResponse([
'success' => 'false',
]);
}
//Remove tag from the category page
$categoryPage->removeProductTag($productTag);
//Remove all product tage products from the category page
foreach ($productTag->getProducts() as $product) {
$categoryPage->removeProduct($product);
}
$entityManager->flush();
return new JsonResponse([
'success' => 'true',
]);
}
/**
* @Route("/category-page/priority-products/sort", name="category_page_priority_products_sort")
*
* @param Request $request
* @return void
*/
public function updatePriorityProductsSortIndexAjaxAction(Request $request): JsonResponse
{
$categoryId = $request->request->get('categoryId');
$order = $request->request->get('order');
if (!is_numeric($categoryId) || !is_array($order)) {
return new JsonResponse([
'error' => 'Invalid data provided',
], 400);
}
$entityManager = $this->getEntityManager();
/**
* @var CategoryPage $categoryPage
*/
$categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
if (is_null($categoryPage)) {
return new JsonResponse([
'error' => 'Category not found',
], 404);
}
foreach ($order as $sortIndex => $productId) {
$categoryPagePriorityProduct = $categoryPage->getPriorityProducts()->findFirst(function ($key, $entity) use ($productId) {
return $entity->getProduct()->getId() == $productId;
});
if ($categoryPagePriorityProduct) {
$categoryPagePriorityProduct->setSortIndex($sortIndex);
}
}
$entityManager->flush();
return new JsonResponse([
'success' => 'Order updated successfully',
]);
}
/**
* @Route("/category-page-search", name="category_search")
*
* @param Request $request
* @return JsonResponse
*/
public function categorySearchAction(Request $request): JsonResponse
{
$searchQuery = $request->query->get('term');
$results = $this->getEntityManager()->createQuery("SELECT cp.id, d.shortTitle AS domainTitle, pm.title
FROM AtechNetCoreBundle:PageMeta pm
INNER JOIN pm.categoryPage cp
INNER JOIN cp.domain d
WHERE pm.title LIKE '%$searchQuery%' OR cp.id = '$searchQuery'")
->setMaxResults(10)
->getResult();
$entityManager = $this->getEntityManager();
$categoryPageRepo = $entityManager->getRepository(CategoryPage::class);
/**
* @var CategoryPage $categoryPage
*/
foreach ($results as $key => $result) {
$categoryPage = $categoryPageRepo->find($result['id']);
/**
* @var CategoryPageFilterAttribute $filterAttribute
*/
foreach ($categoryPage->getFilterAttributes() as $filterAttribute) {
$results[$key]['filterList'][] = $filterAttribute->getAttribute()->getTitle();
}
}
return new JsonResponse($results);
}
/**
* @Route("/vendor_search-search", name="vendor_search")
*
* @param Request $request
* @return JsonResponse
*
* FOR SEARCHING VENDORS TO PRODUCT CATEGORY
*/
public function vendorSearchAction(Request $request): JsonResponse
{
$searchQuery = $request->query->get('term');
$results = $this->getEntityManager()->createQuery("SELECT v.id, v.name
FROM AtechNetCoreBundle:Vendor v
WHERE v.name LIKE '%" . $searchQuery . "%'")
->setMaxResults(5)
->getResult();
return new JsonResponse($results);
}
/**
* @Route("/add-vendor-to-category", name="add_vendor_to_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR ADDING VENDORS TO PRODUCT CATEGORY
*/
public function addVendorToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$vendorId = $request->request->get('vendorId');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && is_numeric($vendorId)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$vendor = $entityManager->getRepository(Vendor::class)->find($vendorId);
if ($category && $vendor) {
$category->addVendor($vendor);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/remove-vendor-to-category", name="remove_vendor_to_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR REMOVING VENDORS TO PRODUCT CATEGORY
*/
public function removeVendorToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$vendorId = $request->request->get('vendorId');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && is_numeric($vendorId)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$vendor = $entityManager->getRepository(Vendor::class)->find($vendorId);
if ($category && $vendor) {
$category->removeVendor($vendor);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/filter-attribute-search", name="filter_attribute_search")
*
* @param Request $request
* @return JsonResponse
*
* FOR SEARCHING FILTER ATTRIBUTES TO PRODUCT CATEGORY
*/
public function filterAttributeSearchAction(Request $request): JsonResponse
{
$searchQuery = $request->query->get('term');
$results = $this->getEntityManager()->createQuery("SELECT a.id, a.title, pt.title AS ptTitle
FROM AtechNetCoreBundle:Attribute a
LEFT JOIN a.productTypes pt
WHERE a.title LIKE '%" . $searchQuery . "%'")
->setMaxResults(10)
->getResult();
return new JsonResponse($results);
}
/**
* @Route("/add-filter-attribute-to-category", name="add_filter_attribute_to_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR ADDING FILTER ATTRIBUTES TO PRODUCT CATEGORY
*/
public function addFilterAttributeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = (int)$request->request->get('categoryId');
$filterAttributeId = (int)$request->request->get('filterAttributeId');
$result = 'error';
/**
* @var CategoryPage $category
*/
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
if ($category && $filterAttribute) {
$addFilterAttribute = new CategoryPageFilterAttribute();
$addFilterAttribute->setAttribute($filterAttribute);
$addFilterAttribute->setCategoryPage($category);
$addFilterAttribute->setDelta($category->getFilterAttributes()->count());
$category->addFilterAttribute($addFilterAttribute);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/update-filter-attribute-to-category", name="update_filter_attribute_to_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR UPDATING FILTER ATTRIBUTES TO PRODUCT CATEGORY
*/
public function updateFilterAttributeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = (int)$request->request->get('categoryId');
$filterAttributes = explode(',', $request->request->get('filterAttributes'));
$result = 'error';
/**
* @var CategoryPage $category
*/
if (!empty($filterAttributes)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
if ($category) {
$category->clearFilterAttribute();
foreach ($filterAttributes as $delta => $filterAttributeId) {
$filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
if ($filterAttribute) {
$addFilterAttribute = new CategoryPageFilterAttribute();
$addFilterAttribute->setAttribute($filterAttribute);
$addFilterAttribute->setCategoryPage($category);
$addFilterAttribute->setDelta($delta);
$category->addFilterAttribute($addFilterAttribute);
$entityManager->flush();
}
}
$entityManager->refresh($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/remove-filter-attribute-to-category", name="remove_filter_attribute_to_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR REMOVING FILTER ATTRIBUTES TO PRODUCT CATEGORY
*/
public function removeFilterAttributeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$filterAttributeId = $request->request->get('filterAttributeId');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && is_numeric($filterAttributeId)) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
$filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
if ($category && $filterAttribute) {
$category->removeFilterAttribute($filterAttribute);
$entityManager->persist($category);
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/add-remove-badge-from-category", name="add_remove_badge_from_category")
*
* @param Request $request
* @return JsonResponse
*
* FOR ADDING AND REMOVING BADGES FROM PRODUCT CATEGORY
*/
public function badgeToCategoryAction(Request $request): JsonResponse
{
$entityManager = $this->getEntityManager();
$categoryId = $request->request->get('categoryId');
$badge = $request->request->get('badge');
$badgeValue = $request->request->get('badgeValue');
$result = 'error';
/**
* @var CategoryPage $category
*/
if (is_numeric($categoryId) && $badge != '' && $badgeValue != '' && in_array($badge, Product::getBadgesChoices())) {
$category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
if ($category) {
$currentBadges = json_decode($category->getBadges(), true);
if ($badgeValue == 0) {
foreach ($currentBadges as $key => $currentBadge) {
if ($currentBadge == $badge) {
unset($currentBadges[$key]);
}
}
} else {
$currentBadges[] = $badge;
}
$category->setBadges(json_encode($currentBadges));
$entityManager->flush();
$result = 'success';
}
}
return new JsonResponse([
'response' => $result,
]);
}
/**
* @Route("/centralis-replay/{year}", name="atech_net_core_year_stats")
*
* @return Response
*/
public function yearStatsAction(Request $request, int $year): Response
{
$data = [];
$entityManager = $this->getEntityManager();
$user = $this->getUser();
$dateFrom = (new \DateTime())->setDate($year, 1, 1)->setTime(0, 0);
$dateFromLiteral = $dateFrom->format('Y-m-d H:i:s');
$dateTo = (new \DateTime())->setDate($year + 1, 1, 1)->setTime(0, 0);
$dateToLiteral = $dateTo->format('Y-m-d H:i:s');
$conn = $entityManager->getConnection();
$data['username'] = $user->getNickname();
$data['domains'] = [
Domain::DOMAIN_ID_RT_SK => 'RT SK',
Domain::DOMAIN_ID_WS_SK => 'WS SK',
Domain::DOMAIN_ID_RT_HU => 'RT HU',
Domain::DOMAIN_ID_WS_HU => 'WS HU',
Domain::DOMAIN_ID_WS_CZ => 'WS CZ',
Domain::DOMAIN_ID_WS_EU => 'WS EU',
Domain::DOMAIN_ID_B2C_EU => 'B2C EU',
Domain::DOMAIN_ID_RT_CZ => 'RT CZ',
];
$data['months'] = [
1 => 'Január',
2 => 'Február',
3 => 'Március',
4 => 'Április',
5 => 'Május',
6 => 'Június',
7 => 'Július',
8 => 'Augusztus',
9 => 'Szeptember',
10 => 'Október',
11 => 'November',
12 => 'December',
];
$data['userCount'] = count($entityManager->getRepository(User::class)->findBy([
'isActive' => 1,
]));
$userAbsences = $entityManager->createQuery("SELECT COUNT(ua.id) AS cnt FROM AtechNetCoreBundle:UserAbsence ua WHERE ua.created > :dateFrom AND ua.created < :dateTo AND ua.user = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['absences'] = $userAbsences[0]['cnt'];
$userMeals = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt, SUM(m.price) AS cnt_price FROM AtechNetCoreBundle:Meal m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.createdBy = :user ")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['meals'] = $userMeals[0]['cnt'];
$data['user']['meals_price'] = $userMeals[0]['cnt_price'];
$userCreatedTasks = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt FROM AtechNetCoreBundle:Task m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.creator = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdTasks'] = $userCreatedTasks[0]['cnt'];
$userAssignedTasks = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt FROM AtechNetCoreBundle:TaskAssignedTo m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.user = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['assignedTasks'] = $userAssignedTasks[0]['cnt'];
$userCreatedOrders = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdOrders'] = $userCreatedOrders[0]['cnt'];
$userUpdatedOrders = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['updatedOrders'] = $userUpdatedOrders[0]['cnt'];
$userCreatedDocuments = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Document o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdDocuments'] = $userCreatedDocuments[0]['cnt'];
$userUpdatedDocuments = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Document o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['updatedDocuments'] = $userUpdatedDocuments[0]['cnt'];
$userCreatedMovements = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:StockMovement o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdMovements'] = $userCreatedMovements[0]['cnt'];
$userUpdatedMovements = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:StockMovement o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['updatedMovements'] = $userUpdatedMovements[0]['cnt'];
$userCreatedCustomers = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdCustomers'] = $userCreatedCustomers[0]['cnt'];
$userUpdatedCustomers = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['updatedCustomers'] = $userUpdatedCustomers[0]['cnt'];
$userCreatedProducts = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Product o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['createdProducts'] = $userCreatedProducts[0]['cnt'];
$userUpdatedProducts = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Product o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
->setParameters([
'dateFrom' => $dateFrom,
'dateTo' => $dateTo,
'user' => $user,
])
->getResult();
$data['user']['updatedProducts'] = $userUpdatedProducts[0]['cnt'];
$cacheItem = $this->cache->getItem("centralis-replay-current-year");
if ($cacheItem->isHit()) {
$data = array_merge($data, $cacheItem->get());
} else {
$items = [];
$items['all']['orders']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
$items['all']['packages']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, SUM(o.box_count) AS sm FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
$items['all']['absences']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM users_absence o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['documents']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM documents o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['documents_billingo']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM customers__billingo_data o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['stockMovements']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_movements o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['stockItems']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_items o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['claim']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM claims o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['meal']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt, SUM(o.price) AS cnt_price FROM meal o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['customers']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM customers o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['all']['orders']['byHour'] = $conn->fetchAllAssociative("SELECT HOUR(o.created) AS hour, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY HOUR(o.created)");
$cacheItem->set($items);
$cacheItem->expiresAfter(self::CACHE_LIFETIME_1_DAY);
$this->cache->save($cacheItem);
$data = array_merge($data, $items);
}
$data['all']['meal']['favouriteRestaurant']['id'] = $conn->fetchAllAssociative("SELECT m.restaurant FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' GROUP BY m.restaurant ORDER BY COUNT(m.restaurant) DESC LIMIT 1")[0]['restaurant'];
$data['all']['meal']['favouriteRestaurant']['title'] = Meal::getRestaurantName($data['all']['meal']['favouriteRestaurant']['id']);
$data['all']['meal']['favouriteRestaurant']['orderCount'] = $conn->fetchAllAssociative("SELECT COUNT(m.id) AS orderCount FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' AND m.restaurant = " . $data['all']['meal']['favouriteRestaurant']['id'])[0]['orderCount'];
$data['all']['meal']['favouriteRestaurant']['orderValue'] = $conn->fetchAllAssociative("SELECT SUM(m.price) AS orderValue FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' AND m.restaurant = " . $data['all']['meal']['favouriteRestaurant']['id'])[0]['orderValue'];
$cacheItem = $this->cache->getItem("centralis-replay-previous-year");
if ($cacheItem->isHit()) {
$data = array_merge($data, $cacheItem->get());
} else {
$items = [];
for ($i = $year - 1; $i > 2011; $i--) {
$dateFrom = (new \DateTime())->setDate($i, 1, 1)->setTime(0, 0);
$dateFromLiteral = $dateFrom->format('Y-m-d H:i:s');
$dateTo = (new \DateTime())->setDate($i + 1, 1, 1)->setTime(0, 0);
$dateToLiteral = $dateTo->format('Y-m-d H:i:s');
$items['previousYear']['orders']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
$items['previousYear']['packages']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, SUM(o.box_count) AS sm FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
$items['previousYear']['documents']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM documents o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['previousYear']['stockItems']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_items o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
$items['previousYear']['claim']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM claims o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
}
$cacheItem->set($items);
$cacheItem->expiresAfter(self::CACHE_LIFETIME_7_DAYS);
$this->cache->save($cacheItem);
$data = array_merge($data, $items);
}
$data['all']['orders']['all'] = 0;
foreach ($data['all']['orders']['byMonth'] as $month) {
$data['all']['orders']['all'] += $month['cnt'];
}
$data['all']['packages']['all'] = 0;
foreach ($data['all']['packages']['byMonth'] as $month) {
$data['all']['packages']['all'] += $month['sm'];
}
$data['all']['absences']['all'] = 0;
foreach ($data['all']['absences']['byMonth'] as $month) {
$data['all']['absences']['all'] += $month['cnt'];
}
$data['all']['documents']['all'] = 0;
foreach ($data['all']['documents']['byMonth'] as $month) {
$data['all']['documents']['all'] += $month['cnt'];
}
foreach ($data['all']['documents_billingo']['byMonth'] as $month) {
$data['all']['documents']['all'] += $month['cnt'];
}
$data['all']['stockMovements']['all'] = 0;
foreach ($data['all']['stockMovements']['byMonth'] as $month) {
$data['all']['stockMovements']['all'] += $month['cnt'];
}
$data['all']['stockItems']['all'] = 0;
foreach ($data['all']['stockItems']['byMonth'] as $month) {
$data['all']['stockItems']['all'] += $month['cnt'];
}
$data['all']['claim']['all'] = 0;
foreach ($data['all']['claim']['byMonth'] as $month) {
$data['all']['claim']['all'] += $month['cnt'];
}
$data['all']['meal']['all'] = 0;
$data['all']['meal']['all_price'] = 0;
foreach ($data['all']['meal']['byMonth'] as $month) {
$data['all']['meal']['all'] += $month['cnt'];
$data['all']['meal']['all_price'] += $month['cnt_price'];
}
$data['all']['customers']['all'] = 0;
foreach ($data['all']['customers']['byMonth'] as $month) {
$data['all']['customers']['all'] += $month['cnt'];
}
$data['year'] = $year;
return $this->render('AtechNetCoreBundle/Default/yearStats.html.twig', $data);
}
/**
* @Route("/cdn/image/product/{image}-{width}-{height}.{extension}", name="image_cdn")
* @param Request $request
* @param string $image
* @param int $width
* @param int $height
* @param string $extension
*
* @return Response
* @throws NotFoundException
*/
public function cdnAction(Request $request, string $image, int $width, int $height, string $extension): Response
{
$photoId = (int)substr($image, 0, (strlen($image) - 32));
$photo = $this->getEntityManager()->getRepository(Photo::class)->find($photoId);
/**
* @var Photo $photo
*/
if ($photo) {
// Validate Salt
if ($photo->getSalt() == str_replace($photoId, '', $image)) {
// Variant
$variant = Image::determineCloudflareVariant($width, $height);
if (!is_null($variant)) {
// Cloudflare
if (!is_null($photo->getCloudflareId())) {
$url = $photo->getCdnUrl($variant);
// Image Mime Type
switch ($extension) {
case 'jpg':
case 'jpeg':
$headerAccept = 'image/jpeg';
break;
case 'gif':
$headerAccept = 'image/gif';
break;
case 'webp':
$headerAccept = 'image/webp';
break;
case 'png':
$headerAccept = 'image/png';
break;
default:
$headerAccept = $request->server->get('HTTP_ACCEPT');
break;
}
$userAgent = $request->server->get('HTTP_USER_AGENT');
// Response Header
$headers = [];
// Get Image
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept' => $headerAccept,
]);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$headers) {
$length = strlen($header);
// Parse Header
$header = explode(':', $header, 2);
// Ignore invalid Header
if (count($header) < 2) {
return $length;
}
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $length;
});
$response = curl_exec($ch);
// HTTP OK
if ((int)curl_getinfo($ch, CURLINFO_HTTP_CODE) == Response::HTTP_OK) {
$contentType = false;
if (isset($headers['content-type'])) {
$contentType = array_pop($headers['content-type']);
}
$contentLength = false;
if (isset($headers['content-length'])) {
$contentLength = array_pop($headers['content-length']);
}
if ($contentType && $contentLength) {
return new Response($response, Response::HTTP_OK, [
'Cache-Control' => 'public',
'Content-Type' => $contentType,
'Content-Length' => $contentLength,
'Content-Disposition' => 'inline; filename="' . $photo->getOriginalName() . '-' . $width . '-' . $height . '.' . $extension . '"',
]);
}
}
}
// Use system photo generation
if ($photo->getAlbum()) {
// Product
$product = $this->getEntityManager()->getRepository(Product::class)->findOneByAlbum($photo->getAlbum());
if ($product) {
$image = $this->getImage($photo, 'product/' . $product->getCode(), false)->resize($width, $height);
$imageContent = file_get_contents(str_replace(' ', '%20', $image));
return new Response($imageContent, Response::HTTP_OK, [
'Cache-Control' => 'public',
'Content-Type' => $photo->getMimeType(),
'Content-Length' => strlen($imageContent),
'Content-Disposition' => 'inline; filename="' . basename($image) . '"',
]);
}
}
}
}
}
throw new NotFoundException('Photo not found!');
}
/**
* @Route("/update-entity-items-settings", name="atech_net_core_update_entity_items_settings")
* @param Request $request
* @return JsonResponse
*/
public function updateEntityItemsSettingsAction(Request $request): JsonResponse
{
$entityName = $request->get('entityName');
$entityColumnName = $request->get('entityColumnName');
$entityIds = $request->get('entityIds');
$columnValue = (bool) $request->get('columnValue');
$entityManager = $this->getEntityManager();
switch ($entityName) {
case 'stockItem':
$entityManager->getRepository(StockItem::class)->updateStockItems(
$entityColumnName,
explode(',', $entityIds),
$columnValue
);
break;
}
return new JsonResponse([]);
}
/**
* @Route("/digitalocean-object/{scope}/{id}", name="atech_net_core_digitalocean_object")
*
* @param Request $request
* @return Response
*/
public function digitalOceanObject(Request $request, string $scope, int $id): Response
{
// Entity Manager
$entityManager = $this->getEntityManager();
// Digital Ocean Space
$digitalOcean = $this->getDigitalOceanSpace();
// Response
$response = new Response();
switch ($scope) {
case 'claim':
$claimMedia = $entityManager->getRepository(ClaimMedia::class)->find($id);
if ($claimMedia) {
$result = $digitalOcean->claimMedia($claimMedia, 'download');
if (!empty($result['body'])) {
$response->headers->set('Content-Type', $claimMedia->getMimeType());
$response->headers->set('Content-Disposition', 'attachment;filename="' . $claimMedia->getFilename());
$response->setContent($result['body']);
}
}
break;
case 'user-avatar':
$user = $entityManager->getRepository(User::class)->find($id);
if ($user) {
$result = $digitalOcean->userAvatar($user, null, 'download');
if (!empty($result['body'])) {
// Extension
$extension = pathinfo($user->getAvatar(), PATHINFO_EXTENSION);
// Mime Type
switch ($extension) {
case 'jpg':
case 'jpeg':
$mimeType = 'image/jpeg';
break;
case 'gif':
$mimeType = 'image/gif';
break;
case 'webp':
$mimeType = 'image/webp';
break;
case 'png':
$mimeType = 'image/png';
break;
default:
// Temporary File
$tmp = tempnam(DigitalOceanSpaces::getUploadDirectory() . 'digitalocean/user-avatar/', 'frb_') . '_' . $user->getAvatar();
file_put_contents($tmp, $result['body']);
$mimeType = MimeTypes::getDefault()->guessMimeType($tmp);
@unlink($tmp);
break;
}
$response->headers->set('Content-Type', $mimeType);
$response->headers->set('Content-Disposition', 'attachment;filename="' . $user->getAvatar());
$response->setContent($result['body']);
}
}
break;
}
return $response;
}
}