<?php
/**
* Created by PhpStorm.
* User: parcel
* Date: 8/28/18
* Time: 2:47 AM
*/
namespace App\Api;
use App\Controller\SendSms;
use App\Entity\DailyAccount;
use App\Entity\Delivery;
use App\Entity\DeliveryParcel;
use App\Entity\Etr;
use App\Entity\Mpesa;
use App\Entity\MpesaAuth;
use App\Entity\MpesaTransaction;
use App\Entity\Organization;
use App\Entity\Parcel;
use App\Entity\ReceivedParcel;
use App\Entity\Station;
use App\Entity\StationDailyAccount;
use App\Entity\TimsStation;
use App\Entity\Transaction;
use App\Entity\UserStation;
use App\Entity\Vehicle;
use App\Entity\WayBill;
use App\Form\api\ApiWayBillForm;
use App\Form\CollectionForm;
use App\Form\ParcelForm;
use App\Form\WayBillForm;
use App\Service\TremolInitiator;
use DateTime;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerBuilder;
use Mpdf\Mpdf;
use Mpdf\QrCode\Output\Png;
use Mpdf\QrCode\QrCode;
use PDOException;
use Psr\Log\LoggerInterface;
use Sasedev\MpdfBundle\Factory\MpdfFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\ConstraintViolation;
class ParcelController extends AbstractController
{
private ObjectManager $em;
private LoggerInterface $logger;
public function __construct(ManagerRegistry $managerInterface, LoggerInterface $logger)
{
$this->em = $managerInterface->getManager();
$this->logger = $logger;
}
/**
* @Rest\Route("/parcels/new", methods={"POST"}, name="app_register_parcel_api_")
* @param Request $request
*/
public function registerParcel(Request $request)
{
$waybill = new WayBill();
$waybill->setLatitude(0);
$waybill->setLongitude(0);
$waybill->setParcelValue(1);
$em = $this->em;
$organization = $em->getRepository(Organization::class)->findOneBy([
'id' => $request->getSession()->get('ORGANIZATION')
]);
$serializer = SerializerBuilder::create()->build();
$context = new SerializationContext();
$context->setSerializeNull(true);
$waybill->setOrganization($organization);
$waybill->setParcelValue(0);
$body = $request->getContent();
$data = json_decode($body, true);
$this->logger->debug($body);
$form = $this->createForm(ApiWayBillForm::class, $waybill, [
'csrf_protection' => false
]);
$form->submit($data);
/** @var UserStation $userStation */
$userStation = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser(),
'isActive' => true
], ['id' => 'DESC']);
$date = new \DateTime();
$stringDate = $date->format('Y-m-d');
$dailyId = $em->getRepository(DailyAccount::class)->getMyAccount($userStation->getUser()->getId());
$dailyAccount = null;
if($dailyId) {
$dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
'id' => $dailyId
]);
}
// return new JsonResponse($dailyId, Response::HTTP_FOUND);
if ($waybill->getToStation()->getId() === $userStation->getStation()->getId()) {
$data = [
'message' => 'Origin Station and Destination Station cannot be the same'
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
if (!$dailyAccount) {
$availableDailyAccount = $this->em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser(),
'isClosed' => false,
], ['id' => 'DESC']);
if ($availableDailyAccount) {
$data = [
'message' => 'Please close your previous daily account to proceed ...'
];
$this->logger->debug($data['message']);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
/** @var StationDailyAccount $stationDailyAccount */
$stationDailyAccount = $em->getRepository(StationDailyAccount::class)->findOneBy([
'station' => $request->getSession()->get('STATION'),
'accountDate' => $date
], ['id' => 'DESC']);
if (!$stationDailyAccount) {
$stationDailyAccount = new StationDailyAccount();
$stationDailyAccount->setAccountDate($date);
$stationDailyAccount->setCreatedAt($date);
$stationDailyAccount->setIsClosed(false);
$stationDailyAccount->setIsBanked(false);
$stationDailyAccount->setCreatedBy($this->getUser());
$stationDailyAccount->setStation($userStation->getStation());
$em->persist($stationDailyAccount);
}
$dailyAccount = new DailyAccount();
$dailyAccount->setIsClosed(false);
$dailyAccount->setCreatedAt($date);
$dailyAccount->setAccountDate($date);
$dailyAccount->setUser($this->getUser());
$dailyAccount->setStationDailyAccount($stationDailyAccount);
$dailyAccount->setDrawerCash(0);
$em->persist($dailyAccount);
$em->flush();
}
if ($form->isValid()) {
$waybill->setCreatedAt(new \DateTime());
$waybill->setCreatedBy($this->getUser());
$waybill->setFromStation($userStation->getStation());
$waybill->setIsCollected(false);
$waybill->setPercelCount(count($waybill->getParcels()));
$waybill->setIsCollected(false);
$waybill->setIsReceived(false);
$waybill->addTransaction($dailyAccount);
foreach ($waybill->getParcels() as $key => $item) {
$waybill->getParcels()->get($key)->setNumber($key + 1);
}
$conn = $em->getConnection();
$conn->beginTransaction();
try {
$em->persist($waybill);
$em->flush();
$em->getConnection()->commit();
$this->logger->debug("waybill_id " . $waybill->getId());
$data = $serializer->serialize($waybill, 'json', $context);
return new Response($data, Response::HTTP_CREATED);
} catch (PDOException $e) {
$em->getConnection()->rollBack();
$data = [
'message' => 'An Error Occurred Please check whether every thing is filled'
];
return new JsonResponse($data, Response::HTTP_NOT_ACCEPTABLE);
}
}else{
$errorp = '';
foreach ($form->getErrors() as $index => $error) {
$this->logger->debug($error);
$errorp = $error;
}
$data = [
'message' => 'some error occurred contact admin form not valid '.$errorp
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$errorp = '';
foreach ($form->getErrors() as $index => $error) {
$this->logger->debug($error);
$errorp = $error;
}
$data = [
'message' => 'some error occurred contact admin '.$errorp
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
/**
* @Rest\Route("/parcels/receipt/g03/{waybill_}/{pay_method}", methods={"GET"},name="receipt_action_tremol_api")
*/
public function ReceiptGO3Action(Request $request, $waybill_, $pay_method, MpdfFactory $MpdfFactory): Response
{
$em = $this->em;
$userStation = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
]);
$timsStation = $em->getRepository(TimsStation::class)->findOneBy([
'station' => $userStation->getStation()
]);
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $waybill_
]);
if (!$transaction->getIsPaid()) {
$transaction->setIsComplete(true);
$transaction->setPaymentMethod($pay_method);
$transaction->setIsPaid(true);
if ($pay_method === 'CASH') {
$transaction->setCashAmount($transaction->getAmount());
}else if ($pay_method === 'MPESA') {
$transId = $request->get('transaction_id');
$mpesa = $this->em->getRepository(Mpesa::class)->findOneBy([
'transactionId' => $transId
]);
$mpesaTransaction = new MpesaTransaction();
$mpesaTransaction->setTransaction($transaction);
$mpesaTransaction->setMpesa($mpesa);
$mpesaTransaction->setCreatedAt(new DateTime());
$mpesaTransaction->setCreatedBy($this->getUser());
$this->em->persist($mpesaTransaction);
$mpesa->setIsUsed(true);
$transaction->setMpesaAmount($transaction->getAmount());
}
if (!$timsStation) {
$em->flush();
return $this->generateReceipt($transaction, $MpdfFactory);
}
if ($timsStation->getSupplierCode() !== 'TREMOL' ) {
$em->flush();
return $this->generateReceipt($transaction, $MpdfFactory);
}else {
$t= $this->generateCuInvoiceNumber($transaction);
$this->em->flush();
return $this->generateReceipt($t, $MpdfFactory);
}
} else {
if ($pay_method === 'MPESA') {
$transId = $request->get('transaction_id');
$mpesa = $this->em->getRepository(Mpesa::class)->findOneBy([
'transactionId' => $transId
]);
if($mpesa->getTransactionAmount() !== $transaction->getAmount()){
$data = [
'message' => 'Mpesa Amount should be equal to cost of service'
];
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$mpesaTransaction = new MpesaTransaction();
$mpesaTransaction->setTransaction($transaction);
$mpesaTransaction->setMpesa($mpesa);
$mpesaTransaction->setCreatedAt(new DateTime());
$mpesaTransaction->setCreatedBy($this->getUser());
$this->em->persist($mpesaTransaction);
$mpesa->setIsUsed(true);
$transaction->setPaymentMethod($pay_method);
$transaction->setMpesaAmount($transaction->getAmount());
$transaction->setCashAmount(0);
$this->em->flush();
}
$receiptType = 'FISCAL RECEIPT COPY';
return $this->generateReceipt($transaction, $MpdfFactory, $receiptType);
}
}
private function generateReceipt(Transaction $transaction, MpdfFactory $MpdfFactory, $receipt=null ): Response
{
$receiptType = $receipt?:'FISCAL RECEIPT';
$mpesa = null;
if ($transaction->getPaymentMethod() == 'MPESA') {
$mpesa = $this->em->getRepository(MpesaTransaction::class)->findOneBy([
'transaction' => $transaction
]);
}
/** @var WayBill $waybill */
$waybill = $transaction->getWaybill();
$parcels = $this->em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
// get the logo image and change it to base64
$logoImage = file_get_contents('../public/logo.png');
$logoBase64 = base64_encode($logoImage);
$html='';
if ($transaction->getCuInvoiceNumber()) {
// create TIMS QRCODE change it to base64;
$timsQRCode = 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' . $transaction->getCuInvoiceNumber();
$timsqrCode = new QrCode($timsQRCode);
$output = new Png();
$timsQRCodeData = $output->output($timsqrCode, 100, [255, 255, 255], [0, 0, 0]);
$base64 = base64_encode($timsQRCodeData);
$html = $this->renderView('fos/parcels/receipt/receipt_g03_pdf_mobile.html.twig', [
'waybill' => $waybill,
'transaction' => $transaction,
'parcels' => $parcels,
'mpesa' => $mpesa,
'qrcode' => $base64,
'logoBase64' => $logoBase64,
'timsInvoiceNumber' => $transaction->getCuInvoiceNumber(),
'by' => $waybill->getCreatedBy()->getPerson(),
'receiptType' => $receiptType
]);
}else {
$html = $this->renderView('fos/parcels/receipt/receipt_g03_pdf_mobile.html.twig', [
'waybill' => $waybill,
'transaction' => $transaction,
'parcels' => $parcels,
'mpesa' => $mpesa,
'logoBase64' => $logoBase64,
'by' => $waybill->getCreatedBy()->getPerson(),
'receiptType' => $receiptType
]);
}
$mpdf = new Mpdf();
$height = $mpdf->_getHtmlHeight($html);
$this->logger->debug('HEIGHT ' . $height);
$mPdf = $MpdfFactory->createMpdfObject([
'mode' => 'utf-8',
'format' => [70, 230],
'orientation' => 'P',
'autoPageBreak' => true
]);
$mPdf->SetTopMargin("0");
$mpdf->margin_footer = 0;
$mPdf->WriteHTML($html);
return $MpdfFactory->createDownloadResponse($mPdf, "receipt_{$transaction->getWayBill()->getId()}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
}
private function generateCuInvoiceNumber(Transaction $transaction): ?Transaction
{
/** Check whether etr is available */
try {
$waybill = $transaction->getWaybill();
$parcels = $this->em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
/** @var Etr $etr */
$etr = $this->em->getRepository(Etr::class)->findOneBy([
'isDefault' => 1
]);
try {
$tremolInitiator = new TremolInitiator($this->em, $etr);
} catch (\Exception $e) {
dump($e);
}
$receiptType = 'FISCAL RECEIPT';
if ($transaction->getPinNumber()) {
TremolInitiator::$FP->OpenInvoiceWithFreeCustomerData(
'',
$transaction->getPinNumber(),
'',
'',
'',
'',
$waybill->getId()
);
} else {
TremolInitiator::$FP->OpenReceipt(1, $waybill->getId());
}
$parcelCount = $waybill->getPercelCount();
foreach ($parcels as $index => $parcel) {
TremolInitiator::$FP->SellPLUfromExtDB($parcel->getDescription(),
'A',
($transaction->getAmount() / $parcelCount),
'',
'',
'',
16.00,
1
);
}
$rec = TremolInitiator::$FP->CloseReceipt();
// var_dump($rec);
$invoiceNumber = $rec->InvoiceNum;
$transaction->setCuInvoiceNumber($invoiceNumber);
$transaction->setIsComplete(true);
$transaction->setIsPaid(true);
$transaction->setIsFinal(true);
$transaction->setCuSerialNumber($etr->getSerialNumber());
if ($transaction->getPaymentMethod() == 'CASH') {
$transaction->setCashAmount($transaction->getAmount());
}
if ($transaction->getPaymentMethod() == 'MPESA') {
$transaction->setMpesaAmount($transaction->getAmount());
}
return $transaction;
} catch (\Exception $e) {
}
return null;
}
/**
* @Rest\Route("/parcels", methods={"GET"}, name="app_my_transactions")
* @param Request $request
*/
public function getMyTransactions(Request $request): Response
{
$serializer = SerializerBuilder::create()->build();
$context = new SerializationContext();
$context->setSerializeNull(true);
$dailyAccount = $this->em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser(),
'isClosed' => false
], ['id' => 'desc']);
$waybills = $this->em->getRepository(WayBill::class)->findMyWaybill($dailyAccount);
$data = $serializer->serialize($waybills, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Rest\Route("/parcels/all", methods={"GET"}, name="app_all_my_transactions")
* @param Request $request
*/
public function getAllMyTransactions(Request $request): Response
{
$serializer = SerializerBuilder::create()->build();
$context = new SerializationContext();
$context->setSerializeNull(true);
$dailyAccount = $this->em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser(),
'isClosed' => false
], ['id' => 'desc']);
$userStation = $this->em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
],['id' => 'DESC']);
if($request->get('waybill')){
$waybill = $request->get('waybill');
$waybills = $this->em->getRepository(WayBill::class)->findAllMyWaybill($userStation->getStation()->getId(), $waybill );
}else{
$waybills = $this->em->getRepository(WayBill::class)->findAllMyWaybill($userStation->getStation()->getId());
}
$data = $serializer->serialize($waybills, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Rest\Route("/mpesa_transactions", methods={"GET"}, name="app_mpesa_transactions")
* @param Request $request
* @return Response
*/
public function getMpesaTransactions(Request $request): Response
{
$userStation = $this->em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
]);
$mpesaAuth = $this->em->getRepository(MpesaAuth::class)->findOneBy([
'station' => $userStation->getStation(),
'authType' => 'PROD'
]);
$transactions = $this->em->getRepository(Mpesa::class)->getTodaysTransactions($mpesaAuth->getPaybill());
return new JsonResponse($transactions, Response::HTTP_OK);
}
/**
* @Rest\Route("/data2", name="get_all_parcels_waybills_transactions_2")
* @param Request $request
*/
public function getData2(Request $request)
{
// $station_id, $waybill, $last_vehicle, $last_delivery_parcel_id, $last_delivery_id;
$station_id = $request->get("station_id");
$last_vehicle = $request->get("last_vehicle");
$waybill = $request->get("last_parcel_id");
$em = $this->getDoctrine()->getManager();
$vehicles = $em->getRepository(Vehicle::class)->findVehicles($last_vehicle);
// $waybills = $em->getRepository(WayBill::class)->findAllWaybills($station_id,$waybill);
$parcels = $em->getRepository(Parcel::class)->getAllParcelWaybills($station_id, $waybill);
/*$deliveries = $em->getRepository(Delivery::class)->findOutGoingDeliveries($station_id, $lastDelivery);
$deliveryParcels = $em->getRepository(DeliveryParcel::class)->outGoingDeliveryParcels($station_id, $lastDelivery);*/
$data = [
"vehicles" => $vehicles,
"parcels" => $parcels
];
// return $this->view($data, Response::HTTP_OK);
return new JsonResponse($data, Response::HTTP_OK);
}
/**
* @Rest\Route("/data", name="get_all_parcels_waybills_transactions")
* @param Request $request
*/
public function getData(Request $request): Response
{
// $station_id, $waybill, $last_vehicle, $last_delivery_parcel_id, $last_delivery_id;
$station_id = $request->get("station_id");
$last_vehicle = $request->get("last_vehicle");
$lastIDelivery = $request->get("last_id");
$waybill = $request->get("last_w");
$lastDelivery = $request->get("last_d");
$em = $this->getDoctrine()->getManager();
$vehicles = $em->getRepository(Vehicle::class)->findVehicles($last_vehicle);
$waybills = $em->getRepository(WayBill::class)->findAllWaybills($station_id, $waybill);
$parcels = $em->getRepository(Parcel::class)->getAllParcels($station_id, $waybill);
$deliveries = $em->getRepository(Delivery::class)->findOutGoingDeliveries($station_id, $lastDelivery);
$deliveryParcels = $em->getRepository(DeliveryParcel::class)->outGoingDeliveryParcels($station_id, $lastDelivery);
$incomingParcels = $em->getRepository(DeliveryParcel::class)->getIncomingParcels($station_id, $lastIDelivery);
$incomingDeliveries = $em->getRepository(Delivery::class)->findIncomingDeliveries($station_id, $lastIDelivery);
$incomingDeliveryParcels = $em->getRepository(DeliveryParcel::class)->deliveryIncomingParcels($station_id, $lastIDelivery);
$deliveryWaybills = $em->getRepository(DeliveryParcel::class)->findAllDeliveryWaybills($station_id, $lastIDelivery);
$data = [
"vehicles" => $vehicles,
"incoming_waybills" => $deliveryWaybills,
"incoming_parcels" => $incomingParcels,
"incoming_delivery_parcels" => $incomingDeliveryParcels,
"incoming_deliveries" => $incomingDeliveries,
"waybills" => $waybills,
"deliveries" => $deliveries,
"delivery_parcels" => $deliveryParcels,
"parcels" => $parcels
];
// return $this->view($data, Response::HTTP_OK);
return new JsonResponse($data, Response::HTTP_OK);
/*if(!$waybills){
if($vehicles){
$data = [
"vehicles" => $vehicles,
"incoming_waybills"=>$deliveryWaybills,
"waybills" => null,
"incoming_parcels" => null,
"deliveries" => $deliveries,
"delivery_parcels" => $deliveryParcels
];
return $this->view($data, Response::HTTP_OK);
}
if($deliveries){
$data = [
"incoming_waybills" => $deliveryWaybills,
"waybills" => $waybills,
"incoming_parcels" => $parcels,
"vehicles" => $vehicles,
"deliveries" => $deliveries,
"delivery_parcels" => $deliveryParcels
];
return $this->view($data, Response::HTTP_OK);
}
return $this->view(null, Response::HTTP_NO_CONTENT);
}else if($deliveries){
$data = [
"incoming_waybills" => $deliveryWaybills,
"waybills" => null,
"incoming_parcels" => $parcels,
"vehicles" => $vehicles,
"deliveries" => $deliveries,
"delivery_parcels" => $deliveryParcels
];
return $this->view($data, Response::HTTP_OK);
}
$data = [
"incoming_waybills" => $deliveryWaybills,
"waybills" => $waybills,
"incoming_parcels" => $parcels,
"vehicles" => $vehicles,
"deliveries" => $deliveries,
"delivery_parcels" => $deliveryParcels
];
return $this->view($data, Response::HTTP_OK);*/
}
/**
* @Rest\Route("/data/delivery/{station}/{delivery_number}", name="getOneParcel")
*/
public function getDelivery($station, $delivery_number)
{
$em = $this->getDoctrine()->getManager();
/** @var Delivery $delivery */
$delivery = $em->getRepository(Delivery::class)->findOneBy([
'id' => $delivery_number
]);
$incomingDelivery = $em->getRepository(Delivery::class)->findOneIncomingDelivery($delivery_number);
$incomingParcels = $em->getRepository(DeliveryParcel::class)->getOneDeliveryIncomingParcels($delivery_number);
$incomingDeliveryParcels = $em->getRepository(DeliveryParcel::class)->oneDeliveryIncomingParcels($delivery_number);
$deliveryWaybills = $em->getRepository(DeliveryParcel::class)->findAllOneDeliveryWaybills($delivery_number);
if ($incomingDelivery) {
if ($delivery->getDestination()->getId() != $station) {
$data = [
'error' => 'This delivery is meant for:' . $delivery->getDestination()->getStationName()
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$data = [
"incoming_waybills" => $deliveryWaybills,
"incoming_parcels" => $incomingParcels,
"incoming_delivery_parcels" => $incomingDeliveryParcels,
"incoming_deliveries" => $incomingDelivery,
];
// $context = new SerializationContext();
// $context->setSerializeNull(true);
// $serializer = SerializerBuilder::create()->build();
// [ DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s']
// $data = $serializer->serialize($data, 'json', $context );
// return $this->view($data, Response::HTTP_OK);
return new JsonResponse($data, Response::HTTP_OK);
} else {
$data = [
'error' => 'Delivery Number:' . $delivery_number . ' NOT FOUND'
];
// return $this->view($data, Response::HTTP_NOT_FOUND);
return new JsonResponse($data, Response::HTTP_NOT_FOUND);
}
}
/**
* @Rest\Route("/parcels/{station_id}/{waybill}", name="getOneWaybill")
* @param $station_id
* @param $waybill
* @return View
*/
public function getParcelCollection($station_id, $waybill)
{
$em = $this->getDoctrine()->getManager();
$resultWaybill = $em->getRepository(WayBill::class)->findReceivedWaybill($station_id, $waybill);
if (!$resultWaybill) {
// return $this->view(null, Response::HTTP_NOT_FOUND);
return new JsonResponse(null, Response::HTTP_NOT_FOUND);
}
/*$waybillParcels = $em->getRepository(Parcel::class)->getWaybillParcels($waybill);
if($waybillParcels){
$resultWaybill['parcels'] = $waybillParcels;
}*/
// return $this->view($resultWaybill, Response::HTTP_OK);
return new JsonResponse($resultWaybill, Response::HTTP_OK);
}
/**
* @Rest\Route("/parcels/{}/{}/{way_bill}/{id}/", name="getOneParcel")
*/
public function getParcel($way_bill, $id)
{
$em = $this->getDoctrine()->getManager();
$waybill = $em->getRepository(WayBill::class)->findOneBy([
'id' => $way_bill
]);
if (!$waybill) {
$data = [
'parcel' => null,
'parcels' => null,
'waybill' => null
];
return $this->view($data, Response::HTTP_NOT_FOUND);
}
$parcel = $em->getRepository(Parcel::class)->findOneBy([
'number' => $id,
'waybill' => $waybill
]);
$parcels = $em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
$data = [
'parcel' => $parcel,
'parcels' => $parcels,
'waybill' => $waybill
];
// return $this->view($data, Response::HTTP_OK);
return new JsonResponse($data, Response::HTTP_OK);
}
/**
* @Rest\Route("/parcels/forms/towns", name="getParcels")
*/
public function getTowns()
{
$em = $this->getDoctrine()->getManager();
$towns = $em->getRepository(Station::class)->findBy([
'isMobile' => false
]);
// return $this->view($towns, Response::HTTP_OK);
return new JsonResponse($towns, Response::HTTP_OK);
}
/**
* @Rest\Route("/deliveries/delete/{id}", name="getParcels")
*/
public function deleteParcelFromDelivery($id)
{
$em = $this->getDoctrine()->getManager();
$towns = $em->getRepository(Station::class)->findAll();
// return $this->view($towns, Response::HTTP_OK);
return new JsonResponse($towns, Response::HTTP_OK);
}
public function collectParcel(Parcel $parcel, Request $request)
{
$em = $this->getDoctrine()->getManager();
$receivedParcel = $em->getRepository(ReceivedParcel::class)->findBy([
'parcel' => $parcel
]);
$user = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser()
], ['id' => 'DESC']);
if ($parcel->getToTown()->getId() != $user->getTown()->getId()) {
$data = [
'error' => 'You are not logged in from ' . $parcel->getToTown()->getTownName()
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
if (!$receivedParcel) {
$data = [
'error' => 'PARCEL HAS NOT BEEN RECEIVED YET'
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($data, Response::HTTP_EXPECTATION_FAILED);
}
$collectParcel = new Collected();
$collectParcel->setParcel($parcel);
$collectParcel->setCollectedAt(new \DateTime());
$collectParcel->setUser($this->getUser());
$parcel->setIsReceived(true);
$content = $request->getContent();
$data = json_decode($content, true);
$form = $this->createForm(CollectionForm::class, $collectParcel);
$form->submit($data);
$validator = $this->get('validator');
/** @var $errors */
$errors = $validator->validate($collectParcel);
// dump($errors);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);
}
try {
$parcel->setIsCollected(true);
$em->persist($collectParcel);
$em->flush();
$sms = new SendSms();
$sms->sendOutSms($parcel->getSenderPhoneNumber(), "HELLO {$parcel->getSenderName()} THE PARCEL YOU SENT TO {$parcel->getToTown()} FROM {$parcel->getFromTown()} HAS BEEN COLLECTED BY {$parcel->getReceiverName()}");
// $view = $this->view($collectParcel, Response::HTTP_CREATED);
// return $view;
return new JsonResponse($collectParcel, Response::HTTP_OK);
} catch (UniqueConstraintViolationException $un) {
$collection = $em->getRepository('AppBundle:Collected')->findOneBy([
'parcel' => $parcel
]);
$data = [
'error' => 'THIS PARCEL HAS ALREADY BEEN COLLECTED #ID ' . $collection->getCollectorNationalId()
];
// return $this->view($data, Response::HTTP_EXPECTATION_FAILED);
return new JsonResponse($collectParcel, Response::HTTP_EXPECTATION_FAILED);
} catch (\PDOException $e) {
// $view = $this->view($collectParcel, Response::HTTP_EXPECTATION_FAILED);
//
// return $view;
return new JsonResponse($collectParcel, Response::HTTP_EXPECTATION_FAILED);
}
}
/**
* @Rest\Route("/new-parcel", name="api_new-parcel")
*/
public function newParcel(Request $request)
{
$parcel = new Parcel();
$em = $this->getDoctrine()->getManager();
$parcelForm = $this->createForm(ParcelForm::class, $parcel);
$amount = 0;
if (isset($request->get('app_bundle_parcel_form')['amount'])) {
$amount = $request->get('app_bundle_parcel_form')['amount'];
}
$parcelForm->handleRequest($request);
/** @var UserTown $userTown */
$userTown = $em->getRepository(UserStation::class)->findOneBy([
'user' => $this->getUser(),
'isActive' => true
], ['id' => 'DESC']);
if (!$userTown) {
$parcelForm->addError(new FormError('You are not assigned a town Please contact admin'));
return $this->render('parcels/new_parcel.html.twig', [
'form' => $parcelForm->createView()
]);
}
if ($parcelForm->isSubmitted() && $parcelForm->isValid()) {
if ($parcel->getToTown()->getId() === $userTown->getTown()->getId()) {
$parcelForm->addError(new FormError('From town and Destination Town cannot be the same'));
return $this->render('parcels/new_parcel.html.twig', [
'form' => $parcelForm->createView(),
'user_town' => $userTown
]);
}
$parcel->setCreatedAt(new \DateTime());
$parcel->setCreatedBy($this->getUser());
$parcel->setFromTown($userTown->getTown());
$parcel->setIsEnRoute(false);
$parcel->setIsCollected(false);
$parcel->setIsReceived(false);
$parcelAmount = new Cost();
$parcelAmount->setCreatedAt(new \DateTime());
$parcelAmount->setAmount($amount);
$parcelAmount->setParcel($parcel);
try {
$em->persist($parcelAmount);
$em->persist($parcel);
$em->flush();
$this->addFlash('success', 'Parcel Saved Successfully');
// $this->redirectToRoute('pdf_report', ['id' => $parcel->getId()]);
// $parcel = new Parcel();
// $parcelForm = $this->createForm(ParcelForm::class, $parcel);
return $this->redirectToRoute('one_parcel', ['id' => $parcel->getId()]);
} catch (\PDOException $e) {
$this->addFlash('error', 'An Error Occurred Please check whether every thin is filled');
return $this->render('parcels/new_parcel.html.twig', [
'form' => $parcelForm->createView(),
'user_town' => $userTown
]);
}
}
return $this->render('parcels/new_parcel.html.twig', [
'form' => $parcelForm->createView(),
'user_town' => $userTown
]);
}
}