<?php
/**
* Created by PhpStorm.
* User: parcel
* Date: 11/12/18
* Time: 8:49 PM
*/
namespace App\Parcels;
use App\Entity\DailyAccount;
use App\Entity\DailyAccountClosed;
use App\Entity\Station;
use App\Entity\StationDailyAccount;
use App\Entity\StationExpense;
use App\Entity\Transaction;
use App\Entity\WayBill;
use App\Form\DayCloseForm;
use Doctrine\DBAL\Exception\ConstraintViolationException;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerBuilder;
use PDOException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\DateTime;
class DailyAccountController extends AbstractController {
/**
* @Route("/close-daily-account", name="close_daily_account")
*/
public function dailyParcelTransactions(Request $request) {
$em = $this->getDoctrine()->getManager();
$openForm = $this->openDayAccount();
$cancelExpenseForm = $this->cancelExpense();
$expenses = null;
$date = new \DateTime('today');
$accountData = null;
$cancelledTransactions = null;
$station = $em->getRepository(Station::class)->findOneBy([
'id' => $request->getSession()->get('STATION')
]);
/** @var DailyAccount $dailyAccount */
$dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser()
// 'isClosed' => 0
],['id' => 'DESC']);
if($dailyAccount){
$cancelledTransactions = $em->getRepository(Transaction::class)->findBy([
'isCancelled' => true,
'dailyAccount' => $dailyAccount
]);
$accountData = $em->getRepository(DailyAccount::class)->findOneDailyAccount($dailyAccount->getId())[0];
// dump($accountData);die;
/** @var StationExpense $expenses */
$expenses = $em->getRepository(StationExpense::class)->findBy([
'dailyAccount' => $dailyAccount
]);
$closeForm = $this->createForm(DayCloseForm::class, $dailyAccount);
$closeForm->handleRequest($request);
if($closeForm->isSubmitted() && $closeForm->isValid()) {
$data = $closeForm->getData();
$conn = $em->getConnection();
$conn->beginTransaction();
try {
$data = $closeForm->getData();
$dailyAccount->setIsClosed(true);
$dailyAccount->setClosedBy($this->getUser());
$dailyAccount->setDrawerCash($data->getDrawerCash());
$em->flush();
$em->getConnection()->commit();
$date = new \DateTime();
$date = $date->format('Y-m-d');
$this->addFlash('success', "Your Account for the day {$date} has been closed successfully ");
return $this->redirectToRoute('close_daily_account');
}catch (PDOException $exception) {
$this->addFlash('error',' An Error Occurred While closing your account');
$em->getConnection()->rollBack();
return $this->redirectToRoute('close_daily_account');
}catch (ConstraintViolationException $e) {
// dump($e->getMessage());die;
$em->getConnection()->rollBack();
$this->addFlash('error',' An Error Occurred While closing your account');
return $this->redirectToRoute('close_daily_account');
}
}
}
$openForm->handleRequest($request);
if($openForm->isSubmitted() && $openForm->isValid()){
if(!$dailyAccount || $dailyAccount->getisClosed()){
/** @var StationDailyAccount $stationDailyAccount */
$stationDailyAccount = $em->getRepository(StationDailyAccount::class)->findOneBy([
'station' => $request->getSession()->get('STATION'),
'accountDate' => $date
],['id' => 'DESC']);
if(!$stationDailyAccount) {
$stationDailyAccount = new StationDailyAccount();
$stationDailyAccount->setAccountDate($date);
$stationDailyAccount->setCreatedAt($date);
$stationDailyAccount->setIsClosed(false);
$stationDailyAccount->setIsBanked(false);
$stationDailyAccount->setCreatedBy($this->getUser());
$stationDailyAccount->setStation($station);
$em->persist($stationDailyAccount);
}
$dailyAccount = new DailyAccount();
$dailyAccount->setIsClosed(false);
$dailyAccount->setCreatedAt($date);
$dailyAccount->setAccountDate($date);
$dailyAccount->setUser($this->getUser());
$dailyAccount->setStationDailyAccount($stationDailyAccount);
$dailyAccount->setDrawerCash(0);
$em->persist($dailyAccount);
try {
$em->flush();
$date = new \DateTime();
$date = $date->format('Y-m-d');
$this->addFlash('success', "Your Account for the day {$date} has been created");
return $this->redirectToRoute('close_daily_account');
}catch (PDOException $exception) {
$this->addFlash('error',' An Error Occurred While creating the an account');
return $this->redirectToRoute('close_daily_account');
}
}
}else if(!$dailyAccount){
return $this->render('fos/transactions/daily_account.html.twig', [
'form' => $openForm->createView(),
]);
}
return $this->render('fos/transactions/daily_account.html.twig', [
'dailyAccount' => $dailyAccount,
'account_data' => $accountData,
'form' => $openForm->createView(),
'stationAccount' => $dailyAccount->getStationDailyAccount(),
'closeForm' => $closeForm->createView(),
'expenses' => $expenses,
'cancelExpenseForm' => $cancelExpenseForm->createView(),
'cancelledTransactions' => $cancelledTransactions
]);
}
private function closeDayAccount() {
$fb = $this->createFormBuilder();
// $fb->getFormFactory()->createNamed('user_account');
return $fb
->setAction($this->generateUrl('close_daily_account'))
->setMethod('POST')
->getForm();
}
private function openDayAccount() {
$fb = $this->createFormBuilder();
// $fb->getFormFactory()->createNamed('user_account');
return $fb
->setAction($this->generateUrl('close_daily_account'))
->setMethod('POST')
->getForm();
}
private function openStationDayAccount() {
return $this->createFormBuilder()
// ->create('station_account')
->setAction($this->generateUrl('close_daily_account'))
->setMethod('PUT')
->getForm();
}
private function closeStationDayAccount() {
return $this->createFormBuilder()
// ->create('station_account')
->setAction($this->generateUrl('close_daily_account'))
->setMethod('PUT')
->getForm();
}
private function cancelExpense() {
return $this->createFormBuilder()
->setMethod('PUT')
->getForm();
}
/**
* @Route("/cancel_expense/{id}", name="cancel_daily_expense")
*
* Method has two parameters primary key for the station_expense table
* @param $id
* @todo should cancel expense in the daily expenses table
* this means setting the isCancelled status in the table station_expense to true
* @todo get the object from the database by searching using the id provided in the parameters
* @todo get the last object in the table for the expense daily account
* the last entry in the table for a daily_account_id in the station_expense table stores the $expenseAccrued
* variable which keeps track of the total amount of expenses for that daily_account_id
* so we need
* cancel the stationExpense in the first response and keep the amount
* Subtract the amount from the second stationExpense
* This should also subtract the amount accrued for the dailyAccount transactions
* and thie method returns @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function cancelDailyExpense($id){
$em = $this->getDoctrine()->getManager();
/** @var StationExpense $toCancelStationExpense */
$toCancelStationExpense = $em->getRepository("App:StationExpense")->findOneBy([
'id' => $id,
'isCancelled' => false
]);
// dump($toCancelStationExpense); die;
if(!$toCancelStationExpense){
$this->addFlash("warning","This expense is already cancelled");
return $this->redirectToRoute('close_daily_account');
}
$toReduceTotalStationAccount = $em->getRepository("App:StationExpense")->findOneBy([
'dailyAccount' => $toCancelStationExpense->getDailyAccount()
],['id'=>'DESC']);
$dailyAccountTotalExpenses = $toReduceTotalStationAccount->getExpenseAccrued();
$toCancelStationExpense->setIsCancelled(true);
$toReduceTotalStationAccount->setExpenseAccrued($dailyAccountTotalExpenses - $toCancelStationExpense->getAmount());
/** @var DailyAccount $dailyAccount */
// $dailyAccount = $toCancelStationExpense->getDailyAccount();
// $dailyAccount->setAmount($dailyAccount->getAmount() + $toCancelStationExpense->getAmount());
// $dailyAccount->setExpenses($dailyAccount->getExpenses() - $toCancelStationExpense->getAmount());
// return $this->redirectToRoute('close_daily_account');
try{
$em->flush();
return $this->redirectToRoute('close_daily_account');
}catch (\PDOException $exception) {
return $this->redirectToRoute('close_daily_account');
}
}
/**
* @Route("/my/transactions", name="my_daily_parcel_transactions")
*/
public function dailyTransactions() {
return $this->render('fos/transactions/my_daily_transaction.html.twig', []);
}
/**
* @Route("/my/transactions/transaction-list", name="my_all_transactions")
*/
public function myDailyTransactions(Request $request) {
$em = $this->getDoctrine()->getManager();
/** @var DailyAccount $dailyAccount */
$dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
'user' => $this->getUser()
// 'isClosed' => false,
],['id' => 'DESC']);
$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');
$parcelsData = $em->getRepository(Transaction::class)->getMyFosDailyTransactions($dailyAccount->getId(), $this->getUser()->getId(), $station_id, $filterRules, $offset,$rows);
$parcels = $parcelsData['transactions'];
$transactionDetails = $parcelsData['totals'];
$total = $parcelsData['count']['total'];
// dump($parcels);die;
/** @var integer $total */
// $total = $em->getRepository(Transaction::class)->findMyFosDailyParcelsTotalTransactions($dailyAccount, $this->getUser(), $station_id, $filterRules);
// $transactionDetails = $em->getRepository(Transaction::class)->myFosDailyTotals($dailyAccount, $this->getUser(), $station_id, $filterRules);
$transaction = new Transaction();
$transaction->setAmount(number_format($transactionDetails['amount']));
$transaction->setTaxAmount(number_format($transactionDetails['tax_amount']));
$transaction->setStationExpenses(number_format($transactionDetails['station_expenses']));
$transaction->setBalance(number_format($transactionDetails['balance']));
$wayBill = new WayBill();
$wayBill->setPercelCount(number_format($transactionDetails['parcel_count']));
$wayBill->setReceiverPhoneNumber('Total');
$wayBill->setFromStation(new Station());
$wayBill->setToStation(new Station());
$transaction->setWayBill($wayBill);
$footerTotals = array();
array_push($footerTotals, $transaction);
$data = [
'total' => $total,
'rows' => $parcels,
'footer' => $footerTotals
];
dump($footerTotals);
$data = $serializer->serialize($data,'json', $context);
return new Response($data, Response::HTTP_OK);
}
/**
* @Route("/my/transactions/details/{id}", methods={"GET"}, name="my_one_transaction_detail_parcel")
* @param $id
* @return Response|null
*/
public function getDetailParcel($id){
$em = $this->getDoctrine()->getManager();
$transaction = $em->getRepository(Transaction::class)->findOneBy([
'wayBill' => $id
]);
return $this->render('fos/transactions/transaction_detail.html.twig',[
'transaction' => $transaction
]);
}
}