src/Service/ProjectService.php line 2821

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.     public function exportProjectRevenueForecast($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $isCashflow = true, $_target)
  2225.     {
  2226.         $startDateRange = date("d-M-Y", strtotime($startDate));
  2227.         $endDateRange = date("d-M-Y", strtotime($endDate));
  2228.         $spreadsheet = new Spreadsheet();
  2229.         $sheet = $spreadsheet->getActiveSheet()->setTitle($isCashflow ? 'Cashflow Forecast' : 'Revenue Recognition');
  2230.         $sheet->setCellValue('A1', 'Today\'s Date');
  2231.         $sheet->setCellValue('A2', 'From');
  2232.         $sheet->setCellValue('A3', 'To');
  2233.         $sheet->setCellValue('B1', date('d-M-Y'));
  2234.         $sheet->setCellValue('B2', $startDateRange);
  2235.         $sheet->setCellValue('B3', $endDateRange);
  2236.         // Define Header Total
  2237.         $sheet->setCellValue('A5', 'Total');
  2238.         $sheet->setCellValue('I5', 'Total Est. Project Billings');
  2239.         $sheet->setCellValue('J5', 'Total Est. Project Billings FYTD');
  2240.         $sheet->setCellValue('K5', 'Total Est. Agency Revenue');
  2241.         $sheet->setCellValue('L5', 'Total Est. Agency Revenue FYTD');
  2242.         $sheet->setCellValue('A6', 'Total Planned Revenue (LEADS + CONFIRMED)');
  2243.         $sheet->setCellValue('A7', 'Total CONFIRMED Revenue');
  2244.         $sheet->setCellValue('A8', 'Total LEADS Revenue');
  2245.         $sheet->mergeCells('A5:H5');
  2246.         $sheet->mergeCells('A6:H6');
  2247.         $sheet->mergeCells('A7:H7');
  2248.         $sheet->mergeCells('A8:H8');
  2249.         // Define Header Data
  2250.         $sheet->setCellValue('A9', 'Project ID');
  2251.         $sheet->setCellValue('B9', 'Client Name');
  2252.         $sheet->setCellValue('C9', 'Client Industry');
  2253.         $sheet->setCellValue('D9', 'Project Name');
  2254.         $sheet->setCellValue('E9', 'Project Classification');
  2255.         $sheet->setCellValue('F9', 'Project Status');
  2256.         $sheet->setCellValue('G9', 'PIC');
  2257.         $sheet->setCellValue('H9', '% Likely to Win');
  2258.         $sheet->setCellValue('I9', 'Est. Project Billings');
  2259.         $sheet->setCellValue('J9', 'Est. Project Billings FYTD');
  2260.         $sheet->setCellValue('K9', 'Est. Agency Revenue');
  2261.         $sheet->setCellValue('L9', 'Est. Agency Revenue FYTD');
  2262.         $lastCol = 'L';
  2263.         $sheet->freezePane('A10');
  2264.         $sheet->freezePane('C10');
  2265.         $sheet->getDefaultColumnDimension()->setWidth(25);
  2266.         $sheet->getColumnDimension('A')->setWidth(11);
  2267.         $sheet->getColumnDimension('H')->setWidth(15);
  2268.         $sheet->getColumnDimension('I')->setWidth(17);
  2269.         $sheet->getColumnDimension('J')->setWidth(17);
  2270.         $sheet->getColumnDimension('K')->setWidth(17);
  2271.         $sheet->getColumnDimension('L')->setWidth(17);
  2272.         $sheet->getStyle("A10:" . $lastCol . "10")->getFont()->setBold(false);
  2273.         $sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setWrapText(true);
  2274.         $sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2275.         $filename = $isCashflow ? "Cashflow_Forecast_Report" : "Revenue_Recognition_Report";
  2276.         $filename .= $startDate ? "_" . urlencode($startDate) : "";
  2277.         $filename .= $endDate ? "-" . urlencode($endDate) : "";
  2278.         $filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
  2279.         $projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
  2280.         $row = $sheet->getHighestRow();
  2281.         $totalEstProjectBillings = [
  2282.             'total' => 0,
  2283.             'confirmed' => 0,
  2284.             'lead' => 0
  2285.         ];
  2286.         $totalEstAgencyRevenue = [
  2287.             'total' => 0,
  2288.             'confirmed' => 0,
  2289.             'lead' => 0
  2290.         ];
  2291.         foreach ($projectsList as $project) {
  2292.             $picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
  2293.             $sheet->setCellValue('A' . $row, $project['generatedId']);
  2294.             $sheet->setCellValue('B' . $row, $project['clientName']);
  2295.             $clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
  2296.             $clientIndustries = [];
  2297.             if ($clientIndustryClassification) {
  2298.                 foreach ($clientIndustryClassification as $industryClass) {
  2299.                     array_push($clientIndustries, $industryClass->getName());
  2300.                 }
  2301.             }
  2302.             $sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
  2303.             $projectTypes = $project[0]->getprojectTypes();
  2304.             $projectClassification = [];
  2305.             if ($projectTypes) {
  2306.                 foreach ($projectTypes as $projectType) {
  2307.                     array_push($projectClassification, $projectType->getName());
  2308.                 }
  2309.             }
  2310.             $sheet->setCellValue('D' . $row, $project['name']);
  2311.             $sheet->getCell('D' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
  2312.             $sheet->setCellValue('E' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
  2313.             $sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
  2314.             $sheet->setCellValue('G' . $row, $picName);
  2315.             $sheet->setCellValue('H' . $row, $project[0]->getProbabilityText());
  2316.             $probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
  2317.             $estProjectBillings = $project['type'] == 'LEAD' ? $project[0]->getPlannedRevenueUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
  2318.             $estAgencyRevenue = $project['type'] == 'LEAD' ? $project[0]->getEstimatedProfitUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD();
  2319.             if ($project['type'] == 'CONFIRMED') {
  2320.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2321.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2322.             } elseif ($project['type'] == 'LEAD') {
  2323.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2324.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2325.             }
  2326.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2327.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2328.             $sheet->setCellValue('I' . $row, $estProjectBillings);
  2329.             $sheet->setCellValue('K' . $row, $estAgencyRevenue);
  2330.             $row++;
  2331.         }
  2332.         $sheet->setCellValue('I6', $totalEstProjectBillings['total']);
  2333.         $sheet->setCellValue('I7', $totalEstProjectBillings['confirmed']);
  2334.         $sheet->setCellValue('I8', $totalEstProjectBillings['lead']);
  2335.         $sheet->setCellValue('K6', $totalEstAgencyRevenue['total']);
  2336.         $sheet->setCellValue('K7', $totalEstAgencyRevenue['confirmed']);
  2337.         $sheet->setCellValue('K8', $totalEstAgencyRevenue['lead']);
  2338.         // define breakdown
  2339.         $column = [];
  2340.         for ($i = 65; $i <= 90; $i++) {
  2341.             $column[] = chr($i);
  2342.         }
  2343.         for ($i = 65; $i <= 90; $i++) {
  2344.             for ($j = 65; $j <= 90; $j++) {
  2345.                 $column[] = chr($i) . chr($j);
  2346.             }
  2347.         }
  2348.         // define column months
  2349.         $monthColumn = [];
  2350.         foreach ($projectsList as $project) {
  2351.             if ($project['lead'] == '8') {
  2352.                 $revenues = $this->monthlyRevenues($project[0], $isCashflow);
  2353.                 $newRevenues = [];
  2354.                 foreach ($revenues as $oldKey => $value) {
  2355.                     list($month, $year) = explode('-', $oldKey);
  2356.                     $parsedMonth = date_parse($month);
  2357.                     $newKey = sprintf('%02d-%s', $parsedMonth['month'], $year);
  2358.                     $newRevenues[$newKey] = $value;
  2359.                 }
  2360.                 foreach ($newRevenues as $newRevenueKey => $value) {
  2361.                     $month = $newRevenueKey;
  2362.                     if (!in_array($month, $monthColumn)) {
  2363.                         $monthColumn[] = $month;
  2364.                     }
  2365.                 }
  2366.             } else {
  2367.                 $revenuePlannings = $project[0]->getRevenuePlannings();
  2368.                 foreach ($revenuePlannings as $revenuePlanning) {
  2369.                     $month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
  2370.                     if (!in_array($month, $monthColumn)) {
  2371.                         $monthColumn[] = $month;
  2372.                     }
  2373.                 }
  2374.             }
  2375.         }
  2376.         // sort
  2377.         usort($monthColumn, function ($a, $b) {
  2378.             $dateA =  \DateTime::createFromFormat('d-m-Y', '01-' . $a);
  2379.             $dateB =  \DateTime::createFromFormat('d-m-Y', '01-' . $b);
  2380.             if ($dateA == $dateB) {
  2381.                 return 0;
  2382.             }
  2383.             return ($dateA < $dateB) ? -1 : 1;
  2384.         });
  2385.         $sortedMonthColumns = array_map(function ($date) {
  2386.             $dateTime = \DateTime::createFromFormat('d-m-Y', '01-' . $date);
  2387.             return $dateTime->format('M-Y');
  2388.         }, $monthColumn);
  2389.         $lastCol = $sheet->getHighestColumn(); // 'L'
  2390.         $key = array_search($lastCol, $column);
  2391.         $cellColumn = []; // breakdown month column based on cell column
  2392.         $i = $key + 1;
  2393.         foreach ($sortedMonthColumns as $monthColumn) {
  2394.             $cellColumn[$i] = $monthColumn;
  2395.             $sheet->setCellValue($column[$i] . "5", $monthColumn);
  2396.             $sheet->setCellValue($column[$i] . "9", $monthColumn);
  2397.             $i++;
  2398.         }
  2399.         $totalColumnBreakdown = [];
  2400.         foreach ($cellColumn as $cell) {
  2401.             $totalColumnBreakdown[$cell]['total'] = 0;
  2402.             $totalColumnBreakdown[$cell]['confirmed'] = 0;
  2403.             $totalColumnBreakdown[$cell]['lead'] = 0;
  2404.         }
  2405.         // fill cell
  2406.         $monthRow = 10;
  2407.         foreach ($projectsList as $project) {
  2408.             foreach ($cellColumn as $cellValue => $value) {
  2409.                 $sheet->setCellValue($column[$cellValue] . $monthRow, '-');
  2410.             }
  2411.             if ($project['lead'] == '8') {
  2412.                 $revenues = $this->monthlyRevenues($project[0], $isCashflow);
  2413.                 foreach ($revenues as $key => $value) {
  2414.                     $month = $key;
  2415.                     $cell = array_search($month, $cellColumn);
  2416.                     $sheet->setCellValue($column[$cell] . $monthRow, $value['totalUsd']);
  2417.                     if ($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
  2418.                     $totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
  2419.                 }
  2420.             } else {
  2421.                 $probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
  2422.                 $revenuePlannings = $project[0]->getRevenuePlannings()->toArray();
  2423.                 if (count($revenuePlannings) > 0) {
  2424.                     foreach ($revenuePlannings as $revenuePlanning) {
  2425.                         $month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
  2426.                         $month =  \DateTime::createFromFormat('d-m-Y', '01-' . $month)->format('M-Y');
  2427.                         $cell = array_search($month, $cellColumn);
  2428.                         $revenueAmountUsd = $project['type'] == 'LEAD' ? $revenuePlanning->getAmountUsd() * $probabilityPercent : $revenuePlanning->getAmountUsd();
  2429.                         $sheet->setCellValue($column[$cell] . $monthRow, $revenueAmountUsd);
  2430.                         if ($project['type'] == 'LEAD')  $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
  2431.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  2432.                         $totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
  2433.                     }
  2434.                 }
  2435.             }
  2436.             $monthRow++;
  2437.         }
  2438.         // fill total cell
  2439.         foreach ($cellColumn as $key => $cellCol) {
  2440.             for ($i = 6; $i <= 8; $i++) {
  2441.                 $type = $i == 6 ? 'total' : ($i == 7 ? 'confirmed' : 'lead');
  2442.                 $sheet->setCellValue($column[$key] . $i, $totalColumnBreakdown[$cellCol][$type]);
  2443.             }
  2444.         }
  2445.         // FYTD = 1st nov22 - 31st oct23 
  2446.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  2447.         $currentYear = date('Y');
  2448.         $fytdStartDate = new \DateTime($currentYear - 1 . '-11-01');
  2449.         $fytdEndDate = new \DateTime($currentYear . '-10-31');
  2450.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  2451.         $totalEstProjectBillingsFYTD = [
  2452.             'total' => 0,
  2453.             'confirmed' => 0,
  2454.             'lead' => 0
  2455.         ];
  2456.         $totalEstAgencyRevenueFYTD = [
  2457.             'total' => 0,
  2458.             'confirmed' => 0,
  2459.             'lead' => 0
  2460.         ];
  2461.         $row = 10;
  2462.         foreach ($projectsList as $project) {
  2463.             $totalMonths = 0;
  2464.             $numMonthsFYTD = 0;
  2465.             if (!empty($project[0]->getStartDate()) && !empty($project[0]->getEndDate())) {
  2466.                 $dateInterval = $project[0]->getEndDate()->diff($project[0]->getStartDate());
  2467.                 $yearsInMonths = $dateInterval->y * 12;
  2468.                 $months = $dateInterval->m;
  2469.                 $days = $dateInterval->d;
  2470.                 if ($days > 0) {
  2471.                     $months++;
  2472.                 }
  2473.                 $totalMonths = $yearsInMonths + $months;
  2474.                 if ($dateInterval->y === 0 && $dateInterval->m === 0 && $dateInterval->d === 0) {
  2475.                     $totalMonths = 1;
  2476.                 }
  2477.                 $numMonthsFYTD = $this->calculateIncludedMonths($project[0]->getStartDate(), $project[0]->getEndDate());
  2478.             } else {
  2479.                 $totalMonths = 1;
  2480.                 $numMonthsFYTD = 1;
  2481.             }
  2482.             $probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
  2483.             $estProjectBillings = $project['type'] == 'LEAD' ? $project[0]->getPlannedRevenueUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
  2484.             $estAgencyRevenue = $project['type'] == 'LEAD' ? $project[0]->getEstimatedProfitUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD();
  2485.             $formulaBillings = $totalMonths == $numMonthsFYTD ? $estProjectBillings : ($estProjectBillings / $totalMonths) + ($estProjectBillings / $totalMonths * $numMonthsFYTD);
  2486.             $formulaRevenue = $totalMonths == $numMonthsFYTD ? $estAgencyRevenue : ($estAgencyRevenue / $totalMonths) + ($estAgencyRevenue / $totalMonths * $numMonthsFYTD);
  2487.             if ($project['type'] == 'CONFIRMED') {
  2488.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  2489.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  2490.             } elseif ($project['type'] == 'LEAD') {
  2491.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  2492.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  2493.             }
  2494.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  2495.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  2496.             $sheet->setCellValue('J' . $row, $formulaBillings);
  2497.             $sheet->setCellValue('L' . $row, $formulaRevenue);
  2498.             $row++;
  2499.         }
  2500.         
  2501.         $sheet->setCellValue('J6', $totalEstProjectBillingsFYTD['total']);
  2502.         $sheet->setCellValue('J7', $totalEstProjectBillingsFYTD['confirmed']);
  2503.         $sheet->setCellValue('J8', $totalEstProjectBillingsFYTD['lead']);
  2504.         $sheet->setCellValue('L6', $totalEstAgencyRevenueFYTD['total']);
  2505.         $sheet->setCellValue('L7', $totalEstAgencyRevenueFYTD['confirmed']);
  2506.         $sheet->setCellValue('L8', $totalEstAgencyRevenueFYTD['lead']);
  2507.         $sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  2508.         $sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2509.         $sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2510.         $sheet->getStyle("A6:" . $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
  2511.         $sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
  2512.         $sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2513.         $sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2514.         $sheet->setAutoFilter('A9:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
  2515.         $sheet->getStyle("D1:D" . $sheet->getHighestRow())->getFont()->setUnderline(true);
  2516.         // $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2517.         $sheet->getStyle('I6:' . $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2518.         // Write the file
  2519.         $writer = new Xlsx($spreadsheet);
  2520.         $writer->save($filename);
  2521.         if ($_target == 'google') {
  2522.             $gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
  2523.             if ($gsheetURL) {
  2524.                 unlink($filename);
  2525.                 return new RedirectResponse($gsheetURL, 302);
  2526.             }
  2527.         } else {
  2528.             $response = new Response();
  2529.             $response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  2530.             $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
  2531.             $response->setContent(file_get_contents($filename));
  2532.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  2533.             $response->headers->set('Content-Transfer-Encoding', 'binary');
  2534.             $response->headers->set('Pragma', 'no-cache');
  2535.             $response->headers->set('Expires', '0');
  2536.             unlink($filename);
  2537.             return $response;
  2538.             exit;
  2539.         }
  2540.     }
  2541.     */
  2542.     // filter based on INV Date
  2543.     public function exportProjectRevenueForecast($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$isCashflow true$_target)
  2544.     {
  2545.         $startDateRange date("d-M-Y"strtotime($startDate));
  2546.         $endDateRange date("d-M-Y"strtotime($endDate));
  2547.         $spreadsheet = new Spreadsheet();
  2548.         $sheet $spreadsheet->getActiveSheet()->setTitle($isCashflow 'Cashflow Forecast' 'Revenue Forecast');
  2549.         $sheet->setCellValue('A1''Today\'s Date');
  2550.         $sheet->setCellValue('A2''From ' . ($isCashflow '(Invoice Due Date)' '(Invoice Date)'));
  2551.         $sheet->setCellValue('A3''To ' . ($isCashflow '(Invoice Due Date)' '(Invoice Date)'));
  2552.         $sheet->setCellValue('C1'date('d-M-Y'));
  2553.         $sheet->setCellValue('C2'$startDateRange);
  2554.         $sheet->setCellValue('C3'$endDateRange);
  2555.         // Define Header Total
  2556.         $sheet->setCellValue('A5''Total');
  2557.         $sheet->setCellValue('I5''Total Est. Project Billings');
  2558.         $sheet->setCellValue('J5''Total Est. Project Billings FYTD');
  2559.         $sheet->setCellValue('K5''Total Est. Agency Revenue');
  2560.         $sheet->setCellValue('L5''Total Est. Agency Revenue FYTD');
  2561.         $sheet->setCellValue('A6''Total Planned Revenue (LEADS + CONFIRMED)');
  2562.         $sheet->setCellValue('A7''Total CONFIRMED Revenue');
  2563.         $sheet->setCellValue('A8''Total LEADS Revenue');
  2564.         $sheet->mergeCells('A5:H5');
  2565.         $sheet->mergeCells('A6:H6');
  2566.         $sheet->mergeCells('A7:H7');
  2567.         $sheet->mergeCells('A8:H8');
  2568.         // Define Header Data
  2569.         $sheet->setCellValue('A9''Project ID');
  2570.         $sheet->setCellValue('B9''Client Name');
  2571.         $sheet->setCellValue('C9''Client Industry');
  2572.         $sheet->setCellValue('D9''Project Name');
  2573.         $sheet->setCellValue('E9''Project Classification');
  2574.         $sheet->setCellValue('F9''Project Status');
  2575.         $sheet->setCellValue('G9''PIC');
  2576.         $sheet->setCellValue('H9''% Likely to Win');
  2577.         $sheet->setCellValue('I9''Est. Project Billings');
  2578.         $sheet->setCellValue('J9''Est. Project Billings FYTD');
  2579.         $sheet->setCellValue('K9''Est. Agency Revenue');
  2580.         $sheet->setCellValue('L9''Est. Agency Revenue FYTD');
  2581.         $lastCol $sheet->getHighestColumn();
  2582.         $sheet->freezePane('A10');
  2583.         $sheet->freezePane('D10');
  2584.         $sheet->getDefaultColumnDimension()->setWidth(25);
  2585.         $sheet->getColumnDimension('A')->setWidth(11);
  2586.         $sheet->getColumnDimension('H')->setWidth(15);
  2587.         $sheet->getColumnDimension('I')->setWidth(17);
  2588.         $sheet->getColumnDimension('J')->setWidth(17);
  2589.         $sheet->getColumnDimension('K')->setWidth(17);
  2590.         $sheet->getColumnDimension('L')->setWidth(17);
  2591.         $sheet->getStyle("A10:" $lastCol "10")->getFont()->setBold(false);
  2592.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setWrapText(true);
  2593.         $sheet->getStyle("A10:" $lastCol "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2594.         $filename $isCashflow "Cashflow_Forecast_Report" "Revenue_Forecast_Report";
  2595.         $filename .= $startDate "_" urlencode($startDate) : "";
  2596.         $filename .= $endDate "-" urlencode($endDate) : "";
  2597.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  2598.         // $projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
  2599.         $projectsList = [];
  2600.         $projectIds = [];
  2601.         $invoiceList $this->invoiceRepository->findByPage(09999"""DESC"""""""$startDate$endDate$isCashflow);
  2602.         foreach ($invoiceList as $invoice) {
  2603.             $salesOrderInvoices $invoice->getSalesOrderInvoices()->toArray();
  2604.             foreach ($salesOrderInvoices as $salesOrderInvoice) {
  2605.                 $project $salesOrderInvoice->getProject();
  2606.                 $projectId $project->getId();
  2607.                 if (!in_array($projectId$projectIds)) {
  2608.                     $projectsList[] = $project;
  2609.                     $projectIds[] = $projectId;
  2610.                 }
  2611.             }
  2612.         }
  2613.         $row $sheet->getHighestRow();
  2614.         $totalEstProjectBillings = [
  2615.             'total' => 0,
  2616.             'confirmed' => 0,
  2617.             'lead' => 0
  2618.         ];
  2619.         $totalEstAgencyRevenue = [
  2620.             'total' => 0,
  2621.             'confirmed' => 0,
  2622.             'lead' => 0
  2623.         ];
  2624.         foreach ($projectsList as $project) {
  2625.             $picName $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
  2626.             $sheet->setCellValue('A' $row$project->getGeneratedId());
  2627.             $sheet->setCellValue('B' $row$project->getClient() ? $project->getClient()->getName() : '');
  2628.             $clientIndustryClassification $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
  2629.             $clientIndustries = [];
  2630.             if ($clientIndustryClassification) {
  2631.                 foreach ($clientIndustryClassification as $industryClass) {
  2632.                     array_push($clientIndustries$industryClass->getName());
  2633.                 }
  2634.             }
  2635.             $sheet->setCellValue('C' $row$clientIndustries implode(', '$clientIndustries) : '-');
  2636.             $projectTypes $project->getProjectTypes();
  2637.             $projectClassification = [];
  2638.             if ($projectTypes) {
  2639.                 foreach ($projectTypes as $projectType) {
  2640.                     array_push($projectClassification$projectType->getName());
  2641.                 }
  2642.             }
  2643.             $sheet->setCellValue('D' $row$project->getName());
  2644.             $sheet->getCell('D' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project->getId());
  2645.             $sheet->setCellValue('E' $row$projectClassification implode(', '$projectClassification) : '-');
  2646.             $sheet->setCellValue('F' $row$project->getType() == 'LEAD' $project->getLead() . ' - ' $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
  2647.             $sheet->setCellValue('G' $row$picName);
  2648.             $sheet->setCellValue('H' $row$project->getProbabilityText());
  2649.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2650.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2651.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2652.             if ($project->getType() == 'CONFIRMED') {
  2653.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2654.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2655.             } elseif ($project->getType() == 'LEAD') {
  2656.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2657.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2658.             }
  2659.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2660.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2661.             $sheet->setCellValue('I' $row$estProjectBillings);
  2662.             $sheet->setCellValue('K' $row$estAgencyRevenue);
  2663.             $row++;
  2664.         }
  2665.         $sheet->setCellValue('I6'$totalEstProjectBillings['total']);
  2666.         $sheet->setCellValue('I7'$totalEstProjectBillings['confirmed']);
  2667.         $sheet->setCellValue('I8'$totalEstProjectBillings['lead']);
  2668.         $sheet->setCellValue('K6'$totalEstAgencyRevenue['total']);
  2669.         $sheet->setCellValue('K7'$totalEstAgencyRevenue['confirmed']);
  2670.         $sheet->setCellValue('K8'$totalEstAgencyRevenue['lead']);
  2671.         // define breakdown
  2672.         $column = [];
  2673.         for ($i 65$i <= 90$i++) {
  2674.             $column[] = chr($i);
  2675.         }
  2676.         for ($i 65$i <= 90$i++) {
  2677.             for ($j 65$j <= 90$j++) {
  2678.                 $column[] = chr($i) . chr($j);
  2679.             }
  2680.         }
  2681.         // define column months
  2682.         $monthColumn = [];
  2683.         foreach ($projectsList as $project) {
  2684.             if ($project->getLead() == '8') {
  2685.                 $revenues $this->monthlyRevenuesNew($project$isCashflow$startDate$endDate);
  2686.                 $newRevenues = [];
  2687.                 foreach ($revenues as $oldKey => $value) {
  2688.                     list($month$year) = explode('-'$oldKey);
  2689.                     $parsedMonth date_parse($month);
  2690.                     $newKey sprintf('%02d-%s'$parsedMonth['month'], $year);
  2691.                     $newRevenues[$newKey] = $value;
  2692.                 }
  2693.                 foreach ($newRevenues as $newRevenueKey => $value) {
  2694.                     $month $newRevenueKey;
  2695.                     if (!in_array($month$monthColumn)) {
  2696.                         $monthColumn[] = $month;
  2697.                     }
  2698.                 }
  2699.             } else {
  2700.                 $revenuePlannings $project->getRevenuePlannings();
  2701.                 foreach ($revenuePlannings as $revenuePlanning) {
  2702.                     $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2703.                     if (!in_array($month$monthColumn)) {
  2704.                         $monthColumn[] = $month;
  2705.                     }
  2706.                 }
  2707.             }
  2708.         }
  2709.         // sort
  2710.         usort($monthColumn, function ($a$b) {
  2711.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  2712.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  2713.             if ($dateA == $dateB) {
  2714.                 return 0;
  2715.             }
  2716.             return ($dateA $dateB) ? -1;
  2717.         });
  2718.         $sortedMonthColumns array_map(function ($date) {
  2719.             $dateTime \DateTime::createFromFormat('d-m-Y''01-' $date);
  2720.             return $dateTime->format('M-Y');
  2721.         }, $monthColumn);
  2722.         // dd($monthColumn);
  2723.         $lastCol $sheet->getHighestColumn(); // 'L'
  2724.         $key array_search($lastCol$column);
  2725.         $cellColumn = []; // breakdown month column based on cell column
  2726.         $i $key 1;
  2727.         foreach ($sortedMonthColumns as $monthColumn) {
  2728.             $cellColumn[$i] = $monthColumn;
  2729.             $sheet->setCellValue($column[$i] . "5"$monthColumn);
  2730.             $sheet->setCellValue($column[$i] . "9"$monthColumn);
  2731.             $i++;
  2732.         }
  2733.         $totalColumnBreakdown = [];
  2734.         foreach ($cellColumn as $cell) {
  2735.             $totalColumnBreakdown[$cell]['total'] = 0;
  2736.             $totalColumnBreakdown[$cell]['confirmed'] = 0;
  2737.             $totalColumnBreakdown[$cell]['lead'] = 0;
  2738.         }
  2739.         // fill cell
  2740.         $monthRow 10;
  2741.         foreach ($projectsList as $project) {
  2742.             foreach ($cellColumn as $cellValue => $value) {
  2743.                 $sheet->setCellValue($column[$cellValue] . $monthRow'-');
  2744.             }
  2745.             if ($project->getLead() == '8') {
  2746.                 $revenues $this->monthlyRevenuesNew($project$isCashflow$startDate$endDate);
  2747.                 foreach ($revenues as $key => $value) {
  2748.                     $month $key;
  2749.                     $cell array_search($month$cellColumn);
  2750.                     $sheet->setCellValue($column[$cell] . $monthRow$value['totalUsd']);
  2751.                     if ($project->getType() == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
  2752.                     $totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
  2753.                 }
  2754.             } else {
  2755.                 $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2756.                 $revenuePlannings $project->getRevenuePlannings()->toArray();
  2757.                 if (count($revenuePlannings) > 0) {
  2758.                     foreach ($revenuePlannings as $revenuePlanning) {
  2759.                         $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  2760.                         $month =  \DateTime::createFromFormat('d-m-Y''01-' $month)->format('M-Y');
  2761.                         $cell array_search($month$cellColumn);
  2762.                         $revenueAmountUsd $project->getType() == 'LEAD' $revenuePlanning->getAmountUsd() * $probabilityPercent $revenuePlanning->getAmountUsd();
  2763.                         $sheet->setCellValue($column[$cell] . $monthRow$revenueAmountUsd);
  2764.                         if ($project->getType() == 'LEAD')  $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
  2765.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  2766.                         $totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
  2767.                     }
  2768.                 }
  2769.             }
  2770.             $monthRow++;
  2771.         }
  2772.         // fill total cell
  2773.         foreach ($cellColumn as $key => $cellCol) {
  2774.             for ($i 6$i <= 8$i++) {
  2775.                 $type $i == 'total' : ($i == 'confirmed' 'lead');
  2776.                 $sheet->setCellValue($column[$key] . $i$totalColumnBreakdown[$cellCol][$type]);
  2777.             }
  2778.         }
  2779.         // FYTD = 1st nov22 - 31st oct23 
  2780.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  2781.         $currentYear date('Y');
  2782.         $fytdStartDate = new \DateTime($currentYear '-11-01');
  2783.         $fytdEndDate = new \DateTime($currentYear '-10-31');
  2784.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  2785.         $totalEstProjectBillingsFYTD = [
  2786.             'total' => 0,
  2787.             'confirmed' => 0,
  2788.             'lead' => 0
  2789.         ];
  2790.         $totalEstAgencyRevenueFYTD = [
  2791.             'total' => 0,
  2792.             'confirmed' => 0,
  2793.             'lead' => 0
  2794.         ];
  2795.         $row 10;
  2796.         foreach ($projectsList as $project) {
  2797.             $totalMonths 0;
  2798.             $numMonthsFYTD 0;
  2799.             if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
  2800.                 $dateInterval $project->getEndDate()->diff($project->getStartDate());
  2801.                 $yearsInMonths $dateInterval->12;
  2802.                 $months $dateInterval->m;
  2803.                 $days $dateInterval->d;
  2804.                 if ($days 0) {
  2805.                     $months++;
  2806.                 }
  2807.                 $totalMonths $yearsInMonths $months;
  2808.                 if ($dateInterval->=== && $dateInterval->=== && $dateInterval->=== 0) {
  2809.                     $totalMonths 1;
  2810.                 }
  2811.                 $numMonthsFYTD $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
  2812.             } else {
  2813.                 $totalMonths 1;
  2814.                 $numMonthsFYTD 1;
  2815.             }
  2816.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2817.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2818.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2819.             $formulaBillings $totalMonths == $numMonthsFYTD $estProjectBillings : ($estProjectBillings $totalMonths) + ($estProjectBillings $totalMonths $numMonthsFYTD);
  2820.             $formulaRevenue $totalMonths == $numMonthsFYTD $estAgencyRevenue : ($estAgencyRevenue $totalMonths) + ($estAgencyRevenue $totalMonths $numMonthsFYTD);
  2821.             if ($project->getType() == 'CONFIRMED') {
  2822.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  2823.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  2824.             } elseif ($project->getType() == 'LEAD') {
  2825.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  2826.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  2827.             }
  2828.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  2829.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  2830.             $sheet->setCellValue('J' $row$formulaBillings);
  2831.             $sheet->setCellValue('L' $row$formulaRevenue);
  2832.             $row++;
  2833.         }
  2834.         
  2835.         $sheet->setCellValue('J6'$totalEstProjectBillingsFYTD['total']);
  2836.         $sheet->setCellValue('J7'$totalEstProjectBillingsFYTD['confirmed']);
  2837.         $sheet->setCellValue('J8'$totalEstProjectBillingsFYTD['lead']);
  2838.         $sheet->setCellValue('L6'$totalEstAgencyRevenueFYTD['total']);
  2839.         $sheet->setCellValue('L7'$totalEstAgencyRevenueFYTD['confirmed']);
  2840.         $sheet->setCellValue('L8'$totalEstAgencyRevenueFYTD['lead']);
  2841.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  2842.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2843.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2844.         $sheet->getStyle("A6:" $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
  2845.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
  2846.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2847.         $sheet->getStyle("A9:" $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  2848.         $sheet->setAutoFilter('A9:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  2849.         $sheet->getStyle("D1:D" $sheet->getHighestRow())->getFont()->setUnderline(true);
  2850.         // $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  2851.         $sheet->getStyle('I6:' $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  2852.         // LEAD Revenue Projection
  2853.         $leadSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Revenue Projection');
  2854.         $spreadsheet->addSheet($leadSheet1);
  2855.         $leadSheet->setCellValue('A1''Today\'s Date');
  2856.         $leadSheet->setCellValue('A2''From (Project Start Date)');
  2857.         $leadSheet->setCellValue('A3''To (Project Start Date)');
  2858.         $leadSheet->setCellValue('C1'date('d-M-Y'));
  2859.         $leadSheet->setCellValue('C2'$startDateRange);
  2860.         $leadSheet->setCellValue('C3'$endDateRange);
  2861.         // Define Header Total
  2862.         $leadSheet->setCellValue('A5''Total');
  2863.         $leadSheet->setCellValue('I5''Total Est. Project Billings');
  2864.         $leadSheet->setCellValue('J5''Total Est. Project Billings FYTD');
  2865.         $leadSheet->setCellValue('K5''Total Est. Agency Revenue');
  2866.         $leadSheet->setCellValue('L5''Total Est. Agency Revenue FYTD');
  2867.         $leadSheet->setCellValue('A6''Total Planned Revenue (LEADS + CONFIRMED)');
  2868.         $leadSheet->setCellValue('A7''Total CONFIRMED Revenue');
  2869.         $leadSheet->setCellValue('A8''Total LEADS Revenue');
  2870.         $leadSheet->mergeCells('A5:H5');
  2871.         $leadSheet->mergeCells('A6:H6');
  2872.         $leadSheet->mergeCells('A7:H7');
  2873.         $leadSheet->mergeCells('A8:H8');
  2874.         // Define Header Data
  2875.         $leadSheet->setCellValue('A9''Project ID');
  2876.         $leadSheet->setCellValue('B9''Client Name');
  2877.         $leadSheet->setCellValue('C9''Client Industry');
  2878.         $leadSheet->setCellValue('D9''Project Name');
  2879.         $leadSheet->setCellValue('E9''Project Classification');
  2880.         $leadSheet->setCellValue('F9''Project Status');
  2881.         $leadSheet->setCellValue('G9''PIC');
  2882.         $leadSheet->setCellValue('H9''% Likely to Win');
  2883.         $leadSheet->setCellValue('I9''Est. Project Billings');
  2884.         $leadSheet->setCellValue('J9''Est. Project Billings FYTD');
  2885.         $leadSheet->setCellValue('K9''Est. Agency Revenue');
  2886.         $leadSheet->setCellValue('L9''Est. Agency Revenue FYTD');
  2887.         $lastColx $leadSheet->getHighestColumn();
  2888.         $leadSheet->freezePane('A10');
  2889.         $leadSheet->freezePane('D10');
  2890.         $leadSheet->getDefaultColumnDimension()->setWidth(25);
  2891.         $leadSheet->getColumnDimension('A')->setWidth(11);
  2892.         $leadSheet->getColumnDimension('H')->setWidth(15);
  2893.         $leadSheet->getColumnDimension('I')->setWidth(17);
  2894.         $leadSheet->getColumnDimension('J')->setWidth(17);
  2895.         $leadSheet->getColumnDimension('K')->setWidth(17);
  2896.         $leadSheet->getColumnDimension('L')->setWidth(17);
  2897.         $leadSheet->getStyle("A10:" $lastColx "10")->getFont()->setBold(false);
  2898.         $leadSheet->getStyle("A10:" $lastColx "10")->getAlignment()->setWrapText(true);
  2899.         $leadSheet->getStyle("A10:" $lastColx "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2900.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate'LEAD'$client$status$project$department$retainer$assignedUser$showDeleted);
  2901.         // $projectsList = [];
  2902.         // $projectIds = [];
  2903.         // $invoiceList = $this->invoiceRepository->findByPage(0, 9999, "", "DESC", "", "PAID", "", $startDate, $endDate);
  2904.         // foreach ($invoiceList as $invoice) {
  2905.         //     $salesOrderInvoices = $invoice->getSalesOrderInvoices()->toArray();
  2906.         //     foreach ($salesOrderInvoices as $salesOrderInvoice) {
  2907.         //         $project = $salesOrderInvoice->getProject();
  2908.         //         $projectId = $project->getId();
  2909.         //         if (!in_array($projectId, $projectIds)) {
  2910.         //             $projectsList[] = $project;
  2911.         //             $projectIds[] = $projectId;
  2912.         //         }
  2913.         //     }
  2914.         // }
  2915.         $leadRow $leadSheet->getHighestRow();
  2916.         $totalEstProjectBillings = [
  2917.             'total' => 0,
  2918.             'confirmed' => 0,
  2919.             'lead' => 0
  2920.         ];
  2921.         $totalEstAgencyRevenue = [
  2922.             'total' => 0,
  2923.             'confirmed' => 0,
  2924.             'lead' => 0
  2925.         ];
  2926.         foreach ($projectsList as $project) {
  2927.             $project $project[0];
  2928.             $picName $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
  2929.             $leadSheet->setCellValue('A' $leadRow$project->getGeneratedId());
  2930.             $leadSheet->setCellValue('B' $leadRow$project->getClient() ? $project->getClient()->getName() : '');
  2931.             $clientIndustryClassification $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
  2932.             $clientIndustries = [];
  2933.             if ($clientIndustryClassification) {
  2934.                 foreach ($clientIndustryClassification as $industryClass) {
  2935.                     array_push($clientIndustries$industryClass->getName());
  2936.                 }
  2937.             }
  2938.             $leadSheet->setCellValue('C' $leadRow$clientIndustries implode(', '$clientIndustries) : '-');
  2939.             $projectTypes $project->getProjectTypes();
  2940.             $projectClassification = [];
  2941.             if ($projectTypes) {
  2942.                 foreach ($projectTypes as $projectType) {
  2943.                     array_push($projectClassification$projectType->getName());
  2944.                 }
  2945.             }
  2946.             $leadSheet->setCellValue('D' $leadRow$project->getName());
  2947.             $leadSheet->getCell('D' $leadRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project->getId());
  2948.             $leadSheet->setCellValue('E' $leadRow$projectClassification implode(', '$projectClassification) : '-');
  2949.             $leadSheet->setCellValue('F' $leadRow$project->getType() == 'LEAD' $project->getLead() . ' - ' $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
  2950.             $leadSheet->setCellValue('G' $leadRow$picName);
  2951.             $leadSheet->setCellValue('H' $leadRow$project->getProbabilityText());
  2952.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  2953.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  2954.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  2955.             if ($project->getType() == 'CONFIRMED') {
  2956.                 $totalEstProjectBillings['confirmed'] += $estProjectBillings;
  2957.                 $totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
  2958.             } elseif ($project->getType() == 'LEAD') {
  2959.                 $totalEstProjectBillings['lead'] += $estProjectBillings;
  2960.                 $totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
  2961.             }
  2962.             $totalEstProjectBillings['total'] += $estProjectBillings;
  2963.             $totalEstAgencyRevenue['total'] += $estAgencyRevenue;
  2964.             $leadSheet->setCellValue('I' $leadRow$estProjectBillings);
  2965.             $leadSheet->setCellValue('K' $leadRow$estAgencyRevenue);
  2966.             $leadRow++;
  2967.         }
  2968.         $leadSheet->setCellValue('I6'$totalEstProjectBillings['total']);
  2969.         $leadSheet->setCellValue('I7'$totalEstProjectBillings['confirmed']);
  2970.         $leadSheet->setCellValue('I8'$totalEstProjectBillings['lead']);
  2971.         $leadSheet->setCellValue('K6'$totalEstAgencyRevenue['total']);
  2972.         $leadSheet->setCellValue('K7'$totalEstAgencyRevenue['confirmed']);
  2973.         $leadSheet->setCellValue('K8'$totalEstAgencyRevenue['lead']);
  2974.         // define breakdown
  2975.         $columnx = [];
  2976.         for ($i 65$i <= 90$i++) {
  2977.             $columnx[] = chr($i);
  2978.         }
  2979.         for ($i 65$i <= 90$i++) {
  2980.             for ($j 65$j <= 90$j++) {
  2981.                 $columnx[] = chr($i) . chr($j);
  2982.             }
  2983.         }
  2984.         // define column months
  2985.         $monthColumnx = [];
  2986.         foreach ($projectsList as $project) {
  2987.             $project $project[0];
  2988.             if ($project->getLead() == '8') {
  2989.                 $revenues $this->monthlyRevenues($project$isCashflow);
  2990.                 $newRevenues = [];
  2991.                 foreach ($revenues as $oldKey => $value) {
  2992.                     list($month$year) = explode('-'$oldKey);
  2993.                     $parsedMonth date_parse($month);
  2994.                     $newKey sprintf('%02d-%s'$parsedMonth['month'], $year);
  2995.                     $newRevenues[$newKey] = $value;
  2996.                 }
  2997.                 foreach ($newRevenues as $newRevenueKey => $value) {
  2998.                     $month $newRevenueKey;
  2999.                     if (!in_array($month$monthColumnx)) {
  3000.                         $monthColumnx[] = $month;
  3001.                     }
  3002.                 }
  3003.             } else {
  3004.                 $revenuePlannings $project->getRevenuePlannings();
  3005.                 foreach ($revenuePlannings as $revenuePlanning) {
  3006.                     $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  3007.                     if (!in_array($month$monthColumnx)) {
  3008.                         $monthColumnx[] = $month;
  3009.                     }
  3010.                 }
  3011.             }
  3012.         }
  3013.         // sort
  3014.         usort($monthColumnx, function ($a$b) {
  3015.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  3016.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  3017.             if ($dateA == $dateB) {
  3018.                 return 0;
  3019.             }
  3020.             return ($dateA $dateB) ? -1;
  3021.         });
  3022.         $sortedMonthColumnsx array_map(function ($date) {
  3023.             $dateTime \DateTime::createFromFormat('d-m-Y''01-' $date);
  3024.             return $dateTime->format('M-Y');
  3025.         }, $monthColumnx);
  3026.         $lastColx $leadSheet->getHighestColumn(); // 'L'
  3027.         $key array_search($lastColx$columnx);
  3028.         $cellColumnx = []; // breakdown month column based on cell column
  3029.         $i $key 1;
  3030.         foreach ($sortedMonthColumnsx as $monthColumnx) {
  3031.             $cellColumnx[$i] = $monthColumnx;
  3032.             $leadSheet->setCellValue($columnx[$i] . "5"$monthColumnx);
  3033.             $leadSheet->setCellValue($columnx[$i] . "9"$monthColumnx);
  3034.             $i++;
  3035.         }
  3036.         $totalColumnBreakdownx = [];
  3037.         foreach ($cellColumnx as $cell) {
  3038.             $totalColumnBreakdownx[$cell]['total'] = 0;
  3039.             $totalColumnBreakdownx[$cell]['confirmed'] = 0;
  3040.             $totalColumnBreakdownx[$cell]['lead'] = 0;
  3041.         }
  3042.         // fill cell
  3043.         $monthRowx 10;
  3044.         foreach ($projectsList as $project) {
  3045.             $project $project[0];
  3046.             foreach ($cellColumnx as $cellValue => $value) {
  3047.                 $leadSheet->setCellValue($columnx[$cellValue] . $monthRowx'-');
  3048.             }
  3049.             if ($project->getLead() == '8') {
  3050.                 $revenues $this->monthlyRevenues($project$isCashflow);
  3051.                 foreach ($revenues as $key => $value) {
  3052.                     $month $key;
  3053.                     $cell array_search($month$cellColumnx);
  3054.                     $leadSheet->setCellValue($columnx[$cell] . $monthRowx$value['totalUsd']);
  3055.                     if ($project->getType() == 'CONFIRMED')  $totalColumnBreakdownx[$month]['confirmed'] += $value['totalUsd'];
  3056.                     $totalColumnBreakdownx[$month]['total'] += $value['totalUsd'];
  3057.                 }
  3058.             } else {
  3059.                 $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  3060.                 $revenuePlannings $project->getRevenuePlannings()->toArray();
  3061.                 if (count($revenuePlannings) > 0) {
  3062.                     foreach ($revenuePlannings as $revenuePlanning) {
  3063.                         $month $revenuePlanning->getMonth() . '-' $revenuePlanning->getYear();
  3064.                         $month =  \DateTime::createFromFormat('d-m-Y''01-' $month)->format('M-Y');
  3065.                         $cell array_search($month$cellColumnx);
  3066.                         $revenueAmountUsd $project->getType() == 'LEAD' $revenuePlanning->getAmountUsd() * $probabilityPercent $revenuePlanning->getAmountUsd();
  3067.                         $leadSheet->setCellValue($columnx[$cell] . $monthRowx$revenueAmountUsd);
  3068.                         if ($project->getType() == 'LEAD')  $totalColumnBreakdownx[$month]['lead'] += $revenueAmountUsd;
  3069.                         // if($project['type'] == 'CONFIRMED')  $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
  3070.                         $totalColumnBreakdownx[$month]['total'] += $revenueAmountUsd;
  3071.                     }
  3072.                 }
  3073.             }
  3074.             $monthRowx++;
  3075.         }
  3076.         // fill total cell
  3077.         foreach ($cellColumnx as $key => $cellCol) {
  3078.             for ($i 6$i <= 8$i++) {
  3079.                 $type $i == 'total' : ($i == 'confirmed' 'lead');
  3080.                 $leadSheet->setCellValue($columnx[$key] . $i$totalColumnBreakdownx[$cellCol][$type]);
  3081.             }
  3082.         }
  3083.         // FYTD = 1st nov22 - 31st oct23 
  3084.         // Calculate FYTD start and end dates (Nov 1st - Oct 31st)
  3085.         $currentYear date('Y');
  3086.         $fytdStartDate = new \DateTime($currentYear '-11-01');
  3087.         $fytdEndDate = new \DateTime($currentYear '-10-31');
  3088.         // Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
  3089.         $totalEstProjectBillingsFYTD = [
  3090.             'total' => 0,
  3091.             'confirmed' => 0,
  3092.             'lead' => 0
  3093.         ];
  3094.         $totalEstAgencyRevenueFYTD = [
  3095.             'total' => 0,
  3096.             'confirmed' => 0,
  3097.             'lead' => 0
  3098.         ];
  3099.         $leadRow 10;
  3100.         foreach ($projectsList as $project) {
  3101.             $project $project[0];
  3102.             $totalMonths 0;
  3103.             $numMonthsFYTD 0;
  3104.             if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
  3105.                 $dateInterval $project->getEndDate()->diff($project->getStartDate());
  3106.                 $yearsInMonths $dateInterval->12;
  3107.                 $months $dateInterval->m;
  3108.                 $days $dateInterval->d;
  3109.                 if ($days 0) {
  3110.                     $months++;
  3111.                 }
  3112.                 $totalMonths $yearsInMonths $months;
  3113.                 if ($dateInterval->=== && $dateInterval->=== && $dateInterval->=== 0) {
  3114.                     $totalMonths 1;
  3115.                 }
  3116.                 $numMonthsFYTD $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
  3117.             } else {
  3118.                 $totalMonths 1;
  3119.                 $numMonthsFYTD 1;
  3120.             }
  3121.             $probabilityPercent $project->getLeadStatus()->getProbability() / 100;
  3122.             $estProjectBillings $project->getType() == 'LEAD' $project->getPlannedRevenueUsd() * $probabilityPercent $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
  3123.             $estAgencyRevenue $project->getType() == 'LEAD' $project->getEstimatedProfitUsd() * $probabilityPercent $project->getTotalRevenueUSD();
  3124.             $formulaBillings $totalMonths == $numMonthsFYTD $estProjectBillings : ($estProjectBillings $totalMonths) + ($estProjectBillings $totalMonths $numMonthsFYTD);
  3125.             $formulaRevenue $totalMonths == $numMonthsFYTD $estAgencyRevenue : ($estAgencyRevenue $totalMonths) + ($estAgencyRevenue $totalMonths $numMonthsFYTD);
  3126.             if ($project->getType() == 'CONFIRMED') {
  3127.                 $totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
  3128.                 $totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
  3129.             } elseif ($project->getType() == 'LEAD') {
  3130.                 $totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
  3131.                 $totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
  3132.             }
  3133.             $totalEstProjectBillingsFYTD['total'] += $formulaBillings;
  3134.             $totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
  3135.             $leadSheet->setCellValue('J' $leadRow$formulaBillings);
  3136.             $leadSheet->setCellValue('L' $leadRow$formulaRevenue);
  3137.             $leadRow++;
  3138.         }
  3139.         
  3140.         $leadSheet->setCellValue('J6'$totalEstProjectBillingsFYTD['total']);
  3141.         $leadSheet->setCellValue('J7'$totalEstProjectBillingsFYTD['confirmed']);
  3142.         $leadSheet->setCellValue('J8'$totalEstProjectBillingsFYTD['lead']);
  3143.         $leadSheet->setCellValue('L6'$totalEstAgencyRevenueFYTD['total']);
  3144.         $leadSheet->setCellValue('L7'$totalEstAgencyRevenueFYTD['confirmed']);
  3145.         $leadSheet->setCellValue('L8'$totalEstAgencyRevenueFYTD['lead']);
  3146.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3147.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3148.         $leadSheet->getStyle("A5:" $leadSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3149.         $leadSheet->getStyle("A6:" $leadSheet->getHighestColumn() . "8")->getFont()->setBold(true);
  3150.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFont()->setBold(true);
  3151.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3152.         $leadSheet->getStyle("A9:" $leadSheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3153.         $leadSheet->setAutoFilter('A9:' $leadSheet->getHighestColumn() . $leadSheet->getHighestRow());
  3154.         $leadSheet->getStyle("D1:D" $leadSheet->getHighestRow())->getFont()->setUnderline(true);
  3155.         // $leadSheet->getStyle('I6:'.$leadSheet->getHighestColumn().$leadSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3156.         $leadSheet->getStyle('I6:' $leadSheet->getHighestColumn() . $leadSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3157.         // Write the file
  3158.         $writer = new Xlsx($spreadsheet);
  3159.         $writer->save($filename);
  3160.         if ($_target == 'google') {
  3161.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3162.             if ($gsheetURL) {
  3163.                 unlink($filename);
  3164.                 return new RedirectResponse($gsheetURL302);
  3165.             }
  3166.         } else {
  3167.             $response = new Response();
  3168.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3169.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3170.             $response->setContent(file_get_contents($filename));
  3171.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3172.             $response->headers->set('Content-Transfer-Encoding''binary');
  3173.             $response->headers->set('Pragma''no-cache');
  3174.             $response->headers->set('Expires''0');
  3175.             unlink($filename);
  3176.             return $response;
  3177.             exit;
  3178.         }
  3179.     }
  3180.     public function exportProjectVendorInvoices($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  3181.     {
  3182.         $startDateRange date("d-M-Y"strtotime($startDate));
  3183.         $endDateRange date("d-M-Y"strtotime($endDate));
  3184.         $spreadsheet = new Spreadsheet();
  3185.         $vendorInvoiceSheet $spreadsheet->getActiveSheet()->setTitle('Vendor Invoices');
  3186.         $vendorInvoiceSheet->setCellValue('A1''Today\'s Date');
  3187.         $vendorInvoiceSheet->setCellValue('A2''From');
  3188.         $vendorInvoiceSheet->setCellValue('A3''To');
  3189.         $vendorInvoiceSheet->setCellValue('B1'date('d-M-Y'));
  3190.         $vendorInvoiceSheet->setCellValue('B2'$startDateRange);
  3191.         $vendorInvoiceSheet->setCellValue('B3'$endDateRange);
  3192.         $vendorInvoiceSheet->setCellValue("A5""Vendor Name");
  3193.         $vendorInvoiceSheet->setCellValue("B5""Invoice Date");
  3194.         $vendorInvoiceSheet->setCellValue("C5""Invoice Status");
  3195.         $vendorInvoiceSheet->setCellValue("D5""Client");
  3196.         $vendorInvoiceSheet->setCellValue("E5""Project");
  3197.         $vendorInvoiceSheet->setCellValue("F5""Amount USD");
  3198.         $vendorInvoiceSheet->setCellValue("G5""Allocated USD");
  3199.         $vendorInvoiceSheet->setCellValue("H5""Amount Left USD");
  3200.         $vendorInvoiceSheet->setCellValue("I5""Due Date");
  3201.         $vendorInvoiceSheet->setCellValue("J5""Client INV");
  3202.         $vendorInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
  3203.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3204.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3205.         $vendorInvoiceSheet->getStyle("A5:" $vendorInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3206.         $filename "Project_Vendor_Invoices_Report";
  3207.         $filename .= $startDate "_" urlencode($startDate) : "";
  3208.         $filename .= $endDate "-" urlencode($endDate) : "";
  3209.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  3210.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted);
  3211.         $vendorRow $vendorInvoiceSheet->getHighestRow() + 1;
  3212.         foreach ($projectsList as $project) {
  3213.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings()->toArray();
  3214.             if ($vendorQuotationPlannings) {
  3215.                 foreach ($vendorQuotationPlannings as $vqp) {
  3216.                     $vqpvis $vqp->getVendorQuotationPlanningVendorInvoices()->toArray();
  3217.                     if ($vqpvis) {
  3218.                         foreach ($vqpvis as $vqpvi) {
  3219.                             $vqp $vqpvi->getVendorQuotationPlanning();
  3220.                             $vendorInvoice $vqpvi->getVendorInvoice();
  3221.                             $vendorInvoiceSheet->setCellValue("A" $vendorRow$vqp->getVendor()->getName());
  3222.                             $vendorInvoiceSheet->setCellValue("B" $vendorRow$vendorInvoice->getInvoiceDate()->format("Y-m-d"));
  3223.                             $vendorInvoiceSheet->setCellValue("C" $vendorRow$vendorInvoice->getCustomXeroStatus());
  3224.                             $vendorInvoiceSheet->setCellValue("D" $vendorRow$vqp->getProject()->getClient()->getName());
  3225.                             $vendorInvoiceSheet->setCellValue("E" $vendorRow$vqp->getProject()->getName());
  3226.                             $vendorInvoiceSheet->getCell('E' $vendorRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3227.                             $vendorInvoiceSheet->setCellValue("F" $vendorRow$vendorInvoice->getSubTotalUsd());
  3228.                             $vendorInvoiceSheet->setCellValue("G" $vendorRow$vqpvi->getAmountUsd());
  3229.                             $vendorInvoiceSheet->setCellValue("H" $vendorRow$vendorInvoice->getAmountLeftUsd());
  3230.                             $vendorInvoiceSheet->setCellValue("I" $vendorRow$vendorInvoice->getDueDate()->format("Y-m-d"));
  3231.                             $vendorInvoiceSheet->setCellValue("J" $vendorRow$vqpvi->getInvoice() ? $vqpvi->getInvoice()->getInvoiceNo() : '-');
  3232.                             $vendorRow++;
  3233.                         }
  3234.                     }
  3235.                 }
  3236.             }
  3237.         }
  3238.         $vendorInvoiceSheet->setAutoFilter('A5:' $vendorInvoiceSheet->getHighestColumn() . $vendorInvoiceSheet->getHighestRow());
  3239.         $vendorInvoiceSheet->getStyle("E6:E" $vendorInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
  3240.         // $vendorInvoiceSheet->getStyle('F6:'.'H'.$vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3241.         $vendorInvoiceSheet->getStyle('F6:' 'H' $vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3242.         $spreadsheet->setActiveSheetIndex(0);
  3243.         // Write the file
  3244.         $writer = new Xlsx($spreadsheet);
  3245.         $writer->save($filename);
  3246.         if ($_target == 'google') {
  3247.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3248.             if ($gsheetURL) {
  3249.                 unlink($filename);
  3250.                 return new RedirectResponse($gsheetURL302);
  3251.             }
  3252.         } else {
  3253.             $response = new Response();
  3254.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3255.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3256.             $response->setContent(file_get_contents($filename));
  3257.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3258.             $response->headers->set('Content-Transfer-Encoding''binary');
  3259.             $response->headers->set('Pragma''no-cache');
  3260.             $response->headers->set('Expires''0');
  3261.             unlink($filename);
  3262.             return $response;
  3263.             exit;
  3264.         }
  3265.     }
  3266.     public function exportProjectClientInvoices($isAdmin$keyword$startDate$endDate$client$status$type$retainer$department$project$assignedUser$pic$showDeleted$baseurl$_target)
  3267.     {
  3268.         $startDateRange date("d-M-Y"strtotime($startDate));
  3269.         $endDateRange date("d-M-Y"strtotime($endDate));
  3270.         $spreadsheet = new Spreadsheet();
  3271.         $clientInvoiceSheet $spreadsheet->getActiveSheet()->setTitle('Client Invoices');
  3272.         $clientInvoiceSheet->setCellValue('A1''Today\'s Date');
  3273.         $clientInvoiceSheet->setCellValue('A2''From');
  3274.         $clientInvoiceSheet->setCellValue('A3''To');
  3275.         $clientInvoiceSheet->setCellValue('B1'date('d-M-Y'));
  3276.         $clientInvoiceSheet->setCellValue('B2'$startDateRange);
  3277.         $clientInvoiceSheet->setCellValue('B3'$endDateRange);
  3278.         $clientInvoiceSheet->setCellValue("A5""Client Name");
  3279.         $clientInvoiceSheet->setCellValue("B5""Project Name");
  3280.         $clientInvoiceSheet->setCellValue("C5""Project Status");
  3281.         $clientInvoiceSheet->setCellValue("D5""PIC Name");
  3282.         $clientInvoiceSheet->setCellValue("E5""Client PIC");
  3283.         $clientInvoiceSheet->setCellValue("F5""INV Number");
  3284.         $clientInvoiceSheet->setCellValue("G5""INV Status");
  3285.         $clientInvoiceSheet->setCellValue("H5""INV Due Date");
  3286.         $clientInvoiceSheet->setCellValue("I5""INV Amount");
  3287.         $clientInvoiceSheet->setCellValue("J5""INV Currency");
  3288.         $clientInvoiceSheet->setCellValue("K5""INV Amount USD");
  3289.         $filename "Project_Client_Invoices_Report";
  3290.         $filename .= $startDate "_" urlencode($startDate) : "";
  3291.         $filename .= $endDate "-" urlencode($endDate) : "";
  3292.         $filename .= $startDate '.xlsx' "_" date('Y-m-d') . '.xlsx';
  3293.         $projectsList $this->projectRepository->findByPage(09999$keyword"DESC"'type'$startDate$endDate$type$client$status$project$department$retainer$assignedUser$showDeleted);
  3294.         $column = [];
  3295.         for ($i 65$i <= 90$i++) {
  3296.             $column[] = chr($i);
  3297.         }
  3298.         for ($i 65$i <= 90$i++) {
  3299.             for ($j 65$j <= 90$j++) {
  3300.                 $column[] = chr($i) . chr($j);
  3301.             }
  3302.         }
  3303.         $monthColumn = [];
  3304.         $row $clientInvoiceSheet->getHighestRow() + 1;
  3305.         foreach ($projectsList as $project) {
  3306.             $projectSalesOrders $project[0]->getProjectSalesOrders()->toArray();
  3307.             if ($projectSalesOrders) {
  3308.                 foreach ($projectSalesOrders as $pso) {
  3309.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
  3310.                     if ($soInvoices) {
  3311.                         foreach ($soInvoices as $soInvoice) {
  3312.                             $proj $soInvoice->getProject();
  3313.                             $projectName $proj->getName();
  3314.                             $clientName $proj->getClient()->getName();
  3315.                             $projectPic $proj->getPersonInCharge() ? $proj->getPersonInCharge()->getPersonalInfo()->getFullName() : '-';
  3316.                             $clientPic $proj->getClientPersonInCharge() ? $proj->getClientPersonInCharge()->getName() : '-';
  3317.                             $invoice $soInvoice->getInvoice();
  3318.                             $clientInvoiceSheet->setCellValue("A" $row$clientName);
  3319.                             $clientInvoiceSheet->setCellValue("B" $row$projectName);
  3320.                             $clientInvoiceSheet->getCell('B' $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $proj->getId());
  3321.                             $clientInvoiceSheet->setCellValue('C' $row$proj->getType() == 'LEAD' $project['lead'] . ' - ' $proj->getLeadStatus()->getName() : $proj->getStatus());
  3322.                             $clientInvoiceSheet->setCellValue("D" $row$projectPic ?: '-');
  3323.                             $clientInvoiceSheet->setCellValue("E" $row$clientPic);
  3324.                             $clientInvoiceSheet->setCellValue("F" $row$invoice->getInvoiceNo());
  3325.                             $clientInvoiceSheet->setCellValue("G" $row$invoice->getCustomXeroStatus());
  3326.                             $month $invoice->getDueDate()->format("m-Y");
  3327.                             if (!in_array($month$monthColumn)) {
  3328.                                 $monthColumn[] = $month;
  3329.                             }
  3330.                             $clientInvoiceSheet->setCellValue("H" $row$invoice->getDueDate()->format("Y-m-d"));
  3331.                             $clientInvoiceSheet->setCellValue("I" $row$soInvoice->getAmount());
  3332.                             $clientInvoiceSheet->setCellValue("J" $row$invoice->getCurrency()->getIso());
  3333.                             $clientInvoiceSheet->setCellValue("K" $row$soInvoice->getAmountUsd());
  3334.                             $row++;
  3335.                         }
  3336.                     }
  3337.                 }
  3338.             }
  3339.         }
  3340.         usort($monthColumn, function ($a$b) {
  3341.             $dateA =  \DateTime::createFromFormat('d-m-Y''01-' $a);
  3342.             $dateB =  \DateTime::createFromFormat('d-m-Y''01-' $b);
  3343.             if ($dateA == $dateB) {
  3344.                 return 0;
  3345.             }
  3346.             return ($dateA $dateB) ? -1;
  3347.         });
  3348.         $sortedMonthColumns array_map(function ($date) {
  3349.             return \DateTime::createFromFormat('d-m-Y''01-' $date)->format('M-Y');
  3350.         }, $monthColumn);
  3351.         $lastCol $clientInvoiceSheet->getHighestColumn(); // 'L'
  3352.         $key array_search($lastCol$column);
  3353.         $cellColumn = []; // breakdown month column based on cell column
  3354.         $i $key 1;
  3355.         foreach ($sortedMonthColumns as $monthColumn) {
  3356.             $cellColumn[$i] = $monthColumn;
  3357.             $clientInvoiceSheet->setCellValue($column[$i] . "5"$monthColumn);
  3358.             $i++;
  3359.         }
  3360.         $monthRow 6;
  3361.         foreach ($projectsList as $project) {
  3362.             $projectSalesOrders $project[0]->getProjectSalesOrders()->toArray();
  3363.             if ($projectSalesOrders) {
  3364.                 foreach ($projectSalesOrders as $pso) {
  3365.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
  3366.                     if ($soInvoices) {
  3367.                         foreach ($soInvoices as $soInvoice) {
  3368.                             $invoice $soInvoice->getInvoice();
  3369.                             $month $invoice->getDueDate()->format("M-Y");
  3370.                             $cell array_search($month$cellColumn);
  3371.                             $clientInvoiceSheet->setCellValue($column[$cell] . $monthRow$soInvoice->getAmountUsd());
  3372.                             $monthRow++;
  3373.                         }
  3374.                     }
  3375.                 }
  3376.             }
  3377.         }
  3378.         $clientInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
  3379.         $highestColumn $clientInvoiceSheet->getHighestColumn();
  3380.         $intHighestCol array_search($highestColumn$column);
  3381.         for ($col 11$col <= $intHighestCol$col++) {
  3382.             $clientInvoiceSheet->getColumnDimension($column[$col])->setWidth(15);
  3383.         }
  3384.         $clientInvoiceSheet->setAutoFilter('A5:' $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow());
  3385.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
  3386.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3387.         $clientInvoiceSheet->getStyle("A5:" $clientInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3388.         $clientInvoiceSheet->getStyle("B6:B" $clientInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
  3389.         // $clientInvoiceSheet->getStyle('I6:'.'I'.$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3390.         $clientInvoiceSheet->getStyle('I6:' 'I' $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3391.         // $clientInvoiceSheet->getStyle('K6:'.$clientInvoiceSheet->getHighestColumn().$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
  3392.         $clientInvoiceSheet->getStyle('K6:' $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  3393.         $spreadsheet->setActiveSheetIndex(0);
  3394.         // Write the file
  3395.         $writer = new Xlsx($spreadsheet);
  3396.         $writer->save($filename);
  3397.         if ($_target == 'google') {
  3398.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  3399.             if ($gsheetURL) {
  3400.                 unlink($filename);
  3401.                 return new RedirectResponse($gsheetURL302);
  3402.             }
  3403.         } else {
  3404.             $response = new Response();
  3405.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3406.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  3407.             $response->setContent(file_get_contents($filename));
  3408.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3409.             $response->headers->set('Content-Transfer-Encoding''binary');
  3410.             $response->headers->set('Pragma''no-cache');
  3411.             $response->headers->set('Expires''0');
  3412.             unlink($filename);
  3413.             return $response;
  3414.             exit;
  3415.         }
  3416.     }
  3417.     /*
  3418.     public function exportProjectRevenueCost($isAdmin, $financialYear, $baseurl, $_target)
  3419.     {
  3420.         $start = '';
  3421.         $end = '';
  3422.         if ($financialYear) {
  3423.             $start = date('Y-m-d', strtotime('first day of November ' . ($financialYear - 1)));
  3424.             $end = date('Y-m-d', strtotime('last day of October ' . $financialYear));
  3425.         }
  3426.         $fyStart = $financialYear - 1;
  3427.         $fyEnd = $financialYear + 1;
  3428.         $overallTotals = [
  3429.             'G' => 0, // Revenue FY Start
  3430.             'H' => 0, // Revenue FY Current
  3431.             'I' => 0, // Revenue FY End
  3432.             'P' => 0, // Invoice Total w/o Tax
  3433.             'Y' => 0, // Vendor Total w/o Tax
  3434.             'AA' => 0, // Vendor Cost FY Start
  3435.             'AB' => 0, // Vendor Cost FY Current
  3436.             'AC' => 0, // Vendor Cost FY End
  3437.             'AD' => 0, // Gross Profit Total
  3438.             'AF' => 0, // Gross Profit FY Current
  3439.         ];
  3440.         $overallTotalRevenue = 0;
  3441.         $overallTotalCost = 0;
  3442.         $spreadsheet = new Spreadsheet();
  3443.         $sheet = $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  3444.         // Define Header Data
  3445.         $sheet->setCellValue('A1', 'Client');
  3446.         $sheet->setCellValue('B1', 'Project ID');
  3447.         $sheet->setCellValue('C1', 'Project Name');
  3448.         $sheet->setCellValue('D1', 'Project Status');
  3449.         $sheet->setCellValue('E1', 'Start Date');
  3450.         $sheet->setCellValue('F1', 'End Date');
  3451.         $sheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
  3452.         $sheet->setCellValue('H1', 'Revenue FY ' . $financialYear);
  3453.         $sheet->setCellValue('I1', 'Revenue FY ' . $fyEnd);
  3454.         $sheet->setCellValue('J1', 'MT INV No.');
  3455.         $sheet->setCellValue('K1', 'INV Date');
  3456.         $sheet->setCellValue('L1', 'INV Due Date');
  3457.         $sheet->setCellValue('M1', 'INV Currency');
  3458.         $sheet->setCellValue('N1', 'INV Amount (w/o Taxes)');
  3459.         $sheet->setCellValue('O1', 'SGD FX Rate');
  3460.         $sheet->setCellValue('P1', 'INV Amount (w/o Taxes in SGD)');
  3461.         $sheet->setCellValue('Q1', '');
  3462.         $sheet->setCellValue('R1', 'Vendor');
  3463.         $sheet->setCellValue('S1', 'Vendor INV No.');
  3464.         $sheet->setCellValue('T1', 'Vendor INV Date');
  3465.         $sheet->setCellValue('U1', 'Vendor INV Due Date');
  3466.         $sheet->setCellValue('V1', 'Vendor INV Currency');
  3467.         $sheet->setCellValue('W1', 'Vendor INV Amount Allocated (w/o Taxes)');
  3468.         $sheet->setCellValue('X1', 'SGD FX Rate');
  3469.         $sheet->setCellValue('Y1', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
  3470.         $sheet->setCellValue('Z1', 'Client INV No');
  3471.         $sheet->setCellValue('AA1', 'Vendor Cost ' . $fyStart);
  3472.         $sheet->setCellValue('AB1', 'Vendor Cost ' . $financialYear);
  3473.         $sheet->setCellValue('AC1', 'Vendor Cost ' . $fyEnd);
  3474.         $sheet->setCellValue('AD1', 'Gross Profit Total');
  3475.         $sheet->setCellValue('AE1', 'Gross Profit Margin Total');
  3476.         $sheet->setCellValue('AF1', 'Gross Profit FY ' . $financialYear);
  3477.         $sheet->setCellValue('AG1', 'Gross Profit Margin FY ' . $financialYear);
  3478.         // $sheet->setCellValue('AG1', 'Total Revenue');
  3479.         $sheet->getDefaultColumnDimension()->setWidth(25);
  3480.         $sheet->getColumnDimension('Q')->setWidth(3);
  3481.         $sheet->getColumnDimension('E')->setWidth(12);
  3482.         $sheet->getColumnDimension('F')->setWidth(12);
  3483.         $sheet->getColumnDimension('G')->setWidth(17);
  3484.         $sheet->getColumnDimension('H')->setWidth(17);
  3485.         $sheet->getColumnDimension('I')->setWidth(17);
  3486.         $sheet->getColumnDimension('J')->setWidth(16);
  3487.         $sheet->getColumnDimension('K')->setWidth(12);
  3488.         $sheet->getColumnDimension('L')->setWidth(12);
  3489.         $sheet->getColumnDimension('M')->setWidth(13);
  3490.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
  3491.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3492.         $sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3493.         $sheet->getStyle("A2:" . $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
  3494.         $sheet->freezePane('A2');
  3495.         $filename = "Financial Year - Project revenue vs. Cost FY " . $financialYear;
  3496.         $filename .= date('Y-m-d') . '.xlsx';
  3497.         // $type = "LEAD;CONFIRMED";
  3498.         $type = "CONFIRMED";
  3499.         $status = "On-Going;Finished";
  3500.         $projectsList = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $start, $end, $type, 0, $status);
  3501.         $row = $sheet->getHighestRow();
  3502.         foreach ($projectsList as $project) {
  3503.             $sheet->setCellValue("A" . $row, $project['clientName']);
  3504.             $sheet->setCellValue("B" . $row, $project['generatedId']);
  3505.             $sheet->getCell("B" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
  3506.             $sheet->setCellValue("C" . $row, $project['name']);
  3507.             $sheet->getCell("C" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
  3508.             $sheet->setCellValue("D" . $row, $project['status']);
  3509.             $sheet->setCellValue("E" . $row, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  3510.             $sheet->setCellValue("F" . $row, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  3511.             $sheet->setCellValue("G" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3512.             $sheet->setCellValue("H" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3513.             $sheet->setCellValue("I" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3514.             $sheet->setCellValue("AA" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3515.             $sheet->setCellValue("AB" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3516.             $sheet->setCellValue("AC" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3517.             $sheet->setCellValue("AD" . $row, $project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd());
  3518.             $grossProfitMargin = 0;
  3519.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3520.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  3521.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  3522.                 $grossProfitMargin = ($project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd()) / $project[0]->getInvRevenueByFinancialYearSgd();
  3523.             }
  3524.             $sheet->setCellValue("AE" . $row, $grossProfitMargin);
  3525.             $sheet->setCellValue("AF" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3526.             $grossProfitMarginFinancialYear = 0;
  3527.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  3528.                 $grossProfitMarginFinancialYear = ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear)) / $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
  3529.             }
  3530.             $sheet->setCellValue("AG" . $row, $grossProfitMarginFinancialYear);
  3531.             // $sheet->setCellValue("AG".$row, $project[0]->getTotalRevenueUsd() ?: '-');
  3532.             // looping project invoice
  3533.             $invRow = $row;
  3534.             $projectSalesOrders = $project[0]->getProjectSalesOrders();
  3535.             $InvTotalwoTax = 0;
  3536.             if ($projectSalesOrders) {
  3537.                 foreach ($projectSalesOrders as $pso) {
  3538.                     $soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  3539.                     foreach ($soInvoices as $soInvoice) {
  3540.                         $invoice = $soInvoice->getInvoice();
  3541.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  3542.                         $sheet->setCellValue("J" . $invRow, $invoice->getInvoiceNo());
  3543.                         $sheet->setCellValue("K" . $invRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3544.                         $sheet->setCellValue("L" . $invRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3545.                         $sheet->setCellValue("M" . $invRow, $invoice->getCurrency()->getIso());
  3546.                         // $sheet->setCellValue("N".$invRow, $invoice->getSubTotal());
  3547.                         $InvTotalwoTax += $invoice->getSubTotalSgd($project[0]);
  3548.                         $sheet->setCellValue("N" . $invRow, $invoice->getSubTotal());
  3549.                         $sheet->setCellValue("O" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3550.                         $amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $invoice->getSubTotal() : $invoice->getSubTotalSgd($project[0]);
  3551.                         $sheet->setCellValue("P" . $invRow, $amountSGD);
  3552.                         $invRow++;
  3553.                     }
  3554.                 }
  3555.             } else {
  3556.                 $sheet->setCellValue("J" . $invRow, "-");
  3557.                 $sheet->setCellValue("K" . $invRow, "-");
  3558.                 $sheet->setCellValue("L" . $invRow, "-");
  3559.                 $sheet->setCellValue("M" . $invRow, "-");
  3560.             }
  3561.             //looping vendor invoice
  3562.             $vendorInvRow = $row;
  3563.             $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  3564.             $vendorTotalWoTax = 0;
  3565.             if ($vendorQuotationPlannings) {
  3566.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  3567.                     $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  3568.                     $vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  3569.                     foreach ($vqpInvoices as $vqpInvoice) {
  3570.                         $invoice = $vqpInvoice->getVendorInvoice();
  3571.                         if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  3572.                         $sheet->setCellValue("R" . $vendorInvRow, $vendorName);
  3573.                         $sheet->setCellValue("S" . $vendorInvRow, $invoice->getInvoiceNo());
  3574.                         $sheet->setCellValue("T" . $vendorInvRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3575.                         $sheet->setCellValue("U" . $vendorInvRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3576.                         $sheet->setCellValue("V" . $vendorInvRow, $invoice->getCurrency()->getIso());
  3577.                         // $sheet->setCellValue("W".$vendorInvRow, $vqpInvoice->getAmount());
  3578.                         $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  3579.                         $sheet->setCellValue("W" . $vendorInvRow, $vqpInvoice->getAmount());
  3580.                         $sheet->setCellValue("X" . $vendorInvRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3581.                         $vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  3582.                         $sheet->setCellValue("Y" . $vendorInvRow, $vendorAmountSGD);
  3583.                         // $clientInvoices = [];
  3584.                         // if(!empty($invoice->getInvoiceVendorInvoices()->toArray())){
  3585.                         //     foreach($invoice->getInvoiceVendorInvoices()->toArray() as $invVendorI){
  3586.                         //         $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  3587.                         //         array_push($clientInvoices, $clientInv);
  3588.                         //     }
  3589.                         // }
  3590.                         $sheet->setCellValue('Z'. $row, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  3591.                         $vendorInvRow++;
  3592.                     }
  3593.                 }
  3594.             } else {
  3595.                 $sheet->setCellValue("R" . $vendorInvRow, "-");
  3596.                 $sheet->setCellValue("S" . $vendorInvRow, "-");
  3597.                 $sheet->setCellValue("T" . $vendorInvRow, "-");
  3598.                 $sheet->setCellValue("U" . $vendorInvRow, "-");
  3599.                 $sheet->setCellValue("V" . $vendorInvRow, "-");
  3600.             }
  3601.             $totalRow = $invRow > $row || $vendorInvRow > $row ? max($invRow, $vendorInvRow) : $row + 1;
  3602.             // define total Row
  3603.             $sheet->setCellValue("A" . $totalRow, "Total");
  3604.             $sheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3605.             $sheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3606.             $sheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3607.             $sheet->setCellValue("P" . $totalRow, $InvTotalwoTax);
  3608.             $sheet->setCellValue("Y" . $totalRow, $vendorTotalWoTax);
  3609.             $sheet->setCellValue("AA" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3610.             $sheet->setCellValue("AB" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3611.             $sheet->setCellValue("AC" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3612.             $sheet->setCellValue("AD" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd() -  $project[0]->getInvVendorCostByFinancialYearSgd());
  3613.             $sheet->setCellValue("AE" . $totalRow, $grossProfitMargin);
  3614.             $sheet->setCellValue("AF" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) -  $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3615.             $sheet->setCellValue("AG" . $totalRow, $grossProfitMarginFinancialYear);
  3616.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  3617.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  3618.             $sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3619.             $sheet->getRowDimension($totalRow)->setRowHeight(20);
  3620.             $overallTotals['G'] += $project[0]->getInvRevenueByFinancialYearSgd($fyStart);
  3621.             $overallTotals['H'] += $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
  3622.             $overallTotals['I'] += $project[0]->getInvRevenueByFinancialYearSgd($fyEnd);
  3623.             $overallTotals['P'] += $InvTotalwoTax;
  3624.             $overallTotals['Y'] += $vendorTotalWoTax;
  3625.             $overallTotals['AA'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyStart);
  3626.             $overallTotals['AB'] += $project[0]->getInvVendorCostByFinancialYearSgd($financialYear);
  3627.             $overallTotals['AC'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd);
  3628.             $overallTotals['AD'] += ($project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd());
  3629.             $overallTotals['AF'] += ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3630.             $row = $totalRow;
  3631.             $row++;
  3632.         }
  3633.         //overall total
  3634.         $row = $row+1;
  3635.         $sheet->setCellValue("A". $row, "Overall Total");
  3636.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  3637.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3638.         $sheet->getRowDimension($row)->setRowHeight(20);
  3639.         foreach ($overallTotals as $column => $value) {
  3640.             $sheet->setCellValue($column . $row, $value);
  3641.         }
  3642.         // Calculate and set overall profit margins
  3643.         $overallGrossProfitMargin = $overallTotalRevenue > 0 ? 
  3644.             ($overallTotalRevenue - $overallTotalCost) / $overallTotalRevenue : 0;
  3645.         $overallGrossProfitMarginFY = $overallTotals['H'] > 0 ? 
  3646.             ($overallTotals['H'] - $overallTotals['AB']) / $overallTotals['H'] : 0;
  3647.         $sheet->setCellValue("AE" . $row, $overallGrossProfitMargin);
  3648.         $sheet->setCellValue("AG" . $row, $overallGrossProfitMarginFY);
  3649.         $sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  3650.         $sheet->getStyle("Q1:Q" . $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3651.         $sheet->setAutoFilter('A1:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
  3652.         $sheet->getStyle('G2:I' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  3653.         $sheet->getStyle('N2:N' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3654.         $sheet->getStyle('P2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3655.         $sheet->getStyle('W2:W' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3656.         $sheet->getStyle('Y2:Y' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3657.         $sheet->getStyle('AA2:AD' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3658.         // $sheet->getStyle('X2:X' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;(#,##0.00)');
  3659.         $sheet->getStyle('AF2:AF' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3660.         $sheet->getStyle("AE")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  3661.         $sheet->getStyle("AG")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  3662.         $sheet->getStyle("B2:B" . $sheet->getHighestRow())->getFont()->setUnderline(true);
  3663.         $sheet->getStyle("C2:C" . $sheet->getHighestRow())->getFont()->setUnderline(true);
  3664.         // Write the file
  3665.         $writer = new Xlsx($spreadsheet);
  3666.         $writer->save($filename);
  3667.         if ($_target == 'google') {
  3668.             $gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
  3669.             if ($gsheetURL) {
  3670.                 unlink($filename);
  3671.                 return new RedirectResponse($gsheetURL, 302);
  3672.             }
  3673.         } else {
  3674.             $response = new Response();
  3675.             $response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  3676.             $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
  3677.             $response->setContent(file_get_contents($filename));
  3678.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  3679.             $response->headers->set('Content-Transfer-Encoding', 'binary');
  3680.             $response->headers->set('Pragma', 'no-cache');
  3681.             $response->headers->set('Expires', '0');
  3682.             unlink($filename);
  3683.             return $response;
  3684.             exit;
  3685.         }
  3686.     }
  3687.     */
  3688.     public function exportProjectRevenueCost($isAdmin$financialYear$baseurl$_target)
  3689.     {
  3690.         $start '';
  3691.         $end '';
  3692.         if ($financialYear) {
  3693.             $start date('Y-m-d'strtotime('first day of November ' . ($financialYear 1)));
  3694.             $end date('Y-m-d'strtotime('last day of October ' $financialYear));
  3695.         }
  3696.         $fyStart $financialYear 1;
  3697.         $fyEnd $financialYear 1;
  3698.         $overallTotals = [];
  3699.         $overallTotalRevenue 0;
  3700.         $overallTotalCost 0;
  3701.         $spreadsheet = new Spreadsheet();
  3702.         $sheet $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  3703.         // Define Header Data
  3704.         $sheet->setCellValue('A1''Client');
  3705.         $sheet->setCellValue('B1''Project ID');
  3706.         $sheet->setCellValue('C1''Project Name');
  3707.         $sheet->setCellValue('D1''Project Status');
  3708.         $sheet->setCellValue('E1''Start Date');
  3709.         $sheet->setCellValue('F1''End Date');
  3710.         $sheet->setCellValue('G1''Revenue FY ' $fyStart);
  3711.         $sheet->setCellValue('H1''Revenue FY ' $fyStart ' Amount Allocated');
  3712.         $sheet->setCellValue('I1''Revenue FY ' $financialYear);
  3713.         $sheet->setCellValue('J1''Revenue FY ' $financialYear ' Amount Allocated');
  3714.         $sheet->setCellValue('K1''Revenue FY ' $fyEnd);
  3715.         $sheet->setCellValue('L1''Revenue FY ' $fyEnd ' Amount Allocated');
  3716.         $sheet->setCellValue('M1''MT INV No.');
  3717.         $sheet->setCellValue('N1''INV Date');
  3718.         $sheet->setCellValue('O1''INV Due Date');
  3719.         $sheet->setCellValue('P1''INV Currency');
  3720.         $sheet->setCellValue('Q1''INV Amount (w/o Taxes)');
  3721.         $sheet->setCellValue('R1''INV Amount Allocated (w/o Taxes)');
  3722.         $sheet->setCellValue('S1''SGD FX Rate');
  3723.         $sheet->setCellValue('T1''INV Amount (w/o Taxes in SGD)');
  3724.         $sheet->setCellValue('U1''INV Amount Allocated (w/o Taxes in SGD)');
  3725.         $sheet->setCellValue('V1''');
  3726.         $sheet->setCellValue('W1''Vendor');
  3727.         $sheet->setCellValue('X1''Vendor INV No.');
  3728.         $sheet->setCellValue('Y1''Vendor INV Date');
  3729.         $sheet->setCellValue('Z1''Vendor INV Due Date');
  3730.         $sheet->setCellValue('AA1''Vendor INV Currency');
  3731.         $sheet->setCellValue('AB1''Vendor INV Amount (w/o Taxes)');
  3732.         $sheet->setCellValue('AC1''Vendor INV Amount Allocated (w/o Taxes)');
  3733.         $sheet->setCellValue('AD1''SGD FX Rate');
  3734.         $sheet->setCellValue('AE1''Vendor INV Amount (w/o Taxes in SGD)');
  3735.         $sheet->setCellValue('AF1''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  3736.         $sheet->setCellValue('AG1''Client INV No');
  3737.         $sheet->setCellValue('AH1''Vendor Cost ' $fyStart);
  3738.         $sheet->setCellValue('AI1''Vendor Cost ' $fyStart ' Amount Allocated');
  3739.         $sheet->setCellValue('AJ1''Vendor Cost ' $financialYear);
  3740.         $sheet->setCellValue('AK1''Vendor Cost ' $financialYear ' Amount Allocated');
  3741.         $sheet->setCellValue('AL1''Vendor Cost ' $fyEnd);
  3742.         $sheet->setCellValue('AM1''Vendor Cost ' $fyEnd ' Amount Allocated');
  3743.         $sheet->setCellValue('AN1''Gross Profit Total');
  3744.         $sheet->setCellValue('AO1''Gross Profit Total Amount Allocated');
  3745.         $sheet->setCellValue('AP1''Gross Profit Margin Total');
  3746.         $sheet->setCellValue('AQ1''Gross Profit Margin Total Amount Allocated');
  3747.         $sheet->setCellValue('AR1''Gross Profit FY ' $financialYear);
  3748.         $sheet->setCellValue('AS1''Gross Profit FY ' $financialYear ' Amount Allocated');
  3749.         $sheet->setCellValue('AT1''Gross Profit Margin FY ' $financialYear);
  3750.         $sheet->setCellValue('AU1''Gross Profit Margin FY ' $financialYear ' Amount Allocated');
  3751.         // $sheet->setCellValue('AG1', 'Total Revenue');
  3752.         $sheet->getDefaultColumnDimension()->setWidth(25);
  3753.         $sheet->getColumnDimension('V')->setWidth(3);
  3754.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
  3755.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  3756.         $sheet->getStyle("A1:" $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3757.         $sheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3758.         $sheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3759.         $sheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3760.         $sheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3761.         $sheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3762.         $sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3763.         $sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3764.         $sheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3765.         $sheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3766.         $sheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3767.         $sheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3768.         $sheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3769.         $sheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3770.         $sheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3771.         $sheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  3772.         $sheet->getStyle("A2:" $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
  3773.         $sheet->freezePane('A2');
  3774.         $filename "Financial Year - Project revenue vs. Cost FY " $financialYear;
  3775.         $filename .= date('Y-m-d') . '.xlsx';
  3776.         // $type = "LEAD;CONFIRMED";
  3777.         $type "CONFIRMED";
  3778.         $status "On-Going;Finished";
  3779.         $projectsList $this->projectRepository->findByPage(09999"""ASC"'client'$start$end$type0$status);
  3780.         $row $sheet->getHighestRow();
  3781.         foreach ($projectsList as $project) {
  3782.             $sheet->setCellValue("A" $row$project['clientName']);
  3783.             $sheet->setCellValue("B" $row$project['generatedId']);
  3784.             $sheet->getCell("B" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3785.             $sheet->getStyle('B' $row)->getFont()->setUnderline(true);
  3786.             $sheet->setCellValue("C" $row$project['name']);
  3787.             $sheet->getCell("C" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  3788.             $sheet->getStyle('C' $row)->getFont()->setUnderline(true);
  3789.             $sheet->setCellValue("D" $row$project['status']);
  3790.             $sheet->setCellValue("E" $row$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  3791.             $sheet->setCellValue("F" $row$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  3792.             $sheet->setCellValue("G" $row$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3793.             $sheet->setCellValue("H" $row$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  3794.             $sheet->setCellValue("I" $row$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3795.             $sheet->setCellValue("J" $row$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  3796.             $sheet->setCellValue("K" $row$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3797.             $sheet->setCellValue("L" $row$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  3798.             $sheet->setCellValue("AH" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  3799.             $sheet->setCellValue("AI" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyStarttrue));
  3800.             $sheet->setCellValue("AJ" $row$project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  3801.             $sheet->setCellValue("AK" $row$project[0]->getInvVendorCostByFinancialYearSgd($financialYeartrue));
  3802.             $sheet->setCellValue("AL" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  3803.             $sheet->setCellValue("AM" $row$project[0]->getInvVendorCostByFinancialYearSgd($fyEndtrue));
  3804.             
  3805.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3806.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  3807.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  3808.             }
  3809.             // looping project invoice
  3810.             $invRow $row;
  3811.             $projectSalesOrders $project[0]->getProjectSalesOrders();
  3812.             $InvTotalwoTax 0;
  3813.             if ($projectSalesOrders) {
  3814.                 foreach ($projectSalesOrders as $pso) {
  3815.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  3816.                     foreach ($soInvoices as $soInvoice) {
  3817.                         $invoice $soInvoice->getInvoice();
  3818.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  3819.                         $sheet->setCellValue("M" $invRow$invoice->getInvoiceNo());
  3820.                         $sheet->setCellValue("N" $invRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3821.                         $sheet->setCellValue("O" $invRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3822.                         $sheet->setCellValue("P" $invRow$invoice->getCurrency()->getIso());
  3823.                         $InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
  3824.                         $sheet->setCellValue("Q" $invRow$invoice->getSubTotal());
  3825.                         $sheet->setCellValue("R" $invRow$soInvoice->getAmount());
  3826.                         $sheet->setCellValue("S" $invRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3827.                         $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  3828.                         $sheet->setCellValue("T" $invRow$invoice->getSubTotalSgd($project[0]));
  3829.                         $sheet->setCellValue("U" $invRow$amountSGD);
  3830.                         $invRow++;
  3831.                     }
  3832.                 }
  3833.             } else {
  3834.                 $sheet->setCellValue("M" $invRow"-");
  3835.                 $sheet->setCellValue("N" $invRow"-");
  3836.                 $sheet->setCellValue("O" $invRow"-");
  3837.                 $sheet->setCellValue("P" $invRow"-");
  3838.                 $sheet->setCellValue("Q" $invRow"-");
  3839.                 $sheet->setCellValue("R" $invRow"-");
  3840.                 $sheet->setCellValue("S" $invRow"-");
  3841.                 $sheet->setCellValue("T" $invRow"-");
  3842.                 $sheet->setCellValue("U" $invRow"-");
  3843.             }
  3844.             //looping vendor invoice
  3845.             $vendorInvRow $row;
  3846.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  3847.             $vendorTotalWoTax 0;
  3848.             if ($vendorQuotationPlannings) {
  3849.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  3850.                     $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  3851.                     $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  3852.                     foreach ($vqpInvoices as $vqpInvoice) {
  3853.                         $invoice $vqpInvoice->getVendorInvoice();
  3854.                         // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  3855.                         $sheet->setCellValue("W" $vendorInvRow$vendorName);
  3856.                         $sheet->setCellValue("X" $vendorInvRow$invoice->getInvoiceNo());
  3857.                         $sheet->setCellValue("Y" $vendorInvRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  3858.                         $sheet->setCellValue("Z" $vendorInvRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  3859.                         $sheet->setCellValue("AA" $vendorInvRow$invoice->getCurrency()->getIso());
  3860.                         $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  3861.                         $sheet->setCellValue("AB" $vendorInvRow$invoice->getSubtotal());
  3862.                         $sheet->setCellValue("AC" $vendorInvRow$vqpInvoice->getAmount());
  3863.                         $sheet->setCellValue("AD" $vendorInvRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  3864.                         $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  3865.                         $sheet->setCellValue("AE" $vendorInvRow$invoice->getSubTotalSgd($project[0]));
  3866.                         $sheet->setCellValue("AF" $vendorInvRow$vendorAmountSGD);
  3867.                         $sheet->setCellValue('AG'$vendorInvRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  3868.                         $vendorInvRow++;
  3869.                     }
  3870.                 }
  3871.             } else {
  3872.                 $sheet->setCellValue("W" $vendorInvRow"-");
  3873.                 $sheet->setCellValue("X" $vendorInvRow"-");
  3874.                 $sheet->setCellValue("Y" $vendorInvRow"-");
  3875.                 $sheet->setCellValue("Z" $vendorInvRow"-");
  3876.                 $sheet->setCellValue("AA" $vendorInvRow"-");
  3877.             }
  3878.             $totalRow $invRow $row || $vendorInvRow $row max($invRow$vendorInvRow) : $row 1;
  3879.             $sheet->setCellValue("A" $totalRow"Total");
  3880.             $sheet->setCellValue("G" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  3881.             $sheet->setCellValue("H" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  3882.             $sheet->setCellValue("I" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  3883.             $sheet->setCellValue("J" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  3884.             $sheet->setCellValue("K" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  3885.             $sheet->setCellValue("L" $totalRow$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  3886.             $sheet->setCellValue("T" $totalRow'=SUM(T'.$row.':T'.($invRow $row $invRow $row).')');
  3887.             $sheet->setCellValue("U" $totalRow'=SUM(U'.$row.':U'.($invRow $row $invRow $row).')');
  3888.             $sheet->setCellValue("AE" $totalRow'=SUM(AE'.$row.':AE'.($vendorInvRow $row $vendorInvRow $row).')');
  3889.             $sheet->setCellValue("AF" $totalRow'=SUM(AF'.$row.':AF'.($vendorInvRow $row $vendorInvRow $row).')');
  3890.             $sheet->setCellValue("AH" $totalRow"=AH" $row);
  3891.             $sheet->setCellValue("AI" $totalRow"=AI" $row);
  3892.             $sheet->setCellValue("AJ" $totalRow"=AJ" $row);
  3893.             $sheet->setCellValue("AK" $totalRow"=AK" $row);
  3894.             $sheet->setCellValue("AL" $totalRow"=AL" $row);
  3895.             $sheet->setCellValue("AM" $totalRow"=AM" $row);
  3896.             $sheet->setCellValue("AN" $totalRow'=T'.$totalRow.'-AE'.$totalRow);
  3897.             $sheet->setCellValue("AN" $row'=T'.$totalRow.'-AE'.$totalRow);
  3898.             $sheet->setCellValue("AO" $totalRow'=U'.$totalRow.'-AF'.$totalRow);
  3899.             $sheet->setCellValue("AO" $row'=U'.$totalRow.'-AF'.$totalRow);
  3900.             $grossProfitMargin 0;
  3901.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  3902.                 $grossProfitMargin '=(T'.$totalRow'-AE'.$totalRow.')/T'.$totalRow;
  3903.                 $sheet->setCellValue("AP" $totalRow$grossProfitMargin);
  3904.                 $sheet->setCellValue("AP" $row$grossProfitMargin);
  3905.             }else{
  3906.                 $sheet->setCellValue("AP" $totalRow$grossProfitMargin);
  3907.                 $sheet->setCellValue("AP" $row$grossProfitMargin);
  3908.             }
  3909.             $grossProfitMarginAllocated 0;
  3910.             if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  3911.                 $grossProfitMarginAllocated '=(U'.$totalRow'-AF'.$totalRow.')/U'.$totalRow;
  3912.                 $sheet->setCellValue("AQ" $totalRow$grossProfitMarginAllocated);
  3913.                 $sheet->setCellValue("AQ" $row$grossProfitMarginAllocated);
  3914.             }else{
  3915.                 $sheet->setCellValue("AQ" $totalRow$grossProfitMarginAllocated);
  3916.                 $sheet->setCellValue("AQ" $row$grossProfitMarginAllocated);
  3917.             }
  3918.             $sheet->setCellValue("AR" $totalRow'=I'.$totalRow.'-AJ'.$totalRow);
  3919.             $sheet->setCellValue("AR" $row'=I'.$totalRow.'-AJ'.$totalRow);
  3920.             $sheet->setCellValue("AS" $totalRow'=J'.$totalRow.'-AK'.$totalRow);
  3921.             $sheet->setCellValue("AS" $row'=J'.$totalRow.'-AK'.$totalRow);
  3922.             $grossProfitMarginFinancialYear 0;
  3923.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  3924.                 $grossProfitMarginFinancialYear '=(I'.$totalRow'-AJ'.$totalRow.')/I'.$totalRow;
  3925.                 $sheet->setCellValue("AT" $totalRow$grossProfitMarginFinancialYear);
  3926.                 $sheet->setCellValue("AT" $row$grossProfitMarginFinancialYear);
  3927.             }else{
  3928.                 $sheet->setCellValue("AT" $totalRow$grossProfitMarginFinancialYear);
  3929.                 $sheet->setCellValue("AT" $row$grossProfitMarginFinancialYear);
  3930.             }
  3931.             $grossProfitMarginFinancialYearAllocated 0;
  3932.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue) > 0) {
  3933.                 $grossProfitMarginFinancialYearAllocated '=(J'.$totalRow'-AK'.$totalRow.')/J'.$totalRow;
  3934.                 $sheet->setCellValue("AU" $totalRow$grossProfitMarginFinancialYearAllocated);
  3935.                 $sheet->setCellValue("AU" $row$grossProfitMarginFinancialYearAllocated);
  3936.             }else{
  3937.                 $sheet->setCellValue("AU" $totalRow$grossProfitMarginFinancialYearAllocated);
  3938.                 $sheet->setCellValue("AU" $row$grossProfitMarginFinancialYearAllocated);
  3939.             }
  3940.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  3941.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  3942.             $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3943.             $sheet->getRowDimension($totalRow)->setRowHeight(20);
  3944.             $overallTotals['G'][] = 'G'.$totalRow;
  3945.             $overallTotals['H'][] = 'H'.$totalRow;
  3946.             $overallTotals['I'][] = 'I'.$totalRow;
  3947.             $overallTotals['J'][] = 'J'.$totalRow;
  3948.             $overallTotals['K'][] = 'K'.$totalRow;
  3949.             $overallTotals['L'][] = 'L'.$totalRow;
  3950.             $overallTotals['T'][] = 'T'.$totalRow;
  3951.             $overallTotals['U'][] = 'U'.$totalRow;
  3952.             $overallTotals['AE'][] = 'AE'.$totalRow;
  3953.             $overallTotals['AF'][] = 'AF'.$totalRow;
  3954.             $overallTotals['AH'][] = 'AH'.$totalRow;
  3955.             $overallTotals['AI'][] = 'AI'.$totalRow;
  3956.             $overallTotals['AJ'][] = 'AJ'.$totalRow;
  3957.             $overallTotals['AK'][] = 'AK'.$totalRow;
  3958.             $overallTotals['AL'][] = 'AL'.$totalRow;
  3959.             $overallTotals['AM'][] = 'AM'.$totalRow;
  3960.             $row $totalRow;
  3961.             $row++;
  3962.         }
  3963.         //overall total
  3964.         $row $row+1;
  3965.         $sheet->setCellValue("A"$row"Overall Total");
  3966.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  3967.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  3968.         $sheet->getRowDimension($row)->setRowHeight(20);
  3969.         $sheet->setCellValue("G" $row'='.implode('+'$overallTotals['G']));
  3970.         $sheet->setCellValue("H" $row'='.implode('+'$overallTotals['H']));
  3971.         $sheet->setCellValue("I" $row'='.implode('+'$overallTotals['I']));
  3972.         $sheet->setCellValue("J" $row'='.implode('+'$overallTotals['J']));
  3973.         $sheet->setCellValue("K" $row'='.implode('+'$overallTotals['K']));
  3974.         $sheet->setCellValue("L" $row'='.implode('+'$overallTotals['L']));
  3975.         $sheet->setCellValue("T" $row'='.implode('+'$overallTotals['T']));
  3976.         $sheet->setCellValue("U" $row'='.implode('+'$overallTotals['U']));
  3977.         $sheet->setCellValue("AE" $row'='.implode('+'$overallTotals['AE']));
  3978.         $sheet->setCellValue("AF" $row'='.implode('+'$overallTotals['AF']));
  3979.         $sheet->setCellValue("AH" $row'='.implode('+'$overallTotals['AH']));
  3980.         $sheet->setCellValue("AI" $row'='.implode('+'$overallTotals['AI']));
  3981.         $sheet->setCellValue("AJ" $row'='.implode('+'$overallTotals['AJ']));
  3982.         $sheet->setCellValue("AK" $row'='.implode('+'$overallTotals['AK']));
  3983.         $sheet->setCellValue("AL" $row'='.implode('+'$overallTotals['AL']));
  3984.         $sheet->setCellValue("AM" $row'='.implode('+'$overallTotals['AM']));
  3985.         $sheet->setCellValue("AN" $row'=T'.$row.'-AE'.$row);
  3986.         $sheet->setCellValue("AO" $row'=U'.$row.'-AF'.$row);
  3987.         $sheet->setCellValue("AR" $row'=I'.$row.'-AJ'.$row);
  3988.         $sheet->setCellValue("AS" $row'=J'.$row.'-AK'.$row);
  3989.         $sheet->setCellValue("AP" $row,'=IF(T'.$row.'=0, "",(T'.$row'-AE'.$row.')/T'.$row.')');
  3990.         $sheet->setCellValue("AQ" $row,'=IF(U'.$row.'=0, "",(U'.$row'-AF'.$row.')/U'.$row.')');
  3991.         $sheet->setCellValue("AT" $row,'=IF(I'.$row.'=0, "",(I'.$row'-AJ'.$row.')/I'.$row.')');
  3992.         $sheet->setCellValue("AU" $row,'=IF(J'.$row.'=0, "",(J'.$row'-AK'.$row.')/J'.$row.')');
  3993.         
  3994.         $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  3995.         $sheet->getStyle("V1:V" $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  3996.         $sheet->setAutoFilter('A1:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  3997.         $sheet->getStyle('G2:L' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  3998.         $sheet->getStyle('Q2:R' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  3999.         $sheet->getStyle('T2:U' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4000.         $sheet->getStyle('AB2:AC' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4001.         $sheet->getStyle('AE2:AF' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4002.         $sheet->getStyle('AH2:AO' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4003.         $sheet->getStyle('AN2:AO' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4004.         $sheet->getStyle('AR2:AS' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4005.         $sheet->getStyle("AP2:AQ"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4006.         $sheet->getStyle("AT2:AU"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4007.         $summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Summary Total');
  4008.         $spreadsheet->addSheet($summarySheet1);
  4009.         $summarySheet->setCellValue('A1''Client');
  4010.         $summarySheet->setCellValue('B1''Project ID');
  4011.         $summarySheet->setCellValue('C1''Project Name');
  4012.         $summarySheet->setCellValue('D1''Project Status');
  4013.         $summarySheet->setCellValue('E1''Start Date');
  4014.         $summarySheet->setCellValue('F1''End Date');
  4015.         $summarySheet->setCellValue('G1''Revenue FY ' $fyStart);
  4016.         $summarySheet->setCellValue('H1''Revenue FY ' $fyStart ' Amount Allocated');
  4017.         $summarySheet->setCellValue('I1''Revenue FY ' $financialYear);
  4018.         $summarySheet->setCellValue('J1''Revenue FY ' $financialYear ' Amount Allocated');
  4019.         $summarySheet->setCellValue('K1''Revenue FY ' $fyEnd);
  4020.         $summarySheet->setCellValue('L1''Revenue FY ' $fyEnd ' Amount Allocated');
  4021.         $summarySheet->setCellValue('M1''MT INV No.');
  4022.         $summarySheet->setCellValue('N1''INV Date');
  4023.         $summarySheet->setCellValue('O1''INV Due Date');
  4024.         $summarySheet->setCellValue('P1''INV Currency');
  4025.         $summarySheet->setCellValue('Q1''INV Amount (w/o Taxes)');
  4026.         $summarySheet->setCellValue('R1''INV Amount Allocated (w/o Taxes)');
  4027.         $summarySheet->setCellValue('S1''SGD FX Rate');
  4028.         $summarySheet->setCellValue('T1''INV Amount (w/o Taxes in SGD)');
  4029.         $summarySheet->setCellValue('U1''INV Amount Allocated (w/o Taxes in SGD)');
  4030.         $summarySheet->setCellValue('V1''');
  4031.         $summarySheet->setCellValue('W1''Vendor');
  4032.         $summarySheet->setCellValue('X1''Vendor INV No.');
  4033.         $summarySheet->setCellValue('Y1''Vendor INV Date');
  4034.         $summarySheet->setCellValue('Z1''Vendor INV Due Date');
  4035.         $summarySheet->setCellValue('AA1''Vendor INV Currency');
  4036.         $summarySheet->setCellValue('AB1''Vendor INV Amount (w/o Taxes)');
  4037.         $summarySheet->setCellValue('AC1''Vendor INV Amount Allocated (w/o Taxes)');
  4038.         $summarySheet->setCellValue('AD1''SGD FX Rate');
  4039.         $summarySheet->setCellValue('AE1''Vendor INV Amount (w/o Taxes in SGD)');
  4040.         $summarySheet->setCellValue('AF1''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4041.         $summarySheet->setCellValue('AG1''Client INV No');
  4042.         $summarySheet->setCellValue('AH1''Vendor Cost ' $fyStart);
  4043.         $summarySheet->setCellValue('AI1''Vendor Cost ' $fyStart ' Amount Allocated');
  4044.         $summarySheet->setCellValue('AJ1''Vendor Cost ' $financialYear);
  4045.         $summarySheet->setCellValue('AK1''Vendor Cost ' $financialYear ' Amount Allocated');
  4046.         $summarySheet->setCellValue('AL1''Vendor Cost ' $fyEnd);
  4047.         $summarySheet->setCellValue('AM1''Vendor Cost ' $fyEnd ' Amount Allocated');
  4048.         $summarySheet->setCellValue('AN1''Gross Profit Total');
  4049.         $summarySheet->setCellValue('AO1''Gross Profit Total Amount Allocated');
  4050.         $summarySheet->setCellValue('AP1''Gross Profit Margin Total');
  4051.         $summarySheet->setCellValue('AQ1''Gross Profit Margin Total Amount Allocated');
  4052.         $summarySheet->setCellValue('AR1''Gross Profit FY ' $financialYear);
  4053.         $summarySheet->setCellValue('AS1''Gross Profit FY ' $financialYear ' Amount Allocated');
  4054.         $summarySheet->setCellValue('AT1''Gross Profit Margin FY ' $financialYear);
  4055.         $summarySheet->setCellValue('AU1''Gross Profit Margin FY ' $financialYear ' Amount Allocated');
  4056.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4057.         $summarySheet->getDefaultColumnDimension()->setWidth(25);
  4058.         $summarySheet->getColumnDimension('V')->setWidth(3);
  4059.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFont()->setBold(true);
  4060.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4061.         $summarySheet->getStyle("A1:" $summarySheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4062.         $summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4063.         $summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4064.         $summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4065.         $summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4066.         $summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4067.         $summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4068.         $summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4069.         $summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4070.         $summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4071.         $summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4072.         $summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4073.         $summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4074.         $summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4075.         $summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4076.         $summarySheet->getStyle("A2:" $summarySheet->getHighestColumn() . "2")->getFont()->setBold(false);
  4077.         $summarySheet->freezePane('A2');
  4078.         // $type = "LEAD;CONFIRMED";
  4079.         $type "CONFIRMED";
  4080.         $status "On-Going;Finished";
  4081.         $projectsListSummary $this->projectRepository->findByPage(09999"""ASC"'client'$start$end$type0$status);
  4082.         
  4083.         $sumOverallTotals = [];
  4084.         $sumRow $summarySheet->getHighestRow();
  4085.         foreach ($projectsListSummary as $project) {
  4086.             $summarySheet->setCellValue("A" $sumRow$project['clientName']);
  4087.             $summarySheet->setCellValue("B" $sumRow$project['generatedId']);
  4088.             $summarySheet->getCell("B" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4089.             $summarySheet->getStyle('B' $sumRow)->getFont()->setUnderline(true);
  4090.             $summarySheet->setCellValue("C" $sumRow$project['name']);
  4091.             $summarySheet->getCell("C" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4092.             $summarySheet->getStyle('C' $sumRow)->getFont()->setUnderline(true);
  4093.             $summarySheet->setCellValue("D" $sumRow$project['status']);
  4094.             $summarySheet->setCellValue("E" $sumRow$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4095.             $summarySheet->setCellValue("F" $sumRow$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4096.             $summarySheet->setCellValue("G" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4097.             $summarySheet->setCellValue("H" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyStarttrue));
  4098.             $summarySheet->setCellValue("I" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4099.             $summarySheet->setCellValue("J" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue));
  4100.             $summarySheet->setCellValue("K" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4101.             $summarySheet->setCellValue("L" $sumRow$project[0]->getInvRevenueByFinancialYearSgd($fyEndtrue));
  4102.             $summarySheet->setCellValue("AH" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  4103.             $summarySheet->setCellValue("AI" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyStarttrue));
  4104.             $summarySheet->setCellValue("AJ" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  4105.             $summarySheet->setCellValue("AK" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($financialYeartrue));
  4106.             $summarySheet->setCellValue("AL" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  4107.             $summarySheet->setCellValue("AM" $sumRow$project[0]->getInvVendorCostByFinancialYearSgd($fyEndtrue));
  4108.             $projectSalesOrders $project[0]->getProjectSalesOrders();
  4109.             $invData = [
  4110.                 'totalAmount' => 0,
  4111.                 'totalAmountSGD' => 0,
  4112.                 'totalAmountAllocated' => 0,
  4113.                 'totalAmountAllocatedSGD' => 0,
  4114.             ];
  4115.             if ($projectSalesOrders) {
  4116.                 foreach ($projectSalesOrders as $pso) {
  4117.                     $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4118.                     foreach ($soInvoices as $soInvoice) {
  4119.                         $invoice $soInvoice->getInvoice();
  4120.                         if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4121.                         $summarySheet->setCellValue("P" $sumRow$invoice->getCurrency()->getIso());
  4122.                         $invData['totalAmount'] += $invoice->getSubTotal();
  4123.                         $invData['totalAmountAllocated'] += $soInvoice->getAmount();
  4124.                         $invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4125.                         $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4126.                         $invData['totalAmountAllocatedSGD'] += $amountSGD;
  4127.                         $summarySheet->setCellValue("Q" $sumRow$invData['totalAmount']);
  4128.                         $summarySheet->setCellValue("R" $sumRow$invData['totalAmountAllocated']);
  4129.                         // $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4130.                         
  4131.                         $summarySheet->setCellValue("T" $sumRow$invData['totalAmountSGD']);
  4132.                         $summarySheet->setCellValue("U" $sumRow$invData['totalAmountAllocatedSGD']);
  4133.                     }
  4134.                 }
  4135.             } else {
  4136.                 $summarySheet->setCellValue("M" $sumRow"-");
  4137.                 $summarySheet->setCellValue("N" $sumRow"-");
  4138.                 $summarySheet->setCellValue("O" $sumRow"-");
  4139.                 $summarySheet->setCellValue("P" $sumRow"-");
  4140.                 $summarySheet->setCellValue("Q" $sumRow"-");
  4141.                 $summarySheet->setCellValue("R" $sumRow"-");
  4142.                 $summarySheet->setCellValue("S" $sumRow"-");
  4143.                 $summarySheet->setCellValue("T" $sumRow"-");
  4144.                 $summarySheet->setCellValue("U" $sumRow"-");
  4145.             }
  4146.             $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4147.             $vendorData = [
  4148.                 'totalAmount' => 0,
  4149.                 'totalAmountAllocated' => 0,
  4150.                 'totalAmountSGD' => 0,
  4151.                 'totalAmountAllocatedSGD' => 0,
  4152.             ];
  4153.             if ($vendorQuotationPlannings) {
  4154.                 foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4155.                     $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4156.                     $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4157.                     foreach ($vqpInvoices as $vqpInvoice) {
  4158.                         $invoice $vqpInvoice->getVendorInvoice();
  4159.                         // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4160.                         // $summarySheet->setCellValue("W" . $sumRow, $vendorName);
  4161.                         // $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
  4162.                         // $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4163.                         // $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4164.                         $summarySheet->setCellValue("AA" $sumRow$invoice->getCurrency()->getIso());
  4165.                         $vendorData['totalAmount'] += $invoice->getSubTotal();
  4166.                         $vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
  4167.                         $summarySheet->setCellValue("AB" $sumRow$vendorData['totalAmount']);
  4168.                         $summarySheet->setCellValue("AC" $sumRow$vendorData['totalAmountAllocated']);
  4169.                         // $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4170.                         $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4171.                         $vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4172.                         $vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
  4173.                         $summarySheet->setCellValue("AE" $sumRow$vendorData['totalAmountSGD']);
  4174.                         $summarySheet->setCellValue("AF" $sumRow$vendorData['totalAmountAllocatedSGD']);
  4175.                         $summarySheet->setCellValue('AG'$sumRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4176.                     }
  4177.                 }
  4178.             } else {
  4179.                 $summarySheet->setCellValue("W" $sumRow"-");
  4180.                 $summarySheet->setCellValue("X" $sumRow"-");
  4181.                 $summarySheet->setCellValue("Y" $sumRow"-");
  4182.                 $summarySheet->setCellValue("Z" $sumRow"-");
  4183.                 $summarySheet->setCellValue("AA" $sumRow"-");
  4184.             }
  4185.             
  4186.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4187.                 $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4188.                 $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4189.             }
  4190.             // $summarySheet->setCellValue("A" . $totalRow, "Total");
  4191.             // $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4192.             // $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4193.             // $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4194.             // $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4195.             // $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4196.             // $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4197.             // $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4198.             // $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4199.             // $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4200.             // $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4201.             // $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
  4202.             // $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
  4203.             // $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
  4204.             // $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
  4205.             // $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
  4206.             // $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
  4207.             $summarySheet->setCellValue("AN" $sumRow'=T'.$sumRow.'-AE'.$sumRow);
  4208.             $summarySheet->setCellValue("AO" $sumRow'=U'.$sumRow.'-AF'.$sumRow);
  4209.             $grossProfitMargin 0;
  4210.             if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4211.                 $grossProfitMargin '=(T'.$sumRow'-AE'.$sumRow.')/T'.$sumRow;
  4212.                 $summarySheet->setCellValue("AP" $sumRow$grossProfitMargin);
  4213.             }else{
  4214.                 $summarySheet->setCellValue("AP" $sumRow$grossProfitMargin);
  4215.             }
  4216.             $grossProfitMarginAllocated 0;
  4217.             if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  4218.                 $grossProfitMarginAllocated '=(U'.$sumRow'-AF'.$sumRow.')/U'.$sumRow;
  4219.                 $summarySheet->setCellValue("AQ" $sumRow$grossProfitMarginAllocated);
  4220.             }else{
  4221.                 $summarySheet->setCellValue("AQ" $sumRow$grossProfitMarginAllocated);
  4222.             }
  4223.             $summarySheet->setCellValue("AR" $sumRow'=I'.$sumRow.'-AJ'.$sumRow);
  4224.             $summarySheet->setCellValue("AS" $sumRow'=J'.$sumRow.'-AK'.$sumRow);
  4225.             $grossProfitMarginFinancialYear 0;
  4226.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  4227.                 $grossProfitMarginFinancialYear '=(I'.$sumRow'-AJ'.$sumRow.')/I'.$sumRow;
  4228.                 $summarySheet->setCellValue("AT" $sumRow$grossProfitMarginFinancialYear);
  4229.             }else{
  4230.                 $summarySheet->setCellValue("AT" $sumRow$grossProfitMarginFinancialYear);
  4231.             }
  4232.             $grossProfitMarginFinancialYearAllocated 0;
  4233.             if ($project[0]->getInvRevenueByFinancialYearSgd($financialYeartrue) > 0) {
  4234.                 $grossProfitMarginFinancialYearAllocated '=(J'.$sumRow'-AK'.$sumRow.')/J'.$sumRow;
  4235.                 $summarySheet->setCellValue("AU" $sumRow$grossProfitMarginFinancialYearAllocated);
  4236.             }else{
  4237.                 $summarySheet->setCellValue("AU" $sumRow$grossProfitMarginFinancialYearAllocated);
  4238.             }
  4239.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
  4240.             // $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4241.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4242.             $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  4243.             $sumOverallTotals['G'][] = 'G'.$sumRow;
  4244.             $sumOverallTotals['H'][] = 'H'.$sumRow;
  4245.             $sumOverallTotals['I'][] = 'I'.$sumRow;
  4246.             $sumOverallTotals['J'][] = 'J'.$sumRow;
  4247.             $sumOverallTotals['K'][] = 'K'.$sumRow;
  4248.             $sumOverallTotals['L'][] = 'L'.$sumRow;
  4249.             $sumOverallTotals['T'][] = 'T'.$sumRow;
  4250.             $sumOverallTotals['U'][] = 'U'.$sumRow;
  4251.             $sumOverallTotals['AE'][] = 'AE'.$sumRow;
  4252.             $sumOverallTotals['AF'][] = 'AF'.$sumRow;
  4253.             $sumOverallTotals['AH'][] = 'AH'.$sumRow;
  4254.             $sumOverallTotals['AI'][] = 'AI'.$sumRow;
  4255.             $sumOverallTotals['AJ'][] = 'AJ'.$sumRow;
  4256.             $sumOverallTotals['AK'][] = 'AK'.$sumRow;
  4257.             $sumOverallTotals['AL'][] = 'AL'.$sumRow;
  4258.             $sumOverallTotals['AM'][] = 'AM'.$sumRow;
  4259.             $sumRow++;
  4260.         }
  4261.         $sumRow $sumRow+1;
  4262.         $summarySheet->setCellValue("A"$sumRow"Overall Total");
  4263.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
  4264.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4265.         $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  4266.         $summarySheet->setCellValue("G" $sumRow'='.implode('+'$sumOverallTotals['G']));
  4267.         $summarySheet->setCellValue("H" $sumRow'='.implode('+'$sumOverallTotals['H']));
  4268.         $summarySheet->setCellValue("I" $sumRow'='.implode('+'$sumOverallTotals['I']));
  4269.         $summarySheet->setCellValue("J" $sumRow'='.implode('+'$sumOverallTotals['J']));
  4270.         $summarySheet->setCellValue("K" $sumRow'='.implode('+'$sumOverallTotals['K']));
  4271.         $summarySheet->setCellValue("L" $sumRow'='.implode('+'$sumOverallTotals['L']));
  4272.         $summarySheet->setCellValue("T" $sumRow'='.implode('+'$sumOverallTotals['T']));
  4273.         $summarySheet->setCellValue("U" $sumRow'='.implode('+'$sumOverallTotals['U']));
  4274.         $summarySheet->setCellValue("AE" $sumRow'='.implode('+'$sumOverallTotals['AE']));
  4275.         $summarySheet->setCellValue("AF" $sumRow'='.implode('+'$sumOverallTotals['AF']));
  4276.         $summarySheet->setCellValue("AH" $sumRow'='.implode('+'$sumOverallTotals['AH']));
  4277.         $summarySheet->setCellValue("AI" $sumRow'='.implode('+'$sumOverallTotals['AI']));
  4278.         $summarySheet->setCellValue("AJ" $sumRow'='.implode('+'$sumOverallTotals['AJ']));
  4279.         $summarySheet->setCellValue("AK" $sumRow'='.implode('+'$sumOverallTotals['AK']));
  4280.         $summarySheet->setCellValue("AL" $sumRow'='.implode('+'$sumOverallTotals['AL']));
  4281.         $summarySheet->setCellValue("AM" $sumRow'='.implode('+'$sumOverallTotals['AM']));
  4282.         $summarySheet->setCellValue("AN" $sumRow'=T'.$sumRow.'-AE'.$sumRow);
  4283.         $summarySheet->setCellValue("AO" $sumRow'=U'.$sumRow.'-AF'.$sumRow);
  4284.         $summarySheet->setCellValue("AR" $sumRow'=I'.$sumRow.'-AJ'.$sumRow);
  4285.         $summarySheet->setCellValue("AS" $sumRow'=J'.$sumRow.'-AK'.$sumRow);
  4286.         $summarySheet->setCellValue("AP" $sumRow,'=IF(T'.$sumRow.'=0, "",(T'.$sumRow'-AE'.$sumRow.')/T'.$sumRow.')');
  4287.         $summarySheet->setCellValue("AQ" $sumRow,'=IF(U'.$sumRow.'=0, "",(U'.$sumRow'-AF'.$sumRow.')/U'.$sumRow.')');
  4288.         $summarySheet->setCellValue("AT" $sumRow,'=IF(I'.$sumRow.'=0, "",(I'.$sumRow'-AJ'.$sumRow.')/I'.$sumRow.')');
  4289.         $summarySheet->setCellValue("AU" $sumRow,'=IF(J'.$sumRow.'=0, "",(J'.$sumRow'-AK'.$sumRow.')/J'.$sumRow.')');
  4290.         $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4291.         $summarySheet->getStyle("V1:V" $summarySheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4292.         $summarySheet->setAutoFilter('A1:' $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
  4293.         $summarySheet->getStyle('G2:L' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4294.         $summarySheet->getStyle('Q2:R' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4295.         $summarySheet->getStyle('T2:U' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4296.         $summarySheet->getStyle('AB2:AC' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4297.         $summarySheet->getStyle('AE2:AF' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4298.         $summarySheet->getStyle('AH2:AO' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4299.         $summarySheet->getStyle('AN2:AO' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4300.         $summarySheet->getStyle('AR2:AS' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4301.         $summarySheet->getStyle("AP2:AQ"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4302.         $summarySheet->getStyle("AT2:AU"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4303.         /** 
  4304.          * 
  4305.          * Amount Left Invoices
  4306.          */
  4307.         // $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
  4308.         // $spreadsheet->addSheet($unallocatedSheet, 2);
  4309.         // $unallocatedSheet->setCellValue('A1', 'Invoice');
  4310.         // $unallocatedSheet->setCellValue('B1', 'Vendor Name');
  4311.         // $unallocatedSheet->setCellValue('C1', 'Client');
  4312.         // $unallocatedSheet->setCellValue('D1', 'Project');
  4313.         // $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
  4314.         // $unallocatedSheet->setCellValue('F1', 'Amount USD');
  4315.         // $unallocatedSheet->setCellValue('G1', 'Allocated USD');
  4316.         // $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
  4317.         // $unallocatedSheet->setCellValue('I1', 'Date');
  4318.         // $unallocatedSheet->setCellValue('J1', 'Due Date');
  4319.         // $unallocatedSheet->setCellValue('K1', 'Client INV');
  4320.         // $unallocatedSheet->setCellValue('L1', 'Status');
  4321.         // $unallocatedSheet->setCellValue('M1', 'Financial Year');
  4322.         // $lastColx = $unallocatedSheet->getHighestColumn();
  4323.         // $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
  4324.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
  4325.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4326.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4327.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
  4328.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
  4329.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  4330.         // try {
  4331.         //     $currentRow = $unallocatedSheet->getHighestRow();
  4332.         //     $invoiceProjectMap = [];
  4333.         //     foreach ($projectsList as $project) {
  4334.         //         $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  4335.                 
  4336.         //         if ($vendorQuotationPlannings) {
  4337.         //             foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4338.         //                 $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4339.                         
  4340.         //                 foreach ($vqpInvoices as $vqpInvoice) {
  4341.         //                     $vendorInvoice = $vqpInvoice->getVendorInvoice();
  4342.                             
  4343.         //                     if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
  4344.         //                     if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
  4345.                             
  4346.         //                     $invoiceId = $vendorInvoice->getVendorInvoiceNo();
  4347.                             
  4348.         //                     if (!isset($invoiceProjectMap[$invoiceId])) {
  4349.         //                         $invoiceProjectMap[$invoiceId] = [
  4350.         //                             'invoice' => $vendorInvoice,
  4351.         //                             'projects' => [],
  4352.         //                             'vendorName' => '',
  4353.         //                             'xeroContact' => null
  4354.         //                         ];
  4355.         //                     }
  4356.                             
  4357.         //                     // Add project information
  4358.         //                     $invoiceProjectMap[$invoiceId]['projects'][] = [
  4359.         //                         'project' => $vendorQuotationPlanning->getProject(),
  4360.         //                         'client' => $vendorQuotationPlanning->getProject()->getClient(),
  4361.         //                         'vendorQuotationPlanning' => $vendorQuotationPlanning,
  4362.         //                         'amount' => $vqpInvoice->getAmountUsd(),
  4363.         //                     ];
  4364.         //                 }
  4365.         //             }
  4366.         //         }
  4367.         //     }
  4368.             
  4369.         //     // Second pass: Write to spreadsheet with merged cells for same invoice
  4370.         //     foreach ($invoiceProjectMap as $invoiceId => $data) {
  4371.         //         $vendorInvoice = $data['invoice'];
  4372.         //         $projects = $data['projects'];
  4373.         //         $startRow = $currentRow;
  4374.                 
  4375.         //         // Get vendor name
  4376.         //         $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
  4377.         //         $vendorName = '';
  4378.         //         if ($vendorInvoice->getXeroContactId()) {
  4379.         //             $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
  4380.         //         } else {
  4381.         //             $vendorName = $vendorInvoice->getVendor()->getName();
  4382.         //         }
  4383.                 
  4384.         //         // Get client invoices
  4385.         //         $clientInvoices = [];
  4386.         //         if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
  4387.         //             foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
  4388.         //                 $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  4389.         //                 array_push($clientInvoices, $clientInv);
  4390.         //             }
  4391.         //         }
  4392.                 
  4393.         //         // Write data for each project
  4394.         //         foreach ($projects as $index => $projectData) {
  4395.         //             $project = $projectData['project'];
  4396.                     
  4397.         //             // Write project-specific information
  4398.         //             $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
  4399.         //             $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
  4400.                     
  4401.         //             // Set project hyperlink
  4402.         //             $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
  4403.         //             $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
  4404.                     
  4405.         //             // Write amount for this project
  4406.         //             $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
  4407.                     
  4408.         //             // For the first project entry, write the shared invoice information
  4409.         //             if ($index === 0) {
  4410.         //                 $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
  4411.         //                 $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
  4412.         //                 $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
  4413.         //                 $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
  4414.         //                 $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
  4415.         //                 $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
  4416.         //                 $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
  4417.         //                 $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
  4418.         //                 $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
  4419.         //             }
  4420.                     
  4421.         //             // Handle vendor quotes
  4422.         //             if ($projectData['vendorQuotationPlanning']) {
  4423.         //                 $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
  4424.         //                 if (!empty($vendorQuotations)) {
  4425.         //                     foreach($vendorQuotations as $vendorQoute){
  4426.         //                         $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
  4427.         //                         $currentRow++;
  4428.         //                     }
  4429.         //                 } else {
  4430.         //                     $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  4431.         //                 }
  4432.         //             } else {
  4433.         //                 $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  4434.         //             }
  4435.                     
  4436.         //             $currentRow++;
  4437.         //         }
  4438.                 
  4439.         //         // If we have multiple projects, merge the shared invoice cells
  4440.         //         if (count($projects) > 1) {
  4441.         //             $endRow = $currentRow - 1;
  4442.         //             $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
  4443.                     
  4444.         //             foreach ($columnsToMerge as $column) {
  4445.         //                 if ($startRow < $endRow) {
  4446.         //                     $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
  4447.         //                     $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
  4448.         //                         ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4449.         //                 }
  4450.         //             }
  4451.         //         }
  4452.         //     }
  4453.         // } catch (\Exception $e) {
  4454.         //     dd($e->getMessage());
  4455.         // }
  4456.         // $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
  4457.         // $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  4458.         
  4459.         // Write the file
  4460.         $writer = new Xlsx($spreadsheet);
  4461.         $writer->save($filename);
  4462.         if ($_target == 'google') {
  4463.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  4464.             if ($gsheetURL) {
  4465.                 unlink($filename);
  4466.                 return new RedirectResponse($gsheetURL302);
  4467.             }
  4468.         } else {
  4469.             $response = new Response();
  4470.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  4471.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  4472.             $response->setContent(file_get_contents($filename));
  4473.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  4474.             $response->headers->set('Content-Transfer-Encoding''binary');
  4475.             $response->headers->set('Pragma''no-cache');
  4476.             $response->headers->set('Expires''0');
  4477.             unlink($filename);
  4478.             return $response;
  4479.             exit;
  4480.         }
  4481.     }
  4482.     // Export Project Revenue Cost Date Range [PENDING]
  4483.     
  4484.     public function exportProjectRevenueCostDateRange($isAdmin$startDate$endDate$baseurl$_target)
  4485.     {
  4486.         $startDateRange date("d-M-Y"strtotime($startDate));
  4487.         $endDateRange date("d-M-Y"strtotime($endDate));
  4488.         $overallTotals = [];
  4489.         $lineItemTotals = [];
  4490.         $overallTotalRevenue 0;
  4491.         $overallTotalCost 0;
  4492.         $spreadsheet = new Spreadsheet();
  4493.         $sheet $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
  4494.         $sheet->setCellValue('A1''Today\'s Date');
  4495.         $sheet->setCellValue('A2''From (Project Start Date)');
  4496.         $sheet->setCellValue('A3''To (Project Start Date)');
  4497.         $sheet->setCellValue('C1'date('d-M-Y'));
  4498.         $sheet->setCellValue('C2'$startDateRange);
  4499.         $sheet->setCellValue('C3'$endDateRange);
  4500.         // Define Header Data
  4501.         $sheet->setCellValue('A5''Client');
  4502.         $sheet->setCellValue('B5''Project ID');
  4503.         $sheet->setCellValue('C5''Project Name');
  4504.         $sheet->setCellValue('D5''Project Status');
  4505.         $sheet->setCellValue('E5''Start Date');
  4506.         $sheet->setCellValue('F5''End Date');
  4507.         // $sheet->setCellValue('G5', 'Revenue FY ' . $fyStart);
  4508.         // $sheet->setCellValue('H5', 'Revenue FY ' . $fyStart . ' Amount Allocated');
  4509.         // $sheet->setCellValue('I5', 'Revenue FY ' . $financialYear);
  4510.         // $sheet->setCellValue('J5', 'Revenue FY ' . $financialYear . ' Amount Allocated');
  4511.         // $sheet->setCellValue('K5', 'Revenue FY ' . $fyEnd);
  4512.         // $sheet->setCellValue('L5', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
  4513.         $sheet->setCellValue('G5''MT INV No.');
  4514.         $sheet->setCellValue('H5''INV Date');
  4515.         $sheet->setCellValue('I5''INV Due Date');
  4516.         $sheet->setCellValue('J5''INV Currency');
  4517.         $sheet->setCellValue('K5''INV Amount (w/o Taxes)');
  4518.         $sheet->setCellValue('L5''INV Amount Allocated (w/o Taxes)');
  4519.         $sheet->setCellValue('M5''SGD FX Rate');
  4520.         $sheet->setCellValue('N5''INV Amount (w/o Taxes in SGD)');
  4521.         $sheet->setCellValue('O5''INV Amount Allocated (w/o Taxes in SGD)');
  4522.         $sheet->setCellValue('P5''Item Code');
  4523.         $sheet->setCellValue('Q5''Amount Item Code');
  4524.         $sheet->setCellValue('R5''Department');
  4525.         $sheet->setCellValue('S5''');
  4526.         $sheet->setCellValue('T5''Vendor');
  4527.         $sheet->setCellValue('U5''Vendor INV No.');
  4528.         $sheet->setCellValue('V5''Vendor INV Date');
  4529.         $sheet->setCellValue('W5''Vendor INV Due Date');
  4530.         $sheet->setCellValue('X5''Vendor INV Currency');
  4531.         $sheet->setCellValue('Y5''Vendor INV Amount (w/o Taxes)');
  4532.         $sheet->setCellValue('Z5''Vendor INV Amount Allocated (w/o Taxes)');
  4533.         $sheet->setCellValue('AA5''SGD FX Rate');
  4534.         $sheet->setCellValue('AB5''Vendor INV Amount (w/o Taxes in SGD)');
  4535.         $sheet->setCellValue('AC5''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4536.         $sheet->setCellValue('AD5''Client INV No');
  4537.         // $sheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
  4538.         // $sheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
  4539.         // $sheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
  4540.         // $sheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
  4541.         // $sheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
  4542.         // $sheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
  4543.         $sheet->setCellValue('AE5''Gross Profit Total');
  4544.         $sheet->setCellValue('AF5''Gross Profit Total Amount Allocated');
  4545.         $sheet->setCellValue('AG5''Gross Profit Margin Total');
  4546.         $sheet->setCellValue('AH5''Gross Profit Margin Total Amount Allocated');
  4547.         // $sheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
  4548.         // $sheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
  4549.         // $sheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
  4550.         // $sheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
  4551.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4552.         $sheet->getDefaultColumnDimension()->setWidth(25);
  4553.         $sheet->getColumnDimension('S')->setWidth(3);
  4554.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
  4555.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4556.         $sheet->getStyle("A5:" $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4557.         $sheet->getStyle("A6:" $sheet->getHighestColumn() . "6")->getFont()->setBold(false);
  4558.         $sheet->freezePane('A6');
  4559.         $filename "Project_Revenue_vs_Cost_" $startDateRange " - " $endDateRange "_" date('Y-m-d') . '.xlsx';
  4560.         // $type = "LEAD;CONFIRMED";
  4561.         $type "CONFIRMED";
  4562.         $status "On-Going;Finished";
  4563.         $projectsList $this->projectRepository->findByPage(09999"""ASC"'client'$startDate$endDate$type0$status);
  4564.         $row $sheet->getHighestRow();
  4565.         $overallRow $row+1;
  4566.         if(count($projectsList)){
  4567.             foreach ($projectsList as $project) {
  4568.                 $sheet->setCellValue("A" $row$project['clientName']);
  4569.                 $sheet->setCellValue("B" $row$project['generatedId']);
  4570.                 $sheet->getCell("B" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4571.                 $sheet->getStyle('B' $row)->getFont()->setUnderline(true);
  4572.                 $sheet->setCellValue("C" $row$project['name']);
  4573.                 $sheet->getCell("C" $row)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4574.                 $sheet->getStyle('C' $row)->getFont()->setUnderline(true);
  4575.                 $sheet->setCellValue("D" $row$project['status']);
  4576.                 $sheet->setCellValue("E" $row$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4577.                 $sheet->setCellValue("F" $row$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4578.                 
  4579.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4580.                     $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4581.                     $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4582.                 }
  4583.                 // looping project invoice
  4584.                 $invRow $row;
  4585.                 $projectSalesOrders $project[0]->getProjectSalesOrders();
  4586.                 $InvTotalwoTax 0;
  4587.                 if ($projectSalesOrders) {
  4588.                     foreach ($projectSalesOrders as $pso) {
  4589.                         $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4590.                         foreach ($soInvoices as $soInvoice) {
  4591.                             $invoice $soInvoice->getInvoice();
  4592.                             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4593.                             $sheet->setCellValue("G" $invRow$invoice->getInvoiceNo());
  4594.                             $sheet->setCellValue("H" $invRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4595.                             $sheet->setCellValue("I" $invRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4596.                             $sheet->setCellValue("J" $invRow$invoice->getCurrency()->getIso());
  4597.                             $InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
  4598.                             $sheet->setCellValue("K" $invRow$invoice->getSubTotal());
  4599.                             $sheet->setCellValue("L" $invRow$soInvoice->getAmount());
  4600.                             $sheet->setCellValue("M" $invRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4601.                             $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4602.                             $sheet->setCellValue("N" $invRow$invoice->getSubTotalSgd($project[0]));
  4603.                             $sheet->setCellValue("O" $invRow$amountSGD);
  4604.                             if($invoice->getXeroLineItems()->count() > 0) {
  4605.                                 $lineItemRow $invRow;
  4606.                                 foreach ($invoice->getXeroLineItems() as $lineItem) {
  4607.                                     $sheet->setCellValue("P" $lineItemRow$lineItem->getItemCode());
  4608.                                     $sheet->setCellValue("Q" $lineItemRow$lineItem->getSubTotal());
  4609.                                     $sheet->setCellValue("R" $lineItemRow$lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-');
  4610.                                     $itemCode $lineItem->getItemCode();
  4611.                                     $department $lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-';
  4612.                                     $amount $lineItem->getSubTotal();
  4613.                                     if (!isset($lineItemTotals[$itemCode])) {
  4614.                                         $lineItemTotals[$itemCode] = [];
  4615.                                     }
  4616.                                     if (!isset($lineItemTotals[$itemCode]['department'])) {
  4617.                                         $lineItemTotals[$itemCode]['department'] = $department;
  4618.                                     }
  4619.                                     if (!isset($lineItemTotals[$itemCode]['amount'])) {
  4620.                                         $lineItemTotals[$itemCode]['amount'] = 0;
  4621.                                     }else{
  4622.                                         $lineItemTotals[$itemCode]['amount'] += $amount;
  4623.                                     }
  4624.                                     $lineItemRow++;
  4625.                                 
  4626.                                 }
  4627.                             }
  4628.                             $invRow $lineItemRow $invRow $lineItemRow $invRow;
  4629.                         }
  4630.                     }
  4631.                 } else {
  4632.                     $sheet->setCellValue("G" $invRow"-");
  4633.                     $sheet->setCellValue("H" $invRow"-");
  4634.                     $sheet->setCellValue("I" $invRow"-");
  4635.                     $sheet->setCellValue("J" $invRow"-");
  4636.                     $sheet->setCellValue("K" $invRow"-");
  4637.                     $sheet->setCellValue("L" $invRow"-");
  4638.                     $sheet->setCellValue("M" $invRow"-");
  4639.                     $sheet->setCellValue("N" $invRow"-");
  4640.                     $sheet->setCellValue("O" $invRow"-");
  4641.                 }
  4642.                 //looping vendor invoice
  4643.                 $vendorInvRow $row;
  4644.                 $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4645.                 $vendorTotalWoTax 0;
  4646.                 if ($vendorQuotationPlannings) {
  4647.                     foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4648.                         $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4649.                         $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4650.                         foreach ($vqpInvoices as $vqpInvoice) {
  4651.                             $invoice $vqpInvoice->getVendorInvoice();
  4652.                             // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4653.                             $sheet->setCellValue("T" $vendorInvRow$vendorName);
  4654.                             $sheet->setCellValue("U" $vendorInvRow$invoice->getInvoiceNo());
  4655.                             $sheet->setCellValue("V" $vendorInvRow$invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4656.                             $sheet->setCellValue("W" $vendorInvRow$invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4657.                             $sheet->setCellValue("X" $vendorInvRow$invoice->getCurrency()->getIso());
  4658.                             $vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
  4659.                             $sheet->setCellValue("Y" $vendorInvRow$invoice->getSubtotal());
  4660.                             $sheet->setCellValue("Z" $vendorInvRow$vqpInvoice->getAmount());
  4661.                             $sheet->setCellValue("AA" $vendorInvRow$this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4662.                             $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4663.                             $sheet->setCellValue("AB" $vendorInvRow$invoice->getSubTotalSgd($project[0]));
  4664.                             $sheet->setCellValue("AC" $vendorInvRow$vendorAmountSGD);
  4665.                             $sheet->setCellValue("AD" $vendorInvRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4666.                             $vendorInvRow++;
  4667.                         }
  4668.                     }
  4669.                 } else {
  4670.                     $sheet->setCellValue("T" $vendorInvRow"-");
  4671.                     $sheet->setCellValue("U" $vendorInvRow"-");
  4672.                     $sheet->setCellValue("V" $vendorInvRow"-");
  4673.                     $sheet->setCellValue("W" $vendorInvRow"-");
  4674.                     $sheet->setCellValue("X" $vendorInvRow"-");
  4675.                     $sheet->setCellValue("Y" $vendorInvRow"-");
  4676.                     $sheet->setCellValue("Z" $vendorInvRow"-");
  4677.                     $sheet->setCellValue("AA" $vendorInvRow"-");
  4678.                     $sheet->setCellValue("AB" $vendorInvRow"-");
  4679.                     $sheet->setCellValue("AC" $vendorInvRow"-");
  4680.                     $sheet->setCellValue("AD" $vendorInvRow"-");
  4681.                 }
  4682.                 $totalRow $invRow $row || $vendorInvRow $row max($invRow$vendorInvRow) : $row 1;
  4683.                 $sheet->setCellValue("A" $totalRow"Total");
  4684.                 $sheet->setCellValue("N" $totalRow'=SUM(N'.$row.':N'.($invRow $row $invRow $row).')');
  4685.                 $sheet->setCellValue("O" $totalRow'=SUM(O'.$row.':O'.($invRow $row $invRow $row).')');
  4686.                 $sheet->setCellValue("AB" $totalRow'=SUM(AB'.$row.':AB'.($vendorInvRow $row $vendorInvRow $row).')');
  4687.                 $sheet->setCellValue("AC" $totalRow'=SUM(AC'.$row.':AC'.($vendorInvRow $row $vendorInvRow $row).')');
  4688.                 $sheet->setCellValue("AE" $totalRow'=N'.$totalRow.'-AB'.$totalRow);
  4689.                 $sheet->setCellValue("AE" $row'=N'.$totalRow.'-AB'.$totalRow);
  4690.                 $sheet->setCellValue("AF" $totalRow'=O'.$totalRow.'-AC'.$totalRow);
  4691.                 $sheet->setCellValue("AF" $row'=O'.$totalRow.'-AC'.$totalRow);
  4692.                 $grossProfitMargin 0;
  4693.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4694.                     $grossProfitMargin '=(N'.$totalRow'-AB'.$totalRow.')/N'.$totalRow;
  4695.                     $sheet->setCellValue("AG" $totalRow$grossProfitMargin);
  4696.                     $sheet->setCellValue("AG" $row$grossProfitMargin);
  4697.                 }else{
  4698.                     $sheet->setCellValue("AG" $totalRow$grossProfitMargin);
  4699.                     $sheet->setCellValue("AG" $row$grossProfitMargin);
  4700.                 }
  4701.                 $grossProfitMarginAllocated 0;
  4702.                 if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  4703.                     $grossProfitMarginAllocated '=(O'.$totalRow'-AC'.$totalRow.')/O'.$totalRow;
  4704.                     $sheet->setCellValue("AH" $totalRow$grossProfitMarginAllocated);
  4705.                     $sheet->setCellValue("AH" $row$grossProfitMarginAllocated);
  4706.                 }else{
  4707.                     $sheet->setCellValue("AH" $totalRow$grossProfitMarginAllocated);
  4708.                     $sheet->setCellValue("AH" $row$grossProfitMarginAllocated);
  4709.                 }
  4710.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
  4711.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4712.                 $sheet->getStyle("A" $totalRow ":" $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4713.                 $sheet->getRowDimension($totalRow)->setRowHeight(20);
  4714.                 $overallTotals['N'][] = 'N'.$totalRow;
  4715.                 $overallTotals['O'][] = 'O'.$totalRow;
  4716.                 $overallTotals['AB'][] = 'AB'.$totalRow;
  4717.                 $overallTotals['AC'][] = 'AC'.$totalRow;
  4718.                 $row $totalRow;
  4719.                 $row++;
  4720.             }
  4721.             //overall total
  4722.             $overallRow $row+1;
  4723.             $row $row+1;
  4724.             $sheet->setCellValue("A"$row"Overall Total");
  4725.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4726.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  4727.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4728.             
  4729.             $sheet->getRowDimension($row)->setRowHeight(20);
  4730.             $sheet->setCellValue("N" $row'='.implode('+'$overallTotals['N']));
  4731.             $sheet->setCellValue("O" $row'='.implode('+'$overallTotals['O']));
  4732.             $sheet->setCellValue("AB" $row'='.implode('+'$overallTotals['AB']));
  4733.             $sheet->setCellValue("AC" $row'='.implode('+'$overallTotals['AC']));
  4734.             $sheet->setCellValue("AE" $row'=N'.$row.'-AB'.$row);
  4735.             $sheet->setCellValue("AF" $row'=O'.$row.'-AC'.$row);
  4736.             $sheet->setCellValue("AG" $row,'=IF(N'.$row.'=0, "",(N'.$row'-AB'.$row.')/N'.$row.')');
  4737.             $sheet->setCellValue("AH" $row,'=IF(O'.$row.'=0, "",(O'.$row'-AC'.$row.')/O'.$row.')');
  4738.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4739.             $row $row+2;
  4740.             $sheet->setCellValue("A" $row"Summary");
  4741.             $sheet->getStyle("A" $row ":" $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
  4742.             $row $row+1;
  4743.             $sheet->setCellValue("A" $row"Item Code");
  4744.             $sheet->setCellValue("B" $row"Department");
  4745.             $sheet->setCellValue("C" $row"Amount");
  4746.             $sheet->getStyle("A" $row ":C" $row)->getFont()->setBold(true);
  4747.             $sheet->getStyle("A" $row ":C" $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  4748.             $row $row+1;
  4749.             foreach ($lineItemTotals as $itemCode => $itemTotal) {
  4750.                 $sheet->setCellValue("A" $row$itemCode);
  4751.                 $sheet->setCellValue("B" $row$itemTotal['department']);
  4752.                 $sheet->setCellValue("C" $row$itemTotal['amount']);
  4753.                 $sheet->getStyle('C' $row)->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4754.                 $row++;
  4755.             }
  4756.         }   
  4757.         $sheet->getStyle("S5:S" $overallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4758.         $sheet->setAutoFilter('A5:' $sheet->getHighestColumn() . $sheet->getHighestRow());
  4759.         $sheet->getStyle('K2:L' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  4760.         $sheet->getStyle('N2:O' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4761.         $sheet->getStyle('Q2:Q' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4762.         $sheet->getStyle('Y2:Z' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4763.         $sheet->getStyle('AB2:AC' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4764.         $sheet->getStyle('AE2:AF' $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  4765.         $sheet->getStyle("AG2:AH"$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  4766.         $summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet'Summary Total');
  4767.         $spreadsheet->addSheet($summarySheet1);
  4768.         $summarySheet->setCellValue('A1''Today\'s Date');
  4769.         $summarySheet->setCellValue('A2''From (Project Start Date)');
  4770.         $summarySheet->setCellValue('A3''To (Project Start Date)');
  4771.         $summarySheet->setCellValue('C1'date('d-M-Y'));
  4772.         $summarySheet->setCellValue('C2'$startDateRange);
  4773.         $summarySheet->setCellValue('C3'$endDateRange);
  4774.         $summarySheet->setCellValue('A5''Client');
  4775.         $summarySheet->setCellValue('B5''Project ID');
  4776.         $summarySheet->setCellValue('C5''Project Name');
  4777.         $summarySheet->setCellValue('D5''Project Status');
  4778.         $summarySheet->setCellValue('E5''Start Date');
  4779.         $summarySheet->setCellValue('F5''End Date');
  4780.         // $summarySheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
  4781.         // $summarySheet->setCellValue('H1', 'Revenue FY ' . $fyStart . ' Amount Allocated');
  4782.         // $summarySheet->setCellValue('I1', 'Revenue FY ' . $financialYear);
  4783.         // $summarySheet->setCellValue('J1', 'Revenue FY ' . $financialYear . ' Amount Allocated');
  4784.         // $summarySheet->setCellValue('K1', 'Revenue FY ' . $fyEnd);
  4785.         // $summarySheet->setCellValue('L1', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
  4786.         $summarySheet->setCellValue('G5''MT INV No.');
  4787.         $summarySheet->setCellValue('H5''INV Date');
  4788.         $summarySheet->setCellValue('I5''INV Due Date');
  4789.         $summarySheet->setCellValue('J5''INV Currency');
  4790.         $summarySheet->setCellValue('K5''INV Amount (w/o Taxes)');
  4791.         $summarySheet->setCellValue('L5''INV Amount Allocated (w/o Taxes)');
  4792.         $summarySheet->setCellValue('M5''SGD FX Rate');
  4793.         $summarySheet->setCellValue('N5''INV Amount (w/o Taxes in SGD)');
  4794.         $summarySheet->setCellValue('O5''INV Amount Allocated (w/o Taxes in SGD)');
  4795.         $summarySheet->setCellValue('P5''');
  4796.         $summarySheet->setCellValue('Q5''Vendor');
  4797.         $summarySheet->setCellValue('R5''Vendor INV No.');
  4798.         $summarySheet->setCellValue('S5''Vendor INV Date');
  4799.         $summarySheet->setCellValue('T5''Vendor INV Due Date');
  4800.         $summarySheet->setCellValue('U5''Vendor INV Currency');
  4801.         $summarySheet->setCellValue('V5''Vendor INV Amount (w/o Taxes)');
  4802.         $summarySheet->setCellValue('W5''Vendor INV Amount Allocated (w/o Taxes)');
  4803.         $summarySheet->setCellValue('X5''SGD FX Rate');
  4804.         $summarySheet->setCellValue('Y5''Vendor INV Amount (w/o Taxes in SGD)');
  4805.         $summarySheet->setCellValue('Z5''Vendor INV Amount Allocated (w/o Taxes in SGD)');
  4806.         $summarySheet->setCellValue('AA5''Client INV No');
  4807.         // $summarySheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
  4808.         // $summarySheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
  4809.         // $summarySheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
  4810.         // $summarySheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
  4811.         // $summarySheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
  4812.         // $summarySheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
  4813.         $summarySheet->setCellValue('AB5''Gross Profit Total');
  4814.         $summarySheet->setCellValue('AC5''Gross Profit Total Amount Allocated');
  4815.         $summarySheet->setCellValue('AD5''Gross Profit Margin Total');
  4816.         $summarySheet->setCellValue('AE5''Gross Profit Margin Total Amount Allocated');
  4817.         // $summarySheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
  4818.         // $summarySheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
  4819.         // $summarySheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
  4820.         // $summarySheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
  4821.         // $sheet->setCellValue('AG1', 'Total Revenue');
  4822.         $summarySheet->getDefaultColumnDimension()->setWidth(25);
  4823.         $summarySheet->getColumnDimension('P')->setWidth(3);
  4824.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFont()->setBold(true);
  4825.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  4826.         $summarySheet->getStyle("A5:" $summarySheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  4827.         // $summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4828.         // $summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4829.         // $summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4830.         // $summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4831.         // $summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4832.         // $summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4833.         // $summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4834.         // $summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4835.         // $summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4836.         // $summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4837.         // $summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4838.         // $summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4839.         // $summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4840.         // $summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
  4841.         $summarySheet->getStyle("A6:" $summarySheet->getHighestColumn() . "6")->getFont()->setBold(false);
  4842.         $summarySheet->freezePane('A6');
  4843.         // $type = "LEAD;CONFIRMED";
  4844.         $type "CONFIRMED";
  4845.         $status "On-Going;Finished";
  4846.         $projectsListSummary $this->projectRepository->findByPage(09999"""ASC"'client'$startDate$endDate$type0$status);
  4847.         
  4848.         $sumOverallTotals = [];
  4849.         $sumRow $summarySheet->getHighestRow();
  4850.         $sumOverallRow $sumRow+1;
  4851.         if(count($projectsListSummary) > 0){
  4852.             foreach ($projectsListSummary as $project) {
  4853.                 $summarySheet->setCellValue("A" $sumRow$project['clientName']);
  4854.                 $summarySheet->setCellValue("B" $sumRow$project['generatedId']);
  4855.                 $summarySheet->getCell("B" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4856.                 $summarySheet->getStyle('B' $sumRow)->getFont()->setUnderline(true);
  4857.                 $summarySheet->setCellValue("C" $sumRow$project['name']);
  4858.                 $summarySheet->getCell("C" $sumRow)->getHyperlink()->setUrl($baseurl '/project-management/project/view/' $project['id']);
  4859.                 $summarySheet->getStyle('C' $sumRow)->getFont()->setUnderline(true);
  4860.                 $summarySheet->setCellValue("D" $sumRow$project['status']);
  4861.                 $summarySheet->setCellValue("E" $sumRow$project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
  4862.                 $summarySheet->setCellValue("F" $sumRow$project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
  4863.                 // $summarySheet->setCellValue("G" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4864.                 // $summarySheet->setCellValue("H" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4865.                 // $summarySheet->setCellValue("I" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4866.                 // $summarySheet->setCellValue("J" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4867.                 // $summarySheet->setCellValue("K" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4868.                 // $summarySheet->setCellValue("L" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4869.                 // $summarySheet->setCellValue("AH" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
  4870.                 // $summarySheet->setCellValue("AI" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart, true));
  4871.                 // $summarySheet->setCellValue("AJ" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
  4872.                 // $summarySheet->setCellValue("AK" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear, true));
  4873.                 // $summarySheet->setCellValue("AL" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
  4874.                 // $summarySheet->setCellValue("AM" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd, true));
  4875.                 $projectSalesOrders $project[0]->getProjectSalesOrders();
  4876.                 $invData = [
  4877.                     'totalAmount' => 0,
  4878.                     'totalAmountSGD' => 0,
  4879.                     'totalAmountAllocated' => 0,
  4880.                     'totalAmountAllocatedSGD' => 0,
  4881.                 ];
  4882.                 if ($projectSalesOrders) {
  4883.                     foreach ($projectSalesOrders as $pso) {
  4884.                         $soInvoices $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
  4885.                         foreach ($soInvoices as $soInvoice) {
  4886.                             $invoice $soInvoice->getInvoice();
  4887.                             if ($invoice->getXeroStatus() == 'VOIDED') continue;
  4888.                             $summarySheet->setCellValue("G" $sumRow"-");
  4889.                             $summarySheet->setCellValue("H" $sumRow"-");
  4890.                             $summarySheet->setCellValue("I" $sumRow"-");
  4891.                             $summarySheet->setCellValue("J" $sumRow$invoice->getCurrency()->getIso());
  4892.                             $invData['totalAmount'] += $invoice->getSubTotal();
  4893.                             $invData['totalAmountAllocated'] += $soInvoice->getAmount();
  4894.                             $invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4895.                             $amountSGD $invoice->getCurrency()->getIso() == 'SGD' $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
  4896.                             $invData['totalAmountAllocatedSGD'] += $amountSGD;
  4897.                             $summarySheet->setCellValue("K" $sumRow$invData['totalAmount']);
  4898.                             $summarySheet->setCellValue("L" $sumRow$invData['totalAmountAllocated']);
  4899.                             // $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4900.                             
  4901.                             $summarySheet->setCellValue("N" $sumRow$invData['totalAmountSGD']);
  4902.                             $summarySheet->setCellValue("O" $sumRow$invData['totalAmountAllocatedSGD']);
  4903.                         }
  4904.                     }
  4905.                 } else {
  4906.                     $summarySheet->setCellValue("G" $sumRow"-");
  4907.                     $summarySheet->setCellValue("H" $sumRow"-");
  4908.                     $summarySheet->setCellValue("I" $sumRow"-");
  4909.                     $summarySheet->setCellValue("J" $sumRow"-");
  4910.                     $summarySheet->setCellValue("K" $sumRow"-");
  4911.                     $summarySheet->setCellValue("L" $sumRow"-");
  4912.                     $summarySheet->setCellValue("M" $sumRow"-");
  4913.                     $summarySheet->setCellValue("N" $sumRow"-");
  4914.                     $summarySheet->setCellValue("O" $sumRow"-");
  4915.                 }
  4916.                 $vendorQuotationPlannings $project[0]->getVendorQuotationPlannings();
  4917.                 $vendorData = [
  4918.                     'totalAmount' => 0,
  4919.                     'totalAmountAllocated' => 0,
  4920.                     'totalAmountSGD' => 0,
  4921.                     'totalAmountAllocatedSGD' => 0,
  4922.                 ];
  4923.                 if ($vendorQuotationPlannings) {
  4924.                     foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  4925.                         $vqpInvoices $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  4926.                         $vendorName $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
  4927.                         foreach ($vqpInvoices as $vqpInvoice) {
  4928.                             $invoice $vqpInvoice->getVendorInvoice();
  4929.                             $summarySheet->setCellValue("Q" $sumRow"-");
  4930.                             $summarySheet->setCellValue("R" $sumRow"-");
  4931.                             $summarySheet->setCellValue("S" $sumRow"-");
  4932.                             $summarySheet->setCellValue("T" $sumRow"-");
  4933.                             $summarySheet->setCellValue("U" $sumRow"-");
  4934.                             // if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
  4935.                             // $summarySheet->setCellValue("W" . $sumRow, $vendorName);
  4936.                             // $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
  4937.                             // $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
  4938.                             // $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
  4939.                             $summarySheet->setCellValue("U" $sumRow$invoice->getCurrency()->getIso());
  4940.                             $vendorData['totalAmount'] += $invoice->getSubTotal();
  4941.                             $vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
  4942.                             $summarySheet->setCellValue("V" $sumRow$vendorData['totalAmount']);
  4943.                             $summarySheet->setCellValue("W" $sumRow$vendorData['totalAmountAllocated']);
  4944.                             // $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
  4945.                             $vendorAmountSGD $invoice->getCurrency()->getIso() == 'SGD' $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
  4946.                             $vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
  4947.                             $vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
  4948.                             $summarySheet->setCellValue("Y" $sumRow$vendorData['totalAmountSGD']);
  4949.                             $summarySheet->setCellValue("Z" $sumRow$vendorData['totalAmountAllocatedSGD']);
  4950.                             $summarySheet->setCellValue('AA'$sumRow$vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
  4951.                         }
  4952.                     }
  4953.                 } else {
  4954.                     $summarySheet->setCellValue("Q" $sumRow"-");
  4955.                     $summarySheet->setCellValue("R" $sumRow"-");
  4956.                     $summarySheet->setCellValue("S" $sumRow"-");
  4957.                     $summarySheet->setCellValue("T" $sumRow"-");
  4958.                     $summarySheet->setCellValue("U" $sumRow"-");
  4959.                     $summarySheet->setCellValue("V" $sumRow"-");
  4960.                     $summarySheet->setCellValue("W" $sumRow"-");
  4961.                     $summarySheet->setCellValue("X" $sumRow"-");
  4962.                     $summarySheet->setCellValue("Y" $sumRow"-");
  4963.                     $summarySheet->setCellValue("Z" $sumRow"-");
  4964.                     $summarySheet->setCellValue("AA" $sumRow"-");
  4965.                 }
  4966.                 
  4967.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4968.                     $overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
  4969.                     $overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
  4970.                 }
  4971.                 // $summarySheet->setCellValue("A" . $totalRow, "Total");
  4972.                 // $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
  4973.                 // $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
  4974.                 // $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
  4975.                 // $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
  4976.                 // $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
  4977.                 // $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
  4978.                 // $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4979.                 // $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
  4980.                 // $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4981.                 // $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
  4982.                 // $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
  4983.                 // $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
  4984.                 // $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
  4985.                 // $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
  4986.                 // $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
  4987.                 // $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
  4988.                 $summarySheet->setCellValue("AB" $sumRow'=N'.$sumRow.'-Y'.$sumRow);
  4989.                 $summarySheet->setCellValue("AC" $sumRow'=O'.$sumRow.'-Z'.$sumRow);
  4990.                 $grossProfitMargin 0;
  4991.                 if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
  4992.                     $grossProfitMargin '=(N'.$sumRow'-Y'.$sumRow.')/N'.$sumRow;
  4993.                     $summarySheet->setCellValue("AD" $sumRow$grossProfitMargin);
  4994.                 }else{
  4995.                     $summarySheet->setCellValue("AD" $sumRow$grossProfitMargin);
  4996.                 }
  4997.                 $grossProfitMarginAllocated 0;
  4998.                 if ($project[0]->getInvRevenueByFinancialYearSgd(nulltrue) > 0) {
  4999.                     $grossProfitMarginAllocated '=(O'.$sumRow'-Z'.$sumRow.')/O'.$sumRow;
  5000.                     $summarySheet->setCellValue("AE" $sumRow$grossProfitMarginAllocated);
  5001.                 }else{
  5002.                     $summarySheet->setCellValue("AE" $sumRow$grossProfitMarginAllocated);
  5003.                 }
  5004.                 // $summarySheet->setCellValue("AR" . $sumRow, '=I'.$sumRow.'-AJ'.$sumRow);
  5005.                 // $summarySheet->setCellValue("AS" . $sumRow, '=J'.$sumRow.'-AK'.$sumRow);
  5006.                 // $grossProfitMarginFinancialYear = 0;
  5007.                 // if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
  5008.                 //     $grossProfitMarginFinancialYear = '=(I'.$sumRow. '-AJ'.$sumRow.')/I'.$sumRow;
  5009.                 //     $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
  5010.                 // }else{
  5011.                 //     $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
  5012.                 // }
  5013.                 // $grossProfitMarginFinancialYearAllocated = 0;
  5014.                 // if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear, true) > 0) {
  5015.                 //     $grossProfitMarginFinancialYearAllocated = '=(J'.$sumRow. '-AK'.$sumRow.')/J'.$sumRow;
  5016.                 //     $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
  5017.                 // }else{
  5018.                 //     $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
  5019.                 // }
  5020.                 $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
  5021.                 // $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
  5022.                 $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5023.                 $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  5024.                 $sumOverallTotals['N'][] = 'N'.$sumRow;
  5025.                 $sumOverallTotals['O'][] = 'O'.$sumRow;
  5026.                 $sumOverallTotals['Y'][] = 'Y'.$sumRow;
  5027.                 $sumOverallTotals['Z'][] = 'Z'.$sumRow;
  5028.                 $sumRow++;
  5029.             }
  5030.             $sumOverallRow $sumRow+1;
  5031.             $sumRow $sumRow+1;
  5032.             $summarySheet->setCellValue("A"$sumRow"Overall Total");
  5033.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5034.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5035.             $summarySheet->getRowDimension($sumRow)->setRowHeight(20);
  5036.             $summarySheet->setCellValue("N" $sumRow'='.implode('+'$sumOverallTotals['N']));
  5037.             $summarySheet->setCellValue("O" $sumRow'='.implode('+'$sumOverallTotals['O']));
  5038.             $summarySheet->setCellValue("Y" $sumRow'='.implode('+'$sumOverallTotals['Y']));
  5039.             $summarySheet->setCellValue("Z" $sumRow'='.implode('+'$sumOverallTotals['Z']));
  5040.             $summarySheet->setCellValue("AB" $sumRow'=N'.$sumRow.'-Y'.$sumRow);
  5041.             $summarySheet->setCellValue("AC" $sumRow'=O'.$sumRow.'-Z'.$sumRow);
  5042.             $summarySheet->setCellValue("AD" $sumRow,'=IF(N'.$sumRow.'=0, "",(N'.$sumRow'-Y'.$sumRow.')/N'.$sumRow.')');
  5043.             $summarySheet->setCellValue("AE" $sumRow,'=IF(O'.$sumRow.'=0, "",(O'.$sumRow'-Z'.$sumRow.')/O'.$sumRow.')');
  5044.             $summarySheet->getStyle("A" $sumRow ":" $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
  5045.         }
  5046.         $summarySheet->getStyle("P5:P" $sumOverallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5047.         $summarySheet->setAutoFilter('A5:' $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
  5048.         $summarySheet->getStyle('K2:L' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
  5049.         $summarySheet->getStyle('N2:O' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5050.         $summarySheet->getStyle('V2:W' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5051.         $summarySheet->getStyle('Y2:Z' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5052.         $summarySheet->getStyle('AB2:AC' $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
  5053.         $summarySheet->getStyle("AD2:AE"$summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
  5054.         // Amount Left Invoices
  5055.         // $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
  5056.         // $spreadsheet->addSheet($unallocatedSheet, 2);
  5057.         // $unallocatedSheet->setCellValue('A1', 'Invoice');
  5058.         // $unallocatedSheet->setCellValue('B1', 'Vendor Name');
  5059.         // $unallocatedSheet->setCellValue('C1', 'Client');
  5060.         // $unallocatedSheet->setCellValue('D1', 'Project');
  5061.         // $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
  5062.         // $unallocatedSheet->setCellValue('F1', 'Amount USD');
  5063.         // $unallocatedSheet->setCellValue('G1', 'Allocated USD');
  5064.         // $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
  5065.         // $unallocatedSheet->setCellValue('I1', 'Date');
  5066.         // $unallocatedSheet->setCellValue('J1', 'Due Date');
  5067.         // $unallocatedSheet->setCellValue('K1', 'Client INV');
  5068.         // $unallocatedSheet->setCellValue('L1', 'Status');
  5069.         // $unallocatedSheet->setCellValue('M1', 'Financial Year');
  5070.         // $lastColx = $unallocatedSheet->getHighestColumn();
  5071.         // $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
  5072.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
  5073.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  5074.         // $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
  5075.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
  5076.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
  5077.         // $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  5078.         // try {
  5079.         //     $currentRow = $unallocatedSheet->getHighestRow();
  5080.         //     $invoiceProjectMap = [];
  5081.         //     foreach ($projectsList as $project) {
  5082.         //         $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
  5083.                 
  5084.         //         if ($vendorQuotationPlannings) {
  5085.         //             foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
  5086.         //                 $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
  5087.                         
  5088.         //                 foreach ($vqpInvoices as $vqpInvoice) {
  5089.         //                     $vendorInvoice = $vqpInvoice->getVendorInvoice();
  5090.                             
  5091.         //                     if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
  5092.         //                     if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
  5093.                             
  5094.         //                     $invoiceId = $vendorInvoice->getVendorInvoiceNo();
  5095.                             
  5096.         //                     if (!isset($invoiceProjectMap[$invoiceId])) {
  5097.         //                         $invoiceProjectMap[$invoiceId] = [
  5098.         //                             'invoice' => $vendorInvoice,
  5099.         //                             'projects' => [],
  5100.         //                             'vendorName' => '',
  5101.         //                             'xeroContact' => null
  5102.         //                         ];
  5103.         //                     }
  5104.                             
  5105.         //                     // Add project information
  5106.         //                     $invoiceProjectMap[$invoiceId]['projects'][] = [
  5107.         //                         'project' => $vendorQuotationPlanning->getProject(),
  5108.         //                         'client' => $vendorQuotationPlanning->getProject()->getClient(),
  5109.         //                         'vendorQuotationPlanning' => $vendorQuotationPlanning,
  5110.         //                         'amount' => $vqpInvoice->getAmountUsd(),
  5111.         //                     ];
  5112.         //                 }
  5113.         //             }
  5114.         //         }
  5115.         //     }
  5116.             
  5117.         //     // Second pass: Write to spreadsheet with merged cells for same invoice
  5118.         //     foreach ($invoiceProjectMap as $invoiceId => $data) {
  5119.         //         $vendorInvoice = $data['invoice'];
  5120.         //         $projects = $data['projects'];
  5121.         //         $startRow = $currentRow;
  5122.                 
  5123.         //         // Get vendor name
  5124.         //         $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
  5125.         //         $vendorName = '';
  5126.         //         if ($vendorInvoice->getXeroContactId()) {
  5127.         //             $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
  5128.         //         } else {
  5129.         //             $vendorName = $vendorInvoice->getVendor()->getName();
  5130.         //         }
  5131.                 
  5132.         //         // Get client invoices
  5133.         //         $clientInvoices = [];
  5134.         //         if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
  5135.         //             foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
  5136.         //                 $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
  5137.         //                 array_push($clientInvoices, $clientInv);
  5138.         //             }
  5139.         //         }
  5140.                 
  5141.         //         // Write data for each project
  5142.         //         foreach ($projects as $index => $projectData) {
  5143.         //             $project = $projectData['project'];
  5144.                     
  5145.         //             // Write project-specific information
  5146.         //             $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
  5147.         //             $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
  5148.                     
  5149.         //             // Set project hyperlink
  5150.         //             $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
  5151.         //             $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
  5152.                     
  5153.         //             // Write amount for this project
  5154.         //             $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
  5155.                     
  5156.         //             // For the first project entry, write the shared invoice information
  5157.         //             if ($index === 0) {
  5158.         //                 $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
  5159.         //                 $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
  5160.         //                 $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
  5161.         //                 $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
  5162.         //                 $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
  5163.         //                 $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
  5164.         //                 $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
  5165.         //                 $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
  5166.         //                 $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
  5167.         //             }
  5168.                     
  5169.         //             // Handle vendor quotes
  5170.         //             if ($projectData['vendorQuotationPlanning']) {
  5171.         //                 $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
  5172.         //                 if (!empty($vendorQuotations)) {
  5173.         //                     foreach($vendorQuotations as $vendorQoute){
  5174.         //                         $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
  5175.         //                         $currentRow++;
  5176.         //                     }
  5177.         //                 } else {
  5178.         //                     $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  5179.         //                 }
  5180.         //             } else {
  5181.         //                 $unallocatedSheet->setCellValue('E' . $currentRow, "-");
  5182.         //             }
  5183.                     
  5184.         //             $currentRow++;
  5185.         //         }
  5186.                 
  5187.         //         // If we have multiple projects, merge the shared invoice cells
  5188.         //         if (count($projects) > 1) {
  5189.         //             $endRow = $currentRow - 1;
  5190.         //             $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
  5191.                     
  5192.         //             foreach ($columnsToMerge as $column) {
  5193.         //                 if ($startRow < $endRow) {
  5194.         //                     $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
  5195.         //                     $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
  5196.         //                         ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  5197.         //                 }
  5198.         //             }
  5199.         //         }
  5200.         //     }
  5201.         // } catch (\Exception $e) {
  5202.         //     dd($e->getMessage());
  5203.         // }
  5204.         // $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
  5205.         // $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
  5206.         
  5207.         // Write the file
  5208.         $writer = new Xlsx($spreadsheet);
  5209.         $writer->save($filename);
  5210.         if ($_target == 'google') {
  5211.             $gsheetURL $this->googleDriveService->uploadToGoogleDrive($filename);
  5212.             if ($gsheetURL) {
  5213.                 unlink($filename);
  5214.                 return new RedirectResponse($gsheetURL302);
  5215.             }
  5216.         } else {
  5217.             $response = new Response();
  5218.             $response->headers->set('Content-type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  5219.             $response->headers->set('Content-Disposition'sprintf('attachment; filename="%s"'$filename));
  5220.             $response->setContent(file_get_contents($filename));
  5221.             $response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
  5222.             $response->headers->set('Content-Transfer-Encoding''binary');
  5223.             $response->headers->set('Pragma''no-cache');
  5224.             $response->headers->set('Expires''0');
  5225.             unlink($filename);
  5226.             return $response;
  5227.             exit;
  5228.         }
  5229.     }
  5230.     
  5231.     public function getProjectLeadStatus($leadId)
  5232.     {
  5233.         return $this->projectLeadStatusRepository->findOneBy(['lead' => $leadId]);
  5234.     }
  5235.     
  5236.     public function generateRevenuePlanning($project$force false)
  5237.     {
  5238.         $result['status'] = 'OK';
  5239.         $estimatedProfit $project->getEstimatedProfit() ?: null;
  5240.         $estimatedProfitUsd $project->getEstimatedProfitUsd() ?: null;
  5241.         $startDate $project->getStartDate() ? new \DateTime($project->getStartDate()->format('Y-m-d H:i:s')) : null;
  5242.         if ($startDate) {
  5243.             $startDate->modify('first day of this month');
  5244.         }
  5245.         $endDate $project->getEndDate() ? new \DateTime($project->getEndDate()->format('Y-m-d H:i:s')) : null;
  5246.         if (is_null($estimatedProfit) || is_null($estimatedProfitUsd)) {
  5247.             $result['status'] = 'ERROR';
  5248.             $result['message'] = 'Please provide Project <b>Estimated Agency Revenue</b> to use this feature.';
  5249.             $result['data'] = null;
  5250.             return $result;
  5251.         }
  5252.         if (is_null($startDate) || is_null($endDate)) {
  5253.             $result['status'] = 'ERROR';
  5254.             $result['message'] = 'Please provide Project <b>Start Date</b> and Project <b>End Date</b> to use this feature.';
  5255.             $result['data'] = null;
  5256.             return $result;
  5257.         }
  5258.         $currentRevenuePlannings $project->getRevenuePlannings()->toArray();
  5259.         $dateInterval $endDate->diff($startDate);
  5260.         // $numMonths = ($dateInterval->y * 12) + $dateInterval->m + 1;
  5261.         $yearsInMonths $dateInterval->12;
  5262.         $months $dateInterval->m;
  5263.         $days $dateInterval->d;
  5264.         if ($days 0) {
  5265.             $months++;
  5266.         }
  5267.         $numMonths $yearsInMonths $months;
  5268.         $entityManager $this->entityManager;
  5269.         // Calculate the average amount for each month
  5270.         // $averageAmount = $numMonths > 0 ? floatval($estimatedProfit / $numMonths) : 0;
  5271.         // $averageAmountUsd = $numMonths > 0 ? floatval($estimatedProfitUsd / $numMonths) : 0;
  5272.         $averageAmount $numMonths floor($estimatedProfit $numMonths) : 0;
  5273.         $averageAmountUsd $numMonths floor($estimatedProfitUsd $numMonths) : 0;
  5274.         $differenceAmount $estimatedProfit - ($averageAmount $numMonths);
  5275.         $differenceAmountUsd $estimatedProfitUsd - ($averageAmountUsd $numMonths);
  5276.         if (empty($currentRevenuePlannings)) {
  5277.             for ($i 0$i $numMonths$i++) {
  5278.                 $currentMonth $startDate->format('m');
  5279.                 $currentYear $startDate->format('Y');
  5280.                 $revenuePlanning = new RevenuePlanning();
  5281.                 if ($i === ($numMonths 1)) {
  5282.                     $amount $averageAmount $differenceAmount;
  5283.                     $amountUsd $averageAmountUsd $differenceAmountUsd;
  5284.                 } else {
  5285.                     $amount $averageAmount;
  5286.                     $amountUsd $averageAmountUsd;
  5287.                 }
  5288.                 $revenuePlanning
  5289.                     ->setMonth($currentMonth)
  5290.                     ->setYear($currentYear)
  5291.                     ->setAmount($amount)
  5292.                     ->setAmountUsd($amountUsd)
  5293.                     ->setCreatedAt(new \DateTimeImmutable())
  5294.                     ->setProject($project);
  5295.                 $entityManager->persist($revenuePlanning);
  5296.                 $currentRevenuePlannings[] = $revenuePlanning;
  5297.                 $startDate->add(new \DateInterval('P1M'));
  5298.             }
  5299.             $entityManager->flush();
  5300.             $project $this->projectRepository->find($project->getId());
  5301.             $entityManager->refresh($project);
  5302.             $result['data'] = $project;
  5303.             return $result;
  5304.         }
  5305.         $totalAmount array_sum(array_map(fn($entry) => $entry->getAmount(), $currentRevenuePlannings));
  5306.         if (!empty($currentRevenuePlannings) && ($force === true || $totalAmount == 0)) {
  5307.             $i 0;
  5308.             foreach ($currentRevenuePlannings as $entry) {
  5309.                 if ($i === ($numMonths 1)) {
  5310.                     $entry->setAmount($averageAmount $differenceAmount);
  5311.                     $entry->setAmountUsd($averageAmountUsd $differenceAmountUsd);
  5312.                 } else {
  5313.                     $entry->setAmount($averageAmount);
  5314.                     $entry->setAmountUsd($averageAmountUsd);
  5315.                 }
  5316.                 $i++;
  5317.             }
  5318.             $entityManager->flush();
  5319.             $project $this->projectRepository->find($project->getId());
  5320.             $entityManager->refresh($project);
  5321.             $result['data'] = $project;
  5322.             return $result;
  5323.         }
  5324.         // Check if the number of months has been reduced
  5325.         if (count($currentRevenuePlannings) > $numMonths) {
  5326.             $startDateClone = clone $startDate;
  5327.             $endDateClone = clone $endDate;
  5328.             foreach ($currentRevenuePlannings as $entry) {
  5329.                 $entryMonth intval($entry->getMonth());
  5330.                 $entryYear intval($entry->getYear());
  5331.                 $entryDate = new \DateTime("$entryYear-$entryMonth-01");
  5332.                 if ($entryDate >= $startDateClone && $entryDate <= $endDateClone)  continue;
  5333.                 $entityManager->remove($entry);
  5334.             }
  5335.             $entityManager->flush();
  5336.             $currentRevenuePlannings $this->revenuePlanningRepository->findBy(['project' => $project]);
  5337.         }
  5338.         // Calculate the total sum of existing amounts
  5339.         $totalExistingAmount 0;
  5340.         $totalExistingAmountUsd 0;
  5341.         foreach ($currentRevenuePlannings as $existingEntry) {
  5342.             $totalExistingAmount += $existingEntry->getAmount();
  5343.             $totalExistingAmountUsd += $existingEntry->getAmountUsd();
  5344.         }
  5345.         // Calculate the remaining amount to distribute or deduct
  5346.         // $remainingAmount = $estimatedProfit - $totalExistingAmount;
  5347.         // $remainingAmountUsd = $estimatedProfitUsd - $totalExistingAmountUsd;
  5348.         // Update or create Revenue Planning entries based on the number of months
  5349.         for ($i 0$i $numMonths$i++) {
  5350.             $currentMonth $startDate->format('m');
  5351.             $currentYear $startDate->format('Y');
  5352.             $matchingEntry null;
  5353.             foreach ($currentRevenuePlannings as $existingEntry) {
  5354.                 if ($existingEntry->getMonth() === $currentMonth && $existingEntry->getYear() === $currentYear) {
  5355.                     $matchingEntry $existingEntry;
  5356.                     break;
  5357.                 }
  5358.             }
  5359.             if (!$matchingEntry) {
  5360.                 // Create new entry with 0 value
  5361.                 $revenuePlanning = new RevenuePlanning();
  5362.                 $revenuePlanning
  5363.                     ->setMonth($currentMonth)
  5364.                     ->setYear($currentYear)
  5365.                     ->setAmount(0)
  5366.                     ->setAmountUsd(0)
  5367.                     ->setCreatedAt(new \DateTimeImmutable())
  5368.                     ->setProject($project);
  5369.                 $entityManager->persist($revenuePlanning);
  5370.                 $currentRevenuePlannings[] = $revenuePlanning;
  5371.             }
  5372.             $startDate->add(new \DateInterval('P1M'));
  5373.         }
  5374.         /*
  5375.         // Distribute remaining amount if numMonths increased
  5376.         if ($numMonths > count($currentRevenuePlannings)) {
  5377.             foreach ($currentRevenuePlannings as $entry) {
  5378.                 if ($remainingAmount <= 0) {
  5379.                     break;
  5380.                 }
  5381.                 $entry->setAmount($entry->getAmount() + 1);
  5382.                 $remainingAmount--;
  5383.             }
  5384.         }
  5385.         // Distribute remaining USD amount if numMonths increased
  5386.         if ($numMonths > count($currentRevenuePlannings)) {
  5387.             foreach ($currentRevenuePlannings as $entry) {
  5388.                 if ($remainingAmountUsd <= 0) {
  5389.                     break;
  5390.                 }
  5391.                 $entry->setAmountUsd($entry->getAmountUsd() + 1);
  5392.                 $remainingAmountUsd--;
  5393.             }
  5394.         }
  5395.         // Remove or update amounts if numMonths decreased
  5396.         if ($numMonths < count($currentRevenuePlannings)) {
  5397.             $lastEntry = end($currentRevenuePlannings);
  5398.             $lastEntry->setAmount($lastEntry->getAmount() + $remainingAmount);
  5399.             $lastEntry->setAmountUsd($lastEntry->getAmountUsd() + $remainingAmountUsd);
  5400.             array_pop($currentRevenuePlannings); // Remove the last entry if numMonths decreased
  5401.         }
  5402.         */
  5403.         $entityManager->flush();
  5404.         $project $this->projectRepository->find($project->getId());
  5405.         $entityManager->refresh($project);
  5406.         $result['data'] = $project;
  5407.         return $result;
  5408.     }
  5409.     public function calculateIncludedMonths($startDate$endDate)
  5410.     {
  5411.         $currentDate = new \DateTime();
  5412.         $currentMonth = (int) $currentDate->format('m'); // 8
  5413.         $currentYear = (int) $currentDate->format('Y'); // 2023
  5414.         $fytdStartMonth 11// November
  5415.         $fytdEndMonth 10;   // October
  5416.         // Adjust the fiscal year based on the current month
  5417.         $fytdYear = ($currentMonth $fytdStartMonth) ? $currentYear $currentYear;
  5418.         $fytdStartDate = new \DateTime();
  5419.         $fytdStartDate->setDate($fytdYear$fytdStartMonth1);
  5420.         $fytdEndDate = new \DateTime();
  5421.         $fytdEndDate->setDate($fytdYear 1$fytdEndMonth31);
  5422.         // Convert start and end dates to DateTime objects
  5423.         // $start = new \DateTime($startDate);
  5424.         // $end = new \DateTime($endDate);
  5425.         $start $startDate;
  5426.         $end $endDate;
  5427.         $includedMonths 0;
  5428.         // Iterate through months and check if they are within FYTD
  5429.         while ($start <= $end) {
  5430.             if ($start >= $fytdStartDate && $start <= $fytdEndDate) {
  5431.                 $includedMonths++;
  5432.             }
  5433.             $start->modify('+1 month');
  5434.         }
  5435.         return $includedMonths;
  5436.     }
  5437.     public function getEmailLogFeedback($emailPic$title)
  5438.     {
  5439.         $emailLogs $this->emailCollectorRepository->findByToAddressAndTitle($emailPic$title);
  5440.         return $emailLogs;
  5441.     }
  5442. }