Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TM-617, 626, 627, 658] feat: add tree restoration controller and export csv #237

Merged
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
4caec5a
[TM-658] export dashboard
cesarLima1 May 28, 2024
8149577
[TM-626] start up restoration strategies controller
cesarLima1 May 28, 2024
fc38a1a
[TM-617] start up tree restoration goal controller
cesarLima1 May 28, 2024
46b6035
fix lint
cesarLima1 May 28, 2024
9b7c14f
[TM-621] add definition for jobs created controller
cesarLima1 May 28, 2024
0df4d69
[TM-626] add definition for restoration strategies controller
cesarLima1 May 28, 2024
e6d7889
[TM-617] add definition for tree restoartion goal controller
cesarLima1 May 28, 2024
132bf4a
[TM-658] add definition for project list export controller
cesarLima1 May 28, 2024
56e7bf0
[TM-671] return polygons, project and country data
egrojMonroy May 29, 2024
068400b
Merge branch 'feat/TM-621_dashboard_jobs_created' into feat/TM-617/62…
cesarLima1 Jun 4, 2024
e558598
Merge branch 'feat/TM-617/626/627/658_tree_restoration_and_export' in…
egrojMonroy Jun 4, 2024
99d84ae
[TM-671] improve queries, remove superfluos code, update Project mode…
egrojMonroy Jun 4, 2024
1310d57
[TM-671] remove inappropiate code, make more idiomatic uses of queries
egrojMonroy Jun 4, 2024
21fb955
return fillable values from staging
egrojMonroy Jun 5, 2024
b4cc8f1
Merge branch 'staging' into feat/TM-617/626/627/658_tree_restoration_…
cesarLima1 Jun 6, 2024
b256cbc
[TM-617, 626, 627, 658] remove unnecesary class for activeprojecttabl…
egrojMonroy Jun 6, 2024
1e1c5b7
Merge branch 'feat/TM-617/626/627/658_tree_restoration_and_export' of…
egrojMonroy Jun 6, 2024
89caf9f
[TM-617, 626, 627, 658] remove unnecesary parse of class
egrojMonroy Jun 6, 2024
2881584
[TM-617, 626, 627, 658] move to constant of the class
egrojMonroy Jun 6, 2024
62779f6
[TM-617, 626, 627, 658] add filter for approved and submitted in PROJ…
egrojMonroy Jun 6, 2024
09d30cc
[TM-617, 626, 627, 658] add filter for approved only in PROJECT REPORT
egrojMonroy Jun 6, 2024
597ed1f
Merge pull request #240 from wri/feat/TM-671_polygons_country_project
cesarLima1 Jun 6, 2024
0b4de85
Merge branch 'staging' into feat/TM-617/626/627/658_tree_restoration_…
cesarLima1 Jun 6, 2024
a5438ab
[TM-617] make lint fix
cesarLima1 Jun 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions app/Helpers/TerrafundDashboardQueryHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace App\Helpers;

use App\Models\V2\Projects\Project;
use App\Models\V2\Sites\SitePolygon;

