<?php
/**
* Created by PhpStorm.
* User: parcel
* Date: 8/24/18
* Time: 6:28 PM
*/
namespace App\Parcels;
use App\Entity\DailyAccount;
use App\Entity\DebitCreditNote;
use App\Entity\DeliveryParcel;
use App\Entity\DeliveryVehicle;
use App\Entity\Etr;
use App\Entity\Mpesa;
use App\Entity\MpesaAuth;
use App\Entity\MpesaPayment;
use App\Entity\MpesaTransaction;
use App\Entity\Organization;
use App\Entity\Parcel;
use App\Entity\Sms;
use App\Entity\Station;
use App\Entity\TimsStation;
use App\Entity\Transaction;
use App\Entity\TransactionExpense;
use App\Entity\UserStation;
use App\Entity\WayBill;
use App\Form\ParcelForm;
use App\Form\WayBillExpense;
use App\Form\WayBillForm;
use App\Service\TremolInitiator;
use App\TimsProcessor\Tremol\core\SException;
use App\TimsProcessor\Tremol\FP;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\ObjectManager;
use Exception;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerBuilder;
use Mpdf\QrCode\Output\Png;
use Mpdf\QrCode\Output\Svg;
use Mpdf\QrCode\QrCode;
use PDOException;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Sasedev\MpdfBundle\Factory\MpdfFactory;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Twig\Error\Error;
class ParcelController extends AbstractController
{
private $authType = 'PROD';
private ManagerRegistry $doctrine;
// private TremolInitiator $initiator;
/** KernelInterface $appKernel */
private $appKernel;
private fp $fp;
private $client;
private ObjectManager $em;
private $smsStatus = [
100 => "Processed",
101 => "Sent",
102 => "Queued",
401 => "RiskHold",
402 => "InvalidSenderId",
403 => "InvalidPhoneNumber",
404 => "UnsupportedNumberType",
405 => "InsufficientBalance",
406 => "UserInBlacklist",
407 => "CouldNotRoute",
409 => "DoNotDisturbRejection",
500 => "InternalServerError",
501 => "GatewayError",
502 => "RejectedByGateway"
];
public function __construct(ManagerRegistry $doctrine, KernelInterface $appKernel, HttpClientInterface $client)
{
$this->doctrine = $doctrine;
$this->appKernel = $appKernel;
$this->em = $this->doctrine->getManager();
$this->client = $client;
}
/**
* @Route("/", name="all_parcels")
*/
public function parcelsAction()
{
return $this->render('fos/parcels/all_parcels.html.twig', []);
}
/**
* @Route("/incoming", name="all_incoming_parcels")
*/
public function incomingParcelsAction()
{
return $this->render('fos/parcels/incoming_parcel.html.twig', []);
}
/**
*
* @Route("/incoming/parcels-list", name="getAllInComingParcels")
*/
public function getInComingParcels(Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
if (!$request->getSession()->get('STATION')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
$station_id = $request->getSession()->get('STATION');
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
$parcels = $em->getRepository(DeliveryParcel::class)->findInComingParcels($filterRules, $station_id, $offset, $rows);
$total = $em->getRepository(DeliveryParcel::class)->findTotalInComingParcels($filterRules, $station_id);
/* $parcels = $em->getRepository(Parcel::class)->findBy([
'fromStation' => $station_id,
'isEnRoute' => true
],['id'=>'DESC']);*/
$data = [
'total' => $total,
'rows' => $parcels
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/collected", name="all_collected_parcels")
*/
public function collectedParcelsAction()
{
return $this->render('fos/parcels/collected_parcels.html.twig', []);
}
/**
*
* @Route("/collected/parcels-list", name="getAllCollectedParcels")
*/
public function getCollectedParcels(Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
if (!$request->getSession()->get('STATION')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
$station_id = $request->getSession()->get('STATION');
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
$results = $em->getRepository(DeliveryParcel::class)->findCollectedParcels($filterRules, $station_id, $offset, $rows);
$parcels = $results['results'];
$count = $results;
/* $parcels = $em->getRepository(Parcel::class)->findBy([
'fromStation' => $station_id,
'isEnRoute' => true
],['id'=>'DESC']);*/
$data = [
'rows' => $parcels,
'total' => $count
];
$readyData = $serializer->serialize($data, 'json', $context);
return new Response($readyData, Response::HTTP_OK);
}
/**
* @Route("/at-office", name="all_at_office_parcels")
*/
public function AtOfficeParcelsAction()
{
return $this->render('fos/parcels/at_office.html.twig', []);
}
/**
*
* @Route("/at-office/parcels-list", name="get_all_at_office")
*/
public function getAtOfficeParcels(Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
if (!$request->getSession()->get('STATION')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
$station_id = $request->getSession()->get('STATION');
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
$parcels = $em->getRepository(Parcel::class)->findAtOfficeParcels($filterRules, $station_id, $offset, $rows);
$total = $em->getRepository(Parcel::class)->findTotalAtOfficeParcels($filterRules, $station_id);
$data = [
'total' => $total,
'rows' => $parcels
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/received", name="all_received_parcels")
*/
public function receivedParcelsAction()
{
return $this->render('fos/parcels/received_parcel.html.twig', []);
}
/**
*
* @Route("/received/parcels-list", name="getAllReceivedParcels")
*/
public function getReceivedParcels(Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
if (!$request->getSession()->get('STATION')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
$station_id = $request->getSession()->get('STATION');
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
$parcels = $em->getRepository(DeliveryParcel::class)->findReceivedParcels($filterRules, $station_id, $offset, $rows);
$total = $em->getRepository(DeliveryParcel::class)->findTotalReceivedParcels($filterRules, $station_id);
/* $parcels = $em->getRepository(Parcel::class)->findBy([
'fromStation' => $station_id,
'isEnRoute' => true
],['id'=>'DESC']);*/
$data = [
'total' => $total,
'rows' => $parcels
];
$allData = $serializer->serialize($data, 'json', $context);
return new Response($allData, Response::HTTP_OK);
}
/**
* @Route("/out_going", name="all_out_going_parcels")
*/
public function outGoingParcelsAction()
{
return $this->render('fos/parcels/en_route_deliveries.html.twig', []);
}
/**
*
* @Route("/en-route/delivery-list", name="getAllEnrouteDeliveries")
*/
public function getEnrouteDeliveries(Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
if (!$request->getSession()->get('STATION')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
$station_id = $request->getSession()->get('STATION');
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
// $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
$parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteDeliveries($filterRules, $station_id, $offset, $rows);
$total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteDeliveries($filterRules, $station_id);
$data = [
'total' => $total,
'rows' => $parcels
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/out_going/delivery/{id}", name="all_delivery_parcels")
*/
public function deliveryParcelsAction($id)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
// $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
$parcels = $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($id);
// $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
return $this->render('fos/parcels/delivery_parcels.html.twig', [
'id' => $id,
'parcels' => $parcels
]);
}
/**
* @Route("/en-route/delivery-parcels-list/{delivery_id}", methods={"GET"},name="getDeliveryParcels")
*/
public function getDeliveryParcels($delivery_id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$context = new SerializationContext();
$context->setSerializeNull(true);
$serializer = SerializerBuilder::create()->build();
// $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
$parcels = $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($delivery_id);
// $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
$data = [
'rows' => $parcels
];
$data = $serializer->serialize($data, 'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/all/parcels-list", methods={"POST"}, name="get_all_Parcels")
*/
public function getAllParcels(Request $request)
{
$em = $this->getDoctrine()->getManager();
$serializer = SerializerBuilder::create()->build();
$page = empty($request->request->get('page')) ? intval('page') : 1;
$rows = empty($request->request->get('rows')) ? intval('rows') : 10;
$offset = ($page - 1) * $rows;
$session = new Session();
if (!$session->get('town')) {
$data = [
'error' => 'User is not well registered'
];
$data = $serializer->serialize($data, 'json');
return new Response($data, Response::HTTP_OK);
}
$page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
$rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
$offset = ($page - 1) * $rows;
$filterRules = $request->request->get('filterRules');
$em = $this->getDoctrine()->getManager();
$parcels = $em->getRepository(Parcel::class)->findTownParcels($session->get('town'), $offset, $rows);
// dump($parcels); die;
$parcelsCount = $em->getRepository(Parcel::class)->findTownParcelsCount($session->get('town'));
$data = [
'rows' => $parcels,
'total' => $parcelsCount
];
$data = $serializer->serialize($data, 'json');
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/new-parcel", name="new-parcel")
*/
public function newParcel(Request $request)
{
$waybill = new WayBill();
$em = $this->getDoctrine()->getManager();
$organization = $em->getRepository(Organization::class)->findOneBy([
'id' => $request->getSession()->get('ORGANIZATION')
]);
$waybill->setOrganization($organization);
$form = $this->createForm(WayBillForm::class, $waybill, [
'validation_groups' => [
'Default'
]
]);
$form->handleRequest($request);
/** @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');
$dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser(),
'isClosed' => false,
'accountDate' => $date
], ['id' => 'DESC']);
if (!$dailyAccount) {
$this->addFlash('warning', "Please Open A new Daily account for today ({$stringDate}) to make any transactions");
return $this->render('fos/parcels/new_parcel.html.twig', [
'form' => $form->createView(),
'user_station' => $userStation
]);
}
if ($form->isSubmitted() && $form->isValid()) {
if ($waybill->getToStation()->getId() === $userStation->getStation()->getId()) {
$form->addError(new FormError('Origin Station and Destination Station cannot be the same'));
return $this->render('fos/parcels/new_parcel.html.twig', [
'form' => $form->createView(),
'user_station' => $userStation
]);
}
$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);
// $waybill->getParcels()->get($key)->setIsCollected(false);
}
$conn = $em->getConnection();
$conn->beginTransaction();
try {
$em->persist($waybill);
$em->flush();
$em->getConnection()->commit();
$this->addFlash('success', 'Parcel Saved Successfully');
return $this->redirectToRoute('one_way_bill', ['id' => $waybill->getId()]);
} catch (PDOException $e) {
$em->getConnection()->rollBack();
$this->addFlash('error', 'An Error Occurred Please check whether every thin is filled');
return $this->render('fos/parcels/new_parcel.html.twig', [
'form' => $form->createView(),
'user_station' => $userStation
]);
}
}
return $this->render('fos/parcels/new_parcel.html.twig', [
'form' => $form->createView(),
'user_station' => $userStation
]);
}
/**
*
* @Route("/details/{id}", name="one_detail_parcel")
*/
public function getDetailParcel($id)
{
$em = $this->getDoctrine()->getManager();
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $id
]);
$parcel = $em->getRepository(Parcel::class)->findOneBy([
'waybill' => $id
]);
return $this->render('fos/parcels/parcel_detail.html.twig', [
'transaction' => $transaction,
'parc' => $parcel
]);
}
/**
* @Route("/way_bill/{id}", methods={"GET","POST"}, name="one_way_bill")
* @param $id
* @param Request $request
* @return RedirectResponse|Response
*/
public function getOneWayBill($id, Request $request, MpdfFactory $mpdfFactory)
{
$em = $this->getDoctrine()->getManager();
$dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser()
], ['id' => 'DESC']);
/** @var Transaction $transaction */
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $id
]);
$isMpesaAvailable = false;
/** @var MpesaAuth $credentials */
$credentials = $em->getRepository(MpesaAuth::class)->findOneBy([
'station' => $request->getSession()->get('STATION'),
'authType' => $this->authType
]);
$isCashCanChangeMpesa = false;
if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId())) {
$isMpesaAvailable = true;
}
if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId()) && $transaction->getPaymentMethod() == 'CASH') {
$isCashCanChangeMpesa = true;
}
$isCancellable = true;
// if ($transaction->getisCancelled()){
// $this->addFlash('warning', 'This Transaction is already cancelled');
// }else if($dailyAccount->getId() !== $transaction->getDailyAccount()->getId()){
// $isCancellable = false;
// $this->addFlash('warning', 'You cannot Cancel this transaction');
// }
// if ($this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
// // the user has the ROLE_BRAND role, so act accordingly
// $isCancellable = true;
// }
/** @var Parcel $parcels */
$parcels = $em->getRepository(Parcel::class)->findBy([
'waybill' => $id
]);
/** @var Sms $sms */
$sms = $em->getRepository(Sms::class)->findBy([
'transaction' => $transaction
]);
dump($sms);
$timsSupport = $em->getRepository(TimsStation::class)->findOneBy([
'station' => $request->getSession()->get('STATION'),
'client' => 'WEB'
]);
// dump($timsSupport);
$wayBillExpense = new TransactionExpense();
$cancelForm = $this->cancelTransactionForm($id);
$cancelForm->handleRequest($request);
if ($cancelForm->isSubmitted()) {
if (!$transaction->getIsComplete() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
if (!$transaction->getisCancelled() && ($dailyAccount == $transaction->getDailyAccount() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER'))) {
if($transaction->getIsFinal() && $transaction->getCuInvoiceNumber()){
return $this->makeCreditNote($transaction, $mpdfFactory);
}else{
$transaction->setIsCancelled(true);
// $transaction->getDailyAccount()->setCash($transaction->getDailyAccount()->getCash() - $transaction->getAmount());
$em->flush();
}
$this->addFlash('warning', 'This Transaction has been cancelled successfully');
} else if ($cancelForm->isSubmitted()) {
$this->addFlash('warning', 'This Transaction has not been cancelled');
}
} else {
$this->addFlash('error', 'YOU CANNOT CANCEL A COMPLETE TRANSACTION, CONTACT ADMIN');
}
}
$cashPaymentOptionForm = $this->cashPaymentOptionForm($id);
$cashPaymentOptionForm->handleRequest($request);
if ($cashPaymentOptionForm->isSubmitted()) {
if (!$transaction->getIsPaid()) {
$conn = $em->getConnection();
$conn->beginTransaction();
try {
// $dailyAccount->setCash($transaction->getAmount() + $dailyAccount->getCash());
$transaction->setIsPaid(true);
$transaction->setPaymentMethod('CASH');
$transaction->setPaidBy('sender');
$transaction->setCashAmount($transaction->getAmount());
$em->getConnection()->commit();
$em->flush();
$this->addFlash('success', 'Transaction paid in cash');
return $this->redirectToRoute('one_way_bill', ['id' => $id]);
} catch (\PDOException $e) {
$em->getConnection()->rollBack();
$this->addFlash('error', 'An Error Occurred Please check whether every thing is ok or contact admin');
return $this->redirectToRoute('one_way_bill', ['id' => $id]);
}
}
}
$form = $this->createForm(WayBillExpense::class, $wayBillExpense);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$wayBillExpense->setTransaction($transaction);
$wayBillExpense->setCreatedBy($this->getUser());
$wayBillExpense->setCreatedAt(new \DateTime());
$conn = $em->getConnection();
$conn->beginTransaction();
try {
$em->persist($wayBillExpense);
$em->flush();
$em->getConnection()->commit();
$this->addFlash('success', 'Expense Updated Successfully');
return $this->redirectToRoute('one_way_bill', ['id' => $transaction->getWayBill()->getId()]);
} catch (\PDOException $e) {
$em->getConnection()->rollBack();
$this->addFlash('error', 'An Error Occurred Please check whether every thing is filled');
return $this->render('fos/parcels/view_parcel.html.twig', [
'transaction' => $transaction,
'daily_account' => $dailyAccount,
'parcels' => $parcels,
'form' => $form->createView(),
'cancelForm' => $cancelForm->createView(),
'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
'isCancellable' => $isCancellable,
'isMpesaAvailable' => $isMpesaAvailable,
'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
'tims' => $timsSupport
]);
}
}
return $this->render('fos/parcels/view_parcel.html.twig', [
'transaction' => $transaction,
'daily_account' => $dailyAccount,
'parcels' => $parcels,
'form' => $form->createView(),
'cancelForm' => $cancelForm->createView(),
'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
'isCancellable' => $isCancellable,
'isMpesaAvailable' => $isMpesaAvailable,
'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
'tims' => $timsSupport,
'sms' => $sms,
'statusChart' => $this->smsStatus
]);
}
/**
* @Route("/way_bill/parcel/{parcel_id}", name="one_waybill_parcel")
* @param $parcel_id
* @return Response
*/
public function getParcelDeliveryData($parcel_id)
{
$em = $this->getDoctrine()->getManager();
$isEnRoute = false;
$isInDelivery = false;
$deliveryParcel = $em->getRepository(DeliveryParcel::class)->findOneBy([
'isCancelled' => false,
'parcel' => $parcel_id
]);
if ($deliveryParcel) {
$isInDelivery = true;
$deliveryVehicle = $em->getRepository(DeliveryVehicle::class)->findOneBy([
'isCancelled' => false,
'delivery' => $deliveryParcel->getDelivery()
]);
if ($deliveryVehicle) {
$isEnRoute = true;
return $this->render('fos/parcels/parcel_status.html.twig', [
'isEnRoute' => $isEnRoute,
'inDelivery' => $isInDelivery,
'delivery_parcel' => $deliveryParcel,
'delivery_vehicle' => $deliveryVehicle
]);
}
return $this->render('fos/parcels/parcel_status.html.twig', [
'isEnRoute' => $isEnRoute,
'inDelivery' => $isInDelivery,
'delivery_parcel' => $deliveryParcel
]);
}
return $this->render('fos/parcels/parcel_status.html.twig', [
'isEnRoute' => $isEnRoute,
'inDelivery' => $isInDelivery,
'delivery_parcel' => null
]);
}
/**
* @Route("/form/towns",methods={"GET"}, name="form_towns")
*/
public function getTowns(Request $request)
{
$queryTerm = $request->get('q');
$em = $this->getDoctrine()->getManager();
$towns = $em->getRepository(Station::class)->findFormTown($queryTerm);
$serializer = SerializerBuilder::create()->build();
$town = new Station();
$town->setStationName('ALL STATIONS');
$town->setId(-1);
array_push($towns, $town);
$data = $serializer->serialize($towns, 'json');
return new Response($data, Response::HTTP_OK);
}
private function cancelTransactionForm($id)
{
$fb = $this->createFormBuilder();
return $fb
->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
->setMethod('POST')
->getForm();
}
private function cashPaymentOptionForm($id)
{
// $fb = $this->createFormBuilder();
$fb = $this->get('form.factory')->createNamedBuilder('cash_payment_mode');
return $fb
->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
->setMethod('POST')
->getForm();
}
/**
* @Route("/receipt/{waybill_}", methods={"GET"}, name="receipt_action")
*/
public function ReceiptAction(Request $request, $waybill_, MpdfFactory $MpdfFactory): Response
{
$em = $this->getDoctrine()->getManager();
/** @var Transaction $transaction */
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $waybill_
]);
$transaction->setIsComplete(true);
$transaction->setIsPaid(true);
$transaction->setIsFinal(true);
$em->flush();
$mpesa = null;
if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH' ) {
$mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
'transaction' => $transaction
]);
}
/** @var WayBill $waybill */
$waybill = $transaction->getWaybill();
$parcels = $em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
$mPdf = $MpdfFactory->createMpdfObject([
'mode' => 'utf-8',
'format' => [70, 254],
'margin_header' => 5,
'margin_footer' => 5,
'orientation' => 'P'
]);
$date = new DateTime();
$time = $date->getTimestamp();
$mPdf->SetTopMargin("50");
// get the logo image and change it to base64
$logoImage = file_get_contents('../public/logo.png');
$logoBase64 = base64_encode($logoImage);
// dump($logoBase64);
// $o = $output->output($qrCode, 100, 'white', 'black');
// $mPdf->SetHTMLHeader($this->renderView('twigfolder/pdf/pdf_header.html.twig', $TwigVars));
// $mPdf->SetFooter($this->renderView('twigfolder/pdf/pdf_footer.html.twig', $TwigVars));
$mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
'waybill' => $waybill,
'transaction' => $transaction,
'parcels' => $parcels,
'mpesa' => $mpesa,
'logoBase64' => $logoBase64,
'by' => $waybill->getCreatedBy()->getPerson(),
'receiptType' => "RECEIPT"
]));
return $MpdfFactory->createDownloadResponse($mPdf, "receipt_{$waybill_}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
}
private function makeCreditNote(Transaction $transaction, MpdfFactory $MpdfFactory): Response
{
$em = $this->em;
/** @var Etr $etr */
$etr = $em->getRepository(Etr::class)->findOneBy([
'isDefault' => 1
]);
try{
$tremolInitiator = new TremolInitiator($em, $etr);
}catch(Exception $e){
dump($e);
$this->addFlash("warn");
return $this->redirectToRoute("one_way_bill", $transaction->getWayBill()->getId());
}
$mpesa = null;
if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
/** @var MpesaTransaction $mpesa */
$mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
'transaction' => $transaction
]);
}
/** @var WayBill $waybill */
$waybill = $transaction->getWaybill();
$parcels = $em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
$mPdf = $MpdfFactory->createMpdfObject([
'mode' => 'utf-8',
'format' => [70, 230],
'margin_header' => 5,
'margin_footer' => 5,
'orientation' => 'P'
]);
$date = new DateTime();
$time = $date->getTimestamp();
$mPdf->SetTopMargin("1");
try {
$invoiceNumber = $transaction->getCuInvoiceNumber();
$receiptType = 'CREDIT NOTE';
if ($invoiceNumber and $transaction->getIsFinal()) {
/** @var Etr $etr */
$etr = $em->getRepository(Etr::class)->findOneBy([
'serialNumber' => $transaction->getCuSerialNumber()
]);
if($etr && !$etr->isDefault()){
$message = "The CU Device {$transaction->getCuSerialNumber()} is not currently the default device on the network Please contact admin";
return new Response($message, Response::HTTP_BAD_REQUEST);
}
if ($transaction->getPinNumber()) {
TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
'',
$transaction->getPinNumber(),
'',
'',
'',
'',
$transaction->getCuInvoiceNumber(),
$waybill->getId()
);
} else {
TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
'',
'',
'',
'',
'',
'',
$transaction->getCuInvoiceNumber(),
$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();
$invoiceNumber = $rec->InvoiceNum;
$creditNote = new DebitCreditNote();
$creditNote->setAmount($transaction->getAmount());
$creditNote->setTransaction($transaction);
$creditNote->setCreatedAt(new Datetime());
$creditNote->setCuInvoiceNumber($invoiceNumber);
$creditNote->setTransactionType('CREDITNOTE');
$em->persist($creditNote);
if($mpesa){
$mpesa->getMpesa()->setIsUsed(false);
$em->remove($mpesa);
}
}
$transaction->setIsComplete(true);
$transaction->setMpesaAmount(0);
$transaction->setCashAmount(0);
$transaction->setIsFinal(true);
$transaction->setTaxAmount(0);
$transaction->setIsCancelled(true);
$em->flush();
// get the logo image and change it to base64
$logoImage = file_get_contents('../public/logo.png');
$logoBase64 = base64_encode($logoImage);
// dump($logoBase64);
// create TIMS QRCODE change it to base64;
$timsQRCode = 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' . $invoiceNumber;
$timsqrCode = new QrCode($timsQRCode);
$output = new Png();
$timsQRCodeData = $output->output($timsqrCode, 100, [255, 255, 255], [0, 0, 0]);
$base64 = base64_encode($timsQRCodeData);
$mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
'waybill' => $waybill,
'transaction' => $transaction,
'parcels' => $parcels,
'mpesa' => $mpesa,
'qrcode' => $base64,
'logoBase64' => $logoBase64,
'timsInvoiceNumber' => $invoiceNumber,
'by' => $waybill->getCreatedBy()->getPerson(),
'receiptType' => $receiptType
]));
return $MpdfFactory->createDownloadResponse($mPdf, "receipt_credit_note{$waybill->getId()}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
} catch (\Exception $e) {
return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
}
}
/**
* @Route("/receipt/g03/{waybill_}", methods={"GET"}, name="receipt_action_tremol")
*/
public function ReceiptGO3Action(Request $request, $waybill_, MpdfFactory $MpdfFactory): Response
{
$em = $this->getDoctrine()->getManager();
/** @var Transaction $transaction */
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $waybill_
]);
$mpesa = null;
if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
$mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
'transaction' => $transaction
]);
}
/** @var WayBill $waybill */
$waybill = $transaction->getWaybill();
$parcels = $em->getRepository(Parcel::class)->findBy([
'waybill' => $waybill
]);
$mPdf = $MpdfFactory->createMpdfObject([
'mode' => 'utf-8',
'format' => [70, 230],
'margin_header' => 0,
'margin_footer' => 0,
'orientation' => 'P'
]);
$date = new DateTime();
$time = $date->getTimestamp();
$mPdf->SetTopMargin("1");
$qrCode = new QrCode($waybill_);
/** @var Etr $etr */
$etr = $em->getRepository(Etr::class)->findOneBy([
'isDefault' => 1
]);
try {
//$fp->ServerSetSettings("192.168.13.125", 4444);
// $fp->SetServer_UsedComModule('LAN/WiFi');
// $fp->SetWiFi_Password(10,'mirage2222');
// $fp->SetTCP_Password(10,'mirage2222');
// $fp->SaveNetworkSettings();
// $fp->ApplyClientLibraryDefinitions();
// var_dump($fp->ServerGetDeviceSettings());
// die;
$invoiceNumber = $transaction->getCuInvoiceNumber();
$receiptType = 'FISCAL RECEIPT COPY';
// dump($fp);
// die;
if (!$invoiceNumber and !$transaction->getIsFinal()) {
try{
$tremolInitiator = new TremolInitiator($this->em, $etr);
}catch(\Exception $e){
dump($e);
}
// $this->fp->ServerGetClients();
$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());
$em->flush();
}
// $data = $output->output($qrCode, 100, [255, 255, 255], [0, 0, 0]);
// file_put_contents('../public/qrcode.png', $data);
// file_put_contents('../public/timsQRCode.png', $timsQRCodeData);
// $dataFile = file_get_contents('../public/timsQRCode.png');
/*$image = imagecreatefromstring($dataFile);
$im = '../public/awesome.png';
imagepng($image, $im, 0);*/
// get the logo image and change it to base64
$logoImage = file_get_contents('../public/logo.png');
$logoBase64 = base64_encode($logoImage);
// dump($logoBase64);
// create TIMS QRCODE change it to base64;
$timsQRCode = 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' . $invoiceNumber;
$timsqrCode = new QrCode($timsQRCode);
$output = new Png();
$timsQRCodeData = $output->output($timsqrCode, 100, [255, 255, 255], [0, 0, 0]);
$base64 = base64_encode($timsQRCodeData);
$mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
'waybill' => $waybill,
'transaction' => $transaction,
'parcels' => $parcels,
'mpesa' => $mpesa,
'qrcode' => $base64,
'logoBase64' => $logoBase64,
'timsInvoiceNumber' => $invoiceNumber,
'by' => $waybill->getCreatedBy()->getPerson(),
'receiptType' => $receiptType
]));
return $MpdfFactory->createDownloadResponse($mPdf, "receipt_{$waybill_}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
} catch (\Exception $e) {
return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
}
// return new Response("error occurred");
}
/**
* @Route("/way_bill/{id}/complete", name="register_transaction_as_complete")
*/
public function registerTransactionAsComplete($id)
{
$em = $this->getDoctrine()->getManager();
// $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$connection = new AMQPStreamConnection('192.168.13.125', 5672, 'guest', 'guest');
$channel = $connection->channel();
/** @var Transaction $transaction */
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $id
]);
$transaction->setIsComplete(true);
try {
if (!$transaction->getIsPaid()) {
$transaction->setIsPaid(true);
$transaction->setCashAmount($transaction->getAmount());
$transaction->setPaymentMethod('CASH');
$transaction->setIsPaid(true);
}
$em->flush();
$response = [
'is_complete' => true
];
return new Response(json_encode($response), Response::HTTP_OK);
} catch (\Exception $e) {
$response = [
'is_complete' => false,
'error' => $e->getMessage()
];
return new Response(json_encode($response), Response::HTTP_NOT_ACCEPTABLE);
}
}
/**
* @Route("/awesome", name="tims_awesomeness")
*/
public function getKRASerials(){
$em = $this->getDoctrine()->getManager();
for($x =19340;$x > 0; $x--) {
$k = sprintf('%010d', $x);
$k = '004079153'.$k;
dump($k);
$response = $this->client->request(
'POST',
'https://itax.kra.go.ke/KRA-Portal/middlewareController.htm?actionCode=fetchInvoiceDtl',
[
'body' => [
'invNo' => "{$k}"
]
]
);
$json = json_decode($response->getContent(),true);
dump($json);
if($json['traderSystemInvNo']){
dump($json['traderSystemInvNo']);
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $json['traderSystemInvNo']
]);
if($transaction){
$transaction->setCuInvoiceNumber($json['mwInvNo']);
$em->flush();
}
}
}
die;
}
}