src/Service/ProjectService.php line 2458

Open in your IDE?
  1. <?php
  2. namespace App\Service;
  3. use App\Entity\Client;
  4. use App\Entity\Department;
  5. use App\Entity\RevenuePlanning;
  6. use App\Entity\User;
  7. use App\Repository\EmailCollectorRepository;
  8. use App\Repository\ProjectAllocatedHoursRepository;
  9. use App\Repository\ProjectRepository;
  10. use App\Repository\RevenuePlanningRepository;
  11. use App\Repository\TimeSpentRepository;
  12. use App\Repository\ProjectLeadStatusRepository;
  13. use App\Repository\UserRepository;
  14. use App\Repository\InvoiceRepository;
  15. use App\Repository\SalesOrderInvoiceRepository;
  16. use App\Repository\XeroContactRepository;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use App\Service\LogService;
  19. use App\Service\MailgunService;
  20. use Doctrine\ORM\Query\Expr\Func;
  21. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  22. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  23. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  24. use Symfony\Component\HttpFoundation\RedirectResponse;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. class ProjectService
  28. {
  29.     private $entityManager;
  30.     private $projectRepository;
  31.     private $timeSpentRepository;
  32.     private $allocatedHoursRepository;
  33.     private $projectLeadStatusRepository;
  34.     private $userRepository;
  35.     private $mailgunService;
  36.     private $translator;
  37.     private $revenuePlanningRepository;
  38.     private $invoiceRepository;
  39.     private $salesOrderInvoiceRepository;
  40.     private $ics;
  41.     private $utilsService;
  42.     private $params;
  43.     private $googleDriveService;
  44.     private $emailCollectorRepository;
  45.     private $currencyService;
  46.     private $projectIdPattern;
  47.     private $xeroContactRepository;
  48.     private $log;
  49.     public function __construct(EntityManagerInterface $entityManagerLogService $logProjectRepository $projectRepositoryTimeSpentRepository $timeSpentRepositoryUserRepository $userRepositoryProjectAllocatedHoursRepository $allocatedHoursRepositoryProjectLeadStatusRepository $projectLeadStatusRepositoryMailgunService $mailgunServiceRevenuePlanningRepository $revenuePlanningRepositoryInvoiceRepository $invoiceRepositorySalesOrderInvoiceRepository $salesOrderInvoiceRepositoryICSService $icsUtilsService $utilsServiceGoogleDriveService $googleDriveServiceEmailCollectorRepository $emailCollectorRepositoryParameterBagInterface $params,  TranslatorInterface $translatorCurrencyService $currencyServiceXeroContactRepository $xeroContactRepository)
  50.     {
  51.         $this->projectRepository $projectRepository;
  52.         $this->userRepository $userRepository;
  53.         $this->timeSpentRepository $timeSpentRepository;
  54.         $this->allocatedHoursRepository $allocatedHoursRepository;
  55.         $this->projectLeadStatusRepository $projectLeadStatusRepository;
  56.         $this->entityManager $entityManager;
  57.         $this->log $log;
  58.         $this->mailgunService $mailgunService;
  59.         $this->translator $translator;
  60.         $this->revenuePlanningRepository $revenuePlanningRepository;
  61.         $this->invoiceRepository $invoiceRepository;
  62.         $this->salesOrderInvoiceRepository $salesOrderInvoiceRepository;
  63.         $this->ics $ics;
  64.         $this->utilsService $utilsService;
  65.         $this->params $params;
  66.         $this->googleDriveService $googleDriveService;
  67.         $this->emailCollectorRepository $emailCollectorRepository;
  68.         $this->currencyService $currencyService;
  69.         $this->projectIdPattern '/Project\s*Id\s*:?\s*(\d{4}-\d{4})/i';
  70.         $this->xeroContactRepository $xeroContactRepository;
  71.     }
  72.     public function getEstimatedProjectHours() {}
  73.     public function getEmployeeTimeRecord($project)
  74.     {
  75.         $_id intval($project['id']);
  76.         $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  77.         $totalHoursAll 0;
  78.         $totalCostAll 0;
  79.         for ($i 0$i sizeof($departments); $i++) {
  80.             $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  81.             /*
  82.         $newEmployeeSummaryList = [];
  83.         foreach ($employeeSummaryList as $employee){
  84.             $user = $this->userRepository->find($employee['id']);
  85.             $employee['hourlyRate'] = $user->getHourlyRateUsd();
  86.             $employee['newCost'] = $employee['hours'] * $user->getHourlyRateUsd();
  87.             array_push($newEmployeeSummaryList, $employee);
  88.         }
  89.         */
  90.             // $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  91.             $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  92.             $tmpHours 0;
  93.             $tmpCost 0;
  94.             for ($j 0$j sizeof($employeeSummaryList); $j++) {
  95.                 $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  96.                 $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  97.             }
  98.             //$totalManpowerCost += $tmpCost;
  99.             $departments[$i]['totalCost'] = $tmpCost;
  100.             $departments[$i]['totalHours'] = $tmpHours;
  101.         }
  102.         if (count($departments) > 0) {
  103.             foreach ($departments as $department) {
  104.                 $totalHoursAll += $department['totalHours'];
  105.                 $totalCostAll += $department['totalCost'];
  106.             }
  107.         }
  108.         $record = [];
  109.         $record['departments'] = $departments;
  110.         $record['total']['hours'] = $totalHoursAll;
  111.         $record['total']['cost'] = $totalCostAll;
  112.         return $record;
  113.     }
  114.     public function getEmployeeTimeRecordByMonth($project$month$year)
  115.     {
  116.         $month intval($month) <= '0' $month $month;
  117.         $start date("Y-m-d"strtotime($year '-' $month '-' '01'));
  118.         $startDate = new \DateTime($start);
  119.         $end date("Y-m-d"strtotime($start 'last day of this month'));
  120.         $endDate = new \DateTime($end);
  121.         $_id intval($project['id']);
  122.         $departments $this->timeSpentRepository->getDepartmentsForProject($_id$startDate$endDate);
  123.         $totalHoursAll 0;
  124.         $totalCostAll 0;
  125.         for ($i 0$i sizeof($departments); $i++) {
  126.             $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id'], $start$end);
  127.             /*
  128.         $newEmployeeSummaryList = [];
  129.         foreach ($employeeSummaryList as $employee){
  130.             $user = $this->userRepository->find($employee['id']);
  131.             $employee['hourlyRate'] = $user->getHourlyRateUsd();
  132.             $employee['newCost'] = $employee['hours'] * $user->getHourlyRateUsd();
  133.             array_push($newEmployeeSummaryList, $employee);
  134.         }
  135.         */
  136.             // $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  137.             $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  138.             $tmpHours 0;
  139.             $tmpCost 0;
  140.             for ($j 0$j sizeof($employeeSummaryList); $j++) {
  141.                 $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  142.                 $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  143.             }
  144.             //$totalManpowerCost += $tmpCost;
  145.             $departments[$i]['totalCost'] = $tmpCost;
  146.             $departments[$i]['totalHours'] = $tmpHours;
  147.         }
  148.         if (count($departments) > 0) {
  149.             foreach ($departments as $department) {
  150.                 $totalHoursAll += $department['totalHours'];
  151.                 $totalCostAll += $department['totalCost'];
  152.             }
  153.         }
  154.         $record = [];
  155.         $record['departments'] = $departments;
  156.         $record['total']['hours'] = $totalHoursAll;
  157.         $record['total']['cost'] = $totalCostAll;
  158.         return $record;
  159.     }
  160.     public function mergeProject($projectA$projectB)
  161.     {
  162.         $projectA $this->projectRepository->find($projectA);
  163.         $projectB $this->projectRepository->find($projectB);
  164.         if ($projectA == null || $projectB == null) {
  165.             return false;
  166.         }
  167.         $timeSpents $this->timeSpentRepository->findBy(['project' => $projectA]);
  168.         foreach ($timeSpents as $timeSpent) {
  169.             $timeSpent->setProject($projectB);
  170.             $this->entityManager->persist($timeSpent);
  171.         }
  172.         $projectA->setDeletedAt(new \DateTimeImmutable());
  173.         $this->entityManager->flush();
  174.         return true;
  175.     }
  176.     public function projectHostingEmail($project$type="domain")
  177.     {
  178.         $loggedIn false;
  179.         $emailDev $this->params->get('systemEmailIT');
  180.         if($type == "domain") {
  181.             $subject 'email.project_management.project_hosting.domain';
  182.             $emailTemplate 'email/user-notification/project-management/project-hosting-domain.html.twig';
  183.         } else if ($type == "platform") {
  184.             $subject 'email.project_management.project_hosting.platform';
  185.             $emailTemplate 'email/user-notification/project-management/project-hosting-platform.html.twig';
  186.         }
  187.         $picEmail $project->getPersonInCharge()->getCanonicalEmail();
  188.         $this->mailgunService->sendEmailAdvanced(
  189.             [
  190.                 'subject' =>  $this->translator->trans($subject, [
  191.                     '%project_name%' => $project->getName(),
  192.                 ]),
  193.                 'to' => [$picEmail],
  194.                 'cc' => [$emailDev],
  195.                 'template' => $emailTemplate,
  196.                 'params' => [
  197.                     'recipient' => $project->getPersonInCharge()->getPersonalInfo()->getFirstName(),
  198.                     'project' => $project,
  199.                 ],
  200.             ],
  201.             $loggedIn
  202.         );
  203.     }
  204.     public function projectEndEmail($project)
  205.     {
  206.         $loggedIn false;
  207.         // $reminderLog = $editedUser->getReminder();
  208.         $emailMarcom $this->params->get('systemEmailMarcom');
  209.         $subject 'email.project_management.project_end';
  210.         $emailTemplate 'email/user-notification/project-management/project-end.html.twig';
  211.         $picEmail $project->getPersonInCharge()->getCanonicalEmail();
  212.         $this->mailgunService->sendEmailAdvanced(
  213.             [
  214.                 'subject' =>  $this->translator->trans($subject, [
  215.                     '%project_name%' => $project->getName(),
  216.                 ]),
  217.                 'to' => [$picEmail],
  218.                 'cc' => [$emailMarcom],
  219.                 'template' => $emailTemplate,
  220.                 'params' => [
  221.                     'recipient' => $project->getPersonInCharge()->getPersonalInfo()->getFirstName(),
  222.                     'project' => $project,
  223.                 ],
  224.             ],
  225.             $loggedIn
  226.         );
  227.     }
  228.     public function projectFinishedEmail($project)
  229.     {
  230.         $loggedIn false;
  231.         // $reminderLog = $editedUser->getReminder();
  232.         $emailMarcom $this->params->get('systemEmailMarcom');
  233.         $subject 'email.project_management.project_finished';
  234.         $emailTemplate 'email/user-notification/project-management/project-finished.html.twig';
  235.         $picEmail $project->getPersonInCharge()->getCanonicalEmail();
  236.         $picName $project->getPersonInCharge()->getPersonalInfo()->getShortFullName();
  237.         $this->mailgunService->sendEmailAdvanced(
  238.             [
  239.                 'subject' =>  $this->translator->trans($subject, [
  240.                     '%project_name%' => $project->getName(),
  241.                 ]),
  242.                 'to' => [$emailMarcom],
  243.                 'cc' => [$picEmail],
  244.                 'template' => $emailTemplate,
  245.                 'params' => [
  246.                     'recipient' => 'Marcom',
  247.                     'project' => $project,
  248.                     'picName' => $picName,
  249.                     'picEmail' => $picEmail,
  250.                 ],
  251.             ],
  252.             $loggedIn
  253.         );
  254.     }
  255.     public function projectClientFeedbackEmail($project$baseUrl)
  256.     {
  257.         $loggedIn true;
  258.         // $reminderLog = $editedUser->getReminder();
  259.         $emailLeadership $this->params->get('systemEmailLeadership');
  260.         $emailMarcom $this->params->get('systemEmailMarcom');
  261.         $emailManagement $this->params->get('systemEmailManagement');
  262.         $subject 'email.project_management.project_finished_feedback';
  263.         $emailTemplate 'email/user-notification/project-management/project-feedback.html.twig';
  264.         $picEmail $project->getClientPersonInCharge()->getEmail();
  265.         $picName $project->getClientPersonInCharge()->getFirstName();
  266.         $picProjectEmail $project->getPersonInCharge()->getCanonicalEmail();
  267.         $this->mailgunService->sendEmailAdvanced(
  268.             [
  269.                 'subject' =>  $this->translator->trans($subject, [
  270.                     '%project_name%' => $project->getName(),
  271.                 ]),
  272.                 'to' => [$picEmail],
  273.                 'bcc' => [$emailLeadership$emailMarcom$emailManagement$picProjectEmail],
  274.                 'template' => $emailTemplate,
  275.                 'params' => [
  276.                     'recipient' => $picName,
  277.                     'project' => $project,
  278.                     'baseUrl' => $baseUrl,
  279.                 ],
  280.             ],
  281.             $loggedIn
  282.         );
  283.     }
  284.     public function projectDeletedEmail($project$user)
  285.     {
  286.         $loggedIn false;
  287.         $deletedBy $user;
  288.         $emailFinance $this->params->get('systemEmailGroup')['finance'];
  289.         $emailLeadership $this->params->get('systemEmailLeadership');
  290.         $subject 'email.project_management.project_deleted';
  291.         $emailTemplate 'email/user-notification/project-management/project-deleted.html.twig';
  292.         $this->mailgunService->sendEmailAdvanced(
  293.             [
  294.                 'subject' =>  $this->translator->trans($subject, [
  295.                     '%project_name%' => $project->fullName(),
  296.                     '%user%' => $deletedBy->getPersonalInfo()->getFirstName()
  297.                 ]),
  298.                 'to' => [$emailFinance$emailLeadership],
  299.                 'template' => $emailTemplate,
  300.                 'params' => [
  301.                     'recipient' => 'Team',
  302.                     'project' => $project,
  303.                     'user' => $deletedBy,
  304.                 ],
  305.             ],
  306.             $loggedIn
  307.         );
  308.     }
  309.     public function projectVendorPlanningEmail($project)
  310.     {
  311.         $loggedIn false;
  312.         $emailFinance $this->params->get('systemEmailGroup')['finance'];
  313.         $subject 'email.project_management.project_vendor_planning';
  314.         $emailTemplate 'email/user-notification/project-management/project-vendor-planning.html.twig';
  315.         $picEmail $project->getPersonInCharge()->getCanonicalEmail();
  316.         $picName $project->getPersonInCharge()->getPersonalInfo()->getFirstName();
  317.         $this->mailgunService->sendEmailAdvanced(
  318.             [
  319.                 'subject' =>  $this->translator->trans($subject, [
  320.                     '%project_name%' => $project->fullName(),
  321.                 ]),
  322.                 'to' => [$picEmail],
  323.                 'cc' => [$emailFinance],
  324.                 'template' => $emailTemplate,
  325.                 'params' => [
  326.                     'recipient' => $picName,
  327.                     'project' => $project,
  328.                 ],
  329.             ],
  330.             $loggedIn
  331.         );
  332.     }
  333.     public function projectDatesEmail($project$emailType)
  334.     {
  335.         $loggedIn true;
  336.         $subject 'email.project_management.' $emailType '.description';
  337.         $emailTemplate 'email/blank.html.twig';
  338.         $receivers = [
  339.             [
  340.                 'name' => $project->getPersonInCharge()->getPersonalInfo()->getFullName(),
  341.                 'email' =>  $project->getPersonInCharge()->getEmail(),
  342.                 'role' => 'REQ-PARTICIPANT'
  343.             ],
  344.         ];
  345.         $existingEmails array_map(function ($receiver) {
  346.             return $receiver['email'];
  347.         }, $receivers);
  348.         foreach ($project->getProjectMembers() as $projectMember) {
  349.             $memberUser $projectMember->getUser();
  350.             $memberEmail $memberUser->getCanonicalEmail();
  351.             $role 'REQ-PARTICIPANT';
  352.             $receiverData = [
  353.                 'name' => $memberUser->getPersonalInfo()->getFullName(),
  354.                 'email' =>  $memberEmail,
  355.                 'role' => $role
  356.             ];
  357.             if (!in_array($memberEmail$existingEmails)) {
  358.                 array_push($receivers$receiverData);
  359.                 $existingEmails[] = $memberEmail;
  360.             }
  361.         }
  362.         $dateFieldMappings = [
  363.             'proposal_sent_date' => 'proposalDate',
  364.             'client_present_date' => 'presentationDate',
  365.             'proposal_followup_date' => 'proposalFollowUpDate',
  366.             'recontact_date' => 'leadFailRemindDate'
  367.         ];
  368.         $whenDate $project->{'get' $dateFieldMappings[$emailType]}()->format('Y-m-d');
  369.         if ($whenDate date('Y-m-d')) {
  370.             $startDateTime date("Ymd\THis"strtotime($whenDate "9:00:00"));
  371.             $endDateTime date("Ymd\THis"strtotime($whenDate "9:01:00"));
  372.             $subjectParams = [
  373.                 '%project_name%' => $project->getName(),
  374.             ];
  375.             if ($emailType == 'proposal_sent_date' || $emailType == 'client_present_date') {
  376.                 $subjectParams['%date%'] = date('d M Y'strtotime($whenDate));
  377.             }
  378.             $subject $this->translator->trans($subject, [
  379.                 '%project_name%' => $project->getName(),
  380.                 '%date%' => date('d M Y'strtotime($whenDate)),
  381.             ]);
  382.             $icsData =  $this->ics->generateEventFile([
  383.                 'uid' => $project->getId() . '-' $emailType,
  384.                 'title' => $subject,
  385.                 'description' => $this->translator->trans('ics.project_management.' $emailType '.description'$subjectParams),
  386.                 'startDateTime' => $startDateTime,
  387.                 'endDateTime' =>  $endDateTime,
  388.                 'location' => 'TBC',
  389.                 'organizer' => [
  390.                     'name' => 'HR',
  391.                     'email' => $this->params->get('systemEmailAddr')
  392.                 ],
  393.                 'attendee' => $receivers,
  394.                 'reminderTime' => '-15M',
  395.                 'reminderDescription' => $this->translator->trans('ics.project_management.' $emailType '.title'),
  396.             ], true'PUBLISH');
  397.             foreach ($receivers as $receiver) {
  398.                 $this->mailgunService->sendEmailWithAttachment(
  399.                     [
  400.                         'subject' => $subject,
  401.                         'to' => $receiver['email'],
  402.                         'template' => $emailTemplate,
  403.                         'params' => [
  404.                             'recipient' => $receiver['name'],
  405.                             'project' => $project,
  406.                         ],
  407.                         'ical' => $icsData
  408.                     ],
  409.                     $loggedIn
  410.                 );
  411.             }
  412.         }
  413.     }
  414.     public function projectXeroAllocationEmail($object): bool
  415.     {
  416.         $type null;
  417.         if (method_exists($object'getSalesOrderNo') && $object->getSalesOrderNo() != null) {
  418.             $type 'SO';
  419.         } elseif (method_exists($object'getInvoiceNo') && $object->getInvoiceNo() != null) {
  420.             $type 'INV';
  421.         } else {
  422.             return false;
  423.         }
  424.    
  425.         if(count($object->getXeroLineItems()) == 0) {
  426.             return false;
  427.         }
  428.         foreach ($object->getXeroLineItems() as $lineItem) {
  429.             // Skip if the description does not match the project ID pattern
  430.             if (!preg_match($this->projectIdPattern$lineItem->getDescription(), $matches)) {
  431.                 continue;
  432.             }
  433.             $projectId $matches[1];
  434.             $project $this->projectRepository->findOneBy(['generatedId' => $projectId]);
  435.             // If no project is found, exit early
  436.             if (!$project) {
  437.                 return false;
  438.             }
  439.             $hasProjectRelation false;
  440.             switch ($type) {
  441.                 case 'SO':
  442.                     foreach($project->getProjectSalesOrders() as $so) {
  443.                         if($so->getSalesOrder() == $object) {
  444.                             $hasProjectRelation true;
  445.                             break;
  446.                         }
  447.                     }
  448.                     $typeNo $object->getSalesOrderNo();
  449.                     break;
  450.                 case 'INV':
  451.                     foreach($project->getProjectSalesOrders() as $so) {
  452.                         foreach($so->getSalesOrder()->getSalesOrderInvoices() as $soInv) {
  453.                             if($soInv->getInvoice() == $object) {
  454.                                 $hasProjectRelation true;
  455.                                 break;
  456.                             }
  457.                         }
  458.                     }
  459.                     $typeNo $object->getInvoiceNo();
  460.                     break;
  461.                 default:
  462.                     return false;
  463.             }
  464.             // If the relation exists, no need to send a reminder
  465.             if ($hasProjectRelation) {
  466.                 return false;
  467.             }
  468.             // Ensure the project has a Person In Charge (PIC) with an email
  469.             $pic $project->getPersonInCharge();
  470.             if (!$pic || !$pic->getEmail()) {
  471.                 return false;
  472.             }
  473.             // Send the reminder email
  474.             try {
  475.                 $this->mailgunService->sendEmail(
  476.                     $this->translator->trans('email.project_management.so_invoice_need_allocation', [
  477.                         '%type_no%' => $typeNo,
  478.                         '%project%' => $project->getGeneratedId() . ': ' $project->getName()
  479.                     ]),
  480.                     [$pic->getEmail()],
  481.                     'email/user-notification/project-management/so-invoice-need-allocation.html.twig',
  482.                     [
  483.                         'recipient' => $pic,
  484.                         'type' => $type,
  485.                         'type_no' => $typeNo,
  486.                         'project' => $project
  487.                     ],
  488.                     false
  489.                 );
  490.             } catch (\Exception $e) {
  491.                 // If email sending fails, return false
  492.                 return false;
  493.             }
  494.             return true;
  495.         }
  496.         return false;
  497.     }
  498.     public function projectSalesHasAllocatedEmail($object$project): bool
  499.     {
  500.         $type null;
  501.         if (method_exists($object'getSalesOrderNo') && $object->getSalesOrderNo() != null) {
  502.             $type 'SO';
  503.         } elseif (method_exists($object'getInvoiceNo') && $object->getInvoiceNo() != null) {
  504.             $type 'INV';
  505.         } else {
  506.             return false;
  507.         }
  508.         $emailFinance $this->params->get('systemEmailGroup')['finance'];
  509.         switch ($type) {
  510.             case 'SO':
  511.                 $typeNo $object->getSalesOrderNo();
  512.                 break;
  513.             case 'INV':
  514.                 $typeNo $object->getInvoiceNo();
  515.                 break;
  516.             default:
  517.                 return false;
  518.         }
  519.          try {
  520.             $this->mailgunService->sendEmail(
  521.                 $this->translator->trans('email.project_management.so_invoice_allocated', [
  522.                     '%type_no%' => $typeNo,
  523.                     '%project%' => $project->getGeneratedId() . ': ' $project->getName()
  524.                 ]),
  525.                 [$emailFinance],
  526.                 'email/user-notification/project-management/so-invoice-allocated.html.twig',
  527.                 [
  528.                     'recipient' => 'Team',
  529.                     'type' => $type,
  530.                     'type_no' => $typeNo,
  531.                     'project' => $project
  532.                 ],
  533.                 false
  534.             );
  535.         } catch (\Exception $e) {
  536.             // If email sending fails, return false
  537.             return false;
  538.         }
  539.         return true;
  540.     }
  541.     public function generateProjectId()
  542.     {
  543.         $projects $this->projectRepository->findAll();
  544.         $total 0;
  545.         foreach ($projects as $project) {
  546.             if ($project->getGeneratedId() != null) continue;
  547.             $project->setGeneratedId($project->getCreatedAt()->format('ym') . '-' sprintf('%04d'$project->getId()));
  548.             $this->entityManager->persist($project);
  549.             $total++;
  550.         }
  551.         $this->entityManager->flush();
  552.         return $total;
  553.     }
  554.     public function syncProjectType()
  555.     {
  556.         $projects $this->projectRepository->findAll();
  557.         $total 0;
  558.         foreach ($projects as $project) {
  559.             if ($project->getType() == 'INTERNAL' || $project->getDeletedAt() != null) continue;
  560.             if ($project->getType() == 'LEAD' && $project->getLead() == null) {
  561.                 $project->setLead(1);
  562.             }
  563.             if ($project->getType() == 'LEAD') {
  564.                 $project->setStatus(NULL);
  565.             }
  566.             if ($project->getType() == 'CONFIRMED' && !in_array($project->getLead(), [89192])) {
  567.                 $project->setLead(8);
  568.             };
  569.             $total++;
  570.             $this->entityManager->persist($project);
  571.         }
  572.         $this->entityManager->flush();
  573.         return $total;
  574.     }
  575.     public function syncProjectRate()
  576.     {
  577.         $projects $this->projectRepository->findAll();
  578.         $total 0;
  579.         foreach ($projects as $project) {
  580.             foreach ($project->getTasks() as $task) {
  581.                 $timespents $this->timeSpentRepository->findBy(['task' => $task]);
  582.                 foreach ($timespents as $timespent) {
  583.                     $date $timespent->getDate()->format('Y-m-d');
  584.                     $newRate $timespent->getUser()->getHourlyRateUsd($date);
  585.                     if ($timespent->getHourlyRate() == $newRate) continue;
  586.                     $timespent->setHourlyRate($newRate);
  587.                     $total++;
  588.                 }
  589.             }
  590.         }
  591.         $this->entityManager->flush();
  592.         return $total;
  593.     }
  594.     public function syncProjectPlannedRevenue($project null)
  595.     {
  596.         $projects $project ? [$project] : $this->projectRepository->findAll();
  597.         $total 0;
  598.         foreach ($projects as $project) {
  599.             if ($project->getPlannedRevenueUsd() != null) continue;
  600.             $project->setPlannedRevenueUsd($project->getPlannedRevenueToUsd());
  601.             $total++;
  602.         }
  603.         $this->entityManager->flush();
  604.         return $total;
  605.     }
  606.     public function syncProjectEstimatedVendorCost($project null)
  607.     {
  608.         $projects $project ? [$project] : $this->projectRepository->findAll();
  609.         $total 0;
  610.         foreach ($projects as $project) {
  611.             if ($project->getEstimatedVendorCostUsd() != null) continue;
  612.             $project->setEstimatedVendorCostUsd($project->getEstimatedVendorCostToUsd());
  613.             $total++;
  614.         }
  615.         $this->entityManager->flush();
  616.         return $total;
  617.     }
  618.     public function syncProjectDate($project null)
  619.     {
  620.         $projects $project ? [$project] : $this->projectRepository->findAll();
  621.         $total 0;
  622.         foreach ($projects as $project) {
  623.             if ($project->getLeadDate() != null) continue;
  624.             $project->setLeadDate($project->getCreatedAt());
  625.             $total++;
  626.         }
  627.         $this->entityManager->flush();
  628.         return $total;
  629.     }
  630.     public function checkProjectDate($project null)
  631.     {
  632.         $projects $project ? [$project] : $this->projectRepository->findAll();
  633.         $total = [
  634.             'allData' => 0,
  635.             'emptyLeadDate' => 0,
  636.             'emptyProposalDate' => 0,
  637.             'proposalDateFromLog' => 0,
  638.             'filledProposalDateAfterSync' => 0,
  639.             'emptyProposalDateAfterSync' => 0,
  640.             'emptyProposalDateAfterSyncPID' => '',
  641.             'emptyStartDate' => 0,
  642.             'startDateFromLog' => 0,
  643.             'filledStartDateAfterSync' => 0,
  644.             'emptyStartDateAfterSync' => 0,
  645.             'emptyStartDateAfterSyncPID' => ''
  646.         ];
  647.         $loop 0;
  648.         foreach ($projects as $project) {
  649.             // if($loop > 10) break;
  650.             if ($project->getDeletedAt() != null) continue;
  651.             if ($project->getLeadDate() == null$total['emptyLeadDate'] = $total['emptyLeadDate'] + 1;
  652.             if ($project->getProposalDate() == null && $project->getLead() == 5$total['emptyProposalDate'] = $total['emptyProposalDate'] + 1;
  653.             if ($project->getStartDate() == null && $project->getLead() == 8$total['emptyStartDate'] = $total['emptyStartDate'] + 1;
  654.             $projectLog $this->log->data('log.project.edit'$project->getId());
  655.             $skipProposal false;
  656.             $skipStart false;
  657.             foreach ($projectLog as $log) {
  658.                 $oldData json_decode($log->getOldData(), true);
  659.                 $newData json_decode($log->getNewData(), true);
  660.                 if (isset($newData['lead']) && $newData['lead'] == && $project->getLead() == && !$skipProposal) {
  661.                     $total['proposalDateFromLog'] = $total['proposalDateFromLog'] + 1;
  662.                     $skipProposal true;
  663.                 }
  664.                 if (isset($newData['lead']) && $newData['lead'] == && $project->getLead() == && !$skipStart) {
  665.                     $total['startDateFromLog'] = $total['startDateFromLog'] + 1;
  666.                     $skipStart true;
  667.                 }
  668.             }
  669.             if ($project->getLead() == && $project->getProposalDate() == null) {
  670.                 // $project->setProposalDate($project->getCreatedAt());
  671.                 // $this->entityManager->persist($project);
  672.                 // $this->entityManager->flush();
  673.                 if ($skipProposal) {
  674.                     $total['filledProposalDateAfterSync'] = $total['filledProposalDateAfterSync'] + 1;
  675.                 } else {
  676.                     $total['emptyProposalDateAfterSyncPID'] = $total['emptyProposalDateAfterSyncPID'] . $project->getId() . ' ';
  677.                 }
  678.             };
  679.             if ($project->getLead() == && $project->getStartDate() == null) {
  680.                 // $project->setStartDate($project->getCreatedAt());
  681.                 // $this->entityManager->persist($project);
  682.                 // $this->entityManager->flush();
  683.                 if ($skipStart) {
  684.                     $total['filledStartDateAfterSync'] = $total['filledStartDateAfterSync'] + 1;
  685.                 } else {
  686.                     $total['emptyStartDateAfterSyncPID'] = $total['emptyStartDateAfterSyncPID'] . $project->getId() . ' ';
  687.                 }
  688.             }
  689.             $loop++;
  690.         }
  691.         $total['emptyProposalDateAfterSync'] = $total['emptyProposalDate'] - $total['filledProposalDateAfterSync'];
  692.         $total['emptyStartDateAfterSync'] = $total['emptyStartDate'] - $total['filledStartDateAfterSync'];
  693.         $total['allData'] = $loop;
  694.         return $total;
  695.     }
  696.     public function syncProjectProbabilityRate($project null)
  697.     {
  698.         $projects $project ? [$project] : $this->projectRepository->findAll();
  699.         $total 0;
  700.         foreach ($projects as $project) {
  701.             if ($project->getProbability() != null) continue;
  702.             $project->setProbability($project->getProbabilityRate());
  703.             $total++;
  704.         }
  705.         $this->entityManager->flush();
  706.         return $total;
  707.     }
  708.     public function fixProjectWinProbabilityRate($project null)
  709.     {
  710.         $projects $project ? [$project] : $this->projectRepository->findAll();
  711.         $total 0;
  712.         foreach ($projects as $project) {
  713.             if ($project->getProbability() != 100 && $project->getLead() == 8) {
  714.                 $project->setProbability(100);
  715.                 $total++;
  716.             }
  717.         }
  718.         $this->entityManager->flush();
  719.         return $total;
  720.     }
  721.     public function monthlyRevenues($project$useDueDate true)
  722.     {
  723.         if ($project->getStartDate() == null || $project->getEndDate() == null) return $this->monthlyRevenuesWithoutOfPeriod($project);
  724.         $startDate = clone $project->getStartDate();
  725.         $endDate = clone $project->getEndDate();
  726.         $monthlyRevenues = [];
  727.         while ($startDate <= $endDate) {
  728.             $monthYearKey $startDate->format('Ym');
  729.             $monthlyRevenues[$monthYearKey] = [
  730.                 'invoices' => [],
  731.                 'total' => 0,
  732.                 'totalUsd' => 0,
  733.             ];
  734.             $startDate->modify('+1 month');
  735.         }
  736.         $salesOrderInvoice =  $this->salesOrderInvoiceRepository->findAllByProject($project);
  737.         foreach ($salesOrderInvoice as $salesOrder) {
  738.             $invoice $salesOrder->getInvoice();
  739.             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  740.             $monthYear $useDueDate $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
  741.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  742.                 $monthYear $salesOrder->getAllocatedAt()->format('Ym');
  743.             }
  744.             if (!isset($monthlyRevenues[$monthYear]['total'])) {
  745.                 $monthlyRevenues[$monthYear]['total'] = 0;
  746.             }
  747.             if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
  748.                 $monthlyRevenues[$monthYear]['totalUsd'] = 0;
  749.             }
  750.             $outOfPeriod false;
  751.             $dueDate $useDueDate $invoice->getDueDate() : $invoice->getInvoiceDate();
  752.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  753.                 $dueDate $salesOrder->getAllocatedAt();
  754.             }
  755.             $projectStartDate $project->getStartDate();
  756.             $projectEndDate $project->getEndDate();
  757.             if ($dueDate !== null) {
  758.                 $dueDateYearMonth $dueDate->format('Ym');
  759.                 if (($projectStartDate !== null && $dueDateYearMonth $projectStartDate->format('Ym')) ||
  760.                     ($projectEndDate !== null && $dueDateYearMonth $projectEndDate->format('Ym'))
  761.                 ) {
  762.                     $outOfPeriod true;
  763.                 }
  764.             }
  765.             $lineItems = [];
  766.             foreach ($invoice->getXeroLineItems() as $lineItem) {
  767.                 $lineItems[] = [
  768.                     'itemCode' => $lineItem->getItemCode(),
  769.                     'total' => $lineItem->getSubTotal(),
  770.                     'totalUsd' => $lineItem->getSubTotalUsd($project),
  771.                     'isIncluded' => $lineItem->getIsIncluded(),
  772.                 ];
  773.             }
  774.             $monthlyRevenues[$monthYear]['invoices'][] = [
  775.                 'invoiceNo' => $invoice->getInvoiceNo(),
  776.                 'total' => $invoice->getSubTotal(),
  777.                 'totalUsd' => $invoice->getSubTotalUsd($project),
  778.                 'revenue' => $invoice->getRevenue($project),
  779.                 'revenueUsd' => $invoice->getRevenueUsd($project),
  780.                 'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
  781.                 'lineItems' => $lineItems,
  782.                 'outOfPeriod' => $outOfPeriod,
  783.             ];
  784.             $monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
  785.             $monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
  786.         }
  787.         ksort($monthlyRevenues);
  788.         $monthlyRevenues array_combine(
  789.             array_map(function ($key) {
  790.                 return \DateTime::createFromFormat('Ym'$key)->format('M-Y');
  791.             }, array_keys($monthlyRevenues)),
  792.             array_values($monthlyRevenues)
  793.         );
  794.         return $monthlyRevenues;
  795.     }
  796.     public function monthlyRevenuesNew($project$useDueDate true$startRange null$endRange null)
  797.     {
  798.         // dd($startDate, $endDate);
  799.         if ($project->getStartDate() == null || $project->getEndDate() == null) return $this->monthlyRevenuesWithoutOfPeriod($project);
  800.         $startDate = clone $project->getStartDate();
  801.         $endDate = clone $project->getEndDate();
  802.         $monthlyRevenues = [];
  803.         while ($startDate <= $endDate) {
  804.             $monthYearKey $startDate->format('Ym');
  805.             $monthlyRevenues[$monthYearKey] = [
  806.                 'invoices' => [],
  807.                 'total' => 0,
  808.                 'totalUsd' => 0,
  809.             ];
  810.             $startDate->modify('+1 month');
  811.         }
  812.         $salesOrderInvoice =  $this->salesOrderInvoiceRepository->findAllByProject($project);
  813.         foreach ($salesOrderInvoice as $salesOrder) {
  814.             $invoice $salesOrder->getInvoice();
  815.             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  816.             // check invoice in date range
  817.             $dateToCheck $useDueDate $invoice->getDueDate() : $invoice->getInvoiceDate();
  818.             $startDateTime $startRange \DateTime::createFromFormat('Y-m-d'$startRange)->setTime(000) : null;
  819.             $endDateTime $endRange \DateTime::createFromFormat('Y-m-d'$endRange)->setTime(235959) : null;
  820.             if (($startDateTime && $dateToCheck $startDateTime) || ($endDateTime && $dateToCheck $endDateTime)) {
  821.                 continue;
  822.             }
  823.             $monthYear $useDueDate $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
  824.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  825.                 $monthYear $salesOrder->getAllocatedAt()->format('Ym');
  826.             }
  827.             if (!isset($monthlyRevenues[$monthYear]['total'])) {
  828.                 $monthlyRevenues[$monthYear]['total'] = 0;
  829.             }
  830.             if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
  831.                 $monthlyRevenues[$monthYear]['totalUsd'] = 0;
  832.             }
  833.             $outOfPeriod false;
  834.             $dueDate $useDueDate $invoice->getDueDate() : $invoice->getInvoiceDate();
  835.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  836.                 $dueDate $salesOrder->getAllocatedAt();
  837.             }
  838.             $projectStartDate $project->getStartDate();
  839.             $projectEndDate $project->getEndDate();
  840.             if ($dueDate !== null) {
  841.                 $dueDateYearMonth $dueDate->format('Ym');
  842.                 if (($projectStartDate !== null && $dueDateYearMonth $projectStartDate->format('Ym')) ||
  843.                     ($projectEndDate !== null && $dueDateYearMonth $projectEndDate->format('Ym'))
  844.                 ) {
  845.                     $outOfPeriod true;
  846.                 }
  847.             }
  848.             $lineItems = [];
  849.             foreach ($invoice->getXeroLineItems() as $lineItem) {
  850.                 $lineItems[] = [
  851.                     'itemCode' => $lineItem->getItemCode(),
  852.                     'total' => $lineItem->getSubTotal(),
  853.                     'totalUsd' => $lineItem->getSubTotalUsd($project),
  854.                     'isIncluded' => $lineItem->getIsIncluded(),
  855.                 ];
  856.             }
  857.             $monthlyRevenues[$monthYear]['invoices'][] = [
  858.                 'invoiceNo' => $invoice->getInvoiceNo(),
  859.                 'total' => $invoice->getSubTotal(),
  860.                 'totalUsd' => $invoice->getSubTotalUsd($project),
  861.                 'revenue' => $invoice->getRevenue($project),
  862.                 'revenueUsd' => $invoice->getRevenueUsd($project),
  863.                 'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
  864.                 'lineItems' => $lineItems,
  865.                 'outOfPeriod' => $outOfPeriod,
  866.             ];
  867.             $monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
  868.             $monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
  869.         }
  870.         ksort($monthlyRevenues);
  871.         $monthlyRevenues array_combine(
  872.             array_map(function ($key) {
  873.                 return \DateTime::createFromFormat('Ym'$key)->format('M-Y');
  874.             }, array_keys($monthlyRevenues)),
  875.             array_values($monthlyRevenues)
  876.         );
  877.         return $monthlyRevenues;
  878.     }
  879.     public function monthlyRevenuesWithoutOfPeriod($project$useDueDate true)
  880.     {
  881.         // $invoices = $this->invoiceRepository->findAllByProject($project);
  882.         $monthlyRevenues = [];
  883.         $salesOrderInvoice =  $this->salesOrderInvoiceRepository->findAllByProject($project);
  884.         foreach ($salesOrderInvoice as $salesOrder) {
  885.             $invoice $salesOrder->getInvoice();
  886.             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  887.             $monthYear $useDueDate $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
  888.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  889.                 $monthYear $salesOrder->getAllocatedAt()->format('Ym');
  890.             }
  891.             if (!isset($monthlyRevenues[$monthYear]['total'])) {
  892.                 $monthlyRevenues[$monthYear]['total'] = 0;
  893.             }
  894.             if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
  895.                 $monthlyRevenues[$monthYear]['totalUsd'] = 0;
  896.             }
  897.             $outOfPeriod false;
  898.             $dueDate $useDueDate $invoice->getDueDate() : $invoice->getInvoiceDate();
  899.             if(!$useDueDate && $salesOrder->getAllocatedAt()) {
  900.                 $dueDate $salesOrder->getAllocatedAt();
  901.             }
  902.             $projectStartDate $project->getStartDate();
  903.             $projectEndDate $project->getEndDate();
  904.             if ($dueDate !== null) {
  905.                 $dueDateYearMonth $dueDate->format('Ym');
  906.                 if (($projectStartDate !== null && $dueDateYearMonth $projectStartDate->format('Ym')) ||
  907.                     ($projectEndDate !== null && $dueDateYearMonth $projectEndDate->format('Ym'))
  908.                 ) {
  909.                     $outOfPeriod true;
  910.                 }
  911.             }
  912.             $monthlyRevenues[$monthYear]['invoices'][] = [
  913.                 'invoiceNo' => $invoice->getInvoiceNo(),
  914.                 'total' => $invoice->getSubTotal(),
  915.                 'totalUsd' => $invoice->getSubTotalUsd($project),
  916.                 'revenue' => $invoice->getRevenue($project),
  917.                 'revenueUsd' => $invoice->getRevenueUsd($project),
  918.                 'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
  919.                 'outOfPeriod' => $outOfPeriod,
  920.             ];
  921.             $monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
  922.             $monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
  923.         }
  924.         ksort($monthlyRevenues);
  925.         $monthlyRevenues array_combine(
  926.             array_map(function ($key) {
  927.                 return \DateTime::createFromFormat('Ym'$key)->format('M-Y');
  928.             }, array_keys($monthlyRevenues)),
  929.             array_values($monthlyRevenues)
  930.         );
  931.         return $monthlyRevenues;
  932.     }
  933.     public function exportProjectLead($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  934.     {
  935.         if ($isAdmin) {
  936.             $spreadsheet = new Spreadsheet();
  937.             $sheet $spreadsheet->getActiveSheet();
  938.             $sheet->freezePane('A2');
  939.             $sheet->setCellValue('A1''ID');
  940.             $sheet->setCellValue('B1''Client Name');
  941.             $sheet->setCellValue('C1''Client Industry');
  942.             $sheet->setCellValue('D1''Project Classification');
  943.             $sheet->setCellValue('E1''Project Name');
  944.             $sheet->setCellValue('F1''Project Status');
  945.             $sheet->setCellValue('G1''Lead Lost Reason');
  946.             $sheet->setCellValue('H1''Lead Source');
  947.             $sheet->setCellValue('I1''PIC');
  948.             $sheet->setCellValue('J1''PIC Client');
  949.             $sheet->setCellValue('K1''Plan File');
  950.             $sheet->setCellValue('L1''Plan URL');
  951.             $sheet->setCellValue('M1''Created Date in HRP');
  952.             $sheet->setCellValue('N1''Sent Date');
  953.             $sheet->setCellValue('O1''Client Presentation Date');
  954.             $sheet->setCellValue('P1''Start Date');
  955.             $sheet->setCellValue('Q1''End Date');
  956.             $sheet->setCellValue('R1''Lost Date');
  957.             $sheet->setCellValue('S1''SO Number(s)');
  958.             $sheet->setCellValue('T1''Invoice Number(s)');
  959.             $sheet->setCellValue('U1''Estimated Project Billings');
  960.             $sheet->setCellValue('V1''Estimated Agency Revenue');
  961.             $sheet->setCellValue('W1''Estimated Project Billings Based on SO');
  962.             $sheet->setCellValue('X1''Estimated Project Billings Based on INV');
  963.             $sheet->setCellValue('Y1''Estimated Project Hours');
  964.             // $sheet->setCellValue('O1', 'Man Hours Cost');
  965.             $sheet->setCellValue('Z1''Employee Time Record Hours');
  966.             $sheet->setCellValue('AA1''Vendor Costs Based On Plan');
  967.             $sheet->setCellValue('AB1''Vendor Costs Based On INV');
  968.             /*
  969.             $sheet->setCellValue('S1', 'Estimated Project Billings');
  970.             $sheet->setCellValue('ST1', 'Total Cost');
  971.             $sheet->setCellValue('U1', 'Total Profit');
  972.             */
  973.             $sheet->setCellValue('AC1''Project Type');
  974.             /*
  975.             $sheet->setCellValue('AB1', 'Profit (SO amount - 3rd party cost planned - man hours)');
  976.             $sheet->setCellValue('AC1', 'Profit (INV amount - 3rd party cost planned - man hours)');
  977.             $sheet->setCellValue('AD1', 'Profit (SO amount - 3rd party invoices - man hours)');
  978.             $sheet->setCellValue('AE1', 'Profit (INV amount - 3rd party invoices - man hours)');
  979.             */
  980.             $sheet->setCellValue('AD1''% Likely To Win');
  981.             $lastCol $sheet->getHighestColumn();
  982.             $sheet->getDefaultColumnDimension()->setWidth(25);
  983.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  984.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  985.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  986.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  987.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  988.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  989.             $departmentName null;
  990.             if ($department) {
  991.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  992.                 if ($departmentData) {
  993.                     $departmentName $departmentData->getName();
  994.                 };
  995.             };
  996.             $clientName null;
  997.             if ($client) {
  998.                 $clientData $this->entityManager->getRepository(Client::class)->find($client);
  999.                 if ($clientData) {
  1000.                     $clientName $clientData->getName();
  1001.                 };
  1002.             };
  1003.             $picName null;
  1004.             if ($pic) {
  1005.                 $picData $this->entityManager->getRepository(User::class)->find($pic);
  1006.                 if ($picData) {
  1007.                     $picName $picData->getPersonalInfo()->getFullName();
  1008.                 };
  1009.             };
  1010.             $filename "Project";
  1011.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  1012.             $filename .= $clientName "-" urlencode($clientName) : "";
  1013.             $filename .= $picName "-" urlencode($picName) : "";
  1014.             $filename .= $keyword "-" urlencode($keyword) : "";
  1015.             $filename .= $status "-" urlencode($status) : "";
  1016.             $filename .= $type "-" urlencode($type) : "";
  1017.             $filename .= $startDate "_" urlencode($startDate) : "";
  1018.             $filename .= $endDate "-" urlencode($endDate) : "";
  1019.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  1020.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  1021.             $n 0;
  1022.             foreach ($projectsList as $projectDetail) {
  1023.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  1024.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  1025.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  1026.                 $n++;
  1027.             };
  1028.             $row $sheet->getHighestRow();
  1029.             foreach ($projectsList as $project) {
  1030.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  1031.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  1032.                 //$sheet->insertNewRowBefore($row);
  1033.                 $sheet->setCellValue('A' $row$project['generatedId']);
  1034.                 $sheet->setCellValue('B' $row$project['clientName']);
  1035.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  1036.                 $clientIndustries = [];
  1037.                 if ($clientIndustryClassification) {
  1038.                     foreach ($clientIndustryClassification as $industryClass) {
  1039.                         array_push($clientIndustries$industryClass->getName());
  1040.                     }
  1041.                 }
  1042.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  1043.                 $projectTypes $project[0]->getprojectTypes();
  1044.                 $projectClassification = [];
  1045.                 if ($projectTypes) {
  1046.                     foreach ($projectTypes as $projectType) {
  1047.                         array_push($projectClassification$projectType->getName());
  1048.                     }
  1049.                 }
  1050.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  1051.                 $sheet->setCellValue('E' $row$project['name']);
  1052.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  1053.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  1054.                 $leadFailText $project[0]->getLeadFail() ? $project[0]->getLeadFail()->getTitle() : null;
  1055.                 $leadFailReason $project[0]->getLeadFailNote() ?: null;
  1056.                 $leadFailShow $leadFailText . ($leadFailReason ': ' $leadFailReason '');
  1057.                 // $sheet->setCellValue('G' . $row, $project[0]->getLeadFailNote() ?: '-');
  1058.                 $sheet->setCellValue('G' $row$project[0]->getLeadLostReason());
  1059.                 $sheet->setCellValue('H' $row$project[0]->getLeadSource() ?: '-');
  1060.                 $sheet->setCellValue('I' $row$picName);
  1061.                 $sheet->setCellValue('J' $row$picClientName);
  1062.                 $sheet->setCellValue('K' $row$project['planFilename'] ? $project['planFilename'] : "-");
  1063.                 if ($project['planFilename']) {
  1064.                     $sheet->getCell('K' $row)->getHyperlink()->setUrl($project['planFilepath']);
  1065.                 }
  1066.                 $sheet->setCellValue('L' $row$project['planURL'] ? $project['planURL'] : "-");
  1067.                 if ($project['planURL']) {
  1068.                     $sheet->getCell('L' $row)->getHyperlink()->setUrl($project['planURL']);
  1069.                 }
  1070.                 $sheet->setCellValue('M' $row$project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
  1071.                 $sheet->setCellValue('N' $row$project['proposalDate'] ? $project['proposalDate']->format('Y-m-d') : '-');
  1072.                 $sheet->setCellValue('O' $row$project['presentationDate'] ? $project['presentationDate']->format('Y-m-d') : '-');
  1073.                 $sheet->setCellValue('P' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  1074.                 $sheet->setCellValue('Q' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  1075.                 $sheet->setCellValue('R' $row$project[0]->getLeadFailDate() ? $project[0]->getLeadFailDate()->format('Y-m-d') : '-');
  1076.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  1077.                 $proSales = [];
  1078.                 $proSalesInvoices = [];
  1079.                 foreach ($proSalesOrders as $so) {
  1080.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  1081.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  1082.                     foreach ($invoices as $invoice) {
  1083.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  1084.                         array_push($proSalesInvoices$dataINV);
  1085.                     }
  1086.                 }
  1087.                 $sheet->setCellValue('S' $rowimplode(', '$proSales));
  1088.                 $sheet->setCellValue('T' $rowimplode(', '$proSalesInvoices));
  1089.                 /*
  1090.                 $multiRow = $row;
  1091.                 $proSalesOrders = $project[0]->getProjectSalesOrders();
  1092.                 foreach ($proSalesOrders as $so){
  1093.                     $sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
  1094.                     $invoices = $so->getSalesOrder()->getSalesOrderInvoices();
  1095.                     $multiMultiRow = $multiRow;
  1096.                     foreach($invoices as $invoice){
  1097.                         $sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
  1098.                         $multiMultiRow++;
  1099.                     }
  1100.                     $multiRow = $multiMultiRow;
  1101.                 }
  1102.                 */
  1103.                 $sheet->setCellValue('U' $row$project[0]->getPlannedRevenueUsd());
  1104.                 $sheet->setCellValue('V' $row$project[0]->getEstimatedProfitUsd());
  1105.                 $sheet->setCellValue('W' $row$project[0]->getSoTotalUsd());
  1106.                 $sheet->setCellValue('X' $row$project[0]->getInvoicesTotalUsd());
  1107.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  1108.                 $totalEstimatedProjectHours 0;
  1109.                 foreach ($resourceAllocations as $allocation) {
  1110.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  1111.                 }
  1112.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  1113.                 $sheet->setCellValue('Y' $row$estimatedProjectHours);
  1114.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  1115.                 // Calculate employee time record
  1116.                 $_id intval($project['id']);
  1117.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  1118.                 $totalHoursAll 0;
  1119.                 $totalCostAll 0;
  1120.                 for ($i 0$i sizeof($departments); $i++) {
  1121.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  1122.                     $i2 0;
  1123.                     /*foreach($employeeSummaryList as $employee){
  1124.                         $projectMember = $project->getProjectMember($employee['id']);
  1125.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  1126.                         $i2++;
  1127.                     }*/
  1128.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  1129.                     $tmpHours 0;
  1130.                     $tmpCost 0;
  1131.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  1132.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  1133.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  1134.                     }
  1135.                     //$totalManpowerCost += $tmpCost;
  1136.                     $departments[$i]['totalCost'] = $tmpCost;
  1137.                     $departments[$i]['totalHours'] = $tmpHours;
  1138.                 }
  1139.                 if (count($departments) > 0) {
  1140.                     foreach ($departments as $department) {
  1141.                         $totalHoursAll += $department['totalHours'];
  1142.                         $totalCostAll += $department['totalCost'];
  1143.                     }
  1144.                 }
  1145.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  1146.                 $sheet->setCellValue('Z' $row$employeeTimeRecordHours);
  1147.                 $sheet->setCellValue('AA' $row$project[0]->getVendorPlannedTotalUsd());
  1148.                 $sheet->setCellValue('AB' $row$project[0]->getVendorInvoicesTotalUsd());
  1149.                 $sheet->setCellValue('AC' $row$project['type']);
  1150.                 /*
  1151.                 $sheet->setCellValue('AB' . $row, $project[0]->getProjectProfit3());
  1152.                 $sheet->setCellValue('AC' . $row, $project[0]->getProjectProfit4());
  1153.                 $sheet->setCellValue('AD' . $row, $project[0]->getProjectProfit2());
  1154.                 $sheet->setCellValue('AE' . $row, $project[0]->getProjectProfit1());
  1155.                 */
  1156.                 $sheet->setCellValue('AD' $row$project[0]->getProbabilityText());
  1157.                 $row++;
  1158.             }
  1159.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  1160.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  1161.             // $sheet->getStyle('T2:W' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1162.             // $sheet->getStyle('Y2:Z' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1163.             $sheet->getStyle('U2:X' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1164.             $sheet->getStyle('Z2:AA' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1165.             // $sheet->getStyle('AB2:AE' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1166.             /*
  1167.             $sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
  1168.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  1169.             $sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
  1170.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  1171.             */
  1172.         } else {
  1173.             $spreadsheet = new Spreadsheet();
  1174.             $sheet $spreadsheet->getActiveSheet();
  1175.             $sheet->setCellValue('A1''ID');
  1176.             $sheet->setCellValue('B1''Client Name');
  1177.             $sheet->setCellValue('C1''Client Industry');
  1178.             $sheet->setCellValue('D1''Project Classification');
  1179.             $sheet->setCellValue('E1''Project Name');
  1180.             $sheet->setCellValue('F1''Project Status');
  1181.             $sheet->setCellValue('G1''Lead Lost Reason');
  1182.             $sheet->setCellValue('H1''Lead Source');
  1183.             $sheet->setCellValue('I1''PIC');
  1184.             $sheet->setCellValue('J1''PIC Client');
  1185.             $sheet->setCellValue('K1''Plan File');
  1186.             $sheet->setCellValue('L1''Plan URL');
  1187.             $sheet->setCellValue('M1''Created Date in HRP');
  1188.             $sheet->setCellValue('N1''Sent Date');
  1189.             $sheet->setCellValue('O1''Client Presentation Date');
  1190.             $sheet->setCellValue('P1''Start Date');
  1191.             $sheet->setCellValue('Q1''End Date');
  1192.             $sheet->setCellValue('R1''Lost Date');
  1193.             $sheet->setCellValue('S1''SO Number(s)');
  1194.             $sheet->setCellValue('T1''Invoice Number(s)');
  1195.             $sheet->setCellValue('U1''Estimated Project Hours');
  1196.             $sheet->setCellValue('V1''Employee Time Record Hours');
  1197.             $sheet->setCellValue('W1''Vendor Costs Based On Plan');
  1198.             $sheet->setCellValue('X1''Vendor Costs Based On INV');
  1199.             $sheet->setCellValue('Y1''Project Type');
  1200.             $sheet->setCellValue('Z1''% Likely To Win');
  1201.             $lastCol $sheet->getHighestColumn();
  1202.             $sheet->getDefaultColumnDimension()->setWidth(25);
  1203.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  1204.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  1205.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  1206.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  1207.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  1208.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  1209.             $departmentName null;
  1210.             if ($department) {
  1211.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  1212.                 if ($departmentData) {
  1213.                     $departmentName $departmentData->getName();
  1214.                 };
  1215.             };
  1216.             $filename "Project";
  1217.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  1218.             $filename .= $keyword "-" urlencode($keyword) : "";
  1219.             $filename .= $status "-" urlencode($status) : "";
  1220.             $filename .= $type "-" urlencode($type) : "";
  1221.             $filename .= $startDate "_" urlencode($startDate) : "";
  1222.             $filename .= $endDate "-" urlencode($endDate) : "";
  1223.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  1224.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  1225.             $n 0;
  1226.             foreach ($projectsList as $projectDetail) {
  1227.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  1228.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  1229.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  1230.                 $n++;
  1231.             };
  1232.             $row $sheet->getHighestRow();
  1233.             foreach ($projectsList as $project) {
  1234.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  1235.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  1236.                 $sheet->setCellValue('A' $row$project['generatedId']);
  1237.                 $sheet->setCellValue('B' $row$project['clientName']);
  1238.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  1239.                 $clientIndustries = [];
  1240.                 if ($clientIndustryClassification) {
  1241.                     foreach ($clientIndustryClassification as $industryClass) {
  1242.                         array_push($clientIndustries$industryClass->getName());
  1243.                     }
  1244.                 }
  1245.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  1246.                 $projectTypes $project[0]->getprojectTypes();
  1247.                 $projectClassification = [];
  1248.                 if ($projectTypes) {
  1249.                     foreach ($projectTypes as $projectType) {
  1250.                         array_push($projectClassification$projectType->getName());
  1251.                     }
  1252.                 }
  1253.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  1254.                 $sheet->setCellValue('E' $row$project['name']);
  1255.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  1256.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  1257.                 $leadFailText $project[0]->getLeadFail() ? $project[0]->getLeadFail()->getTitle() : null;
  1258.                 $leadFailReason $project[0]->getLeadFailNote() ?: null;
  1259.                 $leadFailShow $leadFailText . ($leadFailReason ': ' $leadFailReason '');
  1260.                 // $sheet->setCellValue('G' . $row, $project[0]->getLeadFailNote()?: '-');
  1261.                 $sheet->setCellValue('G' $row$project[0]->getLeadLostReason());
  1262.                 $sheet->setCellValue('H' $row$project[0]->getLeadSource() ?: '-');
  1263.                 $sheet->setCellValue('I' $row$picName);
  1264.                 $sheet->setCellValue('J' $row$picClientName);
  1265.                 $sheet->setCellValue('K' $row$project['planFilename'] ? $project['planFilename'] : "-");
  1266.                 if ($project['planFilename']) {
  1267.                     $sheet->getCell('K' $row)->getHyperlink()->setUrl($project['planFilepath']);
  1268.                 }
  1269.                 $sheet->setCellValue('L' $row$project['planURL'] ? $project['planURL'] : "-");
  1270.                 if ($project['planURL']) {
  1271.                     $sheet->getCell('L' $row)->getHyperlink()->setUrl($project['planURL']);
  1272.                 }
  1273.                 $sheet->setCellValue('M' $row$project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
  1274.                 $sheet->setCellValue('N' $row$project['proposalDate'] ? $project['proposalDate']->format('Y-m-d') : '-');
  1275.                 $sheet->setCellValue('O' $row$project['presentationDate'] ? $project['presentationDate']->format('Y-m-d') : '-');
  1276.                 $sheet->setCellValue('P' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  1277.                 $sheet->setCellValue('Q' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  1278.                 $sheet->setCellValue('R' $row$project[0]->getLeadFailDate() ? $project[0]->getLeadFailDate()->format('Y-m-d') : '-');
  1279.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  1280.                 $proSales = [];
  1281.                 $proSalesInvoices = [];
  1282.                 foreach ($proSalesOrders as $so) {
  1283.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  1284.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  1285.                     foreach ($invoices as $invoice) {
  1286.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  1287.                         array_push($proSalesInvoices$dataINV);
  1288.                     }
  1289.                 }
  1290.                 $sheet->setCellValue('S' $rowimplode(', '$proSales));
  1291.                 $sheet->setCellValue('T' $rowimplode(', '$proSalesInvoices));
  1292.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  1293.                 $totalEstimatedProjectHours 0;
  1294.                 foreach ($resourceAllocations as $allocation) {
  1295.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  1296.                 }
  1297.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  1298.                 $sheet->setCellValue('U' $row$estimatedProjectHours);
  1299.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  1300.                 // Calculate employee time record
  1301.                 $_id intval($project['id']);
  1302.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  1303.                 $totalHoursAll 0;
  1304.                 $totalCostAll 0;
  1305.                 for ($i 0$i sizeof($departments); $i++) {
  1306.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  1307.                     $i2 0;
  1308.                     /*foreach($employeeSummaryList as $employee){
  1309.                         $projectMember = $project->getProjectMember($employee['id']);
  1310.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  1311.                         $i2++;
  1312.                     }*/
  1313.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  1314.                     $tmpHours 0;
  1315.                     $tmpCost 0;
  1316.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  1317.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  1318.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  1319.                     }
  1320.                     //$totalManpowerCost += $tmpCost;
  1321.                     $departments[$i]['totalCost'] = $tmpCost;
  1322.                     $departments[$i]['totalHours'] = $tmpHours;
  1323.                 }
  1324.                 if (count($departments) > 0) {
  1325.                     foreach ($departments as $department) {
  1326.                         $totalHoursAll += $department['totalHours'];
  1327.                         $totalCostAll += $department['totalCost'];
  1328.                     }
  1329.                 }
  1330.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  1331.                 $sheet->setCellValue('V' $row$employeeTimeRecordHours);
  1332.                 $sheet->setCellValue('W' $row$project[0]->getVendorPlannedTotalUsd());
  1333.                 $sheet->setCellValue('X' $row$project[0]->getVendorInvoicesTotalUsd());
  1334.                 $sheet->setCellValue('Y' $row$project['type']);
  1335.                 $sheet->setCellValue('Z' $row$project[0]->getProbabilityText());
  1336.                 $row++;
  1337.             }
  1338.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  1339.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  1340.             // $sheet->getStyle('V2:W'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1341.             $sheet->getStyle('W2:X' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1342.         }
  1343.         $writer = new Xlsx($spreadsheet);
  1344.         $writer->save($filename);
  1345.         if ($_target == 'google') {
  1346.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  1347.             if ($gsheetURL) {
  1348.                 unlink($filename);
  1349.                 return new RedirectResponse($gsheetURL302);
  1350.             }
  1351.         } else {
  1352.             $response = new Response();
  1353.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1354.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  1355.             $response->setContent(file_get_contents($filename));
  1356.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  1357.             $response->headers->set('Content-Transfer-Encoding''binary');
  1358.             $response->headers->set('Pragma''no-cache');
  1359.             $response->headers->set('Expires''0');
  1360.             unlink($filename);
  1361.             return $response;
  1362.             exit;
  1363.         }
  1364.     }
  1365.     public function exportProjectConfirmed($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  1366.     {
  1367.         if ($isAdmin) {
  1368.             $spreadsheet = new Spreadsheet();
  1369.             $sheet $spreadsheet->getActiveSheet();
  1370.             $sheet->freezePane('A2');
  1371.             $sheet->setCellValue('A1''ID');
  1372.             $sheet->setCellValue('B1''Client Name');
  1373.             $sheet->setCellValue('C1''Client Industry');
  1374.             $sheet->setCellValue('D1''Project Classification');
  1375.             $sheet->setCellValue('E1''Project Name');
  1376.             $sheet->setCellValue('F1''Project Status');
  1377.             $sheet->setCellValue('G1''Score');
  1378.             $sheet->setCellValue('H1''Lead Source');
  1379.             $sheet->setCellValue('I1''PIC');
  1380.             $sheet->setCellValue('J1''PIC Client');
  1381.             $sheet->setCellValue('K1''Plan File');
  1382.             $sheet->setCellValue('L1''Plan URL');
  1383.             $sheet->setCellValue('M1''Created Date in HRP');
  1384.             $sheet->setCellValue('N1''Win Date');
  1385.             $sheet->setCellValue('O1''Start Date');
  1386.             $sheet->setCellValue('P1''End Date');
  1387.             $sheet->setCellValue('Q1''SO Number(s)');
  1388.             $sheet->setCellValue('R1''Invoice Number(s)');
  1389.             $sheet->setCellValue('S1''Estimated Project Billings');
  1390.             $sheet->setCellValue('T1''Estimated Agency Revenue');
  1391.             $sheet->setCellValue('U1''Estimated Project Billings Based on SO');
  1392.             $sheet->setCellValue('V1''Estimated Project Billings Based on INV');
  1393.             $sheet->setCellValue('W1''Estimated Project Hours');
  1394.             // $sheet->setCellValue('O1', 'Man Hours Cost');
  1395.             $sheet->setCellValue('X1''Employee Time Record Hours');
  1396.             $sheet->setCellValue('Y1''Vendor Planned Amount USD');
  1397.             $sheet->setCellValue('Z1''Vendor INV Allocated USD');
  1398.             $sheet->setCellValue('AA1''Budget Remaining USD');
  1399.             $sheet->setCellValue('AB1''Vendor Planned Amount (Vendor planning Currency)');
  1400.             $sheet->setCellValue('AC1''Vendor INV Allocated (Vendor planning Currency)');
  1401.             $sheet->setCellValue('AD1''Budget Remaining (Vendor planning Currency)');
  1402.             /*
  1403.             $sheet->setCellValue('S1', 'Estimated Project Billings');
  1404.             $sheet->setCellValue('ST1', 'Total Cost');
  1405.             $sheet->setCellValue('U1', 'Total Profit');
  1406.             */
  1407.             $sheet->setCellValue('AE1''Project Type');
  1408.             /*
  1409.             $sheet->setCellValue('AE1', 'Profit (SO amount - 3rd party cost planned - man hours)');
  1410.             $sheet->setCellValue('AF1', 'Profit (INV amount - 3rd party cost planned - man hours)');
  1411.             $sheet->setCellValue('AG1', 'Profit (SO amount - 3rd party invoices - man hours)');
  1412.             $sheet->setCellValue('AH1', 'Profit (INV amount - 3rd party invoices - man hours)');
  1413.             $sheet->setCellValue('AI1', 'INV Amount - 3rd Party INV');
  1414.             $sheet->setCellValue('AJ1', 'AM GM');
  1415.             $sheet->setCellValue('AK1', 'Media GM');
  1416.             $sheet->setCellValue('AL1', 'Crea GM');
  1417.             $sheet->setCellValue('AM1', 'Tech GM');
  1418.             $sheet->setCellValue('AN1', 'SEO GM');
  1419.             $sheet->setCellValue('AO1', 'Data GM');
  1420.             $sheet->setCellValue('AP1', 'Social GM');
  1421.             */
  1422.             $lastCol $sheet->getHighestColumn();
  1423.             $sheet->getDefaultColumnDimension()->setWidth(25);
  1424.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  1425.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  1426.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  1427.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  1428.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  1429.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  1430.             $departmentName null;
  1431.             if ($department) {
  1432.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  1433.                 if ($departmentData) {
  1434.                     $departmentName $departmentData->getName();
  1435.                 };
  1436.             };
  1437.             $clientName null;
  1438.             if ($client) {
  1439.                 $clientData $this->entityManager->getRepository(Client::class)->find($client);
  1440.                 if ($clientData) {
  1441.                     $clientName $clientData->getName();
  1442.                 };
  1443.             };
  1444.             $picName null;
  1445.             if ($pic) {
  1446.                 $picData $this->entityManager->getRepository(User::class)->find($pic);
  1447.                 if ($picData) {
  1448.                     $picName $picData->getPersonalInfo()->getFullName();
  1449.                 };
  1450.             };
  1451.             $filename "Project";
  1452.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  1453.             $filename .= $clientName "-" urlencode($clientName) : "";
  1454.             $filename .= $picName "-" urlencode($picName) : "";
  1455.             $filename .= $keyword "-" urlencode($keyword) : "";
  1456.             $filename .= $status "-" urlencode($status) : "";
  1457.             $filename .= $type "-" urlencode($type) : "";
  1458.             $filename .= $startDate "_" urlencode($startDate) : "";
  1459.             $filename .= $endDate "-" urlencode($endDate) : "";
  1460.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  1461.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  1462.             $n 0;
  1463.             foreach ($projectsList as $projectDetail) {
  1464.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  1465.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  1466.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  1467.                 $n++;
  1468.             };
  1469.             $row $sheet->getHighestRow();
  1470.             foreach ($projectsList as $project) {
  1471.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  1472.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  1473.                 //$sheet->insertNewRowBefore($row);
  1474.                 $sheet->setCellValue('A' $row$project['generatedId']);
  1475.                 $sheet->setCellValue('B' $row$project['clientName']);
  1476.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  1477.                 $clientIndustries = [];
  1478.                 if ($clientIndustryClassification) {
  1479.                     foreach ($clientIndustryClassification as $industryClass) {
  1480.                         array_push($clientIndustries$industryClass->getName());
  1481.                     }
  1482.                 }
  1483.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  1484.                 $projectTypes $project[0]->getprojectTypes();
  1485.                 $projectClassification = [];
  1486.                 if ($projectTypes) {
  1487.                     foreach ($projectTypes as $projectType) {
  1488.                         array_push($projectClassification$projectType->getName());
  1489.                     }
  1490.                 }
  1491.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  1492.                 $sheet->setCellValue('E' $row$project['name']);
  1493.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  1494.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  1495.                 $sheet->setCellValue('G' $row$project[0]->getScore() ?: '-');
  1496.                 $sheet->setCellValue('H' $row$project[0]->getLeadSource() ?: '-');
  1497.                 $sheet->setCellValue('I' $row$picName);
  1498.                 $sheet->setCellValue('J' $row$picClientName);
  1499.                 $sheet->setCellValue('K' $row$project['planFilename'] ? $project['planFilename'] : "-");
  1500.                 if ($project['planFilename']) {
  1501.                     $sheet->getCell('K' $row)->getHyperlink()->setUrl($project['planFilepath']);
  1502.                 }
  1503.                 $sheet->setCellValue('L' $row$project['planURL'] ? $project['planURL'] : "-");
  1504.                 if ($project['planURL']) {
  1505.                     $sheet->getCell('L' $row)->getHyperlink()->setUrl($project['planURL']);
  1506.                 }
  1507.                 $sheet->setCellValue('M' $row$project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
  1508.                 $sheet->setCellValue('N' $row$project['winDate'] ? $project['winDate']->format('Y-m-d') : '-');
  1509.                 $sheet->setCellValue('O' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  1510.                 $sheet->setCellValue('P' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  1511.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  1512.                 $proSales = [];
  1513.                 $proSalesInvoices = [];
  1514.                 foreach ($proSalesOrders as $so) {
  1515.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  1516.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  1517.                     foreach ($invoices as $invoice) {
  1518.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  1519.                         array_push($proSalesInvoices$dataINV);
  1520.                     }
  1521.                 }
  1522.                 $sheet->setCellValue('Q' $rowimplode(', '$proSales));
  1523.                 $sheet->setCellValue('R' $rowimplode(', '$proSalesInvoices));
  1524.                 /*
  1525.                 $multiRow = $row;
  1526.                 $proSalesOrders = $project[0]->getProjectSalesOrders();
  1527.                 foreach ($proSalesOrders as $so){
  1528.                     $sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
  1529.                     $invoices = $so->getSalesOrder()->getSalesOrderInvoices();
  1530.                     $multiMultiRow = $multiRow;
  1531.                     foreach($invoices as $invoice){
  1532.                         $sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
  1533.                         $multiMultiRow++;
  1534.                     }
  1535.                     $multiRow = $multiMultiRow;
  1536.                 }
  1537.                 */
  1538.                 $sheet->setCellValue('S' $row$project[0]->getPlannedRevenueUsd());
  1539.                 $sheet->setCellValue('T' $row$project[0]->getEstimatedProfitUsd());
  1540.                 $sheet->setCellValue('U' $row$project[0]->getSoTotalUsd());
  1541.                 $sheet->setCellValue('V' $row$project[0]->getInvoicesTotalUsd());
  1542.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  1543.                 $totalEstimatedProjectHours 0;
  1544.                 foreach ($resourceAllocations as $allocation) {
  1545.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  1546.                 }
  1547.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  1548.                 $sheet->setCellValue('W' $row$estimatedProjectHours);
  1549.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  1550.                 // Calculate employee time record
  1551.                 $_id intval($project['id']);
  1552.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  1553.                 $totalHoursAll 0;
  1554.                 $totalCostAll 0;
  1555.                 for ($i 0$i sizeof($departments); $i++) {
  1556.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  1557.                     $i2 0;
  1558.                     /*foreach($employeeSummaryList as $employee){
  1559.                         $projectMember = $project->getProjectMember($employee['id']);
  1560.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  1561.                         $i2++;
  1562.                     }*/
  1563.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  1564.                     $tmpHours 0;
  1565.                     $tmpCost 0;
  1566.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  1567.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  1568.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  1569.                     }
  1570.                     //$totalManpowerCost += $tmpCost;
  1571.                     $departments[$i]['totalCost'] = $tmpCost;
  1572.                     $departments[$i]['totalHours'] = $tmpHours;
  1573.                 }
  1574.                 if (count($departments) > 0) {
  1575.                     foreach ($departments as $department) {
  1576.                         $totalHoursAll += $department['totalHours'];
  1577.                         $totalCostAll += $department['totalCost'];
  1578.                     }
  1579.                 }
  1580.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  1581.                 $sheet->setCellValue('X' $row$employeeTimeRecordHours);
  1582.                 $sheet->setCellValue('Y' $row$project[0]->getVendorPlannedTotalUsd());
  1583.                 $sheet->setCellValue('Z' $row$project[0]->getVendorInvoicesTotalUsd());
  1584.                 $sheet->setCellValue('AA' $row$project[0]->getProjectBudgetRemainingUsd());
  1585.                 $sheet->setCellValue('AB' $row$project[0]->getVendorPlannedTotal());
  1586.                 $sheet->setCellValue('AC' $row$project[0]->getVendorInvoicesTotal());
  1587.                 $sheet->setCellValue('AD' $row$project[0]->getProjectBudgetRemaining());
  1588.                 $sheet->setCellValue('AE' $row$project['type']);
  1589.                 /*
  1590.                 $sheet->setCellValue('AE' . $row, $project[0]->getProjectProfit3());
  1591.                 $sheet->setCellValue('AF' . $row, $project[0]->getProjectProfit4());
  1592.                 $sheet->setCellValue('AG' . $row, $project[0]->getProjectProfit2());
  1593.                 $sheet->setCellValue('AH' . $row, $project[0]->getInvoicesTotalUsd() - $project[0]->getVendorInvoicesTotalUsd() - $project[0]->getProjectManhourCost());
  1594.                 $invVendorProfit = $project[0]->getInvoicesTotalUsd() - $project[0]->getVendorInvoicesTotalUsd();
  1595.                 $sheet->setCellValue('AI' . $row, $invVendorProfit);
  1596.                 foreach($departments as $hourDept){
  1597.                     switch($hourDept['name']){
  1598.                         case 'Account Management':
  1599.                             $sheet->setCellValue('AJ' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1600.                         break;
  1601.                         case 'Media':
  1602.                             $sheet->setCellValue('AK' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1603.                         break;
  1604.                         case 'Creative':
  1605.                             $sheet->setCellValue('AL' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1606.                         break;
  1607.                         case 'Technology':
  1608.                             $sheet->setCellValue('AM' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1609.                         break;
  1610.                         case 'SEO':
  1611.                             $sheet->setCellValue('AN' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1612.                         break;
  1613.                         case 'Data & Analytics':
  1614.                             $sheet->setCellValue('AO' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1615.                         break;
  1616.                         case 'Social & Content':
  1617.                             $sheet->setCellValue('AP' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
  1618.                         break;
  1619.                     }
  1620.                 }
  1621.                 */
  1622.                 $row++;
  1623.             }
  1624.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  1625.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  1626.             // $sheet->getStyle('R2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1627.             // $sheet->getStyle('X2:AC' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1628.             $sheet->getStyle('S2:V' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1629.             $sheet->getStyle('Y2:AD' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1630.             // $sheet->getStyle('AE2:A'.$lastCol. $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1631.             /*
  1632.             $sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
  1633.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  1634.             $sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
  1635.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  1636.             */
  1637.         } else {
  1638.             $spreadsheet = new Spreadsheet();
  1639.             $sheet $spreadsheet->getActiveSheet();
  1640.             $sheet->setCellValue('A1''ID');
  1641.             $sheet->setCellValue('B1''Client Name');
  1642.             $sheet->setCellValue('C1''Client Industry');
  1643.             $sheet->setCellValue('D1''Project Classification');
  1644.             $sheet->setCellValue('E1''Project Name');
  1645.             $sheet->setCellValue('F1''Project Status');
  1646.             $sheet->setCellValue('G1''Score');
  1647.             $sheet->setCellValue('H1''Lead Source');
  1648.             $sheet->setCellValue('I1''PIC');
  1649.             $sheet->setCellValue('J1''PIC Client');
  1650.             $sheet->setCellValue('K1''Plan File');
  1651.             $sheet->setCellValue('L1''Plan URL');
  1652.             $sheet->setCellValue('M1''Created Date in HRP');
  1653.             $sheet->setCellValue('N1''Win Date');
  1654.             $sheet->setCellValue('O1''Start Date');
  1655.             $sheet->setCellValue('P1''End Date');
  1656.             $sheet->setCellValue('Q1''SO Number(s)');
  1657.             $sheet->setCellValue('R1''Invoice Number(s)');
  1658.             $sheet->setCellValue('S1''Estimated Project Hours');
  1659.             $sheet->setCellValue('T1''Employee Time Record Hours');
  1660.             // $sheet->setCellValue('Q1', 'Vendor Costs Based On Plan');
  1661.             // $sheet->setCellValue('R1', 'Vendor Costs Based On INV');
  1662.             $sheet->setCellValue('U1''Vendor Planned Amount USD');
  1663.             $sheet->setCellValue('V1''Vendor INV Allocated USD');
  1664.             $sheet->setCellValue('W1''Budget Remaining USD');
  1665.             $sheet->setCellValue('X1''Vendor Planned Amount (Vendor planning Currency)');
  1666.             $sheet->setCellValue('Y1''Vendor INV Allocated (Vendor planning Currency)');
  1667.             $sheet->setCellValue('Z1''Budget Remaining (Vendor planning Currency)');
  1668.             $sheet->setCellValue('AA1''Project Type');
  1669.             $lastCol $sheet->getHighestColumn();
  1670.             $sheet->getDefaultColumnDimension()->setWidth(25);
  1671.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  1672.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  1673.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  1674.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  1675.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  1676.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  1677.             $departmentName null;
  1678.             if ($department) {
  1679.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  1680.                 if ($departmentData) {
  1681.                     $departmentName $departmentData->getName();
  1682.                 };
  1683.             };
  1684.             $filename "Project";
  1685.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  1686.             $filename .= $keyword "-" urlencode($keyword) : "";
  1687.             $filename .= $status "-" urlencode($status) : "";
  1688.             $filename .= $type "-" urlencode($type) : "";
  1689.             $filename .= $startDate "_" urlencode($startDate) : "";
  1690.             $filename .= $endDate "-" urlencode($endDate) : "";
  1691.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  1692.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  1693.             $n 0;
  1694.             foreach ($projectsList as $projectDetail) {
  1695.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  1696.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  1697.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  1698.                 $n++;
  1699.             };
  1700.             $row $sheet->getHighestRow();
  1701.             foreach ($projectsList as $project) {
  1702.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  1703.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  1704.                 $sheet->setCellValue('A' $row$project['generatedId']);
  1705.                 $sheet->setCellValue('B' $row$project['clientName']);
  1706.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  1707.                 $clientIndustries = [];
  1708.                 if ($clientIndustryClassification) {
  1709.                     foreach ($clientIndustryClassification as $industryClass) {
  1710.                         array_push($clientIndustries$industryClass->getName());
  1711.                     }
  1712.                 }
  1713.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  1714.                 $projectTypes $project[0]->getprojectTypes();
  1715.                 $projectClassification = [];
  1716.                 if ($projectTypes) {
  1717.                     foreach ($projectTypes as $projectType) {
  1718.                         array_push($projectClassification$projectType->getName());
  1719.                     }
  1720.                 }
  1721.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  1722.                 $sheet->setCellValue('E' $row$project['name']);
  1723.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  1724.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  1725.                 $sheet->setCellValue('G' $row$project[0]->getScore() ?: '-');
  1726.                 $sheet->setCellValue('H' $row$project[0]->getLeadSource() ?: '-');
  1727.                 $sheet->setCellValue('I' $row$picName);
  1728.                 $sheet->setCellValue('J' $row$picClientName);
  1729.                 $sheet->setCellValue('K' $row$project['planFilename'] ? $project['planFilename'] : "-");
  1730.                 if ($project['planFilename']) {
  1731.                     $sheet->getCell('K' $row)->getHyperlink()->setUrl($project['planFilepath']);
  1732.                 }
  1733.                 $sheet->setCellValue('L' $row$project['planURL'] ? $project['planURL'] : "-");
  1734.                 if ($project['planURL']) {
  1735.                     $sheet->getCell('L' $row)->getHyperlink()->setUrl($project['planURL']);
  1736.                 }
  1737.                 $sheet->setCellValue('M' $row$project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
  1738.                 $sheet->setCellValue('N' $row$project['winDate'] ? $project['winDate']->format('Y-m-d') : '-');
  1739.                 $sheet->setCellValue('O' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  1740.                 $sheet->setCellValue('P' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  1741.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  1742.                 $proSales = [];
  1743.                 $proSalesInvoices = [];
  1744.                 foreach ($proSalesOrders as $so) {
  1745.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  1746.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  1747.                     foreach ($invoices as $invoice) {
  1748.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  1749.                         array_push($proSalesInvoices$dataINV);
  1750.                     }
  1751.                 }
  1752.                 $sheet->setCellValue('Q' $rowimplode(', '$proSales));
  1753.                 $sheet->setCellValue('R' $rowimplode(', '$proSalesInvoices));
  1754.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  1755.                 $totalEstimatedProjectHours 0;
  1756.                 foreach ($resourceAllocations as $allocation) {
  1757.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  1758.                 }
  1759.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  1760.                 $sheet->setCellValue('S' $row$estimatedProjectHours);
  1761.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  1762.                 // Calculate employee time record
  1763.                 $_id intval($project['id']);
  1764.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  1765.                 $totalHoursAll 0;
  1766.                 $totalCostAll 0;
  1767.                 for ($i 0$i sizeof($departments); $i++) {
  1768.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  1769.                     $i2 0;
  1770.                     /*foreach($employeeSummaryList as $employee){
  1771.                         $projectMember = $project->getProjectMember($employee['id']);
  1772.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  1773.                         $i2++;
  1774.                     }*/
  1775.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  1776.                     $tmpHours 0;
  1777.                     $tmpCost 0;
  1778.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  1779.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  1780.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  1781.                     }
  1782.                     //$totalManpowerCost += $tmpCost;
  1783.                     $departments[$i]['totalCost'] = $tmpCost;
  1784.                     $departments[$i]['totalHours'] = $tmpHours;
  1785.                 }
  1786.                 if (count($departments) > 0) {
  1787.                     foreach ($departments as $department) {
  1788.                         $totalHoursAll += $department['totalHours'];
  1789.                         $totalCostAll += $department['totalCost'];
  1790.                     }
  1791.                 }
  1792.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  1793.                 $sheet->setCellValue('T' $row$employeeTimeRecordHours);
  1794.                 $sheet->setCellValue('U' $row$project[0]->getVendorPlannedTotalUsd());
  1795.                 $sheet->setCellValue('V' $row$project[0]->getVendorInvoicesTotalUsd());
  1796.                 $sheet->setCellValue('W' $row$project[0]->getProjectBudgetRemainingUsd());
  1797.                 $sheet->setCellValue('X' $row$project[0]->getVendorPlannedTotal());
  1798.                 $sheet->setCellValue('Y' $row$project[0]->getVendorInvoicesTotal());
  1799.                 $sheet->setCellValue('Z' $row$project[0]->getProjectBudgetRemaining());
  1800.                 $sheet->setCellValue('AA' $row$project['type']);
  1801.                 $row++;
  1802.             }
  1803.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  1804.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  1805.             // $sheet->getStyle('T2:Y'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  1806.             $sheet->getStyle('U2:Z' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  1807.         }
  1808.         $writer = new Xlsx($spreadsheet);
  1809.         $writer->save($filename);
  1810.         if ($_target == 'google') {
  1811.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  1812.             if ($gsheetURL) {
  1813.                 unlink($filename);
  1814.                 return new RedirectResponse($gsheetURL302);
  1815.             }
  1816.         } else {
  1817.             $response = new Response();
  1818.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1819.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  1820.             $response->setContent(file_get_contents($filename));
  1821.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  1822.             $response->headers->set('Content-Transfer-Encoding''binary');
  1823.             $response->headers->set('Pragma''no-cache');
  1824.             $response->headers->set('Expires''0');
  1825.             unlink($filename);
  1826.             return $response;
  1827.             exit;
  1828.         }
  1829.     }
  1830.     public function exportProjectInternal($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  1831.     {
  1832.         if ($isAdmin) {
  1833.             $spreadsheet = new Spreadsheet();
  1834.             $sheet $spreadsheet->getActiveSheet();
  1835.             $sheet->freezePane('A2');
  1836.             $sheet->setCellValue('A1''ID');
  1837.             $sheet->setCellValue('B1''Client Name');
  1838.             $sheet->setCellValue('C1''Client Industry');
  1839.             $sheet->setCellValue('D1''Project Classification');
  1840.             $sheet->setCellValue('E1''Project Name');
  1841.             $sheet->setCellValue('F1''Project Status');
  1842.             $sheet->setCellValue('G1''PIC');
  1843.             $sheet->setCellValue('H1''PIC Client');
  1844.             $sheet->setCellValue('I1''Plan File');
  1845.             $sheet->setCellValue('J1''Plan URL');
  1846.             $sheet->setCellValue('K1''Start Date');
  1847.             $sheet->setCellValue('L1''End Date');
  1848.             $sheet->setCellValue('M1''SO Number(s)');
  1849.             $sheet->setCellValue('N1''Invoice Number(s)');
  1850.             $sheet->setCellValue('O1''Estimated Project Billings');
  1851.             $sheet->setCellValue('P1''Estimated Agency Revenue');
  1852.             $sheet->setCellValue('Q1''Estimated Project Billings Based on SO');
  1853.             $sheet->setCellValue('R1''Estimated Project Billings Based on INV');
  1854.             $sheet->setCellValue('S1''Estimated Project Hours');
  1855.             // $sheet->setCellValue('O1', 'Man Hours Cost');
  1856.             $sheet->setCellValue('T1''Employee Time Record Hours');
  1857.             $sheet->setCellValue('U1''Vendor Costs Based On Plan');
  1858.             $sheet->setCellValue('V1''Vendor Costs Based On INV');
  1859.             /*
  1860.             $sheet->setCellValue('S1', 'Estimated Project Billings');
  1861.             $sheet->setCellValue('ST1', 'Total Cost');
  1862.             $sheet->setCellValue('U1', 'Total Profit');
  1863.             */
  1864.             $sheet->setCellValue('W1''Project Type');
  1865.             $sheet->setCellValue('X1''Profit (SO amount - 3rd party cost planned - man hours)');
  1866.             $sheet->setCellValue('Y1''Profit (INV amount - 3rd party cost planned - man hours)');
  1867.             $sheet->setCellValue('Z1''Profit (SO amount - 3rd party invoices - man hours)');
  1868.             $sheet->setCellValue('AA1''Profit (INV amount - 3rd party invoices - man hours)');
  1869.             $lastCol 'AA';
  1870.             $sheet->getDefaultColumnDimension()->setWidth(25);
  1871.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  1872.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  1873.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  1874.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  1875.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  1876.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  1877.             $departmentName null;
  1878.             if ($department) {
  1879.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  1880.                 if ($departmentData) {
  1881.                     $departmentName $departmentData->getName();
  1882.                 };
  1883.             };
  1884.             $clientName null;
  1885.             if ($client) {
  1886.                 $clientData $this->entityManager->getRepository(Client::class)->find($client);
  1887.                 if ($clientData) {
  1888.                     $clientName $clientData->getName();
  1889.                 };
  1890.             };
  1891.             $picName null;
  1892.             if ($pic) {
  1893.                 $picData $this->entityManager->getRepository(User::class)->find($pic);
  1894.                 if ($picData) {
  1895.                     $picName $picData->getPersonalInfo()->getFullName();
  1896.                 };
  1897.             };
  1898.             $filename "Project";
  1899.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  1900.             $filename .= $clientName "-" urlencode($clientName) : "";
  1901.             $filename .= $picName "-" urlencode($picName) : "";
  1902.             $filename .= $keyword "-" urlencode($keyword) : "";
  1903.             $filename .= $status "-" urlencode($status) : "";
  1904.             $filename .= $type "-" urlencode($type) : "";
  1905.             $filename .= $startDate "_" urlencode($startDate) : "";
  1906.             $filename .= $endDate "-" urlencode($endDate) : "";
  1907.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  1908.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  1909.             $n 0;
  1910.             foreach ($projectsList as $projectDetail) {
  1911.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  1912.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  1913.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  1914.                 $n++;
  1915.             };
  1916.             $row $sheet->getHighestRow();
  1917.             foreach ($projectsList as $project) {
  1918.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  1919.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  1920.                 //$sheet->insertNewRowBefore($row);
  1921.                 $sheet->setCellValue('A' $row$project['generatedId']);
  1922.                 $sheet->setCellValue('B' $row$project['clientName']);
  1923.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  1924.                 $clientIndustries = [];
  1925.                 if ($clientIndustryClassification) {
  1926.                     foreach ($clientIndustryClassification as $industryClass) {
  1927.                         array_push($clientIndustries$industryClass->getName());
  1928.                     }
  1929.                 }
  1930.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  1931.                 $projectTypes $project[0]->getprojectTypes();
  1932.                 $projectClassification = [];
  1933.                 if ($projectTypes) {
  1934.                     foreach ($projectTypes as $projectType) {
  1935.                         array_push($projectClassification$projectType->getName());
  1936.                     }
  1937.                 }
  1938.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  1939.                 $sheet->setCellValue('E' $row$project['name']);
  1940.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  1941.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  1942.                 $sheet->setCellValue('G' $row$picName);
  1943.                 $sheet->setCellValue('H' $row$picClientName);
  1944.                 $sheet->setCellValue('I' $row$project['planFilename'] ? $project['planFilename'] : "-");
  1945.                 if ($project['planFilename']) {
  1946.                     $sheet->getCell('I' $row)->getHyperlink()->setUrl($project['planFilepath']);
  1947.                 }
  1948.                 $sheet->setCellValue('J' $row$project['planURL'] ? $project['planURL'] : "-");
  1949.                 if ($project['planURL']) {
  1950.                     $sheet->getCell('J' $row)->getHyperlink()->setUrl($project['planURL']);
  1951.                 }
  1952.                 $sheet->setCellValue('K' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  1953.                 $sheet->setCellValue('L' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  1954.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  1955.                 $proSales = [];
  1956.                 $proSalesInvoices = [];
  1957.                 foreach ($proSalesOrders as $so) {
  1958.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  1959.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  1960.                     foreach ($invoices as $invoice) {
  1961.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  1962.                         array_push($proSalesInvoices$dataINV);
  1963.                     }
  1964.                 }
  1965.                 $sheet->setCellValue('M' $rowimplode(', '$proSales));
  1966.                 $sheet->setCellValue('N' $rowimplode(', '$proSalesInvoices));
  1967.                 /*
  1968.                 $multiRow = $row;
  1969.                 $proSalesOrders = $project[0]->getProjectSalesOrders();
  1970.                 foreach ($proSalesOrders as $so){
  1971.                     $sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
  1972.                     $invoices = $so->getSalesOrder()->getSalesOrderInvoices();
  1973.                     $multiMultiRow = $multiRow;
  1974.                     foreach($invoices as $invoice){
  1975.                         $sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
  1976.                         $multiMultiRow++;
  1977.                     }
  1978.                     $multiRow = $multiMultiRow;
  1979.                 }
  1980.                 */
  1981.                 $sheet->setCellValue('O' $row'-');
  1982.                 $sheet->setCellValue('P' $row'-');
  1983.                 $sheet->setCellValue('Q' $row$project[0]->getSoTotalUsd());
  1984.                 $sheet->setCellValue('R' $row$project[0]->getInvoicesTotalUsd());
  1985.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  1986.                 $totalEstimatedProjectHours 0;
  1987.                 foreach ($resourceAllocations as $allocation) {
  1988.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  1989.                 }
  1990.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  1991.                 $sheet->setCellValue('S' $row$estimatedProjectHours);
  1992.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  1993.                 // Calculate employee time record
  1994.                 $_id intval($project['id']);
  1995.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  1996.                 $totalHoursAll 0;
  1997.                 $totalCostAll 0;
  1998.                 for ($i 0$i sizeof($departments); $i++) {
  1999.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  2000.                     $i2 0;
  2001.                     /*foreach($employeeSummaryList as $employee){
  2002.                         $projectMember = $project->getProjectMember($employee['id']);
  2003.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  2004.                         $i2++;
  2005.                     }*/
  2006.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  2007.                     $tmpHours 0;
  2008.                     $tmpCost 0;
  2009.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  2010.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  2011.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  2012.                     }
  2013.                     //$totalManpowerCost += $tmpCost;
  2014.                     $departments[$i]['totalCost'] = $tmpCost;
  2015.                     $departments[$i]['totalHours'] = $tmpHours;
  2016.                 }
  2017.                 if (count($departments) > 0) {
  2018.                     foreach ($departments as $department) {
  2019.                         $totalHoursAll += $department['totalHours'];
  2020.                         $totalCostAll += $department['totalCost'];
  2021.                     }
  2022.                 }
  2023.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  2024.                 $sheet->setCellValue('T' $row$employeeTimeRecordHours);
  2025.                 $sheet->setCellValue('U' $row$project[0]->getVendorPlannedTotalUsd());
  2026.                 $sheet->setCellValue('V' $row$project[0]->getVendorInvoicesTotalUsd());
  2027.                 $sheet->setCellValue('W' $row$project['type']);
  2028.                 $sheet->setCellValue('X' $row$project[0]->getProjectProfit3());
  2029.                 $sheet->setCellValue('Y' $row$project[0]->getProjectProfit4());
  2030.                 $sheet->setCellValue('Z' $row$project[0]->getProjectProfit2());
  2031.                 $sheet->setCellValue('AA' $row$project[0]->getProjectProfit1());
  2032.                 $row++;
  2033.             }
  2034.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  2035.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  2036.             // $sheet->getStyle('O2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2037.             // $sheet->getStyle('T2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2038.             // $sheet->getStyle('W2:AA' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2039.             $sheet->getStyle('O2:P' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2040.             $sheet->getStyle('T2:U' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2041.             $sheet->getStyle('W2:AA' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2042.             /*
  2043.             $sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
  2044.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  2045.             $sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
  2046.             ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
  2047.             */
  2048.         } else {
  2049.             $spreadsheet = new Spreadsheet();
  2050.             $sheet $spreadsheet->getActiveSheet();
  2051.             $sheet->setCellValue('A1''ID');
  2052.             $sheet->setCellValue('B1''Client Name');
  2053.             $sheet->setCellValue('C1''Client Industry');
  2054.             $sheet->setCellValue('D1''Project Classification');
  2055.             $sheet->setCellValue('E1''Project Name');
  2056.             $sheet->setCellValue('F1''Project Status');
  2057.             $sheet->setCellValue('G1''PIC');
  2058.             $sheet->setCellValue('H1''PIC Client');
  2059.             $sheet->setCellValue('I1''Plan File');
  2060.             $sheet->setCellValue('J1''Plan URL');
  2061.             $sheet->setCellValue('K1''Start Date');
  2062.             $sheet->setCellValue('L1''End Date');
  2063.             $sheet->setCellValue('M1''SO Number(s)');
  2064.             $sheet->setCellValue('N1''Invoice Number(s)');
  2065.             $sheet->setCellValue('O1''Estimated Project Hours');
  2066.             $sheet->setCellValue('P1''Employee Time Record Hours');
  2067.             $sheet->setCellValue('Q1''Vendor Costs Based On Plan');
  2068.             $sheet->setCellValue('R1''Vendor Costs Based On INV');
  2069.             $sheet->setCellValue('S1''Project Type');
  2070.             $lastCol 'S';
  2071.             $sheet->getDefaultColumnDimension()->setWidth(25);
  2072.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->setBold(true);
  2073.             $sheet->getStyle("A1:" $lastCol "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2074.             $sheet->getStyle("A1:" $lastCol "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2075.             $sheet->getStyle("A2:" $lastCol "2")->getFont()->setBold(false);
  2076.             // $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
  2077.             $sheet->getStyle("A2:" $lastCol "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2078.             $departmentName null;
  2079.             if ($department) {
  2080.                 $departmentData $this->entityManager->getRepository(Department::class)->find($department);
  2081.                 if ($departmentData) {
  2082.                     $departmentName $departmentData->getName();
  2083.                 };
  2084.             };
  2085.             $filename "Project";
  2086.             $filename .= $departmentName "-" urlencode($departmentName) : "";
  2087.             $filename .= $keyword "-" urlencode($keyword) : "";
  2088.             $filename .= $status "-" urlencode($status) : "";
  2089.             $filename .= $type "-" urlencode($type) : "";
  2090.             $filename .= $startDate "_" urlencode($startDate) : "";
  2091.             $filename .= $endDate "-" urlencode($endDate) : "";
  2092.             $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  2093.             $projectsList $this->projectRepository->findByPage(09999$keyword"ASC"null$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted$pic);
  2094.             $n 0;
  2095.             foreach ($projectsList as $projectDetail) {
  2096.                 $projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
  2097.                 $projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
  2098.                 $projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
  2099.                 $n++;
  2100.             };
  2101.             $row $sheet->getHighestRow();
  2102.             foreach ($projectsList as $project) {
  2103.                 $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  2104.                 $picClientName $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' $project[0]->getClientPersonInCharge()->getLastName() : '-';
  2105.                 $sheet->setCellValue('A' $row$project['generatedId']);
  2106.                 $sheet->setCellValue('B' $row$project['clientName']);
  2107.                 $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  2108.                 $clientIndustries = [];
  2109.                 if ($clientIndustryClassification) {
  2110.                     foreach ($clientIndustryClassification as $industryClass) {
  2111.                         array_push($clientIndustries$industryClass->getName());
  2112.                     }
  2113.                 }
  2114.                 $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  2115.                 $projectTypes $project[0]->getprojectTypes();
  2116.                 $projectClassification = [];
  2117.                 if ($projectTypes) {
  2118.                     foreach ($projectTypes as $projectType) {
  2119.                         array_push($projectClassification$projectType->getName());
  2120.                     }
  2121.                 }
  2122.                 $sheet->setCellValue('D' $row$projectClassification implode(', '$projectClassification) : '-');
  2123.                 $sheet->setCellValue('E' $row$project['name']);
  2124.                 $sheet->getCell('E' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  2125.                 $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  2126.                 $sheet->setCellValue('G' $row$picName);
  2127.                 $sheet->setCellValue('H' $row$picClientName);
  2128.                 $sheet->setCellValue('I' $row$project['planFilename'] ? $project['planFilename'] : "-");
  2129.                 if ($project['planFilename']) {
  2130.                     $sheet->getCell('I' $row)->getHyperlink()->setUrl($project['planFilepath']);
  2131.                 }
  2132.                 $sheet->setCellValue('J' $row$project['planURL'] ? $project['planURL'] : "-");
  2133.                 if ($project['planURL']) {
  2134.                     $sheet->getCell('J' $row)->getHyperlink()->setUrl($project['planURL']);
  2135.                 }
  2136.                 $sheet->setCellValue('K' $row$project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
  2137.                 $sheet->setCellValue('L' $row$project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
  2138.                 $proSalesOrders $project[0]->getProjectSalesOrders();
  2139.                 $proSales = [];
  2140.                 $proSalesInvoices = [];
  2141.                 foreach ($proSalesOrders as $so) {
  2142.                     array_push($proSales$so->getSalesOrder()->getSalesOrderNo());
  2143.                     $invoices $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  2144.                     foreach ($invoices as $invoice) {
  2145.                         $dataINV $invoice->getInvoice()->getXeroStatus() == 'DRAFT' $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' $invoice->getInvoice()->getInvoiceNo();
  2146.                         array_push($proSalesInvoices$dataINV);
  2147.                     }
  2148.                 }
  2149.                 $sheet->setCellValue('M' $rowimplode(', '$proSales));
  2150.                 $sheet->setCellValue('N' $rowimplode(', '$proSalesInvoices));
  2151.                 $resourceAllocations $this->allocatedHoursRepository->findByProject(''''$project['id']);
  2152.                 $totalEstimatedProjectHours 0;
  2153.                 foreach ($resourceAllocations as $allocation) {
  2154.                     $totalEstimatedProjectHours += intval($allocation->getHours());
  2155.                 }
  2156.                 $estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours '-';
  2157.                 $sheet->setCellValue('O' $row$estimatedProjectHours);
  2158.                 // $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
  2159.                 // Calculate employee time record
  2160.                 $_id intval($project['id']);
  2161.                 $departments $this->timeSpentRepository->getDepartmentsForProject($_id$project[0]->getStartDate(), $project[0]->getEndDate());
  2162.                 $totalHoursAll 0;
  2163.                 $totalCostAll 0;
  2164.                 for ($i 0$i sizeof($departments); $i++) {
  2165.                     $employeeSummaryList $this->userRepository->findTaskSummary($_id$departments[$i]['id']);
  2166.                     $i2 0;
  2167.                     /*foreach($employeeSummaryList as $employee){
  2168.                         $projectMember = $project->getProjectMember($employee['id']);
  2169.                         $employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
  2170.                         $i2++;
  2171.                     }*/
  2172.                     $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
  2173.                     $tmpHours 0;
  2174.                     $tmpCost 0;
  2175.                     for ($j 0$j sizeof($employeeSummaryList); $j++) {
  2176.                         $tmpHours $tmpHours $employeeSummaryList[$j]['hours'];
  2177.                         $tmpCost $tmpCost $employeeSummaryList[$j]['cost'];
  2178.                     }
  2179.                     //$totalManpowerCost += $tmpCost;
  2180.                     $departments[$i]['totalCost'] = $tmpCost;
  2181.                     $departments[$i]['totalHours'] = $tmpHours;
  2182.                 }
  2183.                 if (count($departments) > 0) {
  2184.                     foreach ($departments as $department) {
  2185.                         $totalHoursAll += $department['totalHours'];
  2186.                         $totalCostAll += $department['totalCost'];
  2187.                     }
  2188.                 }
  2189.                 $employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll '-';
  2190.                 $sheet->setCellValue('P' $row$employeeTimeRecordHours);
  2191.                 $sheet->setCellValue('Q' $row$project[0]->getVendorPlannedTotalUsd());
  2192.                 $sheet->setCellValue('R' $row$project[0]->getVendorInvoicesTotalUsd());
  2193.                 $sheet->setCellValue('S' $row$project['type']);
  2194.                 $row++;
  2195.             }
  2196.             $sheet->setAutoFilter('A1:' $lastCol $sheet->getHighestRow());
  2197.             $sheet->getStyle("E1:E" $sheet->getHighestRow())->getFont()->setUnderline(true);
  2198.             // $sheet->getStyle('Q2:R'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2199.             $sheet->getStyle('Q2:R' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2200.         }
  2201.         $writer = new Xlsx($spreadsheet);
  2202.         $writer->save($filename);
  2203.         if ($_target == 'google') {
  2204.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  2205.             if ($gsheetURL) {
  2206.                 unlink($filename);
  2207.                 return new RedirectResponse($gsheetURL302);
  2208.             }
  2209.         } else {
  2210.             $response = new Response();
  2211.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  2212.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  2213.             $response->setContent(file_get_contents($filename));
  2214.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  2215.             $response->headers->set('Content-Transfer-Encoding''binary');
  2216.             $response->headers->set('Pragma''no-cache');
  2217.             $response->headers->set('Expires''0');
  2218.             unlink($filename);
  2219.             return $response;
  2220.             exit;
  2221.         }
  2222.     }
  2223.     /**
  2224.      * Export Project Revenue Forecast by Project Date
  2225.      */
  2226.     public function exportProjectRevenueForecastProjectDate($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$isCashflow true$_target)
  2227.     {
  2228.         $startDateRange date("d-M-Y"strtotime($startDate));
  2229.         $endDateRange date("d-M-Y"strtotime($endDate));
  2230.         $spreadsheet = new Spreadsheet();
  2231.         $sheet $spreadsheet->getActiveSheet()->setTitle($isCashflow 'Cashflow Forecast' 'Revenue Forecast');
  2232.         $sheet->setCellValue('A1''Today\'s Date');
  2233.         $sheet->setCellValue('A2''From');
  2234.         $sheet->setCellValue('A3''To');
  2235.         $sheet->setCellValue('B1'date('d-M-Y'));
  2236.         $sheet->setCellValue('B2'$startDateRange);
  2237.         $sheet->setCellValue('B3'$endDateRange);
  2238.         // Define Header Total
  2239.         $sheet->setCellValue('A5''Total');
  2240.         $sheet->setCellValue('I5''Total Est. Project Billings');
  2241.         $sheet->setCellValue('J5''Total Est. Project Billings FYTD');
  2242.         $sheet->setCellValue('K5''Total Est. Agency Revenue');
  2243.         $sheet->setCellValue('L5''Total Est. Agency Revenue FYTD');
  2244.         $sheet->setCellValue('A6''Total Planned Revenue (LEADS + CONFIRMED)');
  2245.         $sheet->setCellValue('A7''Total CONFIRMED Revenue');
  2246.         $sheet->setCellValue('A8''Total LEADS Revenue');
  2247.         $sheet->mergeCells('A5:H5');
  2248.         $sheet->mergeCells('A6:H6');
  2249.         $sheet->mergeCells('A7:H7');
  2250.         $sheet->mergeCells('A8:H8');
  2251.         // Define Header Data
  2252.         $sheet->setCellValue('A9''Project ID');
  2253.         $sheet->setCellValue('B9''Client Name');
  2254.         $sheet->setCellValue('C9''Client Industry');
  2255.         $sheet->setCellValue('D9''Project Name');
  2256.         $sheet->setCellValue('E9''Project Classification');
  2257.         $sheet->setCellValue('F9''Project Status');
  2258.         $sheet->setCellValue('G9''PIC');
  2259.         $sheet->setCellValue('H9''% Likely to Win');
  2260.         $sheet->setCellValue('I9''Est. Project Billings');
  2261.         $sheet->setCellValue('J9''Est. Project Billings FYTD');
  2262.         $sheet->setCellValue('K9''Est. Agency Revenue');
  2263.         $sheet->setCellValue('L9''Est. Agency Revenue FYTD');
  2264.         $lastCol 'L';
  2265.         $sheet->freezePane('A10');
  2266.         $sheet->freezePane('C10');
  2267.         $sheet->getDefaultColumnDimension()->setWidth(25);
  2268.         $sheet->getColumnDimension('A')->setWidth(11);
  2269.         $sheet->getColumnDimension('H')->setWidth(15);
  2270.         $sheet->getColumnDimension('I')->setWidth(17);
  2271.         $sheet->getColumnDimension('J')->setWidth(17);
  2272.         $sheet->getColumnDimension('K')->setWidth(17);
  2273.         $sheet->getColumnDimension('L')->setWidth(17);
  2274.         $sheet->getStyle("A10:" $lastCol "10")->getFont()->setBold(false);
  2275.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setWrapText(true);
  2276.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2277.         $filename $isCashflow "Cashflow_Forecast_Report" "Revenue_Recognition_Report";
  2278.         $filename .= $startDate "_" urlencode($startDate) : "";
  2279.         $filename .= $endDate "-" urlencode($endDate) : "";
  2280.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  2281.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted);
  2282.         $row $sheet->getHighestRow();
  2283.         $totalEstProjectBillings = [
  2284.             'total' => 0,
  2285.             'confirmed' => 0,
  2286.             'lead' => 0
  2287.         ];
  2288.         $totalEstAgencyRevenue = [
  2289.             'total' => 0,
  2290.             'confirmed' => 0,
  2291.             'lead' => 0
  2292.         ];
  2293.         foreach ($projectsList as $project) {
  2294.             $picName $project['picMiddleName'] ? $project['picFirstName'] . ' ' $project['picMiddleName'] . ' ' $project['picLastName'] : $project['picFirstName'] . ' ' $project['picLastName'];
  2295.             $sheet->setCellValue('A' $row$project['generatedId']);
  2296.             $sheet->setCellValue('B' $row$project['clientName']);
  2297.             $clientIndustryClassification $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  2298.             $clientIndustries = [];
  2299.             if ($clientIndustryClassification) {
  2300.                 foreach ($clientIndustryClassification as $industryClass) {
  2301.                     array_push($clientIndustries$industryClass->getName());
  2302.                 }
  2303.             }
  2304.             $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  2305.             $projectTypes $project[0]->getprojectTypes();
  2306.             $projectClassification = [];
  2307.             if ($projectTypes) {
  2308.                 foreach ($projectTypes as $projectType) {
  2309.                     array_push($projectClassification$projectType->getName());
  2310.                 }
  2311.             }
  2312.             $sheet->setCellValue('D' $row$project['name']);
  2313.             $sheet->getCell('D' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  2314.             $sheet->setCellValue('E' $row$projectClassification implode(', '$projectClassification) : '-');
  2315.             $sheet->setCellValue('F' $row$project['type'] == 'LEAD' $project['lead'] . ' - ' $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  2316.             $sheet->setCellValue('G' $row$picName);
  2317.             $sheet->setCellValue('H' $row$project[0]->getProbabilityText());
  2318.             $probabilityPercent $project[0]->getLeadStatus()->getProbability() / 100;
  2319.             $estProjectBillings $project['type'] == 'LEAD' $project[0]->getPlannedRevenueUsd() * $probabilityPercent $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
  2320.             $estAgencyRevenue $project['type'] == 'LEAD' $project[0]->getEstimatedProfitUsd() * $probabilityPercent $project[0]->getTotalRevenueUSD();
  2321.             if ($project['type'] == 'CONFIRMED') {
  2322.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2323.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2324.             } elseif ($project['type'] == 'LEAD') {
  2325.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2326.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2327.             }
  2328.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2329.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2330.             $sheet->setCellValue('I' $row$estProjectBillings);
  2331.             $sheet->setCellValue('K' $row$estAgencyRevenue);
  2332.             $row++;
  2333.         }
  2334.         $sheet->setCellValue('I6'$totalEstProjectBillings['total']);
  2335.         $sheet->setCellValue('I7'$totalEstProjectBillings['confirmed']);
  2336.         $sheet->setCellValue('I8'$totalEstProjectBillings['lead']);
  2337.         $sheet->setCellValue('K6'$totalEstAgencyRevenue['total']);
  2338.         $sheet->setCellValue('K7'$totalEstAgencyRevenue['confirmed']);
  2339.         $sheet->setCellValue('K8'$totalEstAgencyRevenue['lead']);
  2340.         // define breakdown
  2341.         $column = [];
  2342.         for ($i 65$i <= 90$i++) {
  2343.             $column[] = chr($i);
  2344.         }
  2345.         for ($i 65$i <= 90$i++) {
  2346.             for ($j 65$j <= 90$j++) {
  2347.                 $column[] = chr($i) . chr($j);
  2348.             }
  2349.         }
  2350.         // define column months
  2351.         $monthColumn = [];
  2352.         foreach ($projectsList as $project) {
  2353.             if ($project['lead'] == '8') {
  2354.                 $revenues $this->monthlyRevenues($project[0], $isCashflow);
  2355.                 $newRevenues = [];
  2356.                 foreach ($revenues as $oldKey => $value) {
  2357.                     list($month$year) = explode('-'$oldKey);
  2358.                     $parsedMonth date_parse($month);
  2359.                     $newKey sprintf('%02d-%s'$parsedMonth['month'], $year);
  2360.                     $newRevenues[$newKey] = $value;
  2361.                 }
  2362.                 foreach ($newRevenues as $newRevenueKey => $value) {
  2363.                     $month $newRevenueKey;
  2364.                     if (!in_array($month$monthColumn)) {
  2365.                         $monthColumn[] = $month;
  2366.                     }
  2367.                 }
  2368.             } else {
  2369.                 $revenuePlannings $project[0]->getRevenuePlannings();
  2370.                 foreach ($revenuePlannings as $revenuePlanning) {
  2371.                     $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2372.                     if (!in_array($month$monthColumn)) {
  2373.                         $monthColumn[] = $month;
  2374.                     }
  2375.                 }
  2376.             }
  2377.         }
  2378.         // sort
  2379.         usort($monthColumn, function ($a$b) {
  2380.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  2381.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  2382.             if ($dateA == $dateB) {
  2383.                 return 0;
  2384.             }
  2385.             return ($dateA $dateB) ? -1;
  2386.         });
  2387.         $sortedMonthColumns array_map(function ($date) {
  2388.             $dateTime \DateTime::createFromFormat('d-m-Y''01-' $date);
  2389.             return $dateTime->format('M-Y');
  2390.         }, $monthColumn);
  2391.         $lastCol $sheet->getHighestColumn(); // 'L'
  2392.         $key array_search($lastCol$column);
  2393.         $cellColumn = []; // breakdown month column based on cell column
  2394.         $i $key 1;
  2395.         foreach ($sortedMonthColumns as $monthColumn) {
  2396.             $cellColumn[$i] = $monthColumn;
  2397.             $sheet->setCellValue($column[$i] . "5"$monthColumn);
  2398.             $sheet->setCellValue($column[$i] . "9"$monthColumn);
  2399.             $i++;
  2400.         }
  2401.         $totalColumnBreakdown = [];
  2402.         foreach ($cellColumn as $cell) {
  2403.             $totalColumnBreakdown[$cell]['total'] = 0;
  2404.             $totalColumnBreakdown[$cell]['confirmed'] = 0;
  2405.             $totalColumnBreakdown[$cell]['lead'] = 0;
  2406.         }
  2407.         // fill cell
  2408.         $monthRow 10;
  2409.         foreach ($projectsList as $project) {
  2410.             foreach ($cellColumn as $cellValue => $value) {
  2411.                 $sheet->setCellValue($column[$cellValue] . $monthRow'-');
  2412.             }
  2413.             if ($project['lead'] == '8') {
  2414.                 $revenues $this->monthlyRevenues($project[0], $isCashflow);
  2415.                 foreach ($revenues as $key => $value) {
  2416.                     $month $key;
  2417.                     $cell array_search($month$cellColumn);
  2418.                     $sheet->setCellValue($column[$cell] . $monthRow$value['totalUsd']);
  2419.                     if ($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
  2420.                     $totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
  2421.                 }
  2422.             } else {
  2423.                 $probabilityPercent $project[0]->getLeadStatus()->getProbability() / 100;
  2424.                 $revenuePlannings $project[0]->getRevenuePlannings()->toArray();
  2425.                 if (count($revenuePlannings) > 0) {
  2426.                     foreach ($revenuePlannings as $revenuePlanning) {
  2427.                         $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2428.                         $month =  \DateTime::createFromFormat('d-m-Y''01-' $month)->format('M-Y');
  2429.                         $cell array_search($month$cellColumn);
  2430.                         $revenueAmountUsd $project['type'] == 'LEAD' $revenuePlanning->getAmountUsd() * $probabilityPercent $revenuePlanning->getAmountUsd();
  2431.                         $sheet->setCellValue($column[$cell] . $monthRow$revenueAmountUsd);
  2432.                         if ($project['type'] == 'LEAD')  $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
  2433.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  2434.                         $totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
  2435.                     }
  2436.                 }
  2437.             }
  2438.             $monthRow++;
  2439.         }
  2440.         // fill total cell
  2441.         foreach ($cellColumn as $key => $cellCol) {
  2442.             for ($i 6$i <= 8$i++) {
  2443.                 $type $i == 'total' : ($i == 'confirmed' 'lead');
  2444.                 $sheet->setCellValue($column[$key] . $i$totalColumnBreakdown[$cellCol][$type]);
  2445.             }
  2446.         }
  2447.         // FYTD = 1st nov22 - 31st oct23 
  2448.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  2449.         $currentYear date('Y');
  2450.         $fytdStartDate = new \DateTime($currentYear '-11-01');
  2451.         $fytdEndDate = new \DateTime($currentYear '-10-31');
  2452.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  2453.         $totalEstProjectBillingsFYTD = [
  2454.             'total' => 0,
  2455.             'confirmed' => 0,
  2456.             'lead' => 0
  2457.         ];
  2458.         $totalEstAgencyRevenueFYTD = [
  2459.             'total' => 0,
  2460.             'confirmed' => 0,
  2461.             'lead' => 0
  2462.         ];
  2463.         $row 10;
  2464.         foreach ($projectsList as $project) {
  2465.             $totalMonths 0;
  2466.             $numMonthsFYTD 0;
  2467.             if (!empty($project[0]->getStartDate()) && !empty($project[0]->getEndDate())) {
  2468.                 $dateInterval $project[0]->getEndDate()->diff($project[0]->getStartDate());
  2469.                 $yearsInMonths $dateInterval->12;
  2470.                 $months $dateInterval->m;
  2471.                 $days $dateInterval->d;
  2472.                 if ($days 0) {
  2473.                     $months++;
  2474.                 }
  2475.                 $totalMonths $yearsInMonths $months;
  2476.                 if ($dateInterval->=== && $dateInterval->=== && $dateInterval->=== 0) {
  2477.                     $totalMonths 1;
  2478.                 }
  2479.                 $numMonthsFYTD $this->calculateIncludedMonths($project[0]->getStartDate(), $project[0]->getEndDate());
  2480.             } else {
  2481.                 $totalMonths 1;
  2482.                 $numMonthsFYTD 1;
  2483.             }
  2484.             $probabilityPercent $project[0]->getLeadStatus()->getProbability() / 100;
  2485.             $estProjectBillings $project['type'] == 'LEAD' $project[0]->getPlannedRevenueUsd() * $probabilityPercent $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
  2486.             $estAgencyRevenue $project['type'] == 'LEAD' $project[0]->getEstimatedProfitUsd() * $probabilityPercent $project[0]->getTotalRevenueUSD();
  2487.             $formulaBillings $totalMonths == $numMonthsFYTD $estProjectBillings : ($estProjectBillings $totalMonths) + ($estProjectBillings $totalMonths $numMonthsFYTD);
  2488.             $formulaRevenue $totalMonths == $numMonthsFYTD $estAgencyRevenue : ($estAgencyRevenue $totalMonths) + ($estAgencyRevenue $totalMonths $numMonthsFYTD);
  2489.             if ($project['type'] == 'CONFIRMED') {
  2490.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  2491.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  2492.             } elseif ($project['type'] == 'LEAD') {
  2493.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  2494.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  2495.             }
  2496.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  2497.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  2498.             $sheet->setCellValue('J' $row$formulaBillings);
  2499.             $sheet->setCellValue('L' $row$formulaRevenue);
  2500.             $row++;
  2501.         }
  2502.         
  2503.         $sheet->setCellValue('J6'$totalEstProjectBillingsFYTD['total']);
  2504.         $sheet->setCellValue('J7'$totalEstProjectBillingsFYTD['confirmed']);
  2505.         $sheet->setCellValue('J8'$totalEstProjectBillingsFYTD['lead']);
  2506.         $sheet->setCellValue('L6'$totalEstAgencyRevenueFYTD['total']);
  2507.         $sheet->setCellValue('L7'$totalEstAgencyRevenueFYTD['confirmed']);
  2508.         $sheet->setCellValue('L8'$totalEstAgencyRevenueFYTD['lead']);
  2509.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  2510.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2511.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2512.         $sheet->getStyle("A6:" $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
  2513.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
  2514.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2515.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2516.         $sheet->setAutoFilter('A9:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  2517.         $sheet->getStyle("D1:D" $sheet->getHighestRow())->getFont()->setUnderline(true);
  2518.         // $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2519.         $sheet->getStyle('I6:' $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2520.         // Write the file
  2521.         $writer = new Xlsx($spreadsheet);
  2522.         $writer->save($filename);
  2523.         if ($_target == 'google') {
  2524.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  2525.             if ($gsheetURL) {
  2526.                 unlink($filename);
  2527.                 return new RedirectResponse($gsheetURL302);
  2528.             }
  2529.         } else {
  2530.             $response = new Response();
  2531.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  2532.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  2533.             $response->setContent(file_get_contents($filename));
  2534.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  2535.             $response->headers->set('Content-Transfer-Encoding''binary');
  2536.             $response->headers->set('Pragma''no-cache');
  2537.             $response->headers->set('Expires''0');
  2538.             unlink($filename);
  2539.             return $response;
  2540.             exit;
  2541.         }
  2542.     }
  2543.     
  2544.     /**
  2545.      * Export Project Revenue Forecast by Invoice Date / Due Date
  2546.      */
  2547.     public function exportProjectRevenueForecast($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$isCashflow true$_target)
  2548.     {
  2549.         $startDateRange date("d-M-Y"strtotime($startDate));
  2550.         $endDateRange date("d-M-Y"strtotime($endDate));
  2551.         $spreadsheet = new Spreadsheet();
  2552.         $sheet $spreadsheet->getActiveSheet()->setTitle($isCashflow 'Cashflow Forecast' 'Revenue Forecast');
  2553.         $sheet->setCellValue('A1''Today\'s Date');
  2554.         $sheet->setCellValue('A2''From ' . ($isCashflow '(Invoice Due Date)' '(Invoice Date)'));
  2555.         $sheet->setCellValue('A3''To ' . ($isCashflow '(Invoice Due Date)' '(Invoice Date)'));
  2556.         $sheet->setCellValue('C1'date('d-M-Y'));
  2557.         $sheet->setCellValue('C2'$startDateRange);
  2558.         $sheet->setCellValue('C3'$endDateRange);
  2559.         // Define Header Total
  2560.         $sheet->setCellValue('A5''Total');
  2561.         $sheet->setCellValue('I5''Total Est. Project Billings');
  2562.         $sheet->setCellValue('J5''Total Est. Project Billings FYTD');
  2563.         $sheet->setCellValue('K5''Total Est. Agency Revenue');
  2564.         $sheet->setCellValue('L5''Total Est. Agency Revenue FYTD');
  2565.         $sheet->setCellValue('A6''Total Planned Revenue (LEADS + CONFIRMED)');
  2566.         $sheet->setCellValue('A7''Total CONFIRMED Revenue');
  2567.         $sheet->setCellValue('A8''Total LEADS Revenue');
  2568.         $sheet->mergeCells('A5:H5');
  2569.         $sheet->mergeCells('A6:H6');
  2570.         $sheet->mergeCells('A7:H7');
  2571.         $sheet->mergeCells('A8:H8');
  2572.         // Define Header Data
  2573.         $sheet->setCellValue('A9''Project ID');
  2574.         $sheet->setCellValue('B9''Client Name');
  2575.         $sheet->setCellValue('C9''Client Industry');
  2576.         $sheet->setCellValue('D9''Project Name');
  2577.         $sheet->setCellValue('E9''Project Classification');
  2578.         $sheet->setCellValue('F9''Project Status');
  2579.         $sheet->setCellValue('G9''PIC');
  2580.         $sheet->setCellValue('H9''% Likely to Win');
  2581.         $sheet->setCellValue('I9''Est. Project Billings');
  2582.         $sheet->setCellValue('J9''Est. Project Billings FYTD');
  2583.         $sheet->setCellValue('K9''Est. Agency Revenue');
  2584.         $sheet->setCellValue('L9''Est. Agency Revenue FYTD');
  2585.         $lastCol $sheet->getHighestColumn();
  2586.         $sheet->freezePane('A10');
  2587.         $sheet->freezePane('D10');
  2588.         $sheet->getDefaultColumnDimension()->setWidth(25);
  2589.         $sheet->getColumnDimension('A')->setWidth(11);
  2590.         $sheet->getColumnDimension('H')->setWidth(15);
  2591.         $sheet->getColumnDimension('I')->setWidth(17);
  2592.         $sheet->getColumnDimension('J')->setWidth(17);
  2593.         $sheet->getColumnDimension('K')->setWidth(17);
  2594.         $sheet->getColumnDimension('L')->setWidth(17);
  2595.         $sheet->getStyle("A10:" $lastCol "10")->getFont()->setBold(false);
  2596.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setWrapText(true);
  2597.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2598.         $filename $isCashflow "Cashflow_Forecast_Report" "Revenue_Forecast_Report";
  2599.         $filename .= $startDate "_" urlencode($startDate) : "";
  2600.         $filename .= $endDate "-" urlencode($endDate) : "";
  2601.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  2602.         // $projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
  2603.         $projectsList = [];
  2604.         $projectIds = [];
  2605.         $invoiceList $this->invoiceRepository->findByPage(09999"""DESC"""""""$startDate$endDate$isCashflow);
  2606.         foreach ($invoiceList as $invoice) {
  2607.             $salesOrderInvoices $invoice->getSalesOrderInvoices()->toArray();
  2608.             foreach ($salesOrderInvoices as $salesOrderInvoice) {
  2609.                 $project $salesOrderInvoice->getProject();
  2610.                 $projectId $project->getId();
  2611.                 if (!in_array($projectId$projectIds)) {
  2612.                     $projectsList[] = $project;
  2613.                     $projectIds[] = $projectId;
  2614.                 }
  2615.             }
  2616.         }
  2617.         $row $sheet->getHighestRow();
  2618.         $totalEstProjectBillings = [
  2619.             'total' => 0,
  2620.             'confirmed' => 0,
  2621.             'lead' => 0
  2622.         ];
  2623.         $totalEstAgencyRevenue = [
  2624.             'total' => 0,
  2625.             'confirmed' => 0,
  2626.             'lead' => 0
  2627.         ];
  2628.         foreach ($projectsList as $project) {
  2629.             $picName $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
  2630.             $sheet->setCellValue('A' $row$project->getGeneratedId());
  2631.             $sheet->setCellValue('B' $row$project->getClient() ? $project->getClient()->getName() : '');
  2632.             $clientIndustryClassification $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
  2633.             $clientIndustries = [];
  2634.             if ($clientIndustryClassification) {
  2635.                 foreach ($clientIndustryClassification as $industryClass) {
  2636.                     array_push($clientIndustries$industryClass->getName());
  2637.                 }
  2638.             }
  2639.             $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  2640.             $projectTypes $project->getProjectTypes();
  2641.             $projectClassification = [];
  2642.             if ($projectTypes) {
  2643.                 foreach ($projectTypes as $projectType) {
  2644.                     array_push($projectClassification$projectType->getName());
  2645.                 }
  2646.             }
  2647.             $sheet->setCellValue('D' $row$project->getName());
  2648.             $sheet->getCell('D' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project->getId());
  2649.             $sheet->setCellValue('E' $row$projectClassification implode(', '$projectClassification) : '-');
  2650.             $sheet->setCellValue('F' $row$project->getType() == 'LEAD' $project->getLead() . ' - ' $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
  2651.             $sheet->setCellValue('G' $row$picName);
  2652.             $sheet->setCellValue('H' $row$project->getProbabilityText());
  2653.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2654.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2655.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2656.             if ($project->getType() == 'CONFIRMED') {
  2657.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2658.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2659.             } elseif ($project->getType() == 'LEAD') {
  2660.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2661.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2662.             }
  2663.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2664.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2665.             $sheet->setCellValue('I' $row$estProjectBillings);
  2666.             $sheet->setCellValue('K' $row$estAgencyRevenue);
  2667.             $row++;
  2668.         }
  2669.         $sheet->setCellValue('I6'$totalEstProjectBillings['total']);
  2670.         $sheet->setCellValue('I7'$totalEstProjectBillings['confirmed']);
  2671.         $sheet->setCellValue('I8'$totalEstProjectBillings['lead']);
  2672.         $sheet->setCellValue('K6'$totalEstAgencyRevenue['total']);
  2673.         $sheet->setCellValue('K7'$totalEstAgencyRevenue['confirmed']);
  2674.         $sheet->setCellValue('K8'$totalEstAgencyRevenue['lead']);
  2675.         // define breakdown
  2676.         $column = [];
  2677.         for ($i 65$i <= 90$i++) {
  2678.             $column[] = chr($i);
  2679.         }
  2680.         for ($i 65$i <= 90$i++) {
  2681.             for ($j 65$j <= 90$j++) {
  2682.                 $column[] = chr($i) . chr($j);
  2683.             }
  2684.         }
  2685.         // define column months
  2686.         $monthColumn = [];
  2687.         foreach ($projectsList as $project) {
  2688.             if ($project->getLead() == '8') {
  2689.                 $revenues $this->monthlyRevenuesNew($project$isCashflow$startDate$endDate);
  2690.                 $newRevenues = [];
  2691.                 foreach ($revenues as $oldKey => $value) {
  2692.                     list($month$year) = explode('-'$oldKey);
  2693.                     $parsedMonth date_parse($month);
  2694.                     $newKey sprintf('%02d-%s'$parsedMonth['month'], $year);
  2695.                     $newRevenues[$newKey] = $value;
  2696.                 }
  2697.                 foreach ($newRevenues as $newRevenueKey => $value) {
  2698.                     $month $newRevenueKey;
  2699.                     if (!in_array($month$monthColumn)) {
  2700.                         $monthColumn[] = $month;
  2701.                     }
  2702.                 }
  2703.             } else {
  2704.                 $revenuePlannings $project->getRevenuePlannings();
  2705.                 foreach ($revenuePlannings as $revenuePlanning) {
  2706.                     $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2707.                     if (!in_array($month$monthColumn)) {
  2708.                         $monthColumn[] = $month;
  2709.                     }
  2710.                 }
  2711.             }
  2712.         }
  2713.         // sort
  2714.         usort($monthColumn, function ($a$b) {
  2715.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  2716.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  2717.             if ($dateA == $dateB) {
  2718.                 return 0;
  2719.             }
  2720.             return ($dateA $dateB) ? -1;
  2721.         });
  2722.         $sortedMonthColumns array_map(function ($date) {
  2723.             $dateTime \DateTime::createFromFormat('d-m-Y''01-' $date);
  2724.             return $dateTime->format('M-Y');
  2725.         }, $monthColumn);
  2726.         // dd($monthColumn);
  2727.         $lastCol $sheet->getHighestColumn(); // 'L'
  2728.         $key array_search($lastCol$column);
  2729.         $cellColumn = []; // breakdown month column based on cell column
  2730.         $i $key 1;
  2731.         foreach ($sortedMonthColumns as $monthColumn) {
  2732.             $cellColumn[$i] = $monthColumn;
  2733.             $sheet->setCellValue($column[$i] . "5"$monthColumn);
  2734.             $sheet->setCellValue($column[$i] . "9"$monthColumn);
  2735.             $i++;
  2736.         }
  2737.         $totalColumnBreakdown = [];
  2738.         foreach ($cellColumn as $cell) {
  2739.             $totalColumnBreakdown[$cell]['total'] = 0;
  2740.             $totalColumnBreakdown[$cell]['confirmed'] = 0;
  2741.             $totalColumnBreakdown[$cell]['lead'] = 0;
  2742.         }
  2743.         // fill cell
  2744.         $monthRow 10;
  2745.         foreach ($projectsList as $project) {
  2746.             foreach ($cellColumn as $cellValue => $value) {
  2747.                 $sheet->setCellValue($column[$cellValue] . $monthRow'-');
  2748.             }
  2749.             if ($project->getLead() == '8') {
  2750.                 $revenues $this->monthlyRevenuesNew($project$isCashflow$startDate$endDate);
  2751.                 foreach ($revenues as $key => $value) {
  2752.                     $month $key;
  2753.                     $cell array_search($month$cellColumn);
  2754.                     $sheet->setCellValue($column[$cell] . $monthRow$value['totalUsd']);
  2755.                     if ($project->getType() == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
  2756.                     $totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
  2757.                 }
  2758.             } else {
  2759.                 $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2760.                 $revenuePlannings $project->getRevenuePlannings()->toArray();
  2761.                 if (count($revenuePlannings) > 0) {
  2762.                     foreach ($revenuePlannings as $revenuePlanning) {
  2763.                         $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2764.                         $month =  \DateTime::createFromFormat('d-m-Y''01-' $month)->format('M-Y');
  2765.                         $cell array_search($month$cellColumn);
  2766.                         $revenueAmountUsd $project->getType() == 'LEAD' $revenuePlanning->getAmountUsd() * $probabilityPercent $revenuePlanning->getAmountUsd();
  2767.                         $sheet->setCellValue($column[$cell] . $monthRow$revenueAmountUsd);
  2768.                         if ($project->getType() == 'LEAD')  $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
  2769.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  2770.                         $totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
  2771.                     }
  2772.                 }
  2773.             }
  2774.             $monthRow++;
  2775.         }
  2776.         // fill total cell
  2777.         foreach ($cellColumn as $key => $cellCol) {
  2778.             for ($i 6$i <= 8$i++) {
  2779.                 $type $i == 'total' : ($i == 'confirmed' 'lead');
  2780.                 $sheet->setCellValue($column[$key] . $i$totalColumnBreakdown[$cellCol][$type]);
  2781.             }
  2782.         }
  2783.         // FYTD = 1st nov22 - 31st oct23 
  2784.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  2785.         $currentYear date('Y');
  2786.         $fytdStartDate = new \DateTime($currentYear '-11-01');
  2787.         $fytdEndDate = new \DateTime($currentYear '-10-31');
  2788.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  2789.         $totalEstProjectBillingsFYTD = [
  2790.             'total' => 0,
  2791.             'confirmed' => 0,
  2792.             'lead' => 0
  2793.         ];
  2794.         $totalEstAgencyRevenueFYTD = [
  2795.             'total' => 0,
  2796.             'confirmed' => 0,
  2797.             'lead' => 0
  2798.         ];
  2799.         $row 10;
  2800.         foreach ($projectsList as $project) {
  2801.             $totalMonths 0;
  2802.             $numMonthsFYTD 0;
  2803.             if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
  2804.                 $dateInterval $project->getEndDate()->diff($project->getStartDate());
  2805.                 $yearsInMonths $dateInterval->12;
  2806.                 $months $dateInterval->m;
  2807.                 $days $dateInterval->d;
  2808.                 if ($days 0) {
  2809.                     $months++;
  2810.                 }
  2811.                 $totalMonths $yearsInMonths $months;
  2812.                 if ($dateInterval->=== && $dateInterval->=== && $dateInterval->=== 0) {
  2813.                     $totalMonths 1;
  2814.                 }
  2815.                 $numMonthsFYTD $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
  2816.             } else {
  2817.                 $totalMonths 1;
  2818.                 $numMonthsFYTD 1;
  2819.             }
  2820.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2821.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2822.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2823.             $formulaBillings $totalMonths == $numMonthsFYTD $estProjectBillings : ($estProjectBillings $totalMonths) + ($estProjectBillings $totalMonths $numMonthsFYTD);
  2824.             $formulaRevenue $totalMonths == $numMonthsFYTD $estAgencyRevenue : ($estAgencyRevenue $totalMonths) + ($estAgencyRevenue $totalMonths $numMonthsFYTD);
  2825.             if ($project->getType() == 'CONFIRMED') {
  2826.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  2827.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  2828.             } elseif ($project->getType() == 'LEAD') {
  2829.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  2830.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  2831.             }
  2832.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  2833.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  2834.             $sheet->setCellValue('J' $row$formulaBillings);
  2835.             $sheet->setCellValue('L' $row$formulaRevenue);
  2836.             $row++;
  2837.         }
  2838.         
  2839.         $sheet->setCellValue('J6'$totalEstProjectBillingsFYTD['total']);
  2840.         $sheet->setCellValue('J7'$totalEstProjectBillingsFYTD['confirmed']);
  2841.         $sheet->setCellValue('J8'$totalEstProjectBillingsFYTD['lead']);
  2842.         $sheet->setCellValue('L6'$totalEstAgencyRevenueFYTD['total']);
  2843.         $sheet->setCellValue('L7'$totalEstAgencyRevenueFYTD['confirmed']);
  2844.         $sheet->setCellValue('L8'$totalEstAgencyRevenueFYTD['lead']);
  2845.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  2846.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2847.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2848.         $sheet->getStyle("A6:" $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
  2849.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
  2850.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2851.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2852.         $sheet->setAutoFilter('A9:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  2853.         $sheet->getStyle("D1:D" $sheet->getHighestRow())->getFont()->setUnderline(true);
  2854.         // $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2855.         $sheet->getStyle('I6:' $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2856.         // LEAD Revenue Projection
  2857.         $leadSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Revenue Projection');
  2858.         $spreadsheet->addSheet($leadSheet1);
  2859.         $leadSheet->setCellValue('A1''Today\'s Date');
  2860.         $leadSheet->setCellValue('A2''From (Project Start Date)');
  2861.         $leadSheet->setCellValue('A3''To (Project Start Date)');
  2862.         $leadSheet->setCellValue('C1'date('d-M-Y'));
  2863.         $leadSheet->setCellValue('C2'$startDateRange);
  2864.         $leadSheet->setCellValue('C3'$endDateRange);
  2865.         // Define Header Total
  2866.         $leadSheet->setCellValue('A5''Total');
  2867.         $leadSheet->setCellValue('I5''Total Est. Project Billings');
  2868.         $leadSheet->setCellValue('J5''Total Est. Project Billings FYTD');
  2869.         $leadSheet->setCellValue('K5''Total Est. Agency Revenue');
  2870.         $leadSheet->setCellValue('L5''Total Est. Agency Revenue FYTD');
  2871.         $leadSheet->setCellValue('A6''Total Planned Revenue (LEADS + CONFIRMED)');
  2872.         $leadSheet->setCellValue('A7''Total CONFIRMED Revenue');
  2873.         $leadSheet->setCellValue('A8''Total LEADS Revenue');
  2874.         $leadSheet->mergeCells('A5:H5');
  2875.         $leadSheet->mergeCells('A6:H6');
  2876.         $leadSheet->mergeCells('A7:H7');
  2877.         $leadSheet->mergeCells('A8:H8');
  2878.         // Define Header Data
  2879.         $leadSheet->setCellValue('A9''Project ID');
  2880.         $leadSheet->setCellValue('B9''Client Name');
  2881.         $leadSheet->setCellValue('C9''Client Industry');
  2882.         $leadSheet->setCellValue('D9''Project Name');
  2883.         $leadSheet->setCellValue('E9''Project Classification');
  2884.         $leadSheet->setCellValue('F9''Project Status');
  2885.         $leadSheet->setCellValue('G9''PIC');
  2886.         $leadSheet->setCellValue('H9''% Likely to Win');
  2887.         $leadSheet->setCellValue('I9''Est. Project Billings');
  2888.         $leadSheet->setCellValue('J9''Est. Project Billings FYTD');
  2889.         $leadSheet->setCellValue('K9''Est. Agency Revenue');
  2890.         $leadSheet->setCellValue('L9''Est. Agency Revenue FYTD');
  2891.         $lastColx $leadSheet->getHighestColumn();
  2892.         $leadSheet->freezePane('A10');
  2893.         $leadSheet->freezePane('D10');
  2894.         $leadSheet->getDefaultColumnDimension()->setWidth(25);
  2895.         $leadSheet->getColumnDimension('A')->setWidth(11);
  2896.         $leadSheet->getColumnDimension('H')->setWidth(15);
  2897.         $leadSheet->getColumnDimension('I')->setWidth(17);
  2898.         $leadSheet->getColumnDimension('J')->setWidth(17);
  2899.         $leadSheet->getColumnDimension('K')->setWidth(17);
  2900.         $leadSheet->getColumnDimension('L')->setWidth(17);
  2901.         $leadSheet->getStyle("A10:" $lastColx "10")->getFont()->setBold(false);
  2902.         $leadSheet->getStyle("A10:" $lastColx "10")->getAlignment()->setWrapText(true);
  2903.         $leadSheet->getStyle("A10:" $lastColx "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2904.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate'LEAD'$client$status$project$department$retainer$assignedUser$showDeleted);
  2905.         // $projectsList = [];
  2906.         // $projectIds = [];
  2907.         // $invoiceList = $this->invoiceRepository->findByPage(0, 9999, "", "DESC", "", "PAID", "", $startDate, $endDate);
  2908.         // foreach ($invoiceList as $invoice) {
  2909.         //     $salesOrderInvoices = $invoice->getSalesOrderInvoices()->toArray();
  2910.         //     foreach ($salesOrderInvoices as $salesOrderInvoice) {
  2911.         //         $project = $salesOrderInvoice->getProject();
  2912.         //         $projectId = $project->getId();
  2913.         //         if (!in_array($projectId, $projectIds)) {
  2914.         //             $projectsList[] = $project;
  2915.         //             $projectIds[] = $projectId;
  2916.         //         }
  2917.         //     }
  2918.         // }
  2919.         $leadRow $leadSheet->getHighestRow();
  2920.         $totalEstProjectBillings = [
  2921.             'total' => 0,
  2922.             'confirmed' => 0,
  2923.             'lead' => 0
  2924.         ];
  2925.         $totalEstAgencyRevenue = [
  2926.             'total' => 0,
  2927.             'confirmed' => 0,
  2928.             'lead' => 0
  2929.         ];
  2930.         foreach ($projectsList as $project) {
  2931.             $project $project[0];
  2932.             $picName $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
  2933.             $leadSheet->setCellValue('A' $leadRow$project->getGeneratedId());
  2934.             $leadSheet->setCellValue('B' $leadRow$project->getClient() ? $project->getClient()->getName() : '');
  2935.             $clientIndustryClassification $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
  2936.             $clientIndustries = [];
  2937.             if ($clientIndustryClassification) {
  2938.                 foreach ($clientIndustryClassification as $industryClass) {
  2939.                     array_push($clientIndustries$industryClass->getName());
  2940.                 }
  2941.             }
  2942.             $leadSheet->setCellValue('C' $leadRow$clientIndustries implode(', '$clientIndustries) : '-');
  2943.             $projectTypes $project->getProjectTypes();
  2944.             $projectClassification = [];
  2945.             if ($projectTypes) {
  2946.                 foreach ($projectTypes as $projectType) {
  2947.                     array_push($projectClassification$projectType->getName());
  2948.                 }
  2949.             }
  2950.             $leadSheet->setCellValue('D' $leadRow$project->getName());
  2951.             $leadSheet->getCell('D' $leadRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project->getId());
  2952.             $leadSheet->setCellValue('E' $leadRow$projectClassification implode(', '$projectClassification) : '-');
  2953.             $leadSheet->setCellValue('F' $leadRow$project->getType() == 'LEAD' $project->getLead() . ' - ' $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
  2954.             $leadSheet->setCellValue('G' $leadRow$picName);
  2955.             $leadSheet->setCellValue('H' $leadRow$project->getProbabilityText());
  2956.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2957.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2958.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2959.             if ($project->getType() == 'CONFIRMED') {
  2960.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2961.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2962.             } elseif ($project->getType() == 'LEAD') {
  2963.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2964.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2965.             }
  2966.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2967.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2968.             $leadSheet->setCellValue('I' $leadRow$estProjectBillings);
  2969.             $leadSheet->setCellValue('K' $leadRow$estAgencyRevenue);
  2970.             $leadRow++;
  2971.         }
  2972.         $leadSheet->setCellValue('I6'$totalEstProjectBillings['total']);
  2973.         $leadSheet->setCellValue('I7'$totalEstProjectBillings['confirmed']);
  2974.         $leadSheet->setCellValue('I8'$totalEstProjectBillings['lead']);
  2975.         $leadSheet->setCellValue('K6'$totalEstAgencyRevenue['total']);
  2976.         $leadSheet->setCellValue('K7'$totalEstAgencyRevenue['confirmed']);
  2977.         $leadSheet->setCellValue('K8'$totalEstAgencyRevenue['lead']);
  2978.         // define breakdown
  2979.         $columnx = [];
  2980.         for ($i 65$i <= 90$i++) {
  2981.             $columnx[] = chr($i);
  2982.         }
  2983.         for ($i 65$i <= 90$i++) {
  2984.             for ($j 65$j <= 90$j++) {
  2985.                 $columnx[] = chr($i) . chr($j);
  2986.             }
  2987.         }
  2988.         // define column months
  2989.         $monthColumnx = [];
  2990.         foreach ($projectsList as $project) {
  2991.             $project $project[0];
  2992.             if ($project->getLead() == '8') {
  2993.                 $revenues $this->monthlyRevenues($project$isCashflow);
  2994.                 $newRevenues = [];
  2995.                 foreach ($revenues as $oldKey => $value) {
  2996.                     list($month$year) = explode('-'$oldKey);
  2997.                     $parsedMonth date_parse($month);
  2998.                     $newKey sprintf('%02d-%s'$parsedMonth['month'], $year);
  2999.                     $newRevenues[$newKey] = $value;
  3000.                 }
  3001.                 foreach ($newRevenues as $newRevenueKey => $value) {
  3002.                     $month $newRevenueKey;
  3003.                     if (!in_array($month$monthColumnx)) {
  3004.                         $monthColumnx[] = $month;
  3005.                     }
  3006.                 }
  3007.             } else {
  3008.                 $revenuePlannings $project->getRevenuePlannings();
  3009.                 foreach ($revenuePlannings as $revenuePlanning) {
  3010.                     $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  3011.                     if (!in_array($month$monthColumnx)) {
  3012.                         $monthColumnx[] = $month;
  3013.                     }
  3014.                 }
  3015.             }
  3016.         }
  3017.         // sort
  3018.         usort($monthColumnx, function ($a$b) {
  3019.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  3020.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  3021.             if ($dateA == $dateB) {
  3022.                 return 0;
  3023.             }
  3024.             return ($dateA $dateB) ? -1;
  3025.         });
  3026.         $sortedMonthColumnsx array_map(function ($date) {
  3027.             $dateTime \DateTime::createFromFormat('d-m-Y''01-' $date);
  3028.             return $dateTime->format('M-Y');
  3029.         }, $monthColumnx);
  3030.         $lastColx $leadSheet->getHighestColumn(); // 'L'
  3031.         $key array_search($lastColx$columnx);
  3032.         $cellColumnx = []; // breakdown month column based on cell column
  3033.         $i $key 1;
  3034.         foreach ($sortedMonthColumnsx as $monthColumnx) {
  3035.             $cellColumnx[$i] = $monthColumnx;
  3036.             $leadSheet->setCellValue($columnx[$i] . "5"$monthColumnx);
  3037.             $leadSheet->setCellValue($columnx[$i] . "9"$monthColumnx);
  3038.             $i++;
  3039.         }
  3040.         $totalColumnBreakdownx = [];
  3041.         foreach ($cellColumnx as $cell) {
  3042.             $totalColumnBreakdownx[$cell]['total'] = 0;
  3043.             $totalColumnBreakdownx[$cell]['confirmed'] = 0;
  3044.             $totalColumnBreakdownx[$cell]['lead'] = 0;
  3045.         }
  3046.         // fill cell
  3047.         $monthRowx 10;
  3048.         foreach ($projectsList as $project) {
  3049.             $project $project[0];
  3050.             foreach ($cellColumnx as $cellValue => $value) {
  3051.                 $leadSheet->setCellValue($columnx[$cellValue] . $monthRowx'-');
  3052.             }
  3053.             if ($project->getLead() == '8') {
  3054.                 $revenues $this->monthlyRevenues($project$isCashflow);
  3055.                 foreach ($revenues as $key => $value) {
  3056.                     $month $key;
  3057.                     $cell array_search($month$cellColumnx);
  3058.                     $leadSheet->setCellValue($columnx[$cell] . $monthRowx$value['totalUsd']);
  3059.                     if ($project->getType() == 'CONFIRMED')  $totalColumnBreakdownx[$month]['confirmed'] += $value['totalUsd'];
  3060.                     $totalColumnBreakdownx[$month]['total'] += $value['totalUsd'];
  3061.                 }
  3062.             } else {
  3063.                 $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  3064.                 $revenuePlannings $project->getRevenuePlannings()->toArray();
  3065.                 if (count($revenuePlannings) > 0) {
  3066.                     foreach ($revenuePlannings as $revenuePlanning) {
  3067.                         $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  3068.                         $month =  \DateTime::createFromFormat('d-m-Y''01-' $month)->format('M-Y');
  3069.                         $cell array_search($month$cellColumnx);
  3070.                         $revenueAmountUsd $project->getType() == 'LEAD' $revenuePlanning->getAmountUsd() * $probabilityPercent $revenuePlanning->getAmountUsd();
  3071.                         $leadSheet->setCellValue($columnx[$cell] . $monthRowx$revenueAmountUsd);
  3072.                         if ($project->getType() == 'LEAD')  $totalColumnBreakdownx[$month]['lead'] += $revenueAmountUsd;
  3073.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  3074.                         $totalColumnBreakdownx[$month]['total'] += $revenueAmountUsd;
  3075.                     }
  3076.                 }
  3077.             }
  3078.             $monthRowx++;
  3079.         }
  3080.         // fill total cell
  3081.         foreach ($cellColumnx as $key => $cellCol) {
  3082.             for ($i 6$i <= 8$i++) {
  3083.                 $type $i == 'total' : ($i == 'confirmed' 'lead');
  3084.                 $leadSheet->setCellValue($columnx[$key] . $i$totalColumnBreakdownx[$cellCol][$type]);
  3085.             }
  3086.         }
  3087.         // FYTD = 1st nov22 - 31st oct23 
  3088.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  3089.         $currentYear date('Y');
  3090.         $fytdStartDate = new \DateTime($currentYear '-11-01');
  3091.         $fytdEndDate = new \DateTime($currentYear '-10-31');
  3092.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  3093.         $totalEstProjectBillingsFYTD = [
  3094.             'total' => 0,
  3095.             'confirmed' => 0,
  3096.             'lead' => 0
  3097.         ];
  3098.         $totalEstAgencyRevenueFYTD = [
  3099.             'total' => 0,
  3100.             'confirmed' => 0,
  3101.             'lead' => 0
  3102.         ];
  3103.         $leadRow 10;
  3104.         foreach ($projectsList as $project) {
  3105.             $project $project[0];
  3106.             $totalMonths 0;
  3107.             $numMonthsFYTD 0;
  3108.             if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
  3109.                 $dateInterval $project->getEndDate()->diff($project->getStartDate());
  3110.                 $yearsInMonths $dateInterval->12;
  3111.                 $months $dateInterval->m;
  3112.                 $days $dateInterval->d;
  3113.                 if ($days 0) {
  3114.                     $months++;
  3115.                 }
  3116.                 $totalMonths $yearsInMonths $months;
  3117.                 if ($dateInterval->=== && $dateInterval->=== && $dateInterval->=== 0) {
  3118.                     $totalMonths 1;
  3119.                 }
  3120.                 $numMonthsFYTD $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
  3121.             } else {
  3122.                 $totalMonths 1;
  3123.                 $numMonthsFYTD 1;
  3124.             }
  3125.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  3126.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  3127.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  3128.             $formulaBillings $totalMonths == $numMonthsFYTD $estProjectBillings : ($estProjectBillings $totalMonths) + ($estProjectBillings $totalMonths $numMonthsFYTD);
  3129.             $formulaRevenue $totalMonths == $numMonthsFYTD $estAgencyRevenue : ($estAgencyRevenue $totalMonths) + ($estAgencyRevenue $totalMonths $numMonthsFYTD);
  3130.             if ($project->getType() == 'CONFIRMED') {
  3131.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  3132.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  3133.             } elseif ($project->getType() == 'LEAD') {
  3134.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  3135.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  3136.             }
  3137.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  3138.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  3139.             $leadSheet->setCellValue('J' $leadRow$formulaBillings);
  3140.             $leadSheet->setCellValue('L' $leadRow$formulaRevenue);
  3141.             $leadRow++;
  3142.         }
  3143.         
  3144.         $leadSheet->setCellValue('J6'$totalEstProjectBillingsFYTD['total']);
  3145.         $leadSheet->setCellValue('J7'$totalEstProjectBillingsFYTD['confirmed']);
  3146.         $leadSheet->setCellValue('J8'$totalEstProjectBillingsFYTD['lead']);
  3147.         $leadSheet->setCellValue('L6'$totalEstAgencyRevenueFYTD['total']);
  3148.         $leadSheet->setCellValue('L7'$totalEstAgencyRevenueFYTD['confirmed']);
  3149.         $leadSheet->setCellValue('L8'$totalEstAgencyRevenueFYTD['lead']);
  3150.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3151.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3152.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3153.         $leadSheet->getStyle("A6:" $leadSheet->getHighestColumn() . "8")->getFont()->setBold(true);
  3154.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFont()->setBold(true);
  3155.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3156.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3157.         $leadSheet->setAutoFilter('A9:' $leadSheet->getHighestColumn() . $leadSheet->getHighestRow());
  3158.         $leadSheet->getStyle("D1:D" $leadSheet->getHighestRow())->getFont()->setUnderline(true);
  3159.         // $leadSheet->getStyle('I6:'.$leadSheet->getHighestColumn().$leadSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3160.         $leadSheet->getStyle('I6:' $leadSheet->getHighestColumn() . $leadSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3161.         // Write the file
  3162.         $writer = new Xlsx($spreadsheet);
  3163.         $writer->save($filename);
  3164.         if ($_target == 'google') {
  3165.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3166.             if ($gsheetURL) {
  3167.                 unlink($filename);
  3168.                 return new RedirectResponse($gsheetURL302);
  3169.             }
  3170.         } else {
  3171.             $response = new Response();
  3172.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3173.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3174.             $response->setContent(file_get_contents($filename));
  3175.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3176.             $response->headers->set('Content-Transfer-Encoding''binary');
  3177.             $response->headers->set('Pragma''no-cache');
  3178.             $response->headers->set('Expires''0');
  3179.             unlink($filename);
  3180.             return $response;
  3181.             exit;
  3182.         }
  3183.     }
  3184.     public function exportProjectVendorInvoices($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  3185.     {
  3186.         $startDateRange date("d-M-Y"strtotime($startDate));
  3187.         $endDateRange date("d-M-Y"strtotime($endDate));
  3188.         $spreadsheet = new Spreadsheet();
  3189.         $vendorInvoiceSheet $spreadsheet->getActiveSheet()->setTitle('Vendor Invoices');
  3190.         $vendorInvoiceSheet->setCellValue('A1''Today\'s Date');
  3191.         $vendorInvoiceSheet->setCellValue('A2''From');
  3192.         $vendorInvoiceSheet->setCellValue('A3''To');
  3193.         $vendorInvoiceSheet->setCellValue('B1'date('d-M-Y'));
  3194.         $vendorInvoiceSheet->setCellValue('B2'$startDateRange);
  3195.         $vendorInvoiceSheet->setCellValue('B3'$endDateRange);
  3196.         $vendorInvoiceSheet->setCellValue("A5""Vendor Name");
  3197.         $vendorInvoiceSheet->setCellValue("B5""Invoice Date");
  3198.         $vendorInvoiceSheet->setCellValue("C5""Invoice Status");
  3199.         $vendorInvoiceSheet->setCellValue("D5""Client");
  3200.         $vendorInvoiceSheet->setCellValue("E5""Project");
  3201.         $vendorInvoiceSheet->setCellValue("F5""Amount USD");
  3202.         $vendorInvoiceSheet->setCellValue("G5""Allocated USD");
  3203.         $vendorInvoiceSheet->setCellValue("H5""Amount Left USD");
  3204.         $vendorInvoiceSheet->setCellValue("I5""Due Date");
  3205.         $vendorInvoiceSheet->setCellValue("J5""Client INV");
  3206.         $vendorInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
  3207.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3208.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3209.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3210.         $filename "Project_Vendor_Invoices_Report";
  3211.         $filename .= $startDate "_" urlencode($startDate) : "";
  3212.         $filename .= $endDate "-" urlencode($endDate) : "";
  3213.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  3214.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted);
  3215.         $vendorRow $vendorInvoiceSheet->getHighestRow() + 1;
  3216.         foreach ($projectsList as $project) {
  3217.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings()->toArray();
  3218.             if ($vendorQuotationPlannings) {
  3219.                 foreach ($vendorQuotationPlannings as $vqp) {
  3220.                     $vqpvis $vqp->getVendorQuotationPlanningVendorInvoices()->toArray();
  3221.                     if ($vqpvis) {
  3222.                         foreach ($vqpvis as $vqpvi) {
  3223.                             $vqp $vqpvi->getVendorQuotationPlanning();
  3224.                             $vendorInvoice $vqpvi->getVendorInvoice();
  3225.                             $vendorInvoiceSheet->setCellValue("A" $vendorRow$vqp->getVendor()->getName());
  3226.                             $vendorInvoiceSheet->setCellValue("B" $vendorRow$vendorInvoice->getInvoiceDate()->format("Y-m-d"));
  3227.                             $vendorInvoiceSheet->setCellValue("C" $vendorRow$vendorInvoice->getCustomXeroStatus());
  3228.                             $vendorInvoiceSheet->setCellValue("D" $vendorRow$vqp->getProject()->getClient()->getName());
  3229.                             $vendorInvoiceSheet->setCellValue("E" $vendorRow$vqp->getProject()->getName());
  3230.                             $vendorInvoiceSheet->getCell('E' $vendorRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3231.                             $vendorInvoiceSheet->setCellValue("F" $vendorRow$vendorInvoice->getSubTotalUsd());
  3232.                             $vendorInvoiceSheet->setCellValue("G" $vendorRow$vqpvi->getAmountUsd());
  3233.                             $vendorInvoiceSheet->setCellValue("H" $vendorRow$vendorInvoice->getAmountLeftUsd());
  3234.                             $vendorInvoiceSheet->setCellValue("I" $vendorRow$vendorInvoice->getDueDate()->format("Y-m-d"));
  3235.                             $vendorInvoiceSheet->setCellValue("J" $vendorRow$vqpvi->getInvoice() ? $vqpvi->getInvoice()->getInvoiceNo() : '-');
  3236.                             $vendorRow++;
  3237.                         }
  3238.                     }
  3239.                 }
  3240.             }
  3241.         }
  3242.         $vendorInvoiceSheet->setAutoFilter('A5:' $vendorInvoiceSheet->getHighestColumn() . $vendorInvoiceSheet->getHighestRow());
  3243.         $vendorInvoiceSheet->getStyle("E6:E" $vendorInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
  3244.         // $vendorInvoiceSheet->getStyle('F6:'.'H'.$vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3245.         $vendorInvoiceSheet->getStyle('F6:' 'H' $vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3246.         $spreadsheet->setActiveSheetIndex(0);
  3247.         // Write the file
  3248.         $writer = new Xlsx($spreadsheet);
  3249.         $writer->save($filename);
  3250.         if ($_target == 'google') {
  3251.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3252.             if ($gsheetURL) {
  3253.                 unlink($filename);
  3254.                 return new RedirectResponse($gsheetURL302);
  3255.             }
  3256.         } else {
  3257.             $response = new Response();
  3258.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3259.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3260.             $response->setContent(file_get_contents($filename));
  3261.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3262.             $response->headers->set('Content-Transfer-Encoding''binary');
  3263.             $response->headers->set('Pragma''no-cache');
  3264.             $response->headers->set('Expires''0');
  3265.             unlink($filename);
  3266.             return $response;
  3267.             exit;
  3268.         }
  3269.     }
  3270.     public function exportProjectClientInvoices($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  3271.     {
  3272.         $startDateRange date("d-M-Y"strtotime($startDate));
  3273.         $endDateRange date("d-M-Y"strtotime($endDate));
  3274.         $spreadsheet = new Spreadsheet();
  3275.         $clientInvoiceSheet $spreadsheet->getActiveSheet()->setTitle('Client Invoices');
  3276.         $clientInvoiceSheet->setCellValue('A1''Today\'s Date');
  3277.         $clientInvoiceSheet->setCellValue('A2''From');
  3278.         $clientInvoiceSheet->setCellValue('A3''To');
  3279.         $clientInvoiceSheet->setCellValue('B1'date('d-M-Y'));
  3280.         $clientInvoiceSheet->setCellValue('B2'$startDateRange);
  3281.         $clientInvoiceSheet->setCellValue('B3'$endDateRange);
  3282.         $clientInvoiceSheet->setCellValue("A5""Client Name");
  3283.         $clientInvoiceSheet->setCellValue("B5""Project Name");
  3284.         $clientInvoiceSheet->setCellValue("C5""Project Status");
  3285.         $clientInvoiceSheet->setCellValue("D5""PIC Name");
  3286.         $clientInvoiceSheet->setCellValue("E5""Client PIC");
  3287.         $clientInvoiceSheet->setCellValue("F5""INV Number");
  3288.         $clientInvoiceSheet->setCellValue("G5""INV Status");
  3289.         $clientInvoiceSheet->setCellValue("H5""INV Due Date");
  3290.         $clientInvoiceSheet->setCellValue("I5""INV Amount");
  3291.         $clientInvoiceSheet->setCellValue("J5""INV Currency");
  3292.         $clientInvoiceSheet->setCellValue("K5""INV Amount USD");
  3293.         $filename "Project_Client_Invoices_Report";
  3294.         $filename .= $startDate "_" urlencode($startDate) : "";
  3295.         $filename .= $endDate "-" urlencode($endDate) : "";
  3296.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  3297.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted);
  3298.         $column = [];
  3299.         for ($i 65$i <= 90$i++) {
  3300.             $column[] = chr($i);
  3301.         }
  3302.         for ($i 65$i <= 90$i++) {
  3303.             for ($j 65$j <= 90$j++) {
  3304.                 $column[] = chr($i) . chr($j);
  3305.             }
  3306.         }
  3307.         $monthColumn = [];
  3308.         $row $clientInvoiceSheet->getHighestRow() + 1;
  3309.         foreach ($projectsList as $project) {
  3310.             $projectSalesOrders $project[0]->getProjectSalesOrders()->toArray();
  3311.             if ($projectSalesOrders) {
  3312.                 foreach ($projectSalesOrders as $pso) {
  3313.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
  3314.                     if ($soInvoices) {
  3315.                         foreach ($soInvoices as $soInvoice) {
  3316.                             $proj $soInvoice->getProject();
  3317.                             $projectName $proj->getName();
  3318.                             $clientName $proj->getClient()->getName();
  3319.                             $projectPic $proj->getPersonInCharge() ? $proj->getPersonInCharge()->getPersonalInfo()->getFullName() : '-';
  3320.                             $clientPic $proj->getClientPersonInCharge() ? $proj->getClientPersonInCharge()->getName() : '-';
  3321.                             $invoice $soInvoice->getInvoice();
  3322.                             $clientInvoiceSheet->setCellValue("A" $row$clientName);
  3323.                             $clientInvoiceSheet->setCellValue("B" $row$projectName);
  3324.                             $clientInvoiceSheet->getCell('B' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $proj->getId());
  3325.                             $clientInvoiceSheet->setCellValue('C' $row$proj->getType() == 'LEAD' $project['lead'] . ' - ' $proj->getLeadStatus()->getName() : $proj->getStatus());
  3326.                             $clientInvoiceSheet->setCellValue("D" $row$projectPic ?: '-');
  3327.                             $clientInvoiceSheet->setCellValue("E" $row$clientPic);
  3328.                             $clientInvoiceSheet->setCellValue("F" $row$invoice->getInvoiceNo());
  3329.                             $clientInvoiceSheet->setCellValue("G" $row$invoice->getCustomXeroStatus());
  3330.                             $month $invoice->getDueDate()->format("m-Y");
  3331.                             if (!in_array($month$monthColumn)) {
  3332.                                 $monthColumn[] = $month;
  3333.                             }
  3334.                             $clientInvoiceSheet->setCellValue("H" $row$invoice->getDueDate()->format("Y-m-d"));
  3335.                             $clientInvoiceSheet->setCellValue("I" $row$soInvoice->getAmount());
  3336.                             $clientInvoiceSheet->setCellValue("J" $row$invoice->getCurrency()->getIso());
  3337.                             $clientInvoiceSheet->setCellValue("K" $row$soInvoice->getAmountUsd());
  3338.                             $row++;
  3339.                         }
  3340.                     }
  3341.                 }
  3342.             }
  3343.         }
  3344.         usort($monthColumn, function ($a$b) {
  3345.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  3346.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  3347.             if ($dateA == $dateB) {
  3348.                 return 0;
  3349.             }
  3350.             return ($dateA $dateB) ? -1;
  3351.         });
  3352.         $sortedMonthColumns array_map(function ($date) {
  3353.             return \DateTime::createFromFormat('d-m-Y''01-' $date)->format('M-Y');
  3354.         }, $monthColumn);
  3355.         $lastCol $clientInvoiceSheet->getHighestColumn(); // 'L'
  3356.         $key array_search($lastCol$column);
  3357.         $cellColumn = []; // breakdown month column based on cell column
  3358.         $i $key 1;
  3359.         foreach ($sortedMonthColumns as $monthColumn) {
  3360.             $cellColumn[$i] = $monthColumn;
  3361.             $clientInvoiceSheet->setCellValue($column[$i] . "5"$monthColumn);
  3362.             $i++;
  3363.         }
  3364.         $monthRow 6;
  3365.         foreach ($projectsList as $project) {
  3366.             $projectSalesOrders $project[0]->getProjectSalesOrders()->toArray();
  3367.             if ($projectSalesOrders) {
  3368.                 foreach ($projectSalesOrders as $pso) {
  3369.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
  3370.                     if ($soInvoices) {
  3371.                         foreach ($soInvoices as $soInvoice) {
  3372.                             $invoice $soInvoice->getInvoice();
  3373.                             $month $invoice->getDueDate()->format("M-Y");
  3374.                             $cell array_search($month$cellColumn);
  3375.                             $clientInvoiceSheet->setCellValue($column[$cell] . $monthRow$soInvoice->getAmountUsd());
  3376.                             $monthRow++;
  3377.                         }
  3378.                     }
  3379.                 }
  3380.             }
  3381.         }
  3382.         $clientInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
  3383.         $highestColumn $clientInvoiceSheet->getHighestColumn();
  3384.         $intHighestCol array_search($highestColumn$column);
  3385.         for ($col 11$col <= $intHighestCol$col++) {
  3386.             $clientInvoiceSheet->getColumnDimension($column[$col])->setWidth(15);
  3387.         }
  3388.         $clientInvoiceSheet->setAutoFilter('A5:' $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow());
  3389.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3390.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3391.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3392.         $clientInvoiceSheet->getStyle("B6:B" $clientInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
  3393.         // $clientInvoiceSheet->getStyle('I6:'.'I'.$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3394.         $clientInvoiceSheet->getStyle('I6:' 'I' $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3395.         // $clientInvoiceSheet->getStyle('K6:'.$clientInvoiceSheet->getHighestColumn().$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3396.         $clientInvoiceSheet->getStyle('K6:' $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3397.         $spreadsheet->setActiveSheetIndex(0);
  3398.         // Write the file
  3399.         $writer = new Xlsx($spreadsheet);
  3400.         $writer->save($filename);
  3401.         if ($_target == 'google') {
  3402.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3403.             if ($gsheetURL) {
  3404.                 unlink($filename);
  3405.                 return new RedirectResponse($gsheetURL302);
  3406.             }
  3407.         } else {
  3408.             $response = new Response();
  3409.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3410.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3411.             $response->setContent(file_get_contents($filename));
  3412.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3413.             $response->headers->set('Content-Transfer-Encoding''binary');
  3414.             $response->headers->set('Pragma''no-cache');
  3415.             $response->headers->set('Expires''0');
  3416.             unlink($filename);
  3417.             return $response;
  3418.             exit;
  3419.         }
  3420.     }
  3421.     /*
  3422.     public function exportProjectRevenueCost($isAdmin, $financialYear, $baseurl, $_target)
  3423.     {
  3424.         $start = '';
  3425.         $end = '';
  3426.         if ($financialYear) {
  3427.             $start = date('Y-m-d', strtotime('first day of November ' . ($financialYear - 1)));
  3428.             $end = date('Y-m-d', strtotime('last day of October ' . $financialYear));
  3429.         }
  3430.         $fyStart = $financialYear - 1;
  3431.         $fyEnd = $financialYear + 1;
  3432.         $overallTotals = [
  3433.             'G' => 0, // Revenue FY Start
  3434.             'H' => 0, // Revenue FY Current
  3435.             'I' => 0, // Revenue FY End
  3436.             'P' => 0, // Invoice Total w/o Tax
  3437.             'Y' => 0, // Vendor Total w/o Tax
  3438.             'AA' => 0, // Vendor Cost FY Start
  3439.             'AB' => 0, // Vendor Cost FY Current
  3440.             'AC' => 0, // Vendor Cost FY End
  3441.             'AD' => 0, // Gross Profit Total
  3442.             'AF' => 0, // Gross Profit FY Current
  3443.         ];
  3444.         $overallTotalRevenue = 0;
  3445.         $overallTotalCost = 0;
  3446.         $spreadsheet = new Spreadsheet();
  3447.         $sheet = $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  3448.         // Define Header Data
  3449.         $sheet->setCellValue('A1', 'Client');
  3450.         $sheet->setCellValue('B1', 'Project ID');
  3451.         $sheet->setCellValue('C1', 'Project Name');
  3452.         $sheet->setCellValue('D1', 'Project Status');
  3453.         $sheet->setCellValue('E1', 'Start Date');
  3454.         $sheet->setCellValue('F1', 'End Date');
  3455.         $sheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
  3456.         $sheet->setCellValue('H1', 'Revenue FY ' . $financialYear);
  3457.         $sheet->setCellValue('I1', 'Revenue FY ' . $fyEnd);
  3458.         $sheet->setCellValue('J1', 'MT INV No.');
  3459.         $sheet->setCellValue('K1', 'INV Date');
  3460.         $sheet->setCellValue('L1', 'INV Due Date');
  3461.         $sheet->setCellValue('M1', 'INV Currency');
  3462.         $sheet->setCellValue('N1', 'INV Amount (w/o Taxes)');
  3463.         $sheet->setCellValue('O1', 'SGD FX Rate');
  3464.         $sheet->setCellValue('P1', 'INV Amount (w/o Taxes in SGD)');
  3465.         $sheet->setCellValue('Q1', '');
  3466.         $sheet->setCellValue('R1', 'Vendor');
  3467.         $sheet->setCellValue('S1', 'Vendor INV No.');
  3468.         $sheet->setCellValue('T1', 'Vendor INV Date');
  3469.         $sheet->setCellValue('U1', 'Vendor INV Due Date');
  3470.         $sheet->setCellValue('V1', 'Vendor INV Currency');
  3471.         $sheet->setCellValue('W1', 'Vendor INV Amount Allocated (w/o Taxes)');
  3472.         $sheet->setCellValue('X1', 'SGD FX Rate');
  3473.         $sheet->setCellValue('Y1', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
  3474.         $sheet->setCellValue('Z1', 'Client INV No');
  3475.         $sheet->setCellValue('AA1', 'Vendor Cost ' . $fyStart);
  3476.         $sheet->setCellValue('AB1', 'Vendor Cost ' . $financialYear);
  3477.         $sheet->setCellValue('AC1', 'Vendor Cost ' . $fyEnd);
  3478.         $sheet->setCellValue('AD1', 'Gross Profit Total');
  3479.         $sheet->setCellValue('AE1', 'Gross Profit Margin Total');
  3480.         $sheet->setCellValue('AF1', 'Gross Profit FY ' . $financialYear);
  3481.         $sheet->setCellValue('AG1', 'Gross Profit Margin FY ' . $financialYear);
  3482.         // $sheet->setCellValue('AG1', 'Total Revenue');
  3483.         $sheet->getDefaultColumnDimension()->setWidth(25);
  3484.         $sheet->getColumnDimension('Q')->setWidth(3);
  3485.         $sheet->getColumnDimension('E')->setWidth(12);
  3486.         $sheet->getColumnDimension('F')->setWidth(12);
  3487.         $sheet->getColumnDimension('G')->setWidth(17);
  3488.         $sheet->getColumnDimension('H')->setWidth(17);
  3489.         $sheet->getColumnDimension('I')->setWidth(17);
  3490.         $sheet->getColumnDimension('J')->setWidth(16);
  3491.         $sheet->getColumnDimension('K')->setWidth(12);
  3492.         $sheet->getColumnDimension('L')->setWidth(12);
  3493.         $sheet->getColumnDimension('M')->setWidth(13);
  3494.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
  3495.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3496.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3497.         $sheet->getStyle("A2:" . $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
  3498.         $sheet->freezePane('A2');
  3499.         $filename = "Financial Year - Project revenue vs. Cost FY " . $financialYear;
  3500.         $filename .= date('Y-m-d') . '.xlsx';
  3501.         // $type = "LEAD;CONFIRMED";
  3502.         $type = "CONFIRMED";
  3503.         $status = "On-Going;Finished";
  3504.         $projectsList = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $start, $end, $type, 0, $status);
  3505.         $row = $sheet->getHighestRow();
  3506.         foreach ($projectsList as $project) {
  3507.             $sheet->setCellValue("A" . $row, $project['clientName']);
  3508.             $sheet->setCellValue("B" . $row, $project['generatedId']);
  3509.             $sheet->getCell("B" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
  3510.             $sheet->setCellValue("C" . $row, $project['name']);
  3511.             $sheet->getCell("C" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
  3512.             $sheet->setCellValue("D" . $row, $project['status']);
  3513.             $sheet->setCellValue("E" . $row, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  3514.             $sheet->setCellValue("F" . $row, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  3515.             $sheet->setCellValue("G" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3516.             $sheet->setCellValue("H" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3517.             $sheet->setCellValue("I" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3518.             $sheet->setCellValue("AA" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3519.             $sheet->setCellValue("AB" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3520.             $sheet->setCellValue("AC" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3521.             $sheet->setCellValue("AD" . $row, $project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd());
  3522.             $grossProfitMargin = 0;
  3523.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3524.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  3525.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  3526.                 $grossProfitMargin = ($project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd()) / $project[0]->getInvRevenueByFinancialYearSgd();
  3527.             }
  3528.             $sheet->setCellValue("AE" . $row, $grossProfitMargin);
  3529.             $sheet->setCellValue("AF" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3530.             $grossProfitMarginFinancialYear = 0;
  3531.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  3532.                 $grossProfitMarginFinancialYear = ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear)) / $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
  3533.             }
  3534.             $sheet->setCellValue("AG" . $row, $grossProfitMarginFinancialYear);
  3535.             // $sheet->setCellValue("AG".$row, $project[0]->getTotalRevenueUsd() ?: '-');
  3536.             // looping project invoice
  3537.             $invRow = $row;
  3538.             $projectSalesOrders = $project[0]->getProjectSalesOrders();
  3539.             $InvTotalwoTax = 0;
  3540.             if ($projectSalesOrders) {
  3541.                 foreach ($projectSalesOrders as $pso) {
  3542.                     $soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  3543.                     foreach ($soInvoices as $soInvoice) {
  3544.                         $invoice = $soInvoice->getInvoice();
  3545.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  3546.                         $sheet->setCellValue("J" . $invRow, $invoice->getInvoiceNo());
  3547.                         $sheet->setCellValue("K" . $invRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3548.                         $sheet->setCellValue("L" . $invRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3549.                         $sheet->setCellValue("M" . $invRow, $invoice->getCurrency()->getIso());
  3550.                         // $sheet->setCellValue("N".$invRow, $invoice->getSubTotal());
  3551.                         $InvTotalwoTax += $invoice->getSubTotalSgd($project[0]);
  3552.                         $sheet->setCellValue("N" . $invRow, $invoice->getSubTotal());
  3553.                         $sheet->setCellValue("O" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3554.                         $amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $invoice->getSubTotal() : $invoice->getSubTotalSgd($project[0]);
  3555.                         $sheet->setCellValue("P" . $invRow, $amountSGD);
  3556.                         $invRow++;
  3557.                     }
  3558.                 }
  3559.             } else {
  3560.                 $sheet->setCellValue("J" . $invRow, "-");
  3561.                 $sheet->setCellValue("K" . $invRow, "-");
  3562.                 $sheet->setCellValue("L" . $invRow, "-");
  3563.                 $sheet->setCellValue("M" . $invRow, "-");
  3564.             }
  3565.             //looping vendor invoice
  3566.             $vendorInvRow = $row;
  3567.             $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  3568.             $vendorTotalWoTax = 0;
  3569.             if ($vendorQuotationPlannings) {
  3570.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  3571.                     $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  3572.                     $vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  3573.                     foreach ($vqpInvoices as $vqpInvoice) {
  3574.                         $invoice = $vqpInvoice->getVendorInvoice();
  3575.                         if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  3576.                         $sheet->setCellValue("R" . $vendorInvRow, $vendorName);
  3577.                         $sheet->setCellValue("S" . $vendorInvRow, $invoice->getInvoiceNo());
  3578.                         $sheet->setCellValue("T" . $vendorInvRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3579.                         $sheet->setCellValue("U" . $vendorInvRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3580.                         $sheet->setCellValue("V" . $vendorInvRow, $invoice->getCurrency()->getIso());
  3581.                         // $sheet->setCellValue("W".$vendorInvRow, $vqpInvoice->getAmount());
  3582.                         $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  3583.                         $sheet->setCellValue("W" . $vendorInvRow, $vqpInvoice->getAmount());
  3584.                         $sheet->setCellValue("X" . $vendorInvRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3585.                         $vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  3586.                         $sheet->setCellValue("Y" . $vendorInvRow, $vendorAmountSGD);
  3587.                         // $clientInvoices = [];
  3588.                         // if(!empty($invoice->getInvoiceVendorInvoices()->toArray())){
  3589.                         //     foreach($invoice->getInvoiceVendorInvoices()->toArray() as $invVendorI){
  3590.                         //         $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  3591.                         //         array_push($clientInvoices, $clientInv);
  3592.                         //     }
  3593.                         // }
  3594.                         $sheet->setCellValue('Z'. $row, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  3595.                         $vendorInvRow++;
  3596.                     }
  3597.                 }
  3598.             } else {
  3599.                 $sheet->setCellValue("R" . $vendorInvRow, "-");
  3600.                 $sheet->setCellValue("S" . $vendorInvRow, "-");
  3601.                 $sheet->setCellValue("T" . $vendorInvRow, "-");
  3602.                 $sheet->setCellValue("U" . $vendorInvRow, "-");
  3603.                 $sheet->setCellValue("V" . $vendorInvRow, "-");
  3604.             }
  3605.             $totalRow = $invRow > $row || $vendorInvRow > $row ? max($invRow, $vendorInvRow) : $row + 1;
  3606.             // define total Row
  3607.             $sheet->setCellValue("A" . $totalRow, "Total");
  3608.             $sheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3609.             $sheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3610.             $sheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3611.             $sheet->setCellValue("P" . $totalRow, $InvTotalwoTax);
  3612.             $sheet->setCellValue("Y" . $totalRow, $vendorTotalWoTax);
  3613.             $sheet->setCellValue("AA" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3614.             $sheet->setCellValue("AB" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3615.             $sheet->setCellValue("AC" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3616.             $sheet->setCellValue("AD" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd());
  3617.             $sheet->setCellValue("AE" . $totalRow, $grossProfitMargin);
  3618.             $sheet->setCellValue("AF" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3619.             $sheet->setCellValue("AG" . $totalRow, $grossProfitMarginFinancialYear);
  3620.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  3621.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  3622.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3623.             $sheet->getRowDimension($totalRow)->setRowHeight(20);
  3624.             $overallTotals['G'] += $project[0]->getInvRevenueByFinancialYearSgd($fyStart);
  3625.             $overallTotals['H'] += $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
  3626.             $overallTotals['I'] += $project[0]->getInvRevenueByFinancialYearSgd($fyEnd);
  3627.             $overallTotals['P'] += $InvTotalwoTax;
  3628.             $overallTotals['Y'] += $vendorTotalWoTax;
  3629.             $overallTotals['AA'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyStart);
  3630.             $overallTotals['AB'] += $project[0]->getInvVendorCostByFinancialYearSgd($financialYear);
  3631.             $overallTotals['AC'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd);
  3632.             $overallTotals['AD'] += ($project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd());
  3633.             $overallTotals['AF'] += ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3634.             $row = $totalRow;
  3635.             $row++;
  3636.         }
  3637.         //overall total
  3638.         $row = $row+1;
  3639.         $sheet->setCellValue("A". $row, "Overall Total");
  3640.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  3641.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3642.         $sheet->getRowDimension($row)->setRowHeight(20);
  3643.         foreach ($overallTotals as $column => $value) {
  3644.             $sheet->setCellValue($column . $row, $value);
  3645.         }
  3646.         // Calculate and set overall profit margins
  3647.         $overallGrossProfitMargin = $overallTotalRevenue > 0 ? 
  3648.             ($overallTotalRevenue - $overallTotalCost) / $overallTotalRevenue : 0;
  3649.         $overallGrossProfitMarginFY = $overallTotals['H'] > 0 ? 
  3650.             ($overallTotals['H'] - $overallTotals['AB']) / $overallTotals['H'] : 0;
  3651.         $sheet->setCellValue("AE" . $row, $overallGrossProfitMargin);
  3652.         $sheet->setCellValue("AG" . $row, $overallGrossProfitMarginFY);
  3653.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  3654.         $sheet->getStyle("Q1:Q" . $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3655.         $sheet->setAutoFilter('A1:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
  3656.         $sheet->getStyle('G2:I' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  3657.         $sheet->getStyle('N2:N' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3658.         $sheet->getStyle('P2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3659.         $sheet->getStyle('W2:W' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3660.         $sheet->getStyle('Y2:Y' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3661.         $sheet->getStyle('AA2:AD' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3662.         // $sheet->getStyle('X2:X' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;(#,##0.00)');
  3663.         $sheet->getStyle('AF2:AF' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3664.         $sheet->getStyle("AE")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  3665.         $sheet->getStyle("AG")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  3666.         $sheet->getStyle("B2:B" . $sheet->getHighestRow())->getFont()->setUnderline(true);
  3667.         $sheet->getStyle("C2:C" . $sheet->getHighestRow())->getFont()->setUnderline(true);
  3668.         // Write the file
  3669.         $writer = new Xlsx($spreadsheet);
  3670.         $writer->save($filename);
  3671.         if ($_target == 'google') {
  3672.             $gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
  3673.             if ($gsheetURL) {
  3674.                 unlink($filename);
  3675.                 return new RedirectResponse($gsheetURL, 302);
  3676.             }
  3677.         } else {
  3678.             $response = new Response();
  3679.             $response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3680.             $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
  3681.             $response->setContent(file_get_contents($filename));
  3682.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3683.             $response->headers->set('Content-Transfer-Encoding', 'binary');
  3684.             $response->headers->set('Pragma', 'no-cache');
  3685.             $response->headers->set('Expires', '0');
  3686.             unlink($filename);
  3687.             return $response;
  3688.             exit;
  3689.         }
  3690.     }
  3691.     */
  3692.     public function exportProjectRevenueCost($isAdmin$financialYear$baseurl$_target)
  3693.     {
  3694.         $start '';
  3695.         $end '';
  3696.         if ($financialYear) {
  3697.             $start date('Y-m-d'strtotime('first day of November ' . ($financialYear 1)));
  3698.             $end date('Y-m-d'strtotime('last day of October ' $financialYear));
  3699.         }
  3700.         $fyStart $financialYear 1;
  3701.         $fyEnd $financialYear 1;
  3702.         $overallTotals = [];
  3703.         $overallTotalRevenue 0;
  3704.         $overallTotalCost 0;
  3705.         $spreadsheet = new Spreadsheet();
  3706.         $sheet $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  3707.         // Define Header Data
  3708.         $sheet->setCellValue('A1''Client');
  3709.         $sheet->setCellValue('B1''Project ID');
  3710.         $sheet->setCellValue('C1''Project Name');
  3711.         $sheet->setCellValue('D1''Project Status');
  3712.         $sheet->setCellValue('E1''Start Date');
  3713.         $sheet->setCellValue('F1''End Date');
  3714.         $sheet->setCellValue('G1''Revenue FY ' $fyStart);
  3715.         $sheet->setCellValue('H1''Revenue FY ' $fyStart ' Amount Allocated');
  3716.         $sheet->setCellValue('I1''Revenue FY ' $financialYear);
  3717.         $sheet->setCellValue('J1''Revenue FY ' $financialYear ' Amount Allocated');
  3718.         $sheet->setCellValue('K1''Revenue FY ' $fyEnd);
  3719.         $sheet->setCellValue('L1''Revenue FY ' $fyEnd ' Amount Allocated');
  3720.         $sheet->setCellValue('M1''MT INV No.');
  3721.         $sheet->setCellValue('N1''INV Date');
  3722.         $sheet->setCellValue('O1''INV Due Date');
  3723.         $sheet->setCellValue('P1''INV Currency');
  3724.         $sheet->setCellValue('Q1''INV Amount (w/o Taxes)');
  3725.         $sheet->setCellValue('R1''INV Amount Allocated (w/o Taxes)');
  3726.         $sheet->setCellValue('S1''SGD FX Rate');
  3727.         $sheet->setCellValue('T1''INV Amount (w/o Taxes in SGD)');
  3728.         $sheet->setCellValue('U1''INV Amount Allocated (w/o Taxes in SGD)');
  3729.         $sheet->setCellValue('V1''');
  3730.         $sheet->setCellValue('W1''Vendor');
  3731.         $sheet->setCellValue('X1''Vendor INV No.');
  3732.         $sheet->setCellValue('Y1''Vendor INV Date');
  3733.         $sheet->setCellValue('Z1''Vendor INV Due Date');
  3734.         $sheet->setCellValue('AA1''Vendor INV Currency');
  3735.         $sheet->setCellValue('AB1''Vendor INV Amount (w/o Taxes)');
  3736.         $sheet->setCellValue('AC1''Vendor INV Amount Allocated (w/o Taxes)');
  3737.         $sheet->setCellValue('AD1''SGD FX Rate');
  3738.         $sheet->setCellValue('AE1''Vendor INV Amount (w/o Taxes in SGD)');
  3739.         $sheet->setCellValue('AF1''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  3740.         $sheet->setCellValue('AG1''Client INV No');
  3741.         $sheet->setCellValue('AH1''Vendor Cost ' $fyStart);
  3742.         $sheet->setCellValue('AI1''Vendor Cost ' $fyStart ' Amount Allocated');
  3743.         $sheet->setCellValue('AJ1''Vendor Cost ' $financialYear);
  3744.         $sheet->setCellValue('AK1''Vendor Cost ' $financialYear ' Amount Allocated');
  3745.         $sheet->setCellValue('AL1''Vendor Cost ' $fyEnd);
  3746.         $sheet->setCellValue('AM1''Vendor Cost ' $fyEnd ' Amount Allocated');
  3747.         $sheet->setCellValue('AN1''Gross Profit Total');
  3748.         $sheet->setCellValue('AO1''Gross Profit Total Amount Allocated');
  3749.         $sheet->setCellValue('AP1''Gross Profit Margin Total');
  3750.         $sheet->setCellValue('AQ1''Gross Profit Margin Total Amount Allocated');
  3751.         $sheet->setCellValue('AR1''Gross Profit FY ' $financialYear);
  3752.         $sheet->setCellValue('AS1''Gross Profit FY ' $financialYear ' Amount Allocated');
  3753.         $sheet->setCellValue('AT1''Gross Profit Margin FY ' $financialYear);
  3754.         $sheet->setCellValue('AU1''Gross Profit Margin FY ' $financialYear ' Amount Allocated');
  3755.         // $sheet->setCellValue('AG1', 'Total Revenue');
  3756.         $sheet->getDefaultColumnDimension()->setWidth(25);
  3757.         $sheet->getColumnDimension('V')->setWidth(3);
  3758.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
  3759.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3760.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3761.         $sheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3762.         $sheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3763.         $sheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3764.         $sheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3765.         $sheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3766.         $sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3767.         $sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3768.         $sheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3769.         $sheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3770.         $sheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3771.         $sheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3772.         $sheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3773.         $sheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3774.         $sheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3775.         $sheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3776.         $sheet->getStyle("A2:" $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
  3777.         $sheet->freezePane('A2');
  3778.         $filename "Financial Year - Project revenue vs. Cost FY " $financialYear;
  3779.         $filename .= date('Y-m-d') . '.xlsx';
  3780.         // $type = "LEAD;CONFIRMED";
  3781.         $type "CONFIRMED";
  3782.         $status "On-Going;Finished";
  3783.         $projectsList $this->projectRepository->findByPage(09999"""ASC"'client'$start$end$type0$status);
  3784.         $row $sheet->getHighestRow();
  3785.         foreach ($projectsList as $project) {
  3786.             $sheet->setCellValue("A" $row$project['clientName']);
  3787.             $sheet->setCellValue("B" $row$project['generatedId']);
  3788.             $sheet->getCell("B" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3789.             $sheet->getStyle('B' $row)->getFont()->setUnderline(true);
  3790.             $sheet->setCellValue("C" $row$project['name']);
  3791.             $sheet->getCell("C" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3792.             $sheet->getStyle('C' $row)->getFont()->setUnderline(true);
  3793.             $sheet->setCellValue("D" $row$project['status']);
  3794.             $sheet->setCellValue("E" $row$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  3795.             $sheet->setCellValue("F" $row$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  3796.             $sheet->setCellValue("G" $row$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3797.             $sheet->setCellValue("H" $row$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  3798.             $sheet->setCellValue("I" $row$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3799.             $sheet->setCellValue("J" $row$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  3800.             $sheet->setCellValue("K" $row$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3801.             $sheet->setCellValue("L" $row$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  3802.             $sheet->setCellValue("AH" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3803.             $sheet->setCellValue("AI" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyStarttrue));
  3804.             $sheet->setCellValue("AJ" $row$project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3805.             $sheet->setCellValue("AK" $row$project[0]->getInvVendorCostByFinancialYearSgd($financialYeartrue));
  3806.             $sheet->setCellValue("AL" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3807.             $sheet->setCellValue("AM" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyEndtrue));
  3808.             
  3809.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3810.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  3811.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  3812.             }
  3813.             // looping project invoice
  3814.             $invRow $row;
  3815.             $projectSalesOrders $project[0]->getProjectSalesOrders();
  3816.             $InvTotalwoTax 0;
  3817.             if ($projectSalesOrders) {
  3818.                 foreach ($projectSalesOrders as $pso) {
  3819.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  3820.                     foreach ($soInvoices as $soInvoice) {
  3821.                         $invoice $soInvoice->getInvoice();
  3822.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  3823.                         $sheet->setCellValue("M" $invRow$invoice->getInvoiceNo());
  3824.                         $sheet->setCellValue("N" $invRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3825.                         $sheet->setCellValue("O" $invRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3826.                         $sheet->setCellValue("P" $invRow$invoice->getCurrency()->getIso());
  3827.                         $InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
  3828.                         $sheet->setCellValue("Q" $invRow$invoice->getSubTotal());
  3829.                         $sheet->setCellValue("R" $invRow$soInvoice->getAmount());
  3830.                         $sheet->setCellValue("S" $invRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3831.                         $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  3832.                         $sheet->setCellValue("T" $invRow$invoice->getSubTotalSgd($project[0]));
  3833.                         $sheet->setCellValue("U" $invRow$amountSGD);
  3834.                         $invRow++;
  3835.                     }
  3836.                 }
  3837.             } else {
  3838.                 $sheet->setCellValue("M" $invRow"-");
  3839.                 $sheet->setCellValue("N" $invRow"-");
  3840.                 $sheet->setCellValue("O" $invRow"-");
  3841.                 $sheet->setCellValue("P" $invRow"-");
  3842.                 $sheet->setCellValue("Q" $invRow"-");
  3843.                 $sheet->setCellValue("R" $invRow"-");
  3844.                 $sheet->setCellValue("S" $invRow"-");
  3845.                 $sheet->setCellValue("T" $invRow"-");
  3846.                 $sheet->setCellValue("U" $invRow"-");
  3847.             }
  3848.             //looping vendor invoice
  3849.             $vendorInvRow $row;
  3850.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  3851.             $vendorTotalWoTax 0;
  3852.             if ($vendorQuotationPlannings) {
  3853.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  3854.                     $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  3855.                     $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  3856.                     foreach ($vqpInvoices as $vqpInvoice) {
  3857.                         $invoice $vqpInvoice->getVendorInvoice();
  3858.                         // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  3859.                         $sheet->setCellValue("W" $vendorInvRow$vendorName);
  3860.                         $sheet->setCellValue("X" $vendorInvRow$invoice->getInvoiceNo());
  3861.                         $sheet->setCellValue("Y" $vendorInvRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3862.                         $sheet->setCellValue("Z" $vendorInvRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3863.                         $sheet->setCellValue("AA" $vendorInvRow$invoice->getCurrency()->getIso());
  3864.                         $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  3865.                         $sheet->setCellValue("AB" $vendorInvRow$invoice->getSubtotal());
  3866.                         $sheet->setCellValue("AC" $vendorInvRow$vqpInvoice->getAmount());
  3867.                         $sheet->setCellValue("AD" $vendorInvRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3868.                         $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  3869.                         $sheet->setCellValue("AE" $vendorInvRow$invoice->getSubTotalSgd($project[0]));
  3870.                         $sheet->setCellValue("AF" $vendorInvRow$vendorAmountSGD);
  3871.                         $sheet->setCellValue('AG'$vendorInvRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  3872.                         $vendorInvRow++;
  3873.                     }
  3874.                 }
  3875.             } else {
  3876.                 $sheet->setCellValue("W" $vendorInvRow"-");
  3877.                 $sheet->setCellValue("X" $vendorInvRow"-");
  3878.                 $sheet->setCellValue("Y" $vendorInvRow"-");
  3879.                 $sheet->setCellValue("Z" $vendorInvRow"-");
  3880.                 $sheet->setCellValue("AA" $vendorInvRow"-");
  3881.             }
  3882.             $totalRow $invRow $row || $vendorInvRow $row max($invRow$vendorInvRow) : $row 1;
  3883.             $sheet->setCellValue("A" $totalRow"Total");
  3884.             $sheet->setCellValue("G" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3885.             $sheet->setCellValue("H" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  3886.             $sheet->setCellValue("I" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3887.             $sheet->setCellValue("J" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  3888.             $sheet->setCellValue("K" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3889.             $sheet->setCellValue("L" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  3890.             $sheet->setCellValue("T" $totalRow'=SUM(T'.$row.':T'.($invRow $row $invRow $row).')');
  3891.             $sheet->setCellValue("U" $totalRow'=SUM(U'.$row.':U'.($invRow $row $invRow $row).')');
  3892.             $sheet->setCellValue("AE" $totalRow'=SUM(AE'.$row.':AE'.($vendorInvRow $row $vendorInvRow $row).')');
  3893.             $sheet->setCellValue("AF" $totalRow'=SUM(AF'.$row.':AF'.($vendorInvRow $row $vendorInvRow $row).')');
  3894.             $sheet->setCellValue("AH" $totalRow"=AH" $row);
  3895.             $sheet->setCellValue("AI" $totalRow"=AI" $row);
  3896.             $sheet->setCellValue("AJ" $totalRow"=AJ" $row);
  3897.             $sheet->setCellValue("AK" $totalRow"=AK" $row);
  3898.             $sheet->setCellValue("AL" $totalRow"=AL" $row);
  3899.             $sheet->setCellValue("AM" $totalRow"=AM" $row);
  3900.             $sheet->setCellValue("AN" $totalRow'=T'.$totalRow.'-AE'.$totalRow);
  3901.             $sheet->setCellValue("AN" $row'=T'.$totalRow.'-AE'.$totalRow);
  3902.             $sheet->setCellValue("AO" $totalRow'=U'.$totalRow.'-AF'.$totalRow);
  3903.             $sheet->setCellValue("AO" $row'=U'.$totalRow.'-AF'.$totalRow);
  3904.             $grossProfitMargin 0;
  3905.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3906.                 $grossProfitMargin '=(T'.$totalRow'-AE'.$totalRow.')/T'.$totalRow;
  3907.                 $sheet->setCellValue("AP" $totalRow$grossProfitMargin);
  3908.                 $sheet->setCellValue("AP" $row$grossProfitMargin);
  3909.             }else{
  3910.                 $sheet->setCellValue("AP" $totalRow$grossProfitMargin);
  3911.                 $sheet->setCellValue("AP" $row$grossProfitMargin);
  3912.             }
  3913.             $grossProfitMarginAllocated 0;
  3914.             if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  3915.                 $grossProfitMarginAllocated '=(U'.$totalRow'-AF'.$totalRow.')/U'.$totalRow;
  3916.                 $sheet->setCellValue("AQ" $totalRow$grossProfitMarginAllocated);
  3917.                 $sheet->setCellValue("AQ" $row$grossProfitMarginAllocated);
  3918.             }else{
  3919.                 $sheet->setCellValue("AQ" $totalRow$grossProfitMarginAllocated);
  3920.                 $sheet->setCellValue("AQ" $row$grossProfitMarginAllocated);
  3921.             }
  3922.             $sheet->setCellValue("AR" $totalRow'=I'.$totalRow.'-AJ'.$totalRow);
  3923.             $sheet->setCellValue("AR" $row'=I'.$totalRow.'-AJ'.$totalRow);
  3924.             $sheet->setCellValue("AS" $totalRow'=J'.$totalRow.'-AK'.$totalRow);
  3925.             $sheet->setCellValue("AS" $row'=J'.$totalRow.'-AK'.$totalRow);
  3926.             $grossProfitMarginFinancialYear 0;
  3927.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  3928.                 $grossProfitMarginFinancialYear '=(I'.$totalRow'-AJ'.$totalRow.')/I'.$totalRow;
  3929.                 $sheet->setCellValue("AT" $totalRow$grossProfitMarginFinancialYear);
  3930.                 $sheet->setCellValue("AT" $row$grossProfitMarginFinancialYear);
  3931.             }else{
  3932.                 $sheet->setCellValue("AT" $totalRow$grossProfitMarginFinancialYear);
  3933.                 $sheet->setCellValue("AT" $row$grossProfitMarginFinancialYear);
  3934.             }
  3935.             $grossProfitMarginFinancialYearAllocated 0;
  3936.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue) > 0) {
  3937.                 $grossProfitMarginFinancialYearAllocated '=(J'.$totalRow'-AK'.$totalRow.')/J'.$totalRow;
  3938.                 $sheet->setCellValue("AU" $totalRow$grossProfitMarginFinancialYearAllocated);
  3939.                 $sheet->setCellValue("AU" $row$grossProfitMarginFinancialYearAllocated);
  3940.             }else{
  3941.                 $sheet->setCellValue("AU" $totalRow$grossProfitMarginFinancialYearAllocated);
  3942.                 $sheet->setCellValue("AU" $row$grossProfitMarginFinancialYearAllocated);
  3943.             }
  3944.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  3945.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  3946.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3947.             $sheet->getRowDimension($totalRow)->setRowHeight(20);
  3948.             $overallTotals['G'][] = 'G'.$totalRow;
  3949.             $overallTotals['H'][] = 'H'.$totalRow;
  3950.             $overallTotals['I'][] = 'I'.$totalRow;
  3951.             $overallTotals['J'][] = 'J'.$totalRow;
  3952.             $overallTotals['K'][] = 'K'.$totalRow;
  3953.             $overallTotals['L'][] = 'L'.$totalRow;
  3954.             $overallTotals['T'][] = 'T'.$totalRow;
  3955.             $overallTotals['U'][] = 'U'.$totalRow;
  3956.             $overallTotals['AE'][] = 'AE'.$totalRow;
  3957.             $overallTotals['AF'][] = 'AF'.$totalRow;
  3958.             $overallTotals['AH'][] = 'AH'.$totalRow;
  3959.             $overallTotals['AI'][] = 'AI'.$totalRow;
  3960.             $overallTotals['AJ'][] = 'AJ'.$totalRow;
  3961.             $overallTotals['AK'][] = 'AK'.$totalRow;
  3962.             $overallTotals['AL'][] = 'AL'.$totalRow;
  3963.             $overallTotals['AM'][] = 'AM'.$totalRow;
  3964.             $row $totalRow;
  3965.             $row++;
  3966.         }
  3967.         //overall total
  3968.         $row $row+1;
  3969.         $sheet->setCellValue("A"$row"Overall Total");
  3970.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  3971.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3972.         $sheet->getRowDimension($row)->setRowHeight(20);
  3973.         $sheet->setCellValue("G" $row'='.implode('+'$overallTotals['G']));
  3974.         $sheet->setCellValue("H" $row'='.implode('+'$overallTotals['H']));
  3975.         $sheet->setCellValue("I" $row'='.implode('+'$overallTotals['I']));
  3976.         $sheet->setCellValue("J" $row'='.implode('+'$overallTotals['J']));
  3977.         $sheet->setCellValue("K" $row'='.implode('+'$overallTotals['K']));
  3978.         $sheet->setCellValue("L" $row'='.implode('+'$overallTotals['L']));
  3979.         $sheet->setCellValue("T" $row'='.implode('+'$overallTotals['T']));
  3980.         $sheet->setCellValue("U" $row'='.implode('+'$overallTotals['U']));
  3981.         $sheet->setCellValue("AE" $row'='.implode('+'$overallTotals['AE']));
  3982.         $sheet->setCellValue("AF" $row'='.implode('+'$overallTotals['AF']));
  3983.         $sheet->setCellValue("AH" $row'='.implode('+'$overallTotals['AH']));
  3984.         $sheet->setCellValue("AI" $row'='.implode('+'$overallTotals['AI']));
  3985.         $sheet->setCellValue("AJ" $row'='.implode('+'$overallTotals['AJ']));
  3986.         $sheet->setCellValue("AK" $row'='.implode('+'$overallTotals['AK']));
  3987.         $sheet->setCellValue("AL" $row'='.implode('+'$overallTotals['AL']));
  3988.         $sheet->setCellValue("AM" $row'='.implode('+'$overallTotals['AM']));
  3989.         $sheet->setCellValue("AN" $row'=T'.$row.'-AE'.$row);
  3990.         $sheet->setCellValue("AO" $row'=U'.$row.'-AF'.$row);
  3991.         $sheet->setCellValue("AR" $row'=I'.$row.'-AJ'.$row);
  3992.         $sheet->setCellValue("AS" $row'=J'.$row.'-AK'.$row);
  3993.         $sheet->setCellValue("AP" $row,'=IF(T'.$row.'=0, "",(T'.$row'-AE'.$row.')/T'.$row.')');
  3994.         $sheet->setCellValue("AQ" $row,'=IF(U'.$row.'=0, "",(U'.$row'-AF'.$row.')/U'.$row.')');
  3995.         $sheet->setCellValue("AT" $row,'=IF(I'.$row.'=0, "",(I'.$row'-AJ'.$row.')/I'.$row.')');
  3996.         $sheet->setCellValue("AU" $row,'=IF(J'.$row.'=0, "",(J'.$row'-AK'.$row.')/J'.$row.')');
  3997.         
  3998.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  3999.         $sheet->getStyle("V1:V" $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4000.         $sheet->setAutoFilter('A1:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  4001.         $sheet->getStyle('G2:L' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4002.         $sheet->getStyle('Q2:R' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4003.         $sheet->getStyle('T2:U' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4004.         $sheet->getStyle('AB2:AC' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4005.         $sheet->getStyle('AE2:AF' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4006.         $sheet->getStyle('AH2:AO' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4007.         $sheet->getStyle('AN2:AO' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4008.         $sheet->getStyle('AR2:AS' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4009.         $sheet->getStyle("AP2:AQ"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4010.         $sheet->getStyle("AT2:AU"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4011.         $summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Summary Total');
  4012.         $spreadsheet->addSheet($summarySheet1);
  4013.         $summarySheet->setCellValue('A1''Client');
  4014.         $summarySheet->setCellValue('B1''Project ID');
  4015.         $summarySheet->setCellValue('C1''Project Name');
  4016.         $summarySheet->setCellValue('D1''Project Status');
  4017.         $summarySheet->setCellValue('E1''Start Date');
  4018.         $summarySheet->setCellValue('F1''End Date');
  4019.         $summarySheet->setCellValue('G1''Revenue FY ' $fyStart);
  4020.         $summarySheet->setCellValue('H1''Revenue FY ' $fyStart ' Amount Allocated');
  4021.         $summarySheet->setCellValue('I1''Revenue FY ' $financialYear);
  4022.         $summarySheet->setCellValue('J1''Revenue FY ' $financialYear ' Amount Allocated');
  4023.         $summarySheet->setCellValue('K1''Revenue FY ' $fyEnd);
  4024.         $summarySheet->setCellValue('L1''Revenue FY ' $fyEnd ' Amount Allocated');
  4025.         $summarySheet->setCellValue('M1''MT INV No.');
  4026.         $summarySheet->setCellValue('N1''INV Date');
  4027.         $summarySheet->setCellValue('O1''INV Due Date');
  4028.         $summarySheet->setCellValue('P1''INV Currency');
  4029.         $summarySheet->setCellValue('Q1''INV Amount (w/o Taxes)');
  4030.         $summarySheet->setCellValue('R1''INV Amount Allocated (w/o Taxes)');
  4031.         $summarySheet->setCellValue('S1''SGD FX Rate');
  4032.         $summarySheet->setCellValue('T1''INV Amount (w/o Taxes in SGD)');
  4033.         $summarySheet->setCellValue('U1''INV Amount Allocated (w/o Taxes in SGD)');
  4034.         $summarySheet->setCellValue('V1''');
  4035.         $summarySheet->setCellValue('W1''Vendor');
  4036.         $summarySheet->setCellValue('X1''Vendor INV No.');
  4037.         $summarySheet->setCellValue('Y1''Vendor INV Date');
  4038.         $summarySheet->setCellValue('Z1''Vendor INV Due Date');
  4039.         $summarySheet->setCellValue('AA1''Vendor INV Currency');
  4040.         $summarySheet->setCellValue('AB1''Vendor INV Amount (w/o Taxes)');
  4041.         $summarySheet->setCellValue('AC1''Vendor INV Amount Allocated (w/o Taxes)');
  4042.         $summarySheet->setCellValue('AD1''SGD FX Rate');
  4043.         $summarySheet->setCellValue('AE1''Vendor INV Amount (w/o Taxes in SGD)');
  4044.         $summarySheet->setCellValue('AF1''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4045.         $summarySheet->setCellValue('AG1''Client INV No');
  4046.         $summarySheet->setCellValue('AH1''Vendor Cost ' $fyStart);
  4047.         $summarySheet->setCellValue('AI1''Vendor Cost ' $fyStart ' Amount Allocated');
  4048.         $summarySheet->setCellValue('AJ1''Vendor Cost ' $financialYear);
  4049.         $summarySheet->setCellValue('AK1''Vendor Cost ' $financialYear ' Amount Allocated');
  4050.         $summarySheet->setCellValue('AL1''Vendor Cost ' $fyEnd);
  4051.         $summarySheet->setCellValue('AM1''Vendor Cost ' $fyEnd ' Amount Allocated');
  4052.         $summarySheet->setCellValue('AN1''Gross Profit Total');
  4053.         $summarySheet->setCellValue('AO1''Gross Profit Total Amount Allocated');
  4054.         $summarySheet->setCellValue('AP1''Gross Profit Margin Total');
  4055.         $summarySheet->setCellValue('AQ1''Gross Profit Margin Total Amount Allocated');
  4056.         $summarySheet->setCellValue('AR1''Gross Profit FY ' $financialYear);
  4057.         $summarySheet->setCellValue('AS1''Gross Profit FY ' $financialYear ' Amount Allocated');
  4058.         $summarySheet->setCellValue('AT1''Gross Profit Margin FY ' $financialYear);
  4059.         $summarySheet->setCellValue('AU1''Gross Profit Margin FY ' $financialYear ' Amount Allocated');
  4060.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4061.         $summarySheet->getDefaultColumnDimension()->setWidth(25);
  4062.         $summarySheet->getColumnDimension('V')->setWidth(3);
  4063.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFont()->setBold(true);
  4064.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4065.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4066.         $summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4067.         $summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4068.         $summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4069.         $summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4070.         $summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4071.         $summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4072.         $summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4073.         $summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4074.         $summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4075.         $summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4076.         $summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4077.         $summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4078.         $summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4079.         $summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4080.         $summarySheet->getStyle("A2:" $summarySheet->getHighestColumn() . "2")->getFont()->setBold(false);
  4081.         $summarySheet->freezePane('A2');
  4082.         // $type = "LEAD;CONFIRMED";
  4083.         $type "CONFIRMED";
  4084.         $status "On-Going;Finished";
  4085.         $projectsListSummary $this->projectRepository->findByPage(09999"""ASC"'client'$start$end$type0$status);
  4086.         
  4087.         $sumOverallTotals = [];
  4088.         $sumRow $summarySheet->getHighestRow();
  4089.         foreach ($projectsListSummary as $project) {
  4090.             $summarySheet->setCellValue("A" $sumRow$project['clientName']);
  4091.             $summarySheet->setCellValue("B" $sumRow$project['generatedId']);
  4092.             $summarySheet->getCell("B" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4093.             $summarySheet->getStyle('B' $sumRow)->getFont()->setUnderline(true);
  4094.             $summarySheet->setCellValue("C" $sumRow$project['name']);
  4095.             $summarySheet->getCell("C" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4096.             $summarySheet->getStyle('C' $sumRow)->getFont()->setUnderline(true);
  4097.             $summarySheet->setCellValue("D" $sumRow$project['status']);
  4098.             $summarySheet->setCellValue("E" $sumRow$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4099.             $summarySheet->setCellValue("F" $sumRow$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4100.             $summarySheet->setCellValue("G" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4101.             $summarySheet->setCellValue("H" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  4102.             $summarySheet->setCellValue("I" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4103.             $summarySheet->setCellValue("J" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  4104.             $summarySheet->setCellValue("K" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4105.             $summarySheet->setCellValue("L" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  4106.             $summarySheet->setCellValue("AH" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  4107.             $summarySheet->setCellValue("AI" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyStarttrue));
  4108.             $summarySheet->setCellValue("AJ" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  4109.             $summarySheet->setCellValue("AK" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($financialYeartrue));
  4110.             $summarySheet->setCellValue("AL" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  4111.             $summarySheet->setCellValue("AM" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyEndtrue));
  4112.             $projectSalesOrders $project[0]->getProjectSalesOrders();
  4113.             $invData = [
  4114.                 'totalAmount' => 0,
  4115.                 'totalAmountSGD' => 0,
  4116.                 'totalAmountAllocated' => 0,
  4117.                 'totalAmountAllocatedSGD' => 0,
  4118.             ];
  4119.             if ($projectSalesOrders) {
  4120.                 foreach ($projectSalesOrders as $pso) {
  4121.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4122.                     foreach ($soInvoices as $soInvoice) {
  4123.                         $invoice $soInvoice->getInvoice();
  4124.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4125.                         $summarySheet->setCellValue("P" $sumRow$invoice->getCurrency()->getIso());
  4126.                         $invData['totalAmount'] += $invoice->getSubTotal();
  4127.                         $invData['totalAmountAllocated'] += $soInvoice->getAmount();
  4128.                         $invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4129.                         $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4130.                         $invData['totalAmountAllocatedSGD'] += $amountSGD;
  4131.                         $summarySheet->setCellValue("Q" $sumRow$invData['totalAmount']);
  4132.                         $summarySheet->setCellValue("R" $sumRow$invData['totalAmountAllocated']);
  4133.                         // $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4134.                         
  4135.                         $summarySheet->setCellValue("T" $sumRow$invData['totalAmountSGD']);
  4136.                         $summarySheet->setCellValue("U" $sumRow$invData['totalAmountAllocatedSGD']);
  4137.                     }
  4138.                 }
  4139.             } else {
  4140.                 $summarySheet->setCellValue("M" $sumRow"-");
  4141.                 $summarySheet->setCellValue("N" $sumRow"-");
  4142.                 $summarySheet->setCellValue("O" $sumRow"-");
  4143.                 $summarySheet->setCellValue("P" $sumRow"-");
  4144.                 $summarySheet->setCellValue("Q" $sumRow"-");
  4145.                 $summarySheet->setCellValue("R" $sumRow"-");
  4146.                 $summarySheet->setCellValue("S" $sumRow"-");
  4147.                 $summarySheet->setCellValue("T" $sumRow"-");
  4148.                 $summarySheet->setCellValue("U" $sumRow"-");
  4149.             }
  4150.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4151.             $vendorData = [
  4152.                 'totalAmount' => 0,
  4153.                 'totalAmountAllocated' => 0,
  4154.                 'totalAmountSGD' => 0,
  4155.                 'totalAmountAllocatedSGD' => 0,
  4156.             ];
  4157.             if ($vendorQuotationPlannings) {
  4158.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4159.                     $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4160.                     $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4161.                     foreach ($vqpInvoices as $vqpInvoice) {
  4162.                         $invoice $vqpInvoice->getVendorInvoice();
  4163.                         // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4164.                         // $summarySheet->setCellValue("W" . $sumRow, $vendorName);
  4165.                         // $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
  4166.                         // $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4167.                         // $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4168.                         $summarySheet->setCellValue("AA" $sumRow$invoice->getCurrency()->getIso());
  4169.                         $vendorData['totalAmount'] += $invoice->getSubTotal();
  4170.                         $vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
  4171.                         $summarySheet->setCellValue("AB" $sumRow$vendorData['totalAmount']);
  4172.                         $summarySheet->setCellValue("AC" $sumRow$vendorData['totalAmountAllocated']);
  4173.                         // $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4174.                         $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4175.                         $vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4176.                         $vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
  4177.                         $summarySheet->setCellValue("AE" $sumRow$vendorData['totalAmountSGD']);
  4178.                         $summarySheet->setCellValue("AF" $sumRow$vendorData['totalAmountAllocatedSGD']);
  4179.                         $summarySheet->setCellValue('AG'$sumRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4180.                     }
  4181.                 }
  4182.             } else {
  4183.                 $summarySheet->setCellValue("W" $sumRow"-");
  4184.                 $summarySheet->setCellValue("X" $sumRow"-");
  4185.                 $summarySheet->setCellValue("Y" $sumRow"-");
  4186.                 $summarySheet->setCellValue("Z" $sumRow"-");
  4187.                 $summarySheet->setCellValue("AA" $sumRow"-");
  4188.             }
  4189.             
  4190.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4191.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4192.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4193.             }
  4194.             // $summarySheet->setCellValue("A" . $totalRow, "Total");
  4195.             // $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4196.             // $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4197.             // $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4198.             // $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4199.             // $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4200.             // $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4201.             // $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4202.             // $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4203.             // $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4204.             // $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4205.             // $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
  4206.             // $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
  4207.             // $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
  4208.             // $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
  4209.             // $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
  4210.             // $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
  4211.             $summarySheet->setCellValue("AN" $sumRow'=T'.$sumRow.'-AE'.$sumRow);
  4212.             $summarySheet->setCellValue("AO" $sumRow'=U'.$sumRow.'-AF'.$sumRow);
  4213.             $grossProfitMargin 0;
  4214.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4215.                 $grossProfitMargin '=(T'.$sumRow'-AE'.$sumRow.')/T'.$sumRow;
  4216.                 $summarySheet->setCellValue("AP" $sumRow$grossProfitMargin);
  4217.             }else{
  4218.                 $summarySheet->setCellValue("AP" $sumRow$grossProfitMargin);
  4219.             }
  4220.             $grossProfitMarginAllocated 0;
  4221.             if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  4222.                 $grossProfitMarginAllocated '=(U'.$sumRow'-AF'.$sumRow.')/U'.$sumRow;
  4223.                 $summarySheet->setCellValue("AQ" $sumRow$grossProfitMarginAllocated);
  4224.             }else{
  4225.                 $summarySheet->setCellValue("AQ" $sumRow$grossProfitMarginAllocated);
  4226.             }
  4227.             $summarySheet->setCellValue("AR" $sumRow'=I'.$sumRow.'-AJ'.$sumRow);
  4228.             $summarySheet->setCellValue("AS" $sumRow'=J'.$sumRow.'-AK'.$sumRow);
  4229.             $grossProfitMarginFinancialYear 0;
  4230.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  4231.                 $grossProfitMarginFinancialYear '=(I'.$sumRow'-AJ'.$sumRow.')/I'.$sumRow;
  4232.                 $summarySheet->setCellValue("AT" $sumRow$grossProfitMarginFinancialYear);
  4233.             }else{
  4234.                 $summarySheet->setCellValue("AT" $sumRow$grossProfitMarginFinancialYear);
  4235.             }
  4236.             $grossProfitMarginFinancialYearAllocated 0;
  4237.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue) > 0) {
  4238.                 $grossProfitMarginFinancialYearAllocated '=(J'.$sumRow'-AK'.$sumRow.')/J'.$sumRow;
  4239.                 $summarySheet->setCellValue("AU" $sumRow$grossProfitMarginFinancialYearAllocated);
  4240.             }else{
  4241.                 $summarySheet->setCellValue("AU" $sumRow$grossProfitMarginFinancialYearAllocated);
  4242.             }
  4243.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
  4244.             // $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4245.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4246.             $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  4247.             $sumOverallTotals['G'][] = 'G'.$sumRow;
  4248.             $sumOverallTotals['H'][] = 'H'.$sumRow;
  4249.             $sumOverallTotals['I'][] = 'I'.$sumRow;
  4250.             $sumOverallTotals['J'][] = 'J'.$sumRow;
  4251.             $sumOverallTotals['K'][] = 'K'.$sumRow;
  4252.             $sumOverallTotals['L'][] = 'L'.$sumRow;
  4253.             $sumOverallTotals['T'][] = 'T'.$sumRow;
  4254.             $sumOverallTotals['U'][] = 'U'.$sumRow;
  4255.             $sumOverallTotals['AE'][] = 'AE'.$sumRow;
  4256.             $sumOverallTotals['AF'][] = 'AF'.$sumRow;
  4257.             $sumOverallTotals['AH'][] = 'AH'.$sumRow;
  4258.             $sumOverallTotals['AI'][] = 'AI'.$sumRow;
  4259.             $sumOverallTotals['AJ'][] = 'AJ'.$sumRow;
  4260.             $sumOverallTotals['AK'][] = 'AK'.$sumRow;
  4261.             $sumOverallTotals['AL'][] = 'AL'.$sumRow;
  4262.             $sumOverallTotals['AM'][] = 'AM'.$sumRow;
  4263.             $sumRow++;
  4264.         }
  4265.         $sumRow $sumRow+1;
  4266.         $summarySheet->setCellValue("A"$sumRow"Overall Total");
  4267.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  4268.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4269.         $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  4270.         $summarySheet->setCellValue("G" $sumRow'='.implode('+'$sumOverallTotals['G']));
  4271.         $summarySheet->setCellValue("H" $sumRow'='.implode('+'$sumOverallTotals['H']));
  4272.         $summarySheet->setCellValue("I" $sumRow'='.implode('+'$sumOverallTotals['I']));
  4273.         $summarySheet->setCellValue("J" $sumRow'='.implode('+'$sumOverallTotals['J']));
  4274.         $summarySheet->setCellValue("K" $sumRow'='.implode('+'$sumOverallTotals['K']));
  4275.         $summarySheet->setCellValue("L" $sumRow'='.implode('+'$sumOverallTotals['L']));
  4276.         $summarySheet->setCellValue("T" $sumRow'='.implode('+'$sumOverallTotals['T']));
  4277.         $summarySheet->setCellValue("U" $sumRow'='.implode('+'$sumOverallTotals['U']));
  4278.         $summarySheet->setCellValue("AE" $sumRow'='.implode('+'$sumOverallTotals['AE']));
  4279.         $summarySheet->setCellValue("AF" $sumRow'='.implode('+'$sumOverallTotals['AF']));
  4280.         $summarySheet->setCellValue("AH" $sumRow'='.implode('+'$sumOverallTotals['AH']));
  4281.         $summarySheet->setCellValue("AI" $sumRow'='.implode('+'$sumOverallTotals['AI']));
  4282.         $summarySheet->setCellValue("AJ" $sumRow'='.implode('+'$sumOverallTotals['AJ']));
  4283.         $summarySheet->setCellValue("AK" $sumRow'='.implode('+'$sumOverallTotals['AK']));
  4284.         $summarySheet->setCellValue("AL" $sumRow'='.implode('+'$sumOverallTotals['AL']));
  4285.         $summarySheet->setCellValue("AM" $sumRow'='.implode('+'$sumOverallTotals['AM']));
  4286.         $summarySheet->setCellValue("AN" $sumRow'=T'.$sumRow.'-AE'.$sumRow);
  4287.         $summarySheet->setCellValue("AO" $sumRow'=U'.$sumRow.'-AF'.$sumRow);
  4288.         $summarySheet->setCellValue("AR" $sumRow'=I'.$sumRow.'-AJ'.$sumRow);
  4289.         $summarySheet->setCellValue("AS" $sumRow'=J'.$sumRow.'-AK'.$sumRow);
  4290.         $summarySheet->setCellValue("AP" $sumRow,'=IF(T'.$sumRow.'=0, "",(T'.$sumRow'-AE'.$sumRow.')/T'.$sumRow.')');
  4291.         $summarySheet->setCellValue("AQ" $sumRow,'=IF(U'.$sumRow.'=0, "",(U'.$sumRow'-AF'.$sumRow.')/U'.$sumRow.')');
  4292.         $summarySheet->setCellValue("AT" $sumRow,'=IF(I'.$sumRow.'=0, "",(I'.$sumRow'-AJ'.$sumRow.')/I'.$sumRow.')');
  4293.         $summarySheet->setCellValue("AU" $sumRow,'=IF(J'.$sumRow.'=0, "",(J'.$sumRow'-AK'.$sumRow.')/J'.$sumRow.')');
  4294.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4295.         $summarySheet->getStyle("V1:V" $summarySheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4296.         $summarySheet->setAutoFilter('A1:' $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
  4297.         $summarySheet->getStyle('G2:L' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4298.         $summarySheet->getStyle('Q2:R' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4299.         $summarySheet->getStyle('T2:U' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4300.         $summarySheet->getStyle('AB2:AC' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4301.         $summarySheet->getStyle('AE2:AF' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4302.         $summarySheet->getStyle('AH2:AO' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4303.         $summarySheet->getStyle('AN2:AO' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4304.         $summarySheet->getStyle('AR2:AS' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4305.         $summarySheet->getStyle("AP2:AQ"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4306.         $summarySheet->getStyle("AT2:AU"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4307.         /** 
  4308.          * 
  4309.          * Amount Left Invoices
  4310.          */
  4311.         // $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
  4312.         // $spreadsheet->addSheet($unallocatedSheet, 2);
  4313.         // $unallocatedSheet->setCellValue('A1', 'Invoice');
  4314.         // $unallocatedSheet->setCellValue('B1', 'Vendor Name');
  4315.         // $unallocatedSheet->setCellValue('C1', 'Client');
  4316.         // $unallocatedSheet->setCellValue('D1', 'Project');
  4317.         // $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
  4318.         // $unallocatedSheet->setCellValue('F1', 'Amount USD');
  4319.         // $unallocatedSheet->setCellValue('G1', 'Allocated USD');
  4320.         // $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
  4321.         // $unallocatedSheet->setCellValue('I1', 'Date');
  4322.         // $unallocatedSheet->setCellValue('J1', 'Due Date');
  4323.         // $unallocatedSheet->setCellValue('K1', 'Client INV');
  4324.         // $unallocatedSheet->setCellValue('L1', 'Status');
  4325.         // $unallocatedSheet->setCellValue('M1', 'Financial Year');
  4326.         // $lastColx = $unallocatedSheet->getHighestColumn();
  4327.         // $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
  4328.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
  4329.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4330.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4331.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
  4332.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
  4333.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  4334.         // try {
  4335.         //     $currentRow = $unallocatedSheet->getHighestRow();
  4336.         //     $invoiceProjectMap = [];
  4337.         //     foreach ($projectsList as $project) {
  4338.         //         $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  4339.                 
  4340.         //         if ($vendorQuotationPlannings) {
  4341.         //             foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4342.         //                 $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4343.                         
  4344.         //                 foreach ($vqpInvoices as $vqpInvoice) {
  4345.         //                     $vendorInvoice = $vqpInvoice->getVendorInvoice();
  4346.                             
  4347.         //                     if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
  4348.         //                     if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
  4349.                             
  4350.         //                     $invoiceId = $vendorInvoice->getVendorInvoiceNo();
  4351.                             
  4352.         //                     if (!isset($invoiceProjectMap[$invoiceId])) {
  4353.         //                         $invoiceProjectMap[$invoiceId] = [
  4354.         //                             'invoice' => $vendorInvoice,
  4355.         //                             'projects' => [],
  4356.         //                             'vendorName' => '',
  4357.         //                             'xeroContact' => null
  4358.         //                         ];
  4359.         //                     }
  4360.                             
  4361.         //                     // Add project information
  4362.         //                     $invoiceProjectMap[$invoiceId]['projects'][] = [
  4363.         //                         'project' => $vendorQuotationPlanning->getProject(),
  4364.         //                         'client' => $vendorQuotationPlanning->getProject()->getClient(),
  4365.         //                         'vendorQuotationPlanning' => $vendorQuotationPlanning,
  4366.         //                         'amount' => $vqpInvoice->getAmountUsd(),
  4367.         //                     ];
  4368.         //                 }
  4369.         //             }
  4370.         //         }
  4371.         //     }
  4372.             
  4373.         //     // Second pass: Write to spreadsheet with merged cells for same invoice
  4374.         //     foreach ($invoiceProjectMap as $invoiceId => $data) {
  4375.         //         $vendorInvoice = $data['invoice'];
  4376.         //         $projects = $data['projects'];
  4377.         //         $startRow = $currentRow;
  4378.                 
  4379.         //         // Get vendor name
  4380.         //         $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
  4381.         //         $vendorName = '';
  4382.         //         if ($vendorInvoice->getXeroContactId()) {
  4383.         //             $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
  4384.         //         } else {
  4385.         //             $vendorName = $vendorInvoice->getVendor()->getName();
  4386.         //         }
  4387.                 
  4388.         //         // Get client invoices
  4389.         //         $clientInvoices = [];
  4390.         //         if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
  4391.         //             foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
  4392.         //                 $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  4393.         //                 array_push($clientInvoices, $clientInv);
  4394.         //             }
  4395.         //         }
  4396.                 
  4397.         //         // Write data for each project
  4398.         //         foreach ($projects as $index => $projectData) {
  4399.         //             $project = $projectData['project'];
  4400.                     
  4401.         //             // Write project-specific information
  4402.         //             $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
  4403.         //             $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
  4404.                     
  4405.         //             // Set project hyperlink
  4406.         //             $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
  4407.         //             $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
  4408.                     
  4409.         //             // Write amount for this project
  4410.         //             $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
  4411.                     
  4412.         //             // For the first project entry, write the shared invoice information
  4413.         //             if ($index === 0) {
  4414.         //                 $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
  4415.         //                 $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
  4416.         //                 $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
  4417.         //                 $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
  4418.         //                 $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
  4419.         //                 $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
  4420.         //                 $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
  4421.         //                 $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
  4422.         //                 $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
  4423.         //             }
  4424.                     
  4425.         //             // Handle vendor quotes
  4426.         //             if ($projectData['vendorQuotationPlanning']) {
  4427.         //                 $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
  4428.         //                 if (!empty($vendorQuotations)) {
  4429.         //                     foreach($vendorQuotations as $vendorQoute){
  4430.         //                         $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
  4431.         //                         $currentRow++;
  4432.         //                     }
  4433.         //                 } else {
  4434.         //                     $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  4435.         //                 }
  4436.         //             } else {
  4437.         //                 $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  4438.         //             }
  4439.                     
  4440.         //             $currentRow++;
  4441.         //         }
  4442.                 
  4443.         //         // If we have multiple projects, merge the shared invoice cells
  4444.         //         if (count($projects) > 1) {
  4445.         //             $endRow = $currentRow - 1;
  4446.         //             $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
  4447.                     
  4448.         //             foreach ($columnsToMerge as $column) {
  4449.         //                 if ($startRow < $endRow) {
  4450.         //                     $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
  4451.         //                     $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
  4452.         //                         ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4453.         //                 }
  4454.         //             }
  4455.         //         }
  4456.         //     }
  4457.         // } catch (\Exception $e) {
  4458.         //     dd($e->getMessage());
  4459.         // }
  4460.         // $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
  4461.         // $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  4462.         
  4463.         // Write the file
  4464.         $writer = new Xlsx($spreadsheet);
  4465.         $writer->save($filename);
  4466.         if ($_target == 'google') {
  4467.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  4468.             if ($gsheetURL) {
  4469.                 unlink($filename);
  4470.                 return new RedirectResponse($gsheetURL302);
  4471.             }
  4472.         } else {
  4473.             $response = new Response();
  4474.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  4475.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  4476.             $response->setContent(file_get_contents($filename));
  4477.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  4478.             $response->headers->set('Content-Transfer-Encoding''binary');
  4479.             $response->headers->set('Pragma''no-cache');
  4480.             $response->headers->set('Expires''0');
  4481.             unlink($filename);
  4482.             return $response;
  4483.             exit;
  4484.         }
  4485.     }
  4486.     // Export Project Revenue Cost Date Range [PENDING]
  4487.     
  4488.     public function exportProjectRevenueCostDateRange($isAdmin$startDate$endDate$baseurl$_target)
  4489.     {
  4490.         $startDateRange date("d-M-Y"strtotime($startDate));
  4491.         $endDateRange date("d-M-Y"strtotime($endDate));
  4492.         $overallTotals = [];
  4493.         $lineItemTotals = [];
  4494.         $overallTotalRevenue 0;
  4495.         $overallTotalCost 0;
  4496.         $spreadsheet = new Spreadsheet();
  4497.         $sheet $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  4498.         $sheet->setCellValue('A1''Today\'s Date');
  4499.         $sheet->setCellValue('A2''From (Project Start Date)');
  4500.         $sheet->setCellValue('A3''To (Project Start Date)');
  4501.         $sheet->setCellValue('C1'date('d-M-Y'));
  4502.         $sheet->setCellValue('C2'$startDateRange);
  4503.         $sheet->setCellValue('C3'$endDateRange);
  4504.         // Define Header Data
  4505.         $sheet->setCellValue('A5''Client');
  4506.         $sheet->setCellValue('B5''Project ID');
  4507.         $sheet->setCellValue('C5''Project Name');
  4508.         $sheet->setCellValue('D5''Project Status');
  4509.         $sheet->setCellValue('E5''Start Date');
  4510.         $sheet->setCellValue('F5''End Date');
  4511.         // $sheet->setCellValue('G5', 'Revenue FY ' . $fyStart);
  4512.         // $sheet->setCellValue('H5', 'Revenue FY ' . $fyStart . ' Amount Allocated');
  4513.         // $sheet->setCellValue('I5', 'Revenue FY ' . $financialYear);
  4514.         // $sheet->setCellValue('J5', 'Revenue FY ' . $financialYear . ' Amount Allocated');
  4515.         // $sheet->setCellValue('K5', 'Revenue FY ' . $fyEnd);
  4516.         // $sheet->setCellValue('L5', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
  4517.         $sheet->setCellValue('G5''MT INV No.');
  4518.         $sheet->setCellValue('H5''INV Date');
  4519.         $sheet->setCellValue('I5''INV Due Date');
  4520.         $sheet->setCellValue('J5''INV Currency');
  4521.         $sheet->setCellValue('K5''INV Amount (w/o Taxes)');
  4522.         $sheet->setCellValue('L5''INV Amount Allocated (w/o Taxes)');
  4523.         $sheet->setCellValue('M5''SGD FX Rate');
  4524.         $sheet->setCellValue('N5''INV Amount (w/o Taxes in SGD)');
  4525.         $sheet->setCellValue('O5''INV Amount Allocated (w/o Taxes in SGD)');
  4526.         $sheet->setCellValue('P5''Item Code');
  4527.         $sheet->setCellValue('Q5''Amount Item Code');
  4528.         $sheet->setCellValue('R5''Department');
  4529.         $sheet->setCellValue('S5''');
  4530.         $sheet->setCellValue('T5''Vendor');
  4531.         $sheet->setCellValue('U5''Vendor INV No.');
  4532.         $sheet->setCellValue('V5''Vendor INV Date');
  4533.         $sheet->setCellValue('W5''Vendor INV Due Date');
  4534.         $sheet->setCellValue('X5''Vendor INV Currency');
  4535.         $sheet->setCellValue('Y5''Vendor INV Amount (w/o Taxes)');
  4536.         $sheet->setCellValue('Z5''Vendor INV Amount Allocated (w/o Taxes)');
  4537.         $sheet->setCellValue('AA5''SGD FX Rate');
  4538.         $sheet->setCellValue('AB5''Vendor INV Amount (w/o Taxes in SGD)');
  4539.         $sheet->setCellValue('AC5''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4540.         $sheet->setCellValue('AD5''Client INV No');
  4541.         // $sheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
  4542.         // $sheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
  4543.         // $sheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
  4544.         // $sheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
  4545.         // $sheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
  4546.         // $sheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
  4547.         $sheet->setCellValue('AE5''Gross Profit Total');
  4548.         $sheet->setCellValue('AF5''Gross Profit Total Amount Allocated');
  4549.         $sheet->setCellValue('AG5''Gross Profit Margin Total');
  4550.         $sheet->setCellValue('AH5''Gross Profit Margin Total Amount Allocated');
  4551.         // $sheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
  4552.         // $sheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
  4553.         // $sheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
  4554.         // $sheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
  4555.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4556.         $sheet->getDefaultColumnDimension()->setWidth(25);
  4557.         $sheet->getColumnDimension('S')->setWidth(3);
  4558.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  4559.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4560.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4561.         $sheet->getStyle("A6:" $sheet->getHighestColumn() . "6")->getFont()->setBold(false);
  4562.         $sheet->freezePane('A6');
  4563.         $filename "Project_Revenue_vs_Cost_" $startDateRange " - " $endDateRange "_" date('Y-m-d') . '.xlsx';
  4564.         // $type = "LEAD;CONFIRMED";
  4565.         $type "CONFIRMED";
  4566.         $status "On-Going;Finished";
  4567.         $projectsList $this->projectRepository->findByPage(09999"""ASC"'client'$startDate$endDate$type0$status);
  4568.         $row $sheet->getHighestRow();
  4569.         $overallRow $row+1;
  4570.         if(count($projectsList)){
  4571.             foreach ($projectsList as $project) {
  4572.                 $sheet->setCellValue("A" $row$project['clientName']);
  4573.                 $sheet->setCellValue("B" $row$project['generatedId']);
  4574.                 $sheet->getCell("B" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4575.                 $sheet->getStyle('B' $row)->getFont()->setUnderline(true);
  4576.                 $sheet->setCellValue("C" $row$project['name']);
  4577.                 $sheet->getCell("C" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4578.                 $sheet->getStyle('C' $row)->getFont()->setUnderline(true);
  4579.                 $sheet->setCellValue("D" $row$project['status']);
  4580.                 $sheet->setCellValue("E" $row$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4581.                 $sheet->setCellValue("F" $row$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4582.                 
  4583.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4584.                     $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4585.                     $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4586.                 }
  4587.                 // looping project invoice
  4588.                 $invRow $row;
  4589.                 $projectSalesOrders $project[0]->getProjectSalesOrders();
  4590.                 $InvTotalwoTax 0;
  4591.                 if ($projectSalesOrders) {
  4592.                     foreach ($projectSalesOrders as $pso) {
  4593.                         $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4594.                         foreach ($soInvoices as $soInvoice) {
  4595.                             $invoice $soInvoice->getInvoice();
  4596.                             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4597.                             $sheet->setCellValue("G" $invRow$invoice->getInvoiceNo());
  4598.                             $sheet->setCellValue("H" $invRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4599.                             $sheet->setCellValue("I" $invRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4600.                             $sheet->setCellValue("J" $invRow$invoice->getCurrency()->getIso());
  4601.                             $InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
  4602.                             $sheet->setCellValue("K" $invRow$invoice->getSubTotal());
  4603.                             $sheet->setCellValue("L" $invRow$soInvoice->getAmount());
  4604.                             $sheet->setCellValue("M" $invRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4605.                             $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4606.                             $sheet->setCellValue("N" $invRow$invoice->getSubTotalSgd($project[0]));
  4607.                             $sheet->setCellValue("O" $invRow$amountSGD);
  4608.                             if($invoice->getXeroLineItems()->count() > 0) {
  4609.                                 $lineItemRow $invRow;
  4610.                                 foreach ($invoice->getXeroLineItems() as $lineItem) {
  4611.                                     $sheet->setCellValue("P" $lineItemRow$lineItem->getItemCode());
  4612.                                     $sheet->setCellValue("Q" $lineItemRow$lineItem->getSubTotal());
  4613.                                     $sheet->setCellValue("R" $lineItemRow$lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-');
  4614.                                     $itemCode $lineItem->getItemCode();
  4615.                                     $department $lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-';
  4616.                                     $amount $lineItem->getSubTotal();
  4617.                                     if (!isset($lineItemTotals[$itemCode])) {
  4618.                                         $lineItemTotals[$itemCode] = [];
  4619.                                     }
  4620.                                     if (!isset($lineItemTotals[$itemCode]['department'])) {
  4621.                                         $lineItemTotals[$itemCode]['department'] = $department;
  4622.                                     }
  4623.                                     if (!isset($lineItemTotals[$itemCode]['amount'])) {
  4624.                                         $lineItemTotals[$itemCode]['amount'] = 0;
  4625.                                     }else{
  4626.                                         $lineItemTotals[$itemCode]['amount'] += $amount;
  4627.                                     }
  4628.                                     $lineItemRow++;
  4629.                                 
  4630.                                 }
  4631.                             }
  4632.                             $invRow $lineItemRow $invRow $lineItemRow $invRow;
  4633.                         }
  4634.                     }
  4635.                 } else {
  4636.                     $sheet->setCellValue("G" $invRow"-");
  4637.                     $sheet->setCellValue("H" $invRow"-");
  4638.                     $sheet->setCellValue("I" $invRow"-");
  4639.                     $sheet->setCellValue("J" $invRow"-");
  4640.                     $sheet->setCellValue("K" $invRow"-");
  4641.                     $sheet->setCellValue("L" $invRow"-");
  4642.                     $sheet->setCellValue("M" $invRow"-");
  4643.                     $sheet->setCellValue("N" $invRow"-");
  4644.                     $sheet->setCellValue("O" $invRow"-");
  4645.                 }
  4646.                 //looping vendor invoice
  4647.                 $vendorInvRow $row;
  4648.                 $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4649.                 $vendorTotalWoTax 0;
  4650.                 if ($vendorQuotationPlannings) {
  4651.                     foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4652.                         $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4653.                         $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4654.                         foreach ($vqpInvoices as $vqpInvoice) {
  4655.                             $invoice $vqpInvoice->getVendorInvoice();
  4656.                             // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4657.                             $sheet->setCellValue("T" $vendorInvRow$vendorName);
  4658.                             $sheet->setCellValue("U" $vendorInvRow$invoice->getInvoiceNo());
  4659.                             $sheet->setCellValue("V" $vendorInvRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4660.                             $sheet->setCellValue("W" $vendorInvRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4661.                             $sheet->setCellValue("X" $vendorInvRow$invoice->getCurrency()->getIso());
  4662.                             $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  4663.                             $sheet->setCellValue("Y" $vendorInvRow$invoice->getSubtotal());
  4664.                             $sheet->setCellValue("Z" $vendorInvRow$vqpInvoice->getAmount());
  4665.                             $sheet->setCellValue("AA" $vendorInvRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4666.                             $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4667.                             $sheet->setCellValue("AB" $vendorInvRow$invoice->getSubTotalSgd($project[0]));
  4668.                             $sheet->setCellValue("AC" $vendorInvRow$vendorAmountSGD);
  4669.                             $sheet->setCellValue("AD" $vendorInvRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4670.                             $vendorInvRow++;
  4671.                         }
  4672.                     }
  4673.                 } else {
  4674.                     $sheet->setCellValue("T" $vendorInvRow"-");
  4675.                     $sheet->setCellValue("U" $vendorInvRow"-");
  4676.                     $sheet->setCellValue("V" $vendorInvRow"-");
  4677.                     $sheet->setCellValue("W" $vendorInvRow"-");
  4678.                     $sheet->setCellValue("X" $vendorInvRow"-");
  4679.                     $sheet->setCellValue("Y" $vendorInvRow"-");
  4680.                     $sheet->setCellValue("Z" $vendorInvRow"-");
  4681.                     $sheet->setCellValue("AA" $vendorInvRow"-");
  4682.                     $sheet->setCellValue("AB" $vendorInvRow"-");
  4683.                     $sheet->setCellValue("AC" $vendorInvRow"-");
  4684.                     $sheet->setCellValue("AD" $vendorInvRow"-");
  4685.                 }
  4686.                 $totalRow $invRow $row || $vendorInvRow $row max($invRow$vendorInvRow) : $row 1;
  4687.                 $sheet->setCellValue("A" $totalRow"Total");
  4688.                 $sheet->setCellValue("N" $totalRow'=SUM(N'.$row.':N'.($invRow $row $invRow $row).')');
  4689.                 $sheet->setCellValue("O" $totalRow'=SUM(O'.$row.':O'.($invRow $row $invRow $row).')');
  4690.                 $sheet->setCellValue("AB" $totalRow'=SUM(AB'.$row.':AB'.($vendorInvRow $row $vendorInvRow $row).')');
  4691.                 $sheet->setCellValue("AC" $totalRow'=SUM(AC'.$row.':AC'.($vendorInvRow $row $vendorInvRow $row).')');
  4692.                 $sheet->setCellValue("AE" $totalRow'=N'.$totalRow.'-AB'.$totalRow);
  4693.                 $sheet->setCellValue("AE" $row'=N'.$totalRow.'-AB'.$totalRow);
  4694.                 $sheet->setCellValue("AF" $totalRow'=O'.$totalRow.'-AC'.$totalRow);
  4695.                 $sheet->setCellValue("AF" $row'=O'.$totalRow.'-AC'.$totalRow);
  4696.                 $grossProfitMargin 0;
  4697.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4698.                     $grossProfitMargin '=(N'.$totalRow'-AB'.$totalRow.')/N'.$totalRow;
  4699.                     $sheet->setCellValue("AG" $totalRow$grossProfitMargin);
  4700.                     $sheet->setCellValue("AG" $row$grossProfitMargin);
  4701.                 }else{
  4702.                     $sheet->setCellValue("AG" $totalRow$grossProfitMargin);
  4703.                     $sheet->setCellValue("AG" $row$grossProfitMargin);
  4704.                 }
  4705.                 $grossProfitMarginAllocated 0;
  4706.                 if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  4707.                     $grossProfitMarginAllocated '=(O'.$totalRow'-AC'.$totalRow.')/O'.$totalRow;
  4708.                     $sheet->setCellValue("AH" $totalRow$grossProfitMarginAllocated);
  4709.                     $sheet->setCellValue("AH" $row$grossProfitMarginAllocated);
  4710.                 }else{
  4711.                     $sheet->setCellValue("AH" $totalRow$grossProfitMarginAllocated);
  4712.                     $sheet->setCellValue("AH" $row$grossProfitMarginAllocated);
  4713.                 }
  4714.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  4715.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4716.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4717.                 $sheet->getRowDimension($totalRow)->setRowHeight(20);
  4718.                 $overallTotals['N'][] = 'N'.$totalRow;
  4719.                 $overallTotals['O'][] = 'O'.$totalRow;
  4720.                 $overallTotals['AB'][] = 'AB'.$totalRow;
  4721.                 $overallTotals['AC'][] = 'AC'.$totalRow;
  4722.                 $row $totalRow;
  4723.                 $row++;
  4724.             }
  4725.             //overall total
  4726.             $overallRow $row+1;
  4727.             $row $row+1;
  4728.             $sheet->setCellValue("A"$row"Overall Total");
  4729.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4730.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4731.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4732.             
  4733.             $sheet->getRowDimension($row)->setRowHeight(20);
  4734.             $sheet->setCellValue("N" $row'='.implode('+'$overallTotals['N']));
  4735.             $sheet->setCellValue("O" $row'='.implode('+'$overallTotals['O']));
  4736.             $sheet->setCellValue("AB" $row'='.implode('+'$overallTotals['AB']));
  4737.             $sheet->setCellValue("AC" $row'='.implode('+'$overallTotals['AC']));
  4738.             $sheet->setCellValue("AE" $row'=N'.$row.'-AB'.$row);
  4739.             $sheet->setCellValue("AF" $row'=O'.$row.'-AC'.$row);
  4740.             $sheet->setCellValue("AG" $row,'=IF(N'.$row.'=0, "",(N'.$row'-AB'.$row.')/N'.$row.')');
  4741.             $sheet->setCellValue("AH" $row,'=IF(O'.$row.'=0, "",(O'.$row'-AC'.$row.')/O'.$row.')');
  4742.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4743.             $row $row+2;
  4744.             $sheet->setCellValue("A" $row"Summary");
  4745.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4746.             $row $row+1;
  4747.             $sheet->setCellValue("A" $row"Item Code");
  4748.             $sheet->setCellValue("B" $row"Department");
  4749.             $sheet->setCellValue("C" $row"Amount");
  4750.             $sheet->getStyle("A" $row ":C" $row)->getFont()->setBold(true);
  4751.             $sheet->getStyle("A" $row ":C" $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4752.             $row $row+1;
  4753.             foreach ($lineItemTotals as $itemCode => $itemTotal) {
  4754.                 $sheet->setCellValue("A" $row$itemCode);
  4755.                 $sheet->setCellValue("B" $row$itemTotal['department']);
  4756.                 $sheet->setCellValue("C" $row$itemTotal['amount']);
  4757.                 $sheet->getStyle('C' $row)->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4758.                 $row++;
  4759.             }
  4760.         }   
  4761.         $sheet->getStyle("S5:S" $overallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4762.         $sheet->setAutoFilter('A5:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  4763.         $sheet->getStyle('K2:L' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4764.         $sheet->getStyle('N2:O' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4765.         $sheet->getStyle('Q2:Q' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4766.         $sheet->getStyle('Y2:Z' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4767.         $sheet->getStyle('AB2:AC' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4768.         $sheet->getStyle('AE2:AF' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4769.         $sheet->getStyle("AG2:AH"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4770.         $summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Summary Total');
  4771.         $spreadsheet->addSheet($summarySheet1);
  4772.         $summarySheet->setCellValue('A1''Today\'s Date');
  4773.         $summarySheet->setCellValue('A2''From (Project Start Date)');
  4774.         $summarySheet->setCellValue('A3''To (Project Start Date)');
  4775.         $summarySheet->setCellValue('C1'date('d-M-Y'));
  4776.         $summarySheet->setCellValue('C2'$startDateRange);
  4777.         $summarySheet->setCellValue('C3'$endDateRange);
  4778.         $summarySheet->setCellValue('A5''Client');
  4779.         $summarySheet->setCellValue('B5''Project ID');
  4780.         $summarySheet->setCellValue('C5''Project Name');
  4781.         $summarySheet->setCellValue('D5''Project Status');
  4782.         $summarySheet->setCellValue('E5''Start Date');
  4783.         $summarySheet->setCellValue('F5''End Date');
  4784.         // $summarySheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
  4785.         // $summarySheet->setCellValue('H1', 'Revenue FY ' . $fyStart . ' Amount Allocated');
  4786.         // $summarySheet->setCellValue('I1', 'Revenue FY ' . $financialYear);
  4787.         // $summarySheet->setCellValue('J1', 'Revenue FY ' . $financialYear . ' Amount Allocated');
  4788.         // $summarySheet->setCellValue('K1', 'Revenue FY ' . $fyEnd);
  4789.         // $summarySheet->setCellValue('L1', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
  4790.         $summarySheet->setCellValue('G5''MT INV No.');
  4791.         $summarySheet->setCellValue('H5''INV Date');
  4792.         $summarySheet->setCellValue('I5''INV Due Date');
  4793.         $summarySheet->setCellValue('J5''INV Currency');
  4794.         $summarySheet->setCellValue('K5''INV Amount (w/o Taxes)');
  4795.         $summarySheet->setCellValue('L5''INV Amount Allocated (w/o Taxes)');
  4796.         $summarySheet->setCellValue('M5''SGD FX Rate');
  4797.         $summarySheet->setCellValue('N5''INV Amount (w/o Taxes in SGD)');
  4798.         $summarySheet->setCellValue('O5''INV Amount Allocated (w/o Taxes in SGD)');
  4799.         $summarySheet->setCellValue('P5''');
  4800.         $summarySheet->setCellValue('Q5''Vendor');
  4801.         $summarySheet->setCellValue('R5''Vendor INV No.');
  4802.         $summarySheet->setCellValue('S5''Vendor INV Date');
  4803.         $summarySheet->setCellValue('T5''Vendor INV Due Date');
  4804.         $summarySheet->setCellValue('U5''Vendor INV Currency');
  4805.         $summarySheet->setCellValue('V5''Vendor INV Amount (w/o Taxes)');
  4806.         $summarySheet->setCellValue('W5''Vendor INV Amount Allocated (w/o Taxes)');
  4807.         $summarySheet->setCellValue('X5''SGD FX Rate');
  4808.         $summarySheet->setCellValue('Y5''Vendor INV Amount (w/o Taxes in SGD)');
  4809.         $summarySheet->setCellValue('Z5''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4810.         $summarySheet->setCellValue('AA5''Client INV No');
  4811.         // $summarySheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
  4812.         // $summarySheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
  4813.         // $summarySheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
  4814.         // $summarySheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
  4815.         // $summarySheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
  4816.         // $summarySheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
  4817.         $summarySheet->setCellValue('AB5''Gross Profit Total');
  4818.         $summarySheet->setCellValue('AC5''Gross Profit Total Amount Allocated');
  4819.         $summarySheet->setCellValue('AD5''Gross Profit Margin Total');
  4820.         $summarySheet->setCellValue('AE5''Gross Profit Margin Total Amount Allocated');
  4821.         // $summarySheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
  4822.         // $summarySheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
  4823.         // $summarySheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
  4824.         // $summarySheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
  4825.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4826.         $summarySheet->getDefaultColumnDimension()->setWidth(25);
  4827.         $summarySheet->getColumnDimension('P')->setWidth(3);
  4828.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFont()->setBold(true);
  4829.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4830.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4831.         // $summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4832.         // $summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4833.         // $summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4834.         // $summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4835.         // $summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4836.         // $summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4837.         // $summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4838.         // $summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4839.         // $summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4840.         // $summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4841.         // $summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4842.         // $summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4843.         // $summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4844.         // $summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4845.         $summarySheet->getStyle("A6:" $summarySheet->getHighestColumn() . "6")->getFont()->setBold(false);
  4846.         $summarySheet->freezePane('A6');
  4847.         // $type = "LEAD;CONFIRMED";
  4848.         $type "CONFIRMED";
  4849.         $status "On-Going;Finished";
  4850.         $projectsListSummary $this->projectRepository->findByPage(09999"""ASC"'client'$startDate$endDate$type0$status);
  4851.         
  4852.         $sumOverallTotals = [];
  4853.         $sumRow $summarySheet->getHighestRow();
  4854.         $sumOverallRow $sumRow+1;
  4855.         if(count($projectsListSummary) > 0){
  4856.             foreach ($projectsListSummary as $project) {
  4857.                 $summarySheet->setCellValue("A" $sumRow$project['clientName']);
  4858.                 $summarySheet->setCellValue("B" $sumRow$project['generatedId']);
  4859.                 $summarySheet->getCell("B" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4860.                 $summarySheet->getStyle('B' $sumRow)->getFont()->setUnderline(true);
  4861.                 $summarySheet->setCellValue("C" $sumRow$project['name']);
  4862.                 $summarySheet->getCell("C" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4863.                 $summarySheet->getStyle('C' $sumRow)->getFont()->setUnderline(true);
  4864.                 $summarySheet->setCellValue("D" $sumRow$project['status']);
  4865.                 $summarySheet->setCellValue("E" $sumRow$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4866.                 $summarySheet->setCellValue("F" $sumRow$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4867.                 // $summarySheet->setCellValue("G" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4868.                 // $summarySheet->setCellValue("H" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4869.                 // $summarySheet->setCellValue("I" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4870.                 // $summarySheet->setCellValue("J" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4871.                 // $summarySheet->setCellValue("K" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4872.                 // $summarySheet->setCellValue("L" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4873.                 // $summarySheet->setCellValue("AH" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  4874.                 // $summarySheet->setCellValue("AI" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart, true));
  4875.                 // $summarySheet->setCellValue("AJ" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  4876.                 // $summarySheet->setCellValue("AK" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear, true));
  4877.                 // $summarySheet->setCellValue("AL" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  4878.                 // $summarySheet->setCellValue("AM" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd, true));
  4879.                 $projectSalesOrders $project[0]->getProjectSalesOrders();
  4880.                 $invData = [
  4881.                     'totalAmount' => 0,
  4882.                     'totalAmountSGD' => 0,
  4883.                     'totalAmountAllocated' => 0,
  4884.                     'totalAmountAllocatedSGD' => 0,
  4885.                 ];
  4886.                 if ($projectSalesOrders) {
  4887.                     foreach ($projectSalesOrders as $pso) {
  4888.                         $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4889.                         foreach ($soInvoices as $soInvoice) {
  4890.                             $invoice $soInvoice->getInvoice();
  4891.                             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4892.                             $summarySheet->setCellValue("G" $sumRow"-");
  4893.                             $summarySheet->setCellValue("H" $sumRow"-");
  4894.                             $summarySheet->setCellValue("I" $sumRow"-");
  4895.                             $summarySheet->setCellValue("J" $sumRow$invoice->getCurrency()->getIso());
  4896.                             $invData['totalAmount'] += $invoice->getSubTotal();
  4897.                             $invData['totalAmountAllocated'] += $soInvoice->getAmount();
  4898.                             $invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4899.                             $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4900.                             $invData['totalAmountAllocatedSGD'] += $amountSGD;
  4901.                             $summarySheet->setCellValue("K" $sumRow$invData['totalAmount']);
  4902.                             $summarySheet->setCellValue("L" $sumRow$invData['totalAmountAllocated']);
  4903.                             // $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4904.                             
  4905.                             $summarySheet->setCellValue("N" $sumRow$invData['totalAmountSGD']);
  4906.                             $summarySheet->setCellValue("O" $sumRow$invData['totalAmountAllocatedSGD']);
  4907.                         }
  4908.                     }
  4909.                 } else {
  4910.                     $summarySheet->setCellValue("G" $sumRow"-");
  4911.                     $summarySheet->setCellValue("H" $sumRow"-");
  4912.                     $summarySheet->setCellValue("I" $sumRow"-");
  4913.                     $summarySheet->setCellValue("J" $sumRow"-");
  4914.                     $summarySheet->setCellValue("K" $sumRow"-");
  4915.                     $summarySheet->setCellValue("L" $sumRow"-");
  4916.                     $summarySheet->setCellValue("M" $sumRow"-");
  4917.                     $summarySheet->setCellValue("N" $sumRow"-");
  4918.                     $summarySheet->setCellValue("O" $sumRow"-");
  4919.                 }
  4920.                 $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4921.                 $vendorData = [
  4922.                     'totalAmount' => 0,
  4923.                     'totalAmountAllocated' => 0,
  4924.                     'totalAmountSGD' => 0,
  4925.                     'totalAmountAllocatedSGD' => 0,
  4926.                 ];
  4927.                 if ($vendorQuotationPlannings) {
  4928.                     foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4929.                         $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4930.                         $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4931.                         foreach ($vqpInvoices as $vqpInvoice) {
  4932.                             $invoice $vqpInvoice->getVendorInvoice();
  4933.                             $summarySheet->setCellValue("Q" $sumRow"-");
  4934.                             $summarySheet->setCellValue("R" $sumRow"-");
  4935.                             $summarySheet->setCellValue("S" $sumRow"-");
  4936.                             $summarySheet->setCellValue("T" $sumRow"-");
  4937.                             $summarySheet->setCellValue("U" $sumRow"-");
  4938.                             // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4939.                             // $summarySheet->setCellValue("W" . $sumRow, $vendorName);
  4940.                             // $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
  4941.                             // $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4942.                             // $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4943.                             $summarySheet->setCellValue("U" $sumRow$invoice->getCurrency()->getIso());
  4944.                             $vendorData['totalAmount'] += $invoice->getSubTotal();
  4945.                             $vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
  4946.                             $summarySheet->setCellValue("V" $sumRow$vendorData['totalAmount']);
  4947.                             $summarySheet->setCellValue("W" $sumRow$vendorData['totalAmountAllocated']);
  4948.                             // $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4949.                             $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4950.                             $vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4951.                             $vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
  4952.                             $summarySheet->setCellValue("Y" $sumRow$vendorData['totalAmountSGD']);
  4953.                             $summarySheet->setCellValue("Z" $sumRow$vendorData['totalAmountAllocatedSGD']);
  4954.                             $summarySheet->setCellValue('AA'$sumRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4955.                         }
  4956.                     }
  4957.                 } else {
  4958.                     $summarySheet->setCellValue("Q" $sumRow"-");
  4959.                     $summarySheet->setCellValue("R" $sumRow"-");
  4960.                     $summarySheet->setCellValue("S" $sumRow"-");
  4961.                     $summarySheet->setCellValue("T" $sumRow"-");
  4962.                     $summarySheet->setCellValue("U" $sumRow"-");
  4963.                     $summarySheet->setCellValue("V" $sumRow"-");
  4964.                     $summarySheet->setCellValue("W" $sumRow"-");
  4965.                     $summarySheet->setCellValue("X" $sumRow"-");
  4966.                     $summarySheet->setCellValue("Y" $sumRow"-");
  4967.                     $summarySheet->setCellValue("Z" $sumRow"-");
  4968.                     $summarySheet->setCellValue("AA" $sumRow"-");
  4969.                 }
  4970.                 
  4971.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4972.                     $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4973.                     $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4974.                 }
  4975.                 // $summarySheet->setCellValue("A" . $totalRow, "Total");
  4976.                 // $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4977.                 // $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4978.                 // $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4979.                 // $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4980.                 // $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4981.                 // $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4982.                 // $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4983.                 // $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4984.                 // $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4985.                 // $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4986.                 // $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
  4987.                 // $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
  4988.                 // $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
  4989.                 // $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
  4990.                 // $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
  4991.                 // $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
  4992.                 $summarySheet->setCellValue("AB" $sumRow'=N'.$sumRow.'-Y'.$sumRow);
  4993.                 $summarySheet->setCellValue("AC" $sumRow'=O'.$sumRow.'-Z'.$sumRow);
  4994.                 $grossProfitMargin 0;
  4995.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4996.                     $grossProfitMargin '=(N'.$sumRow'-Y'.$sumRow.')/N'.$sumRow;
  4997.                     $summarySheet->setCellValue("AD" $sumRow$grossProfitMargin);
  4998.                 }else{
  4999.                     $summarySheet->setCellValue("AD" $sumRow$grossProfitMargin);
  5000.                 }
  5001.                 $grossProfitMarginAllocated 0;
  5002.                 if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  5003.                     $grossProfitMarginAllocated '=(O'.$sumRow'-Z'.$sumRow.')/O'.$sumRow;
  5004.                     $summarySheet->setCellValue("AE" $sumRow$grossProfitMarginAllocated);
  5005.                 }else{
  5006.                     $summarySheet->setCellValue("AE" $sumRow$grossProfitMarginAllocated);
  5007.                 }
  5008.                 // $summarySheet->setCellValue("AR" . $sumRow, '=I'.$sumRow.'-AJ'.$sumRow);
  5009.                 // $summarySheet->setCellValue("AS" . $sumRow, '=J'.$sumRow.'-AK'.$sumRow);
  5010.                 // $grossProfitMarginFinancialYear = 0;
  5011.                 // if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  5012.                 //     $grossProfitMarginFinancialYear = '=(I'.$sumRow. '-AJ'.$sumRow.')/I'.$sumRow;
  5013.                 //     $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
  5014.                 // }else{
  5015.                 //     $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
  5016.                 // }
  5017.                 // $grossProfitMarginFinancialYearAllocated = 0;
  5018.                 // if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear, true) > 0) {
  5019.                 //     $grossProfitMarginFinancialYearAllocated = '=(J'.$sumRow. '-AK'.$sumRow.')/J'.$sumRow;
  5020.                 //     $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
  5021.                 // }else{
  5022.                 //     $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
  5023.                 // }
  5024.                 $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
  5025.                 // $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  5026.                 $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5027.                 $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  5028.                 $sumOverallTotals['N'][] = 'N'.$sumRow;
  5029.                 $sumOverallTotals['O'][] = 'O'.$sumRow;
  5030.                 $sumOverallTotals['Y'][] = 'Y'.$sumRow;
  5031.                 $sumOverallTotals['Z'][] = 'Z'.$sumRow;
  5032.                 $sumRow++;
  5033.             }
  5034.             $sumOverallRow $sumRow+1;
  5035.             $sumRow $sumRow+1;
  5036.             $summarySheet->setCellValue("A"$sumRow"Overall Total");
  5037.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5038.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5039.             $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  5040.             $summarySheet->setCellValue("N" $sumRow'='.implode('+'$sumOverallTotals['N']));
  5041.             $summarySheet->setCellValue("O" $sumRow'='.implode('+'$sumOverallTotals['O']));
  5042.             $summarySheet->setCellValue("Y" $sumRow'='.implode('+'$sumOverallTotals['Y']));
  5043.             $summarySheet->setCellValue("Z" $sumRow'='.implode('+'$sumOverallTotals['Z']));
  5044.             $summarySheet->setCellValue("AB" $sumRow'=N'.$sumRow.'-Y'.$sumRow);
  5045.             $summarySheet->setCellValue("AC" $sumRow'=O'.$sumRow.'-Z'.$sumRow);
  5046.             $summarySheet->setCellValue("AD" $sumRow,'=IF(N'.$sumRow.'=0, "",(N'.$sumRow'-Y'.$sumRow.')/N'.$sumRow.')');
  5047.             $summarySheet->setCellValue("AE" $sumRow,'=IF(O'.$sumRow.'=0, "",(O'.$sumRow'-Z'.$sumRow.')/O'.$sumRow.')');
  5048.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
  5049.         }
  5050.         $summarySheet->getStyle("P5:P" $sumOverallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5051.         $summarySheet->setAutoFilter('A5:' $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
  5052.         $summarySheet->getStyle('K2:L' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  5053.         $summarySheet->getStyle('N2:O' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5054.         $summarySheet->getStyle('V2:W' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5055.         $summarySheet->getStyle('Y2:Z' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5056.         $summarySheet->getStyle('AB2:AC' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5057.         $summarySheet->getStyle("AD2:AE"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  5058.         // Amount Left Invoices
  5059.         // $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
  5060.         // $spreadsheet->addSheet($unallocatedSheet, 2);
  5061.         // $unallocatedSheet->setCellValue('A1', 'Invoice');
  5062.         // $unallocatedSheet->setCellValue('B1', 'Vendor Name');
  5063.         // $unallocatedSheet->setCellValue('C1', 'Client');
  5064.         // $unallocatedSheet->setCellValue('D1', 'Project');
  5065.         // $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
  5066.         // $unallocatedSheet->setCellValue('F1', 'Amount USD');
  5067.         // $unallocatedSheet->setCellValue('G1', 'Allocated USD');
  5068.         // $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
  5069.         // $unallocatedSheet->setCellValue('I1', 'Date');
  5070.         // $unallocatedSheet->setCellValue('J1', 'Due Date');
  5071.         // $unallocatedSheet->setCellValue('K1', 'Client INV');
  5072.         // $unallocatedSheet->setCellValue('L1', 'Status');
  5073.         // $unallocatedSheet->setCellValue('M1', 'Financial Year');
  5074.         // $lastColx = $unallocatedSheet->getHighestColumn();
  5075.         // $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
  5076.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
  5077.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  5078.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5079.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
  5080.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
  5081.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  5082.         // try {
  5083.         //     $currentRow = $unallocatedSheet->getHighestRow();
  5084.         //     $invoiceProjectMap = [];
  5085.         //     foreach ($projectsList as $project) {
  5086.         //         $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  5087.                 
  5088.         //         if ($vendorQuotationPlannings) {
  5089.         //             foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  5090.         //                 $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  5091.                         
  5092.         //                 foreach ($vqpInvoices as $vqpInvoice) {
  5093.         //                     $vendorInvoice = $vqpInvoice->getVendorInvoice();
  5094.                             
  5095.         //                     if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
  5096.         //                     if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
  5097.                             
  5098.         //                     $invoiceId = $vendorInvoice->getVendorInvoiceNo();
  5099.                             
  5100.         //                     if (!isset($invoiceProjectMap[$invoiceId])) {
  5101.         //                         $invoiceProjectMap[$invoiceId] = [
  5102.         //                             'invoice' => $vendorInvoice,
  5103.         //                             'projects' => [],
  5104.         //                             'vendorName' => '',
  5105.         //                             'xeroContact' => null
  5106.         //                         ];
  5107.         //                     }
  5108.                             
  5109.         //                     // Add project information
  5110.         //                     $invoiceProjectMap[$invoiceId]['projects'][] = [
  5111.         //                         'project' => $vendorQuotationPlanning->getProject(),
  5112.         //                         'client' => $vendorQuotationPlanning->getProject()->getClient(),
  5113.         //                         'vendorQuotationPlanning' => $vendorQuotationPlanning,
  5114.         //                         'amount' => $vqpInvoice->getAmountUsd(),
  5115.         //                     ];
  5116.         //                 }
  5117.         //             }
  5118.         //         }
  5119.         //     }
  5120.             
  5121.         //     // Second pass: Write to spreadsheet with merged cells for same invoice
  5122.         //     foreach ($invoiceProjectMap as $invoiceId => $data) {
  5123.         //         $vendorInvoice = $data['invoice'];
  5124.         //         $projects = $data['projects'];
  5125.         //         $startRow = $currentRow;
  5126.                 
  5127.         //         // Get vendor name
  5128.         //         $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
  5129.         //         $vendorName = '';
  5130.         //         if ($vendorInvoice->getXeroContactId()) {
  5131.         //             $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
  5132.         //         } else {
  5133.         //             $vendorName = $vendorInvoice->getVendor()->getName();
  5134.         //         }
  5135.                 
  5136.         //         // Get client invoices
  5137.         //         $clientInvoices = [];
  5138.         //         if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
  5139.         //             foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
  5140.         //                 $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  5141.         //                 array_push($clientInvoices, $clientInv);
  5142.         //             }
  5143.         //         }
  5144.                 
  5145.         //         // Write data for each project
  5146.         //         foreach ($projects as $index => $projectData) {
  5147.         //             $project = $projectData['project'];
  5148.                     
  5149.         //             // Write project-specific information
  5150.         //             $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
  5151.         //             $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
  5152.                     
  5153.         //             // Set project hyperlink
  5154.         //             $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
  5155.         //             $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
  5156.                     
  5157.         //             // Write amount for this project
  5158.         //             $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
  5159.                     
  5160.         //             // For the first project entry, write the shared invoice information
  5161.         //             if ($index === 0) {
  5162.         //                 $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
  5163.         //                 $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
  5164.         //                 $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
  5165.         //                 $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
  5166.         //                 $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
  5167.         //                 $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
  5168.         //                 $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
  5169.         //                 $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
  5170.         //                 $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
  5171.         //             }
  5172.                     
  5173.         //             // Handle vendor quotes
  5174.         //             if ($projectData['vendorQuotationPlanning']) {
  5175.         //                 $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
  5176.         //                 if (!empty($vendorQuotations)) {
  5177.         //                     foreach($vendorQuotations as $vendorQoute){
  5178.         //                         $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
  5179.         //                         $currentRow++;
  5180.         //                     }
  5181.         //                 } else {
  5182.         //                     $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  5183.         //                 }
  5184.         //             } else {
  5185.         //                 $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  5186.         //             }
  5187.                     
  5188.         //             $currentRow++;
  5189.         //         }
  5190.                 
  5191.         //         // If we have multiple projects, merge the shared invoice cells
  5192.         //         if (count($projects) > 1) {
  5193.         //             $endRow = $currentRow - 1;
  5194.         //             $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
  5195.                     
  5196.         //             foreach ($columnsToMerge as $column) {
  5197.         //                 if ($startRow < $endRow) {
  5198.         //                     $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
  5199.         //                     $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
  5200.         //                         ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5201.         //                 }
  5202.         //             }
  5203.         //         }
  5204.         //     }
  5205.         // } catch (\Exception $e) {
  5206.         //     dd($e->getMessage());
  5207.         // }
  5208.         // $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
  5209.         // $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  5210.         
  5211.         // Write the file
  5212.         $writer = new Xlsx($spreadsheet);
  5213.         $writer->save($filename);
  5214.         if ($_target == 'google') {
  5215.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  5216.             if ($gsheetURL) {
  5217.                 unlink($filename);
  5218.                 return new RedirectResponse($gsheetURL302);
  5219.             }
  5220.         } else {
  5221.             $response = new Response();
  5222.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5223.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  5224.             $response->setContent(file_get_contents($filename));
  5225.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  5226.             $response->headers->set('Content-Transfer-Encoding''binary');
  5227.             $response->headers->set('Pragma''no-cache');
  5228.             $response->headers->set('Expires''0');
  5229.             unlink($filename);
  5230.             return $response;
  5231.             exit;
  5232.         }
  5233.     }
  5234.     
  5235.     public function getProjectLeadStatus($leadId)
  5236.     {
  5237.         return $this->projectLeadStatusRepository->findOneBy(['lead' => $leadId]);
  5238.     }
  5239.     
  5240.     public function generateRevenuePlanning($project$force false)
  5241.     {
  5242.         $result['status'] = 'OK';
  5243.         $estimatedProfit $project->getEstimatedProfit() ?: null;
  5244.         $estimatedProfitUsd $project->getEstimatedProfitUsd() ?: null;
  5245.         $startDate $project->getStartDate() ? new \DateTime($project->getStartDate()->format('Y-m-d H:i:s')) : null;
  5246.         if ($startDate) {
  5247.             $startDate->modify('first day of this month');
  5248.         }
  5249.         $endDate $project->getEndDate() ? new \DateTime($project->getEndDate()->format('Y-m-d H:i:s')) : null;
  5250.         if (is_null($estimatedProfit) || is_null($estimatedProfitUsd)) {
  5251.             $result['status'] = 'ERROR';
  5252.             $result['message'] = 'Please provide Project <b>Estimated Agency Revenue</b> to use this feature.';
  5253.             $result['data'] = null;
  5254.             return $result;
  5255.         }
  5256.         if (is_null($startDate) || is_null($endDate)) {
  5257.             $result['status'] = 'ERROR';
  5258.             $result['message'] = 'Please provide Project <b>Start Date</b> and Project <b>End Date</b> to use this feature.';
  5259.             $result['data'] = null;
  5260.             return $result;
  5261.         }
  5262.         $currentRevenuePlannings $project->getRevenuePlannings()->toArray();
  5263.         $dateInterval $endDate->diff($startDate);
  5264.         // $numMonths = ($dateInterval->y * 12) + $dateInterval->m + 1;
  5265.         $yearsInMonths $dateInterval->12;
  5266.         $months $dateInterval->m;
  5267.         $days $dateInterval->d;
  5268.         if ($days 0) {
  5269.             $months++;
  5270.         }
  5271.         $numMonths $yearsInMonths $months;
  5272.         $entityManager $this->entityManager;
  5273.         // Calculate the average amount for each month
  5274.         // $averageAmount = $numMonths > 0 ? floatval($estimatedProfit / $numMonths) : 0;
  5275.         // $averageAmountUsd = $numMonths > 0 ? floatval($estimatedProfitUsd / $numMonths) : 0;
  5276.         $averageAmount $numMonths floor($estimatedProfit $numMonths) : 0;
  5277.         $averageAmountUsd $numMonths floor($estimatedProfitUsd $numMonths) : 0;
  5278.         $differenceAmount $estimatedProfit - ($averageAmount $numMonths);
  5279.         $differenceAmountUsd $estimatedProfitUsd - ($averageAmountUsd $numMonths);
  5280.         if (empty($currentRevenuePlannings)) {
  5281.             for ($i 0$i $numMonths$i++) {
  5282.                 $currentMonth $startDate->format('m');
  5283.                 $currentYear $startDate->format('Y');
  5284.                 $revenuePlanning = new RevenuePlanning();
  5285.                 if ($i === ($numMonths 1)) {
  5286.                     $amount $averageAmount $differenceAmount;
  5287.                     $amountUsd $averageAmountUsd $differenceAmountUsd;
  5288.                 } else {
  5289.                     $amount $averageAmount;
  5290.                     $amountUsd $averageAmountUsd;
  5291.                 }
  5292.                 $revenuePlanning
  5293.                     ->setMonth($currentMonth)
  5294.                     ->setYear($currentYear)
  5295.                     ->setAmount($amount)
  5296.                     ->setAmountUsd($amountUsd)
  5297.                     ->setCreatedAt(new \DateTimeImmutable())
  5298.                     ->setProject($project);
  5299.                 $entityManager->persist($revenuePlanning);
  5300.                 $currentRevenuePlannings[] = $revenuePlanning;
  5301.                 $startDate->add(new \DateInterval('P1M'));
  5302.             }
  5303.             $entityManager->flush();
  5304.             $project $this->projectRepository->find($project->getId());
  5305.             $entityManager->refresh($project);
  5306.             $result['data'] = $project;
  5307.             return $result;
  5308.         }
  5309.         $totalAmount array_sum(array_map(fn($entry) => $entry->getAmount(), $currentRevenuePlannings));
  5310.         if (!empty($currentRevenuePlannings) && ($force === true || $totalAmount == 0)) {
  5311.             $i 0;
  5312.             foreach ($currentRevenuePlannings as $entry) {
  5313.                 if ($i === ($numMonths 1)) {
  5314.                     $entry->setAmount($averageAmount $differenceAmount);
  5315.                     $entry->setAmountUsd($averageAmountUsd $differenceAmountUsd);
  5316.                 } else {
  5317.                     $entry->setAmount($averageAmount);
  5318.                     $entry->setAmountUsd($averageAmountUsd);
  5319.                 }
  5320.                 $i++;
  5321.             }
  5322.             $entityManager->flush();
  5323.             $project $this->projectRepository->find($project->getId());
  5324.             $entityManager->refresh($project);
  5325.             $result['data'] = $project;
  5326.             return $result;
  5327.         }
  5328.         // Check if the number of months has been reduced
  5329.         if (count($currentRevenuePlannings) > $numMonths) {
  5330.             $startDateClone = clone $startDate;
  5331.             $endDateClone = clone $endDate;
  5332.             foreach ($currentRevenuePlannings as $entry) {
  5333.                 $entryMonth intval($entry->getMonth());
  5334.                 $entryYear intval($entry->getYear());
  5335.                 $entryDate = new \DateTime("$entryYear-$entryMonth-01");
  5336.                 if ($entryDate >= $startDateClone && $entryDate <= $endDateClone)  continue;
  5337.                 $entityManager->remove($entry);
  5338.             }
  5339.             $entityManager->flush();
  5340.             $currentRevenuePlannings $this->revenuePlanningRepository->findBy(['project' => $project]);
  5341.         }
  5342.         // Calculate the total sum of existing amounts
  5343.         $totalExistingAmount 0;
  5344.         $totalExistingAmountUsd 0;
  5345.         foreach ($currentRevenuePlannings as $existingEntry) {
  5346.             $totalExistingAmount += $existingEntry->getAmount();
  5347.             $totalExistingAmountUsd += $existingEntry->getAmountUsd();
  5348.         }
  5349.         // Calculate the remaining amount to distribute or deduct
  5350.         // $remainingAmount = $estimatedProfit - $totalExistingAmount;
  5351.         // $remainingAmountUsd = $estimatedProfitUsd - $totalExistingAmountUsd;
  5352.         // Update or create Revenue Planning entries based on the number of months
  5353.         for ($i 0$i $numMonths$i++) {
  5354.             $currentMonth $startDate->format('m');
  5355.             $currentYear $startDate->format('Y');
  5356.             $matchingEntry null;
  5357.             foreach ($currentRevenuePlannings as $existingEntry) {
  5358.                 if ($existingEntry->getMonth() === $currentMonth && $existingEntry->getYear() === $currentYear) {
  5359.                     $matchingEntry $existingEntry;
  5360.                     break;
  5361.                 }
  5362.             }
  5363.             if (!$matchingEntry) {
  5364.                 // Create new entry with 0 value
  5365.                 $revenuePlanning = new RevenuePlanning();
  5366.                 $revenuePlanning
  5367.                     ->setMonth($currentMonth)
  5368.                     ->setYear($currentYear)
  5369.                     ->setAmount(0)
  5370.                     ->setAmountUsd(0)
  5371.                     ->setCreatedAt(new \DateTimeImmutable())
  5372.                     ->setProject($project);
  5373.                 $entityManager->persist($revenuePlanning);
  5374.                 $currentRevenuePlannings[] = $revenuePlanning;
  5375.             }
  5376.             $startDate->add(new \DateInterval('P1M'));
  5377.         }
  5378.         /*
  5379.         // Distribute remaining amount if numMonths increased
  5380.         if ($numMonths > count($currentRevenuePlannings)) {
  5381.             foreach ($currentRevenuePlannings as $entry) {
  5382.                 if ($remainingAmount <= 0) {
  5383.                     break;
  5384.                 }
  5385.                 $entry->setAmount($entry->getAmount() + 1);
  5386.                 $remainingAmount--;
  5387.             }
  5388.         }
  5389.         // Distribute remaining USD amount if numMonths increased
  5390.         if ($numMonths > count($currentRevenuePlannings)) {
  5391.             foreach ($currentRevenuePlannings as $entry) {
  5392.                 if ($remainingAmountUsd <= 0) {
  5393.                     break;
  5394.                 }
  5395.                 $entry->setAmountUsd($entry->getAmountUsd() + 1);
  5396.                 $remainingAmountUsd--;
  5397.             }
  5398.         }
  5399.         // Remove or update amounts if numMonths decreased
  5400.         if ($numMonths < count($currentRevenuePlannings)) {
  5401.             $lastEntry = end($currentRevenuePlannings);
  5402.             $lastEntry->setAmount($lastEntry->getAmount() + $remainingAmount);
  5403.             $lastEntry->setAmountUsd($lastEntry->getAmountUsd() + $remainingAmountUsd);
  5404.             array_pop($currentRevenuePlannings); // Remove the last entry if numMonths decreased
  5405.         }
  5406.         */
  5407.         $entityManager->flush();
  5408.         $project $this->projectRepository->find($project->getId());
  5409.         $entityManager->refresh($project);
  5410.         $result['data'] = $project;
  5411.         return $result;
  5412.     }
  5413.     public function calculateIncludedMonths($startDate$endDate)
  5414.     {
  5415.         $currentDate = new \DateTime();
  5416.         $currentMonth = (int) $currentDate->format('m'); // 8
  5417.         $currentYear = (int) $currentDate->format('Y'); // 2023
  5418.         $fytdStartMonth 11// November
  5419.         $fytdEndMonth 10;   // October
  5420.         // Adjust the fiscal year based on the current month
  5421.         $fytdYear = ($currentMonth $fytdStartMonth) ? $currentYear $currentYear;
  5422.         $fytdStartDate = new \DateTime();
  5423.         $fytdStartDate->setDate($fytdYear$fytdStartMonth1);
  5424.         $fytdEndDate = new \DateTime();
  5425.         $fytdEndDate->setDate($fytdYear 1$fytdEndMonth31);
  5426.         // Convert start and end dates to DateTime objects
  5427.         // $start = new \DateTime($startDate);
  5428.         // $end = new \DateTime($endDate);
  5429.         $start $startDate;
  5430.         $end $endDate;
  5431.         $includedMonths 0;
  5432.         // Iterate through months and check if they are within FYTD
  5433.         while ($start <= $end) {
  5434.             if ($start >= $fytdStartDate && $start <= $fytdEndDate) {
  5435.                 $includedMonths++;
  5436.             }
  5437.             $start->modify('+1 month');
  5438.         }
  5439.         return $includedMonths;
  5440.     }
  5441.     public function getEmailLogFeedback($emailPic$title)
  5442.     {
  5443.         $emailLogs $this->emailCollectorRepository->findByToAddressAndTitle($emailPic$title);
  5444.         return $emailLogs;
  5445.     }
  5446. }