Skip to content

Commit

Permalink
Merge pull request #511 from wri/release/queenly-queenwood
Browse files Browse the repository at this point in the history
[RELEASE] Queenly Queenwood
  • Loading branch information
roguenet authored Oct 21, 2024
2 parents 8feffb4 + 3c52b1d commit 7a4795d
Show file tree
Hide file tree
Showing 36 changed files with 678 additions and 15 deletions.
8 changes: 5 additions & 3 deletions app/Console/Commands/BulkWorkdayImport.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function handle(): void
$parseErrors = [];
while ($csvRow = fgetcsv($fileHandle)) {
try {
$rows->push($this->parseRow($csvRow));
$rows->push($this->parseRow($csvRow, $parseErrors));
} catch (AbortException $e) {
$parseErrors[] = $e;
}
Expand Down Expand Up @@ -224,7 +224,7 @@ protected function getColumnDescription($header): ?array
/**
* @throws AbortException
*/
protected function parseRow($csvRow): ?array
protected function parseRow($csvRow, &$parseErrors): ?array
{
$row = [];
foreach ($csvRow as $index => $cell) {
Expand Down Expand Up @@ -304,7 +304,9 @@ protected function parseRow($csvRow): ?array
'totals' => $totals,
], JSON_PRETTY_PRINT) . "\n";

$this->abort($message, ExceptionLevel::Warning);
// We've decided go ahead and import unbalanced collections, but we do want to make sure we still
// log the error in sequence with the rest.
$parseErrors[] = new AbortException(ExceptionLevel::Warning, $message, 1);
}
}

Expand Down
67 changes: 67 additions & 0 deletions app/Console/Commands/OneOff/UpdatePPCDueDatesCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

namespace App\Console\Commands\OneOff;

use App\Models\V2\Tasks\Task;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class UpdatePPCDueDatesCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'one-off:update:ppc-due-dates';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Update due dates shown on PPC reports.';

/**
* Execute the console command.
*/
public function handle()
{
Log::info('update ppc due dates');

$tasks = Task::whereHas('project', function ($query) {
$query->where('framework_key', 'ppc');
})->get();
foreach ($tasks as $task) {
$project = $task->project;
if ($project && $project->framework_key == 'ppc') {
$dueAt = Carbon::parse($task->due_at)->setTimezone('UTC');

if ($dueAt->hour >= 0 && $dueAt->hour <= 4) {
$task->due_at = $dueAt->setHour(5);
$task->save();
}
}

$reports = collect([$task->projectReport])->concat($task->siteReports)->concat($task->nurseryReports)->filter(function ($report) {
return $report !== null;
});

foreach ($reports as $report) {
if ($report->framework_key !== 'ppc') {
continue;
}
$dueAt = Carbon::parse($report->due_at)->setTimezone('UTC');
if ($dueAt->hour >= 0 && $dueAt->hour <= 4) {
$report->due_at = $dueAt->setHour(5);
$report->save();
}
}
}

$this->info('All due dates updated successfully.');

return 0;
}
}
14 changes: 12 additions & 2 deletions app/Helpers/TerrafundDashboardQueryHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,21 @@ public static function buildQueryFromRequest($request)
$query = QueryBuilder::for(Project::class)
->join('organisations', 'v2_projects.organisation_id', '=', 'organisations.id')
->select('v2_projects.*')
->where('v2_projects.status', 'approved')
->whereIn('organisations.type', ['non-profit-organization', 'for-profit-organization'])
->whereIn('v2_projects.framework_key', ['terrafund', 'terrafund-landscapes'])
->allowedFilters([
AllowedFilter::exact('framework_key'),
AllowedFilter::exact('landscape'),
AllowedFilter::callback('landscapes', function ($query, $value) {
$query->whereIn('landscape', $value);
}),
AllowedFilter::exact('country'),
AllowedFilter::exact('organisations.type'),
AllowedFilter::callback('organisations.type', function ($query, $value) {
$query->whereIn('organisations.type', $value);
}),
AllowedFilter::callback('programmes', function ($query, $value) {
$query->whereIn('framework_key', $value);
}),
AllowedFilter::exact('v2_projects.status'),
AllowedFilter::exact('v2_projects.uuid'),
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public function getAllCountries($request)

$totalNurseries = $this->numberOfNurseries($country->slug, $projects);

$totalHectaresRestored = round($this->getTotalHectaresSum($country->slug, $projects));

$activeCountries[] = [
'country_slug' => $country->slug,
'country' => $country->label,
Expand All @@ -51,6 +53,7 @@ public function getAllCountries($request)
'total_jobs_created' => $totalJobsCreated,
'number_of_sites' => $numberOfSites,
'number_of_nurseries' => $totalNurseries,
'hectares_restored' => $totalHectaresRestored,
];
}

Expand Down Expand Up @@ -101,4 +104,13 @@ public function numberOfNurseries($country, $projects)

return Nursery::whereIn('project_id', $projectIds)->count();
}