class TerrafundDashboardQueryHelper
{
public static function buildQueryFromRequest($request)
{
$query = Project::where('framework_key', 'terrafund')
->whereHas('organisation', function ($query) {
$query->whereIn('type', ['for-profit-organization', 'non-profit-organization']);
});
if ($request->has('country')) {
$country = $request->input('country');
$query = $query->where('country', $country);
} elseif ($request->has('uuid')) {
$projectId = $request->input('uuid');
$query = $query->where('v2_projects.uuid', $projectId);
}

return $query;
}

public static function getPolygonIdsOfProject($request)
{
$projectIds = TerrafundDashboardQueryHelper::buildQueryFromRequest($request)
->pluck('uuid');
$polygonsIds = SitePolygon::whereHas('site.project', function ($query) use ($projectIds) {
$query->whereIn('uuid', $projectIds);
})->pluck('poly_id');

return $polygonsIds;
}

public static function getPolygonsByStatusOfProject($request)
{
$projectIds = TerrafundDashboardQueryHelper::buildQueryFromRequest($request)
->pluck('uuid');

$statuses = ['Needs More Info', 'Submitted', 'Approved'];

$polygons = [];

foreach ($statuses as $status) {
// Get polygons of the project filtered by status
$polygonsOfProject = SitePolygon::whereHas('site.project', function ($query) use ($projectIds) {
$query->whereIn('uuid', $projectIds);
})
->where('status', $status)
->pluck('poly_id');

$polygons[$status] = $polygonsOfProject;
}

return $polygons;
}
}
116 changes: 116 additions & 0 deletions app/Http/Controllers/V2/Dashboard/ActiveProjectsTableController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Helpers\TerrafundDashboardQueryHelper;
use App\Http\Controllers\Controller;
use App\Models\V2\Forms\FormOptionList;
use App\Models\V2\Forms\FormOptionListOption;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class ActiveProjectsTableController extends Controller
{
public function __invoke(Request $request)
{
$perPage = $request->input('per_page', PHP_INT_MAX);
$page = $request->input('page', 1);

$projects = $this->getAllProjects($request, $perPage, $page);
$count = $this->getQuery($request)->count();

return response()->json([
'current_page' => $page,
'data' => $projects,
'per_page' => $perPage,
'last_page' => ceil($count / $perPage),
'total' => $count,
]);
}

public function getQuery($request)
{
return TerrafundDashboardQueryHelper::buildQueryFromRequest($request)
->with('organisation')
->withCount(['sites', 'nurseries']);
}

public function getAllProjects($request, $perPage, $page)
{
$query = $this->getQuery($request)
->skip(($page - 1) * $perPage)
->take($perPage);

$projects = $query->get();

return $projects->map(function ($project) {
return [
'uuid' => $project->uuid,
'name' => $project->name,
'organisation' => $project->organisation->name,
'trees_under_restoration' => $this->treesUnderRestoration($project),
'jobs_created' => $this->jobsCreated($project),
'volunteers' => $this->volunteers($project),
'beneficiaries' => $this->beneficiaries($project),
'survival_rate' => $project->survival_rate,
'number_of_sites' => $project->sites_count,
'number_of_nurseries' => $project->nurseries_count,
'project_country' => $this->projectCountry($project->country),
'country_slug' => $project->country,
'number_of_trees_goal' => $project->trees_grown_goal,
'date_added' => $project->created_at,
];
});
}

public function treesUnderRestoration($project)
{
return $project->trees_planted_count;
}

public function jobsCreated($project)
{
$projectReport = $project->reports()
->selectRaw('SUM(ft_total) as total_ft, SUM(pt_total) as total_pt')
->groupBy('project_id')
->first();

if ($projectReport) {
return $projectReport->total_ft + $projectReport->total_pt;
} else {
return 0;
}
}

public function volunteers($project)
{
$totalVolunteers = $project->reports()->selectRaw('SUM(volunteer_total) as total')->first();

return $totalVolunteers ? intval($totalVolunteers->total) : 0;
}

public function beneficiaries($project)
{
$totalBeneficiaries = $project->reports()->selectRaw('SUM(beneficiaries) as total')->first();

return $totalBeneficiaries ? intval($totalBeneficiaries->total) : 0;
}

public function projectCountry($slug)
{
$countryId = FormOptionList::where('key', 'countries')->value('id');

return FormOptionListOption::where('form_option_list_id', $countryId)
->where('slug', $slug)
->value('label');
}

public function paginate($items, $perPage = 10, $page = null, $options = [])
{
$page = $page ?: (LengthAwarePaginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);

return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
}
115 changes: 115 additions & 0 deletions app/Http/Controllers/V2/Dashboard/GetJobsCreatedController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Helpers\TerrafundDashboardQueryHelper;
use App\Http\Controllers\Controller;
use App\Http\Resources\V2\Dashboard\JobsCreatedResource;
use App\Models\V2\Projects\ProjectReport;
use Illuminate\Http\Request;

class GetJobsCreatedController extends Controller
{
public function __invoke(Request $request): JobsCreatedResource
{

$query = TerrafundDashboardQueryHelper::buildQueryFromRequest($request);

$rawProjectIds = $query
->join('organisations', 'v2_projects.organisation_id', '=', 'organisations.id')
->select('v2_projects.id', 'organisations.type')
->get();

$forProfitProjectIds = $this->filterProjectIdsByType($rawProjectIds, 'for-profit-organization');
$nonProfitProjectIds = $this->filterProjectIdsByType($rawProjectIds, 'non-profit-organization');
$allProjectIds = $this->getAllProjectIds($rawProjectIds);

$forProfitJobsCreated = $this->getTotalJobsCreated($forProfitProjectIds);
$nonProfitJobsCreated = $this->getTotalJobsCreated($nonProfitProjectIds);
$totalJobsCreated = $this->getTotalJobsCreated($allProjectIds);
$jobsCreatedDetailed = $this->getJobsCreatedDetailed($allProjectIds);

$finalResult = (object) [
'totalJobsCreated' => $totalJobsCreated,
'forProfitJobsCreated' => $forProfitJobsCreated,
'nonProfitJobsCreated' => $nonProfitJobsCreated,
'total_ft' => $jobsCreatedDetailed->total_ft,
'total_pt' => $jobsCreatedDetailed->total_pt,
'total_men' => $this->calculateTotalMen($jobsCreatedDetailed),
'total_pt_men' => $jobsCreatedDetailed->total_pt_men,
'total_ft_men' => $jobsCreatedDetailed->total_ft_men,
'total_women' => $this->calculateTotalWomen($jobsCreatedDetailed),
'total_pt_women' => $jobsCreatedDetailed->total_pt_women,
'total_ft_women' => $jobsCreatedDetailed->total_ft_women,
'total_youth' => $this->calculateTotalYouth($jobsCreatedDetailed),
'total_pt_youth' => $jobsCreatedDetailed->total_pt_youth,
'total_ft_youth' => $jobsCreatedDetailed->total_ft_youth,
'total_non_youth' => $this->calculateTotalNonYouth($jobsCreatedDetailed),
'total_pt_non_youth' => $jobsCreatedDetailed->total_pt_non_youth,
'total_ft_non_youth' => $jobsCreatedDetailed->total_ft_non_youth,
];

return new JobsCreatedResource($finalResult);
}

private function filterProjectIdsByType($projectIds, $type)
{
return $projectIds->filter(function ($row) use ($type) {
return $row->type === $type;
})->pluck('id')->toArray();
}

private function getAllProjectIds($projectIds)
{
return $projectIds->pluck('id')->toArray();
}

private function calculateTotalMen($jobsCreatedDetailed)
{
return $jobsCreatedDetailed->total_pt_men + $jobsCreatedDetailed->total_ft_men;
}

private function calculateTotalWomen($jobsCreatedDetailed)
{
return $jobsCreatedDetailed->total_pt_women + $jobsCreatedDetailed->total_ft_women;
}

private function calculateTotalYouth($jobsCreatedDetailed)
{
return $jobsCreatedDetailed->total_pt_youth + $jobsCreatedDetailed->total_ft_youth;
}

private function calculateTotalNonYouth($jobsCreatedDetailed)
{
return $jobsCreatedDetailed->total_pt_non_youth + $jobsCreatedDetailed->total_ft_non_youth;
}

private function getTotalJobsCreated($projectIds)
{
$sumData = ProjectReport::whereIn('project_id', $projectIds)
->where('framework_key', 'terrafund')
->selectRaw('SUM(ft_total) as total_ft, SUM(pt_total) as total_pt')
->first();

return $sumData->total_ft + $sumData->total_pt;
}

private function getJobsCreatedDetailed($projectIds)
{
return ProjectReport::whereIn('project_id', $projectIds)
->where('framework_key', 'terrafund')
->selectRaw(
'SUM(ft_total) as total_ft,
SUM(pt_total) as total_pt,
SUM(pt_men) as total_pt_men,
SUM(ft_men) as total_ft_men,
SUM(pt_women) as total_pt_women,
SUM(ft_women) as total_ft_women,
SUM(pt_youth) as total_pt_youth,
SUM(ft_youth) as total_ft_youth,
SUM(pt_non_youth) as total_pt_non_youth,
SUM(ft_jobs_non_youth) as total_ft_non_youth'
)
->first();
}
}
62 changes: 62 additions & 0 deletions app/Http/Controllers/V2/Dashboard/ProjectListExportController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use League\Csv\Writer;

class ProjectListExportController extends Controller
{
public function __invoke(Request $request)
{
return $this->exportCsv($request);
}

public function exportCsv($request)
{
$activeProjectsController = new ActiveProjectsTableController();
$perPage = $request->input('per_page', PHP_INT_MAX);
$page = $request->input('page', 1);

$projects = $activeProjectsController->getAllProjects($request, $perPage, $page);

$headers = [
'uuid' => 'UUID',
'name' => 'Project Name',
'organisation' => 'Organisation',
'project_country' => 'Country',
'number_of_trees_goal' => 'No. of Trees Goal',
'trees_under_restoration' => 'No. of Trees Restored',
'jobs_created' => 'No. of Jobs Created',
'date_added' => 'Date Added',
'number_of_sites' => 'No. of Sites',
'number_of_nurseries' => 'No. of Nurseries',
];

$filteredProjects = [];
foreach ($projects as $project) {
$filteredProject = [];
foreach ($headers as $key => $label) {
$filteredProject[$key] = $project[$key] ?? '';
}
$filteredProjects[] = $filteredProject;
}

$csv = Writer::createFromString('');

$csv->insertOne(array_values($headers));

foreach ($filteredProjects as $filteredProject) {
$csv->insertOne(array_values($filteredProject));
}

$csvContent = $csv->toString();

return response($csvContent, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename=activeProject.csv',
]);

}
}
Loading