src/Parcels/DailyAccountController.php line 39

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: parcel
  5.  * Date: 11/12/18
  6.  * Time: 8:49 PM
  7.  */
  8. namespace App\Parcels;
  9. use App\Entity\DailyAccount;
  10. use App\Entity\DailyAccountClosed;
  11. use App\Entity\Station;
  12. use App\Entity\StationDailyAccount;
  13. use App\Entity\StationExpense;
  14. use App\Entity\Transaction;
  15. use App\Entity\WayBill;
  16. use App\Form\DayCloseForm;
  17. use Doctrine\DBAL\Exception\ConstraintViolationException;
  18. use JMS\Serializer\SerializationContext;
  19. use JMS\Serializer\SerializerBuilder;
  20. use PDOException;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\Form\FormError;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. use Symfony\Component\Validator\Constraints\DateTime;
  28. class DailyAccountController extends AbstractController {
  29.     /**
  30.      * @Route("/close-daily-account", name="close_daily_account")
  31.      */
  32.     public function dailyParcelTransactions(Request $request) {
  33.         $em $this->getDoctrine()->getManager();
  34.         $openForm $this->openDayAccount();
  35.         $cancelExpenseForm $this->cancelExpense();
  36.         $expenses null;
  37.         $date = new \DateTime('today');
  38.         $accountData null;
  39.         $cancelledTransactions null;
  40.         $station $em->getRepository(Station::class)->findOneBy([
  41.             'id' => $request->getSession()->get('STATION')
  42.         ]);
  43.         /** @var DailyAccount $dailyAccount */
  44.         $dailyAccount $em->getRepository(DailyAccount::class)->findOneBy([
  45.             'user' => $this->getUser()
  46. //            'isClosed' => 0
  47.         ],['id' => 'DESC']);
  48.         if($dailyAccount){
  49.             $cancelledTransactions $em->getRepository(Transaction::class)->findBy([
  50.                 'isCancelled' => true,
  51.                 'dailyAccount' => $dailyAccount
  52.             ]);
  53.             $accountData $em->getRepository(DailyAccount::class)->findOneDailyAccount($dailyAccount->getId())[0];
  54. //            dump($accountData);die;
  55.             /** @var StationExpense $expenses */
  56.             $expenses $em->getRepository(StationExpense::class)->findBy([
  57.                 'dailyAccount' => $dailyAccount
  58.             ]);
  59.             $closeForm $this->createForm(DayCloseForm::class, $dailyAccount);
  60.             $closeForm->handleRequest($request);
  61.             if($closeForm->isSubmitted() && $closeForm->isValid()) {
  62.                 $data $closeForm->getData();
  63.                 $conn $em->getConnection();
  64.                 $conn->beginTransaction();
  65.                 try {
  66.                     $data $closeForm->getData();
  67.                     $dailyAccount->setIsClosed(true);
  68.                     $dailyAccount->setClosedBy($this->getUser());
  69.                     $dailyAccount->setDrawerCash($data->getDrawerCash());
  70.                     $em->flush();
  71.                     $em->getConnection()->commit();
  72.                     $date = new \DateTime();
  73.                     $date $date->format('Y-m-d');
  74.                     $this->addFlash('success'"Your Account for the day {$date} has been closed successfully ");
  75.                     return $this->redirectToRoute('close_daily_account');
  76.                 }catch (PDOException $exception) {
  77.                     $this->addFlash('error',' An Error Occurred While closing your account');
  78.                     $em->getConnection()->rollBack();
  79.                     return $this->redirectToRoute('close_daily_account');
  80.                 }catch (ConstraintViolationException $e) {
  81. //                dump($e->getMessage());die;
  82.                     $em->getConnection()->rollBack();
  83.                     $this->addFlash('error',' An Error Occurred While closing your account');
  84.                     return $this->redirectToRoute('close_daily_account');
  85.                 }
  86.             }
  87.         }
  88.         $openForm->handleRequest($request);
  89.         if($openForm->isSubmitted() && $openForm->isValid()){
  90.             if(!$dailyAccount || $dailyAccount->getisClosed()){
  91.                 /** @var StationDailyAccount $stationDailyAccount */
  92.                 $stationDailyAccount $em->getRepository(StationDailyAccount::class)->findOneBy([
  93.                     'station' => $request->getSession()->get('STATION'),
  94.                     'accountDate' => $date
  95.                 ],['id' => 'DESC']);
  96.                 if(!$stationDailyAccount) {
  97.                     $stationDailyAccount = new StationDailyAccount();
  98.                     $stationDailyAccount->setAccountDate($date);
  99.                     $stationDailyAccount->setCreatedAt($date);
  100.                     $stationDailyAccount->setIsClosed(false);
  101.                     $stationDailyAccount->setIsBanked(false);
  102.                     $stationDailyAccount->setCreatedBy($this->getUser());
  103.                     $stationDailyAccount->setStation($station);
  104.                     $em->persist($stationDailyAccount);
  105.                 }
  106.                 $dailyAccount = new DailyAccount();
  107.                 $dailyAccount->setIsClosed(false);
  108.                 $dailyAccount->setCreatedAt($date);
  109.                 $dailyAccount->setAccountDate($date);
  110.                 $dailyAccount->setUser($this->getUser());
  111.                 $dailyAccount->setStationDailyAccount($stationDailyAccount);
  112.                 $dailyAccount->setDrawerCash(0);
  113.                 $em->persist($dailyAccount);
  114.                 try {
  115.                     $em->flush();
  116.                     $date = new \DateTime();
  117.                     $date $date->format('Y-m-d');
  118.                     $this->addFlash('success'"Your Account for the day {$date} has been created");
  119.                     return $this->redirectToRoute('close_daily_account');
  120.                 }catch (PDOException $exception) {
  121.                     $this->addFlash('error',' An Error Occurred While creating the an account');
  122.                     return $this->redirectToRoute('close_daily_account');
  123.                 }
  124.             }
  125.         }else if(!$dailyAccount){
  126.             return $this->render('fos/transactions/daily_account.html.twig', [
  127.                 'form' => $openForm->createView(),
  128.             ]);
  129.         }
  130.         return $this->render('fos/transactions/daily_account.html.twig', [
  131.             'dailyAccount' => $dailyAccount,
  132.             'account_data' => $accountData,
  133.             'form' => $openForm->createView(),
  134.             'stationAccount' => $dailyAccount->getStationDailyAccount(),
  135.             'closeForm' => $closeForm->createView(),
  136.             'expenses' => $expenses,
  137.             'cancelExpenseForm' => $cancelExpenseForm->createView(),
  138.             'cancelledTransactions' => $cancelledTransactions
  139.         ]);
  140.     }
  141.     private function closeDayAccount() {
  142.         $fb $this->createFormBuilder();
  143. //        $fb->getFormFactory()->createNamed('user_account');
  144.         return $fb
  145.             ->setAction($this->generateUrl('close_daily_account'))
  146.             ->setMethod('POST')
  147.             ->getForm();
  148.     }
  149.     private function openDayAccount() {
  150.         $fb $this->createFormBuilder();
  151. //        $fb->getFormFactory()->createNamed('user_account');
  152.         return $fb
  153.             ->setAction($this->generateUrl('close_daily_account'))
  154.             ->setMethod('POST')
  155.             ->getForm();
  156.     }
  157.     private function openStationDayAccount() {
  158.         return $this->createFormBuilder()
  159. //            ->create('station_account')
  160.             ->setAction($this->generateUrl('close_daily_account'))
  161.             ->setMethod('PUT')
  162.             ->getForm();
  163.     }
  164.     private function closeStationDayAccount() {
  165.         return $this->createFormBuilder()
  166. //            ->create('station_account')
  167.             ->setAction($this->generateUrl('close_daily_account'))
  168.             ->setMethod('PUT')
  169.             ->getForm();
  170.     }
  171.     private function cancelExpense() {
  172.         return $this->createFormBuilder()
  173.             ->setMethod('PUT')
  174.             ->getForm();
  175.     }
  176.     /**
  177.      * @Route("/cancel_expense/{id}", name="cancel_daily_expense")
  178.      *
  179.      * Method has two parameters primary key for the station_expense table
  180.      * @param $id
  181.      * @todo  should cancel expense in the daily expenses table
  182.      * this means setting the isCancelled status in the table station_expense to true
  183.      * @todo get the object from the database by searching using the id provided in the parameters
  184.      * @todo get the last object in the table for the expense daily account
  185.      * the last entry in the table for a daily_account_id in the station_expense table stores the $expenseAccrued
  186.      * variable which keeps track of the total amount of expenses for that daily_account_id
  187.      * so we need
  188.      * cancel the stationExpense in the first response and keep the amount
  189.      * Subtract the amount from the second stationExpense
  190.      * This should also subtract the amount accrued for the dailyAccount transactions
  191.      * and thie method returns @return \Symfony\Component\HttpFoundation\RedirectResponse
  192.      */
  193.     public function cancelDailyExpense($id){
  194.         $em $this->getDoctrine()->getManager();
  195.         /** @var StationExpense $toCancelStationExpense */
  196.         $toCancelStationExpense $em->getRepository("App:StationExpense")->findOneBy([
  197.             'id' => $id,
  198.             'isCancelled' => false
  199.         ]);
  200. //        dump($toCancelStationExpense); die;
  201.         if(!$toCancelStationExpense){
  202.             $this->addFlash("warning","This expense is already cancelled");
  203.             return $this->redirectToRoute('close_daily_account');
  204.         }
  205.         $toReduceTotalStationAccount $em->getRepository("App:StationExpense")->findOneBy([
  206.             'dailyAccount' => $toCancelStationExpense->getDailyAccount()
  207.         ],['id'=>'DESC']);
  208.         $dailyAccountTotalExpenses  $toReduceTotalStationAccount->getExpenseAccrued();
  209.         $toCancelStationExpense->setIsCancelled(true);
  210.         $toReduceTotalStationAccount->setExpenseAccrued($dailyAccountTotalExpenses $toCancelStationExpense->getAmount());
  211.         /** @var DailyAccount $dailyAccount */
  212. //        $dailyAccount = $toCancelStationExpense->getDailyAccount();
  213. //        $dailyAccount->setAmount($dailyAccount->getAmount() + $toCancelStationExpense->getAmount());
  214. //        $dailyAccount->setExpenses($dailyAccount->getExpenses() - $toCancelStationExpense->getAmount());
  215. //        return $this->redirectToRoute('close_daily_account');
  216.         try{
  217.             $em->flush();
  218.             return $this->redirectToRoute('close_daily_account');
  219.         }catch (\PDOException $exception) {
  220.             return $this->redirectToRoute('close_daily_account');
  221.         }
  222.     }
  223.     /**
  224.      * @Route("/my/transactions", name="my_daily_parcel_transactions")
  225.      */
  226.     public function dailyTransactions() {
  227.         return $this->render('fos/transactions/my_daily_transaction.html.twig', []);
  228.     }
  229.     /**
  230.      * @Route("/my/transactions/transaction-list", name="my_all_transactions")
  231.      */
  232.     public function myDailyTransactions(Request $request) {
  233.         $em $this->getDoctrine()->getManager();
  234.         /** @var DailyAccount $dailyAccount */
  235.         $dailyAccount $em->getRepository(DailyAccount::class)->findOneBy([
  236.             'user' => $this->getUser()
  237. //            'isClosed' => false,
  238.         ],['id' => 'DESC']);
  239.         $context = new SerializationContext();
  240.         $context->setSerializeNull(true);
  241.         $serializer SerializerBuilder::create()->build();
  242.         if(!$request->getSession()->get('STATION')) {
  243.             $data = [
  244.                 'error' => 'User is not well registered'
  245.             ];
  246.             $data $serializer->serialize($data,'json'$context);
  247.             return new Response($dataResponse::HTTP_OK);
  248.         }
  249.         $station_id $request->getSession()->get('STATION');
  250.         $page $request->request->get('page') > $request->request->get('page'): 1;
  251.         $rows $request->request->get('rows') > $request->request->get('rows'): 20;
  252.         $offset = ($page 1)*$rows;
  253.         $filterRules $request->request->get('filterRules');
  254.         $parcelsData $em->getRepository(Transaction::class)->getMyFosDailyTransactions($dailyAccount->getId(), $this->getUser()->getId(), $station_id$filterRules$offset,$rows);
  255.         $parcels $parcelsData['transactions'];
  256.         $transactionDetails $parcelsData['totals'];
  257.         $total $parcelsData['count']['total'];
  258. //        dump($parcels);die;
  259.         /** @var integer $total */
  260. //        $total = $em->getRepository(Transaction::class)->findMyFosDailyParcelsTotalTransactions($dailyAccount, $this->getUser(), $station_id, $filterRules);
  261. //        $transactionDetails = $em->getRepository(Transaction::class)->myFosDailyTotals($dailyAccount, $this->getUser(), $station_id, $filterRules);
  262.         $transaction = new Transaction();
  263.         $transaction->setAmount(number_format($transactionDetails['amount']));
  264.         $transaction->setTaxAmount(number_format($transactionDetails['tax_amount']));
  265.         $transaction->setStationExpenses(number_format($transactionDetails['station_expenses']));
  266.         $transaction->setBalance(number_format($transactionDetails['balance']));
  267.         $wayBill = new WayBill();
  268.         $wayBill->setPercelCount(number_format($transactionDetails['parcel_count']));
  269.         $wayBill->setReceiverPhoneNumber('Total');
  270.         $wayBill->setFromStation(new Station());
  271.         $wayBill->setToStation(new Station());
  272.         $transaction->setWayBill($wayBill);
  273.         $footerTotals = array();
  274.         array_push($footerTotals$transaction);
  275.         $data = [
  276.             'total'  => $total,
  277.             'rows'   => $parcels,
  278.             'footer' => $footerTotals
  279.         ];
  280.         dump($footerTotals);
  281.         $data $serializer->serialize($data,'json'$context);
  282.         return new Response($dataResponse::HTTP_OK);
  283.     }
  284.     /**
  285.      * @Route("/my/transactions/details/{id}", methods={"GET"}, name="my_one_transaction_detail_parcel")
  286.      * @param $id
  287.      * @return Response|null
  288.      */
  289.     public function getDetailParcel($id){
  290.         $em $this->getDoctrine()->getManager();
  291.         $transaction $em->getRepository(Transaction::class)->findOneBy([
  292.             'wayBill' => $id
  293.         ]);
  294.         return $this->render('fos/transactions/transaction_detail.html.twig',[
  295.             'transaction' => $transaction
  296.         ]);
  297.     }
  298. }