src/Controller/DonationController.php line 236

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\FilmProject;
  4. use App\Entity\RecurringDonation;
  5. use App\Entity\User;
  6. use App\Form\DonationFormType;
  7. use App\Repository\DonationRepository;
  8. use App\Repository\FilmProjectRepository;
  9. use App\Repository\RecurringDonationRepository;
  10. use App\Service\DonationService;
  11. use App\Service\UserBillingService;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\JsonResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. class DonationController extends AbstractController
  19. {
  20.     #[Route('/donation'name'app_donation')]
  21.     public function index(Request $requestDonationService $donationServiceFilmProjectRepository $filmProjectRepositoryEntityManagerInterface $emUserBillingService $userBillingService): Response
  22.     {
  23.         $user $this->getUser();
  24.         $wordpressId $request->get('wpId');
  25.         $filmProject $filmProjectRepository->findOneBy(['wordpressId' => $wordpressId]);
  26.         if (empty($filmProject) || empty($request->get('wpId'))) {
  27.             return $this->render('donation/error.html.twig', [
  28.                 'title' => 'Project is not available',
  29.                 'message' => 'The project that you are looking for is not available. Please select other projects to donate.',
  30.             ]);
  31.         }
  32.         if ($user) {
  33.             if ($this->checkOwnershipProject($user$filmProject)) { // Check ownership project
  34.                 return $this->render('donation/error.html.twig', [
  35.                     'title' => 'You are not allowed to donate to this project',
  36.                     'message' => 'The owner of this project is not allowed to donate to the project that the owner created.',
  37.                 ]);
  38.             }
  39.         }
  40.         $isRecurringParam $request->get('is_recurring'); // Check if is recurring donation
  41.         $recurringDetails null;
  42.         if ($isRecurringParam == 1) {
  43.             $recurringDetails $this->getRecurringDetails($request);
  44.         }
  45.         $amount = (float)$request->get('amount');
  46.         $supportdaf 0// CHECK IF THERE IS ANY DAF DONATION
  47.         if ($request->get('supportdaf')) {
  48.             $supportdaf $request->get('supportdaf');
  49.         }
  50.         
  51.         $donation $donationService->createObject($user$filmProject, (($request->get('amount')) * 100), $recurringDetails, ($supportdaf 100)); // Create object 
  52.         $cards $userBillingService->getCurrentSavedCards(); // Get saved cards
  53.         $form $this->createForm(DonationFormType::class, $donation);
  54.         $form->handleRequest($request);
  55.         if ($form->isSubmitted() && $form->isValid()) {
  56.             $entityInstance $form->getData();
  57.             $cardID $request->request->get('card_payment');
  58.             $addCard $request->request->get('add_card');
  59.             if ($isRecurringParam == 1) {
  60.                 $addCard 1// FORCE ADDING PAYMENT CARD TOKEN IF DONATION IS RECURRING
  61.             }
  62.             $donationService->proceedPayment($entityInstance$cardID$addCard);
  63.             // if recurring 
  64.             if ($isRecurringParam == 1) {
  65.                 $entityInstance $donationService->updateRecurringDonation($entityInstance);
  66.             }
  67.             $donationService->dispatchPersistEntity($entityInstance);
  68.             $em->persist($entityInstance);
  69.             $em->flush();
  70.             return $this->redirectToRoute('app_donation_thankyou', ['projectId' => $filmProject->getId()]);
  71.         }
  72.         return $this->render('donation/index.html.twig', [
  73.             'form' => $form->createView(),
  74.             'user' => $user,
  75.             'cards' => $cards,
  76.             'amount' => $amount,
  77.             'project' => $filmProject,
  78.             'product' => $filmProject->getProduct(),
  79.             'supportdaf' => $supportdaf,
  80.             'total' => $amount $supportdaf,
  81.             'wordpressId' => $wordpressId
  82.         ]);
  83.     }
  84.     #[Route('/support-our-work'name'app_daf_donation')]
  85.     public function dafDonation(Request $requestDonationService $donationServiceEntityManagerInterface $em
  86.         UserBillingService $userBillingServiceFilmProjectRepository $filmProjectRepository): Response
  87.     {
  88.         $user $this->getUser();
  89.         $isRecurringParam $request->get('is_recurring'); // Check if is recurring donation
  90.         $recurringDetails null;
  91.         if ($isRecurringParam == 1) {
  92.             $recurringDetails $this->getRecurringDetails($request);
  93.         }
  94.         $supportdaf = (float)$request->get('supportdaf');
  95.         $supportProjectId = (float)$request->get('supportprojectid');
  96.         $supportProject $filmProjectRepository->findOneBy(['wordpressId' => $supportProjectId]);
  97.         
  98.         $donation $donationService->createDafDonationObject($user$supportdaf 100$recurringDetails$supportProject); // Create object 
  99.         if($supportProject->isIsDafProgram()) {
  100.             $donation =  $donationService->createObject($user$supportProject$supportdaf 100$recurringDetails); // Create object as normal project if it's daf program 
  101.         }
  102.         
  103.         $cards $userBillingService->getCurrentSavedCards(); // Get saved cards
  104.         $form $this->createForm(DonationFormType::class, $donation);
  105.         $form->handleRequest($request);
  106.         if ($form->isSubmitted() && $form->isValid()) {
  107.             $entityInstance $form->getData();
  108.             $cardID $request->request->get('card_payment');
  109.             $addCard $request->request->get('add_card');
  110.             if ($isRecurringParam == 1) {
  111.                 $addCard 1// FORCE ADDING PAYMENT CARD TOKEN IF DONATION IS RECURRING
  112.             }
  113.             $donationService->proceedPayment($entityInstance$cardID$addCard);
  114.             // if recurring 
  115.             if ($isRecurringParam == 1) {
  116.                 $entityInstance $donationService->updateRecurringDonation($entityInstance);
  117.             }
  118.             $donationService->dispatchPersistEntity($entityInstance);
  119.             $em->persist($entityInstance);
  120.             $em->flush();
  121.             return $this->redirectToRoute('app_donation_thankyou', ['projectId' => $supportProject->getId()]);
  122.         }
  123.         return $this->render('donation/index.html.twig', [
  124.             'form' => $form->createView(),
  125.             'user' => $user,
  126.             'cards' => $cards,
  127.             'project' => null,
  128.             'amount' => $supportdaf,
  129.             'supportdaf' => $supportdaf,
  130.             'total' => $supportdaf
  131.         ]);
  132.     }
  133.     #[Route('/donation/thank-you'name'app_donation_thankyou')]
  134.     public function finishPage(Request $requestEntityManagerInterface $em)
  135.     {
  136.         $projectRepo $em->getRepository(FilmProject::class);
  137.         $projectId $request->get('projectId');
  138.         $filmProject $projectRepo->findOneBy(['id' => $projectId]);
  139.         if (empty($filmProject)) {
  140.             return $this->render('donation/thankyou.html.twig');
  141.         }
  142.         return $this->render('donation/thankyou.html.twig', [
  143.             'filmProject' => $filmProject
  144.         ]);
  145.     }
  146.     #[Route('/donation/recurring-payment'name'app_donation_recurring_payment')]
  147.     public function recurringDonationPayment(Request $requestRecurringDonationRepository $recurringDonationRepositoryDonationService $donationServiceEntityManagerInterface $em): Response
  148.     {
  149.         // $page = $request->get('page'); // one page has 50 recurring entities
  150.         $recurringDonations $recurringDonationRepository->findTodayRecurringDonation(); // Get active recurring donations
  151.         if (empty($recurringDonations)) {
  152.             return new Response('No active recurring donations');
  153.         }
  154.         $resultMsg = [];
  155.         foreach ($recurringDonations as $recurringDonation) {
  156.             $donations $recurringDonation->getDonations(); // Get previous donations
  157.             $previousDonation $donations[0];
  158.             $previousOrderDetails $previousDonation->getOrderDetails();
  159.             $previousOrderBillingDetails $previousOrderDetails->getOrderBillingDetails();
  160.             $prevFilmProject $previousDonation->getFilmProject();
  161.             if ($prevFilmProject) {
  162.                 if (!$this->checkRecurringPastCampaignDate($recurringDonation$prevFilmProject)) { // Check if eligible to pay
  163.                     array_push($resultMsg$prevFilmProject->getTitle() . ' campaign has ended.');
  164.                     continue;
  165.                 }
  166.                 if (!$this->checkRecurringEligible($recurringDonation)) { // Check if eligible to pay
  167.                     array_push($resultMsg'Recurring Donation under name '$previousOrderBillingDetails->getFullName() .' is not eligible to pay yet.');
  168.                     continue;
  169.                 }
  170.             }
  171.             $newDonation $donationService->recreateDonationForRecurringDonation($previousDonation); // Recreate new object and orderDetails
  172.             $donationService->proceedPayment($newDonation$recurringDonation->getCardId());
  173.             $donationService->updateRecurringDonationTimeline($newDonation);   
  174.             
  175.             // Empty Xero and Salesforce ID
  176.             $newOrderDetails $newDonation->getOrderDetails();
  177.             $newOrderDetails
  178.                 ->setXeroId(null)
  179.                 ->setXeroContactId(null)
  180.                 ->setSalesforceId(null)
  181.             ;
  182.             $em->persist($newOrderDetails);
  183.             $em->flush();
  184.             if ($prevFilmProject) {
  185.                 $donationService->dispatchPersistEntity($newDonation);
  186.                 array_push($resultMsg'Recurring Donation under name '$previousOrderBillingDetails->getFullName() .' with project '$prevFilmProject->getTitle() .' has been paid.');
  187.             } else {
  188.                 $donationService->dispatchPersistEntity($newDonationtrue);
  189.                 array_push($resultMsg'Recurring Donation under name '$previousOrderBillingDetails->getFullName() .' for DAF Donation has been paid.');
  190.             }
  191.             $donationService->updateRecurringDonation($newDonation);
  192.         }
  193.         return new JsonResponse($resultMsg);
  194.     }
  195.     #[Route('/donation/dataset'name'app_donation_dataset')]
  196.     public function getDonationDataset(Request $requestFilmProjectRepository $filmProjectRepositoryDonationRepository $donationRepository): Response
  197.     {
  198.         $projectId $request->get('id');
  199.         $period $request->get('period');
  200.         $filmProject $filmProjectRepository->findOneBy(['id' => $projectId]);
  201.         $donations null;
  202.         if ($filmProject) {
  203.             // $donations = $filmProject->getDonations();
  204.             $donations $donationRepository->findDonationsByProjectOrderDate($filmProject->getId());
  205.         }
  206.         $dataset = [
  207.             'dataset'   => [],
  208.             'total'     => [],
  209.         ];
  210.         $numberOfDays 7;
  211.         switch($period) {
  212.             case '2 weeks':
  213.                 $numberOfDays 14;
  214.                 break;
  215.             case '1 month':
  216.                 $numberOfDays 30;
  217.                 break;
  218.             case '3 months':
  219.                 $numberOfDays 90;
  220.                 break;
  221.             case '6 months':
  222.                 $numberOfDays 180;
  223.                 break;
  224.             case '1 year':
  225.                 $numberOfDays 365;
  226.                 break;
  227.             case 'fiscal year':
  228.                 $numberOfDays 365;
  229.                 break;
  230.             default:
  231.                 break;
  232.         }
  233.         // Gather collection of datetimes
  234.         $datetimes = [];
  235.         if ($period != 'fiscal year') {
  236.             for($i $numberOfDays 1$i >= 0$i--) {
  237.                 array_push($datetimes, new \DateTime('-'.$i.' days'));
  238.             }           
  239.         } else {
  240.             $now = new \DateTime();
  241.             $currentYear date('Y'); 
  242.             $previousyear $currentYear 1;
  243.             $currentFiscalYear = new \DateTime($currentYear .'-07-01');
  244.             $dateString = ( $now >= $currentFiscalYear ) ? $currentYear.'-07-01' $previousyear.'-07-01';
  245.             
  246.             // $dateString = $previousyear.'-07-01';
  247.             for($i 0$i $numberOfDays$i++) {
  248.                 $newDate = new \DateTime($dateString.' +'.$i.' days'); 
  249.                 array_push($datetimes$newDate);
  250.             }
  251.         }
  252.         // Get all donations for each datetime
  253.         $totalDonationAmount 0;
  254.         foreach ($datetimes as $datetime) {
  255.             $total 0;
  256.             if ($filmProject) {
  257.                 $donations $donationRepository->findDonationsByDate($datetime$filmProject->getId());
  258.             } else {
  259.                 $donations $donationRepository->findAllDonationsByDate($datetime);
  260.             }
  261.             foreach ($donations as $donation) {
  262.                 $orderDetails $donation->getOrderDetails();
  263.                 $total += $orderDetails->getTotal() / 100;
  264.                 // Need to exclude popup amount if there is one
  265.                 if ($filmProject) {
  266.                     if(!$filmProject->isIsDafCore()) {
  267.                         $supportdaf $donation->getSupportDaf();
  268.                         if ($supportdaf) { 
  269.                             $total -=  ($supportdaf 100);
  270.                         }
  271.                     }
  272.                 }
  273.             }
  274.             $totalDonationAmount += $total;
  275.             array_push($dataset['dataset'], $total);
  276.         }
  277.         array_push($dataset['total'], number_format($totalDonationAmount2));
  278.         return new JsonResponse($dataset);
  279.     }
  280.     
  281.     /**
  282.      * Return array of recurring details
  283.      *
  284.      * @param Request $request
  285.      * @return array
  286.      */
  287.     protected function getRecurringDetails(Request $request): array
  288.     {
  289.         $frequency $request->get('frequency');
  290.         $totalPeriod $request->get('total_period');
  291.         return [
  292.             'frequency' => $frequency// Can be weekly, monthly
  293.             'totalPeriod' => $totalPeriod// option here could be: 1,3,6,12 in months
  294.         ];
  295.     }
  296.     protected function checkRecurringEligible(RecurringDonation $recurringDonation): bool
  297.     {
  298.         $nextPaymentDate $recurringDonation->getNextPaymentDate();
  299.         $from = new \DateTime($nextPaymentDate->format("Y-m-d")." 00:00:00");
  300.         $to   = new \DateTime($nextPaymentDate->format("Y-m-d")." 23:59:59");
  301.         $currentDate = new \DateTime('now');
  302.         if ($currentDate >= $from && $currentDate <= $to) {
  303.             return true;
  304.         }
  305.         return false;
  306.     }
  307.     protected function checkRecurringPastCampaignDate(RecurringDonation $recurringDonationFilmProject $filmProject): bool
  308.     {
  309.         $filmProjectTimeline $filmProject->getFilmProjectTimeline();
  310.         $campaignEndDate $filmProjectTimeline->getFundraisingCampaignEndDate();
  311.         $currentDate = new \DateTime('now');
  312.         if ($currentDate <= $campaignEndDate) {
  313.             return true;
  314.         }
  315.         return false;
  316.     }
  317.     protected function checkOwnershipProject(User $userFilmProject $filmProject
  318.     {
  319.         $owner $filmProject->getOwner();
  320.         if ($owner == $user) {
  321.             return true;
  322.         }
  323.         return false;
  324.     }
  325.         #[Route('/donation/custom_test'name'app_donation_custom_test')]
  326.         public function runDonationCustomTest(Request $requestDonationRepository $donationRepositoryDonationService $donationService): Response
  327.         {
  328.             $id 10705;
  329.             $donation $donationRepository->findOneBy(['id' => $id]);
  330.             if (!$donation) {
  331.                 var_dump('donation is empty'); exit();
  332.             }
  333.             $donationService->dispatchPersistEntity($donation);
  334.         }
  335. }