<?php
namespace App\Controller;
use App\Entity\Catalog;
use App\Entity\StanMag;
use App\Entity\StanMagStatus;
use App\Entity\SystemConfig;
use App\Integration\Marketplace\Allegro\AllegroRestApi;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
class ApiController extends ApiBaseController
{
/**
* @Route("/api/stanmagReactivate/{id}", name="api_stanmag_reactivate", methods={"GET"})
* @param string $id
* @return JsonResponse
*/
public function getApiStanmagReactivate(string $id = ''): Response
{
$output = [];
/** @var StanMag $item */
$id = preg_replace("/-/","/",$id);
/** @var StanMag $item */
$item = $this->em->getRepository(StanMag::class)->findOneBy(['nrEtykiety'=> $id]);
if (!$item) {
return $this->respondWithErrors("No item found");
}
// if already active - return with error
if ($item->getStanMagStatus()->getAllegroActive() > 0) {
return $this->respondWithErrors("Item already published");
}
# if ($item->getStanMagStatus()->getIsEligible() > 0) {
# return $this->respondWithErrors("Item already active");
# $item->makeAvailable();
# }
if (!$item->makeAvailable()) {
return $this->respondWithErrors("Item activation failed");
}
$this->em->persist($item);
$this->em->flush();
// if sold - make previous auctions as ignore
// update sold dates
// update active status
// update ilosc = 1
// udpate usun = 0
return $this->respondWithText("Produkt ".$item->getNrEtykiety()." może być ponownie wystawiony na Allegro");
return $this->respondWithSuccess($output);
}
/**
* @Route("/api/stanmagDeactivate/{id}", name="api_stanmag_deactivate", methods={"GET"})
* @param string $id
* @return JsonResponse
*/
public function getApiStanmagDeactivate(string $id = ''): JsonResponse
{
$output = [];
/** @var StanMag $item */
$id = preg_replace("/-/","/",$id);
/** @var StanMag $item */
$item = $this->em->getRepository(StanMag::class)->findOneBy(['nrEtykiety'=> $id]);
if (!$item) {
return $this->respondWithErrors("No item found");
}
// if already active - return with error
if ($item->getStanMagStatus()->getAllegroActive() > 0) {
return $this->respondWithErrors("Item already published");
}
if ($item->getStanMagStatus()->getIsEligible() == 0) {
return $this->respondWithErrors("Item already inactive");
}
if (!$item->makeUnavailable()) {
return $this->respondWithErrors("Item deactivation failed");
}
$this->em->persist($item);
$this->em->flush();
// update ilosc = 0
// udpate usun = 98
return $this->respondWithSuccess($output);
}
/**
* @Route("/api/stanmagUnpublish/{id}", name="api_stanmag_unpublish", methods={"GET"})
* @param string $id
* @return JsonResponse
*/
public function getApiStanmagUnpublish(string $id = ''): Response
{
$output = [];
/** @var StanMag $item */
$id = preg_replace("/-/","/",$id);
/** @var StanMag $item */
$item = $this->em->getRepository(StanMag::class)->findOneBy(['nrEtykiety'=> $id]);
if (!$item) {
return $this->respondWithErrors("ERROR: UNABLE TO UNPUBLISH THIS ITEM No item found");
}
if (!$item->getAllegroOffers()) {
return $this->respondWithErrors("ERROR: UNABLE TO UNPUBLISH THIS ITEM No Allegro offers found");
} else {
$output['log'][] = "Found ".count($item->getAllegroOffers())." Allegro offers ";
}
$activeOffer = null;
foreach($item->getAllegroOffers() as $offer) {
if (strtoupper($offer->getStatus()) == 'ACTIVE' || strtoupper($offer->getStatus()) == 'PLACEHOLDER') {
$activeOffer = $offer;
$output['log'][] = "Found active offer ".$offer->getId()." ";
}
}
if (null === $activeOffer) {
return $this->respondWithErrors("ERROR: UNABLE TO UNPUBLISH THIS ITEM No Active Allegro offer found");
}
$source = ($item->getKodLokalizacji() == 12) ? "waw" : "gru";
if ($item->getKodLokalizacji() == 99) {
$source = "aga";
}
$allegroClientId = $this->em->getRepository(SystemConfig::class)->getParameter('allegroClientId','allegro');
$allegroClientSecret = $this->em->getRepository(SystemConfig::class)->getParameter('allegroClientSecret','allegro');
$allegroAccessToken = $this->em->getRepository(SystemConfig::class)->getParameter('allegroAccessToken.'.$source,'allegro');
$api = new AllegroRestApi();
$api->setAccessToken($allegroAccessToken)
->setClientId($allegroClientId)
->setClientSecret($allegroClientSecret);
$output['log'][] = "Active offer removed - ".$activeOffer->getId()." ";
$res = $api->removeOfferFromAllegro($activeOffer->getId());
$output['response'] = $res;
$activeOffer->setStatus("ENDED");
$this->em->persist($activeOffer);
$this->em->flush();
$output['log'][] = "Active offer status set to ENDED - ".$activeOffer->getId()." ";
//return $this->respondWithText("PRODUKT BYL WYSTAWIONY I JEST TERAZ USUNIETY");
return $this->respondWithSuccess($output);
}
/**
* @Route("/api/stanmagStatus/{location}", name="api_stanmag_status", methods={"GET"})
* @param string $location
* @return JsonResponse
*/
public function getApiStanmagStatus(string $location = '00'): JsonResponse
{
$output = [];
$alias = "s";
$prefix = $alias.'.';
$start = 0;
$limit = 10000;
$countQuery = $this->em->createQueryBuilder();
$countQuery->select('count(s.nrEtykiety)')->from(StanMagStatus::class, $alias);
$countQuery->where('1=1');
$countQuery->andWhere(" s.kodLokalizacji = '".$location."' ");
$countRecords = $countQuery->getQuery()->getSingleScalarResult();
//$output['log'][] = "Total records: ".$countRecords." ";
if ($countRecords > 0) {
while ($start < $countRecords) {
//$output['log'][] = "Batch start [".$start."] limit [".$limit."] ";
$query = $this->em->createQueryBuilder();
// $query->select('s','st')->from(StanMagStatus::class, $alias)->leftJoin($alias.'.stanMag', 'st');
$query->select('s')->from(StanMagStatus::class, $alias);
$query->where('1=1');
$query->andWhere(" s.kodLokalizacji = '".$location."' ");
$items = $query->getQuery()
->setFirstResult($start)
->setMaxResults($limit)
->getArrayResult();
//->getResult();
if (is_array($items) && count($items) > 0) {
foreach($items as $item) {
$row = [
'nr_etykiety' => $item['nrEtykiety'],
'location' => $item['kodLokalizacji'],
'allegro_active' => $item['allegroActive'],
'allegro_sold' => $item['allegroSold'],
'status' => $item['isAvailable'],
'is_eligible' => $item['isEligible'],
'status_allegro' => $this->getStatusAllegro($item),
];
$output[] = $row;
}
} else {
return $this->respondWithErrors("No data to render");
}
$start += $limit;
}
} else {
// no count records received
return $this->respondWithErrors("No data received");
}
//
//
// //$items = $this->em->getRepository(StanMagStatus::class)->findBy(['kodLokalizacji'=> $location]);
// if (is_array($items) && count($items) > 0) {
//
//// /** @var StanMagStatus $item */
//// foreach($items as $item) {
//// $row = [
//// 'nr_etykiety' => $item->getNrEtykiety(),
//// 'location' => $item->getKodLokalizacji(),
//// 'allegro_active' => $item->getAllegroActive(),
//// 'allegro_sold' => $item->getAllegroSold(),
//// 'status' => $item->getIsAvailable(),
//// 'is_eligible' => $item->getIsEligible(),
//// 'status_allegro' => $item->getStatusAllegro(),
//// ];
//// $output[] = $row;
//// }
//
// foreach($items as $item) {
// $row = [
// 'nr_etykiety' => $item['nrEtykiety'],
// 'location' => $item['kodLokalizacji'],
// 'allegro_active' => $item['allegroActive'],
// 'allegro_sold' => $item['allegroSold'],
// 'status' => $item['isAvailable'],
// 'is_eligible' => $item['isEligible'],
// 'status_allegro' => $this->getStatusAllegro($item),
// ];
// $output[] = $row;
//// print_r($item);
//// print_r($row);
//// die();
//
// }
//
// } else {
// return $this->respondWithErrors("No data to render");
// }
return $this->respondWithSuccess($output);
}
private function getStatusAllegro(array $item) : ?string
{
if ($item['allegroActive'] > 0) return "wystawione";
if ($item['allegroSold'] > 0) return "sprzedane";
if ($item['isAvailable'] < 1) return "sprzedane sisd";
if ($item['hasPhotoPrimary'] < 1 || $item['hasPhotos'] < 1) return "brak zdjec";
if($item['isEligible'] == 1) return "gotowe do wystawiania";
return null;
}
//
// /**
// * @Route("/api/login_check", name="login-check", methods={"POST"})
// * @return JsonResponse
// */
// public function getTokenUser(): JsonResponse
// {
// return new JsonResponse(['token' => 'TOKEN']);
// }
}