<?php
namespace App\Controller;
use App\Entity\ObjectAvanti;
use App\Repository\AuctionBidRepository;
use App\Repository\FavoriteRepository;
use App\Schemas\MyLastBidSchema;
use App\Schemas\ObjectSchema;
use App\Service\Api\Avanti\CustomerService;
use App\Service\Customer\CustomerService as DbCustomerService;
use App\Service\Api\Avanti\ObjectService;
use DateTime;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\AdapterInterface as Cache;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @Route ("", name="object_")
*/
class ObjectController extends BaseController
{
/**
* @Route ("/object/findById", name="getObjectById")
*
* @throws \Exception
*/
public function getObjectById(ObjectService $objectService, Request $request): Response
{
$dataParams = $this->getData($request, ['id'], 'fields');
$data = $objectService->getObjectById((int) $dataParams['fields']['id'], false);
if (!$data) {
return new JsonResponse([]);
}
$object = new ObjectAvanti();
if (!empty($data)) {
$object->mapping($data);
}
if ($actualCurrencyEur = $objectService->getExchangeEur()) {
$object->setCurrentEurPrice($actualCurrencyEur['nok']);
}
$result = $this->getEncoder($object, [], ObjectAvanti::class, ObjectSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/object/goingtoauction", name="goingtoauction")
*/
public function goingtoauction(ObjectService $objectService, Request $request): Response
{
$data = $this->getData($request, [], 'filter');
$data['size'] ??= 8;
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '>',
'date' => date('Y-m-d H:i:s'),
];
$data['filter']['onlyAvailable'] = true;
$data['filter']['countCategories'] = true;
$data['filter']['department_id'] = [ObjectAvanti::AVANTI_DEPARTMENT_ONLINE, ObjectAvanti::AVANTI_DEPARTMENT_CLASSIC];
$data['sort'] = 'OnlineClassicStart';
$data['direction'] = 'DESC';
if (date('H') < 9) {
$startDate = new DateTime('yesterday');
$endDate = new DateTime();
} else {
$startDate = new DateTime();
$endDate = new DateTime('tomorrow');
}
$startDate->setTime(9,0,0);
$endDate->setTime(8,59,59);
$data['filter']['betweenDate'] = [
'field' => 'Start',
'start' => $startDate->format('Y-m-d H:i:s'),
'finish' => $endDate->format('Y-m-d H:i:s'),
];
$objects = $objectService->getObjectSearch($data);
$result = [];
if (!is_null($objects) && property_exists($objects, 'data')) {
$objectArray = [];
foreach ($objects->data as $obj) {
$object = new ObjectAvanti();
array_push($objectArray, $object->mapping($obj));
}
$result = $this->getEncoder($objectArray, $this->getMeta($objects->paginate ?? null, $data['sort'], $data['direction'], $objects->aggregations ?? null), ObjectAvanti::class, ObjectSchema::class);
$result = json_decode($result);
}
return new JsonResponse($result);
}
/**
* @Route ("/object/endingauction", name="endingauction")
*/
public function endingauction(ObjectService $objectService, Request $request): Response
{
$data = $this->getData($request, [], 'filter');
$data['size'] ??= 8;
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '>',
'date' => date('Y-m-d H:i:s'),
];
$data['filter']['isNettauksjon'] = true;
$data['filter']['countCategories'] = true;
$data['filter']['department_id'] = [ObjectAvanti::AVANTI_DEPARTMENT_ONLINE];
$data['sort'] = 'Slutt';
$data['direction'] = 'ASC';
$objects = $objectService->getObjectSearch($data);
$result = [];
if (!is_null($objects) && property_exists($objects, 'data')) {
$objectsDate = new DateTime($objects->data[0]->Slutt);
$data['filter']['betweenDate'] = [
'field' => 'Slutt',
'start' => $objectsDate->format('Y-m-d') . ' 00:00:00',
'finish' => $objectsDate->format('Y-m-d') . ' 23:59:59',
];
$objects = $objectService->getObjectSearch($data);
$objectArray = [];
foreach ($objects->data as $obj) {
$object = new ObjectAvanti();
array_push($objectArray, $object->mapping($obj));
}
$result = $this->getEncoder($objectArray, $this->getMeta($objects->paginate ?? null, $data['sort'], $data['direction'], $objects->aggregations ?? null), ObjectAvanti::class, ObjectSchema::class);
$result = json_decode($result);
}
return new JsonResponse($result);
}
/**
* @Route ("/object/getObjectSold", name="getObjectSold")
*/
public function getObjectSold(ObjectService $objectService, Request $request, FavoriteRepository $favoriteRepository, UserInterface $customer = null): Response
{
$data = $this->getData($request, [], 'filter');
$data['size'] ??= 8;
$data['filter']['countCategories'] = true;
$data['filter']['onlySold'] = true;
$data['filter']['onlyAvailable'] = false;
$data['filter']['showObjectStartFuture'] = true;
$data['sort'] = $data['sort'] ?? 'CurrentEndDate';
$data['direction'] = $data['direction'] ?? 'DESC';
$objects = $objectService->getObjectSearch($data);
if (!isset($objects->data) or (null == $objects && null == $objects->data)) {
return new JsonResponse([]);
}
$favoriteIds = [];
if ($customer) {
$favoriteIds = array_flip($favoriteRepository->listIDsByCustomer($customer->getId()));
}
$objectArray = [];
foreach ($objects->data as $obj) {
$obj->favorite = isset($favoriteIds[$obj->Objektid]);
$object = new ObjectAvanti();
array_push($objectArray, $object->mapping($obj));
}
$result = $this->getEncoder($objectArray, $this->getMeta($objects->paginate ?? null, $data['sort'], $data['direction'], $objects->aggregations ?? null), ObjectAvanti::class, ObjectSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/object/getObjectPhotos", name="getObjectPhotos")
*/
public function getObjectPhotos(ObjectService $objectService, Request $request): Response
{
$dataParams = $this->getData($request, ['objectNo'], 'fields');
$size = $dataParams['fields']['size'] ?? null;
$data = $objectService->getFotowarePhotos($dataParams['fields']['objectNo'], $size);
$result = ['data' => $data];
return new JsonResponse($result);
}
/**
* @Route ("/object/findobject", name="findObject")
*
* @throws \Exception
*/
public function findObject(ObjectService $objectService, Request $request, FavoriteRepository $favoriteRepository, UserInterface $customer = null)
{
$data = $this->getData($request, [], 'filter');
if (null == $data['sort']) {
if (isset($data['filter']['isNettauksjon']) && 'false' === $data['filter']['isNettauksjon']) {
$data['sort'] = 'Katalognr';
} else {
$data['sort'] = 'OnlineClassicSlutt';
}
}
if (null == $data['direction']) {
$data['direction'] = 'ASC';
}
if (!isset($data['filter']['auction_id'])) {
if (isset($data['filter']['recently_sold']) and 'true' == $data['filter']['recently_sold']) {
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '<',
'date' => date('Y-m-d H:i:s'),
];
} else {
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '>',
'date' => date('Y-m-d H:i:s'),
];
}
} else {
$data['filter']['onlyAvailable'] = false;
}
$object = $objectService->getObjectSearch($data);
if (!isset($object->data)) {
return new JsonResponse(['meta' => [], 'data' => []]);
}
$favoriteIds = [];
if ($customer) {
$favoriteIds = array_flip($favoriteRepository->listIDsByCustomer($customer->getId()));
}
$objectArray = [];
foreach ($object->data as $obj) {
$objectAvanti = new ObjectAvanti();
$obj->favorite = isset($favoriteIds[$obj->Objektid]);
$objectArray[] = $objectAvanti->mapping($obj);
}
$result = $this->getEncoder($objectArray, $this->getMeta($object->paginate ?? null, $data['sort'], $data['direction'], $object->aggregations ?? null), ObjectAvanti::class, ObjectSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/api/admin/object/updateImage/{object_id}", name="updateImage", methods={"POST"})
*
* @throws \Exception
*/
public function updateImage(ObjectService $objectService, Request $request)
{
$objectId = $request->attributes->get('object_id');
$objectService->updateImageObject($objectId);
return new JsonResponse(['success' => true]);
}
/**
* @Route ("/object/getshippingtype", name="getShippingType")
*/
public function getShippingType(ObjectService $objectService, Request $request, Cache $cache)
{
$dataParams = $this->getData($request, ['objectId'], 'fields');
$cacheItem = $cache->getItem(__FUNCTION__ . http_build_query($dataParams));
$cacheItem->expiresAfter(3600);
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
$data = $objectService->getShippingType($dataParams['fields']['objectId'], $dataParams['fields']['zipCode'] ?? null);
$result = ['data' => $data];
$cacheItem->set(new JsonResponse($result));
$cache->save($cacheItem);
return $cacheItem->get();
}
/**
* @Route ("/object/searchobject", name="searchObject")
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function searchObject(ObjectService $objectService, Request $request)
{
$data = $this->getData($request, [], 'filter');
if (null == $data['sort']) {
$data['sort'] = 'Objektid';
}
if (null == $data['direction']) {
$data['direction'] = 'ASC';
}
$object = $objectService->getObjectSearchPreview($data);
return new JsonResponse(['data' => ['categories' => $object]]);
}
/**
* @Route ("/object/searchcomplete", name="searchComplete")
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function searchComplete(ObjectService $objectService, Request $request)
{
$data = $this->getData($request, [], 'filter');
$data['filter']['onlyAvailable'] = false;
$search = $objectService->getObjectSearch($data);
$objects = [];
foreach ($search->data as $object) {
$objects[] = $object->title;
}
return new JsonResponse(['data' => array_values(array_unique($objects, SORT_REGULAR))]);
}
/**
* @Route ("/object/getPopularCategories", name="getPopularCategories")
*/
public function getPopularCategories(ObjectService $objectService, Request $request): Response
{
$data = $objectService->getPopularCategories();
$result = ['data' => $data];
return new JsonResponse($result);
}
/**
* @Route ("/api/object/registerAdvanceBid", name="registerAdvanceBid", methods={"POST"})
*/
public function registerAdvanceBid(ObjectService $objectService, Request $request, CustomerService $customerService): Response
{
$data = $this->getData($request, ['object_id', 'value']);
$objectService->registerAdvanceBid($this->getUser(), $data['attributes']['object_id'], $data['attributes']['value'], $customerService);
return new JsonResponse([]);
}
/**
* @Route ("/api/object/registerPhoneBid", name="registerPhoneBid", methods={"POST"})
*/
public function registerPhoneBid(ObjectService $objectService, Request $request, CustomerService $customerService): Response
{
$data = $this->getData($request, ['object_id', 'message']);
$objectService->registerPhoneBid($this->getUser(), $data['attributes']['object_id'], $data['attributes']['message'], $customerService);
return new JsonResponse([]);
}
/**
* @Route ("/object/getStorageFee", name="getStorageFee")
*/
public function getStorageFee(ObjectService $objectService, Request $request)
{
$dataParams = $this->getData($request, ['objectNo'], 'fields');
$data = $objectService->getStorageFee($dataParams['fields']['objectNo']);
$result = ['data' => $data];
return new JsonResponse($result);
}
/**
* @Route ("/api/object/mylastbids", name="object_mylastbids")'
*
* @throws \Exception
*/
public function mylastbids(ObjectService $objectService, Request $request, AuctionBidRepository $auctionBidRepository, UserInterface $customer): Response
{
$requestData = $this->getData($request, [], 'filter');
$data['page'] = $requestData['page'];
$data['size'] = $requestData['size'];
$data['sort'] = $requestData['sort'] ?? 'Slutt';
$data['direction'] = $requestData['direction'] ?? 'DESC';
$data['filter'] = $requestData['filter'] ?? [];
$objects = $auctionBidRepository->getMyBidsObjectsIds($customer);
if (!$objects) {
return new JsonResponse([]);
}
$data['filter']['ObjectId'] = implode(',', array_column($objects, 'object_id'));
if (isset($requestData['filter']['active_auction'])) {
if ($requestData['filter']['active_auction']) {
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '>',
'date' => date('Y-m-d H:i:s'),
];
$data['sort'] = $requestData['sort'] ?? 'Slutt';
$data['direction'] = $requestData['direction'] ?? 'ASC';
} else {
$data['filter']['whereDate'] = [
'field' => 'Slutt',
'operation' => '<',
'date' => date('Y-m-d H:i:s'),
];
}
}
$object = $objectService->getObjectSearch($data);
if (!isset($object->data[0])) {
return new JsonResponse([]);
}
$objectArray = [];
foreach ($object->data as $objectData) {
$objectAvanti = new ObjectAvanti();
$objectAvanti->mapping($objectData);
$auction = array_values(array_filter($objects, function ($object) use ($objectAvanti) {
return $object['object_id'] == $objectAvanti->getObjectId();
}));
if (!isset($auction[0]['auction_id'])) {
continue;
}
$lastBid = $auctionBidRepository->getLastBid($auction[0]['auction_id'], $objectAvanti->getObjectId());
$mylastBid = $auctionBidRepository->getMyLastBid($customer, $auction[0]['auction_id'], $objectAvanti->getObjectId());
if ($lastBid) {
$objectAvanti->setWinningAuction($customer->getId() == $lastBid->getObjectCustomer()->getCustomer()->getId());
$objectAvanti->setMyBid($mylastBid->getValue() ?? null);
$objectAvanti->setObjectCustomerId($mylastBid->getObjectCustomer()->getId());
} else {
$objectAvanti->setWinningAuction(false);
}
$objectArray[] = $objectAvanti;
}
$result = $this->getEncoder($objectArray, $this->getMeta($object->paginate ?? null, $data['sort'], $data['direction'], $object->aggregations ?? null), ObjectAvanti::class, MyLastBidSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/api/object/cutprice/{id}", name="cutPrice")
*
* @throws \Exception
*/
public function cutPrice(ObjectService $objectService, Request $request): Response
{
$dataParams = $this->getData($request, ['value']);
$object_id = $request->attributes->get('id');
$value = $dataParams['attributes']['value'];
$data = $objectService->cutPrice($object_id, $value, true);
$object = new ObjectAvanti();
if (!empty($data)) {
$object->mapping($data);
}
$result = $this->getEncoder($object, [], ObjectAvanti::class, ObjectSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/object/objectpreview", name="objectpreview")
*
* @throws \Exception
*/
public function objectPreview(ObjectService $objectService, Request $request): Response
{
$dataParams = $this->getData($request, ['objectNo'], 'fields');
$data['filter']['q'] = $dataParams['fields']['objectNo'];
$data['filter']['onlyAvailable'] = false;
$data['filter']['shouldSkipNettauksjon'] = true;
$objectResult = $objectService->getObjectSearch($data);
if (!isset($objectResult->data[0])) {
return new JsonResponse([]);
}
$object = new ObjectAvanti();
$object->mapping($objectResult->data[0]);
if ($actualCurrencyEur = $objectService->getExchangeEur()) {
$object->setCurrentEurPrice($actualCurrencyEur['nok']);
}
$result = $this->getEncoder($object, [], ObjectAvanti::class, ObjectSchema::class);
return new JsonResponse(json_decode($result));
}
/**
* @Route ("/api/admin/object/update-enddate", name="NettobjektUpdate", methods={"PUT"})
*
* @throws \Exception
*/
public function updateObjectEndDate(ObjectService $objectService, Request $request)
{
try {
$idsUpdated = [];
$content = json_decode($request->getContent(), true);
if(isset($content['objects'])){
$objectSlutts = $content['objects'];
$idsUpdated = $objectService->updateEndDate($objectSlutts);
}
return new JsonResponse(['success' => true, 'ids'=> $idsUpdated]);
} catch (\Throwable $th) {
return new JsonResponse(['success' => false, 'ids'=> null, 'error' => $th->getMessage()], 400);
}
}
/**
* @Route ("/api/admin/object/clear-cache", name="ClearObjectCaches", methods={"POST"})
*
* @throws \Exception
*/
public function clearObjectCaches(ObjectService $objectService, Request $request)
{
try {
$data = json_decode($request->getContent(), true);
foreach ($data['objects'] ?? [] as $object_id) {
$objectService->deleteObjectCache($object_id);
}
return new JsonResponse(['success' => true]);
} catch (\Throwable $th) {
return new JsonResponse(['success' => false, 'error' => $th->getMessage()], 400);
}
}
/**
* @Route ("/api/admin/object/send-advance-bid-notification", name="sendAdvanceBidNotification", methods={"POST"})
*/
public function sendAdvanceBidNotification(ObjectService $objectService, Request $request, DbCustomerService $customerService): Response
{
$data = $this->getData($request, ['customer_number', 'object_id', 'value']);
$objectService->sendAdvanceBidNotification($customerService->getCustomerByCustomerNumberOrCreate($data['attributes']['customer_number']), $data['attributes']['object_id'], $data['attributes']['value']);
return new JsonResponse([]);
}
/**
* @Route ("/api/admin/object/send-phone-bid-notification", name="sendPhoneBidNotification", methods={"POST"})
*/
public function sendPhoneBidNotification(ObjectService $objectService, Request $request, DbCustomerService $customerService): Response
{
$data = $this->getData($request, ['customer_number', 'object_id', 'message']);
$objectService->sendPhoneBidNotification($customerService->getCustomerByCustomerNumberOrCreate($data['attributes']['customer_number']), $data['attributes']['object_id'], $data['attributes']['message'], $customerService);
return new JsonResponse([]);
}
/**
* @Route ("/api/admin/object/send-manual-start-storage-notification", name="sendManualStartStorageNotification", methods={"POST"})
*/
public function sendManualStartStorageNotification(ObjectService $objectService, Request $request, DbCustomerService $customerService): Response
{
$data = $this->getData($request, ['customer_number', 'object_id']);
$objectService->sendManualStartStorageNotification($customerService->getCustomerByCustomerNumberOrCreate($data['attributes']['customer_number']), $data['attributes']['object_id']);
return new JsonResponse([]);
}
}