<?php
namespace App\Controller\Admin;
use App\Entity\Donation;
use App\Entity\FilmProject;
use App\Entity\FilmProjectProgressReport;
use App\Form\FilmApplicationMemberType;
use App\Repository\ProductRepository;
use App\Repository\FilmProjectProgressReportRepository;
use App\Serializer\FilmProjectObjectConverter;
use App\Service\FilmApplicationService;
use App\Service\UserBillingService;
use App\Service\ProgressReportService;
use App\String\Constant;
use App\String\ProjectString;
use App\Utility\CsvExporter;
use App\Utility\DropdownValues;
use App\Utility\FormGenerator;
use App\Utility\PdfExporter;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\BatchActionDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CountryField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
use EasyCorp\Bundle\EasyAdminBundle\Field\HiddenField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\MoneyField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TelephoneField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\UrlField;
use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Knp\Snappy\Pdf;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Twig\Environment;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
class FilmProjectCrudController extends AbstractCrudController
{
private EntityManagerInterface $em;
private AdminUrlGenerator $adminUrlGenerator;
private FilmApplicationService $filmApplicationService;
private UserBillingService $userBillingService;
private $requestStack;
private ProgressReportService $progressReportService;
private bool $isProgressReport = false;
public function __construct(EntityManagerInterface $em, AdminUrlGenerator $adminUrlGenerator, FilmApplicationService $filmApplicationService, UserBillingService $userBillingService, RequestStack $requestStack, ProgressReportService $progressReportService)
{
$this->em = $em;
$this->adminUrlGenerator = $adminUrlGenerator;
$this->filmApplicationService = $filmApplicationService;
$this->userBillingService = $userBillingService;
$this->requestStack = $requestStack;
$this->progressReportService = $progressReportService;
}
public static function getEntityFqcn(): string
{
return FilmProject::class;
}
public function configureFields(string $pageName): iterable
{
$formGenerator = new FormGenerator();
$formFields = $formGenerator->generateForm(Constant::PROJECT_FORM);
$formFields = array_merge($formFields, [
// FormField::addTab('Additional Information')->addCssClass('application_payment')->setPermission(Constant::PORTAL_USER_ROLE),
TextField::new('orderDetails.orderBillingDetails.firstName', ProjectString::PROJECT_PAYMENT_FIRST_NAME)->setColumns(6)->hideOnIndex()->setRequired(true)->addCssClass('firstName'),
TextField::new('orderDetails.orderBillingDetails.lastName', ProjectString::PROJECT_PAYMENT_LAST_NAME)->setColumns(6)->hideOnIndex()->setRequired(true)->addCssClass('lastName'),
TextField::new('orderDetails.orderBillingDetails.organisation', ProjectString::PROJECT_PAYMENT_ORGANISATION)->setColumns(12)->hideOnIndex(),
TextField::new('orderDetails.orderBillingDetails.abn', ProjectString::PROJECT_PAYMENT_ABN)->setColumns(12)->hideOnIndex()->setRequired(true)->addCssClass('abn'),
TextField::new('orderDetails.orderBillingDetails.street', ProjectString::PROJECT_PAYMENT_STREET)->setColumns(12)->hideOnIndex()->setRequired(true)->addCssClass('streetAddress'),
TextField::new('orderDetails.orderBillingDetails.suburb', ProjectString::PROJECT_PAYMENT_SUBURB)->setColumns(4)->hideOnIndex()->setRequired(true)->addCssClass('suburb'),
ChoiceField::new('orderDetails.orderBillingDetails.state', ProjectString::PROJECT_PAYMENT_STATE)->setColumns(4)->hideOnIndex()->setRequired(true)->addCssClass('state')->setChoices(DropdownValues::$states),
CountryField::new('orderDetails.orderBillingDetails.country', ProjectString::PROJECT_PAYMENT_COUNTRY)->setColumns(4)->hideOnIndex()->setRequired(true)->addCssClass('country'),
TextField::new('orderDetails.orderBillingDetails.postcode', ProjectString::PROJECT_PAYMENT_POSTCODE)->setColumns(3)->hideOnIndex()->setRequired(true)->setFormTypeOptions([
'attr' => [
'maxlength' => 4,
'minlength' => 4,
]
])->addCssClass('postcode'),
TextField::new('orderDetails.orderBillingDetails.phoneNumber', ProjectString::PROJECT_PAYMENT_PHONE)->setColumns(4)->hideOnIndex()->setRequired(true)->addCssClass('phone'),
TextField::new('orderDetails.orderBillingDetails.emailAddress', ProjectString::PROJECT_PAYMENT_EMAIL)->setColumns(5)->hideOnIndex()->setRequired(true)->addCssClass('emailAddress'),
// Hidden fields for Merchant Warrior payment
HiddenField::new('orderDetails.orderBillingDetails.payframeToken')->hideOnIndex()->hideOnDetail()->setCssClass('mw-token'),
HiddenField::new('orderDetails.orderBillingDetails.payframeKey')->hideOnIndex()->hideOnDetail()->setCssClass('mw-key'),
HiddenField::new('orderDetails.orderBillingDetails.cardId')->hideOnIndex()->hideOnDetail()->setCssClass('cardID'),
BooleanField::new('orderDetails.orderBillingDetails.isSavedCreditCard')->hideOnIndex()->hideOnDetail()->setCssClass('d-none is-saved-credit-card'),
// Index fields
TextField::new('title', 'Project Name')->hideOnForm()->setTemplatePath('admin/field/project_title.html.twig'),
TextField::new('fundingStatus', 'Funding Status / Goal')->hideOnForm(),
DateField::new('filmProjectTimeline.fundraisingCampaignEndDate', 'End Date')->renderAsText()->hideOnForm()->setFormat('d MMM y')->setTemplatePath('admin/field/project_date.html.twig'),
TextField::new('productionStage', 'Project Stage')->hideOnForm()->setTemplatePath('admin/field/project_stage.html.twig'),
TextField::new('status', 'Status')->hideOnForm()->setTemplatePath('admin/field/project_status.html.twig'),
TextField::new('wordpressStatus', 'Wordpress Status')->hideOnForm()->setTemplatePath('admin/field/project_wordpress_status.html.twig'),
BooleanField::new('isHideDonationBox', 'Donation Box')->hideOnForm()->setTemplatePath('admin/field/is_display_donation.html.twig'),
IdField::new('wordpressId', 'WP ID')->hideOnForm()->setTemplatePath('admin/field/wordpress_id.html.twig')->setPermission(Constant::ADMIN_ROLE),
IdField::new('oldWordpressId', 'old WP ID')->hideOnForm()->setTemplatePath('admin/field/wordpress_id.html.twig')->setPermission(Constant::ADMIN_ROLE),
]);
$user = $this->getUser();
$isProgressReport = $this->progressReportService->checkIfProgressReportStarts();
if($isProgressReport) {
$formFields = array_merge($formFields, [
// BooleanField::new('progressReportStatus', 'Progress Report Status')->hideOnForm()->setTemplatePath('admin/field/is_progress_report_complete.html.twig'),
TextField::new('progressReportStatusUpdate', 'Progress Report Status')->hideOnForm()->setTemplatePath('admin/field/progress_report_status_update.html.twig'),
]);
}
// $formFields = array_merge($formFields, [
// BooleanField::new('isProgressReportActive', 'Progress Report Status')->hideOnForm()->setTemplatePath('admin/field/is_progress_report_active.html.twig'),
// ]);
return $formFields;
}
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
// Get current user profile
$user = $this->getUser();
if ($user->isAdmin()) {
$response = $this->container->get(EntityRepository::class)->createQueryBuilder($searchDto, $entityDto, $fields, $filters);
$response
->andWhere('entity.status = :declined or entity.status = :approved or entity.status = :resubmit')
->setParameter('declined', 'declined')
->setParameter('approved', 'approved')
->setParameter('resubmit', 'resubmit')
// ->addOrderBy('entity.title', 'ASC')
->addOrderBy('entity.id', 'DESC')
;
return $response;
}
$response = $this->container->get(EntityRepository::class)->createQueryBuilder($searchDto, $entityDto, $fields, $filters);
$response
->leftJoin('entity.filmProjectMembers','f')
->andWhere('entity.owner = :userId or (f.email = :userEmail and f.isActive = true)')
->andWhere('entity.status = :approved or entity.status = :declined or entity.status = :resubmit')
->setParameter('userId', $user->getId())
->setParameter('userEmail', $user->getEmail())
->setParameter('approved', 'approved')
->setParameter('declined', 'declined')
->setParameter('resubmit', 'resubmit')
->addOrderBy('entity.id', 'DESC');
return $response;
}
public function createEntity(string $entityFqcn)
{
$user = $this->getUser();
return $this->filmApplicationService->createFilmProjectObj($user);
}
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance, AdminContext $context = null): void
{
$entityManager->persist($entityInstance);
$entityManager->flush();
$this->updateMainMembers($entityManager, $entityInstance);
}
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$entityManager->persist($entityInstance);
$entityManager->flush();
$this->updateMainMembers($entityManager, $entityInstance);
}
public function deleteEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
// $filmProjectAdmin = $entityInstance->getFilmProjectAdmin();
// $filmProjectProducer = $entityInstance->getFilmProjectProducer();
// $filmProjectDirector = $entityInstance->getFilmProjectDirector();
// $filmProjectMembers = $entityInstance->getFilmProjectMembers();
// $filmProjectAdmin->setAdminFilmProject(null);
// $filmProjectProducer->setProducerFilmProject(null);
// $filmProjectDirector->setDirectorFilmProject(null);
// $entityManager->persist($filmProjectAdmin);
// $entityManager->persist($filmProjectProducer);
// $entityManager->persist($filmProjectDirector);
// $entityManager->flush();
// $entityInstance
// ->setFilmProjectAdmin(null)
// ->setFilmProjectProducer(null)
// ->setFilmProjectDirector(null)
// ;
// $entityManager->remove($filmProjectAdmin);
// $entityManager->remove($filmProjectProducer);
// $entityManager->remove($filmProjectDirector);
// $entityManager->flush();
// foreach ($filmProjectMembers as $filmProjectMember) {
// $entityManager->remove($filmProjectMember);
// $entityInstance->removeFilmProjectMember($filmProjectMember);
// }
// $entityManager->persist($entityInstance);
// $entityManager->flush();
// $entityManager->remove($entityInstance);
// $entityManager->flush();
$entityInstance->setStatus('archived');
$entityManager->persist($entityInstance);
$entityManager->flush();
$this->addFlash('Project removed', 'Project '. $entityInstance->getTitle() .' has been removed.');
}
public function configureCrud(Crud $crud): Crud
{
// $user = $this->getUser();
$crud
->setPaginatorPageSize(60)
->addFormTheme('admin/formTheme/film_application_theme.html.twig')
->setPageTitle('index', 'Manage Projects')
->setPageTitle('new', 'New Project Application')
->setPageTitle('edit', 'Edit Film Project')
->overrideTemplate('crud/new', 'admin/form/new_film_application_form.html.twig')
->overrideTemplate('crud/edit', 'admin/form/film_application_form.html.twig')
->overrideTemplate('crud/index', 'admin/index/film_project_index.html.twig')
->overrideTemplate('flash_messages', 'admin/crud/flash_messages_alt.html.twig')
;
return $crud;
}
public function configureActions(Actions $actions): Actions
{
$user = $this->getUser();
$isProgressReport = $this->progressReportService->checkProgressReportStartsWithUser($user);
$backAction = Action::new('backAction', 'Save Draft', '')
->linkToCrudAction('backAction')
;
$saveDraft = Action::new('saveDraft', 'Save Draft', '')
->linkToCrudAction('saveDraft')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
return $status == 'draft' || $status == 'resubmit';
})
;
$viewWordpressLink = Action::new('viewWordpressLink', 'View Project', '')
->linkToUrl(function (FilmProject $entity) {
return $entity->getWordpressUrl();
})
->displayIf(static function ($entity) {
$status = $entity->getWordpressStatus();
$url = $entity->getWordpressUrl();
return (( $url != '' ) && ( $status == Constant::WP_STATUS_PUBLISH ));
})
->setHtmlAttributes(['target' => '_blank'])
;
$viewDraftWordpressLink = Action::new('viewDraftWordpressLink', 'View Project', '')
->linkToUrl(function (FilmProject $entity) {
return $entity->getWordpressDraftUrl();
})
->displayIf(static function ($entity) {
$status = $entity->getWordpressStatus();
$url = $entity->getWordpressDraftUrl();
return (( $url != '' ) && ( $status == Constant::WP_STATUS_DRAFT ));
})
->setHtmlAttributes(['target' => '_blank'])
;
$exportOriginalCopy = Action::new('exportOriginalCopy', 'Export Original Copy', '')
->linkToCrudAction('exportOriginalCopy')
->displayIf(static function ($entity) {
$filmProjectOriginalCopy = $entity->getFilmProjectOriginal();
return !empty($filmProjectOriginalCopy);
})
;
$exportCurrentVersionCopy = Action::new('exportCurrentVersionCopy', 'Export Current Version', '')
->linkToCrudAction('exportCurrentVersionCopy')
->displayIf(static function ($entity) {
$filmProjectOriginalCopy = $entity->getFilmProjectOriginal();
return !empty($filmProjectOriginalCopy);
})
;
$exportOriginalCopies = Action::new('exportOriginalCopies', 'Export Original Copy')
->linkToCrudAction('exportOriginalCopies')
;
$exportCurrentVersionCopies = Action::new('exportCurrentVersionCopies', 'Export Current Version')
->linkToCrudAction('exportCurrentVersionCopies')
;
$publishProjects = Action::new('publishProjects', 'Publish')
->linkToCrudAction('publishProjects')
->addCssClass('wordpress-action')
;
$unpublishProjects = Action::new('unpublishProjects', 'Unpublish')
->linkToCrudAction('unpublishProjects')
->addCssClass('wordpress-action')
;
$archiveProjects = Action::new('archiveProjects', 'Archive')
->linkToCrudAction('archiveProjects')
->addCssClass('wordpress-action')
;
$viewProject = Action::new('viewProject', 'View Project', '')
->linktoCrudACtion('viewProject')
->displayIf(static function ($entity) {
$status = $entity->getWordpressStatus();
$url = $entity->getWordpressUrl();
return (( $url != '' ) && ( $status == Constant::WP_STATUS_PUBLISH ));
})
->setHtmlAttributes(['target' => '_blank'])
;
$makePrivateProjects = Action::new('makePrivateProjects', 'Make Password Protected')
->linkToCrudAction('makePrivateProjects')
;
$makeHiddenProjects = Action::new('makeHiddenProjects', 'Hide project')
->linkToCrudAction('makeHiddenProjects')
;
$editProject = Action::new('editProject', 'Edit Project')
->linkToCrudAction(Action::EDIT)
->displayIf(static function ($entity) {
$isDisplay = false;
$status = $entity->getStatus();
if ($status != 'approved' && $status != 'declined') {
$isDisplay = true;
}
return $isDisplay;
})
;
$hideDonationBox = Action::new('hideDonationBox', 'Hide Donation Box')
->linkToCrudAction('hideDonationBox')
->displayIf(static function ($entity) {
$wpStatus = $entity->getStatus();
$status = $entity->isIsHideDonationBox();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return (!$status && $wpStatus == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available'));
}
// return (!$status && $wpStatus == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available'));
return (!$status && $wpStatus == 'approved');
})
;
$showDonationBox = Action::new('showDonationBox', 'Show Donation Box')
->linkToCrudAction('showDonationBox')
->displayIf(static function ($entity) {
$wpStatus = $entity->getStatus();
$status = $entity->isIsHideDonationBox();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return ($status && $wpStatus == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available'));
}
// return ($status && $wpStatus == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available'));
return ($status && $wpStatus == 'approved');
})
;
$updateProjectDetails = Action::new('updateProjectDetails', 'Edit Project')
->linkToCrudAction('updateProjectDetails')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
return ($status == 'approved');
})
;
$viewProjectUpdates = Action::new('viewProjectUpdates', 'View Updates')
->linkToCrudAction('viewProjectUpdates')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
}
// return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
return $status == 'approved';
})
;
$addProjectUpdates = Action::new('addProjectUpdates', 'Add an update')
->linkToCrudAction('addProjectUpdates')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return ($status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available'));
}
return $status == 'approved';
// return $status == 'approved';
})
;
$manageMedia = Action::new('manageMedia', 'Manage Image Gallery')
->linkToCrudAction('manageMedia')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
}
// return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
return $status == 'approved';
})
;
$managePartner = Action::new('managePartner', 'Manage Impact Partner')
->linkToCrudAction('managePartner')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
$isProgressReportActive = $entity->isIsProgressReportActive();
if ($isProgressReportActive) {
return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
}
// return $status == 'approved' && ($entity->getProgressReportStatusUpdate() == 'complete' || $entity->getProgressReportStatusUpdate() == 'not_available');
return $status == 'approved';
})
;
$downloadReport = Action::new('downloadReport', 'Download Application')
->linkToCrudAction('downloadReport')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
return $status == 'approved';
})
;
$exportDonorList = Action::new('exportDonorList', 'Export Donor List')
->linkToCrudAction('exportDonorList')
->displayIf(static function ($entity) {
$status = $entity->getStatus();
$oldWordpressId = $entity->getOldWordpressId();
return ($status == 'approved' && !$oldWordpressId);
})
;
$viewProgressReport = Action::new('viewProgressReport', 'View Progress Report')
->setHtmlAttributes(['target' => '_blank'])
->linkToCrudAction('viewProgressReport')
->setCssClass('view-progress-report-action')
->displayIf(static function ($entity) {
$status = $entity->getProgressReportStatusUpdate();
return $status != 'complete' && $status != 'not_available';
})
;
$viewSingleProgressReport = Action::new('viewSingleProgressReport', 'View Progress Report')
->setHtmlAttributes(['target' => '_blank'])
->linkToCrudAction('viewProgressReport')
->setCssClass('view-progress-report-action')
->displayIf(static function ($entity) {
$status = $entity->getProgressReportStatusUpdate();
$isActive = $entity->isIsprogressReportActive();
return $isActive && $status != 'complete' && $status != 'not_available';
})
;
// $submitProjectAsAdmin = Action::new('submitProjectAsAdmin', 'Submit Project', '')
// ->linkToCrudAction('submitProjectAsAdmin')
// ->displayIf(static function ($entity) {
// $status = $entity->getStatus();
// return $status == 'draft' || $status == 'resubmit';
// })
// ;
$exportAllProjects = Action::new('exportAllProjects', 'Export all projects')
->linkToUrl('/admin/project/export-all')
->createAsGlobalAction()
->addCssClass('btn btn-primary me-2 d-block')
;
$exportAllDonations = Action::new('exportAllDonations', 'Export Donations', '')
->linkToCrudAction('exportAllDonations')
->displayIf(static function ($entity) {
$filmProjectOriginalCopy = $entity->getFilmProjectOriginal();
return !empty($filmProjectOriginalCopy);
})
;
// $exportDonorList->setCssClass('d-none');
// $exportAllDonations->setCssClass('d-none');
$toggleOnProgressReportStatus = Action::new('toggleOnProgressReportStatus', 'Turn on Progress Report')
->linkToUrl(function(FilmProject $project) {
return '/admin/progress-report/workflow/cron/single/'. $project->getId();
})
->displayIf(static function ($entity) {
return !$entity->isIsProgressReportActive();
})
;
$toggleOffProgressReportStatus = Action::new('toggleOffProgressReportStatus', 'Turn off Progress Report')
->linkToUrl(function(FilmProject $project) {
return '/admin/progress-report/workflow/cron/single/'. $project->getId();
})
->displayIf(static function ($entity) {
return $entity->isIsProgressReportActive();
})
;
$downloadProgressReport = Action::new('downloadProgressReport', 'Download Progress Report', '')
->linkToCrudAction('downloadProgressReport')
// ->displayIf(static function ($entity) {
// return $entity->isIsProgressReportActive();
// })
;
if ($isProgressReport) {
// $updateProjectDetails->setCssClass('d-none');
$hideDonationBox->setCssClass('progress-report-action');
$showDonationBox->setCssClass('progress-report-action');
$manageMedia->setCssClass('progress-report-action');
$managePartner->setCssClass('progress-report-action');
$addProjectUpdates->setCssClass('progress-report-action');
$viewProjectUpdates->setCssClass('progress-report-action');
// $downloadProgressReport->setCssClass('progress-report-action');
}
$actions
->add(Crud::PAGE_INDEX, $editProject)
->add(Crud::PAGE_INDEX, $updateProjectDetails)
->add(Crud::PAGE_INDEX, $viewProjectUpdates)
->add(Crud::PAGE_INDEX, $addProjectUpdates)
->add(Crud::PAGE_INDEX, $manageMedia)
->add(Crud::PAGE_INDEX, $managePartner)
->add(Crud::PAGE_INDEX, $hideDonationBox)
->add(Crud::PAGE_INDEX, $showDonationBox)
->add(Crud::PAGE_INDEX, $downloadReport)
->add(Crud::PAGE_INDEX, $exportDonorList)
->add(Crud::PAGE_INDEX, $viewWordpressLink)
->add(Crud::PAGE_INDEX, $viewDraftWordpressLink)
->add(Crud::PAGE_INDEX, $exportAllProjects)
->add(Crud::PAGE_INDEX, $exportAllDonations)
->add(Crud::PAGE_INDEX, $toggleOnProgressReportStatus)
->add(Crud::PAGE_INDEX, $toggleOffProgressReportStatus)
->add(Crud::PAGE_INDEX, $viewSingleProgressReport)
->add(Crud::PAGE_INDEX, $downloadProgressReport)
->add(Crud::PAGE_NEW, $backAction)
->add(Crud::PAGE_NEW, $saveDraft)
// ->add(Crud::PAGE_NEW, Action::INDEX)
->add(Crud::PAGE_NEW, Action::SAVE_AND_CONTINUE)
->add(Crud::PAGE_EDIT, $backAction)
->add(Crud::PAGE_EDIT, $saveDraft)
->add(Crud::PAGE_EDIT, $exportOriginalCopy)
->add(Crud::PAGE_EDIT, $exportCurrentVersionCopy)
// ->add(Crud::PAGE_EDIT, $submitProjectAsAdmin)
// ->add(Crud::PAGE_EDIT, Action::INDEX)
->add(Crud::PAGE_EDIT, $viewProject)
->add(Crud::PAGE_EDIT, Action::DELETE)
->addBatchAction($exportOriginalCopies)
->addBatchAction($exportCurrentVersionCopies)
->addBatchAction($publishProjects)
->addBatchAction($unpublishProjects)
->addBatchAction($archiveProjects)
->addBatchAction($makePrivateProjects)
->addBatchAction($makeHiddenProjects)
->update(Crud::PAGE_INDEX, Action::NEW, function (Action $action) {
return $action->setLabel('Start an Application');
})
// ->update(Crud::PAGE_NEW, Action::INDEX, function (Action $action) {
// return $action
// ->setLabel('<i class="fa-fw fa fa-list me-1"></i> View Project')
// ->setCssClass('me-3 link-primary fw-bold')
// ;
// })
->update(Crud::PAGE_NEW, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('Next');
})
->update(Crud::PAGE_NEW, $saveDraft, function (Action $action) {
return $action->addCssClass('ms-2 px-4 btn btn-secondary action-saveDraft');
})
->update(Crud::PAGE_NEW, $backAction, function (Action $action) {
return $action->addCssClass('btn btn-primary d-none action-backAction me-2')->setLabel('Back');
})
->update(Crud::PAGE_EDIT, $viewProject, function (Action $action) {
return $action
->setLabel('<i class="fa-fw fa fa-list me-1"></i> View Project')
->setCssClass('mx-3 link-primary fw-bold')
;
})
->update(Crud::PAGE_EDIT, Action::SAVE_AND_RETURN, function (Action $action) {
return $action->setLabel('Next');
})
->update(Crud::PAGE_EDIT, $saveDraft, function (Action $action) {
return $action->addCssClass('ms-2 px-4 btn btn-secondary action-saveDraft');
})
->update(Crud::PAGE_EDIT, $backAction, function (Action $action) {
return $action->addCssClass('btn btn-primary d-none action-backAction me-2')->setLabel('Back');
})
->update(Crud::PAGE_EDIT, $exportOriginalCopy, function (Action $action) {
return $action->addCssClass('btn btn-secondary me-2')->setLabel('Export Original Version');
})
->update(Crud::PAGE_EDIT, $exportCurrentVersionCopy, function (Action $action) {
return $action->addCssClass('btn btn-secondary me-2')->setLabel('Export Current Version');
})
// ->update(Crud::PAGE_EDIT, $submitProjectAsAdmin, function (Action $action) {
// return $action->addCssClass('btn btn-primary me-2 order-1')->setLabel('Submit Project');
// })
->remove(Crud::PAGE_INDEX, Action::EDIT)
->setPermission($exportOriginalCopy, Constant::ADMIN_ROLE)
->setPermission($exportCurrentVersionCopy, Constant::ADMIN_ROLE)
->setPermission($publishProjects, Constant::ADMIN_ROLE)
->setPermission($unpublishProjects, Constant::ADMIN_ROLE)
->setPermission($archiveProjects, Constant::ADMIN_ROLE)
->setPermission($makePrivateProjects, Constant::ADMIN_ROLE)
->setPermission($makeHiddenProjects, Constant::ADMIN_ROLE)
->setPermission(Action::DELETE, Constant::ADMIN_ROLE)
->setPermission(Action::BATCH_DELETE, Constant::ADMIN_ROLE)
->setPermission($exportAllProjects, Constant::ADMIN_ROLE)
->setPermission($viewDraftWordpressLink, Constant::ADMIN_ROLE)
->setPermission($exportAllDonations, Constant::ADMIN_ROLE)
->setPermission($toggleOnProgressReportStatus, Constant::ADMIN_ROLE)
->setPermission($toggleOffProgressReportStatus, Constant::ADMIN_ROLE)
// ->setPermission($submitProjectAsAdmin, Constant::ADMIN_ROLE)
->reorder(Crud::PAGE_INDEX, ['viewSingleProgressReport', 'viewDraftWordpressLink', 'viewWordpressLink', 'editProject', 'updateProjectDetails', 'showDonationBox', 'hideDonationBox', 'manageMedia', 'managePartner', 'addProjectUpdates', 'viewProjectUpdates', 'exportAllDonations', 'downloadReport', 'downloadProgressReport', 'exportDonorList', 'toggleOnProgressReportStatus', 'toggleOffProgressReportStatus', Action::DELETE])
->reorder(Crud::PAGE_EDIT, [Action::DELETE, 'viewProject', 'backAction', 'saveDraft', 'exportOriginalCopy', 'exportCurrentVersionCopy', Action::SAVE_AND_RETURN])
->reorder(Crud::PAGE_NEW, ['backAction', 'saveDraft', Action::SAVE_AND_RETURN])
;
if ($isProgressReport) {
$actions
->add(Crud::PAGE_INDEX, $viewProgressReport)
->update(Crud::PAGE_INDEX, $updateProjectDetails, function(Action $action) {
return $action->setLabel('View Project Details');
})
;
}
return $actions;
}
public function configureFilters(Filters $filters): Filters
{
// Get current user profile
$user = $this->getUser();
if ($user->isAdmin()) {
$filters = $filters
->add('owner')
->add(EntityFilter::new('filmProjectAdmin', 'Project Admin'))
;
}
return $filters;
}
protected function getRedirectResponseAfterSave(AdminContext $context, string $action): RedirectResponse
{
$submitButtonName = $context->getRequest()->request->all()['ea']['newForm']['btn'];
$user = $this->getUser();
// if (!$user->isAdmin()) { // IF USER IS NOT ADMIN
if (Action::SAVE_AND_CONTINUE === $submitButtonName) { // SAVE DRAFT RESPONSE
$entityInstance = $context->getEntity()->getInstance();
$this->filmApplicationService->setFilmProjectToDraft($entityInstance);
$this->addFlash('success', 'Your draft has been saved.');
$url = $this->container->get(AdminUrlGenerator::class)
->setAction(Action::EDIT)
->setEntityId($context->getEntity()->getPrimaryKeyValue())
->generateUrl();
return $this->redirect($url);
}
if (Action::SAVE_AND_RETURN === $submitButtonName) { // FINISH APPLICATION RESPONSE
$entityInstance = $context->getEntity()->getInstance();
$user = $this->getUser();
// Save everything before
$this->em->persist($entityInstance);
$this->em->flush();
// Check if image exists
$isImage = $this->filmApplicationService->checkIsProjectImage($entityInstance);
if (!$isImage) {
$backUrl = $this->container->get(AdminUrlGenerator::class)
->setAction(Action::EDIT)
->setEntityId($context->getEntity()->getPrimaryKeyValue())
->generateUrl();
$this->addFlash('notice', 'Image in Project Details Tab is required.');
return $this->redirect($backUrl);
}
if (!$entityInstance->getResubmitCount()) {
$this->filmApplicationService->proceedPayment($entityInstance);
}
$this->filmApplicationService->setFilmProjectToReadyForReview($entityInstance);
$this->filmApplicationService->setFilmProjectCreatedDateToday($entityInstance); // Set created date for searching purpose
$this->filmApplicationService->generateSponsorsFromText($entityInstance);
$this->handleWordpressEndpoint($entityInstance); // handles Wordpress creation and update
$this->handleSalesforceEndpoint($entityInstance, $user); // handles Salesforce creation and update
if (!$entityInstance->getResubmitCount()) {
$this->filmApplicationService->createFilmProjectInvoice($user, $entityInstance);
$this->filmApplicationService->sendEmail($entityInstance);
}
$this->addFlash('Application Submitted', 'Film project '. $entityInstance->getTitle() . ' has been submitted.');
$url = $this->container->get(AdminUrlGenerator::class)
->setController(PendingFilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return $this->redirect($url);
}
if (Action::SAVE_AND_ADD_ANOTHER === $submitButtonName) {
$url = $this->container->get(AdminUrlGenerator::class)->setAction(Action::NEW)->generateUrl();
return $this->redirect($url);
}
return $this->redirectToRoute($context->getDashboardRouteName());
}
private function handleWordpressEndpoint(FilmProject $entityInstance) {
$wordpressId = $entityInstance->getWordpressId();
$oldWordpressId = $entityInstance->getOldWordpressId();
if ($wordpressId && $wordpressId != $oldWordpressId) {
$this->filmApplicationService->updateWordpressObject($entityInstance);
} else {
$this->filmApplicationService->createWordpressObject($entityInstance);
}
}
private function handleSalesforceEndpoint(FilmProject $entityInstance, $user = null) {
$salesforceCampaignId = $entityInstance->getSalesforceId();
if ($salesforceCampaignId) {
$this->filmApplicationService->updateCampaignSalesforce($entityInstance);
} else {
$this->filmApplicationService->createCampaignSalesforce($entityInstance);
}
if (empty($orderDetailsSalesforceId) && empty($oldWordpressId) && !$user->isAdmin() && !$entityInstance->getResubmitCount()) {
$this->filmApplicationService->createTransactionSalesforce($entityInstance);
}
if ($user->isAdmin()) {
$this->filmApplicationService->updateCampaignSalesforceAdmin($entityInstance);
}
}
public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
{
if ( $_GET['crudAction'] === Action::EDIT) {
$filmProject = $this->getFilmProjectFromEntityId();
if ($filmProject) {
$responseParameters
->set('filmProject', $filmProject)
;
}
}
$product = $this->filmApplicationService->getDefaultProduct();
$cards = $this->userBillingService->getCurrentSavedCards(); // Get saved cards
$responseParameters->setAll([
'product' => $product,
'cards' => $cards,
]);
return $responseParameters;
}
// Custom Actions
public function saveDraft(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$entityInstance->setStatus('draft');
if ( $entityInstance->getResubmitCount() ) {
$entityInstance->setStatus('resubmit');
}
$this->em->persist($entityInstance);
$this->em->flush();
$this->addFlash('success', 'Your draft has been saved');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(DraftFilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
public function exportOriginalCopy(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$filmProjectOriginalCopy = $entityInstance->getFilmProjectOriginal()->getData();
$csvExporter = new CsvExporter();
$csvExporter->exportArrayToCsv($filmProjectOriginalCopy, $entityInstance->getTitle() .'-V1.csv');
$this->addFlash('success', 'Your original copy has been exported');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(FilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
public function exportCurrentVersionCopy(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$filmProjectConverter = new FilmProjectObjectConverter();
$serializedFilmProject = $filmProjectConverter->serializeFilmProjectDocument($entityInstance);
$csvExporter = new CsvExporter();
$csvExporter->exportArrayToCsv($serializedFilmProject, $entityInstance->getTitle() .'.csv');
$this->addFlash('success', 'Your current version project has been exported');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(FilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
public function updateProjectDetails(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectEditCrudController::class)
->setAction(Action::EDIT)
->setEntityId($entityInstance->getId())
->generateUrl();
if ($entityInstance->isIsProgressReportActive() && $entityInstance->getProgressReportStatusUpdate() != 'complete') {
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectEditCrudController::class)
->setAction(Action::EDIT)
->setEntityId($entityInstance->getId())
->set('disableFields', "true")
->generateUrl()
;
}
return new RedirectResponse($projectUpdateUrl);
}
public function viewProjectUpdates(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectUpdateCrudController::class)
->setAction(Action::INDEX)
->unset('entityId')
->set('project', $entityInstance->getId())
->generateUrl();
return new RedirectResponse($projectUpdateUrl);
}
public function addProjectUpdates(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectUpdateCrudController::class)
->setAction(Action::NEW)
->unset('entityId')
->set('project', $entityInstance->getId())
->generateUrl();
return new RedirectResponse($projectUpdateUrl);
}
public function manageMedia(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectMediaCrudController::class)
->setAction(Action::EDIT)
->setEntityId($entityInstance->getId())
->generateUrl();
return new RedirectResponse($projectUpdateUrl);
}
public function managePartner(AdminContext $context): Response
{
$entityInstance = $context->getEntity()->getInstance();
$projectUpdateUrl = $this->adminUrlGenerator->setController(FilmProjectPartnerCrudController::class)
->setAction(Action::EDIT)
->setEntityId($entityInstance->getId())
->generateUrl();
return new RedirectResponse($projectUpdateUrl);
}
/**
* BATCH ACTION: export original version
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function exportOriginalCopies(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
$filmProjectOriginalCopies = [];
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$filmProjectOriginalCopy = $entityInstance->getFilmProjectOriginal();
if (empty($filmProjectOriginalCopy)) {
$this->addFlash('warning', 'Only approved projects can be exported into CSV');
return $this->redirect($batchActionDto->getReferrerUrl());
}
array_push($filmProjectOriginalCopies, $filmProjectOriginalCopy->getData());
}
$dateValue = (new \DateTime('today'))->format('d-m-y');
$csvExporter = new CsvExporter();
$csvExporter->exportProjectsToCsv($filmProjectOriginalCopies, 'projects_V1-'. $dateValue .'.xlsx');
// return $this->redirect($batchActionDto->getReferrerUrl());
}
/**
* BATCH: Export current version copy
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function exportCurrentVersionCopies(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
$filmProjectConverter = new FilmProjectObjectConverter();
$filmProjectOriginalCopies = [];
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$serializedFilmProject = $filmProjectConverter->serializeFilmProjectDocument($entityInstance);
array_push($filmProjectOriginalCopies, $serializedFilmProject);
}
$dateValue = (new \DateTime('today'))->format('d-m-y');
$csvExporter = new CsvExporter();
$csvExporter->exportProjectsToCsv($filmProjectOriginalCopies, 'projects-'. $dateValue .'.xlsx');
// return $this->redirect($batchActionDto->getReferrerUrl());
}
/**
* BATCH: Publish projects
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function publishProjects(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
// Check if there is non-approved projects
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
if ($entityInstance->getStatus() != 'approved') {
$this->addFlash('notice', 'Project(s) have to be approved before being published.');
return $this->redirect($batchActionDto->getReferrerUrl());
}
}
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$this->filmApplicationService->publishProject($entityInstance);
}
$this->addFlash('success', 'Project(s) have been published');
return $this->redirect($batchActionDto->getReferrerUrl());
}
/**
* BATCH: Unublish projects
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function unpublishProjects(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
// Check if there is non-approved projects
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
if ($entityInstance->getStatus() != 'approved') {
$this->addFlash('notice', 'Project(s) have to be approved before being unpublished.');
return $this->redirect($batchActionDto->getReferrerUrl());
}
}
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$this->filmApplicationService->unpublishProject($entityInstance);
}
$this->addFlash('success', 'Project(s) have been unpublished');
return $this->redirect($batchActionDto->getReferrerUrl());
}
public function viewProject(AdminContext $adminContext)
{
$entityInstance = $adminContext->getEntity()->getInstance();
return $this->redirect($entityInstance->getWordpressUrl());
}
/**
* BATCH: archive projects
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function archiveProjects(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
// Check if there is non-approved projects
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
if ($entityInstance->getStatus() != 'approved') {
$this->addFlash('notice', 'Project(s) have to be approved before being archived.');
return $this->redirect($batchActionDto->getReferrerUrl());
}
}
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$this->filmApplicationService->archiveProject($entityInstance);
}
$this->addFlash('success', 'Project(s) have been archived');
return $this->redirect($batchActionDto->getReferrerUrl());
}
/**
* BATCH: Make private projects
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function makePrivateProjects(BatchActionDto $batchActionDto)
{
$postPassword = '';
if (isset($_COOKIE['postpassword'])) {
$postPassword = $_COOKIE['postpassword'];
}
if ($postPassword) {
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$this->filmApplicationService->makePrivateProject($entityInstance, $postPassword);
}
}
$this->addFlash('success', 'Project(s) have been made private');
return $this->redirect($batchActionDto->getReferrerUrl());
}
public function downloadReport(AdminContext $context, Environment $twig = null, Pdf $pdf)
{
$filmProject = $context->getEntity()->getInstance();
$pdfExporter = new PdfExporter($twig, $pdf);
$pdfExporter->convertProjectToPdf($filmProject);
}
public function hideDonationBox(AdminContext $adminContext)
{
$entityInstance = $adminContext->getEntity()->getInstance();
$this->filmApplicationService->hideDonationBox($entityInstance);
$this->addFlash('success', 'The donation box for project '. $entityInstance->getTitle() .' has been hidden.');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(FilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
public function showDonationBox(AdminContext $adminContext)
{
$entityInstance = $adminContext->getEntity()->getInstance();
$this->filmApplicationService->showDonationBox($entityInstance);
$this->addFlash('success', 'The donation box for project '. $entityInstance->getTitle() .' has been displayed.');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(FilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
public function submitProjectAsAdmin(AdminContext $context)
{
$user = $this->getUser();
$entityInstance = $context->getEntity()->getInstance();
// Save everything before
$this->em->persist($entityInstance);
$this->em->flush();
// Check if image exists
$isImage = $this->filmApplicationService->checkIsProjectImage($entityInstance);
if (!$isImage) {
$backUrl = $this->container->get(AdminUrlGenerator::class)
->setAction(Action::EDIT)
->setEntityId($context->getEntity()->getPrimaryKeyValue())
->generateUrl();
$this->addFlash('notice', 'Image in Project Details Tab is required.');
return $this->redirect($backUrl);
}
$this->filmApplicationService->setFilmProjectToReadyForReview($entityInstance);
$this->filmApplicationService->setFilmProjectCreatedDateToday($entityInstance); // Set created date for searching purpose
$this->filmApplicationService->generateSponsorsFromText($entityInstance);
$this->filmApplicationService->createWordpressObject($entityInstance);
$this->filmApplicationService->createCampaignSalesforce($entityInstance);
if (!$entityInstance->getOldWordpressId()) {
$this->filmApplicationService->createTransactionSalesforce($entityInstance);
}
if (!$entityInstance->getResubmitCount()) {
$this->filmApplicationService->proceedPayment($entityInstance);
$this->filmApplicationService->createFilmProjectInvoice($user, $entityInstance);
$this->filmApplicationService->sendEmail($entityInstance);
}
$this->addFlash('Application Submitted', 'Film project '. $entityInstance->getTitle() . ' has been submitted.');
$url = $this->container->get(AdminUrlGenerator::class)
->setController(PendingFilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return $this->redirect($url);
}
public function exportAllDonations(AdminContext $adminContext) {
$entityInstance = $adminContext->getEntity()->getInstance();
$donationRepository = $this->em->getRepository(Donation::class);
$donations = $donationRepository->findDonationsByProjectOrderDate($entityInstance->getId());
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Generate columns first
$columnTitles = ["Order ID", "Receipt ID", "First Name", "Last Name", "Email", "Organisation", "Donation to", "Wordpress ID", "Is Anonymous", "Total Amount", "Pop-up Amount", "Fundraising Goal", "Date", "Status", "Salesforce ID", "Xero Invoice ID", "Xero Contact ID", "Merchant Warrior ID"];
$excelCol = 'A';
$excelRow = 1;
foreach($columnTitles as $columnTitle) {
$currentPosition = $excelCol .''. $excelRow;
$sheet->setCellValue($currentPosition, $columnTitle)->getColumnDimension($excelCol)->setAutoSize(TRUE);
$excelCol++;
}
$excelRow++;
// Universal project field(s)
$filmProjectFunding = $entityInstance->getFilmProjectFunding();
$fundraisingGoal = (number_format((float)$filmProjectFunding->getFundraisingGoal() / 100, 2));
$fundraisingStatus = 0;
// After that, we generate data respectively
$limit = 2000;
foreach ($donations as $donation) {
// Universal project field(s)
$project = $donation->getFilmProject();
$filmProjectFunding = $project->getFilmProjectFunding();
$fundraisingGoal = (number_format((float)$filmProjectFunding->getFundraisingGoal() / 100, 2));
$orderDetails = $donation->getOrderDetails();
$orderBillingDetails = $orderDetails->getOrderBillingDetails();
$paymentDetails = $orderDetails->getPaymentDetails();
$isAnonymous = (!$donation->isIsContactShared() || !$donation->isIsOrganisationConsent());
$isAnon = (!$donation->isIsContactShared() || !$donation->isIsOrganisationConsent()) ? 'yes' : 'no';
$totalAmount = (number_format((float)$orderDetails->getTotal() / 100, 2));
if ($donation->getSupportDaf()) {
$totalAmount = (number_format(((float)$orderDetails->getTotal()- $donation->getSupportDaf()) / 100, 2));
}
$popupAmount = (number_format((float)$donation->getSupportDaf() / 100, 2));
$isAnonymous = !$this->getUser()->isAdmin();
$sheet->setCellValue('A'.$excelRow , 'MW'.$orderDetails->getId())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Order ID
$sheet->setCellValue('B'.$excelRow , $orderDetails->getInvoiceNumber())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Receipt ID
$sheet->setCellValue('C'.$excelRow , $isAnonymous ? 'Anonymous' : $orderBillingDetails->getFirstName())->getColumnDimension($excelCol)->setAutoSize(TRUE); // First Name
$sheet->setCellValue('D'.$excelRow , $isAnonymous ? 'Anonymous' : $orderBillingDetails->getLastName())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Last Name
$sheet->setCellValue('E'.$excelRow , $isAnonymous ? 'Anonymous' : $orderBillingDetails->getEmailAddress())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Email
$sheet->setCellValue('F'.$excelRow , $isAnonymous ? 'Anonymous' : $orderBillingDetails->getOrganisation())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Organisation
$sheet->setCellValue('G'.$excelRow , $donation->getFilmProject())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Donation to
$sheet->setCellValue('H'.$excelRow , (string)$donation->getFilmProject()->getWordpressId())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Wordpress ID
$sheet->setCellValue('I'.$excelRow , $isAnon)->getColumnDimension($excelCol)->setAutoSize(TRUE); // Is Anonymous
$sheet->setCellValue('J'.$excelRow , str_replace(",", "", $totalAmount))->getColumnDimension($excelCol)->setAutoSize(TRUE); // Total Amount
$sheet->setCellValue('K'.$excelRow , str_replace(",", "", $popupAmount))->getColumnDimension($excelCol)->setAutoSize(TRUE); // pop-up Amount
// $sheet->setCellValue('L'.$excelRow , str_replace(",", "", $fundraisingStatus))->getColumnDimension($excelCol)->setAutoSize(TRUE); // Fundraising Status
$sheet->setCellValue('L'.$excelRow , str_replace(",", "", $fundraisingGoal))->getColumnDimension($excelCol)->setAutoSize(TRUE); // Fundraising Goal
$sheet->setCellValue('M'.$excelRow , date_format($donation->getModifiedAt(), 'd/m/Y'))->getColumnDimension($excelCol)->setAutoSize(TRUE); // Date
$sheet->setCellValue('N'.$excelRow , $paymentDetails->getStatus())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Status
$sheet->setCellValue('O'.$excelRow , $orderDetails->getSalesforceId())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Salesforce ID
$sheet->setCellValue('P'.$excelRow , $orderDetails->getXeroId())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Xero Invoice ID
$sheet->setCellValue('Q'.$excelRow , $orderDetails->getXeroContactId())->getColumnDimension($excelCol)->setAutoSize(TRUE); // Xero Contact ID
$sheet->setCellValue('R'.$excelRow , ($orderDetails->getTransactionId()) ? $orderDetails->getTransactionId() : 'Manual Donation')->getColumnDimension($excelCol)->setAutoSize(TRUE); // Merchant Warrior ID
$sheet->getStyle('J'.$excelRow)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
$sheet->getStyle('K'.$excelRow)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
$sheet->getStyle('L'.$excelRow)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
if ($excelRow > $limit ) {
break;
}
$excelRow++;
}
ob_clean();
$writer = new Xlsx($spreadsheet);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="'. $entityInstance->getTitle() .' donations.xlsx"');
$writer->save('php://output');
exit();
}
/**
* Get film project from entity ID
*
* @return FilmProject|null
*/
protected function getFilmProjectFromEntityId(): ?FilmProject
{
$entityManager = $this->container->get('doctrine')->getManagerForClass(FilmProject::class);
$repository = $entityManager->getRepository(FilmProject::class);
$filmProject = $repository->findOneBy(['id' => $_GET['entityId']]);
return $filmProject;
}
protected function updateMainMembers(EntityManagerInterface $entityManager, FilmProject $entityInstance)
{
// Assign main members to project
$administrator = $entityInstance->getFilmProjectAdmin();
$administrator->setAdminFilmProject($entityInstance);
$entityManager->persist($administrator);
$director = $entityInstance->getFilmProjectDirector();
$director->setDirectorFilmProject($entityInstance);
$entityManager->persist($director);
$producer = $entityInstance->getFilmProjectProducer();
$producer->setProducerFilmProject($entityInstance);
$entityManager->persist($producer);
$entityManager->flush();
}
/**
* BATCH: Make hidden projects
*
* @param BatchActionDto $batchActionDto
* @return void
*/
public function makeHiddenProjects(BatchActionDto $batchActionDto)
{
$className = $batchActionDto->getEntityFqcn();
$entityManager = $this->container->get('doctrine')->getManagerForClass($className);
foreach ($batchActionDto->getEntityIds() as $id) {
$entityInstance = $entityManager->find($className, $id);
$this->filmApplicationService->makeHiddenProject($entityInstance);
}
$this->addFlash('success', 'Project(s) have been made private');
return $this->redirect($batchActionDto->getReferrerUrl());
}
public function exportDonorList(AdminContext $context, EntityManagerInterface $em)
{
$entityInstance = $context->getEntity()->getInstance(); // get film project
$donations = $entityInstance->getDonations();
$dateValue = (new \DateTime('today'))->format('d-m-y');
$csvExporter = new CsvExporter();
$csvExporter->exportDonorList($donations, $entityInstance->getTitle() .' Donor List -'. $dateValue .'.xlsx', $this->getUser());
}
public function viewProgressReport(AdminContext $context, EntityManagerInterface $em)
{
$entityInstance = $context->getEntity()->getInstance(); // get film project
$currentYear = (int) date('Y');
$progressReportUrl = '/progress-report/'. $currentYear .'?projectId=' . $entityInstance->getId();
return $this->redirect($progressReportUrl);
}
public function downloadProgressReport(AdminContext $context, Environment $twig = null, Pdf $pdf, EntityManagerInterface $em)
{
$filmProject = $context->getEntity()->getInstance();
$progressReportRepo = $em->getRepository(FilmProjectProgressReport::class);
$progressReport = $progressReportRepo->findByYear((int)date("Y"), $filmProject->getId());
if (empty($progressReport)) {
$this->addFlash('Notice', 'Progress report is not available.');
$filmProjectIndexUrl = $this->adminUrlGenerator->setController(FilmProjectCrudController::class)
->setAction(Action::INDEX)
->generateUrl();
return new RedirectResponse($filmProjectIndexUrl);
}
$pdfExporter = new PdfExporter($twig, $pdf);
$pdfExporter->convertProgressReportToPdf($progressReport);
}
}