src/Parcels/ParcelController.php line 697

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: parcel
  5.  * Date: 8/24/18
  6.  * Time: 6:28 PM
  7.  */
  8. namespace App\Parcels;
  9. use App\Entity\DailyAccount;
  10. use App\Entity\DebitCreditNote;
  11. use App\Entity\DeliveryParcel;
  12. use App\Entity\DeliveryVehicle;
  13. use App\Entity\Etr;
  14. use App\Entity\Mpesa;
  15. use App\Entity\MpesaAuth;
  16. use App\Entity\MpesaPayment;
  17. use App\Entity\MpesaTransaction;
  18. use App\Entity\Organization;
  19. use App\Entity\Parcel;
  20. use App\Entity\Sms;
  21. use App\Entity\Station;
  22. use App\Entity\TimsStation;
  23. use App\Entity\Transaction;
  24. use App\Entity\TransactionExpense;
  25. use App\Entity\UserStation;
  26. use App\Entity\WayBill;
  27. use App\Form\ParcelForm;
  28. use App\Form\WayBillExpense;
  29. use App\Form\WayBillForm;
  30. use App\Service\TremolInitiator;
  31. use App\TimsProcessor\Tremol\core\SException;
  32. use App\TimsProcessor\Tremol\FP;
  33. use DateTime;
  34. use Doctrine\Persistence\ManagerRegistry;
  35. use Doctrine\Persistence\ObjectManager;
  36. use Exception;
  37. use JMS\Serializer\SerializationContext;
  38. use JMS\Serializer\SerializerBuilder;
  39. use Mpdf\QrCode\Output\Png;
  40. use Mpdf\QrCode\Output\Svg;
  41. use Mpdf\QrCode\QrCode;
  42. use PDOException;
  43. use PhpAmqpLib\Connection\AMQPStreamConnection;
  44. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  45. use Symfony\Component\Form\FormError;
  46. use Symfony\Component\HttpFoundation\RedirectResponse;
  47. use Symfony\Component\HttpFoundation\Request;
  48. use Symfony\Component\HttpFoundation\Response;
  49. use Symfony\Component\HttpFoundation\Session\Session;
  50. use Symfony\Component\HttpKernel\KernelInterface;
  51. use Symfony\Component\Routing\Annotation\Route;
  52. use Sasedev\MpdfBundle\Factory\MpdfFactory;
  53. use Symfony\Contracts\HttpClient\HttpClientInterface;
  54. use Twig\Error\Error;
  55. class ParcelController extends AbstractController
  56. {
  57.     private $authType 'PROD';
  58.     private ManagerRegistry $doctrine;
  59. //    private TremolInitiator $initiator;
  60.     /** KernelInterface $appKernel */
  61.     private $appKernel;
  62.     private fp $fp;
  63.     private $client;
  64.     private ObjectManager $em;
  65.     private $smsStatus = [
  66.         100 => "Processed",
  67.         101 => "Sent",
  68.         102 => "Queued",
  69.         401 => "RiskHold",
  70.         402 => "InvalidSenderId",
  71.         403 => "InvalidPhoneNumber",
  72.         404 => "UnsupportedNumberType",
  73.         405 => "InsufficientBalance",
  74.         406 => "UserInBlacklist",
  75.         407 => "CouldNotRoute",
  76.         409 => "DoNotDisturbRejection",
  77.         500 => "InternalServerError",
  78.         501 => "GatewayError",
  79.         502 => "RejectedByGateway"
  80.     ];
  81.     public function __construct(ManagerRegistry $doctrineKernelInterface $appKernelHttpClientInterface $client)
  82.     {
  83.         $this->doctrine $doctrine;
  84.         $this->appKernel $appKernel;
  85.         $this->em $this->doctrine->getManager();
  86.         $this->client $client;
  87.     }
  88.     /**
  89.      * @Route("/", name="all_parcels")
  90.      */
  91.     public function parcelsAction()
  92.     {
  93.         return $this->render('fos/parcels/all_parcels.html.twig', []);
  94.     }
  95.     /**
  96.      * @Route("/incoming", name="all_incoming_parcels")
  97.      */
  98.     public function incomingParcelsAction()
  99.     {
  100.         return $this->render('fos/parcels/incoming_parcel.html.twig', []);
  101.     }
  102.     /**
  103.      *
  104.      * @Route("/incoming/parcels-list", name="getAllInComingParcels")
  105.      */
  106.     public function getInComingParcels(Request $request)
  107.     {
  108.         $em $this->getDoctrine()->getManager();
  109.         $context = new SerializationContext();
  110.         $context->setSerializeNull(true);
  111.         $serializer SerializerBuilder::create()->build();
  112.         if (!$request->getSession()->get('STATION')) {
  113.             $data = [
  114.                 'error' => 'User is not well registered'
  115.             ];
  116.             $data $serializer->serialize($data'json'$context);
  117.             return new Response($dataResponse::HTTP_OK);
  118.         }
  119.         $station_id $request->getSession()->get('STATION');
  120.         $page $request->request->get('page') > $request->request->get('page') : 1;
  121.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  122.         $offset = ($page 1) * $rows;
  123.         $filterRules $request->request->get('filterRules');
  124.         $parcels $em->getRepository(DeliveryParcel::class)->findInComingParcels($filterRules$station_id$offset$rows);
  125.         $total $em->getRepository(DeliveryParcel::class)->findTotalInComingParcels($filterRules$station_id);
  126.         /* $parcels = $em->getRepository(Parcel::class)->findBy([
  127.             'fromStation' =>  $station_id,
  128.             'isEnRoute' => true
  129.         ],['id'=>'DESC']);*/
  130.         $data = [
  131.             'total' => $total,
  132.             'rows' => $parcels
  133.         ];
  134.         $data $serializer->serialize($data'json'$context);
  135.         return new Response($dataResponse::HTTP_OK);
  136.     }
  137.     /**
  138.      * @Route("/collected", name="all_collected_parcels")
  139.      */
  140.     public function collectedParcelsAction()
  141.     {
  142.         return $this->render('fos/parcels/collected_parcels.html.twig', []);
  143.     }
  144.     /**
  145.      *
  146.      * @Route("/collected/parcels-list", name="getAllCollectedParcels")
  147.      */
  148.     public function getCollectedParcels(Request $request)
  149.     {
  150.         $em $this->getDoctrine()->getManager();
  151.         $context = new SerializationContext();
  152.         $context->setSerializeNull(true);
  153.         $serializer SerializerBuilder::create()->build();
  154.         if (!$request->getSession()->get('STATION')) {
  155.             $data = [
  156.                 'error' => 'User is not well registered'
  157.             ];
  158.             $data $serializer->serialize($data'json'$context);
  159.             return new Response($dataResponse::HTTP_OK);
  160.         }
  161.         $station_id $request->getSession()->get('STATION');
  162.         $page $request->request->get('page') > $request->request->get('page') : 1;
  163.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  164.         $offset = ($page 1) * $rows;
  165.         $filterRules $request->request->get('filterRules');
  166.         $results $em->getRepository(DeliveryParcel::class)->findCollectedParcels($filterRules$station_id$offset$rows);
  167.         $parcels $results['results'];
  168.         $count $results;
  169.         /* $parcels = $em->getRepository(Parcel::class)->findBy([
  170.             'fromStation' =>  $station_id,
  171.             'isEnRoute' => true
  172.         ],['id'=>'DESC']);*/
  173.         $data = [
  174.             'rows' => $parcels,
  175.             'total' => $count
  176.         ];
  177.         $readyData $serializer->serialize($data'json'$context);
  178.         return new Response($readyDataResponse::HTTP_OK);
  179.     }
  180.     /**
  181.      * @Route("/at-office", name="all_at_office_parcels")
  182.      */
  183.     public function AtOfficeParcelsAction()
  184.     {
  185.         return $this->render('fos/parcels/at_office.html.twig', []);
  186.     }
  187.     /**
  188.      *
  189.      * @Route("/at-office/parcels-list", name="get_all_at_office")
  190.      */
  191.     public function getAtOfficeParcels(Request $request)
  192.     {
  193.         $em $this->getDoctrine()->getManager();
  194.         $context = new SerializationContext();
  195.         $context->setSerializeNull(true);
  196.         $serializer SerializerBuilder::create()->build();
  197.         if (!$request->getSession()->get('STATION')) {
  198.             $data = [
  199.                 'error' => 'User is not well registered'
  200.             ];
  201.             $data $serializer->serialize($data'json'$context);
  202.             return new Response($dataResponse::HTTP_OK);
  203.         }
  204.         $station_id $request->getSession()->get('STATION');
  205.         $page $request->request->get('page') > $request->request->get('page') : 1;
  206.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  207.         $offset = ($page 1) * $rows;
  208.         $filterRules $request->request->get('filterRules');
  209.         $parcels $em->getRepository(Parcel::class)->findAtOfficeParcels($filterRules$station_id$offset$rows);
  210.         $total $em->getRepository(Parcel::class)->findTotalAtOfficeParcels($filterRules$station_id);
  211.         $data = [
  212.             'total' => $total,
  213.             'rows' => $parcels
  214.         ];
  215.         $data $serializer->serialize($data'json'$context);
  216.         return new Response($dataResponse::HTTP_OK);
  217.     }
  218.     /**
  219.      * @Route("/received", name="all_received_parcels")
  220.      */
  221.     public function receivedParcelsAction()
  222.     {
  223.         return $this->render('fos/parcels/received_parcel.html.twig', []);
  224.     }
  225.     /**
  226.      *
  227.      * @Route("/received/parcels-list", name="getAllReceivedParcels")
  228.      */
  229.     public function getReceivedParcels(Request $request)
  230.     {
  231.         $em $this->getDoctrine()->getManager();
  232.         $context = new SerializationContext();
  233.         $context->setSerializeNull(true);
  234.         $serializer SerializerBuilder::create()->build();
  235.         if (!$request->getSession()->get('STATION')) {
  236.             $data = [
  237.                 'error' => 'User is not well registered'
  238.             ];
  239.             $data $serializer->serialize($data'json'$context);
  240.             return new Response($dataResponse::HTTP_OK);
  241.         }
  242.         $station_id $request->getSession()->get('STATION');
  243.         $page $request->request->get('page') > $request->request->get('page') : 1;
  244.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  245.         $offset = ($page 1) * $rows;
  246.         $filterRules $request->request->get('filterRules');
  247.         $parcels $em->getRepository(DeliveryParcel::class)->findReceivedParcels($filterRules$station_id$offset$rows);
  248.         $total $em->getRepository(DeliveryParcel::class)->findTotalReceivedParcels($filterRules$station_id);
  249.         /* $parcels = $em->getRepository(Parcel::class)->findBy([
  250.             'fromStation' =>  $station_id,
  251.             'isEnRoute' => true
  252.         ],['id'=>'DESC']);*/
  253.         $data = [
  254.             'total' => $total,
  255.             'rows' => $parcels
  256.         ];
  257.         $allData $serializer->serialize($data'json'$context);
  258.         return new Response($allDataResponse::HTTP_OK);
  259.     }
  260.     /**
  261.      * @Route("/out_going", name="all_out_going_parcels")
  262.      */
  263.     public function outGoingParcelsAction()
  264.     {
  265.         return $this->render('fos/parcels/en_route_deliveries.html.twig', []);
  266.     }
  267.     /**
  268.      *
  269.      * @Route("/en-route/delivery-list", name="getAllEnrouteDeliveries")
  270.      */
  271.     public function getEnrouteDeliveries(Request $request)
  272.     {
  273.         $em $this->getDoctrine()->getManager();
  274.         $context = new SerializationContext();
  275.         $context->setSerializeNull(true);
  276.         $serializer SerializerBuilder::create()->build();
  277.         if (!$request->getSession()->get('STATION')) {
  278.             $data = [
  279.                 'error' => 'User is not well registered'
  280.             ];
  281.             $data $serializer->serialize($data'json'$context);
  282.             return new Response($dataResponse::HTTP_OK);
  283.         }
  284.         $station_id $request->getSession()->get('STATION');
  285.         $page $request->request->get('page') > $request->request->get('page') : 1;
  286.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  287.         $offset = ($page 1) * $rows;
  288.         $filterRules $request->request->get('filterRules');
  289. //        $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  290.         $parcels $em->getRepository(DeliveryParcel::class)->findEnRouteDeliveries($filterRules$station_id$offset$rows);
  291.         $total $em->getRepository(DeliveryParcel::class)->findTotalEnRouteDeliveries($filterRules$station_id);
  292.         $data = [
  293.             'total' => $total,
  294.             'rows' => $parcels
  295.         ];
  296.         $data $serializer->serialize($data'json'$context);
  297.         return new Response($dataResponse::HTTP_OK);
  298.     }
  299.     /**
  300.      * @Route("/out_going/delivery/{id}", name="all_delivery_parcels")
  301.      */
  302.     public function deliveryParcelsAction($id)
  303.     {
  304.         $em $this->getDoctrine()->getManager();
  305.         $context = new SerializationContext();
  306.         $context->setSerializeNull(true);
  307.         $serializer SerializerBuilder::create()->build();
  308. //        $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  309.         $parcels $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($id);
  310. //        $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
  311.         return $this->render('fos/parcels/delivery_parcels.html.twig', [
  312.             'id' => $id,
  313.             'parcels' => $parcels
  314.         ]);
  315.     }
  316.     /**
  317.      * @Route("/en-route/delivery-parcels-list/{delivery_id}", methods={"GET"},name="getDeliveryParcels")
  318.      */
  319.     public function getDeliveryParcels($delivery_idRequest $request)
  320.     {
  321.         $em $this->getDoctrine()->getManager();
  322.         $context = new SerializationContext();
  323.         $context->setSerializeNull(true);
  324.         $serializer SerializerBuilder::create()->build();
  325. //        $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  326.         $parcels $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($delivery_id);
  327. //        $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
  328.         $data = [
  329.             'rows' => $parcels
  330.         ];
  331.         $data $serializer->serialize($data'json'$context);
  332.         return new Response($dataResponse::HTTP_OK);
  333.     }
  334.     /**
  335.      * @Route("/all/parcels-list", methods={"POST"}, name="get_all_Parcels")
  336.      */
  337.     public function getAllParcels(Request $request)
  338.     {
  339.         $em $this->getDoctrine()->getManager();
  340.         $serializer SerializerBuilder::create()->build();
  341.         $page = empty($request->request->get('page')) ? intval('page') : 1;
  342.         $rows = empty($request->request->get('rows')) ? intval('rows') : 10;
  343.         $offset = ($page 1) * $rows;
  344.         $session = new Session();
  345.         if (!$session->get('town')) {
  346.             $data = [
  347.                 'error' => 'User is not well registered'
  348.             ];
  349.             $data $serializer->serialize($data'json');
  350.             return new Response($dataResponse::HTTP_OK);
  351.         }
  352.         $page $request->request->get('page') > $request->request->get('page') : 1;
  353.         $rows $request->request->get('rows') > $request->request->get('rows') : 20;
  354.         $offset = ($page 1) * $rows;
  355.         $filterRules $request->request->get('filterRules');
  356.         $em $this->getDoctrine()->getManager();
  357.         $parcels $em->getRepository(Parcel::class)->findTownParcels($session->get('town'), $offset$rows);
  358. //        dump($parcels); die;
  359.         $parcelsCount $em->getRepository(Parcel::class)->findTownParcelsCount($session->get('town'));
  360.         $data = [
  361.             'rows' => $parcels,
  362.             'total' => $parcelsCount
  363.         ];
  364.         $data $serializer->serialize($data'json');
  365.         return new Response($dataResponse::HTTP_OK);
  366.     }
  367.     /**
  368.      * @Route("/new-parcel", name="new-parcel")
  369.      */
  370.     public function newParcel(Request $request)
  371.     {
  372.         $waybill = new WayBill();
  373.         $em $this->getDoctrine()->getManager();
  374.         $organization $em->getRepository(Organization::class)->findOneBy([
  375.             'id' => $request->getSession()->get('ORGANIZATION')
  376.         ]);
  377.         $waybill->setOrganization($organization);
  378.         $form $this->createForm(WayBillForm::class, $waybill, [
  379.             'validation_groups' => [
  380.                 'Default'
  381.             ]
  382.         ]);
  383.         $form->handleRequest($request);
  384.         /** @var UserStation $userStation */
  385.         $userStation $em->getRepository(UserStation::class)->findOneBy([
  386.             'user' => $this->getUser(),
  387.             'isActive' => true
  388.         ], ['id' => 'DESC']);
  389.         $date = new \DateTime();
  390.         $stringDate $date->format('Y-m-d');
  391.         $dailyAccount $em->getRepository(DailyAccount::class)->findOneBy([
  392.             'user' => $this->getUser(),
  393.             'isClosed' => false,
  394.             'accountDate' => $date
  395.         ], ['id' => 'DESC']);
  396.         if (!$dailyAccount) {
  397.             $this->addFlash('warning'"Please Open A new Daily account for today ({$stringDate}) to make any transactions");
  398.             return $this->render('fos/parcels/new_parcel.html.twig', [
  399.                 'form' => $form->createView(),
  400.                 'user_station' => $userStation
  401.             ]);
  402.         }
  403.         if ($form->isSubmitted() && $form->isValid()) {
  404.             if ($waybill->getToStation()->getId() === $userStation->getStation()->getId()) {
  405.                 $form->addError(new FormError('Origin Station and Destination Station cannot be the same'));
  406.                 return $this->render('fos/parcels/new_parcel.html.twig', [
  407.                     'form' => $form->createView(),
  408.                     'user_station' => $userStation
  409.                 ]);
  410.             }
  411.             $waybill->setCreatedAt(new \DateTime());
  412.             $waybill->setCreatedBy($this->getUser());
  413.             $waybill->setFromStation($userStation->getStation());
  414.             $waybill->setIsCollected(false);
  415.             $waybill->setPercelCount(count($waybill->getParcels()));
  416.             $waybill->setIsCollected(false);
  417.             $waybill->setIsReceived(false);
  418.             $waybill->addTransaction($dailyAccount);
  419.             foreach ($waybill->getParcels() as $key => $item) {
  420.                 $waybill->getParcels()->get($key)->setNumber($key 1);
  421. //                $waybill->getParcels()->get($key)->setIsCollected(false);
  422.             }
  423.             $conn $em->getConnection();
  424.             $conn->beginTransaction();
  425.             try {
  426.                 $em->persist($waybill);
  427.                 $em->flush();
  428.                 $em->getConnection()->commit();
  429.                 $this->addFlash('success''Parcel Saved Successfully');
  430.                 return $this->redirectToRoute('one_way_bill', ['id' => $waybill->getId()]);
  431.             } catch (PDOException $e) {
  432.                 $em->getConnection()->rollBack();
  433.                 $this->addFlash('error''An Error Occurred Please check whether every thin is filled');
  434.                 return $this->render('fos/parcels/new_parcel.html.twig', [
  435.                     'form' => $form->createView(),
  436.                     'user_station' => $userStation
  437.                 ]);
  438.             }
  439.         }
  440.         return $this->render('fos/parcels/new_parcel.html.twig', [
  441.             'form' => $form->createView(),
  442.             'user_station' => $userStation
  443.         ]);
  444.     }
  445.     /**
  446.      *
  447.      * @Route("/details/{id}", name="one_detail_parcel")
  448.      */
  449.     public function getDetailParcel($id)
  450.     {
  451.         $em $this->getDoctrine()->getManager();
  452.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  453.             'wayBill' => $id
  454.         ]);
  455.         $parcel $em->getRepository(Parcel::class)->findOneBy([
  456.             'waybill' => $id
  457.         ]);
  458.         return $this->render('fos/parcels/parcel_detail.html.twig', [
  459.             'transaction' => $transaction,
  460.             'parc' => $parcel
  461.         ]);
  462.     }
  463.     /**
  464.      * @Route("/way_bill/{id}", methods={"GET","POST"}, name="one_way_bill")
  465.      * @param $id
  466.      * @param Request $request
  467.      * @return RedirectResponse|Response
  468.      */
  469.     public function getOneWayBill($idRequest $requestMpdfFactory $mpdfFactory)
  470.     {
  471.         $em $this->getDoctrine()->getManager();
  472.         $dailyAccount $em->getRepository(DailyAccount::class)->findOneBy([
  473.             'user' => $this->getUser()
  474.         ], ['id' => 'DESC']);
  475.         /** @var Transaction $transaction */
  476.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  477.             'wayBill' => $id
  478.         ]);
  479.         $isMpesaAvailable false;
  480.         /** @var MpesaAuth $credentials */
  481.         $credentials $em->getRepository(MpesaAuth::class)->findOneBy([
  482.             'station' => $request->getSession()->get('STATION'),
  483.             'authType' => $this->authType
  484.         ]);
  485.         $isCashCanChangeMpesa false;
  486.         if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId())) {
  487.             $isMpesaAvailable true;
  488.         }
  489.         if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId()) && $transaction->getPaymentMethod() == 'CASH') {
  490.             $isCashCanChangeMpesa true;
  491.         }
  492.         $isCancellable true;
  493. //        if ($transaction->getisCancelled()){
  494. //            $this->addFlash('warning', 'This Transaction is already cancelled');
  495. //        }else if($dailyAccount->getId() !== $transaction->getDailyAccount()->getId()){
  496. //            $isCancellable = false;
  497. //            $this->addFlash('warning', 'You cannot Cancel this transaction');
  498. //        }
  499. //        if ($this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
  500. //            // the user has the ROLE_BRAND role, so act accordingly
  501. //            $isCancellable = true;
  502. //        }
  503.         /** @var Parcel $parcels */
  504.         $parcels $em->getRepository(Parcel::class)->findBy([
  505.             'waybill' => $id
  506.         ]);
  507.         /** @var Sms $sms */
  508.         $sms $em->getRepository(Sms::class)->findBy([
  509.             'transaction' => $transaction
  510.         ]);
  511.         dump($sms);
  512.         $timsSupport $em->getRepository(TimsStation::class)->findOneBy([
  513.             'station' => $request->getSession()->get('STATION'),
  514.             'client' => 'WEB'
  515.         ]);
  516. //        dump($timsSupport);
  517.         $wayBillExpense = new TransactionExpense();
  518.         $cancelForm $this->cancelTransactionForm($id);
  519.         $cancelForm->handleRequest($request);
  520.         if ($cancelForm->isSubmitted()) {
  521.             if (!$transaction->getIsComplete() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
  522.                 if (!$transaction->getisCancelled() && ($dailyAccount == $transaction->getDailyAccount() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER'))) {
  523.                     if($transaction->getIsFinal() && $transaction->getCuInvoiceNumber()){
  524.                         return $this->makeCreditNote($transaction$mpdfFactory);
  525.                     }else{
  526.                         $transaction->setIsCancelled(true);
  527. //                    $transaction->getDailyAccount()->setCash($transaction->getDailyAccount()->getCash() - $transaction->getAmount());
  528.                         $em->flush();
  529.                     }
  530.                     $this->addFlash('warning''This Transaction has been cancelled successfully');
  531.                 } else if ($cancelForm->isSubmitted()) {
  532.                     $this->addFlash('warning''This Transaction has not been cancelled');
  533.                 }
  534.             } else {
  535.                 $this->addFlash('error''YOU CANNOT CANCEL A COMPLETE TRANSACTION, CONTACT ADMIN');
  536.             }
  537.         }
  538.         $cashPaymentOptionForm $this->cashPaymentOptionForm($id);
  539.         $cashPaymentOptionForm->handleRequest($request);
  540.         if ($cashPaymentOptionForm->isSubmitted()) {
  541.             if (!$transaction->getIsPaid()) {
  542.                 $conn $em->getConnection();
  543.                 $conn->beginTransaction();
  544.                 try {
  545. //                    $dailyAccount->setCash($transaction->getAmount() + $dailyAccount->getCash());
  546.                     $transaction->setIsPaid(true);
  547.                     $transaction->setPaymentMethod('CASH');
  548.                     $transaction->setPaidBy('sender');
  549.                     $transaction->setCashAmount($transaction->getAmount());
  550.                     $em->getConnection()->commit();
  551.                     $em->flush();
  552.                     $this->addFlash('success''Transaction paid in cash');
  553.                     return $this->redirectToRoute('one_way_bill', ['id' => $id]);
  554.                 } catch (\PDOException $e) {
  555.                     $em->getConnection()->rollBack();
  556.                     $this->addFlash('error''An Error Occurred Please check whether every thing is ok or contact admin');
  557.                     return $this->redirectToRoute('one_way_bill', ['id' => $id]);
  558.                 }
  559.             }
  560.         }
  561.         $form $this->createForm(WayBillExpense::class, $wayBillExpense);
  562.         $form->handleRequest($request);
  563.         if ($form->isSubmitted() && $form->isValid()) {
  564.             $wayBillExpense->setTransaction($transaction);
  565.             $wayBillExpense->setCreatedBy($this->getUser());
  566.             $wayBillExpense->setCreatedAt(new \DateTime());
  567.             $conn $em->getConnection();
  568.             $conn->beginTransaction();
  569.             try {
  570.                 $em->persist($wayBillExpense);
  571.                 $em->flush();
  572.                 $em->getConnection()->commit();
  573.                 $this->addFlash('success''Expense Updated Successfully');
  574.                 return $this->redirectToRoute('one_way_bill', ['id' => $transaction->getWayBill()->getId()]);
  575.             } catch (\PDOException $e) {
  576.                 $em->getConnection()->rollBack();
  577.                 $this->addFlash('error''An Error Occurred Please check whether every thing is filled');
  578.                 return $this->render('fos/parcels/view_parcel.html.twig', [
  579.                     'transaction' => $transaction,
  580.                     'daily_account' => $dailyAccount,
  581.                     'parcels' => $parcels,
  582.                     'form' => $form->createView(),
  583.                     'cancelForm' => $cancelForm->createView(),
  584.                     'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
  585.                     'isCancellable' => $isCancellable,
  586.                     'isMpesaAvailable' => $isMpesaAvailable,
  587.                     'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
  588.                     'tims' => $timsSupport
  589.                 ]);
  590.             }
  591.         }
  592.         return $this->render('fos/parcels/view_parcel.html.twig', [
  593.             'transaction' => $transaction,
  594.             'daily_account' => $dailyAccount,
  595.             'parcels' => $parcels,
  596.             'form' => $form->createView(),
  597.             'cancelForm' => $cancelForm->createView(),
  598.             'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
  599.             'isCancellable' => $isCancellable,
  600.             'isMpesaAvailable' => $isMpesaAvailable,
  601.             'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
  602.             'tims' => $timsSupport,
  603.             'sms' => $sms,
  604.             'statusChart' => $this->smsStatus
  605.         ]);
  606.     }
  607.     /**
  608.      * @Route("/way_bill/parcel/{parcel_id}", name="one_waybill_parcel")
  609.      * @param $parcel_id
  610.      * @return Response
  611.      */
  612.     public function getParcelDeliveryData($parcel_id)
  613.     {
  614.         $em $this->getDoctrine()->getManager();
  615.         $isEnRoute false;
  616.         $isInDelivery false;
  617.         $deliveryParcel $em->getRepository(DeliveryParcel::class)->findOneBy([
  618.             'isCancelled' => false,
  619.             'parcel' => $parcel_id
  620.         ]);
  621.         if ($deliveryParcel) {
  622.             $isInDelivery true;
  623.             $deliveryVehicle $em->getRepository(DeliveryVehicle::class)->findOneBy([
  624.                 'isCancelled' => false,
  625.                 'delivery' => $deliveryParcel->getDelivery()
  626.             ]);
  627.             if ($deliveryVehicle) {
  628.                 $isEnRoute true;
  629.                 return $this->render('fos/parcels/parcel_status.html.twig', [
  630.                     'isEnRoute' => $isEnRoute,
  631.                     'inDelivery' => $isInDelivery,
  632.                     'delivery_parcel' => $deliveryParcel,
  633.                     'delivery_vehicle' => $deliveryVehicle
  634.                 ]);
  635.             }
  636.             return $this->render('fos/parcels/parcel_status.html.twig', [
  637.                 'isEnRoute' => $isEnRoute,
  638.                 'inDelivery' => $isInDelivery,
  639.                 'delivery_parcel' => $deliveryParcel
  640.             ]);
  641.         }
  642.         return $this->render('fos/parcels/parcel_status.html.twig', [
  643.             'isEnRoute' => $isEnRoute,
  644.             'inDelivery' => $isInDelivery,
  645.             'delivery_parcel' => null
  646.         ]);
  647.     }
  648.     /**
  649.      * @Route("/form/towns",methods={"GET"}, name="form_towns")
  650.      */
  651.     public function getTowns(Request $request)
  652.     {
  653.         $queryTerm $request->get('q');
  654.         $em $this->getDoctrine()->getManager();
  655.         $towns $em->getRepository(Station::class)->findFormTown($queryTerm);
  656.         $serializer SerializerBuilder::create()->build();
  657.         $town = new Station();
  658.         $town->setStationName('ALL STATIONS');
  659.         $town->setId(-1);
  660.         array_push($towns$town);
  661.         $data $serializer->serialize($towns'json');
  662.         return new Response($dataResponse::HTTP_OK);
  663.     }
  664.     private function cancelTransactionForm($id)
  665.     {
  666.         $fb $this->createFormBuilder();
  667.         return $fb
  668.             ->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
  669.             ->setMethod('POST')
  670.             ->getForm();
  671.     }
  672.     private function cashPaymentOptionForm($id)
  673.     {
  674. //        $fb = $this->createFormBuilder();
  675.         $fb $this->get('form.factory')->createNamedBuilder('cash_payment_mode');
  676.         return $fb
  677.             ->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
  678.             ->setMethod('POST')
  679.             ->getForm();
  680.     }
  681.     /**
  682.      * @Route("/receipt/{waybill_}", methods={"GET"}, name="receipt_action")
  683.      */
  684.     public function ReceiptAction(Request $request$waybill_MpdfFactory $MpdfFactory): Response
  685.     {
  686.         $em $this->getDoctrine()->getManager();
  687.         /** @var Transaction $transaction */
  688.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  689.             'wayBill' => $waybill_
  690.         ]);
  691.         $transaction->setIsComplete(true);
  692.         $transaction->setIsPaid(true);
  693.         $transaction->setIsFinal(true);
  694.         $em->flush();
  695.         $mpesa null;
  696.         if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH' ) {
  697.             $mpesa $em->getRepository(MpesaTransaction::class)->findOneBy([
  698.                 'transaction' => $transaction
  699.             ]);
  700.         }
  701.         /** @var WayBill $waybill */
  702.         $waybill $transaction->getWaybill();
  703.         $parcels $em->getRepository(Parcel::class)->findBy([
  704.             'waybill' => $waybill
  705.         ]);
  706.         $mPdf $MpdfFactory->createMpdfObject([
  707.             'mode' => 'utf-8',
  708.             'format' => [70254],
  709.             'margin_header' => 5,
  710.             'margin_footer' => 5,
  711.             'orientation' => 'P'
  712.         ]);
  713.         $date = new DateTime();
  714.         $time $date->getTimestamp();
  715.         $mPdf->SetTopMargin("50");
  716.         // get the logo image and change it to base64
  717.         $logoImage file_get_contents('../public/logo.png');
  718.         $logoBase64 base64_encode($logoImage);
  719. //            dump($logoBase64);
  720. //        $o =  $output->output($qrCode, 100, 'white', 'black');
  721. //        $mPdf->SetHTMLHeader($this->renderView('twigfolder/pdf/pdf_header.html.twig', $TwigVars));
  722. //        $mPdf->SetFooter($this->renderView('twigfolder/pdf/pdf_footer.html.twig', $TwigVars));
  723.         $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  724.             'waybill' => $waybill,
  725.             'transaction' => $transaction,
  726.             'parcels' => $parcels,
  727.             'mpesa' => $mpesa,
  728.             'logoBase64' => $logoBase64,
  729.             'by' => $waybill->getCreatedBy()->getPerson(),
  730.             'receiptType' => "RECEIPT"
  731.         ]));
  732.         return $MpdfFactory->createDownloadResponse($mPdf"receipt_{$waybill_}.pdf"Response::HTTP_OK, ["Set-Cookie""fileDownload=true; path=/"]);
  733.     }
  734.     private function makeCreditNote(Transaction $transactionMpdfFactory $MpdfFactory): Response
  735.     {
  736.         $em $this->em;
  737.         /** @var Etr $etr */
  738.         $etr $em->getRepository(Etr::class)->findOneBy([
  739.             'isDefault' => 1
  740.         ]);
  741.        try{
  742.             $tremolInitiator = new TremolInitiator($em$etr);
  743.         }catch(Exception $e){
  744.             dump($e);
  745.             $this->addFlash("warn");
  746.             return $this->redirectToRoute("one_way_bill"$transaction->getWayBill()->getId());
  747.         }
  748.         $mpesa null;
  749.         if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
  750.             /** @var MpesaTransaction $mpesa */
  751.             $mpesa $em->getRepository(MpesaTransaction::class)->findOneBy([
  752.                 'transaction' => $transaction
  753.             ]);
  754.         }
  755.         /** @var WayBill $waybill */
  756.         $waybill $transaction->getWaybill();
  757.         $parcels $em->getRepository(Parcel::class)->findBy([
  758.             'waybill' => $waybill
  759.         ]);
  760.         $mPdf $MpdfFactory->createMpdfObject([
  761.             'mode' => 'utf-8',
  762.             'format' => [70230],
  763.             'margin_header' => 5,
  764.             'margin_footer' => 5,
  765.             'orientation' => 'P'
  766.         ]);
  767.         $date = new DateTime();
  768.         $time $date->getTimestamp();
  769.         $mPdf->SetTopMargin("1");
  770.         try  {
  771.             $invoiceNumber $transaction->getCuInvoiceNumber();
  772.             $receiptType 'CREDIT NOTE';
  773.             if ($invoiceNumber and $transaction->getIsFinal()) {
  774.                 /** @var Etr $etr */
  775.                 $etr $em->getRepository(Etr::class)->findOneBy([
  776.                     'serialNumber' => $transaction->getCuSerialNumber()
  777.                 ]);
  778.                 if($etr && !$etr->isDefault()){
  779.                     $message "The CU Device {$transaction->getCuSerialNumber()} is not currently the default device on the network Please contact admin";
  780.                     return new Response($messageResponse::HTTP_BAD_REQUEST);
  781.                 }
  782.                 if ($transaction->getPinNumber()) {
  783.                     TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
  784.                         '',
  785.                         $transaction->getPinNumber(),
  786.                         '',
  787.                         '',
  788.                         '',
  789.                         '',
  790.                         $transaction->getCuInvoiceNumber(),
  791.                         $waybill->getId()
  792.                     );
  793.                 } else {
  794.                     TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
  795.                         '',
  796.                         '',
  797.                         '',
  798.                         '',
  799.                         '',
  800.                         '',
  801.                         $transaction->getCuInvoiceNumber(),
  802.                         $waybill->getId()
  803.                     );
  804.                 }
  805.                 $parcelCount $waybill->getPercelCount();
  806.                 foreach ($parcels as $index => $parcel) {
  807.                     TremolInitiator::$FP->SellPLUfromExtDB($parcel->getDescription(),
  808.                         'A',
  809.                         ($transaction->getAmount() / $parcelCount),
  810.                         '',
  811.                         '',
  812.                         '',
  813.                         16.00,
  814.                         1
  815.                     );
  816.                 }
  817.                 $rec TremolInitiator::$FP->CloseReceipt();
  818.                 $invoiceNumber $rec->InvoiceNum;
  819.                 $creditNote = new DebitCreditNote();
  820.                 $creditNote->setAmount($transaction->getAmount());
  821.                 $creditNote->setTransaction($transaction);
  822.                 $creditNote->setCreatedAt(new Datetime());
  823.                 $creditNote->setCuInvoiceNumber($invoiceNumber);
  824.                 $creditNote->setTransactionType('CREDITNOTE');
  825.                 $em->persist($creditNote);
  826.                 if($mpesa){
  827.                     $mpesa->getMpesa()->setIsUsed(false);
  828.                     $em->remove($mpesa);
  829.                 }
  830.             }
  831.             $transaction->setIsComplete(true);
  832.             $transaction->setMpesaAmount(0);
  833.             $transaction->setCashAmount(0);
  834.             $transaction->setIsFinal(true);
  835.             $transaction->setTaxAmount(0);
  836.             $transaction->setIsCancelled(true);
  837.             $em->flush();
  838.             // get the logo image and change it to base64
  839.             $logoImage file_get_contents('../public/logo.png');
  840.             $logoBase64 base64_encode($logoImage);
  841. //            dump($logoBase64);
  842.             // create TIMS QRCODE change it to base64;
  843.             $timsQRCode 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' $invoiceNumber;
  844.             $timsqrCode = new QrCode($timsQRCode);
  845.             $output = new Png();
  846.             $timsQRCodeData $output->output($timsqrCode100, [255255255], [000]);
  847.             $base64 base64_encode($timsQRCodeData);
  848.             $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  849.                 'waybill' => $waybill,
  850.                 'transaction' => $transaction,
  851.                 'parcels' => $parcels,
  852.                 'mpesa' => $mpesa,
  853.                 'qrcode' => $base64,
  854.                 'logoBase64' => $logoBase64,
  855.                 'timsInvoiceNumber' => $invoiceNumber,
  856.                 'by' => $waybill->getCreatedBy()->getPerson(),
  857.                 'receiptType' => $receiptType
  858.             ]));
  859.             return $MpdfFactory->createDownloadResponse($mPdf"receipt_credit_note{$waybill->getId()}.pdf"Response::HTTP_OK, ["Set-Cookie""fileDownload=true; path=/"]);
  860.         } catch (\Exception $e) {
  861.             return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
  862.         }
  863.     }
  864.     /**
  865.      * @Route("/receipt/g03/{waybill_}", methods={"GET"}, name="receipt_action_tremol")
  866.      */
  867.     public function ReceiptGO3Action(Request $request$waybill_MpdfFactory $MpdfFactory): Response
  868.     {
  869.         $em $this->getDoctrine()->getManager();
  870.         /** @var Transaction $transaction */
  871.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  872.             'wayBill' => $waybill_
  873.         ]);
  874.         $mpesa null;
  875.         if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
  876.             $mpesa $em->getRepository(MpesaTransaction::class)->findOneBy([
  877.                 'transaction' => $transaction
  878.             ]);
  879.         }
  880.         /** @var WayBill $waybill */
  881.         $waybill $transaction->getWaybill();
  882.         $parcels $em->getRepository(Parcel::class)->findBy([
  883.             'waybill' => $waybill
  884.         ]);
  885.         $mPdf $MpdfFactory->createMpdfObject([
  886.             'mode' => 'utf-8',
  887.             'format' => [70230],
  888.             'margin_header' => 0,
  889.             'margin_footer' => 0,
  890.             'orientation' => 'P'
  891.         ]);
  892.         $date = new DateTime();
  893.         $time $date->getTimestamp();
  894.         $mPdf->SetTopMargin("1");
  895.         $qrCode = new QrCode($waybill_);
  896.         /** @var Etr $etr */
  897.         $etr $em->getRepository(Etr::class)->findOneBy([
  898.             'isDefault' => 1
  899.         ]);
  900.         try {
  901.              //$fp->ServerSetSettings("192.168.13.125", 4444);
  902.             // $fp->SetServer_UsedComModule('LAN/WiFi');
  903.             // $fp->SetWiFi_Password(10,'mirage2222');
  904.             // $fp->SetTCP_Password(10,'mirage2222');
  905.             // $fp->SaveNetworkSettings();
  906.             
  907.            // $fp->ApplyClientLibraryDefinitions();
  908. //            var_dump($fp->ServerGetDeviceSettings());
  909. //            die;
  910.             $invoiceNumber $transaction->getCuInvoiceNumber();
  911.             $receiptType 'FISCAL RECEIPT COPY';
  912.             // dump($fp);
  913.             // die;
  914.              if (!$invoiceNumber and !$transaction->getIsFinal()) {
  915.                  try{
  916.                      $tremolInitiator = new TremolInitiator($this->em$etr);
  917.                  }catch(\Exception $e){
  918.                      dump($e);
  919.                  }
  920. //                $this->fp->ServerGetClients();
  921.                 $receiptType 'FISCAL RECEIPT';
  922.                 if ($transaction->getPinNumber()) {
  923.                     TremolInitiator::$FP->OpenInvoiceWithFreeCustomerData(
  924.                         '',
  925.                         $transaction->getPinNumber(),
  926.                         '',
  927.                         '',
  928.                         '',
  929.                         '',
  930.                         $waybill->getId()
  931.                     );
  932.                 } else {
  933.                     TremolInitiator::$FP->OpenReceipt(1$waybill->getId());
  934.                 }
  935.                 $parcelCount $waybill->getPercelCount();
  936.                 foreach ($parcels as $index => $parcel) {
  937.                     TremolInitiator::$FP->SellPLUfromExtDB($parcel->getDescription(),
  938.                         'A',
  939.                         ($transaction->getAmount() / $parcelCount),
  940.                         '',
  941.                         '',
  942.                         '',
  943.                         16.00,
  944.                         1
  945.                     );
  946.                 }
  947.                 $rec TremolInitiator::$FP->CloseReceipt();
  948. //                var_dump($rec);
  949.                 $invoiceNumber $rec->InvoiceNum;
  950.                 $transaction->setCuInvoiceNumber($invoiceNumber);
  951.                 $transaction->setIsComplete(true);
  952.                 $transaction->setIsPaid(true);
  953.                 $transaction->setIsFinal(true);
  954.                 $transaction->setCuSerialNumber($etr->getSerialNumber());
  955.                 $em->flush();
  956.             }
  957. //            $data = $output->output($qrCode, 100, [255, 255, 255], [0, 0, 0]);
  958.             //            file_put_contents('../public/qrcode.png', $data);
  959. //            file_put_contents('../public/timsQRCode.png', $timsQRCodeData);
  960. //            $dataFile = file_get_contents('../public/timsQRCode.png');
  961.             /*$image = imagecreatefromstring($dataFile);
  962.             $im = '../public/awesome.png';
  963.             imagepng($image, $im, 0);*/
  964.             // get the logo image and change it to base64
  965.             $logoImage file_get_contents('../public/logo.png');
  966.             $logoBase64 base64_encode($logoImage);
  967. //            dump($logoBase64);
  968.              // create TIMS QRCODE change it to base64;
  969.             $timsQRCode 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' $invoiceNumber;
  970.             $timsqrCode = new QrCode($timsQRCode);
  971.             $output = new Png();
  972.             $timsQRCodeData $output->output($timsqrCode100, [255255255], [000]);
  973.             $base64 base64_encode($timsQRCodeData);
  974.             $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  975.                 'waybill' => $waybill,
  976.                 'transaction' => $transaction,
  977.                 'parcels' => $parcels,
  978.                 'mpesa' => $mpesa,
  979.                 'qrcode' => $base64,
  980.                 'logoBase64' => $logoBase64,
  981.                 'timsInvoiceNumber' => $invoiceNumber,
  982.                 'by' => $waybill->getCreatedBy()->getPerson(),
  983.                 'receiptType' => $receiptType
  984.             ]));
  985.             return $MpdfFactory->createDownloadResponse($mPdf"receipt_{$waybill_}.pdf"Response::HTTP_OK, ["Set-Cookie""fileDownload=true; path=/"]);
  986.         } catch (\Exception $e) {
  987.              return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
  988.         }
  989. //        return new Response("error occurred");
  990.     }
  991.     /**
  992.      * @Route("/way_bill/{id}/complete", name="register_transaction_as_complete")
  993.      */
  994.     public function registerTransactionAsComplete($id)
  995.     {
  996.         $em $this->getDoctrine()->getManager();
  997. //        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
  998.         $connection = new AMQPStreamConnection('192.168.13.125'5672'guest''guest');
  999.         $channel $connection->channel();
  1000.         /** @var Transaction $transaction */
  1001.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  1002.             'wayBill' => $id
  1003.         ]);
  1004.         $transaction->setIsComplete(true);
  1005.         try {
  1006.             if (!$transaction->getIsPaid()) {
  1007.                 $transaction->setIsPaid(true);
  1008.                 $transaction->setCashAmount($transaction->getAmount());
  1009.                 $transaction->setPaymentMethod('CASH');
  1010.                 $transaction->setIsPaid(true);
  1011.             }
  1012.             $em->flush();
  1013.             $response = [
  1014.                 'is_complete' => true
  1015.             ];
  1016.             return new Response(json_encode($response), Response::HTTP_OK);
  1017.         } catch (\Exception $e) {
  1018.             $response = [
  1019.                 'is_complete' => false,
  1020.                 'error' => $e->getMessage()
  1021.             ];
  1022.             return new Response(json_encode($response), Response::HTTP_NOT_ACCEPTABLE);
  1023.         }
  1024.     }
  1025.     /**
  1026.      * @Route("/awesome", name="tims_awesomeness")
  1027.      */
  1028.     public function getKRASerials(){
  1029.         $em $this->getDoctrine()->getManager();
  1030.         for($x =19340;$x 0$x--) {
  1031.             $k sprintf('%010d'$x);
  1032.             $k '004079153'.$k;
  1033.             dump($k);
  1034.             $response $this->client->request(
  1035.                 'POST',
  1036.                 'https://itax.kra.go.ke/KRA-Portal/middlewareController.htm?actionCode=fetchInvoiceDtl',
  1037.                 [
  1038.                     'body' => [
  1039.                         'invNo' => "{$k}"
  1040.                     ]
  1041.                 ]
  1042.             );
  1043.             $json json_decode($response->getContent(),true);
  1044.             dump($json);
  1045.             if($json['traderSystemInvNo']){
  1046.                 dump($json['traderSystemInvNo']);
  1047.                 $transaction $em->getRepository(Transaction::class)->findOneBy([
  1048.                     'wayBill' => $json['traderSystemInvNo']
  1049.                 ]);
  1050.                 if($transaction){
  1051.                     $transaction->setCuInvoiceNumber($json['mwInvNo']);
  1052.                     $em->flush();
  1053.                 }
  1054.             }
  1055.         }
  1056.         die;
  1057.     }
  1058. }