public function getTotalHectaresSum($country, $projects)
{
$projects = $projects->where('country', $country);

return $projects->sum(function ($project) {
return $project->sitePolygons->sum('calc_area');
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public function getAllProjects($request, $perPage, $page)
'country_slug' => $project->country,
'number_of_trees_goal' => $project->trees_grown_goal,
'date_added' => $project->created_at,
'hectares_under_restoration' => round($project->sitePolygons->sum('calc_area')),
];
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public function __invoke(Request $request)
{
$projects = TerrafundDashboardQueryHelper::buildQueryFromRequest($request)->get();
$countryName = '';
if (data_get($request, 'filter.country')) {
$countryName = WorldCountryGeneralized::where('iso', $request['filter']['country'])->first()->country;
if ($country = data_get($request, 'filter.country')) {
$countryName = WorldCountryGeneralized::where('iso', $country)->first()->country;
}
$response = (object)[
'total_non_profit_count' => $this->getTotalNonProfitCount($projects),
Expand All @@ -30,6 +30,25 @@ public function __invoke(Request $request)
return response()->json($response);
}

public function getTotalDataForCountry(Request $request)
{
$projects = TerrafundDashboardQueryHelper::buildQueryFromRequest($request)->get();
$countryName = '';
if ($country = data_get($request, 'filter.country')) {
$countryName = WorldCountryGeneralized::where('iso', $country)->first()->country;
}
$response = (object)[
'total_non_profit_count' => $this->getTotalNonProfitCount($projects),
'total_enterprise_count' => $this->getTotalEnterpriseCount($projects),
'total_entries' => $this->getTotalJobsCreatedSum($projects),
'total_hectares_restored' => round($this->getTotalHectaresSum($projects)),
'total_trees_restored' => $this->getTotalTreesRestoredSum($projects),
'country_name' => $countryName,
];

return response()->json($response);
}

public function getTotalNonProfitCount($projects)
{
$projects = $projects->filter(function ($project) {
Expand Down
26 changes: 26 additions & 0 deletions app/Http/Controllers/V2/Dashboard/ViewProjectController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Helpers\TerrafundDashboardQueryHelper;
use App\Http\Controllers\Controller;
use App\Models\Framework;
use App\Models\V2\Projects\Project;
use App\Models\V2\Projects\ProjectInvite;
use App\Models\V2\User;
Expand Down Expand Up @@ -133,4 +134,29 @@ public function getAllProjectsAllowedToUser()
return response()->json(['error' => 'An error occurred while fetching the data', 'message' => $errorMessage], 500);
}
}

public function getFrameworks($request = null)
{
if ($request === null) {
$request = request();
}

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

$frameworkKeys = $baseQuery->distinct()->pluck('framework_key')->toArray();

$frameworks = Framework::whereIn('slug', $frameworkKeys)
->select('name', 'slug')
->get();

$frameworksResponse = [];
foreach ($frameworks as $framework) {
$frameworksResponse[] = [
'framework_slug' => $framework->slug,
'name' => $framework->name,
];
}

return $frameworksResponse;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use App\Models\V2\Sites\Site;
use App\Models\V2\Sites\SiteReport;
use App\Models\V2\TreeSpecies\TreeSpecies;
use App\StateMachines\EntityStatusStateMachine;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
Expand Down Expand Up @@ -78,7 +77,7 @@ private function getAllProjectIds($projectIds)

private function getSiteIds($projectIds)
{
return Site::whereIn('project_id', $projectIds)->where('status', EntityStatusStateMachine::APPROVED)->pluck('id');
return Site::whereIn('project_id', $projectIds)->whereIn('status', Site::$approvedStatuses)->pluck('id');
}

private function getDistinctDates($siteIds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function store(StoreFundingProgrammeRequest $storeFundingProgrammeRequest
$fundingProgramme = FundingProgramme::create($storeFundingProgrammeRequest->validated());
$fundingProgramme->name_id = I18nHelper::generateI18nItem($fundingProgramme, 'name');
$fundingProgramme->description_id = I18nHelper::generateI18nItem($fundingProgramme, 'description');
$fundingProgramme->location_id = I18nHelper::generateI18nItem($fundingProgramme, 'location');
$fundingProgramme->save();

return new FundingProgrammeResource($fundingProgramme);
Expand All @@ -57,6 +58,7 @@ public function update(UpdateFundingProgrammeRequest $updateFundingProgrammeRequ
$fundingProgramme->update($updateFundingProgrammeRequest->validated());
$fundingProgramme->name_id = I18nHelper::generateI18nItem($fundingProgramme, 'name');
$fundingProgramme->description_id = I18nHelper::generateI18nItem($fundingProgramme, 'description');
$fundingProgramme->location_id = I18nHelper::generateI18nItem($fundingProgramme, 'location');
$fundingProgramme->save();

return new FundingProgrammeResource($fundingProgramme);
Expand Down
2 changes: 1 addition & 1 deletion app/Http/Resources/V2/Forms/FormResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function toArray($request)
'documentation' => $this->documentation,
'documentation_label' => $this->documentation_label,
'deadline_at' => $this->deadline_at ? Carbon::parse($this->deadline_at, 'EST')->toISOString() : null,
'submission_message' => $this->submission_message,
'submission_message' => $this->translated_submission_message,
'published' => $this->published,
'stage_id' => $this->stage_id,
'form_sections' => (new FormSectionCollection($this->sections))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function toArray($request)
'uuid' => $this->uuid,
'name' => $this->translated_name,
'description' => $this->translated_description,
'location' => $this->location,
'location' => $this->translated_location,
'read_more_url' => $this->read_more_url,
'framework_key' => $this->framework_key,
'status' => $this->status,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function toArray($request)
'uuid' => $this->uuid,
'name' => $this->translated_name,
'description' => $this->translated_description,
'location' => $this->location,
'location' => $this->translated_location,
'read_more_url' => $this->read_more_url,
'framework_key' => $this->framework_key,
'deadline_at' => $deadline ? Carbon::parse($deadline, 'EST')->toISOString() : null,
Expand Down
16 changes: 13 additions & 3 deletions app/Models/Traits/HasWorkdays.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ trait HasWorkdays
{
public static function bootHasWorkdays()
{
collect([static::WORKDAY_COLLECTIONS['paid'], static::WORKDAY_COLLECTIONS['volunteer']])
collect([static::WORKDAY_COLLECTIONS['paid'], static::WORKDAY_COLLECTIONS['volunteer'], static::WORKDAY_COLLECTIONS['finance']])
->flatten()
->each(function ($collection) {
self::resolveRelationUsing(
Expand Down Expand Up @@ -72,10 +72,20 @@ public function setOtherWorkdaysDescriptionAttribute(?string $value): void

protected function sumTotalWorkdaysAmounts(array $collections): int
{
// Assume that the types are balanced, and just return the value from `gender`
// Gender is considered the canonical total value for all current types of workdays, so just pull and sum gender.
return WorkdayDemographic::whereIn(
'workday_id',
$this->workdays()->visible()->collections($collections)->select('id')
)->gender()->sum('amount');
)
->gender()
->with('workday')
->get()
->groupBy(function ($demographic) {
return $demographic->workday->collection . '_' . $demographic->name;
})
->map(function ($group) {
return $group->first();
})
->sum('amount');
}
}
11 changes: 11 additions & 0 deletions app/Models/V2/Forms/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ class Form extends Model implements MediaModel
'documentation',
'documentation_label',
'submission_message',
'submission_message_id',
'framework_key',
'model',
'duration',
Expand Down Expand Up @@ -161,4 +162,14 @@ public function getTranslatedDescriptionAttribute(): ?string
{
return $this->getTranslation('i18nDescription', 'description');
}

public function i18nSubmissionMessage(): BelongsTo
{
return $this->belongsTo(I18nItem::class, 'submission_message_id', 'id');
}

public function getTranslatedSubmissionMessageAttribute(): ?string
{
return $this->getTranslation('i18nSubmissionMessage', 'submission_message');
}
}
11 changes: 11 additions & 0 deletions app/Models/V2/FundingProgramme.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class FundingProgramme extends Model implements MediaModel
'name_id',
'status',
'location',
'location_id',
'read_more_url',
'description',
'description_id',
Expand Down Expand Up @@ -98,6 +99,16 @@ public function i18nDescription(): BelongsTo
return $this->belongsTo(I18nItem::class, 'description_id', 'id');
}

public function i18nLocation(): BelongsTo
{
return $this->belongsTo(I18nItem::class, 'location_id', 'id');
}

public function getTranslatedLocationAttribute(): ?string
{
return $this->getTranslation('i18nLocation', 'location');
}

public function applications(): HasMany
{
return $this->hasMany(Application::class, 'funding_programme_uuid', 'uuid');
Expand Down
4 changes: 4 additions & 0 deletions app/Models/V2/Projects/ProjectReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,10 @@ class ProjectReport extends Model implements MediaModel, AuditableContract, Repo
Workday::COLLECTION_PROJECT_PAID_OTHER,
Workday::COLLECTION_PROJECT_VOLUNTEER_OTHER,
],
'finance' => [
Workday::COLLECTION_PROJECT_DIRECT,
Workday::COLLECTION_PROJECT_CONVERGENCE,
],
];

public function registerMediaConversions(Media $media = null): void
Expand Down
4 changes: 4 additions & 0 deletions app/Models/V2/Sites/SiteReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ class SiteReport extends Model implements MediaModel, AuditableContract, ReportM
Workday::COLLECTION_SITE_PAID_OTHER,
Workday::COLLECTION_SITE_VOLUNTEER_OTHER,
],
'finance' => [
Workday::COLLECTION_PROJECT_DIRECT,
Workday::COLLECTION_PROJECT_CONVERGENCE,
],
];

public function registerMediaConversions(Media $media = null): void
Expand Down
Loading

0 comments on commit 7a4795d

Please sign in to comment.