<?php
/**
* Created by PhpStorm.
* User: parcel
* Date: 10/26/18
* Time: 3:19 AM
*/
namespace App\Api;
use App\Controller\SendSms;
use App\Entity\CollectedParcel;
use App\Entity\OrganizationUser;
use App\Entity\Parcel;
use App\Entity\Sms;
use App\Entity\UserStation;
use App\Entity\WayBill;
use App\Form\CollectionForm;
use App\Service\ActionMatrix;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use Exception;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\ConstraintViolation;
use FOS\RestBundle\Controller\Annotations as Rest;
class CollectionController extends AbstractFOSRestController {
private ObjectManager $em;
private LoggerInterface $logger;
private MessageBusInterface $messageBus;
private ActionMatrix $actionMatrix;
public function __construct(LoggerInterface $logger, ManagerRegistry $managerRegistry, MessageBusInterface $messageBus){
$this->logger = $logger;
$this->em = $managerRegistry->getManager();
$this->messageBus = $messageBus;
}
/**
* @Rest\Post("/collection/parcels", name="receivedParcelList_")
*/
public function getReceivedParcels(Request $request){
$content = $request->getContent();
// [2019-10-08 12:00:36] app.INFO: {"origin":0,"search":"","search_parameter":""} [] []
$data = json_decode($content, true);
// dump($data['receiver']); die;
$searchParameter = null;
$search = null;
$origin = null;
if(isset($data['origin']) && $data['origin'] !== 0){
$origin = $data['origin'];
}
if(isset($data['search_parameter']) && isset($data['search'])){
$searchParameter = $data['search_parameter'];
$search = $data['search'];
}
$em = $this->em;
$userStation = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
], ['id' => 'DESC']);
$parcels = $em->getRepository(WayBill::class)->findReceivedWaybillsRawSql(
$userStation->getStation()->getId(), $origin, $searchParameter, $search
);
return new JsonResponse($parcels, Response::HTTP_OK);
}
/**
* @Rest\Post("/collections", name="collectorDetailsfd_")
*/
public function makeCollection(Request $request): JsonResponse
{
$em = $this->em;
$content = $request->getContent();
$data = json_decode($content, true);
// {"collector_name":"GEORGE IKAHU","consignee_national_id":"5255418855","id":0,"is_consignee":true,"national_id":"5255418855","waybill_id":62}
// {"collector_name":"evelyn karu","consignee_national_id":"27787431","id":0,"is_consignee":true,"national_id":"27787431","waybill_id":252587}
$this->logger->debug('COLLECTION '.$content);
$consigneeId = null;
$collectorName = null;
$collectorNationalId = null;
$waybillId = null;
$isConsignee = false;
if(isset($data['consignee_national_id'])
&& isset($data['collector_name'])
&& isset($data['national_id'])
&& isset($data['waybill_id'])
&& isset($data['is_consignee']) ){
$waybillId = $data['waybill_id'];
$collectorName = $data['collector_name'];
$collectorNationalId = $data['national_id'];
$consigneeId = $data['consignee_national_id'];
$isConsignee = $data['is_consignee'];
$waybill = $em->getRepository(WayBill::class)->findOneBy([
'id' => $waybillId
]);
if(!$waybill){
$data = [
'error' => 'Waybill not found'
];
return new JsonResponse($data, Response::HTTP_NOT_FOUND);
}else if($waybill->getIsCollected()){
$data = [
'error' => 'Waybill found but is collected'
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
}else{
$data = [
'error' => 'Please fill in all fields for collection'
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$waybill->setIsCollected(true);
$collectedParcel = new CollectedParcel();
$collectedParcel->setCollectorName($collectorName);
$collectedParcel->setConsigneeNationalId($consigneeId);
$collectedParcel->setWaybill($waybill);
$collectedParcel->setCreatedAt(new DateTime());
$collectedParcel->setCreatedBy($this->getUser());
$collectedParcel->setIsConsignee($isConsignee);
$collectedParcel->setNationalId($collectorNationalId);
try{
$em->persist($collectedParcel);
$em->flush();
$data = [
'message'=> 'saved successfully'
];
$this->actionMatrix = new ActionMatrix($this->messageBus,$this->em,$waybill);
$this->actionMatrix->collectingAction($this->getUser());
return new JsonResponse($data, Response::HTTP_CREATED);
} catch (Exception $e){
$message = [
'error'=>"could not save collector information",
"data" =>$collectedParcel
];
// $view = $this->view($message, Response::HTTP_EXPECTATION_FAILED);
// return $view;
return new JsonResponse($message, Response::HTTP_OK );
}
}
/**
* @Rest\Post("/parcels/collect/parcel/{id}", name="collectOneParcel")
*/
public function receiveParcel($id, Request $request) {
$em = $this->getDoctrine()->getManager();
/** @var Parcel $parcel */
$parcel = $em->getRepository(Parcel::class)->findOneBy([
'id' => $id
]);
if(!$parcel) {
$data = [
'error' => 'Parcel does not exist'
];
// return $this->view($data, Response::HTTP_NOT_FOUND);
return new JsonResponse($data, Response::HTTP_NOT_FOUND);
}
if(!$parcel->getWaybill()->getisReceived()){
$data = [
'error' => "THIS PARCEL FROM {$parcel->getWaybill()->getFromStation()} HAS NOT BEEN RECEIVED"
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
if($parcel->getWaybill()->getIsCollected()){
$data = [
'error' => 'THIS PARCEL HAS ALREADY BEEN COLLECTED'
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
/** @var UserStation $user */
$user = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
],['id' => 'DESC']);
if($parcel->getWaybill()->getToStation()->getId() != $user->getStation()->getId()){
$data = [
'error' => 'You are not logged in from '.$parcel->getWaybill()->getToStation()->getStationName()
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$content = $request->getContent();
$data = json_decode($content, true);
$p = new Parcel();
$form = $this->createForm(CollectionForm::class, $p,[
'validation_groups' => [
'collection'
]
]);
$form->submit($data);
// dump($data); die;
$validator = $this->get('validator');
/** @var $errors*/
$errors = $validator->validate($p, null, ["collection"]);
// dump($collectParcel);die;
if(count($errors) > 0){
$fields = array();
/** @var $error ConstraintViolation */
foreach ($errors as $key => $error){
$fields[$error->getPropertyPath()] = $error->getMessage();
}
$data = [
'error' => 'Please check this fields for errors',
'fields' => $fields
];
// $view = $this->view($data, Response::HTTP_BAD_REQUEST);
//
// return $view;
return new JsonResponse($data, Response::HTTP_BAD_REQUEST);
}
// dump($collectParcel);die;
/** @var OrganizationUser $organization */
$organization = $em->getRepository('AppBundle:OrganizationUser')->findOneBy([
'user' => $this->getUser()
]);
if(!$parcel->getisEnRoute()){
$data = [
'error' => "THIS PARCEL HAS NOT BEEN LOADED TO VEHICLE"
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
if(!$parcel->getWaybill()->getIsReceived()){
$data = [
'error' => "THIS PARCEL HAS NOT BEEN RECEIVED YET"
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$parcel->setCollectedAt(new \DateTime());
$parcel->setCollectedOfficerBy($this->getUser());
$parcel->setIsCollected(true);
$parcel->setCollectorNationalId($p->getCollectorNationalId());
try{
$smsMessage = new Sms();
$smsMessage->setTransaction($parcel->getWaybill()->getTransaction());
$smsMessage->setRecepient($parcel->getWaybill()->getSenderPhoneNumber());
$smsMessage->setCreatedAt(new \DateTime());
$smsMessage->setCreatedBy($this->getUser());
$smsMessage->setSms("HELLO {$parcel->getWaybill()->getSenderName()} 1 OF THE PARCELS YOU SENT TO {$parcel->getWaybill()->getReceiverName()} IN {$parcel->getWaybill()->getToStation()->getStationName()} FROM {$parcel->getWaybill()->getFromStation()->getStationName()} HAS BEEN COLLECTED BY {$parcel->getWaybill()->getReceiverName()}");
$smsMessage->setOrganization($organization->getOrganization());
$sms = new SendSms();
$smsMessage = $sms->sendSms($smsMessage);
$em->persist($smsMessage);
$em->flush();
// $view = $this->view($parcel->getWaybill(), Response::HTTP_CREATED);
//
// return $view;
return new JsonResponse($parcel->getWaybill(), Response::HTTP_CREATED);
} catch (\PDOException $e){
// $view = $this->view($parcel->getWaybill(), Response::HTTP_EXPECTATION_FAILED);
//
// return $view;
return new JsonResponse($parcel->getWaybill(), Response::HTTP_EXPECTATION_FAILED);
}
}
}