<?php
namespace App\Service;
use App\Entity\Client;
use App\Entity\Department;
use App\Entity\RevenuePlanning;
use App\Entity\User;
use App\Repository\EmailCollectorRepository;
use App\Repository\ProjectAllocatedHoursRepository;
use App\Repository\ProjectRepository;
use App\Repository\RevenuePlanningRepository;
use App\Repository\TimeSpentRepository;
use App\Repository\ProjectLeadStatusRepository;
use App\Repository\UserRepository;
use App\Repository\InvoiceRepository;
use App\Repository\SalesOrderInvoiceRepository;
use App\Repository\XeroContactRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\LogService;
use App\Service\MailgunService;
use Doctrine\ORM\Query\Expr\Func;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProjectService
{
private $entityManager;
private $projectRepository;
private $timeSpentRepository;
private $allocatedHoursRepository;
private $projectLeadStatusRepository;
private $userRepository;
private $mailgunService;
private $translator;
private $revenuePlanningRepository;
private $invoiceRepository;
private $salesOrderInvoiceRepository;
private $ics;
private $utilsService;
private $params;
private $googleDriveService;
private $emailCollectorRepository;
private $currencyService;
private $projectIdPattern;
private $xeroContactRepository;
private $log;
public function __construct(EntityManagerInterface $entityManager, LogService $log, ProjectRepository $projectRepository, TimeSpentRepository $timeSpentRepository, UserRepository $userRepository, ProjectAllocatedHoursRepository $allocatedHoursRepository, ProjectLeadStatusRepository $projectLeadStatusRepository, MailgunService $mailgunService, RevenuePlanningRepository $revenuePlanningRepository, InvoiceRepository $invoiceRepository, SalesOrderInvoiceRepository $salesOrderInvoiceRepository, ICSService $ics, UtilsService $utilsService, GoogleDriveService $googleDriveService, EmailCollectorRepository $emailCollectorRepository, ParameterBagInterface $params, TranslatorInterface $translator, CurrencyService $currencyService, XeroContactRepository $xeroContactRepository)
{
$this->projectRepository = $projectRepository;
$this->userRepository = $userRepository;
$this->timeSpentRepository = $timeSpentRepository;
$this->allocatedHoursRepository = $allocatedHoursRepository;
$this->projectLeadStatusRepository = $projectLeadStatusRepository;
$this->entityManager = $entityManager;
$this->log = $log;
$this->mailgunService = $mailgunService;
$this->translator = $translator;
$this->revenuePlanningRepository = $revenuePlanningRepository;
$this->invoiceRepository = $invoiceRepository;
$this->salesOrderInvoiceRepository = $salesOrderInvoiceRepository;
$this->ics = $ics;
$this->utilsService = $utilsService;
$this->params = $params;
$this->googleDriveService = $googleDriveService;
$this->emailCollectorRepository = $emailCollectorRepository;
$this->currencyService = $currencyService;
$this->projectIdPattern = '/Project\s*Id\s*:?\s*(\d{4}-\d{4})/i';
$this->xeroContactRepository = $xeroContactRepository;
}
public function getEstimatedProjectHours() {}
public function getEmployeeTimeRecord($project)
{
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
/*
$newEmployeeSummaryList = [];
foreach ($employeeSummaryList as $employee){
$user = $this->userRepository->find($employee['id']);
$employee['hourlyRate'] = $user->getHourlyRateUsd();
$employee['newCost'] = $employee['hours'] * $user->getHourlyRateUsd();
array_push($newEmployeeSummaryList, $employee);
}
*/
// $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$record = [];
$record['departments'] = $departments;
$record['total']['hours'] = $totalHoursAll;
$record['total']['cost'] = $totalCostAll;
return $record;
}
public function getEmployeeTimeRecordByMonth($project, $month, $year)
{
$month = intval($month) <= 9 ? '0' . $month : $month;
$start = date("Y-m-d", strtotime($year . '-' . $month . '-' . '01'));
$startDate = new \DateTime($start);
$end = date("Y-m-d", strtotime($start . 'last day of this month'));
$endDate = new \DateTime($end);
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $startDate, $endDate);
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id'], $start, $end);
/*
$newEmployeeSummaryList = [];
foreach ($employeeSummaryList as $employee){
$user = $this->userRepository->find($employee['id']);
$employee['hourlyRate'] = $user->getHourlyRateUsd();
$employee['newCost'] = $employee['hours'] * $user->getHourlyRateUsd();
array_push($newEmployeeSummaryList, $employee);
}
*/
// $departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$record = [];
$record['departments'] = $departments;
$record['total']['hours'] = $totalHoursAll;
$record['total']['cost'] = $totalCostAll;
return $record;
}
public function mergeProject($projectA, $projectB)
{
$projectA = $this->projectRepository->find($projectA);
$projectB = $this->projectRepository->find($projectB);
if ($projectA == null || $projectB == null) {
return false;
}
$timeSpents = $this->timeSpentRepository->findBy(['project' => $projectA]);
foreach ($timeSpents as $timeSpent) {
$timeSpent->setProject($projectB);
$this->entityManager->persist($timeSpent);
}
$projectA->setDeletedAt(new \DateTimeImmutable());
$this->entityManager->flush();
return true;
}
public function projectHostingEmail($project, $type="domain")
{
$loggedIn = false;
$emailDev = $this->params->get('systemEmailIT');
if($type == "domain") {
$subject = 'email.project_management.project_hosting.domain';
$emailTemplate = 'email/user-notification/project-management/project-hosting-domain.html.twig';
} else if ($type == "platform") {
$subject = 'email.project_management.project_hosting.platform';
$emailTemplate = 'email/user-notification/project-management/project-hosting-platform.html.twig';
}
$picEmail = $project->getPersonInCharge()->getCanonicalEmail();
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->getName(),
]),
'to' => [$picEmail],
'cc' => [$emailDev],
'template' => $emailTemplate,
'params' => [
'recipient' => $project->getPersonInCharge()->getPersonalInfo()->getFirstName(),
'project' => $project,
],
],
$loggedIn
);
}
public function projectEndEmail($project)
{
$loggedIn = false;
// $reminderLog = $editedUser->getReminder();
$emailMarcom = $this->params->get('systemEmailMarcom');
$subject = 'email.project_management.project_end';
$emailTemplate = 'email/user-notification/project-management/project-end.html.twig';
$picEmail = $project->getPersonInCharge()->getCanonicalEmail();
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->getName(),
]),
'to' => [$picEmail],
'cc' => [$emailMarcom],
'template' => $emailTemplate,
'params' => [
'recipient' => $project->getPersonInCharge()->getPersonalInfo()->getFirstName(),
'project' => $project,
],
],
$loggedIn
);
}
public function projectFinishedEmail($project)
{
$loggedIn = false;
// $reminderLog = $editedUser->getReminder();
$emailMarcom = $this->params->get('systemEmailMarcom');
$subject = 'email.project_management.project_finished';
$emailTemplate = 'email/user-notification/project-management/project-finished.html.twig';
$picEmail = $project->getPersonInCharge()->getCanonicalEmail();
$picName = $project->getPersonInCharge()->getPersonalInfo()->getShortFullName();
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->getName(),
]),
'to' => [$emailMarcom],
'cc' => [$picEmail],
'template' => $emailTemplate,
'params' => [
'recipient' => 'Marcom',
'project' => $project,
'picName' => $picName,
'picEmail' => $picEmail,
],
],
$loggedIn
);
}
public function projectClientFeedbackEmail($project, $baseUrl)
{
$loggedIn = true;
// $reminderLog = $editedUser->getReminder();
$emailLeadership = $this->params->get('systemEmailLeadership');
$emailMarcom = $this->params->get('systemEmailMarcom');
$emailManagement = $this->params->get('systemEmailManagement');
$subject = 'email.project_management.project_finished_feedback';
$emailTemplate = 'email/user-notification/project-management/project-feedback.html.twig';
$picEmail = $project->getClientPersonInCharge()->getEmail();
$picName = $project->getClientPersonInCharge()->getFirstName();
$picProjectEmail = $project->getPersonInCharge()->getCanonicalEmail();
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->getName(),
]),
'to' => [$picEmail],
'bcc' => [$emailLeadership, $emailMarcom, $emailManagement, $picProjectEmail],
'template' => $emailTemplate,
'params' => [
'recipient' => $picName,
'project' => $project,
'baseUrl' => $baseUrl,
],
],
$loggedIn
);
}
public function projectDeletedEmail($project, $user)
{
$loggedIn = false;
$deletedBy = $user;
$emailFinance = $this->params->get('systemEmailGroup')['finance'];
$emailLeadership = $this->params->get('systemEmailLeadership');
$subject = 'email.project_management.project_deleted';
$emailTemplate = 'email/user-notification/project-management/project-deleted.html.twig';
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->fullName(),
'%user%' => $deletedBy->getPersonalInfo()->getFirstName()
]),
'to' => [$emailFinance, $emailLeadership],
'template' => $emailTemplate,
'params' => [
'recipient' => 'Team',
'project' => $project,
'user' => $deletedBy,
],
],
$loggedIn
);
}
public function projectVendorPlanningEmail($project)
{
$loggedIn = false;
$emailFinance = $this->params->get('systemEmailGroup')['finance'];
$subject = 'email.project_management.project_vendor_planning';
$emailTemplate = 'email/user-notification/project-management/project-vendor-planning.html.twig';
$picEmail = $project->getPersonInCharge()->getCanonicalEmail();
$picName = $project->getPersonInCharge()->getPersonalInfo()->getFirstName();
$this->mailgunService->sendEmailAdvanced(
[
'subject' => $this->translator->trans($subject, [
'%project_name%' => $project->fullName(),
]),
'to' => [$picEmail],
'cc' => [$emailFinance],
'template' => $emailTemplate,
'params' => [
'recipient' => $picName,
'project' => $project,
],
],
$loggedIn
);
}
public function projectDatesEmail($project, $emailType)
{
$loggedIn = true;
$subject = 'email.project_management.' . $emailType . '.description';
$emailTemplate = 'email/blank.html.twig';
$receivers = [
[
'name' => $project->getPersonInCharge()->getPersonalInfo()->getFullName(),
'email' => $project->getPersonInCharge()->getEmail(),
'role' => 'REQ-PARTICIPANT'
],
];
$existingEmails = array_map(function ($receiver) {
return $receiver['email'];
}, $receivers);
foreach ($project->getProjectMembers() as $projectMember) {
$memberUser = $projectMember->getUser();
$memberEmail = $memberUser->getCanonicalEmail();
$role = 'REQ-PARTICIPANT';
$receiverData = [
'name' => $memberUser->getPersonalInfo()->getFullName(),
'email' => $memberEmail,
'role' => $role
];
if (!in_array($memberEmail, $existingEmails)) {
array_push($receivers, $receiverData);
$existingEmails[] = $memberEmail;
}
}
$dateFieldMappings = [
'proposal_sent_date' => 'proposalDate',
'client_present_date' => 'presentationDate',
'proposal_followup_date' => 'proposalFollowUpDate',
'recontact_date' => 'leadFailRemindDate'
];
$whenDate = $project->{'get' . $dateFieldMappings[$emailType]}()->format('Y-m-d');
if ($whenDate > date('Y-m-d')) {
$startDateTime = date("Ymd\THis", strtotime($whenDate . "9:00:00"));
$endDateTime = date("Ymd\THis", strtotime($whenDate . "9:01:00"));
$subjectParams = [
'%project_name%' => $project->getName(),
];
if ($emailType == 'proposal_sent_date' || $emailType == 'client_present_date') {
$subjectParams['%date%'] = date('d M Y', strtotime($whenDate));
}
$subject = $this->translator->trans($subject, [
'%project_name%' => $project->getName(),
'%date%' => date('d M Y', strtotime($whenDate)),
]);
$icsData = $this->ics->generateEventFile([
'uid' => $project->getId() . '-' . $emailType,
'title' => $subject,
'description' => $this->translator->trans('ics.project_management.' . $emailType . '.description', $subjectParams),
'startDateTime' => $startDateTime,
'endDateTime' => $endDateTime,
'location' => 'TBC',
'organizer' => [
'name' => 'HR',
'email' => $this->params->get('systemEmailAddr')
],
'attendee' => $receivers,
'reminderTime' => '-15M',
'reminderDescription' => $this->translator->trans('ics.project_management.' . $emailType . '.title'),
], true, 'PUBLISH');
foreach ($receivers as $receiver) {
$this->mailgunService->sendEmailWithAttachment(
[
'subject' => $subject,
'to' => $receiver['email'],
'template' => $emailTemplate,
'params' => [
'recipient' => $receiver['name'],
'project' => $project,
],
'ical' => $icsData
],
$loggedIn
);
}
}
}
public function projectXeroAllocationEmail($object): bool
{
$type = null;
if (method_exists($object, 'getSalesOrderNo') && $object->getSalesOrderNo() != null) {
$type = 'SO';
} elseif (method_exists($object, 'getInvoiceNo') && $object->getInvoiceNo() != null) {
$type = 'INV';
} else {
return false;
}
if(count($object->getXeroLineItems()) == 0) {
return false;
}
foreach ($object->getXeroLineItems() as $lineItem) {
// Skip if the description does not match the project ID pattern
if (!preg_match($this->projectIdPattern, $lineItem->getDescription(), $matches)) {
continue;
}
$projectId = $matches[1];
$project = $this->projectRepository->findOneBy(['generatedId' => $projectId]);
// If no project is found, exit early
if (!$project) {
return false;
}
$hasProjectRelation = false;
switch ($type) {
case 'SO':
foreach($project->getProjectSalesOrders() as $so) {
if($so->getSalesOrder() == $object) {
$hasProjectRelation = true;
break;
}
}
$typeNo = $object->getSalesOrderNo();
break;
case 'INV':
foreach($project->getProjectSalesOrders() as $so) {
foreach($so->getSalesOrder()->getSalesOrderInvoices() as $soInv) {
if($soInv->getInvoice() == $object) {
$hasProjectRelation = true;
break;
}
}
}
$typeNo = $object->getInvoiceNo();
break;
default:
return false;
}
// If the relation exists, no need to send a reminder
if ($hasProjectRelation) {
return false;
}
// Ensure the project has a Person In Charge (PIC) with an email
$pic = $project->getPersonInCharge();
if (!$pic || !$pic->getEmail()) {
return false;
}
// Send the reminder email
try {
$this->mailgunService->sendEmail(
$this->translator->trans('email.project_management.so_invoice_need_allocation', [
'%type_no%' => $typeNo,
'%project%' => $project->getGeneratedId() . ': ' . $project->getName()
]),
[$pic->getEmail()],
'email/user-notification/project-management/so-invoice-need-allocation.html.twig',
[
'recipient' => $pic,
'type' => $type,
'type_no' => $typeNo,
'project' => $project
],
false
);
} catch (\Exception $e) {
// If email sending fails, return false
return false;
}
return true;
}
return false;
}
public function projectSalesHasAllocatedEmail($object, $project): bool
{
$type = null;
if (method_exists($object, 'getSalesOrderNo') && $object->getSalesOrderNo() != null) {
$type = 'SO';
} elseif (method_exists($object, 'getInvoiceNo') && $object->getInvoiceNo() != null) {
$type = 'INV';
} else {
return false;
}
$emailFinance = $this->params->get('systemEmailGroup')['finance'];
switch ($type) {
case 'SO':
$typeNo = $object->getSalesOrderNo();
break;
case 'INV':
$typeNo = $object->getInvoiceNo();
break;
default:
return false;
}
try {
$this->mailgunService->sendEmail(
$this->translator->trans('email.project_management.so_invoice_allocated', [
'%type_no%' => $typeNo,
'%project%' => $project->getGeneratedId() . ': ' . $project->getName()
]),
[$emailFinance],
'email/user-notification/project-management/so-invoice-allocated.html.twig',
[
'recipient' => 'Team',
'type' => $type,
'type_no' => $typeNo,
'project' => $project
],
false
);
} catch (\Exception $e) {
// If email sending fails, return false
return false;
}
return true;
}
public function generateProjectId()
{
$projects = $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getGeneratedId() != null) continue;
$project->setGeneratedId($project->getCreatedAt()->format('ym') . '-' . sprintf('%04d', $project->getId()));
$this->entityManager->persist($project);
$total++;
}
$this->entityManager->flush();
return $total;
}
public function syncProjectType()
{
$projects = $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getType() == 'INTERNAL' || $project->getDeletedAt() != null) continue;
if ($project->getType() == 'LEAD' && $project->getLead() == null) {
$project->setLead(1);
}
if ($project->getType() == 'LEAD') {
$project->setStatus(NULL);
}
if ($project->getType() == 'CONFIRMED' && !in_array($project->getLead(), [8, 91, 92])) {
$project->setLead(8);
};
$total++;
$this->entityManager->persist($project);
}
$this->entityManager->flush();
return $total;
}
public function syncProjectRate()
{
$projects = $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
foreach ($project->getTasks() as $task) {
$timespents = $this->timeSpentRepository->findBy(['task' => $task]);
foreach ($timespents as $timespent) {
$date = $timespent->getDate()->format('Y-m-d');
$newRate = $timespent->getUser()->getHourlyRateUsd($date);
if ($timespent->getHourlyRate() == $newRate) continue;
$timespent->setHourlyRate($newRate);
$total++;
}
}
}
$this->entityManager->flush();
return $total;
}
public function syncProjectPlannedRevenue($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getPlannedRevenueUsd() != null) continue;
$project->setPlannedRevenueUsd($project->getPlannedRevenueToUsd());
$total++;
}
$this->entityManager->flush();
return $total;
}
public function syncProjectEstimatedVendorCost($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getEstimatedVendorCostUsd() != null) continue;
$project->setEstimatedVendorCostUsd($project->getEstimatedVendorCostToUsd());
$total++;
}
$this->entityManager->flush();
return $total;
}
public function syncProjectDate($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getLeadDate() != null) continue;
$project->setLeadDate($project->getCreatedAt());
$total++;
}
$this->entityManager->flush();
return $total;
}
public function checkProjectDate($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = [
'allData' => 0,
'emptyLeadDate' => 0,
'emptyProposalDate' => 0,
'proposalDateFromLog' => 0,
'filledProposalDateAfterSync' => 0,
'emptyProposalDateAfterSync' => 0,
'emptyProposalDateAfterSyncPID' => '',
'emptyStartDate' => 0,
'startDateFromLog' => 0,
'filledStartDateAfterSync' => 0,
'emptyStartDateAfterSync' => 0,
'emptyStartDateAfterSyncPID' => ''
];
$loop = 0;
foreach ($projects as $project) {
// if($loop > 10) break;
if ($project->getDeletedAt() != null) continue;
if ($project->getLeadDate() == null) $total['emptyLeadDate'] = $total['emptyLeadDate'] + 1;
if ($project->getProposalDate() == null && $project->getLead() == 5) $total['emptyProposalDate'] = $total['emptyProposalDate'] + 1;
if ($project->getStartDate() == null && $project->getLead() == 8) $total['emptyStartDate'] = $total['emptyStartDate'] + 1;
$projectLog = $this->log->data('log.project.edit', $project->getId());
$skipProposal = false;
$skipStart = false;
foreach ($projectLog as $log) {
$oldData = json_decode($log->getOldData(), true);
$newData = json_decode($log->getNewData(), true);
if (isset($newData['lead']) && $newData['lead'] == 5 && $project->getLead() == 5 && !$skipProposal) {
$total['proposalDateFromLog'] = $total['proposalDateFromLog'] + 1;
$skipProposal = true;
}
if (isset($newData['lead']) && $newData['lead'] == 8 && $project->getLead() == 8 && !$skipStart) {
$total['startDateFromLog'] = $total['startDateFromLog'] + 1;
$skipStart = true;
}
}
if ($project->getLead() == 5 && $project->getProposalDate() == null) {
// $project->setProposalDate($project->getCreatedAt());
// $this->entityManager->persist($project);
// $this->entityManager->flush();
if ($skipProposal) {
$total['filledProposalDateAfterSync'] = $total['filledProposalDateAfterSync'] + 1;
} else {
$total['emptyProposalDateAfterSyncPID'] = $total['emptyProposalDateAfterSyncPID'] . $project->getId() . ' ';
}
};
if ($project->getLead() == 8 && $project->getStartDate() == null) {
// $project->setStartDate($project->getCreatedAt());
// $this->entityManager->persist($project);
// $this->entityManager->flush();
if ($skipStart) {
$total['filledStartDateAfterSync'] = $total['filledStartDateAfterSync'] + 1;
} else {
$total['emptyStartDateAfterSyncPID'] = $total['emptyStartDateAfterSyncPID'] . $project->getId() . ' ';
}
}
$loop++;
}
$total['emptyProposalDateAfterSync'] = $total['emptyProposalDate'] - $total['filledProposalDateAfterSync'];
$total['emptyStartDateAfterSync'] = $total['emptyStartDate'] - $total['filledStartDateAfterSync'];
$total['allData'] = $loop;
return $total;
}
public function syncProjectProbabilityRate($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getProbability() != null) continue;
$project->setProbability($project->getProbabilityRate());
$total++;
}
$this->entityManager->flush();
return $total;
}
public function fixProjectWinProbabilityRate($project = null)
{
$projects = $project ? [$project] : $this->projectRepository->findAll();
$total = 0;
foreach ($projects as $project) {
if ($project->getProbability() != 100 && $project->getLead() == 8) {
$project->setProbability(100);
$total++;
}
}
$this->entityManager->flush();
return $total;
}
public function monthlyRevenues($project, $useDueDate = true)
{
if ($project->getStartDate() == null || $project->getEndDate() == null) return $this->monthlyRevenuesWithoutOfPeriod($project);
$startDate = clone $project->getStartDate();
$endDate = clone $project->getEndDate();
$monthlyRevenues = [];
while ($startDate <= $endDate) {
$monthYearKey = $startDate->format('Ym');
$monthlyRevenues[$monthYearKey] = [
'invoices' => [],
'total' => 0,
'totalUsd' => 0,
];
$startDate->modify('+1 month');
}
$salesOrderInvoice = $this->salesOrderInvoiceRepository->findAllByProject($project);
foreach ($salesOrderInvoice as $salesOrder) {
$invoice = $salesOrder->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$monthYear = $useDueDate ? $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$monthYear = $salesOrder->getAllocatedAt()->format('Ym');
}
if (!isset($monthlyRevenues[$monthYear]['total'])) {
$monthlyRevenues[$monthYear]['total'] = 0;
}
if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
$monthlyRevenues[$monthYear]['totalUsd'] = 0;
}
$outOfPeriod = false;
$dueDate = $useDueDate ? $invoice->getDueDate() : $invoice->getInvoiceDate();
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$dueDate = $salesOrder->getAllocatedAt();
}
$projectStartDate = $project->getStartDate();
$projectEndDate = $project->getEndDate();
if ($dueDate !== null) {
$dueDateYearMonth = $dueDate->format('Ym');
if (($projectStartDate !== null && $dueDateYearMonth < $projectStartDate->format('Ym')) ||
($projectEndDate !== null && $dueDateYearMonth > $projectEndDate->format('Ym'))
) {
$outOfPeriod = true;
}
}
$lineItems = [];
foreach ($invoice->getXeroLineItems() as $lineItem) {
$lineItems[] = [
'itemCode' => $lineItem->getItemCode(),
'total' => $lineItem->getSubTotal(),
'totalUsd' => $lineItem->getSubTotalUsd($project),
'isIncluded' => $lineItem->getIsIncluded(),
];
}
$monthlyRevenues[$monthYear]['invoices'][] = [
'invoiceNo' => $invoice->getInvoiceNo(),
'total' => $invoice->getSubTotal(),
'totalUsd' => $invoice->getSubTotalUsd($project),
'revenue' => $invoice->getRevenue($project),
'revenueUsd' => $invoice->getRevenueUsd($project),
'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
'lineItems' => $lineItems,
'outOfPeriod' => $outOfPeriod,
];
$monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
$monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
}
ksort($monthlyRevenues);
$monthlyRevenues = array_combine(
array_map(function ($key) {
return \DateTime::createFromFormat('Ym', $key)->format('M-Y');
}, array_keys($monthlyRevenues)),
array_values($monthlyRevenues)
);
return $monthlyRevenues;
}
public function monthlyRevenuesNew($project, $useDueDate = true, $startRange = null, $endRange = null)
{
// dd($startDate, $endDate);
if ($project->getStartDate() == null || $project->getEndDate() == null) return $this->monthlyRevenuesWithoutOfPeriod($project);
$startDate = clone $project->getStartDate();
$endDate = clone $project->getEndDate();
$monthlyRevenues = [];
while ($startDate <= $endDate) {
$monthYearKey = $startDate->format('Ym');
$monthlyRevenues[$monthYearKey] = [
'invoices' => [],
'total' => 0,
'totalUsd' => 0,
];
$startDate->modify('+1 month');
}
$salesOrderInvoice = $this->salesOrderInvoiceRepository->findAllByProject($project);
foreach ($salesOrderInvoice as $salesOrder) {
$invoice = $salesOrder->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
// check invoice in date range
$dateToCheck = $useDueDate ? $invoice->getDueDate() : $invoice->getInvoiceDate();
$startDateTime = $startRange ? \DateTime::createFromFormat('Y-m-d', $startRange)->setTime(0, 0, 0) : null;
$endDateTime = $endRange ? \DateTime::createFromFormat('Y-m-d', $endRange)->setTime(23, 59, 59) : null;
if (($startDateTime && $dateToCheck < $startDateTime) || ($endDateTime && $dateToCheck > $endDateTime)) {
continue;
}
$monthYear = $useDueDate ? $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$monthYear = $salesOrder->getAllocatedAt()->format('Ym');
}
if (!isset($monthlyRevenues[$monthYear]['total'])) {
$monthlyRevenues[$monthYear]['total'] = 0;
}
if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
$monthlyRevenues[$monthYear]['totalUsd'] = 0;
}
$outOfPeriod = false;
$dueDate = $useDueDate ? $invoice->getDueDate() : $invoice->getInvoiceDate();
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$dueDate = $salesOrder->getAllocatedAt();
}
$projectStartDate = $project->getStartDate();
$projectEndDate = $project->getEndDate();
if ($dueDate !== null) {
$dueDateYearMonth = $dueDate->format('Ym');
if (($projectStartDate !== null && $dueDateYearMonth < $projectStartDate->format('Ym')) ||
($projectEndDate !== null && $dueDateYearMonth > $projectEndDate->format('Ym'))
) {
$outOfPeriod = true;
}
}
$lineItems = [];
foreach ($invoice->getXeroLineItems() as $lineItem) {
$lineItems[] = [
'itemCode' => $lineItem->getItemCode(),
'total' => $lineItem->getSubTotal(),
'totalUsd' => $lineItem->getSubTotalUsd($project),
'isIncluded' => $lineItem->getIsIncluded(),
];
}
$monthlyRevenues[$monthYear]['invoices'][] = [
'invoiceNo' => $invoice->getInvoiceNo(),
'total' => $invoice->getSubTotal(),
'totalUsd' => $invoice->getSubTotalUsd($project),
'revenue' => $invoice->getRevenue($project),
'revenueUsd' => $invoice->getRevenueUsd($project),
'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
'lineItems' => $lineItems,
'outOfPeriod' => $outOfPeriod,
];
$monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
$monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
}
ksort($monthlyRevenues);
$monthlyRevenues = array_combine(
array_map(function ($key) {
return \DateTime::createFromFormat('Ym', $key)->format('M-Y');
}, array_keys($monthlyRevenues)),
array_values($monthlyRevenues)
);
return $monthlyRevenues;
}
public function monthlyRevenuesWithoutOfPeriod($project, $useDueDate = true)
{
// $invoices = $this->invoiceRepository->findAllByProject($project);
$monthlyRevenues = [];
$salesOrderInvoice = $this->salesOrderInvoiceRepository->findAllByProject($project);
foreach ($salesOrderInvoice as $salesOrder) {
$invoice = $salesOrder->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$monthYear = $useDueDate ? $invoice->getDueDate()->format('Ym') : $invoice->getInvoiceDate()->format('Ym');
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$monthYear = $salesOrder->getAllocatedAt()->format('Ym');
}
if (!isset($monthlyRevenues[$monthYear]['total'])) {
$monthlyRevenues[$monthYear]['total'] = 0;
}
if (!isset($monthlyRevenues[$monthYear]['totalUsd'])) {
$monthlyRevenues[$monthYear]['totalUsd'] = 0;
}
$outOfPeriod = false;
$dueDate = $useDueDate ? $invoice->getDueDate() : $invoice->getInvoiceDate();
if(!$useDueDate && $salesOrder->getAllocatedAt()) {
$dueDate = $salesOrder->getAllocatedAt();
}
$projectStartDate = $project->getStartDate();
$projectEndDate = $project->getEndDate();
if ($dueDate !== null) {
$dueDateYearMonth = $dueDate->format('Ym');
if (($projectStartDate !== null && $dueDateYearMonth < $projectStartDate->format('Ym')) ||
($projectEndDate !== null && $dueDateYearMonth > $projectEndDate->format('Ym'))
) {
$outOfPeriod = true;
}
}
$monthlyRevenues[$monthYear]['invoices'][] = [
'invoiceNo' => $invoice->getInvoiceNo(),
'total' => $invoice->getSubTotal(),
'totalUsd' => $invoice->getSubTotalUsd($project),
'revenue' => $invoice->getRevenue($project),
'revenueUsd' => $invoice->getRevenueUsd($project),
'lineItemFetched' => count($invoice->getXeroLineItems()) > 0,
'outOfPeriod' => $outOfPeriod,
];
$monthlyRevenues[$monthYear]['total'] += $invoice->getRevenue($project);
$monthlyRevenues[$monthYear]['totalUsd'] += $invoice->getRevenueUsd($project);
}
ksort($monthlyRevenues);
$monthlyRevenues = array_combine(
array_map(function ($key) {
return \DateTime::createFromFormat('Ym', $key)->format('M-Y');
}, array_keys($monthlyRevenues)),
array_values($monthlyRevenues)
);
return $monthlyRevenues;
}
public function exportProjectLead($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $_target)
{
if ($isAdmin) {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->freezePane('A2');
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'Lead Lost Reason');
$sheet->setCellValue('H1', 'Lead Source');
$sheet->setCellValue('I1', 'PIC');
$sheet->setCellValue('J1', 'PIC Client');
$sheet->setCellValue('K1', 'Plan File');
$sheet->setCellValue('L1', 'Plan URL');
$sheet->setCellValue('M1', 'Created Date in HRP');
$sheet->setCellValue('N1', 'Sent Date');
$sheet->setCellValue('O1', 'Client Presentation Date');
$sheet->setCellValue('P1', 'Start Date');
$sheet->setCellValue('Q1', 'End Date');
$sheet->setCellValue('R1', 'Lost Date');
$sheet->setCellValue('S1', 'SO Number(s)');
$sheet->setCellValue('T1', 'Invoice Number(s)');
$sheet->setCellValue('U1', 'Estimated Project Billings');
$sheet->setCellValue('V1', 'Estimated Agency Revenue');
$sheet->setCellValue('W1', 'Estimated Project Billings Based on SO');
$sheet->setCellValue('X1', 'Estimated Project Billings Based on INV');
$sheet->setCellValue('Y1', 'Estimated Project Hours');
// $sheet->setCellValue('O1', 'Man Hours Cost');
$sheet->setCellValue('Z1', 'Employee Time Record Hours');
$sheet->setCellValue('AA1', 'Vendor Costs Based On Plan');
$sheet->setCellValue('AB1', 'Vendor Costs Based On INV');
/*
$sheet->setCellValue('S1', 'Estimated Project Billings');
$sheet->setCellValue('ST1', 'Total Cost');
$sheet->setCellValue('U1', 'Total Profit');
*/
$sheet->setCellValue('AC1', 'Project Type');
/*
$sheet->setCellValue('AB1', 'Profit (SO amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('AC1', 'Profit (INV amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('AD1', 'Profit (SO amount - 3rd party invoices - man hours)');
$sheet->setCellValue('AE1', 'Profit (INV amount - 3rd party invoices - man hours)');
*/
$sheet->setCellValue('AD1', '% Likely To Win');
$lastCol = $sheet->getHighestColumn();
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$clientName = null;
if ($client) {
$clientData = $this->entityManager->getRepository(Client::class)->find($client);
if ($clientData) {
$clientName = $clientData->getName();
};
};
$picName = null;
if ($pic) {
$picData = $this->entityManager->getRepository(User::class)->find($pic);
if ($picData) {
$picName = $picData->getPersonalInfo()->getFullName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $clientName ? "-" . urlencode($clientName) : "";
$filename .= $picName ? "-" . urlencode($picName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
//$sheet->insertNewRowBefore($row);
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$leadFailText = $project[0]->getLeadFail() ? $project[0]->getLeadFail()->getTitle() : null;
$leadFailReason = $project[0]->getLeadFailNote() ?: null;
$leadFailShow = $leadFailText . ($leadFailReason ? ': ' . $leadFailReason : '');
// $sheet->setCellValue('G' . $row, $project[0]->getLeadFailNote() ?: '-');
$sheet->setCellValue('G' . $row, $project[0]->getLeadLostReason());
$sheet->setCellValue('H' . $row, $project[0]->getLeadSource() ?: '-');
$sheet->setCellValue('I' . $row, $picName);
$sheet->setCellValue('J' . $row, $picClientName);
$sheet->setCellValue('K' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('K' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('L' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('L' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('M' . $row, $project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
$sheet->setCellValue('N' . $row, $project['proposalDate'] ? $project['proposalDate']->format('Y-m-d') : '-');
$sheet->setCellValue('O' . $row, $project['presentationDate'] ? $project['presentationDate']->format('Y-m-d') : '-');
$sheet->setCellValue('P' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('Q' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$sheet->setCellValue('R' . $row, $project[0]->getLeadFailDate() ? $project[0]->getLeadFailDate()->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('S' . $row, implode(', ', $proSales));
$sheet->setCellValue('T' . $row, implode(', ', $proSalesInvoices));
/*
$multiRow = $row;
$proSalesOrders = $project[0]->getProjectSalesOrders();
foreach ($proSalesOrders as $so){
$sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices();
$multiMultiRow = $multiRow;
foreach($invoices as $invoice){
$sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
$multiMultiRow++;
}
$multiRow = $multiMultiRow;
}
*/
$sheet->setCellValue('U' . $row, $project[0]->getPlannedRevenueUsd());
$sheet->setCellValue('V' . $row, $project[0]->getEstimatedProfitUsd());
$sheet->setCellValue('W' . $row, $project[0]->getSoTotalUsd());
$sheet->setCellValue('X' . $row, $project[0]->getInvoicesTotalUsd());
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('Y' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('Z' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('AA' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('AB' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('AC' . $row, $project['type']);
/*
$sheet->setCellValue('AB' . $row, $project[0]->getProjectProfit3());
$sheet->setCellValue('AC' . $row, $project[0]->getProjectProfit4());
$sheet->setCellValue('AD' . $row, $project[0]->getProjectProfit2());
$sheet->setCellValue('AE' . $row, $project[0]->getProjectProfit1());
*/
$sheet->setCellValue('AD' . $row, $project[0]->getProbabilityText());
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('T2:W' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
// $sheet->getStyle('Y2:Z' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('U2:X' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$sheet->getStyle('Z2:AA' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// $sheet->getStyle('AB2:AE' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
/*
$sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
$sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
*/
} else {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'Lead Lost Reason');
$sheet->setCellValue('H1', 'Lead Source');
$sheet->setCellValue('I1', 'PIC');
$sheet->setCellValue('J1', 'PIC Client');
$sheet->setCellValue('K1', 'Plan File');
$sheet->setCellValue('L1', 'Plan URL');
$sheet->setCellValue('M1', 'Created Date in HRP');
$sheet->setCellValue('N1', 'Sent Date');
$sheet->setCellValue('O1', 'Client Presentation Date');
$sheet->setCellValue('P1', 'Start Date');
$sheet->setCellValue('Q1', 'End Date');
$sheet->setCellValue('R1', 'Lost Date');
$sheet->setCellValue('S1', 'SO Number(s)');
$sheet->setCellValue('T1', 'Invoice Number(s)');
$sheet->setCellValue('U1', 'Estimated Project Hours');
$sheet->setCellValue('V1', 'Employee Time Record Hours');
$sheet->setCellValue('W1', 'Vendor Costs Based On Plan');
$sheet->setCellValue('X1', 'Vendor Costs Based On INV');
$sheet->setCellValue('Y1', 'Project Type');
$sheet->setCellValue('Z1', '% Likely To Win');
$lastCol = $sheet->getHighestColumn();
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$leadFailText = $project[0]->getLeadFail() ? $project[0]->getLeadFail()->getTitle() : null;
$leadFailReason = $project[0]->getLeadFailNote() ?: null;
$leadFailShow = $leadFailText . ($leadFailReason ? ': ' . $leadFailReason : '');
// $sheet->setCellValue('G' . $row, $project[0]->getLeadFailNote()?: '-');
$sheet->setCellValue('G' . $row, $project[0]->getLeadLostReason());
$sheet->setCellValue('H' . $row, $project[0]->getLeadSource() ?: '-');
$sheet->setCellValue('I' . $row, $picName);
$sheet->setCellValue('J' . $row, $picClientName);
$sheet->setCellValue('K' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('K' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('L' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('L' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('M' . $row, $project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
$sheet->setCellValue('N' . $row, $project['proposalDate'] ? $project['proposalDate']->format('Y-m-d') : '-');
$sheet->setCellValue('O' . $row, $project['presentationDate'] ? $project['presentationDate']->format('Y-m-d') : '-');
$sheet->setCellValue('P' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('Q' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$sheet->setCellValue('R' . $row, $project[0]->getLeadFailDate() ? $project[0]->getLeadFailDate()->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('S' . $row, implode(', ', $proSales));
$sheet->setCellValue('T' . $row, implode(', ', $proSalesInvoices));
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('U' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('V' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('W' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('X' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('Y' . $row, $project['type']);
$sheet->setCellValue('Z' . $row, $project[0]->getProbabilityText());
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('V2:W'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('W2:X' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
}
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
public function exportProjectConfirmed($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $_target)
{
if ($isAdmin) {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->freezePane('A2');
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'Score');
$sheet->setCellValue('H1', 'Lead Source');
$sheet->setCellValue('I1', 'PIC');
$sheet->setCellValue('J1', 'PIC Client');
$sheet->setCellValue('K1', 'Plan File');
$sheet->setCellValue('L1', 'Plan URL');
$sheet->setCellValue('M1', 'Created Date in HRP');
$sheet->setCellValue('N1', 'Win Date');
$sheet->setCellValue('O1', 'Start Date');
$sheet->setCellValue('P1', 'End Date');
$sheet->setCellValue('Q1', 'SO Number(s)');
$sheet->setCellValue('R1', 'Invoice Number(s)');
$sheet->setCellValue('S1', 'Estimated Project Billings');
$sheet->setCellValue('T1', 'Estimated Agency Revenue');
$sheet->setCellValue('U1', 'Estimated Project Billings Based on SO');
$sheet->setCellValue('V1', 'Estimated Project Billings Based on INV');
$sheet->setCellValue('W1', 'Estimated Project Hours');
// $sheet->setCellValue('O1', 'Man Hours Cost');
$sheet->setCellValue('X1', 'Employee Time Record Hours');
$sheet->setCellValue('Y1', 'Vendor Planned Amount USD');
$sheet->setCellValue('Z1', 'Vendor INV Allocated USD');
$sheet->setCellValue('AA1', 'Budget Remaining USD');
$sheet->setCellValue('AB1', 'Vendor Planned Amount (Vendor planning Currency)');
$sheet->setCellValue('AC1', 'Vendor INV Allocated (Vendor planning Currency)');
$sheet->setCellValue('AD1', 'Budget Remaining (Vendor planning Currency)');
/*
$sheet->setCellValue('S1', 'Estimated Project Billings');
$sheet->setCellValue('ST1', 'Total Cost');
$sheet->setCellValue('U1', 'Total Profit');
*/
$sheet->setCellValue('AE1', 'Project Type');
/*
$sheet->setCellValue('AE1', 'Profit (SO amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('AF1', 'Profit (INV amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('AG1', 'Profit (SO amount - 3rd party invoices - man hours)');
$sheet->setCellValue('AH1', 'Profit (INV amount - 3rd party invoices - man hours)');
$sheet->setCellValue('AI1', 'INV Amount - 3rd Party INV');
$sheet->setCellValue('AJ1', 'AM GM');
$sheet->setCellValue('AK1', 'Media GM');
$sheet->setCellValue('AL1', 'Crea GM');
$sheet->setCellValue('AM1', 'Tech GM');
$sheet->setCellValue('AN1', 'SEO GM');
$sheet->setCellValue('AO1', 'Data GM');
$sheet->setCellValue('AP1', 'Social GM');
*/
$lastCol = $sheet->getHighestColumn();
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$clientName = null;
if ($client) {
$clientData = $this->entityManager->getRepository(Client::class)->find($client);
if ($clientData) {
$clientName = $clientData->getName();
};
};
$picName = null;
if ($pic) {
$picData = $this->entityManager->getRepository(User::class)->find($pic);
if ($picData) {
$picName = $picData->getPersonalInfo()->getFullName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $clientName ? "-" . urlencode($clientName) : "";
$filename .= $picName ? "-" . urlencode($picName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
//$sheet->insertNewRowBefore($row);
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$sheet->setCellValue('G' . $row, $project[0]->getScore() ?: '-');
$sheet->setCellValue('H' . $row, $project[0]->getLeadSource() ?: '-');
$sheet->setCellValue('I' . $row, $picName);
$sheet->setCellValue('J' . $row, $picClientName);
$sheet->setCellValue('K' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('K' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('L' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('L' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('M' . $row, $project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
$sheet->setCellValue('N' . $row, $project['winDate'] ? $project['winDate']->format('Y-m-d') : '-');
$sheet->setCellValue('O' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('P' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('Q' . $row, implode(', ', $proSales));
$sheet->setCellValue('R' . $row, implode(', ', $proSalesInvoices));
/*
$multiRow = $row;
$proSalesOrders = $project[0]->getProjectSalesOrders();
foreach ($proSalesOrders as $so){
$sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices();
$multiMultiRow = $multiRow;
foreach($invoices as $invoice){
$sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
$multiMultiRow++;
}
$multiRow = $multiMultiRow;
}
*/
$sheet->setCellValue('S' . $row, $project[0]->getPlannedRevenueUsd());
$sheet->setCellValue('T' . $row, $project[0]->getEstimatedProfitUsd());
$sheet->setCellValue('U' . $row, $project[0]->getSoTotalUsd());
$sheet->setCellValue('V' . $row, $project[0]->getInvoicesTotalUsd());
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('W' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('X' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('Y' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('Z' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('AA' . $row, $project[0]->getProjectBudgetRemainingUsd());
$sheet->setCellValue('AB' . $row, $project[0]->getVendorPlannedTotal());
$sheet->setCellValue('AC' . $row, $project[0]->getVendorInvoicesTotal());
$sheet->setCellValue('AD' . $row, $project[0]->getProjectBudgetRemaining());
$sheet->setCellValue('AE' . $row, $project['type']);
/*
$sheet->setCellValue('AE' . $row, $project[0]->getProjectProfit3());
$sheet->setCellValue('AF' . $row, $project[0]->getProjectProfit4());
$sheet->setCellValue('AG' . $row, $project[0]->getProjectProfit2());
$sheet->setCellValue('AH' . $row, $project[0]->getInvoicesTotalUsd() - $project[0]->getVendorInvoicesTotalUsd() - $project[0]->getProjectManhourCost());
$invVendorProfit = $project[0]->getInvoicesTotalUsd() - $project[0]->getVendorInvoicesTotalUsd();
$sheet->setCellValue('AI' . $row, $invVendorProfit);
foreach($departments as $hourDept){
switch($hourDept['name']){
case 'Account Management':
$sheet->setCellValue('AJ' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'Media':
$sheet->setCellValue('AK' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'Creative':
$sheet->setCellValue('AL' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'Technology':
$sheet->setCellValue('AM' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'SEO':
$sheet->setCellValue('AN' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'Data & Analytics':
$sheet->setCellValue('AO' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
case 'Social & Content':
$sheet->setCellValue('AP' . $row, ($hourDept['totalCost'] / $totalCostAll) * $invVendorProfit);
break;
}
}
*/
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('R2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
// $sheet->getStyle('X2:AC' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('S2:V' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$sheet->getStyle('Y2:AD' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// $sheet->getStyle('AE2:A'.$lastCol. $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
/*
$sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
$sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
*/
} else {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'Score');
$sheet->setCellValue('H1', 'Lead Source');
$sheet->setCellValue('I1', 'PIC');
$sheet->setCellValue('J1', 'PIC Client');
$sheet->setCellValue('K1', 'Plan File');
$sheet->setCellValue('L1', 'Plan URL');
$sheet->setCellValue('M1', 'Created Date in HRP');
$sheet->setCellValue('N1', 'Win Date');
$sheet->setCellValue('O1', 'Start Date');
$sheet->setCellValue('P1', 'End Date');
$sheet->setCellValue('Q1', 'SO Number(s)');
$sheet->setCellValue('R1', 'Invoice Number(s)');
$sheet->setCellValue('S1', 'Estimated Project Hours');
$sheet->setCellValue('T1', 'Employee Time Record Hours');
// $sheet->setCellValue('Q1', 'Vendor Costs Based On Plan');
// $sheet->setCellValue('R1', 'Vendor Costs Based On INV');
$sheet->setCellValue('U1', 'Vendor Planned Amount USD');
$sheet->setCellValue('V1', 'Vendor INV Allocated USD');
$sheet->setCellValue('W1', 'Budget Remaining USD');
$sheet->setCellValue('X1', 'Vendor Planned Amount (Vendor planning Currency)');
$sheet->setCellValue('Y1', 'Vendor INV Allocated (Vendor planning Currency)');
$sheet->setCellValue('Z1', 'Budget Remaining (Vendor planning Currency)');
$sheet->setCellValue('AA1', 'Project Type');
$lastCol = $sheet->getHighestColumn();
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$sheet->setCellValue('G' . $row, $project[0]->getScore() ?: '-');
$sheet->setCellValue('H' . $row, $project[0]->getLeadSource() ?: '-');
$sheet->setCellValue('I' . $row, $picName);
$sheet->setCellValue('J' . $row, $picClientName);
$sheet->setCellValue('K' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('K' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('L' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('L' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('M' . $row, $project['createdAt'] ? $project['createdAt']->format('Y-m-d') : '-');
$sheet->setCellValue('N' . $row, $project['winDate'] ? $project['winDate']->format('Y-m-d') : '-');
$sheet->setCellValue('O' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('P' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('Q' . $row, implode(', ', $proSales));
$sheet->setCellValue('R' . $row, implode(', ', $proSalesInvoices));
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('S' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('T' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('U' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('V' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('W' . $row, $project[0]->getProjectBudgetRemainingUsd());
$sheet->setCellValue('X' . $row, $project[0]->getVendorPlannedTotal());
$sheet->setCellValue('Y' . $row, $project[0]->getVendorInvoicesTotal());
$sheet->setCellValue('Z' . $row, $project[0]->getProjectBudgetRemaining());
$sheet->setCellValue('AA' . $row, $project['type']);
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('T2:Y'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('U2:Z' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
}
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
public function exportProjectInternal($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $_target)
{
if ($isAdmin) {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->freezePane('A2');
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'PIC');
$sheet->setCellValue('H1', 'PIC Client');
$sheet->setCellValue('I1', 'Plan File');
$sheet->setCellValue('J1', 'Plan URL');
$sheet->setCellValue('K1', 'Start Date');
$sheet->setCellValue('L1', 'End Date');
$sheet->setCellValue('M1', 'SO Number(s)');
$sheet->setCellValue('N1', 'Invoice Number(s)');
$sheet->setCellValue('O1', 'Estimated Project Billings');
$sheet->setCellValue('P1', 'Estimated Agency Revenue');
$sheet->setCellValue('Q1', 'Estimated Project Billings Based on SO');
$sheet->setCellValue('R1', 'Estimated Project Billings Based on INV');
$sheet->setCellValue('S1', 'Estimated Project Hours');
// $sheet->setCellValue('O1', 'Man Hours Cost');
$sheet->setCellValue('T1', 'Employee Time Record Hours');
$sheet->setCellValue('U1', 'Vendor Costs Based On Plan');
$sheet->setCellValue('V1', 'Vendor Costs Based On INV');
/*
$sheet->setCellValue('S1', 'Estimated Project Billings');
$sheet->setCellValue('ST1', 'Total Cost');
$sheet->setCellValue('U1', 'Total Profit');
*/
$sheet->setCellValue('W1', 'Project Type');
$sheet->setCellValue('X1', 'Profit (SO amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('Y1', 'Profit (INV amount - 3rd party cost planned - man hours)');
$sheet->setCellValue('Z1', 'Profit (SO amount - 3rd party invoices - man hours)');
$sheet->setCellValue('AA1', 'Profit (INV amount - 3rd party invoices - man hours)');
$lastCol = 'AA';
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$clientName = null;
if ($client) {
$clientData = $this->entityManager->getRepository(Client::class)->find($client);
if ($clientData) {
$clientName = $clientData->getName();
};
};
$picName = null;
if ($pic) {
$picData = $this->entityManager->getRepository(User::class)->find($pic);
if ($picData) {
$picName = $picData->getPersonalInfo()->getFullName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $clientName ? "-" . urlencode($clientName) : "";
$filename .= $picName ? "-" . urlencode($picName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
//$sheet->insertNewRowBefore($row);
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$sheet->setCellValue('G' . $row, $picName);
$sheet->setCellValue('H' . $row, $picClientName);
$sheet->setCellValue('I' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('I' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('J' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('J' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('K' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('L' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('M' . $row, implode(', ', $proSales));
$sheet->setCellValue('N' . $row, implode(', ', $proSalesInvoices));
/*
$multiRow = $row;
$proSalesOrders = $project[0]->getProjectSalesOrders();
foreach ($proSalesOrders as $so){
$sheet->setCellValue('J' . $multiRow, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices();
$multiMultiRow = $multiRow;
foreach($invoices as $invoice){
$sheet->setCellValue('K' . $multiMultiRow, $invoice->getInvoice()->getInvoiceNo());
$multiMultiRow++;
}
$multiRow = $multiMultiRow;
}
*/
$sheet->setCellValue('O' . $row, '-');
$sheet->setCellValue('P' . $row, '-');
$sheet->setCellValue('Q' . $row, $project[0]->getSoTotalUsd());
$sheet->setCellValue('R' . $row, $project[0]->getInvoicesTotalUsd());
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('S' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('T' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('U' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('V' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('W' . $row, $project['type']);
$sheet->setCellValue('X' . $row, $project[0]->getProjectProfit3());
$sheet->setCellValue('Y' . $row, $project[0]->getProjectProfit4());
$sheet->setCellValue('Z' . $row, $project[0]->getProjectProfit2());
$sheet->setCellValue('AA' . $row, $project[0]->getProjectProfit1());
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('O2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
// $sheet->getStyle('T2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
// $sheet->getStyle('W2:AA' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('O2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$sheet->getStyle('T2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$sheet->getStyle('W2:AA' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
/*
$sheet->getStyle('L2:M'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
$sheet->getStyle('O2:V'. $sheet->getHighestRow())->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
*/
} else {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Client Name');
$sheet->setCellValue('C1', 'Client Industry');
$sheet->setCellValue('D1', 'Project Classification');
$sheet->setCellValue('E1', 'Project Name');
$sheet->setCellValue('F1', 'Project Status');
$sheet->setCellValue('G1', 'PIC');
$sheet->setCellValue('H1', 'PIC Client');
$sheet->setCellValue('I1', 'Plan File');
$sheet->setCellValue('J1', 'Plan URL');
$sheet->setCellValue('K1', 'Start Date');
$sheet->setCellValue('L1', 'End Date');
$sheet->setCellValue('M1', 'SO Number(s)');
$sheet->setCellValue('N1', 'Invoice Number(s)');
$sheet->setCellValue('O1', 'Estimated Project Hours');
$sheet->setCellValue('P1', 'Employee Time Record Hours');
$sheet->setCellValue('Q1', 'Vendor Costs Based On Plan');
$sheet->setCellValue('R1', 'Vendor Costs Based On INV');
$sheet->setCellValue('S1', 'Project Type');
$lastCol = 'S';
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $lastCol . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $lastCol . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $lastCol . "2")->getFont()->setBold(false);
// $sheet->getStyle("A2:".$lastCol."2")->getAlignment()->setWrapText(true);
$sheet->getStyle("A2:" . $lastCol . "2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$departmentName = null;
if ($department) {
$departmentData = $this->entityManager->getRepository(Department::class)->find($department);
if ($departmentData) {
$departmentName = $departmentData->getName();
};
};
$filename = "Project";
$filename .= $departmentName ? "-" . urlencode($departmentName) : "";
$filename .= $keyword ? "-" . urlencode($keyword) : "";
$filename .= $status ? "-" . urlencode($status) : "";
$filename .= $type ? "-" . urlencode($type) : "";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "ASC", null, $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted, $pic);
$n = 0;
foreach ($projectsList as $projectDetail) {
$projectsList[$n]['cost'] = $projectDetail[0]->getProjectCost();
$projectsList[$n]['profit'] = $projectDetail[0]->getProjectProfit1();
$projectsList[$n]['leadStatusText'] = $projectDetail[0]->getLeadStatus() ? $projectDetail[0]->getLeadStatus()->getName() : null;
$n++;
};
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$picClientName = $project[0]->getClientPersonInCharge() ? $project[0]->getClientPersonInCharge()->getFirstName() . ' ' . $project[0]->getClientPersonInCharge()->getLastName() : '-';
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('E' . $row, $project['name']);
$sheet->getCell('E' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$sheet->setCellValue('G' . $row, $picName);
$sheet->setCellValue('H' . $row, $picClientName);
$sheet->setCellValue('I' . $row, $project['planFilename'] ? $project['planFilename'] : "-");
if ($project['planFilename']) {
$sheet->getCell('I' . $row)->getHyperlink()->setUrl($project['planFilepath']);
}
$sheet->setCellValue('J' . $row, $project['planURL'] ? $project['planURL'] : "-");
if ($project['planURL']) {
$sheet->getCell('J' . $row)->getHyperlink()->setUrl($project['planURL']);
}
$sheet->setCellValue('K' . $row, $project['startDate'] ? $project['startDate']->format('Y-m-d') : '-');
$sheet->setCellValue('L' . $row, $project['endDate'] ? $project['endDate']->format('Y-m-d') : '-');
$proSalesOrders = $project[0]->getProjectSalesOrders();
$proSales = [];
$proSalesInvoices = [];
foreach ($proSalesOrders as $so) {
array_push($proSales, $so->getSalesOrder()->getSalesOrderNo());
$invoices = $so->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($invoices as $invoice) {
$dataINV = $invoice->getInvoice()->getXeroStatus() == 'DRAFT' ? $invoice->getInvoice()->getInvoiceNo() . ' (Draft)' : $invoice->getInvoice()->getInvoiceNo();
array_push($proSalesInvoices, $dataINV);
}
}
$sheet->setCellValue('M' . $row, implode(', ', $proSales));
$sheet->setCellValue('N' . $row, implode(', ', $proSalesInvoices));
$resourceAllocations = $this->allocatedHoursRepository->findByProject('', '', $project['id']);
$totalEstimatedProjectHours = 0;
foreach ($resourceAllocations as $allocation) {
$totalEstimatedProjectHours += intval($allocation->getHours());
}
$estimatedProjectHours = !empty($totalEstimatedProjectHours) ? $totalEstimatedProjectHours : '-';
$sheet->setCellValue('O' . $row, $estimatedProjectHours);
// $sheet->setCellValue('O' . $row, $project[0]->getProjectManhourCost());
// Calculate employee time record
$_id = intval($project['id']);
$departments = $this->timeSpentRepository->getDepartmentsForProject($_id, $project[0]->getStartDate(), $project[0]->getEndDate());
$totalHoursAll = 0;
$totalCostAll = 0;
for ($i = 0; $i < sizeof($departments); $i++) {
$employeeSummaryList = $this->userRepository->findTaskSummary($_id, $departments[$i]['id']);
$i2 = 0;
/*foreach($employeeSummaryList as $employee){
$projectMember = $project->getProjectMember($employee['id']);
$employeeSummaryList[$i2]['hourly'] = $projectMember->getUser()->getHourlyRateUsd();
$i2++;
}*/
$departments[$i]['employeeSummaryList'] = $employeeSummaryList;
$tmpHours = 0;
$tmpCost = 0;
for ($j = 0; $j < sizeof($employeeSummaryList); $j++) {
$tmpHours = $tmpHours + $employeeSummaryList[$j]['hours'];
$tmpCost = $tmpCost + $employeeSummaryList[$j]['cost'];
}
//$totalManpowerCost += $tmpCost;
$departments[$i]['totalCost'] = $tmpCost;
$departments[$i]['totalHours'] = $tmpHours;
}
if (count($departments) > 0) {
foreach ($departments as $department) {
$totalHoursAll += $department['totalHours'];
$totalCostAll += $department['totalCost'];
}
}
$employeeTimeRecordHours = !empty($totalHoursAll) ? $totalHoursAll : '-';
$sheet->setCellValue('P' . $row, $employeeTimeRecordHours);
$sheet->setCellValue('Q' . $row, $project[0]->getVendorPlannedTotalUsd());
$sheet->setCellValue('R' . $row, $project[0]->getVendorInvoicesTotalUsd());
$sheet->setCellValue('S' . $row, $project['type']);
$row++;
}
$sheet->setAutoFilter('A1:' . $lastCol . $sheet->getHighestRow());
$sheet->getStyle("E1:E" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('Q2:R'.$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('Q2:R' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
}
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
/**
* Export Project Revenue Forecast by Project Date
*/
public function exportProjectRevenueForecastProjectDate($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $isCashflow = true, $_target)
{
$startDateRange = date("d-M-Y", strtotime($startDate));
$endDateRange = date("d-M-Y", strtotime($endDate));
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle($isCashflow ? 'Cashflow Forecast' : 'Revenue Forecast');
$sheet->setCellValue('A1', 'Today\'s Date');
$sheet->setCellValue('A2', 'From');
$sheet->setCellValue('A3', 'To');
$sheet->setCellValue('B1', date('d-M-Y'));
$sheet->setCellValue('B2', $startDateRange);
$sheet->setCellValue('B3', $endDateRange);
// Define Header Total
$sheet->setCellValue('A5', 'Total');
$sheet->setCellValue('I5', 'Total Est. Project Billings');
$sheet->setCellValue('J5', 'Total Est. Project Billings FYTD');
$sheet->setCellValue('K5', 'Total Est. Agency Revenue');
$sheet->setCellValue('L5', 'Total Est. Agency Revenue FYTD');
$sheet->setCellValue('A6', 'Total Planned Revenue (LEADS + CONFIRMED)');
$sheet->setCellValue('A7', 'Total CONFIRMED Revenue');
$sheet->setCellValue('A8', 'Total LEADS Revenue');
$sheet->mergeCells('A5:H5');
$sheet->mergeCells('A6:H6');
$sheet->mergeCells('A7:H7');
$sheet->mergeCells('A8:H8');
// Define Header Data
$sheet->setCellValue('A9', 'Project ID');
$sheet->setCellValue('B9', 'Client Name');
$sheet->setCellValue('C9', 'Client Industry');
$sheet->setCellValue('D9', 'Project Name');
$sheet->setCellValue('E9', 'Project Classification');
$sheet->setCellValue('F9', 'Project Status');
$sheet->setCellValue('G9', 'PIC');
$sheet->setCellValue('H9', '% Likely to Win');
$sheet->setCellValue('I9', 'Est. Project Billings');
$sheet->setCellValue('J9', 'Est. Project Billings FYTD');
$sheet->setCellValue('K9', 'Est. Agency Revenue');
$sheet->setCellValue('L9', 'Est. Agency Revenue FYTD');
$lastCol = 'L';
$sheet->freezePane('A10');
$sheet->freezePane('C10');
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getColumnDimension('A')->setWidth(11);
$sheet->getColumnDimension('H')->setWidth(15);
$sheet->getColumnDimension('I')->setWidth(17);
$sheet->getColumnDimension('J')->setWidth(17);
$sheet->getColumnDimension('K')->setWidth(17);
$sheet->getColumnDimension('L')->setWidth(17);
$sheet->getStyle("A10:" . $lastCol . "10")->getFont()->setBold(false);
$sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setWrapText(true);
$sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$filename = $isCashflow ? "Cashflow_Forecast_Report" : "Revenue_Recognition_Report";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
$row = $sheet->getHighestRow();
$totalEstProjectBillings = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenue = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
foreach ($projectsList as $project) {
$picName = $project['picMiddleName'] ? $project['picFirstName'] . ' ' . $project['picMiddleName'] . ' ' . $project['picLastName'] : $project['picFirstName'] . ' ' . $project['picLastName'];
$sheet->setCellValue('A' . $row, $project['generatedId']);
$sheet->setCellValue('B' . $row, $project['clientName']);
$clientIndustryClassification = $project[0]->getClient() ? $project[0]->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project[0]->getprojectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $project['name']);
$sheet->getCell('D' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue('E' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('F' . $row, $project['type'] == 'LEAD' ? $project['lead'] . ' - ' . $project[0]->getLeadStatus()->getName() : ($project['status'] ? $project['status'] : '-'));
$sheet->setCellValue('G' . $row, $picName);
$sheet->setCellValue('H' . $row, $project[0]->getProbabilityText());
$probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project['type'] == 'LEAD' ? $project[0]->getPlannedRevenueUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
$estAgencyRevenue = $project['type'] == 'LEAD' ? $project[0]->getEstimatedProfitUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD();
if ($project['type'] == 'CONFIRMED') {
$totalEstProjectBillings['confirmed'] += $estProjectBillings;
$totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
} elseif ($project['type'] == 'LEAD') {
$totalEstProjectBillings['lead'] += $estProjectBillings;
$totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
}
$totalEstProjectBillings['total'] += $estProjectBillings;
$totalEstAgencyRevenue['total'] += $estAgencyRevenue;
$sheet->setCellValue('I' . $row, $estProjectBillings);
$sheet->setCellValue('K' . $row, $estAgencyRevenue);
$row++;
}
$sheet->setCellValue('I6', $totalEstProjectBillings['total']);
$sheet->setCellValue('I7', $totalEstProjectBillings['confirmed']);
$sheet->setCellValue('I8', $totalEstProjectBillings['lead']);
$sheet->setCellValue('K6', $totalEstAgencyRevenue['total']);
$sheet->setCellValue('K7', $totalEstAgencyRevenue['confirmed']);
$sheet->setCellValue('K8', $totalEstAgencyRevenue['lead']);
// define breakdown
$column = [];
for ($i = 65; $i <= 90; $i++) {
$column[] = chr($i);
}
for ($i = 65; $i <= 90; $i++) {
for ($j = 65; $j <= 90; $j++) {
$column[] = chr($i) . chr($j);
}
}
// define column months
$monthColumn = [];
foreach ($projectsList as $project) {
if ($project['lead'] == '8') {
$revenues = $this->monthlyRevenues($project[0], $isCashflow);
$newRevenues = [];
foreach ($revenues as $oldKey => $value) {
list($month, $year) = explode('-', $oldKey);
$parsedMonth = date_parse($month);
$newKey = sprintf('%02d-%s', $parsedMonth['month'], $year);
$newRevenues[$newKey] = $value;
}
foreach ($newRevenues as $newRevenueKey => $value) {
$month = $newRevenueKey;
if (!in_array($month, $monthColumn)) {
$monthColumn[] = $month;
}
}
} else {
$revenuePlannings = $project[0]->getRevenuePlannings();
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
if (!in_array($month, $monthColumn)) {
$monthColumn[] = $month;
}
}
}
}
// sort
usort($monthColumn, function ($a, $b) {
$dateA = \DateTime::createFromFormat('d-m-Y', '01-' . $a);
$dateB = \DateTime::createFromFormat('d-m-Y', '01-' . $b);
if ($dateA == $dateB) {
return 0;
}
return ($dateA < $dateB) ? -1 : 1;
});
$sortedMonthColumns = array_map(function ($date) {
$dateTime = \DateTime::createFromFormat('d-m-Y', '01-' . $date);
return $dateTime->format('M-Y');
}, $monthColumn);
$lastCol = $sheet->getHighestColumn(); // 'L'
$key = array_search($lastCol, $column);
$cellColumn = []; // breakdown month column based on cell column
$i = $key + 1;
foreach ($sortedMonthColumns as $monthColumn) {
$cellColumn[$i] = $monthColumn;
$sheet->setCellValue($column[$i] . "5", $monthColumn);
$sheet->setCellValue($column[$i] . "9", $monthColumn);
$i++;
}
$totalColumnBreakdown = [];
foreach ($cellColumn as $cell) {
$totalColumnBreakdown[$cell]['total'] = 0;
$totalColumnBreakdown[$cell]['confirmed'] = 0;
$totalColumnBreakdown[$cell]['lead'] = 0;
}
// fill cell
$monthRow = 10;
foreach ($projectsList as $project) {
foreach ($cellColumn as $cellValue => $value) {
$sheet->setCellValue($column[$cellValue] . $monthRow, '-');
}
if ($project['lead'] == '8') {
$revenues = $this->monthlyRevenues($project[0], $isCashflow);
foreach ($revenues as $key => $value) {
$month = $key;
$cell = array_search($month, $cellColumn);
$sheet->setCellValue($column[$cell] . $monthRow, $value['totalUsd']);
if ($project['type'] == 'CONFIRMED') $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
$totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
}
} else {
$probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
$revenuePlannings = $project[0]->getRevenuePlannings()->toArray();
if (count($revenuePlannings) > 0) {
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
$month = \DateTime::createFromFormat('d-m-Y', '01-' . $month)->format('M-Y');
$cell = array_search($month, $cellColumn);
$revenueAmountUsd = $project['type'] == 'LEAD' ? $revenuePlanning->getAmountUsd() * $probabilityPercent : $revenuePlanning->getAmountUsd();
$sheet->setCellValue($column[$cell] . $monthRow, $revenueAmountUsd);
if ($project['type'] == 'LEAD') $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
// if($project['type'] == 'CONFIRMED') $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
$totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
}
}
}
$monthRow++;
}
// fill total cell
foreach ($cellColumn as $key => $cellCol) {
for ($i = 6; $i <= 8; $i++) {
$type = $i == 6 ? 'total' : ($i == 7 ? 'confirmed' : 'lead');
$sheet->setCellValue($column[$key] . $i, $totalColumnBreakdown[$cellCol][$type]);
}
}
// FYTD = 1st nov22 - 31st oct23
// Calculate FYTD start and end dates (Nov 1st - Oct 31st)
$currentYear = date('Y');
$fytdStartDate = new \DateTime($currentYear - 1 . '-11-01');
$fytdEndDate = new \DateTime($currentYear . '-10-31');
// Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
$totalEstProjectBillingsFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenueFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$row = 10;
foreach ($projectsList as $project) {
$totalMonths = 0;
$numMonthsFYTD = 0;
if (!empty($project[0]->getStartDate()) && !empty($project[0]->getEndDate())) {
$dateInterval = $project[0]->getEndDate()->diff($project[0]->getStartDate());
$yearsInMonths = $dateInterval->y * 12;
$months = $dateInterval->m;
$days = $dateInterval->d;
if ($days > 0) {
$months++;
}
$totalMonths = $yearsInMonths + $months;
if ($dateInterval->y === 0 && $dateInterval->m === 0 && $dateInterval->d === 0) {
$totalMonths = 1;
}
$numMonthsFYTD = $this->calculateIncludedMonths($project[0]->getStartDate(), $project[0]->getEndDate());
} else {
$totalMonths = 1;
$numMonthsFYTD = 1;
}
$probabilityPercent = $project[0]->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project['type'] == 'LEAD' ? $project[0]->getPlannedRevenueUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD() + $project[0]->getTotalVendorCostUsd();
$estAgencyRevenue = $project['type'] == 'LEAD' ? $project[0]->getEstimatedProfitUsd() * $probabilityPercent : $project[0]->getTotalRevenueUSD();
$formulaBillings = $totalMonths == $numMonthsFYTD ? $estProjectBillings : ($estProjectBillings / $totalMonths) + ($estProjectBillings / $totalMonths * $numMonthsFYTD);
$formulaRevenue = $totalMonths == $numMonthsFYTD ? $estAgencyRevenue : ($estAgencyRevenue / $totalMonths) + ($estAgencyRevenue / $totalMonths * $numMonthsFYTD);
if ($project['type'] == 'CONFIRMED') {
$totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
} elseif ($project['type'] == 'LEAD') {
$totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
}
$totalEstProjectBillingsFYTD['total'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
$sheet->setCellValue('J' . $row, $formulaBillings);
$sheet->setCellValue('L' . $row, $formulaRevenue);
$row++;
}
$sheet->setCellValue('J6', $totalEstProjectBillingsFYTD['total']);
$sheet->setCellValue('J7', $totalEstProjectBillingsFYTD['confirmed']);
$sheet->setCellValue('J8', $totalEstProjectBillingsFYTD['lead']);
$sheet->setCellValue('L6', $totalEstAgencyRevenueFYTD['total']);
$sheet->setCellValue('L7', $totalEstAgencyRevenueFYTD['confirmed']);
$sheet->setCellValue('L8', $totalEstAgencyRevenueFYTD['lead']);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A6:" . $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->setAutoFilter('A9:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
$sheet->getStyle("D1:D" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('I6:' . $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
/**
* Export Project Revenue Forecast by Invoice Date / Due Date
*/
public function exportProjectRevenueForecast($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $isCashflow = true, $_target)
{
$startDateRange = date("d-M-Y", strtotime($startDate));
$endDateRange = date("d-M-Y", strtotime($endDate));
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle($isCashflow ? 'Cashflow Forecast' : 'Revenue Forecast');
$sheet->setCellValue('A1', 'Today\'s Date');
$sheet->setCellValue('A2', 'From ' . ($isCashflow ? '(Invoice Due Date)' : '(Invoice Date)'));
$sheet->setCellValue('A3', 'To ' . ($isCashflow ? '(Invoice Due Date)' : '(Invoice Date)'));
$sheet->setCellValue('C1', date('d-M-Y'));
$sheet->setCellValue('C2', $startDateRange);
$sheet->setCellValue('C3', $endDateRange);
// Define Header Total
$sheet->setCellValue('A5', 'Total');
$sheet->setCellValue('I5', 'Total Est. Project Billings');
$sheet->setCellValue('J5', 'Total Est. Project Billings FYTD');
$sheet->setCellValue('K5', 'Total Est. Agency Revenue');
$sheet->setCellValue('L5', 'Total Est. Agency Revenue FYTD');
$sheet->setCellValue('A6', 'Total Planned Revenue (LEADS + CONFIRMED)');
$sheet->setCellValue('A7', 'Total CONFIRMED Revenue');
$sheet->setCellValue('A8', 'Total LEADS Revenue');
$sheet->mergeCells('A5:H5');
$sheet->mergeCells('A6:H6');
$sheet->mergeCells('A7:H7');
$sheet->mergeCells('A8:H8');
// Define Header Data
$sheet->setCellValue('A9', 'Project ID');
$sheet->setCellValue('B9', 'Client Name');
$sheet->setCellValue('C9', 'Client Industry');
$sheet->setCellValue('D9', 'Project Name');
$sheet->setCellValue('E9', 'Project Classification');
$sheet->setCellValue('F9', 'Project Status');
$sheet->setCellValue('G9', 'PIC');
$sheet->setCellValue('H9', '% Likely to Win');
$sheet->setCellValue('I9', 'Est. Project Billings');
$sheet->setCellValue('J9', 'Est. Project Billings FYTD');
$sheet->setCellValue('K9', 'Est. Agency Revenue');
$sheet->setCellValue('L9', 'Est. Agency Revenue FYTD');
$lastCol = $sheet->getHighestColumn();
$sheet->freezePane('A10');
$sheet->freezePane('D10');
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getColumnDimension('A')->setWidth(11);
$sheet->getColumnDimension('H')->setWidth(15);
$sheet->getColumnDimension('I')->setWidth(17);
$sheet->getColumnDimension('J')->setWidth(17);
$sheet->getColumnDimension('K')->setWidth(17);
$sheet->getColumnDimension('L')->setWidth(17);
$sheet->getStyle("A10:" . $lastCol . "10")->getFont()->setBold(false);
$sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setWrapText(true);
$sheet->getStyle("A10:" . $lastCol . "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$filename = $isCashflow ? "Cashflow_Forecast_Report" : "Revenue_Forecast_Report";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
// $projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
$projectsList = [];
$projectIds = [];
$invoiceList = $this->invoiceRepository->findByPage(0, 9999, "", "DESC", "", "", "", $startDate, $endDate, $isCashflow);
foreach ($invoiceList as $invoice) {
$salesOrderInvoices = $invoice->getSalesOrderInvoices()->toArray();
foreach ($salesOrderInvoices as $salesOrderInvoice) {
$project = $salesOrderInvoice->getProject();
$projectId = $project->getId();
if (!in_array($projectId, $projectIds)) {
$projectsList[] = $project;
$projectIds[] = $projectId;
}
}
}
$row = $sheet->getHighestRow();
$totalEstProjectBillings = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenue = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
foreach ($projectsList as $project) {
$picName = $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' . $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' . $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
$sheet->setCellValue('A' . $row, $project->getGeneratedId());
$sheet->setCellValue('B' . $row, $project->getClient() ? $project->getClient()->getName() : '');
$clientIndustryClassification = $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$sheet->setCellValue('C' . $row, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project->getProjectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$sheet->setCellValue('D' . $row, $project->getName());
$sheet->getCell('D' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
$sheet->setCellValue('E' . $row, $projectClassification ? implode(', ', $projectClassification) : '-');
$sheet->setCellValue('F' . $row, $project->getType() == 'LEAD' ? $project->getLead() . ' - ' . $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
$sheet->setCellValue('G' . $row, $picName);
$sheet->setCellValue('H' . $row, $project->getProbabilityText());
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project->getType() == 'LEAD' ? $project->getPlannedRevenueUsd() * $probabilityPercent : $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
$estAgencyRevenue = $project->getType() == 'LEAD' ? $project->getEstimatedProfitUsd() * $probabilityPercent : $project->getTotalRevenueUSD();
if ($project->getType() == 'CONFIRMED') {
$totalEstProjectBillings['confirmed'] += $estProjectBillings;
$totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
} elseif ($project->getType() == 'LEAD') {
$totalEstProjectBillings['lead'] += $estProjectBillings;
$totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
}
$totalEstProjectBillings['total'] += $estProjectBillings;
$totalEstAgencyRevenue['total'] += $estAgencyRevenue;
$sheet->setCellValue('I' . $row, $estProjectBillings);
$sheet->setCellValue('K' . $row, $estAgencyRevenue);
$row++;
}
$sheet->setCellValue('I6', $totalEstProjectBillings['total']);
$sheet->setCellValue('I7', $totalEstProjectBillings['confirmed']);
$sheet->setCellValue('I8', $totalEstProjectBillings['lead']);
$sheet->setCellValue('K6', $totalEstAgencyRevenue['total']);
$sheet->setCellValue('K7', $totalEstAgencyRevenue['confirmed']);
$sheet->setCellValue('K8', $totalEstAgencyRevenue['lead']);
// define breakdown
$column = [];
for ($i = 65; $i <= 90; $i++) {
$column[] = chr($i);
}
for ($i = 65; $i <= 90; $i++) {
for ($j = 65; $j <= 90; $j++) {
$column[] = chr($i) . chr($j);
}
}
// define column months
$monthColumn = [];
foreach ($projectsList as $project) {
if ($project->getLead() == '8') {
$revenues = $this->monthlyRevenuesNew($project, $isCashflow, $startDate, $endDate);
$newRevenues = [];
foreach ($revenues as $oldKey => $value) {
list($month, $year) = explode('-', $oldKey);
$parsedMonth = date_parse($month);
$newKey = sprintf('%02d-%s', $parsedMonth['month'], $year);
$newRevenues[$newKey] = $value;
}
foreach ($newRevenues as $newRevenueKey => $value) {
$month = $newRevenueKey;
if (!in_array($month, $monthColumn)) {
$monthColumn[] = $month;
}
}
} else {
$revenuePlannings = $project->getRevenuePlannings();
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
if (!in_array($month, $monthColumn)) {
$monthColumn[] = $month;
}
}
}
}
// sort
usort($monthColumn, function ($a, $b) {
$dateA = \DateTime::createFromFormat('d-m-Y', '01-' . $a);
$dateB = \DateTime::createFromFormat('d-m-Y', '01-' . $b);
if ($dateA == $dateB) {
return 0;
}
return ($dateA < $dateB) ? -1 : 1;
});
$sortedMonthColumns = array_map(function ($date) {
$dateTime = \DateTime::createFromFormat('d-m-Y', '01-' . $date);
return $dateTime->format('M-Y');
}, $monthColumn);
// dd($monthColumn);
$lastCol = $sheet->getHighestColumn(); // 'L'
$key = array_search($lastCol, $column);
$cellColumn = []; // breakdown month column based on cell column
$i = $key + 1;
foreach ($sortedMonthColumns as $monthColumn) {
$cellColumn[$i] = $monthColumn;
$sheet->setCellValue($column[$i] . "5", $monthColumn);
$sheet->setCellValue($column[$i] . "9", $monthColumn);
$i++;
}
$totalColumnBreakdown = [];
foreach ($cellColumn as $cell) {
$totalColumnBreakdown[$cell]['total'] = 0;
$totalColumnBreakdown[$cell]['confirmed'] = 0;
$totalColumnBreakdown[$cell]['lead'] = 0;
}
// fill cell
$monthRow = 10;
foreach ($projectsList as $project) {
foreach ($cellColumn as $cellValue => $value) {
$sheet->setCellValue($column[$cellValue] . $monthRow, '-');
}
if ($project->getLead() == '8') {
$revenues = $this->monthlyRevenuesNew($project, $isCashflow, $startDate, $endDate);
foreach ($revenues as $key => $value) {
$month = $key;
$cell = array_search($month, $cellColumn);
$sheet->setCellValue($column[$cell] . $monthRow, $value['totalUsd']);
if ($project->getType() == 'CONFIRMED') $totalColumnBreakdown[$month]['confirmed'] += $value['totalUsd'];
$totalColumnBreakdown[$month]['total'] += $value['totalUsd'];
}
} else {
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$revenuePlannings = $project->getRevenuePlannings()->toArray();
if (count($revenuePlannings) > 0) {
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
$month = \DateTime::createFromFormat('d-m-Y', '01-' . $month)->format('M-Y');
$cell = array_search($month, $cellColumn);
$revenueAmountUsd = $project->getType() == 'LEAD' ? $revenuePlanning->getAmountUsd() * $probabilityPercent : $revenuePlanning->getAmountUsd();
$sheet->setCellValue($column[$cell] . $monthRow, $revenueAmountUsd);
if ($project->getType() == 'LEAD') $totalColumnBreakdown[$month]['lead'] += $revenueAmountUsd;
// if($project['type'] == 'CONFIRMED') $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
$totalColumnBreakdown[$month]['total'] += $revenueAmountUsd;
}
}
}
$monthRow++;
}
// fill total cell
foreach ($cellColumn as $key => $cellCol) {
for ($i = 6; $i <= 8; $i++) {
$type = $i == 6 ? 'total' : ($i == 7 ? 'confirmed' : 'lead');
$sheet->setCellValue($column[$key] . $i, $totalColumnBreakdown[$cellCol][$type]);
}
}
// FYTD = 1st nov22 - 31st oct23
// Calculate FYTD start and end dates (Nov 1st - Oct 31st)
$currentYear = date('Y');
$fytdStartDate = new \DateTime($currentYear - 1 . '-11-01');
$fytdEndDate = new \DateTime($currentYear . '-10-31');
// Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
$totalEstProjectBillingsFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenueFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$row = 10;
foreach ($projectsList as $project) {
$totalMonths = 0;
$numMonthsFYTD = 0;
if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
$dateInterval = $project->getEndDate()->diff($project->getStartDate());
$yearsInMonths = $dateInterval->y * 12;
$months = $dateInterval->m;
$days = $dateInterval->d;
if ($days > 0) {
$months++;
}
$totalMonths = $yearsInMonths + $months;
if ($dateInterval->y === 0 && $dateInterval->m === 0 && $dateInterval->d === 0) {
$totalMonths = 1;
}
$numMonthsFYTD = $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
} else {
$totalMonths = 1;
$numMonthsFYTD = 1;
}
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project->getType() == 'LEAD' ? $project->getPlannedRevenueUsd() * $probabilityPercent : $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
$estAgencyRevenue = $project->getType() == 'LEAD' ? $project->getEstimatedProfitUsd() * $probabilityPercent : $project->getTotalRevenueUSD();
$formulaBillings = $totalMonths == $numMonthsFYTD ? $estProjectBillings : ($estProjectBillings / $totalMonths) + ($estProjectBillings / $totalMonths * $numMonthsFYTD);
$formulaRevenue = $totalMonths == $numMonthsFYTD ? $estAgencyRevenue : ($estAgencyRevenue / $totalMonths) + ($estAgencyRevenue / $totalMonths * $numMonthsFYTD);
if ($project->getType() == 'CONFIRMED') {
$totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
} elseif ($project->getType() == 'LEAD') {
$totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
}
$totalEstProjectBillingsFYTD['total'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
$sheet->setCellValue('J' . $row, $formulaBillings);
$sheet->setCellValue('L' . $row, $formulaRevenue);
$row++;
}
$sheet->setCellValue('J6', $totalEstProjectBillingsFYTD['total']);
$sheet->setCellValue('J7', $totalEstProjectBillingsFYTD['confirmed']);
$sheet->setCellValue('J8', $totalEstProjectBillingsFYTD['lead']);
$sheet->setCellValue('L6', $totalEstAgencyRevenueFYTD['total']);
$sheet->setCellValue('L7', $totalEstAgencyRevenueFYTD['confirmed']);
$sheet->setCellValue('L8', $totalEstAgencyRevenueFYTD['lead']);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A6:" . $sheet->getHighestColumn() . "8")->getFont()->setBold(true);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->setBold(true);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A9:" . $sheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->setAutoFilter('A9:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
$sheet->getStyle("D1:D" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// $sheet->getStyle('I6:'.$sheet->getHighestColumn().$sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$sheet->getStyle('I6:' . $sheet->getHighestColumn() . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// LEAD Revenue Projection
$leadSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Revenue Projection');
$spreadsheet->addSheet($leadSheet, 1);
$leadSheet->setCellValue('A1', 'Today\'s Date');
$leadSheet->setCellValue('A2', 'From (Project Start Date)');
$leadSheet->setCellValue('A3', 'To (Project Start Date)');
$leadSheet->setCellValue('C1', date('d-M-Y'));
$leadSheet->setCellValue('C2', $startDateRange);
$leadSheet->setCellValue('C3', $endDateRange);
// Define Header Total
$leadSheet->setCellValue('A5', 'Total');
$leadSheet->setCellValue('I5', 'Total Est. Project Billings');
$leadSheet->setCellValue('J5', 'Total Est. Project Billings FYTD');
$leadSheet->setCellValue('K5', 'Total Est. Agency Revenue');
$leadSheet->setCellValue('L5', 'Total Est. Agency Revenue FYTD');
$leadSheet->setCellValue('A6', 'Total Planned Revenue (LEADS + CONFIRMED)');
$leadSheet->setCellValue('A7', 'Total CONFIRMED Revenue');
$leadSheet->setCellValue('A8', 'Total LEADS Revenue');
$leadSheet->mergeCells('A5:H5');
$leadSheet->mergeCells('A6:H6');
$leadSheet->mergeCells('A7:H7');
$leadSheet->mergeCells('A8:H8');
// Define Header Data
$leadSheet->setCellValue('A9', 'Project ID');
$leadSheet->setCellValue('B9', 'Client Name');
$leadSheet->setCellValue('C9', 'Client Industry');
$leadSheet->setCellValue('D9', 'Project Name');
$leadSheet->setCellValue('E9', 'Project Classification');
$leadSheet->setCellValue('F9', 'Project Status');
$leadSheet->setCellValue('G9', 'PIC');
$leadSheet->setCellValue('H9', '% Likely to Win');
$leadSheet->setCellValue('I9', 'Est. Project Billings');
$leadSheet->setCellValue('J9', 'Est. Project Billings FYTD');
$leadSheet->setCellValue('K9', 'Est. Agency Revenue');
$leadSheet->setCellValue('L9', 'Est. Agency Revenue FYTD');
$lastColx = $leadSheet->getHighestColumn();
$leadSheet->freezePane('A10');
$leadSheet->freezePane('D10');
$leadSheet->getDefaultColumnDimension()->setWidth(25);
$leadSheet->getColumnDimension('A')->setWidth(11);
$leadSheet->getColumnDimension('H')->setWidth(15);
$leadSheet->getColumnDimension('I')->setWidth(17);
$leadSheet->getColumnDimension('J')->setWidth(17);
$leadSheet->getColumnDimension('K')->setWidth(17);
$leadSheet->getColumnDimension('L')->setWidth(17);
$leadSheet->getStyle("A10:" . $lastColx . "10")->getFont()->setBold(false);
$leadSheet->getStyle("A10:" . $lastColx . "10")->getAlignment()->setWrapText(true);
$leadSheet->getStyle("A10:" . $lastColx . "10")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, 'LEAD', $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
// $projectsList = [];
// $projectIds = [];
// $invoiceList = $this->invoiceRepository->findByPage(0, 9999, "", "DESC", "", "PAID", "", $startDate, $endDate);
// foreach ($invoiceList as $invoice) {
// $salesOrderInvoices = $invoice->getSalesOrderInvoices()->toArray();
// foreach ($salesOrderInvoices as $salesOrderInvoice) {
// $project = $salesOrderInvoice->getProject();
// $projectId = $project->getId();
// if (!in_array($projectId, $projectIds)) {
// $projectsList[] = $project;
// $projectIds[] = $projectId;
// }
// }
// }
$leadRow = $leadSheet->getHighestRow();
$totalEstProjectBillings = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenue = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
foreach ($projectsList as $project) {
$project = $project[0];
$picName = $project->getPersonInCharge() ? $project->getPersonInCharge()->getPersonalInfo()->getFirstName() . ' ' . $project->getPersonInCharge()->getPersonalInfo()->getMiddleName() . ' ' . $project->getPersonInCharge()->getPersonalInfo()->getLastName() : '';
$leadSheet->setCellValue('A' . $leadRow, $project->getGeneratedId());
$leadSheet->setCellValue('B' . $leadRow, $project->getClient() ? $project->getClient()->getName() : '');
$clientIndustryClassification = $project->getClient() ? $project->getClient()->getIndustryClassification() : '';
$clientIndustries = [];
if ($clientIndustryClassification) {
foreach ($clientIndustryClassification as $industryClass) {
array_push($clientIndustries, $industryClass->getName());
}
}
$leadSheet->setCellValue('C' . $leadRow, $clientIndustries ? implode(', ', $clientIndustries) : '-');
$projectTypes = $project->getProjectTypes();
$projectClassification = [];
if ($projectTypes) {
foreach ($projectTypes as $projectType) {
array_push($projectClassification, $projectType->getName());
}
}
$leadSheet->setCellValue('D' . $leadRow, $project->getName());
$leadSheet->getCell('D' . $leadRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
$leadSheet->setCellValue('E' . $leadRow, $projectClassification ? implode(', ', $projectClassification) : '-');
$leadSheet->setCellValue('F' . $leadRow, $project->getType() == 'LEAD' ? $project->getLead() . ' - ' . $project->getLeadStatus()->getName() : ($project->getStatus() ? $project->getStatus() : '-'));
$leadSheet->setCellValue('G' . $leadRow, $picName);
$leadSheet->setCellValue('H' . $leadRow, $project->getProbabilityText());
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project->getType() == 'LEAD' ? $project->getPlannedRevenueUsd() * $probabilityPercent : $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
$estAgencyRevenue = $project->getType() == 'LEAD' ? $project->getEstimatedProfitUsd() * $probabilityPercent : $project->getTotalRevenueUSD();
if ($project->getType() == 'CONFIRMED') {
$totalEstProjectBillings['confirmed'] += $estProjectBillings;
$totalEstAgencyRevenue['confirmed'] += $estAgencyRevenue;
} elseif ($project->getType() == 'LEAD') {
$totalEstProjectBillings['lead'] += $estProjectBillings;
$totalEstAgencyRevenue['lead'] += $estAgencyRevenue;
}
$totalEstProjectBillings['total'] += $estProjectBillings;
$totalEstAgencyRevenue['total'] += $estAgencyRevenue;
$leadSheet->setCellValue('I' . $leadRow, $estProjectBillings);
$leadSheet->setCellValue('K' . $leadRow, $estAgencyRevenue);
$leadRow++;
}
$leadSheet->setCellValue('I6', $totalEstProjectBillings['total']);
$leadSheet->setCellValue('I7', $totalEstProjectBillings['confirmed']);
$leadSheet->setCellValue('I8', $totalEstProjectBillings['lead']);
$leadSheet->setCellValue('K6', $totalEstAgencyRevenue['total']);
$leadSheet->setCellValue('K7', $totalEstAgencyRevenue['confirmed']);
$leadSheet->setCellValue('K8', $totalEstAgencyRevenue['lead']);
// define breakdown
$columnx = [];
for ($i = 65; $i <= 90; $i++) {
$columnx[] = chr($i);
}
for ($i = 65; $i <= 90; $i++) {
for ($j = 65; $j <= 90; $j++) {
$columnx[] = chr($i) . chr($j);
}
}
// define column months
$monthColumnx = [];
foreach ($projectsList as $project) {
$project = $project[0];
if ($project->getLead() == '8') {
$revenues = $this->monthlyRevenues($project, $isCashflow);
$newRevenues = [];
foreach ($revenues as $oldKey => $value) {
list($month, $year) = explode('-', $oldKey);
$parsedMonth = date_parse($month);
$newKey = sprintf('%02d-%s', $parsedMonth['month'], $year);
$newRevenues[$newKey] = $value;
}
foreach ($newRevenues as $newRevenueKey => $value) {
$month = $newRevenueKey;
if (!in_array($month, $monthColumnx)) {
$monthColumnx[] = $month;
}
}
} else {
$revenuePlannings = $project->getRevenuePlannings();
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
if (!in_array($month, $monthColumnx)) {
$monthColumnx[] = $month;
}
}
}
}
// sort
usort($monthColumnx, function ($a, $b) {
$dateA = \DateTime::createFromFormat('d-m-Y', '01-' . $a);
$dateB = \DateTime::createFromFormat('d-m-Y', '01-' . $b);
if ($dateA == $dateB) {
return 0;
}
return ($dateA < $dateB) ? -1 : 1;
});
$sortedMonthColumnsx = array_map(function ($date) {
$dateTime = \DateTime::createFromFormat('d-m-Y', '01-' . $date);
return $dateTime->format('M-Y');
}, $monthColumnx);
$lastColx = $leadSheet->getHighestColumn(); // 'L'
$key = array_search($lastColx, $columnx);
$cellColumnx = []; // breakdown month column based on cell column
$i = $key + 1;
foreach ($sortedMonthColumnsx as $monthColumnx) {
$cellColumnx[$i] = $monthColumnx;
$leadSheet->setCellValue($columnx[$i] . "5", $monthColumnx);
$leadSheet->setCellValue($columnx[$i] . "9", $monthColumnx);
$i++;
}
$totalColumnBreakdownx = [];
foreach ($cellColumnx as $cell) {
$totalColumnBreakdownx[$cell]['total'] = 0;
$totalColumnBreakdownx[$cell]['confirmed'] = 0;
$totalColumnBreakdownx[$cell]['lead'] = 0;
}
// fill cell
$monthRowx = 10;
foreach ($projectsList as $project) {
$project = $project[0];
foreach ($cellColumnx as $cellValue => $value) {
$leadSheet->setCellValue($columnx[$cellValue] . $monthRowx, '-');
}
if ($project->getLead() == '8') {
$revenues = $this->monthlyRevenues($project, $isCashflow);
foreach ($revenues as $key => $value) {
$month = $key;
$cell = array_search($month, $cellColumnx);
$leadSheet->setCellValue($columnx[$cell] . $monthRowx, $value['totalUsd']);
if ($project->getType() == 'CONFIRMED') $totalColumnBreakdownx[$month]['confirmed'] += $value['totalUsd'];
$totalColumnBreakdownx[$month]['total'] += $value['totalUsd'];
}
} else {
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$revenuePlannings = $project->getRevenuePlannings()->toArray();
if (count($revenuePlannings) > 0) {
foreach ($revenuePlannings as $revenuePlanning) {
$month = $revenuePlanning->getMonth() . '-' . $revenuePlanning->getYear();
$month = \DateTime::createFromFormat('d-m-Y', '01-' . $month)->format('M-Y');
$cell = array_search($month, $cellColumnx);
$revenueAmountUsd = $project->getType() == 'LEAD' ? $revenuePlanning->getAmountUsd() * $probabilityPercent : $revenuePlanning->getAmountUsd();
$leadSheet->setCellValue($columnx[$cell] . $monthRowx, $revenueAmountUsd);
if ($project->getType() == 'LEAD') $totalColumnBreakdownx[$month]['lead'] += $revenueAmountUsd;
// if($project['type'] == 'CONFIRMED') $totalColumnBreakdown[$month]['confirmed'] += $revenueAmountUsd;
$totalColumnBreakdownx[$month]['total'] += $revenueAmountUsd;
}
}
}
$monthRowx++;
}
// fill total cell
foreach ($cellColumnx as $key => $cellCol) {
for ($i = 6; $i <= 8; $i++) {
$type = $i == 6 ? 'total' : ($i == 7 ? 'confirmed' : 'lead');
$leadSheet->setCellValue($columnx[$key] . $i, $totalColumnBreakdownx[$cellCol][$type]);
}
}
// FYTD = 1st nov22 - 31st oct23
// Calculate FYTD start and end dates (Nov 1st - Oct 31st)
$currentYear = date('Y');
$fytdStartDate = new \DateTime($currentYear - 1 . '-11-01');
$fytdEndDate = new \DateTime($currentYear . '-10-31');
// Calculate Total Est. Project Billings FYTD and Est. Agency Revenue FYTD
$totalEstProjectBillingsFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$totalEstAgencyRevenueFYTD = [
'total' => 0,
'confirmed' => 0,
'lead' => 0
];
$leadRow = 10;
foreach ($projectsList as $project) {
$project = $project[0];
$totalMonths = 0;
$numMonthsFYTD = 0;
if (!empty($project->getStartDate()) && !empty($project->getEndDate())) {
$dateInterval = $project->getEndDate()->diff($project->getStartDate());
$yearsInMonths = $dateInterval->y * 12;
$months = $dateInterval->m;
$days = $dateInterval->d;
if ($days > 0) {
$months++;
}
$totalMonths = $yearsInMonths + $months;
if ($dateInterval->y === 0 && $dateInterval->m === 0 && $dateInterval->d === 0) {
$totalMonths = 1;
}
$numMonthsFYTD = $this->calculateIncludedMonths($project->getStartDate(), $project->getEndDate());
} else {
$totalMonths = 1;
$numMonthsFYTD = 1;
}
$probabilityPercent = $project->getLeadStatus()->getProbability() / 100;
$estProjectBillings = $project->getType() == 'LEAD' ? $project->getPlannedRevenueUsd() * $probabilityPercent : $project->getTotalRevenueUSD() + $project->getTotalVendorCostUsd();
$estAgencyRevenue = $project->getType() == 'LEAD' ? $project->getEstimatedProfitUsd() * $probabilityPercent : $project->getTotalRevenueUSD();
$formulaBillings = $totalMonths == $numMonthsFYTD ? $estProjectBillings : ($estProjectBillings / $totalMonths) + ($estProjectBillings / $totalMonths * $numMonthsFYTD);
$formulaRevenue = $totalMonths == $numMonthsFYTD ? $estAgencyRevenue : ($estAgencyRevenue / $totalMonths) + ($estAgencyRevenue / $totalMonths * $numMonthsFYTD);
if ($project->getType() == 'CONFIRMED') {
$totalEstProjectBillingsFYTD['confirmed'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['confirmed'] += $formulaRevenue;
} elseif ($project->getType() == 'LEAD') {
$totalEstProjectBillingsFYTD['lead'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['lead'] += $formulaRevenue;
}
$totalEstProjectBillingsFYTD['total'] += $formulaBillings;
$totalEstAgencyRevenueFYTD['total'] += $formulaRevenue;
$leadSheet->setCellValue('J' . $leadRow, $formulaBillings);
$leadSheet->setCellValue('L' . $leadRow, $formulaRevenue);
$leadRow++;
}
$leadSheet->setCellValue('J6', $totalEstProjectBillingsFYTD['total']);
$leadSheet->setCellValue('J7', $totalEstProjectBillingsFYTD['confirmed']);
$leadSheet->setCellValue('J8', $totalEstProjectBillingsFYTD['lead']);
$leadSheet->setCellValue('L6', $totalEstAgencyRevenueFYTD['total']);
$leadSheet->setCellValue('L7', $totalEstAgencyRevenueFYTD['confirmed']);
$leadSheet->setCellValue('L8', $totalEstAgencyRevenueFYTD['lead']);
$leadSheet->getStyle("A5:" . $leadSheet->getHighestColumn() . "5")->getFont()->setBold(true);
$leadSheet->getStyle("A5:" . $leadSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$leadSheet->getStyle("A5:" . $leadSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$leadSheet->getStyle("A6:" . $leadSheet->getHighestColumn() . "8")->getFont()->setBold(true);
$leadSheet->getStyle("A9:" . $leadSheet->getHighestColumn() . "9")->getFont()->setBold(true);
$leadSheet->getStyle("A9:" . $leadSheet->getHighestColumn() . "9")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$leadSheet->getStyle("A9:" . $leadSheet->getHighestColumn() . "9")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$leadSheet->setAutoFilter('A9:' . $leadSheet->getHighestColumn() . $leadSheet->getHighestRow());
$leadSheet->getStyle("D1:D" . $leadSheet->getHighestRow())->getFont()->setUnderline(true);
// $leadSheet->getStyle('I6:'.$leadSheet->getHighestColumn().$leadSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$leadSheet->getStyle('I6:' . $leadSheet->getHighestColumn() . $leadSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
public function exportProjectVendorInvoices($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $_target)
{
$startDateRange = date("d-M-Y", strtotime($startDate));
$endDateRange = date("d-M-Y", strtotime($endDate));
$spreadsheet = new Spreadsheet();
$vendorInvoiceSheet = $spreadsheet->getActiveSheet()->setTitle('Vendor Invoices');
$vendorInvoiceSheet->setCellValue('A1', 'Today\'s Date');
$vendorInvoiceSheet->setCellValue('A2', 'From');
$vendorInvoiceSheet->setCellValue('A3', 'To');
$vendorInvoiceSheet->setCellValue('B1', date('d-M-Y'));
$vendorInvoiceSheet->setCellValue('B2', $startDateRange);
$vendorInvoiceSheet->setCellValue('B3', $endDateRange);
$vendorInvoiceSheet->setCellValue("A5", "Vendor Name");
$vendorInvoiceSheet->setCellValue("B5", "Invoice Date");
$vendorInvoiceSheet->setCellValue("C5", "Invoice Status");
$vendorInvoiceSheet->setCellValue("D5", "Client");
$vendorInvoiceSheet->setCellValue("E5", "Project");
$vendorInvoiceSheet->setCellValue("F5", "Amount USD");
$vendorInvoiceSheet->setCellValue("G5", "Allocated USD");
$vendorInvoiceSheet->setCellValue("H5", "Amount Left USD");
$vendorInvoiceSheet->setCellValue("I5", "Due Date");
$vendorInvoiceSheet->setCellValue("J5", "Client INV");
$vendorInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
$vendorInvoiceSheet->getStyle("A5:" . $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
$vendorInvoiceSheet->getStyle("A5:" . $vendorInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$vendorInvoiceSheet->getStyle("A5:" . $vendorInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$filename = "Project_Vendor_Invoices_Report";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
$vendorRow = $vendorInvoiceSheet->getHighestRow() + 1;
foreach ($projectsList as $project) {
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings()->toArray();
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vqp) {
$vqpvis = $vqp->getVendorQuotationPlanningVendorInvoices()->toArray();
if ($vqpvis) {
foreach ($vqpvis as $vqpvi) {
$vqp = $vqpvi->getVendorQuotationPlanning();
$vendorInvoice = $vqpvi->getVendorInvoice();
$vendorInvoiceSheet->setCellValue("A" . $vendorRow, $vqp->getVendor()->getName());
$vendorInvoiceSheet->setCellValue("B" . $vendorRow, $vendorInvoice->getInvoiceDate()->format("Y-m-d"));
$vendorInvoiceSheet->setCellValue("C" . $vendorRow, $vendorInvoice->getCustomXeroStatus());
$vendorInvoiceSheet->setCellValue("D" . $vendorRow, $vqp->getProject()->getClient()->getName());
$vendorInvoiceSheet->setCellValue("E" . $vendorRow, $vqp->getProject()->getName());
$vendorInvoiceSheet->getCell('E' . $vendorRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$vendorInvoiceSheet->setCellValue("F" . $vendorRow, $vendorInvoice->getSubTotalUsd());
$vendorInvoiceSheet->setCellValue("G" . $vendorRow, $vqpvi->getAmountUsd());
$vendorInvoiceSheet->setCellValue("H" . $vendorRow, $vendorInvoice->getAmountLeftUsd());
$vendorInvoiceSheet->setCellValue("I" . $vendorRow, $vendorInvoice->getDueDate()->format("Y-m-d"));
$vendorInvoiceSheet->setCellValue("J" . $vendorRow, $vqpvi->getInvoice() ? $vqpvi->getInvoice()->getInvoiceNo() : '-');
$vendorRow++;
}
}
}
}
}
$vendorInvoiceSheet->setAutoFilter('A5:' . $vendorInvoiceSheet->getHighestColumn() . $vendorInvoiceSheet->getHighestRow());
$vendorInvoiceSheet->getStyle("E6:E" . $vendorInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
// $vendorInvoiceSheet->getStyle('F6:'.'H'.$vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$vendorInvoiceSheet->getStyle('F6:' . 'H' . $vendorInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$spreadsheet->setActiveSheetIndex(0);
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
public function exportProjectClientInvoices($isAdmin, $keyword, $startDate, $endDate, $client, $status, $type, $retainer, $department, $project, $assignedUser, $pic, $showDeleted, $baseurl, $_target)
{
$startDateRange = date("d-M-Y", strtotime($startDate));
$endDateRange = date("d-M-Y", strtotime($endDate));
$spreadsheet = new Spreadsheet();
$clientInvoiceSheet = $spreadsheet->getActiveSheet()->setTitle('Client Invoices');
$clientInvoiceSheet->setCellValue('A1', 'Today\'s Date');
$clientInvoiceSheet->setCellValue('A2', 'From');
$clientInvoiceSheet->setCellValue('A3', 'To');
$clientInvoiceSheet->setCellValue('B1', date('d-M-Y'));
$clientInvoiceSheet->setCellValue('B2', $startDateRange);
$clientInvoiceSheet->setCellValue('B3', $endDateRange);
$clientInvoiceSheet->setCellValue("A5", "Client Name");
$clientInvoiceSheet->setCellValue("B5", "Project Name");
$clientInvoiceSheet->setCellValue("C5", "Project Status");
$clientInvoiceSheet->setCellValue("D5", "PIC Name");
$clientInvoiceSheet->setCellValue("E5", "Client PIC");
$clientInvoiceSheet->setCellValue("F5", "INV Number");
$clientInvoiceSheet->setCellValue("G5", "INV Status");
$clientInvoiceSheet->setCellValue("H5", "INV Due Date");
$clientInvoiceSheet->setCellValue("I5", "INV Amount");
$clientInvoiceSheet->setCellValue("J5", "INV Currency");
$clientInvoiceSheet->setCellValue("K5", "INV Amount USD");
$filename = "Project_Client_Invoices_Report";
$filename .= $startDate ? "_" . urlencode($startDate) : "";
$filename .= $endDate ? "-" . urlencode($endDate) : "";
$filename .= $startDate ? '.xlsx' : "_" . date('Y-m-d') . '.xlsx';
$projectsList = $this->projectRepository->findByPage(0, 9999, $keyword, "DESC", 'type', $startDate, $endDate, $type, $client, $status, $project, $department, $retainer, $assignedUser, $showDeleted);
$column = [];
for ($i = 65; $i <= 90; $i++) {
$column[] = chr($i);
}
for ($i = 65; $i <= 90; $i++) {
for ($j = 65; $j <= 90; $j++) {
$column[] = chr($i) . chr($j);
}
}
$monthColumn = [];
$row = $clientInvoiceSheet->getHighestRow() + 1;
foreach ($projectsList as $project) {
$projectSalesOrders = $project[0]->getProjectSalesOrders()->toArray();
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
if ($soInvoices) {
foreach ($soInvoices as $soInvoice) {
$proj = $soInvoice->getProject();
$projectName = $proj->getName();
$clientName = $proj->getClient()->getName();
$projectPic = $proj->getPersonInCharge() ? $proj->getPersonInCharge()->getPersonalInfo()->getFullName() : '-';
$clientPic = $proj->getClientPersonInCharge() ? $proj->getClientPersonInCharge()->getName() : '-';
$invoice = $soInvoice->getInvoice();
$clientInvoiceSheet->setCellValue("A" . $row, $clientName);
$clientInvoiceSheet->setCellValue("B" . $row, $projectName);
$clientInvoiceSheet->getCell('B' . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $proj->getId());
$clientInvoiceSheet->setCellValue('C' . $row, $proj->getType() == 'LEAD' ? $project['lead'] . ' - ' . $proj->getLeadStatus()->getName() : $proj->getStatus());
$clientInvoiceSheet->setCellValue("D" . $row, $projectPic ?: '-');
$clientInvoiceSheet->setCellValue("E" . $row, $clientPic);
$clientInvoiceSheet->setCellValue("F" . $row, $invoice->getInvoiceNo());
$clientInvoiceSheet->setCellValue("G" . $row, $invoice->getCustomXeroStatus());
$month = $invoice->getDueDate()->format("m-Y");
if (!in_array($month, $monthColumn)) {
$monthColumn[] = $month;
}
$clientInvoiceSheet->setCellValue("H" . $row, $invoice->getDueDate()->format("Y-m-d"));
$clientInvoiceSheet->setCellValue("I" . $row, $soInvoice->getAmount());
$clientInvoiceSheet->setCellValue("J" . $row, $invoice->getCurrency()->getIso());
$clientInvoiceSheet->setCellValue("K" . $row, $soInvoice->getAmountUsd());
$row++;
}
}
}
}
}
usort($monthColumn, function ($a, $b) {
$dateA = \DateTime::createFromFormat('d-m-Y', '01-' . $a);
$dateB = \DateTime::createFromFormat('d-m-Y', '01-' . $b);
if ($dateA == $dateB) {
return 0;
}
return ($dateA < $dateB) ? -1 : 1;
});
$sortedMonthColumns = array_map(function ($date) {
return \DateTime::createFromFormat('d-m-Y', '01-' . $date)->format('M-Y');
}, $monthColumn);
$lastCol = $clientInvoiceSheet->getHighestColumn(); // 'L'
$key = array_search($lastCol, $column);
$cellColumn = []; // breakdown month column based on cell column
$i = $key + 1;
foreach ($sortedMonthColumns as $monthColumn) {
$cellColumn[$i] = $monthColumn;
$clientInvoiceSheet->setCellValue($column[$i] . "5", $monthColumn);
$i++;
}
$monthRow = 6;
foreach ($projectsList as $project) {
$projectSalesOrders = $project[0]->getProjectSalesOrders()->toArray();
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices()->toArray();
if ($soInvoices) {
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
$month = $invoice->getDueDate()->format("M-Y");
$cell = array_search($month, $cellColumn);
$clientInvoiceSheet->setCellValue($column[$cell] . $monthRow, $soInvoice->getAmountUsd());
$monthRow++;
}
}
}
}
}
$clientInvoiceSheet->getDefaultColumnDimension()->setWidth(25);
$highestColumn = $clientInvoiceSheet->getHighestColumn();
$intHighestCol = array_search($highestColumn, $column);
for ($col = 11; $col <= $intHighestCol; $col++) {
$clientInvoiceSheet->getColumnDimension($column[$col])->setWidth(15);
}
$clientInvoiceSheet->setAutoFilter('A5:' . $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow());
$clientInvoiceSheet->getStyle("A5:" . $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->setBold(true);
$clientInvoiceSheet->getStyle("A5:" . $clientInvoiceSheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$clientInvoiceSheet->getStyle("A5:" . $clientInvoiceSheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$clientInvoiceSheet->getStyle("B6:B" . $clientInvoiceSheet->getHighestRow())->getFont()->setUnderline(true);
// $clientInvoiceSheet->getStyle('I6:'.'I'.$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$clientInvoiceSheet->getStyle('I6:' . 'I' . $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// $clientInvoiceSheet->getStyle('K6:'.$clientInvoiceSheet->getHighestColumn().$clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2);
$clientInvoiceSheet->getStyle('K6:' . $clientInvoiceSheet->getHighestColumn() . $clientInvoiceSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
$spreadsheet->setActiveSheetIndex(0);
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
/*
public function exportProjectRevenueCost($isAdmin, $financialYear, $baseurl, $_target)
{
$start = '';
$end = '';
if ($financialYear) {
$start = date('Y-m-d', strtotime('first day of November ' . ($financialYear - 1)));
$end = date('Y-m-d', strtotime('last day of October ' . $financialYear));
}
$fyStart = $financialYear - 1;
$fyEnd = $financialYear + 1;
$overallTotals = [
'G' => 0, // Revenue FY Start
'H' => 0, // Revenue FY Current
'I' => 0, // Revenue FY End
'P' => 0, // Invoice Total w/o Tax
'Y' => 0, // Vendor Total w/o Tax
'AA' => 0, // Vendor Cost FY Start
'AB' => 0, // Vendor Cost FY Current
'AC' => 0, // Vendor Cost FY End
'AD' => 0, // Gross Profit Total
'AF' => 0, // Gross Profit FY Current
];
$overallTotalRevenue = 0;
$overallTotalCost = 0;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
// Define Header Data
$sheet->setCellValue('A1', 'Client');
$sheet->setCellValue('B1', 'Project ID');
$sheet->setCellValue('C1', 'Project Name');
$sheet->setCellValue('D1', 'Project Status');
$sheet->setCellValue('E1', 'Start Date');
$sheet->setCellValue('F1', 'End Date');
$sheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
$sheet->setCellValue('H1', 'Revenue FY ' . $financialYear);
$sheet->setCellValue('I1', 'Revenue FY ' . $fyEnd);
$sheet->setCellValue('J1', 'MT INV No.');
$sheet->setCellValue('K1', 'INV Date');
$sheet->setCellValue('L1', 'INV Due Date');
$sheet->setCellValue('M1', 'INV Currency');
$sheet->setCellValue('N1', 'INV Amount (w/o Taxes)');
$sheet->setCellValue('O1', 'SGD FX Rate');
$sheet->setCellValue('P1', 'INV Amount (w/o Taxes in SGD)');
$sheet->setCellValue('Q1', '');
$sheet->setCellValue('R1', 'Vendor');
$sheet->setCellValue('S1', 'Vendor INV No.');
$sheet->setCellValue('T1', 'Vendor INV Date');
$sheet->setCellValue('U1', 'Vendor INV Due Date');
$sheet->setCellValue('V1', 'Vendor INV Currency');
$sheet->setCellValue('W1', 'Vendor INV Amount Allocated (w/o Taxes)');
$sheet->setCellValue('X1', 'SGD FX Rate');
$sheet->setCellValue('Y1', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
$sheet->setCellValue('Z1', 'Client INV No');
$sheet->setCellValue('AA1', 'Vendor Cost ' . $fyStart);
$sheet->setCellValue('AB1', 'Vendor Cost ' . $financialYear);
$sheet->setCellValue('AC1', 'Vendor Cost ' . $fyEnd);
$sheet->setCellValue('AD1', 'Gross Profit Total');
$sheet->setCellValue('AE1', 'Gross Profit Margin Total');
$sheet->setCellValue('AF1', 'Gross Profit FY ' . $financialYear);
$sheet->setCellValue('AG1', 'Gross Profit Margin FY ' . $financialYear);
// $sheet->setCellValue('AG1', 'Total Revenue');
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getColumnDimension('Q')->setWidth(3);
$sheet->getColumnDimension('E')->setWidth(12);
$sheet->getColumnDimension('F')->setWidth(12);
$sheet->getColumnDimension('G')->setWidth(17);
$sheet->getColumnDimension('H')->setWidth(17);
$sheet->getColumnDimension('I')->setWidth(17);
$sheet->getColumnDimension('J')->setWidth(16);
$sheet->getColumnDimension('K')->setWidth(12);
$sheet->getColumnDimension('L')->setWidth(12);
$sheet->getColumnDimension('M')->setWidth(13);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A2:" . $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
$sheet->freezePane('A2');
$filename = "Financial Year - Project revenue vs. Cost FY " . $financialYear;
$filename .= date('Y-m-d') . '.xlsx';
// $type = "LEAD;CONFIRMED";
$type = "CONFIRMED";
$status = "On-Going;Finished";
$projectsList = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $start, $end, $type, 0, $status);
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$sheet->setCellValue("A" . $row, $project['clientName']);
$sheet->setCellValue("B" . $row, $project['generatedId']);
$sheet->getCell("B" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue("C" . $row, $project['name']);
$sheet->getCell("C" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->setCellValue("D" . $row, $project['status']);
$sheet->setCellValue("E" . $row, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
$sheet->setCellValue("F" . $row, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
$sheet->setCellValue("G" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
$sheet->setCellValue("H" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
$sheet->setCellValue("I" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
$sheet->setCellValue("AA" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
$sheet->setCellValue("AB" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$sheet->setCellValue("AC" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
$sheet->setCellValue("AD" . $row, $project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd());
$grossProfitMargin = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
$overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
$grossProfitMargin = ($project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd()) / $project[0]->getInvRevenueByFinancialYearSgd();
}
$sheet->setCellValue("AE" . $row, $grossProfitMargin);
$sheet->setCellValue("AF" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$grossProfitMarginFinancialYear = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
$grossProfitMarginFinancialYear = ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear)) / $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
}
$sheet->setCellValue("AG" . $row, $grossProfitMarginFinancialYear);
// $sheet->setCellValue("AG".$row, $project[0]->getTotalRevenueUsd() ?: '-');
// looping project invoice
$invRow = $row;
$projectSalesOrders = $project[0]->getProjectSalesOrders();
$InvTotalwoTax = 0;
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$sheet->setCellValue("J" . $invRow, $invoice->getInvoiceNo());
$sheet->setCellValue("K" . $invRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("L" . $invRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("M" . $invRow, $invoice->getCurrency()->getIso());
// $sheet->setCellValue("N".$invRow, $invoice->getSubTotal());
$InvTotalwoTax += $invoice->getSubTotalSgd($project[0]);
$sheet->setCellValue("N" . $invRow, $invoice->getSubTotal());
$sheet->setCellValue("O" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $invoice->getSubTotal() : $invoice->getSubTotalSgd($project[0]);
$sheet->setCellValue("P" . $invRow, $amountSGD);
$invRow++;
}
}
} else {
$sheet->setCellValue("J" . $invRow, "-");
$sheet->setCellValue("K" . $invRow, "-");
$sheet->setCellValue("L" . $invRow, "-");
$sheet->setCellValue("M" . $invRow, "-");
}
//looping vendor invoice
$vendorInvRow = $row;
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
$vendorTotalWoTax = 0;
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
$vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
$vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
foreach ($vqpInvoices as $vqpInvoice) {
$invoice = $vqpInvoice->getVendorInvoice();
if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
$sheet->setCellValue("R" . $vendorInvRow, $vendorName);
$sheet->setCellValue("S" . $vendorInvRow, $invoice->getInvoiceNo());
$sheet->setCellValue("T" . $vendorInvRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("U" . $vendorInvRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("V" . $vendorInvRow, $invoice->getCurrency()->getIso());
// $sheet->setCellValue("W".$vendorInvRow, $vqpInvoice->getAmount());
$vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("W" . $vendorInvRow, $vqpInvoice->getAmount());
$sheet->setCellValue("X" . $vendorInvRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("Y" . $vendorInvRow, $vendorAmountSGD);
// $clientInvoices = [];
// if(!empty($invoice->getInvoiceVendorInvoices()->toArray())){
// foreach($invoice->getInvoiceVendorInvoices()->toArray() as $invVendorI){
// $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
// array_push($clientInvoices, $clientInv);
// }
// }
$sheet->setCellValue('Z'. $row, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
$vendorInvRow++;
}
}
} else {
$sheet->setCellValue("R" . $vendorInvRow, "-");
$sheet->setCellValue("S" . $vendorInvRow, "-");
$sheet->setCellValue("T" . $vendorInvRow, "-");
$sheet->setCellValue("U" . $vendorInvRow, "-");
$sheet->setCellValue("V" . $vendorInvRow, "-");
}
$totalRow = $invRow > $row || $vendorInvRow > $row ? max($invRow, $vendorInvRow) : $row + 1;
// define total Row
$sheet->setCellValue("A" . $totalRow, "Total");
$sheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
$sheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
$sheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
$sheet->setCellValue("P" . $totalRow, $InvTotalwoTax);
$sheet->setCellValue("Y" . $totalRow, $vendorTotalWoTax);
$sheet->setCellValue("AA" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
$sheet->setCellValue("AB" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$sheet->setCellValue("AC" . $totalRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
$sheet->setCellValue("AD" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd());
$sheet->setCellValue("AE" . $totalRow, $grossProfitMargin);
$sheet->setCellValue("AF" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$sheet->setCellValue("AG" . $totalRow, $grossProfitMarginFinancialYear);
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getRowDimension($totalRow)->setRowHeight(20);
$overallTotals['G'] += $project[0]->getInvRevenueByFinancialYearSgd($fyStart);
$overallTotals['H'] += $project[0]->getInvRevenueByFinancialYearSgd($financialYear);
$overallTotals['I'] += $project[0]->getInvRevenueByFinancialYearSgd($fyEnd);
$overallTotals['P'] += $InvTotalwoTax;
$overallTotals['Y'] += $vendorTotalWoTax;
$overallTotals['AA'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyStart);
$overallTotals['AB'] += $project[0]->getInvVendorCostByFinancialYearSgd($financialYear);
$overallTotals['AC'] += $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd);
$overallTotals['AD'] += ($project[0]->getInvRevenueByFinancialYearSgd() - $project[0]->getInvVendorCostByFinancialYearSgd());
$overallTotals['AF'] += ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) - $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$row = $totalRow;
$row++;
}
//overall total
$row = $row+1;
$sheet->setCellValue("A". $row, "Overall Total");
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getRowDimension($row)->setRowHeight(20);
foreach ($overallTotals as $column => $value) {
$sheet->setCellValue($column . $row, $value);
}
// Calculate and set overall profit margins
$overallGrossProfitMargin = $overallTotalRevenue > 0 ?
($overallTotalRevenue - $overallTotalCost) / $overallTotalRevenue : 0;
$overallGrossProfitMarginFY = $overallTotals['H'] > 0 ?
($overallTotals['H'] - $overallTotals['AB']) / $overallTotals['H'] : 0;
$sheet->setCellValue("AE" . $row, $overallGrossProfitMargin);
$sheet->setCellValue("AG" . $row, $overallGrossProfitMarginFY);
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
$sheet->getStyle("Q1:Q" . $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->setAutoFilter('A1:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
$sheet->getStyle('G2:I' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$sheet->getStyle('N2:N' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('P2:P' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('W2:W' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('Y2:Y' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AA2:AD' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
// $sheet->getStyle('X2:X' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;(#,##0.00)');
$sheet->getStyle('AF2:AF' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle("AE")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$sheet->getStyle("AG")->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$sheet->getStyle("B2:B" . $sheet->getHighestRow())->getFont()->setUnderline(true);
$sheet->getStyle("C2:C" . $sheet->getHighestRow())->getFont()->setUnderline(true);
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
*/
public function exportProjectRevenueCost($isAdmin, $financialYear, $baseurl, $_target)
{
$start = '';
$end = '';
if ($financialYear) {
$start = date('Y-m-d', strtotime('first day of November ' . ($financialYear - 1)));
$end = date('Y-m-d', strtotime('last day of October ' . $financialYear));
}
$fyStart = $financialYear - 1;
$fyEnd = $financialYear + 1;
$overallTotals = [];
$overallTotalRevenue = 0;
$overallTotalCost = 0;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
// Define Header Data
$sheet->setCellValue('A1', 'Client');
$sheet->setCellValue('B1', 'Project ID');
$sheet->setCellValue('C1', 'Project Name');
$sheet->setCellValue('D1', 'Project Status');
$sheet->setCellValue('E1', 'Start Date');
$sheet->setCellValue('F1', 'End Date');
$sheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
$sheet->setCellValue('H1', 'Revenue FY ' . $fyStart . ' Amount Allocated');
$sheet->setCellValue('I1', 'Revenue FY ' . $financialYear);
$sheet->setCellValue('J1', 'Revenue FY ' . $financialYear . ' Amount Allocated');
$sheet->setCellValue('K1', 'Revenue FY ' . $fyEnd);
$sheet->setCellValue('L1', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
$sheet->setCellValue('M1', 'MT INV No.');
$sheet->setCellValue('N1', 'INV Date');
$sheet->setCellValue('O1', 'INV Due Date');
$sheet->setCellValue('P1', 'INV Currency');
$sheet->setCellValue('Q1', 'INV Amount (w/o Taxes)');
$sheet->setCellValue('R1', 'INV Amount Allocated (w/o Taxes)');
$sheet->setCellValue('S1', 'SGD FX Rate');
$sheet->setCellValue('T1', 'INV Amount (w/o Taxes in SGD)');
$sheet->setCellValue('U1', 'INV Amount Allocated (w/o Taxes in SGD)');
$sheet->setCellValue('V1', '');
$sheet->setCellValue('W1', 'Vendor');
$sheet->setCellValue('X1', 'Vendor INV No.');
$sheet->setCellValue('Y1', 'Vendor INV Date');
$sheet->setCellValue('Z1', 'Vendor INV Due Date');
$sheet->setCellValue('AA1', 'Vendor INV Currency');
$sheet->setCellValue('AB1', 'Vendor INV Amount (w/o Taxes)');
$sheet->setCellValue('AC1', 'Vendor INV Amount Allocated (w/o Taxes)');
$sheet->setCellValue('AD1', 'SGD FX Rate');
$sheet->setCellValue('AE1', 'Vendor INV Amount (w/o Taxes in SGD)');
$sheet->setCellValue('AF1', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
$sheet->setCellValue('AG1', 'Client INV No');
$sheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
$sheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
$sheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
$sheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
$sheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
$sheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
$sheet->setCellValue('AN1', 'Gross Profit Total');
$sheet->setCellValue('AO1', 'Gross Profit Total Amount Allocated');
$sheet->setCellValue('AP1', 'Gross Profit Margin Total');
$sheet->setCellValue('AQ1', 'Gross Profit Margin Total Amount Allocated');
$sheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
$sheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
$sheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
$sheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AG1', 'Total Revenue');
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getColumnDimension('V')->setWidth(3);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->setBold(true);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A1:" . $sheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$sheet->getStyle("A2:" . $sheet->getHighestColumn() . "2")->getFont()->setBold(false);
$sheet->freezePane('A2');
$filename = "Financial Year - Project revenue vs. Cost FY " . $financialYear;
$filename .= date('Y-m-d') . '.xlsx';
// $type = "LEAD;CONFIRMED";
$type = "CONFIRMED";
$status = "On-Going;Finished";
$projectsList = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $start, $end, $type, 0, $status);
$row = $sheet->getHighestRow();
foreach ($projectsList as $project) {
$sheet->setCellValue("A" . $row, $project['clientName']);
$sheet->setCellValue("B" . $row, $project['generatedId']);
$sheet->getCell("B" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->getStyle('B' . $row)->getFont()->setUnderline(true);
$sheet->setCellValue("C" . $row, $project['name']);
$sheet->getCell("C" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->getStyle('C' . $row)->getFont()->setUnderline(true);
$sheet->setCellValue("D" . $row, $project['status']);
$sheet->setCellValue("E" . $row, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
$sheet->setCellValue("F" . $row, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
$sheet->setCellValue("G" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
$sheet->setCellValue("H" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
$sheet->setCellValue("I" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
$sheet->setCellValue("J" . $row, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
$sheet->setCellValue("K" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
$sheet->setCellValue("L" . $row, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
$sheet->setCellValue("AH" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
$sheet->setCellValue("AI" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart, true));
$sheet->setCellValue("AJ" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$sheet->setCellValue("AK" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear, true));
$sheet->setCellValue("AL" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
$sheet->setCellValue("AM" . $row, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd, true));
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
$overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
}
// looping project invoice
$invRow = $row;
$projectSalesOrders = $project[0]->getProjectSalesOrders();
$InvTotalwoTax = 0;
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$sheet->setCellValue("M" . $invRow, $invoice->getInvoiceNo());
$sheet->setCellValue("N" . $invRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("O" . $invRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("P" . $invRow, $invoice->getCurrency()->getIso());
$InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("Q" . $invRow, $invoice->getSubTotal());
$sheet->setCellValue("R" . $invRow, $soInvoice->getAmount());
$sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("T" . $invRow, $invoice->getSubTotalSgd($project[0]));
$sheet->setCellValue("U" . $invRow, $amountSGD);
$invRow++;
}
}
} else {
$sheet->setCellValue("M" . $invRow, "-");
$sheet->setCellValue("N" . $invRow, "-");
$sheet->setCellValue("O" . $invRow, "-");
$sheet->setCellValue("P" . $invRow, "-");
$sheet->setCellValue("Q" . $invRow, "-");
$sheet->setCellValue("R" . $invRow, "-");
$sheet->setCellValue("S" . $invRow, "-");
$sheet->setCellValue("T" . $invRow, "-");
$sheet->setCellValue("U" . $invRow, "-");
}
//looping vendor invoice
$vendorInvRow = $row;
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
$vendorTotalWoTax = 0;
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
$vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
$vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
foreach ($vqpInvoices as $vqpInvoice) {
$invoice = $vqpInvoice->getVendorInvoice();
// if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
$sheet->setCellValue("W" . $vendorInvRow, $vendorName);
$sheet->setCellValue("X" . $vendorInvRow, $invoice->getInvoiceNo());
$sheet->setCellValue("Y" . $vendorInvRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("Z" . $vendorInvRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("AA" . $vendorInvRow, $invoice->getCurrency()->getIso());
$vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("AB" . $vendorInvRow, $invoice->getSubtotal());
$sheet->setCellValue("AC" . $vendorInvRow, $vqpInvoice->getAmount());
$sheet->setCellValue("AD" . $vendorInvRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("AE" . $vendorInvRow, $invoice->getSubTotalSgd($project[0]));
$sheet->setCellValue("AF" . $vendorInvRow, $vendorAmountSGD);
$sheet->setCellValue('AG'. $vendorInvRow, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
$vendorInvRow++;
}
}
} else {
$sheet->setCellValue("W" . $vendorInvRow, "-");
$sheet->setCellValue("X" . $vendorInvRow, "-");
$sheet->setCellValue("Y" . $vendorInvRow, "-");
$sheet->setCellValue("Z" . $vendorInvRow, "-");
$sheet->setCellValue("AA" . $vendorInvRow, "-");
}
$totalRow = $invRow > $row || $vendorInvRow > $row ? max($invRow, $vendorInvRow) : $row + 1;
$sheet->setCellValue("A" . $totalRow, "Total");
$sheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
$sheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
$sheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
$sheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
$sheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
$sheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
$sheet->setCellValue("T" . $totalRow, '=SUM(T'.$row.':T'.($invRow > $row ? $invRow - 1 : $row).')');
$sheet->setCellValue("U" . $totalRow, '=SUM(U'.$row.':U'.($invRow > $row ? $invRow - 1 : $row).')');
$sheet->setCellValue("AE" . $totalRow, '=SUM(AE'.$row.':AE'.($vendorInvRow > $row ? $vendorInvRow - 1 : $row).')');
$sheet->setCellValue("AF" . $totalRow, '=SUM(AF'.$row.':AF'.($vendorInvRow > $row ? $vendorInvRow - 1 : $row).')');
$sheet->setCellValue("AH" . $totalRow, "=AH" . $row);
$sheet->setCellValue("AI" . $totalRow, "=AI" . $row);
$sheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
$sheet->setCellValue("AK" . $totalRow, "=AK" . $row);
$sheet->setCellValue("AL" . $totalRow, "=AL" . $row);
$sheet->setCellValue("AM" . $totalRow, "=AM" . $row);
$sheet->setCellValue("AN" . $totalRow, '=T'.$totalRow.'-AE'.$totalRow);
$sheet->setCellValue("AN" . $row, '=T'.$totalRow.'-AE'.$totalRow);
$sheet->setCellValue("AO" . $totalRow, '=U'.$totalRow.'-AF'.$totalRow);
$sheet->setCellValue("AO" . $row, '=U'.$totalRow.'-AF'.$totalRow);
$grossProfitMargin = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$grossProfitMargin = '=(T'.$totalRow. '-AE'.$totalRow.')/T'.$totalRow;
$sheet->setCellValue("AP" . $totalRow, $grossProfitMargin);
$sheet->setCellValue("AP" . $row, $grossProfitMargin);
}else{
$sheet->setCellValue("AP" . $totalRow, $grossProfitMargin);
$sheet->setCellValue("AP" . $row, $grossProfitMargin);
}
$grossProfitMarginAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd(null, true) > 0) {
$grossProfitMarginAllocated = '=(U'.$totalRow. '-AF'.$totalRow.')/U'.$totalRow;
$sheet->setCellValue("AQ" . $totalRow, $grossProfitMarginAllocated);
$sheet->setCellValue("AQ" . $row, $grossProfitMarginAllocated);
}else{
$sheet->setCellValue("AQ" . $totalRow, $grossProfitMarginAllocated);
$sheet->setCellValue("AQ" . $row, $grossProfitMarginAllocated);
}
$sheet->setCellValue("AR" . $totalRow, '=I'.$totalRow.'-AJ'.$totalRow);
$sheet->setCellValue("AR" . $row, '=I'.$totalRow.'-AJ'.$totalRow);
$sheet->setCellValue("AS" . $totalRow, '=J'.$totalRow.'-AK'.$totalRow);
$sheet->setCellValue("AS" . $row, '=J'.$totalRow.'-AK'.$totalRow);
$grossProfitMarginFinancialYear = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
$grossProfitMarginFinancialYear = '=(I'.$totalRow. '-AJ'.$totalRow.')/I'.$totalRow;
$sheet->setCellValue("AT" . $totalRow, $grossProfitMarginFinancialYear);
$sheet->setCellValue("AT" . $row, $grossProfitMarginFinancialYear);
}else{
$sheet->setCellValue("AT" . $totalRow, $grossProfitMarginFinancialYear);
$sheet->setCellValue("AT" . $row, $grossProfitMarginFinancialYear);
}
$grossProfitMarginFinancialYearAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear, true) > 0) {
$grossProfitMarginFinancialYearAllocated = '=(J'.$totalRow. '-AK'.$totalRow.')/J'.$totalRow;
$sheet->setCellValue("AU" . $totalRow, $grossProfitMarginFinancialYearAllocated);
$sheet->setCellValue("AU" . $row, $grossProfitMarginFinancialYearAllocated);
}else{
$sheet->setCellValue("AU" . $totalRow, $grossProfitMarginFinancialYearAllocated);
$sheet->setCellValue("AU" . $row, $grossProfitMarginFinancialYearAllocated);
}
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getRowDimension($totalRow)->setRowHeight(20);
$overallTotals['G'][] = 'G'.$totalRow;
$overallTotals['H'][] = 'H'.$totalRow;
$overallTotals['I'][] = 'I'.$totalRow;
$overallTotals['J'][] = 'J'.$totalRow;
$overallTotals['K'][] = 'K'.$totalRow;
$overallTotals['L'][] = 'L'.$totalRow;
$overallTotals['T'][] = 'T'.$totalRow;
$overallTotals['U'][] = 'U'.$totalRow;
$overallTotals['AE'][] = 'AE'.$totalRow;
$overallTotals['AF'][] = 'AF'.$totalRow;
$overallTotals['AH'][] = 'AH'.$totalRow;
$overallTotals['AI'][] = 'AI'.$totalRow;
$overallTotals['AJ'][] = 'AJ'.$totalRow;
$overallTotals['AK'][] = 'AK'.$totalRow;
$overallTotals['AL'][] = 'AL'.$totalRow;
$overallTotals['AM'][] = 'AM'.$totalRow;
$row = $totalRow;
$row++;
}
//overall total
$row = $row+1;
$sheet->setCellValue("A". $row, "Overall Total");
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getRowDimension($row)->setRowHeight(20);
$sheet->setCellValue("G" . $row, '='.implode('+', $overallTotals['G']));
$sheet->setCellValue("H" . $row, '='.implode('+', $overallTotals['H']));
$sheet->setCellValue("I" . $row, '='.implode('+', $overallTotals['I']));
$sheet->setCellValue("J" . $row, '='.implode('+', $overallTotals['J']));
$sheet->setCellValue("K" . $row, '='.implode('+', $overallTotals['K']));
$sheet->setCellValue("L" . $row, '='.implode('+', $overallTotals['L']));
$sheet->setCellValue("T" . $row, '='.implode('+', $overallTotals['T']));
$sheet->setCellValue("U" . $row, '='.implode('+', $overallTotals['U']));
$sheet->setCellValue("AE" . $row, '='.implode('+', $overallTotals['AE']));
$sheet->setCellValue("AF" . $row, '='.implode('+', $overallTotals['AF']));
$sheet->setCellValue("AH" . $row, '='.implode('+', $overallTotals['AH']));
$sheet->setCellValue("AI" . $row, '='.implode('+', $overallTotals['AI']));
$sheet->setCellValue("AJ" . $row, '='.implode('+', $overallTotals['AJ']));
$sheet->setCellValue("AK" . $row, '='.implode('+', $overallTotals['AK']));
$sheet->setCellValue("AL" . $row, '='.implode('+', $overallTotals['AL']));
$sheet->setCellValue("AM" . $row, '='.implode('+', $overallTotals['AM']));
$sheet->setCellValue("AN" . $row, '=T'.$row.'-AE'.$row);
$sheet->setCellValue("AO" . $row, '=U'.$row.'-AF'.$row);
$sheet->setCellValue("AR" . $row, '=I'.$row.'-AJ'.$row);
$sheet->setCellValue("AS" . $row, '=J'.$row.'-AK'.$row);
$sheet->setCellValue("AP" . $row,'=IF(T'.$row.'=0, "",(T'.$row. '-AE'.$row.')/T'.$row.')');
$sheet->setCellValue("AQ" . $row,'=IF(U'.$row.'=0, "",(U'.$row. '-AF'.$row.')/U'.$row.')');
$sheet->setCellValue("AT" . $row,'=IF(I'.$row.'=0, "",(I'.$row. '-AJ'.$row.')/I'.$row.')');
$sheet->setCellValue("AU" . $row,'=IF(J'.$row.'=0, "",(J'.$row. '-AK'.$row.')/J'.$row.')');
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
$sheet->getStyle("V1:V" . $sheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->setAutoFilter('A1:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
$sheet->getStyle('G2:L' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$sheet->getStyle('Q2:R' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('T2:U' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AB2:AC' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AE2:AF' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AH2:AO' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AN2:AO' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AR2:AS' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle("AP2:AQ". $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$sheet->getStyle("AT2:AU". $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Summary Total');
$spreadsheet->addSheet($summarySheet, 1);
$summarySheet->setCellValue('A1', 'Client');
$summarySheet->setCellValue('B1', 'Project ID');
$summarySheet->setCellValue('C1', 'Project Name');
$summarySheet->setCellValue('D1', 'Project Status');
$summarySheet->setCellValue('E1', 'Start Date');
$summarySheet->setCellValue('F1', 'End Date');
$summarySheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
$summarySheet->setCellValue('H1', 'Revenue FY ' . $fyStart . ' Amount Allocated');
$summarySheet->setCellValue('I1', 'Revenue FY ' . $financialYear);
$summarySheet->setCellValue('J1', 'Revenue FY ' . $financialYear . ' Amount Allocated');
$summarySheet->setCellValue('K1', 'Revenue FY ' . $fyEnd);
$summarySheet->setCellValue('L1', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
$summarySheet->setCellValue('M1', 'MT INV No.');
$summarySheet->setCellValue('N1', 'INV Date');
$summarySheet->setCellValue('O1', 'INV Due Date');
$summarySheet->setCellValue('P1', 'INV Currency');
$summarySheet->setCellValue('Q1', 'INV Amount (w/o Taxes)');
$summarySheet->setCellValue('R1', 'INV Amount Allocated (w/o Taxes)');
$summarySheet->setCellValue('S1', 'SGD FX Rate');
$summarySheet->setCellValue('T1', 'INV Amount (w/o Taxes in SGD)');
$summarySheet->setCellValue('U1', 'INV Amount Allocated (w/o Taxes in SGD)');
$summarySheet->setCellValue('V1', '');
$summarySheet->setCellValue('W1', 'Vendor');
$summarySheet->setCellValue('X1', 'Vendor INV No.');
$summarySheet->setCellValue('Y1', 'Vendor INV Date');
$summarySheet->setCellValue('Z1', 'Vendor INV Due Date');
$summarySheet->setCellValue('AA1', 'Vendor INV Currency');
$summarySheet->setCellValue('AB1', 'Vendor INV Amount (w/o Taxes)');
$summarySheet->setCellValue('AC1', 'Vendor INV Amount Allocated (w/o Taxes)');
$summarySheet->setCellValue('AD1', 'SGD FX Rate');
$summarySheet->setCellValue('AE1', 'Vendor INV Amount (w/o Taxes in SGD)');
$summarySheet->setCellValue('AF1', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
$summarySheet->setCellValue('AG1', 'Client INV No');
$summarySheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
$summarySheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
$summarySheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
$summarySheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
$summarySheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
$summarySheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
$summarySheet->setCellValue('AN1', 'Gross Profit Total');
$summarySheet->setCellValue('AO1', 'Gross Profit Total Amount Allocated');
$summarySheet->setCellValue('AP1', 'Gross Profit Margin Total');
$summarySheet->setCellValue('AQ1', 'Gross Profit Margin Total Amount Allocated');
$summarySheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
$summarySheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
$summarySheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
$summarySheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AG1', 'Total Revenue');
$summarySheet->getDefaultColumnDimension()->setWidth(25);
$summarySheet->getColumnDimension('V')->setWidth(3);
$summarySheet->getStyle("A1:" . $summarySheet->getHighestColumn() . "1")->getFont()->setBold(true);
$summarySheet->getStyle("A1:" . $summarySheet->getHighestColumn() . "1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$summarySheet->getStyle("A1:" . $summarySheet->getHighestColumn() . "1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("A2:" . $summarySheet->getHighestColumn() . "2")->getFont()->setBold(false);
$summarySheet->freezePane('A2');
// $type = "LEAD;CONFIRMED";
$type = "CONFIRMED";
$status = "On-Going;Finished";
$projectsListSummary = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $start, $end, $type, 0, $status);
$sumOverallTotals = [];
$sumRow = $summarySheet->getHighestRow();
foreach ($projectsListSummary as $project) {
$summarySheet->setCellValue("A" . $sumRow, $project['clientName']);
$summarySheet->setCellValue("B" . $sumRow, $project['generatedId']);
$summarySheet->getCell("B" . $sumRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$summarySheet->getStyle('B' . $sumRow)->getFont()->setUnderline(true);
$summarySheet->setCellValue("C" . $sumRow, $project['name']);
$summarySheet->getCell("C" . $sumRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$summarySheet->getStyle('C' . $sumRow)->getFont()->setUnderline(true);
$summarySheet->setCellValue("D" . $sumRow, $project['status']);
$summarySheet->setCellValue("E" . $sumRow, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
$summarySheet->setCellValue("F" . $sumRow, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
$summarySheet->setCellValue("G" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
$summarySheet->setCellValue("H" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
$summarySheet->setCellValue("I" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
$summarySheet->setCellValue("J" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
$summarySheet->setCellValue("K" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
$summarySheet->setCellValue("L" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
$summarySheet->setCellValue("AH" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
$summarySheet->setCellValue("AI" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart, true));
$summarySheet->setCellValue("AJ" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
$summarySheet->setCellValue("AK" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear, true));
$summarySheet->setCellValue("AL" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
$summarySheet->setCellValue("AM" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd, true));
$projectSalesOrders = $project[0]->getProjectSalesOrders();
$invData = [
'totalAmount' => 0,
'totalAmountSGD' => 0,
'totalAmountAllocated' => 0,
'totalAmountAllocatedSGD' => 0,
];
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$summarySheet->setCellValue("P" . $sumRow, $invoice->getCurrency()->getIso());
$invData['totalAmount'] += $invoice->getSubTotal();
$invData['totalAmountAllocated'] += $soInvoice->getAmount();
$invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
$amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
$invData['totalAmountAllocatedSGD'] += $amountSGD;
$summarySheet->setCellValue("Q" . $sumRow, $invData['totalAmount']);
$summarySheet->setCellValue("R" . $sumRow, $invData['totalAmountAllocated']);
// $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$summarySheet->setCellValue("T" . $sumRow, $invData['totalAmountSGD']);
$summarySheet->setCellValue("U" . $sumRow, $invData['totalAmountAllocatedSGD']);
}
}
} else {
$summarySheet->setCellValue("M" . $sumRow, "-");
$summarySheet->setCellValue("N" . $sumRow, "-");
$summarySheet->setCellValue("O" . $sumRow, "-");
$summarySheet->setCellValue("P" . $sumRow, "-");
$summarySheet->setCellValue("Q" . $sumRow, "-");
$summarySheet->setCellValue("R" . $sumRow, "-");
$summarySheet->setCellValue("S" . $sumRow, "-");
$summarySheet->setCellValue("T" . $sumRow, "-");
$summarySheet->setCellValue("U" . $sumRow, "-");
}
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
$vendorData = [
'totalAmount' => 0,
'totalAmountAllocated' => 0,
'totalAmountSGD' => 0,
'totalAmountAllocatedSGD' => 0,
];
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
$vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
$vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
foreach ($vqpInvoices as $vqpInvoice) {
$invoice = $vqpInvoice->getVendorInvoice();
// if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
// $summarySheet->setCellValue("W" . $sumRow, $vendorName);
// $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
// $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
// $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$summarySheet->setCellValue("AA" . $sumRow, $invoice->getCurrency()->getIso());
$vendorData['totalAmount'] += $invoice->getSubTotal();
$vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
$summarySheet->setCellValue("AB" . $sumRow, $vendorData['totalAmount']);
$summarySheet->setCellValue("AC" . $sumRow, $vendorData['totalAmountAllocated']);
// $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
$vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
$vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
$summarySheet->setCellValue("AE" . $sumRow, $vendorData['totalAmountSGD']);
$summarySheet->setCellValue("AF" . $sumRow, $vendorData['totalAmountAllocatedSGD']);
$summarySheet->setCellValue('AG'. $sumRow, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
}
}
} else {
$summarySheet->setCellValue("W" . $sumRow, "-");
$summarySheet->setCellValue("X" . $sumRow, "-");
$summarySheet->setCellValue("Y" . $sumRow, "-");
$summarySheet->setCellValue("Z" . $sumRow, "-");
$summarySheet->setCellValue("AA" . $sumRow, "-");
}
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
$overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
}
// $summarySheet->setCellValue("A" . $totalRow, "Total");
// $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
// $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
// $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
// $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
// $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
// $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
// $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
// $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
// $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
// $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
// $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
// $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
$summarySheet->setCellValue("AN" . $sumRow, '=T'.$sumRow.'-AE'.$sumRow);
$summarySheet->setCellValue("AO" . $sumRow, '=U'.$sumRow.'-AF'.$sumRow);
$grossProfitMargin = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$grossProfitMargin = '=(T'.$sumRow. '-AE'.$sumRow.')/T'.$sumRow;
$summarySheet->setCellValue("AP" . $sumRow, $grossProfitMargin);
}else{
$summarySheet->setCellValue("AP" . $sumRow, $grossProfitMargin);
}
$grossProfitMarginAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd(null, true) > 0) {
$grossProfitMarginAllocated = '=(U'.$sumRow. '-AF'.$sumRow.')/U'.$sumRow;
$summarySheet->setCellValue("AQ" . $sumRow, $grossProfitMarginAllocated);
}else{
$summarySheet->setCellValue("AQ" . $sumRow, $grossProfitMarginAllocated);
}
$summarySheet->setCellValue("AR" . $sumRow, '=I'.$sumRow.'-AJ'.$sumRow);
$summarySheet->setCellValue("AS" . $sumRow, '=J'.$sumRow.'-AK'.$sumRow);
$grossProfitMarginFinancialYear = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
$grossProfitMarginFinancialYear = '=(I'.$sumRow. '-AJ'.$sumRow.')/I'.$sumRow;
$summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
}else{
$summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
}
$grossProfitMarginFinancialYearAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear, true) > 0) {
$grossProfitMarginFinancialYearAllocated = '=(J'.$sumRow. '-AK'.$sumRow.')/J'.$sumRow;
$summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
}else{
$summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
}
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
// $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$summarySheet->getRowDimension($sumRow)->setRowHeight(20);
$sumOverallTotals['G'][] = 'G'.$sumRow;
$sumOverallTotals['H'][] = 'H'.$sumRow;
$sumOverallTotals['I'][] = 'I'.$sumRow;
$sumOverallTotals['J'][] = 'J'.$sumRow;
$sumOverallTotals['K'][] = 'K'.$sumRow;
$sumOverallTotals['L'][] = 'L'.$sumRow;
$sumOverallTotals['T'][] = 'T'.$sumRow;
$sumOverallTotals['U'][] = 'U'.$sumRow;
$sumOverallTotals['AE'][] = 'AE'.$sumRow;
$sumOverallTotals['AF'][] = 'AF'.$sumRow;
$sumOverallTotals['AH'][] = 'AH'.$sumRow;
$sumOverallTotals['AI'][] = 'AI'.$sumRow;
$sumOverallTotals['AJ'][] = 'AJ'.$sumRow;
$sumOverallTotals['AK'][] = 'AK'.$sumRow;
$sumOverallTotals['AL'][] = 'AL'.$sumRow;
$sumOverallTotals['AM'][] = 'AM'.$sumRow;
$sumRow++;
}
$sumRow = $sumRow+1;
$summarySheet->setCellValue("A". $sumRow, "Overall Total");
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFB87800');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$summarySheet->getRowDimension($sumRow)->setRowHeight(20);
$summarySheet->setCellValue("G" . $sumRow, '='.implode('+', $sumOverallTotals['G']));
$summarySheet->setCellValue("H" . $sumRow, '='.implode('+', $sumOverallTotals['H']));
$summarySheet->setCellValue("I" . $sumRow, '='.implode('+', $sumOverallTotals['I']));
$summarySheet->setCellValue("J" . $sumRow, '='.implode('+', $sumOverallTotals['J']));
$summarySheet->setCellValue("K" . $sumRow, '='.implode('+', $sumOverallTotals['K']));
$summarySheet->setCellValue("L" . $sumRow, '='.implode('+', $sumOverallTotals['L']));
$summarySheet->setCellValue("T" . $sumRow, '='.implode('+', $sumOverallTotals['T']));
$summarySheet->setCellValue("U" . $sumRow, '='.implode('+', $sumOverallTotals['U']));
$summarySheet->setCellValue("AE" . $sumRow, '='.implode('+', $sumOverallTotals['AE']));
$summarySheet->setCellValue("AF" . $sumRow, '='.implode('+', $sumOverallTotals['AF']));
$summarySheet->setCellValue("AH" . $sumRow, '='.implode('+', $sumOverallTotals['AH']));
$summarySheet->setCellValue("AI" . $sumRow, '='.implode('+', $sumOverallTotals['AI']));
$summarySheet->setCellValue("AJ" . $sumRow, '='.implode('+', $sumOverallTotals['AJ']));
$summarySheet->setCellValue("AK" . $sumRow, '='.implode('+', $sumOverallTotals['AK']));
$summarySheet->setCellValue("AL" . $sumRow, '='.implode('+', $sumOverallTotals['AL']));
$summarySheet->setCellValue("AM" . $sumRow, '='.implode('+', $sumOverallTotals['AM']));
$summarySheet->setCellValue("AN" . $sumRow, '=T'.$sumRow.'-AE'.$sumRow);
$summarySheet->setCellValue("AO" . $sumRow, '=U'.$sumRow.'-AF'.$sumRow);
$summarySheet->setCellValue("AR" . $sumRow, '=I'.$sumRow.'-AJ'.$sumRow);
$summarySheet->setCellValue("AS" . $sumRow, '=J'.$sumRow.'-AK'.$sumRow);
$summarySheet->setCellValue("AP" . $sumRow,'=IF(T'.$sumRow.'=0, "",(T'.$sumRow. '-AE'.$sumRow.')/T'.$sumRow.')');
$summarySheet->setCellValue("AQ" . $sumRow,'=IF(U'.$sumRow.'=0, "",(U'.$sumRow. '-AF'.$sumRow.')/U'.$sumRow.')');
$summarySheet->setCellValue("AT" . $sumRow,'=IF(I'.$sumRow.'=0, "",(I'.$sumRow. '-AJ'.$sumRow.')/I'.$sumRow.')');
$summarySheet->setCellValue("AU" . $sumRow,'=IF(J'.$sumRow.'=0, "",(J'.$sumRow. '-AK'.$sumRow.')/J'.$sumRow.')');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
$summarySheet->getStyle("V1:V" . $summarySheet->getHighestRow())->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$summarySheet->setAutoFilter('A1:' . $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
$summarySheet->getStyle('G2:L' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$summarySheet->getStyle('Q2:R' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('T2:U' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AB2:AC' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AE2:AF' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AH2:AO' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AN2:AO' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AR2:AS' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle("AP2:AQ". $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$summarySheet->getStyle("AT2:AU". $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
/**
*
* Amount Left Invoices
*/
// $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
// $spreadsheet->addSheet($unallocatedSheet, 2);
// $unallocatedSheet->setCellValue('A1', 'Invoice');
// $unallocatedSheet->setCellValue('B1', 'Vendor Name');
// $unallocatedSheet->setCellValue('C1', 'Client');
// $unallocatedSheet->setCellValue('D1', 'Project');
// $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
// $unallocatedSheet->setCellValue('F1', 'Amount USD');
// $unallocatedSheet->setCellValue('G1', 'Allocated USD');
// $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
// $unallocatedSheet->setCellValue('I1', 'Date');
// $unallocatedSheet->setCellValue('J1', 'Due Date');
// $unallocatedSheet->setCellValue('K1', 'Client INV');
// $unallocatedSheet->setCellValue('L1', 'Status');
// $unallocatedSheet->setCellValue('M1', 'Financial Year');
// $lastColx = $unallocatedSheet->getHighestColumn();
// $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
// try {
// $currentRow = $unallocatedSheet->getHighestRow();
// $invoiceProjectMap = [];
// foreach ($projectsList as $project) {
// $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
// if ($vendorQuotationPlannings) {
// foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
// $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
// foreach ($vqpInvoices as $vqpInvoice) {
// $vendorInvoice = $vqpInvoice->getVendorInvoice();
// if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
// if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
// $invoiceId = $vendorInvoice->getVendorInvoiceNo();
// if (!isset($invoiceProjectMap[$invoiceId])) {
// $invoiceProjectMap[$invoiceId] = [
// 'invoice' => $vendorInvoice,
// 'projects' => [],
// 'vendorName' => '',
// 'xeroContact' => null
// ];
// }
// // Add project information
// $invoiceProjectMap[$invoiceId]['projects'][] = [
// 'project' => $vendorQuotationPlanning->getProject(),
// 'client' => $vendorQuotationPlanning->getProject()->getClient(),
// 'vendorQuotationPlanning' => $vendorQuotationPlanning,
// 'amount' => $vqpInvoice->getAmountUsd(),
// ];
// }
// }
// }
// }
// // Second pass: Write to spreadsheet with merged cells for same invoice
// foreach ($invoiceProjectMap as $invoiceId => $data) {
// $vendorInvoice = $data['invoice'];
// $projects = $data['projects'];
// $startRow = $currentRow;
// // Get vendor name
// $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
// $vendorName = '';
// if ($vendorInvoice->getXeroContactId()) {
// $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
// } else {
// $vendorName = $vendorInvoice->getVendor()->getName();
// }
// // Get client invoices
// $clientInvoices = [];
// if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
// foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
// $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
// array_push($clientInvoices, $clientInv);
// }
// }
// // Write data for each project
// foreach ($projects as $index => $projectData) {
// $project = $projectData['project'];
// // Write project-specific information
// $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
// $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
// // Set project hyperlink
// $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
// $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
// // Write amount for this project
// $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
// // For the first project entry, write the shared invoice information
// if ($index === 0) {
// $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
// $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
// $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
// $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
// $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
// $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
// $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
// $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
// $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
// }
// // Handle vendor quotes
// if ($projectData['vendorQuotationPlanning']) {
// $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
// if (!empty($vendorQuotations)) {
// foreach($vendorQuotations as $vendorQoute){
// $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
// $currentRow++;
// }
// } else {
// $unallocatedSheet->setCellValue('E' . $currentRow, "-");
// }
// } else {
// $unallocatedSheet->setCellValue('E' . $currentRow, "-");
// }
// $currentRow++;
// }
// // If we have multiple projects, merge the shared invoice cells
// if (count($projects) > 1) {
// $endRow = $currentRow - 1;
// $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
// foreach ($columnsToMerge as $column) {
// if ($startRow < $endRow) {
// $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
// $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
// ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
// }
// }
// }
// }
// } catch (\Exception $e) {
// dd($e->getMessage());
// }
// $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
// $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
// Export Project Revenue Cost Date Range [PENDING]
public function exportProjectRevenueCostDateRange($isAdmin, $startDate, $endDate, $baseurl, $_target)
{
$startDateRange = date("d-M-Y", strtotime($startDate));
$endDateRange = date("d-M-Y", strtotime($endDate));
$overallTotals = [];
$lineItemTotals = [];
$overallTotalRevenue = 0;
$overallTotalCost = 0;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet()->setTitle('Revenue vs Cost');
$sheet->setCellValue('A1', 'Today\'s Date');
$sheet->setCellValue('A2', 'From (Project Start Date)');
$sheet->setCellValue('A3', 'To (Project Start Date)');
$sheet->setCellValue('C1', date('d-M-Y'));
$sheet->setCellValue('C2', $startDateRange);
$sheet->setCellValue('C3', $endDateRange);
// Define Header Data
$sheet->setCellValue('A5', 'Client');
$sheet->setCellValue('B5', 'Project ID');
$sheet->setCellValue('C5', 'Project Name');
$sheet->setCellValue('D5', 'Project Status');
$sheet->setCellValue('E5', 'Start Date');
$sheet->setCellValue('F5', 'End Date');
// $sheet->setCellValue('G5', 'Revenue FY ' . $fyStart);
// $sheet->setCellValue('H5', 'Revenue FY ' . $fyStart . ' Amount Allocated');
// $sheet->setCellValue('I5', 'Revenue FY ' . $financialYear);
// $sheet->setCellValue('J5', 'Revenue FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('K5', 'Revenue FY ' . $fyEnd);
// $sheet->setCellValue('L5', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
$sheet->setCellValue('G5', 'MT INV No.');
$sheet->setCellValue('H5', 'INV Date');
$sheet->setCellValue('I5', 'INV Due Date');
$sheet->setCellValue('J5', 'INV Currency');
$sheet->setCellValue('K5', 'INV Amount (w/o Taxes)');
$sheet->setCellValue('L5', 'INV Amount Allocated (w/o Taxes)');
$sheet->setCellValue('M5', 'SGD FX Rate');
$sheet->setCellValue('N5', 'INV Amount (w/o Taxes in SGD)');
$sheet->setCellValue('O5', 'INV Amount Allocated (w/o Taxes in SGD)');
$sheet->setCellValue('P5', 'Item Code');
$sheet->setCellValue('Q5', 'Amount Item Code');
$sheet->setCellValue('R5', 'Department');
$sheet->setCellValue('S5', '');
$sheet->setCellValue('T5', 'Vendor');
$sheet->setCellValue('U5', 'Vendor INV No.');
$sheet->setCellValue('V5', 'Vendor INV Date');
$sheet->setCellValue('W5', 'Vendor INV Due Date');
$sheet->setCellValue('X5', 'Vendor INV Currency');
$sheet->setCellValue('Y5', 'Vendor INV Amount (w/o Taxes)');
$sheet->setCellValue('Z5', 'Vendor INV Amount Allocated (w/o Taxes)');
$sheet->setCellValue('AA5', 'SGD FX Rate');
$sheet->setCellValue('AB5', 'Vendor INV Amount (w/o Taxes in SGD)');
$sheet->setCellValue('AC5', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
$sheet->setCellValue('AD5', 'Client INV No');
// $sheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
// $sheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
// $sheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
// $sheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
// $sheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
$sheet->setCellValue('AE5', 'Gross Profit Total');
$sheet->setCellValue('AF5', 'Gross Profit Total Amount Allocated');
$sheet->setCellValue('AG5', 'Gross Profit Margin Total');
$sheet->setCellValue('AH5', 'Gross Profit Margin Total Amount Allocated');
// $sheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
// $sheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
// $sheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AG1', 'Total Revenue');
$sheet->getDefaultColumnDimension()->setWidth(25);
$sheet->getColumnDimension('S')->setWidth(3);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->setBold(true);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle("A5:" . $sheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A6:" . $sheet->getHighestColumn() . "6")->getFont()->setBold(false);
$sheet->freezePane('A6');
$filename = "Project_Revenue_vs_Cost_" . $startDateRange . " - " . $endDateRange . "_" . date('Y-m-d') . '.xlsx';
// $type = "LEAD;CONFIRMED";
$type = "CONFIRMED";
$status = "On-Going;Finished";
$projectsList = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $startDate, $endDate, $type, 0, $status);
$row = $sheet->getHighestRow();
$overallRow = $row+1;
if(count($projectsList)){
foreach ($projectsList as $project) {
$sheet->setCellValue("A" . $row, $project['clientName']);
$sheet->setCellValue("B" . $row, $project['generatedId']);
$sheet->getCell("B" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->getStyle('B' . $row)->getFont()->setUnderline(true);
$sheet->setCellValue("C" . $row, $project['name']);
$sheet->getCell("C" . $row)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$sheet->getStyle('C' . $row)->getFont()->setUnderline(true);
$sheet->setCellValue("D" . $row, $project['status']);
$sheet->setCellValue("E" . $row, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
$sheet->setCellValue("F" . $row, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
$overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
}
// looping project invoice
$invRow = $row;
$projectSalesOrders = $project[0]->getProjectSalesOrders();
$InvTotalwoTax = 0;
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$sheet->setCellValue("G" . $invRow, $invoice->getInvoiceNo());
$sheet->setCellValue("H" . $invRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("I" . $invRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("J" . $invRow, $invoice->getCurrency()->getIso());
$InvTotalwoTax += $soInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("K" . $invRow, $invoice->getSubTotal());
$sheet->setCellValue("L" . $invRow, $soInvoice->getAmount());
$sheet->setCellValue("M" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("N" . $invRow, $invoice->getSubTotalSgd($project[0]));
$sheet->setCellValue("O" . $invRow, $amountSGD);
if($invoice->getXeroLineItems()->count() > 0) {
$lineItemRow = $invRow;
foreach ($invoice->getXeroLineItems() as $lineItem) {
$sheet->setCellValue("P" . $lineItemRow, $lineItem->getItemCode());
$sheet->setCellValue("Q" . $lineItemRow, $lineItem->getSubTotal());
$sheet->setCellValue("R" . $lineItemRow, $lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-');
$itemCode = $lineItem->getItemCode();
$department = $lineItem->getDepartment() ? $lineItem->getDepartment()->getName() : '-';
$amount = $lineItem->getSubTotal();
if (!isset($lineItemTotals[$itemCode])) {
$lineItemTotals[$itemCode] = [];
}
if (!isset($lineItemTotals[$itemCode]['department'])) {
$lineItemTotals[$itemCode]['department'] = $department;
}
if (!isset($lineItemTotals[$itemCode]['amount'])) {
$lineItemTotals[$itemCode]['amount'] = 0;
}else{
$lineItemTotals[$itemCode]['amount'] += $amount;
}
$lineItemRow++;
}
}
$invRow = $lineItemRow > $invRow ? $lineItemRow : $invRow;
}
}
} else {
$sheet->setCellValue("G" . $invRow, "-");
$sheet->setCellValue("H" . $invRow, "-");
$sheet->setCellValue("I" . $invRow, "-");
$sheet->setCellValue("J" . $invRow, "-");
$sheet->setCellValue("K" . $invRow, "-");
$sheet->setCellValue("L" . $invRow, "-");
$sheet->setCellValue("M" . $invRow, "-");
$sheet->setCellValue("N" . $invRow, "-");
$sheet->setCellValue("O" . $invRow, "-");
}
//looping vendor invoice
$vendorInvRow = $row;
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
$vendorTotalWoTax = 0;
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
$vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
$vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
foreach ($vqpInvoices as $vqpInvoice) {
$invoice = $vqpInvoice->getVendorInvoice();
// if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
$sheet->setCellValue("T" . $vendorInvRow, $vendorName);
$sheet->setCellValue("U" . $vendorInvRow, $invoice->getInvoiceNo());
$sheet->setCellValue("V" . $vendorInvRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
$sheet->setCellValue("W" . $vendorInvRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$sheet->setCellValue("X" . $vendorInvRow, $invoice->getCurrency()->getIso());
$vendorTotalWoTax += $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("Y" . $vendorInvRow, $invoice->getSubtotal());
$sheet->setCellValue("Z" . $vendorInvRow, $vqpInvoice->getAmount());
$sheet->setCellValue("AA" . $vendorInvRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
$sheet->setCellValue("AB" . $vendorInvRow, $invoice->getSubTotalSgd($project[0]));
$sheet->setCellValue("AC" . $vendorInvRow, $vendorAmountSGD);
$sheet->setCellValue("AD" . $vendorInvRow, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
$vendorInvRow++;
}
}
} else {
$sheet->setCellValue("T" . $vendorInvRow, "-");
$sheet->setCellValue("U" . $vendorInvRow, "-");
$sheet->setCellValue("V" . $vendorInvRow, "-");
$sheet->setCellValue("W" . $vendorInvRow, "-");
$sheet->setCellValue("X" . $vendorInvRow, "-");
$sheet->setCellValue("Y" . $vendorInvRow, "-");
$sheet->setCellValue("Z" . $vendorInvRow, "-");
$sheet->setCellValue("AA" . $vendorInvRow, "-");
$sheet->setCellValue("AB" . $vendorInvRow, "-");
$sheet->setCellValue("AC" . $vendorInvRow, "-");
$sheet->setCellValue("AD" . $vendorInvRow, "-");
}
$totalRow = $invRow > $row || $vendorInvRow > $row ? max($invRow, $vendorInvRow) : $row + 1;
$sheet->setCellValue("A" . $totalRow, "Total");
$sheet->setCellValue("N" . $totalRow, '=SUM(N'.$row.':N'.($invRow > $row ? $invRow - 1 : $row).')');
$sheet->setCellValue("O" . $totalRow, '=SUM(O'.$row.':O'.($invRow > $row ? $invRow - 1 : $row).')');
$sheet->setCellValue("AB" . $totalRow, '=SUM(AB'.$row.':AB'.($vendorInvRow > $row ? $vendorInvRow - 1 : $row).')');
$sheet->setCellValue("AC" . $totalRow, '=SUM(AC'.$row.':AC'.($vendorInvRow > $row ? $vendorInvRow - 1 : $row).')');
$sheet->setCellValue("AE" . $totalRow, '=N'.$totalRow.'-AB'.$totalRow);
$sheet->setCellValue("AE" . $row, '=N'.$totalRow.'-AB'.$totalRow);
$sheet->setCellValue("AF" . $totalRow, '=O'.$totalRow.'-AC'.$totalRow);
$sheet->setCellValue("AF" . $row, '=O'.$totalRow.'-AC'.$totalRow);
$grossProfitMargin = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$grossProfitMargin = '=(N'.$totalRow. '-AB'.$totalRow.')/N'.$totalRow;
$sheet->setCellValue("AG" . $totalRow, $grossProfitMargin);
$sheet->setCellValue("AG" . $row, $grossProfitMargin);
}else{
$sheet->setCellValue("AG" . $totalRow, $grossProfitMargin);
$sheet->setCellValue("AG" . $row, $grossProfitMargin);
}
$grossProfitMarginAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd(null, true) > 0) {
$grossProfitMarginAllocated = '=(O'.$totalRow. '-AC'.$totalRow.')/O'.$totalRow;
$sheet->setCellValue("AH" . $totalRow, $grossProfitMarginAllocated);
$sheet->setCellValue("AH" . $row, $grossProfitMarginAllocated);
}else{
$sheet->setCellValue("AH" . $totalRow, $grossProfitMarginAllocated);
$sheet->setCellValue("AH" . $row, $grossProfitMarginAllocated);
}
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFont()->setBold(true);
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$sheet->getStyle("A" . $totalRow . ":" . $sheet->getHighestColumn() . $totalRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getRowDimension($totalRow)->setRowHeight(20);
$overallTotals['N'][] = 'N'.$totalRow;
$overallTotals['O'][] = 'O'.$totalRow;
$overallTotals['AB'][] = 'AB'.$totalRow;
$overallTotals['AC'][] = 'AC'.$totalRow;
$row = $totalRow;
$row++;
}
//overall total
$overallRow = $row+1;
$row = $row+1;
$sheet->setCellValue("A". $row, "Overall Total");
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getRowDimension($row)->setRowHeight(20);
$sheet->setCellValue("N" . $row, '='.implode('+', $overallTotals['N']));
$sheet->setCellValue("O" . $row, '='.implode('+', $overallTotals['O']));
$sheet->setCellValue("AB" . $row, '='.implode('+', $overallTotals['AB']));
$sheet->setCellValue("AC" . $row, '='.implode('+', $overallTotals['AC']));
$sheet->setCellValue("AE" . $row, '=N'.$row.'-AB'.$row);
$sheet->setCellValue("AF" . $row, '=O'.$row.'-AC'.$row);
$sheet->setCellValue("AG" . $row,'=IF(N'.$row.'=0, "",(N'.$row. '-AB'.$row.')/N'.$row.')');
$sheet->setCellValue("AH" . $row,'=IF(O'.$row.'=0, "",(O'.$row. '-AC'.$row.')/O'.$row.')');
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
$row = $row+2;
$sheet->setCellValue("A" . $row, "Summary");
$sheet->getStyle("A" . $row . ":" . $sheet->getHighestColumn() . $row)->getFont()->setBold(true);
$row = $row+1;
$sheet->setCellValue("A" . $row, "Item Code");
$sheet->setCellValue("B" . $row, "Department");
$sheet->setCellValue("C" . $row, "Amount");
$sheet->getStyle("A" . $row . ":C" . $row)->getFont()->setBold(true);
$sheet->getStyle("A" . $row . ":C" . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$row = $row+1;
foreach ($lineItemTotals as $itemCode => $itemTotal) {
$sheet->setCellValue("A" . $row, $itemCode);
$sheet->setCellValue("B" . $row, $itemTotal['department']);
$sheet->setCellValue("C" . $row, $itemTotal['amount']);
$sheet->getStyle('C' . $row)->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$row++;
}
}
$sheet->getStyle("S5:S" . $overallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$sheet->setAutoFilter('A5:' . $sheet->getHighestColumn() . $sheet->getHighestRow());
$sheet->getStyle('K2:L' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$sheet->getStyle('N2:O' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('Q2:Q' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('Y2:Z' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AB2:AC' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle('AE2:AF' . $sheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$sheet->getStyle("AG2:AH". $sheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
$summarySheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Summary Total');
$spreadsheet->addSheet($summarySheet, 1);
$summarySheet->setCellValue('A1', 'Today\'s Date');
$summarySheet->setCellValue('A2', 'From (Project Start Date)');
$summarySheet->setCellValue('A3', 'To (Project Start Date)');
$summarySheet->setCellValue('C1', date('d-M-Y'));
$summarySheet->setCellValue('C2', $startDateRange);
$summarySheet->setCellValue('C3', $endDateRange);
$summarySheet->setCellValue('A5', 'Client');
$summarySheet->setCellValue('B5', 'Project ID');
$summarySheet->setCellValue('C5', 'Project Name');
$summarySheet->setCellValue('D5', 'Project Status');
$summarySheet->setCellValue('E5', 'Start Date');
$summarySheet->setCellValue('F5', 'End Date');
// $summarySheet->setCellValue('G1', 'Revenue FY ' . $fyStart);
// $summarySheet->setCellValue('H1', 'Revenue FY ' . $fyStart . ' Amount Allocated');
// $summarySheet->setCellValue('I1', 'Revenue FY ' . $financialYear);
// $summarySheet->setCellValue('J1', 'Revenue FY ' . $financialYear . ' Amount Allocated');
// $summarySheet->setCellValue('K1', 'Revenue FY ' . $fyEnd);
// $summarySheet->setCellValue('L1', 'Revenue FY ' . $fyEnd . ' Amount Allocated');
$summarySheet->setCellValue('G5', 'MT INV No.');
$summarySheet->setCellValue('H5', 'INV Date');
$summarySheet->setCellValue('I5', 'INV Due Date');
$summarySheet->setCellValue('J5', 'INV Currency');
$summarySheet->setCellValue('K5', 'INV Amount (w/o Taxes)');
$summarySheet->setCellValue('L5', 'INV Amount Allocated (w/o Taxes)');
$summarySheet->setCellValue('M5', 'SGD FX Rate');
$summarySheet->setCellValue('N5', 'INV Amount (w/o Taxes in SGD)');
$summarySheet->setCellValue('O5', 'INV Amount Allocated (w/o Taxes in SGD)');
$summarySheet->setCellValue('P5', '');
$summarySheet->setCellValue('Q5', 'Vendor');
$summarySheet->setCellValue('R5', 'Vendor INV No.');
$summarySheet->setCellValue('S5', 'Vendor INV Date');
$summarySheet->setCellValue('T5', 'Vendor INV Due Date');
$summarySheet->setCellValue('U5', 'Vendor INV Currency');
$summarySheet->setCellValue('V5', 'Vendor INV Amount (w/o Taxes)');
$summarySheet->setCellValue('W5', 'Vendor INV Amount Allocated (w/o Taxes)');
$summarySheet->setCellValue('X5', 'SGD FX Rate');
$summarySheet->setCellValue('Y5', 'Vendor INV Amount (w/o Taxes in SGD)');
$summarySheet->setCellValue('Z5', 'Vendor INV Amount Allocated (w/o Taxes in SGD)');
$summarySheet->setCellValue('AA5', 'Client INV No');
// $summarySheet->setCellValue('AH1', 'Vendor Cost ' . $fyStart);
// $summarySheet->setCellValue('AI1', 'Vendor Cost ' . $fyStart . ' Amount Allocated');
// $summarySheet->setCellValue('AJ1', 'Vendor Cost ' . $financialYear);
// $summarySheet->setCellValue('AK1', 'Vendor Cost ' . $financialYear . ' Amount Allocated');
// $summarySheet->setCellValue('AL1', 'Vendor Cost ' . $fyEnd);
// $summarySheet->setCellValue('AM1', 'Vendor Cost ' . $fyEnd . ' Amount Allocated');
$summarySheet->setCellValue('AB5', 'Gross Profit Total');
$summarySheet->setCellValue('AC5', 'Gross Profit Total Amount Allocated');
$summarySheet->setCellValue('AD5', 'Gross Profit Margin Total');
$summarySheet->setCellValue('AE5', 'Gross Profit Margin Total Amount Allocated');
// $summarySheet->setCellValue('AR1', 'Gross Profit FY ' . $financialYear);
// $summarySheet->setCellValue('AS1', 'Gross Profit FY ' . $financialYear . ' Amount Allocated');
// $summarySheet->setCellValue('AT1', 'Gross Profit Margin FY ' . $financialYear);
// $summarySheet->setCellValue('AU1', 'Gross Profit Margin FY ' . $financialYear . ' Amount Allocated');
// $sheet->setCellValue('AG1', 'Total Revenue');
$summarySheet->getDefaultColumnDimension()->setWidth(25);
$summarySheet->getColumnDimension('P')->setWidth(3);
$summarySheet->getStyle("A5:" . $summarySheet->getHighestColumn() . "5")->getFont()->setBold(true);
$summarySheet->getStyle("A5:" . $summarySheet->getHighestColumn() . "5")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$summarySheet->getStyle("A5:" . $summarySheet->getHighestColumn() . "5")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
// $summarySheet->getStyle("H1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("J1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("L1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("R1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("U1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AC1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AF1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AI1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AK1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AM1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AO1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AQ1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AS1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
// $summarySheet->getStyle("AU1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('2856bfcc');
$summarySheet->getStyle("A6:" . $summarySheet->getHighestColumn() . "6")->getFont()->setBold(false);
$summarySheet->freezePane('A6');
// $type = "LEAD;CONFIRMED";
$type = "CONFIRMED";
$status = "On-Going;Finished";
$projectsListSummary = $this->projectRepository->findByPage(0, 9999, "", "ASC", 'client', $startDate, $endDate, $type, 0, $status);
$sumOverallTotals = [];
$sumRow = $summarySheet->getHighestRow();
$sumOverallRow = $sumRow+1;
if(count($projectsListSummary) > 0){
foreach ($projectsListSummary as $project) {
$summarySheet->setCellValue("A" . $sumRow, $project['clientName']);
$summarySheet->setCellValue("B" . $sumRow, $project['generatedId']);
$summarySheet->getCell("B" . $sumRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$summarySheet->getStyle('B' . $sumRow)->getFont()->setUnderline(true);
$summarySheet->setCellValue("C" . $sumRow, $project['name']);
$summarySheet->getCell("C" . $sumRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project['id']);
$summarySheet->getStyle('C' . $sumRow)->getFont()->setUnderline(true);
$summarySheet->setCellValue("D" . $sumRow, $project['status']);
$summarySheet->setCellValue("E" . $sumRow, $project['startDate'] ? $project['startDate']->format('d-M-Y') : null);
$summarySheet->setCellValue("F" . $sumRow, $project['endDate'] ? $project['endDate']->format('d-M-Y') : null);
// $summarySheet->setCellValue("G" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
// $summarySheet->setCellValue("H" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
// $summarySheet->setCellValue("I" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
// $summarySheet->setCellValue("J" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
// $summarySheet->setCellValue("K" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
// $summarySheet->setCellValue("L" . $sumRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
// $summarySheet->setCellValue("AH" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart));
// $summarySheet->setCellValue("AI" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyStart, true));
// $summarySheet->setCellValue("AJ" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear));
// $summarySheet->setCellValue("AK" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($financialYear, true));
// $summarySheet->setCellValue("AL" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd));
// $summarySheet->setCellValue("AM" . $sumRow, $project[0]->getInvVendorCostByFinancialYearSgd($fyEnd, true));
$projectSalesOrders = $project[0]->getProjectSalesOrders();
$invData = [
'totalAmount' => 0,
'totalAmountSGD' => 0,
'totalAmountAllocated' => 0,
'totalAmountAllocatedSGD' => 0,
];
if ($projectSalesOrders) {
foreach ($projectSalesOrders as $pso) {
$soInvoices = $pso->getSalesOrder()->getSalesOrderInvoices($project[0]->getId());
foreach ($soInvoices as $soInvoice) {
$invoice = $soInvoice->getInvoice();
if ($invoice->getXeroStatus() == 'VOIDED') continue;
$summarySheet->setCellValue("G" . $sumRow, "-");
$summarySheet->setCellValue("H" . $sumRow, "-");
$summarySheet->setCellValue("I" . $sumRow, "-");
$summarySheet->setCellValue("J" . $sumRow, $invoice->getCurrency()->getIso());
$invData['totalAmount'] += $invoice->getSubTotal();
$invData['totalAmountAllocated'] += $soInvoice->getAmount();
$invData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
$amountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $soInvoice->getAmount() : $soInvoice->getAmountSgd($project[0]);
$invData['totalAmountAllocatedSGD'] += $amountSGD;
$summarySheet->setCellValue("K" . $sumRow, $invData['totalAmount']);
$summarySheet->setCellValue("L" . $sumRow, $invData['totalAmountAllocated']);
// $sheet->setCellValue("S" . $invRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$summarySheet->setCellValue("N" . $sumRow, $invData['totalAmountSGD']);
$summarySheet->setCellValue("O" . $sumRow, $invData['totalAmountAllocatedSGD']);
}
}
} else {
$summarySheet->setCellValue("G" . $sumRow, "-");
$summarySheet->setCellValue("H" . $sumRow, "-");
$summarySheet->setCellValue("I" . $sumRow, "-");
$summarySheet->setCellValue("J" . $sumRow, "-");
$summarySheet->setCellValue("K" . $sumRow, "-");
$summarySheet->setCellValue("L" . $sumRow, "-");
$summarySheet->setCellValue("M" . $sumRow, "-");
$summarySheet->setCellValue("N" . $sumRow, "-");
$summarySheet->setCellValue("O" . $sumRow, "-");
}
$vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
$vendorData = [
'totalAmount' => 0,
'totalAmountAllocated' => 0,
'totalAmountSGD' => 0,
'totalAmountAllocatedSGD' => 0,
];
if ($vendorQuotationPlannings) {
foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
$vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
$vendorName = $vendorQuotationPlanning->getVendor() ? $vendorQuotationPlanning->getVendor()->getName() : '[No Vendor]';
foreach ($vqpInvoices as $vqpInvoice) {
$invoice = $vqpInvoice->getVendorInvoice();
$summarySheet->setCellValue("Q" . $sumRow, "-");
$summarySheet->setCellValue("R" . $sumRow, "-");
$summarySheet->setCellValue("S" . $sumRow, "-");
$summarySheet->setCellValue("T" . $sumRow, "-");
$summarySheet->setCellValue("U" . $sumRow, "-");
// if ($vqpInvoice->getVendorInvoice()->getXeroStatus() != 'PAID') continue;
// $summarySheet->setCellValue("W" . $sumRow, $vendorName);
// $summarySheet->setCellValue("X" . $sumRow, $invoice->getInvoiceNo());
// $summarySheet->setCellValue("Y" . $sumRow, $invoice->getInvoiceDate() ? $invoice->getInvoiceDate()->format('d-M-Y') : null);
// $summarySheet->setCellValue("Z" . $sumRow, $invoice->getDueDate() ? $invoice->getDueDate()->format('d-M-Y') : null);
$summarySheet->setCellValue("U" . $sumRow, $invoice->getCurrency()->getIso());
$vendorData['totalAmount'] += $invoice->getSubTotal();
$vendorData['totalAmountAllocated'] += $vqpInvoice->getAmount();
$summarySheet->setCellValue("V" . $sumRow, $vendorData['totalAmount']);
$summarySheet->setCellValue("W" . $sumRow, $vendorData['totalAmountAllocated']);
// $summarySheet->setCellValue("AD" . $sumRow, $this->currencyService->getExchangeRate($project[0]->getCreatedAt()->format('Y-m-d'), $invoice->getCurrency()->getIso(), 'SGD'));
$vendorAmountSGD = $invoice->getCurrency()->getIso() == 'SGD' ? $vqpInvoice->getAmount() : $vqpInvoice->getAmountSgd($project[0]);
$vendorData['totalAmountSGD'] += $invoice->getSubTotalSgd($project[0]);
$vendorData['totalAmountAllocatedSGD'] += $vendorAmountSGD;
$summarySheet->setCellValue("Y" . $sumRow, $vendorData['totalAmountSGD']);
$summarySheet->setCellValue("Z" . $sumRow, $vendorData['totalAmountAllocatedSGD']);
$summarySheet->setCellValue('AA'. $sumRow, $vqpInvoice->getInvoice() ? $vqpInvoice->getInvoice()->getInvoiceNo() : '-');
}
}
} else {
$summarySheet->setCellValue("Q" . $sumRow, "-");
$summarySheet->setCellValue("R" . $sumRow, "-");
$summarySheet->setCellValue("S" . $sumRow, "-");
$summarySheet->setCellValue("T" . $sumRow, "-");
$summarySheet->setCellValue("U" . $sumRow, "-");
$summarySheet->setCellValue("V" . $sumRow, "-");
$summarySheet->setCellValue("W" . $sumRow, "-");
$summarySheet->setCellValue("X" . $sumRow, "-");
$summarySheet->setCellValue("Y" . $sumRow, "-");
$summarySheet->setCellValue("Z" . $sumRow, "-");
$summarySheet->setCellValue("AA" . $sumRow, "-");
}
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$overallTotalRevenue += $project[0]->getInvRevenueByFinancialYearSgd();
$overallTotalCost += $project[0]->getInvVendorCostByFinancialYearSgd();
}
// $summarySheet->setCellValue("A" . $totalRow, "Total");
// $summarySheet->setCellValue("G" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart));
// $summarySheet->setCellValue("H" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyStart, true));
// $summarySheet->setCellValue("I" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear));
// $summarySheet->setCellValue("J" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($financialYear, true));
// $summarySheet->setCellValue("K" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd));
// $summarySheet->setCellValue("L" . $totalRow, $project[0]->getInvRevenueByFinancialYearSgd($fyEnd, true));
// $summarySheet->setCellValue("T" . $sumRow, '=SUM(T'.$sumRow.':T'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("U" . $sumRow, '=SUM(U'.$sumRow.':U'.($invRow > $sumRow ? $invRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AE" . $sumRow, '=SUM(AE'.$sumRow.':AE'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AF" . $sumRow, '=SUM(AF'.$sumRow.':AF'.($vendorInvRow > $sumRow ? $vendorInvRow - 1 : $sumRow).')');
// $summarySheet->setCellValue("AH" . $totalRow, "=AH" . $row);
// $summarySheet->setCellValue("AI" . $totalRow, "=AI" . $row);
// $summarySheet->setCellValue("AJ" . $totalRow, "=AJ" . $row);
// $summarySheet->setCellValue("AK" . $totalRow, "=AK" . $row);
// $summarySheet->setCellValue("AL" . $totalRow, "=AL" . $row);
// $summarySheet->setCellValue("AM" . $totalRow, "=AM" . $row);
$summarySheet->setCellValue("AB" . $sumRow, '=N'.$sumRow.'-Y'.$sumRow);
$summarySheet->setCellValue("AC" . $sumRow, '=O'.$sumRow.'-Z'.$sumRow);
$grossProfitMargin = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd() > 0) {
$grossProfitMargin = '=(N'.$sumRow. '-Y'.$sumRow.')/N'.$sumRow;
$summarySheet->setCellValue("AD" . $sumRow, $grossProfitMargin);
}else{
$summarySheet->setCellValue("AD" . $sumRow, $grossProfitMargin);
}
$grossProfitMarginAllocated = 0;
if ($project[0]->getInvRevenueByFinancialYearSgd(null, true) > 0) {
$grossProfitMarginAllocated = '=(O'.$sumRow. '-Z'.$sumRow.')/O'.$sumRow;
$summarySheet->setCellValue("AE" . $sumRow, $grossProfitMarginAllocated);
}else{
$summarySheet->setCellValue("AE" . $sumRow, $grossProfitMarginAllocated);
}
// $summarySheet->setCellValue("AR" . $sumRow, '=I'.$sumRow.'-AJ'.$sumRow);
// $summarySheet->setCellValue("AS" . $sumRow, '=J'.$sumRow.'-AK'.$sumRow);
// $grossProfitMarginFinancialYear = 0;
// if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear) > 0) {
// $grossProfitMarginFinancialYear = '=(I'.$sumRow. '-AJ'.$sumRow.')/I'.$sumRow;
// $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
// }else{
// $summarySheet->setCellValue("AT" . $sumRow, $grossProfitMarginFinancialYear);
// }
// $grossProfitMarginFinancialYearAllocated = 0;
// if ($project[0]->getInvRevenueByFinancialYearSgd($financialYear, true) > 0) {
// $grossProfitMarginFinancialYearAllocated = '=(J'.$sumRow. '-AK'.$sumRow.')/J'.$sumRow;
// $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
// }else{
// $summarySheet->setCellValue("AU" . $sumRow, $grossProfitMarginFinancialYearAllocated);
// }
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFont()->setBold(true);
// $summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('ffc000');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$summarySheet->getRowDimension($sumRow)->setRowHeight(20);
$sumOverallTotals['N'][] = 'N'.$sumRow;
$sumOverallTotals['O'][] = 'O'.$sumRow;
$sumOverallTotals['Y'][] = 'Y'.$sumRow;
$sumOverallTotals['Z'][] = 'Z'.$sumRow;
$sumRow++;
}
$sumOverallRow = $sumRow+1;
$sumRow = $sumRow+1;
$summarySheet->setCellValue("A". $sumRow, "Overall Total");
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $sumRow)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
$summarySheet->getRowDimension($sumRow)->setRowHeight(20);
$summarySheet->setCellValue("N" . $sumRow, '='.implode('+', $sumOverallTotals['N']));
$summarySheet->setCellValue("O" . $sumRow, '='.implode('+', $sumOverallTotals['O']));
$summarySheet->setCellValue("Y" . $sumRow, '='.implode('+', $sumOverallTotals['Y']));
$summarySheet->setCellValue("Z" . $sumRow, '='.implode('+', $sumOverallTotals['Z']));
$summarySheet->setCellValue("AB" . $sumRow, '=N'.$sumRow.'-Y'.$sumRow);
$summarySheet->setCellValue("AC" . $sumRow, '=O'.$sumRow.'-Z'.$sumRow);
$summarySheet->setCellValue("AD" . $sumRow,'=IF(N'.$sumRow.'=0, "",(N'.$sumRow. '-Y'.$sumRow.')/N'.$sumRow.')');
$summarySheet->setCellValue("AE" . $sumRow,'=IF(O'.$sumRow.'=0, "",(O'.$sumRow. '-Z'.$sumRow.')/O'.$sumRow.')');
$summarySheet->getStyle("A" . $sumRow . ":" . $summarySheet->getHighestColumn() . $row)->getFont()->setBold(true);
}
$summarySheet->getStyle("P5:P" . $sumOverallRow)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
$summarySheet->setAutoFilter('A5:' . $summarySheet->getHighestColumn() . $summarySheet->getHighestRow());
$summarySheet->getStyle('K2:L' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$($#,##0.00)');
$summarySheet->getStyle('N2:O' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('V2:W' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('Y2:Z' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle('AB2:AC' . $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode('$#,##0.00;$(#,##0.00)');
$summarySheet->getStyle("AD2:AE". $summarySheet->getHighestRow())->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
// Amount Left Invoices
// $unallocatedSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'Amount Left Invoices');
// $spreadsheet->addSheet($unallocatedSheet, 2);
// $unallocatedSheet->setCellValue('A1', 'Invoice');
// $unallocatedSheet->setCellValue('B1', 'Vendor Name');
// $unallocatedSheet->setCellValue('C1', 'Client');
// $unallocatedSheet->setCellValue('D1', 'Project');
// $unallocatedSheet->setCellValue('E1', 'Vendor Qoute');
// $unallocatedSheet->setCellValue('F1', 'Amount USD');
// $unallocatedSheet->setCellValue('G1', 'Allocated USD');
// $unallocatedSheet->setCellValue('H1', 'Amount Left USD');
// $unallocatedSheet->setCellValue('I1', 'Date');
// $unallocatedSheet->setCellValue('J1', 'Due Date');
// $unallocatedSheet->setCellValue('K1', 'Client INV');
// $unallocatedSheet->setCellValue('L1', 'Status');
// $unallocatedSheet->setCellValue('M1', 'Financial Year');
// $lastColx = $unallocatedSheet->getHighestColumn();
// $unallocatedSheet->getDefaultColumnDimension()->setWidth(30);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->setBold(true);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
// $unallocatedSheet->getStyle("A1:".$lastColx."1")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('00000000');
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getFont()->setBold(false);
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setWrapText(true);
// $unallocatedSheet->getStyle("A2:".$lastColx."2")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
// try {
// $currentRow = $unallocatedSheet->getHighestRow();
// $invoiceProjectMap = [];
// foreach ($projectsList as $project) {
// $vendorQuotationPlannings = $project[0]->getVendorQuotationPlannings();
// if ($vendorQuotationPlannings) {
// foreach ($vendorQuotationPlannings as $vendorQuotationPlanning) {
// $vqpInvoices = $vendorQuotationPlanning->getVendorQuotationPlanningVendorInvoices();
// foreach ($vqpInvoices as $vqpInvoice) {
// $vendorInvoice = $vqpInvoice->getVendorInvoice();
// if ($vendorInvoice->getXeroStatus() != 'PAID') continue;
// if (empty($vendorInvoice->getAmountLeftUsd($project[0]))) continue;
// $invoiceId = $vendorInvoice->getVendorInvoiceNo();
// if (!isset($invoiceProjectMap[$invoiceId])) {
// $invoiceProjectMap[$invoiceId] = [
// 'invoice' => $vendorInvoice,
// 'projects' => [],
// 'vendorName' => '',
// 'xeroContact' => null
// ];
// }
// // Add project information
// $invoiceProjectMap[$invoiceId]['projects'][] = [
// 'project' => $vendorQuotationPlanning->getProject(),
// 'client' => $vendorQuotationPlanning->getProject()->getClient(),
// 'vendorQuotationPlanning' => $vendorQuotationPlanning,
// 'amount' => $vqpInvoice->getAmountUsd(),
// ];
// }
// }
// }
// }
// // Second pass: Write to spreadsheet with merged cells for same invoice
// foreach ($invoiceProjectMap as $invoiceId => $data) {
// $vendorInvoice = $data['invoice'];
// $projects = $data['projects'];
// $startRow = $currentRow;
// // Get vendor name
// $xeroContact = $this->xeroContactRepository->findOneBy(['xeroContactId' => $vendorInvoice->getXeroContactId()]);
// $vendorName = '';
// if ($vendorInvoice->getXeroContactId()) {
// $vendorName = $xeroContact ? "[".$xeroContact->getName()."]" : null;
// } else {
// $vendorName = $vendorInvoice->getVendor()->getName();
// }
// // Get client invoices
// $clientInvoices = [];
// if (!empty($vendorInvoice->getInvoiceVendorInvoices()->toArray())) {
// foreach ($vendorInvoice->getInvoiceVendorInvoices()->toArray() as $invVendorI) {
// $clientInv = $invVendorI->getInvoice()->getInvoiceNo();
// array_push($clientInvoices, $clientInv);
// }
// }
// // Write data for each project
// foreach ($projects as $index => $projectData) {
// $project = $projectData['project'];
// // Write project-specific information
// $unallocatedSheet->setCellValue('C' . $currentRow, $project->getClient()->getName());
// $unallocatedSheet->setCellValue('D' . $currentRow, $project->fullName());
// // Set project hyperlink
// $unallocatedSheet->getCell('D' . $currentRow)->getHyperlink()->setUrl($baseurl . '/project-management/project/view/' . $project->getId());
// $unallocatedSheet->getStyle('D' . $currentRow)->getFont()->setUnderline(true);
// // Write amount for this project
// $unallocatedSheet->setCellValue('G' . $currentRow, $projectData['amount']);
// // For the first project entry, write the shared invoice information
// if ($index === 0) {
// $unallocatedSheet->setCellValue('A' . $currentRow, $vendorInvoice->getVendorInvoiceNo() ?: '-');
// $unallocatedSheet->setCellValue('B' . $currentRow, $vendorName);
// $unallocatedSheet->setCellValue('F' . $currentRow, $vendorInvoice->getSubTotalUsd());
// $unallocatedSheet->setCellValue('H' . $currentRow, $vendorInvoice->getAmountLeftUsd());
// $unallocatedSheet->setCellValue('I' . $currentRow, $vendorInvoice->getInvoiceDate()->format("d M Y"));
// $unallocatedSheet->setCellValue('J' . $currentRow, $vendorInvoice->getDueDate()->format("d M Y"));
// $unallocatedSheet->setCellValue('K' . $currentRow, $clientInvoices ? implode(';', $clientInvoices) : '-');
// $unallocatedSheet->setCellValue('L' . $currentRow, 'PAID');
// $unallocatedSheet->setCellValue('M' . $currentRow, $vendorInvoice->getFinancialYear());
// }
// // Handle vendor quotes
// if ($projectData['vendorQuotationPlanning']) {
// $vendorQuotations = $projectData['vendorQuotationPlanning']->getVendorQuotations() ?? null;
// if (!empty($vendorQuotations)) {
// foreach($vendorQuotations as $vendorQoute){
// $unallocatedSheet->setCellValue('E' . $row, $vendorQoute->getAmountUsd());
// $currentRow++;
// }
// } else {
// $unallocatedSheet->setCellValue('E' . $currentRow, "-");
// }
// } else {
// $unallocatedSheet->setCellValue('E' . $currentRow, "-");
// }
// $currentRow++;
// }
// // If we have multiple projects, merge the shared invoice cells
// if (count($projects) > 1) {
// $endRow = $currentRow - 1;
// $columnsToMerge = ['A', 'B', 'F', 'H', 'I', 'J', 'K', 'L', 'M'];
// foreach ($columnsToMerge as $column) {
// if ($startRow < $endRow) {
// $unallocatedSheet->mergeCells($column . $startRow . ':' . $column . $endRow);
// $unallocatedSheet->getStyle($column . $startRow . ':' . $column . $endRow)
// ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
// }
// }
// }
// }
// } catch (\Exception $e) {
// dd($e->getMessage());
// }
// $unallocatedSheet->setAutoFilter('A1:'. $unallocatedSheet->getHighestColumn() . $unallocatedSheet->getHighestRow());
// $unallocatedSheet->getStyle('E2:H' . $unallocatedSheet->getHighestRow())->getNumberFormat()->setFormatCode('#,##0.00;(#,##0.00)');
// Write the file
$writer = new Xlsx($spreadsheet);
$writer->save($filename);
if ($_target == 'google') {
$gsheetURL = $this->googleDriveService->uploadToGoogleDrive($filename);
if ($gsheetURL) {
unlink($filename);
return new RedirectResponse($gsheetURL, 302);
}
} else {
$response = new Response();
$response->headers->set('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
$response->setContent(file_get_contents($filename));
$response->setStatusCode(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
$response->headers->set('Content-Transfer-Encoding', 'binary');
$response->headers->set('Pragma', 'no-cache');
$response->headers->set('Expires', '0');
unlink($filename);
return $response;
exit;
}
}
public function getProjectLeadStatus($leadId)
{
return $this->projectLeadStatusRepository->findOneBy(['lead' => $leadId]);
}
public function generateRevenuePlanning($project, $force = false)
{
$result['status'] = 'OK';
$estimatedProfit = $project->getEstimatedProfit() ?: null;
$estimatedProfitUsd = $project->getEstimatedProfitUsd() ?: null;
$startDate = $project->getStartDate() ? new \DateTime($project->getStartDate()->format('Y-m-d H:i:s')) : null;
if ($startDate) {
$startDate->modify('first day of this month');
}
$endDate = $project->getEndDate() ? new \DateTime($project->getEndDate()->format('Y-m-d H:i:s')) : null;
if (is_null($estimatedProfit) || is_null($estimatedProfitUsd)) {
$result['status'] = 'ERROR';
$result['message'] = 'Please provide Project <b>Estimated Agency Revenue</b> to use this feature.';
$result['data'] = null;
return $result;
}
if (is_null($startDate) || is_null($endDate)) {
$result['status'] = 'ERROR';
$result['message'] = 'Please provide Project <b>Start Date</b> and Project <b>End Date</b> to use this feature.';
$result['data'] = null;
return $result;
}
$currentRevenuePlannings = $project->getRevenuePlannings()->toArray();
$dateInterval = $endDate->diff($startDate);
// $numMonths = ($dateInterval->y * 12) + $dateInterval->m + 1;
$yearsInMonths = $dateInterval->y * 12;
$months = $dateInterval->m;
$days = $dateInterval->d;
if ($days > 0) {
$months++;
}
$numMonths = $yearsInMonths + $months;
$entityManager = $this->entityManager;
// Calculate the average amount for each month
// $averageAmount = $numMonths > 0 ? floatval($estimatedProfit / $numMonths) : 0;
// $averageAmountUsd = $numMonths > 0 ? floatval($estimatedProfitUsd / $numMonths) : 0;
$averageAmount = $numMonths > 0 ? floor($estimatedProfit / $numMonths) : 0;
$averageAmountUsd = $numMonths > 0 ? floor($estimatedProfitUsd / $numMonths) : 0;
$differenceAmount = $estimatedProfit - ($averageAmount * $numMonths);
$differenceAmountUsd = $estimatedProfitUsd - ($averageAmountUsd * $numMonths);
if (empty($currentRevenuePlannings)) {
for ($i = 0; $i < $numMonths; $i++) {
$currentMonth = $startDate->format('m');
$currentYear = $startDate->format('Y');
$revenuePlanning = new RevenuePlanning();
if ($i === ($numMonths - 1)) {
$amount = $averageAmount + $differenceAmount;
$amountUsd = $averageAmountUsd + $differenceAmountUsd;
} else {
$amount = $averageAmount;
$amountUsd = $averageAmountUsd;
}
$revenuePlanning
->setMonth($currentMonth)
->setYear($currentYear)
->setAmount($amount)
->setAmountUsd($amountUsd)
->setCreatedAt(new \DateTimeImmutable())
->setProject($project);
$entityManager->persist($revenuePlanning);
$currentRevenuePlannings[] = $revenuePlanning;
$startDate->add(new \DateInterval('P1M'));
}
$entityManager->flush();
$project = $this->projectRepository->find($project->getId());
$entityManager->refresh($project);
$result['data'] = $project;
return $result;
}
$totalAmount = array_sum(array_map(fn($entry) => $entry->getAmount(), $currentRevenuePlannings));
if (!empty($currentRevenuePlannings) && ($force === true || $totalAmount == 0)) {
$i = 0;
foreach ($currentRevenuePlannings as $entry) {
if ($i === ($numMonths - 1)) {
$entry->setAmount($averageAmount + $differenceAmount);
$entry->setAmountUsd($averageAmountUsd + $differenceAmountUsd);
} else {
$entry->setAmount($averageAmount);
$entry->setAmountUsd($averageAmountUsd);
}
$i++;
}
$entityManager->flush();
$project = $this->projectRepository->find($project->getId());
$entityManager->refresh($project);
$result['data'] = $project;
return $result;
}
// Check if the number of months has been reduced
if (count($currentRevenuePlannings) > $numMonths) {
$startDateClone = clone $startDate;
$endDateClone = clone $endDate;
foreach ($currentRevenuePlannings as $entry) {
$entryMonth = intval($entry->getMonth());
$entryYear = intval($entry->getYear());
$entryDate = new \DateTime("$entryYear-$entryMonth-01");
if ($entryDate >= $startDateClone && $entryDate <= $endDateClone) continue;
$entityManager->remove($entry);
}
$entityManager->flush();
$currentRevenuePlannings = $this->revenuePlanningRepository->findBy(['project' => $project]);
}
// Calculate the total sum of existing amounts
$totalExistingAmount = 0;
$totalExistingAmountUsd = 0;
foreach ($currentRevenuePlannings as $existingEntry) {
$totalExistingAmount += $existingEntry->getAmount();
$totalExistingAmountUsd += $existingEntry->getAmountUsd();
}
// Calculate the remaining amount to distribute or deduct
// $remainingAmount = $estimatedProfit - $totalExistingAmount;
// $remainingAmountUsd = $estimatedProfitUsd - $totalExistingAmountUsd;
// Update or create Revenue Planning entries based on the number of months
for ($i = 0; $i < $numMonths; $i++) {
$currentMonth = $startDate->format('m');
$currentYear = $startDate->format('Y');
$matchingEntry = null;
foreach ($currentRevenuePlannings as $existingEntry) {
if ($existingEntry->getMonth() === $currentMonth && $existingEntry->getYear() === $currentYear) {
$matchingEntry = $existingEntry;
break;
}
}
if (!$matchingEntry) {
// Create new entry with 0 value
$revenuePlanning = new RevenuePlanning();
$revenuePlanning
->setMonth($currentMonth)
->setYear($currentYear)
->setAmount(0)
->setAmountUsd(0)
->setCreatedAt(new \DateTimeImmutable())
->setProject($project);
$entityManager->persist($revenuePlanning);
$currentRevenuePlannings[] = $revenuePlanning;
}
$startDate->add(new \DateInterval('P1M'));
}
/*
// Distribute remaining amount if numMonths increased
if ($numMonths > count($currentRevenuePlannings)) {
foreach ($currentRevenuePlannings as $entry) {
if ($remainingAmount <= 0) {
break;
}
$entry->setAmount($entry->getAmount() + 1);
$remainingAmount--;
}
}
// Distribute remaining USD amount if numMonths increased
if ($numMonths > count($currentRevenuePlannings)) {
foreach ($currentRevenuePlannings as $entry) {
if ($remainingAmountUsd <= 0) {
break;
}
$entry->setAmountUsd($entry->getAmountUsd() + 1);
$remainingAmountUsd--;
}
}
// Remove or update amounts if numMonths decreased
if ($numMonths < count($currentRevenuePlannings)) {
$lastEntry = end($currentRevenuePlannings);
$lastEntry->setAmount($lastEntry->getAmount() + $remainingAmount);
$lastEntry->setAmountUsd($lastEntry->getAmountUsd() + $remainingAmountUsd);
array_pop($currentRevenuePlannings); // Remove the last entry if numMonths decreased
}
*/
$entityManager->flush();
$project = $this->projectRepository->find($project->getId());
$entityManager->refresh($project);
$result['data'] = $project;
return $result;
}
public function calculateIncludedMonths($startDate, $endDate)
{
$currentDate = new \DateTime();
$currentMonth = (int) $currentDate->format('m'); // 8
$currentYear = (int) $currentDate->format('Y'); // 2023
$fytdStartMonth = 11; // November
$fytdEndMonth = 10; // October
// Adjust the fiscal year based on the current month
$fytdYear = ($currentMonth < $fytdStartMonth) ? $currentYear - 1 : $currentYear;
$fytdStartDate = new \DateTime();
$fytdStartDate->setDate($fytdYear, $fytdStartMonth, 1);
$fytdEndDate = new \DateTime();
$fytdEndDate->setDate($fytdYear + 1, $fytdEndMonth, 31);
// Convert start and end dates to DateTime objects
// $start = new \DateTime($startDate);
// $end = new \DateTime($endDate);
$start = $startDate;
$end = $endDate;
$includedMonths = 0;
// Iterate through months and check if they are within FYTD
while ($start <= $end) {
if ($start >= $fytdStartDate && $start <= $fytdEndDate) {
$includedMonths++;
}
$start->modify('+1 month');
}
return $includedMonths;
}
public function getEmailLogFeedback($emailPic, $title)
{
$emailLogs = $this->emailCollectorRepository->findByToAddressAndTitle($emailPic, $title);
return $emailLogs;
}
}