Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
150 changes: 150 additions & 0 deletions src/app/Http/Controllers/ProjectStatsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?php

namespace App\Http\Controllers;

use App\Http\Resources\ProjectStatsResource;
use App\Models\Project;
use App\Models\ProjectStatsView;
use App\Models\Team;
use App\Traits\Rename;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ProjectStatsController extends ResponseController
{
use Rename;

public function show(int $id): JsonResponse
{
try {
$data = DB::select('SELECT * FROM project_stats_view WHERE ProjectId = ?', [$id]);


if (empty($data)) {
return $this->sendError('Not found', 'No statistics exists for this Project yet.');
}

$collection = collect($data);

$summary = $this->buildProjectStatisticsSummary($collection);

$users = [];
$collection->groupBy('UserId')->each(function ($item, $userId) use (&$users) {
$user = $this->buildStatistics($item);
$user['UserId'] = $userId;
$users[] = $user;
});

$teams = $this->buildTeamStatisticsByProject($id);

$grouped = [
'ProjectId' => $id,
'Summary' => $summary,
'Teams' => $teams,
'Users' => $users,
];

$resource = new ProjectStatsResource($grouped);

return $this->sendResponse($resource, 'Projects statistics fetched.');
} catch (\Exception $exception) {
return $this->sendError('Invalid data', $exception->getMessage(), 400);
}
}

protected function buildTeamStatisticsByProject(int $projectId): array
{
$project = Project::findOrFail($projectId);

$teams = Team::query()
->whereExists(function ($query) use ($projectId) {
$query->select(DB::raw(1))
->from('TeamScore as ts')
->join('Score as s', 's.ScoreId', '=', 'ts.ScoreId')
->join('Item as i', 'i.ItemId', '=', 's.ItemId')
->join('Story as st', 'st.StoryId', '=', 'i.StoryId')
->whereColumn('ts.TeamId', 'Team.TeamId')
->where('st.ProjectId', $projectId);
})
->get();

$allTeamsStats = [];

foreach ($teams as $team) {
$teamItemIds = DB::table('TeamScore as ts')
->join('Score as s', 's.ScoreId', '=', 'ts.ScoreId')
->join('Item as i', 'i.ItemId', '=', 's.ItemId')
->join('Story as st', 'st.StoryId', '=', 'i.StoryId')
->where('ts.TeamId', $team->TeamId)
->where('st.ProjectId', $projectId)
->pluck('s.ItemId')
->unique();

$row = ProjectStatsView::query()
->where('ProjectId', $projectId)
->whereIn('ItemId', $teamItemIds)
->selectRaw('
SUM(Locations) AS Locations,
SUM(ManualTranscriptions) AS ManualTranscriptions,
SUM(Enrichments) AS Enrichments,
SUM(Descriptions) AS Descriptions,
SUM(HTRTranscriptions) AS HTRTranscriptions,
SUM(Miles) AS Miles,
COUNT(DISTINCT StoryId) AS Stories,
COUNT(DISTINCT ItemId) AS Items
')
->first();

$allTeamsStats[] = [
'TeamId' => $team->TeamId,
'Locations' => (int) ($row->Locations ?? 0),
'ManualTranscriptions' => (int) ($row->ManualTranscriptions ?? 0),
'Enrichments' => (int) ($row->Enrichments ?? 0),
'Descriptions' => (int) ($row->Descriptions ?? 0),
'HTRTranscriptions' => (int) ($row->HTRTranscriptions ?? 0),
'Stories' => (int) ($row->Stories ?? 0),
'Items' => (int) ($row->Items ?? 0),
'Miles' => (int) ceil($row->Miles ?? 0),
];
}

return $allTeamsStats;
}

protected function emptyTeamStats(int $teamId): array
{
return [
'TeamId' => $teamId,
'Locations' => 0,
'ManualTranscriptions' => 0,
'Enrichments' => 0,
'Descriptions' => 0,
'HTRTranscriptions' => 0,
'Stories' => 0,
'Items' => 0,
'Miles' => 0,
];
}

protected function buildProjectStatisticsSummary(Collection $collection): array
{
$data = $this->buildStatistics($collection);

return $data;
}

protected function buildStatistics(Collection $collection): array
{
return [
'Stories' => $collection->pluck('StoryId')->unique()->count(),
'Items' => $collection->pluck('ItemId')->unique()->count(),
'Locations' => $collection->pluck('Locations')->sum(),
'ManualTranscriptions' => $collection->pluck('ManualTranscriptions')->sum(),
'Enrichments' => $collection->pluck('Enrichments')->sum(),
'Descriptions' => $collection->pluck('Descriptions')->sum(),
'HTRTranscriptions' => $collection->pluck('HTRTranscriptions')->sum(),
'Miles' => ceil($collection->pluck('Miles')->sum()),
];
}
}
13 changes: 13 additions & 0 deletions src/app/Http/Resources/ProjectStatsResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProjectStatsResource extends JsonResource
{
public function toArray($request): array
{
return parent::toArray($request);
}
}
15 changes: 15 additions & 0 deletions src/app/Models/ProjectStatsView.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ProjectStatsView extends Model
{
protected $table = 'project_stats_view';

public $incrementing = false;
public $timestamps = false;

protected $guarded = [];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class() extends Migration {
public function up(): void
{
DB::statement('
CREATE VIEW project_stats_view AS
SELECT
p.ProjectId,
st.StoryId,
s.ItemId,
s.UserId,
SUM(CASE WHEN s.ScoreTypeId = 1 THEN s.Amount ELSE 0 END) AS Locations,
SUM(CASE WHEN s.ScoreTypeId = 2 THEN s.Amount ELSE 0 END) AS ManualTranscriptions,
SUM(CASE WHEN s.ScoreTypeId = 3 THEN s.Amount ELSE 0 END) AS Enrichments,
SUM(CASE WHEN s.ScoreTypeId = 4 THEN s.Amount ELSE 0 END) AS Descriptions,
SUM(CASE WHEN s.ScoreTypeId = 5 THEN s.Amount ELSE 0 END) AS HTRTranscriptions,
ROUND(SUM(s.Amount * stt.Rate) + 0.5, 0) AS Miles
FROM
Project p
JOIN
Story st ON st.ProjectId = p.ProjectId
JOIN
Item i ON i.StoryId = st.StoryId
JOIN
Score s ON s.ItemId = i.ItemId
JOIN
ScoreType stt ON stt.ScoreTypeId = s.ScoreTypeId
GROUP BY
p.ProjectId, st.StoryId, s.ItemId, s.UserId;
');
}

public function down(): void
{
DB::statement('DROP VIEW IF EXISTS project_stats_view');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class() extends Migration {
public function up(): void
{
Schema::create('Team', function (Blueprint $table) {
$table->increments('TeamId');
$table->string('Name', 255);
$table->string('ShortName', 10);
$table->string('Code', 255)->nullable();
$table->string('Description', 255)->nullable();
$table->boolean('EventUser')->default(false);
});
}

public function down(): void
{
Schema::dropIfExists('Team');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class() extends Migration {
public function up(): void
{
Schema::create('TeamUser', function (Blueprint $table) {
$table->unsignedInteger('TeamId');
$table->unsignedInteger('UserId');

$table->primary(['TeamId', 'UserId']);

$table->foreign('TeamId', 'FK_46')
->references('TeamId')
->on('Team')
->onDelete('cascade')
->onUpdate('cascade');

$table->foreign('UserId', 'FK_50')
->references('UserId')
->on('User')
->onDelete('cascade')
->onUpdate('cascade');
});
}

public function down(): void
{
Schema::dropIfExists('TeamUser');
}
};
4 changes: 4 additions & 0 deletions src/routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
use App\Http\Controllers\PlaceController;
use App\Http\Controllers\PersonController;
use App\Http\Controllers\ProjectController;
use App\Http\Controllers\ProjectStatsController;

;
use App\Http\Controllers\PropertyController;
use App\Http\Controllers\SolrController;
use App\Http\Controllers\StoryController;
Expand Down Expand Up @@ -143,6 +146,7 @@
Route::put('/projects/{id}', [ProjectController::class, 'update']);
Route::delete('/projects/{id}', [ProjectController::class, 'destroy']);
Route::get('/projects/{id}/places', [PlaceController::class, 'showByProjectId']);
Route::get('/projects/{id}/statistics', [ProjectStatsController::class, 'show']);

Route::get('/statistics', [StatisticsController::class, 'index']);
Route::get('/statistics/alltime', [StatisticsController::class, 'alltimeIndex']);
Expand Down
4 changes: 3 additions & 1 deletion src/storage/api-docs/api-docs.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
openapi: 3.1.1

info:
version: 2.0.2
version: 2.1.0
title: Transcribathon Platform API v2
description: This is the documentation of the Transcribathon API v2 used by [https:transcribathon.eu](https://transcribathon.eu/).<br />
For authorization you can use the the bearer token you are provided with.
Expand Down Expand Up @@ -182,6 +182,8 @@ paths:
$ref: 'projects-projectId-path.yaml'
/projects/{ProjectId}/places:
$ref: 'projects-projectId-places-path.yaml'
/projects/{ProjectId}/statistics:
$ref: 'projects-projectId-statistics-path.yaml'

/properties:
$ref: 'properties-path.yaml'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
get:
tags:
- statistics
- campaigns
summary: Get stored statistics data of a campaign
- scores
- statistics
summary: Get statistics/scores of a Campaign
description: The returned data is single object
parameters:
- in: path
Expand Down
4 changes: 1 addition & 3 deletions src/storage/api-docs/items-statistics-schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ ItemsStatisticsUserIdsReferenceSchema:
example: 2865

ItemsStatisticsEnrichmentsReferenceSchema:
type: object
description: Object with statistics data of enrichments
properties:
Places:
type: integer
Expand Down Expand Up @@ -80,7 +78,7 @@ ItemsStatisticsGetResponseSchema:
- $ref: '#/ItemsStatisticsMinimalDataReferenceSchema'
- $ref: '#/ItemsStatisticsAdditionalGetReferenceSchema'
- $ref: '#/ItemsStatisticsUserIdsReferenceSchema'
properties:
- properties:
Enrichments:
$ref: '#/ItemsStatisticsEnrichmentsReferenceSchema'

Expand Down
30 changes: 30 additions & 0 deletions src/storage/api-docs/projects-projectId-statistics-path.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
get:
tags:
- scores
- statistics
- projects
summary: Get statistics/scores of a Project
description: The returned data is single object
parameters:
- in: path
name: ProjectId
description: Numeric ID of the entry
type: integer
required: true
responses:
200:
description: Ok
content:
application/json:
schema:
allOf:
- $ref: 'responses.yaml#/BasicSuccessResponse'
- properties:
data:
$ref: 'projects-statistics-schema.yaml#/ProjectStatisticsGetResponseSchema'
400:
$ref: 'responses.yaml#/400ErrorResponse'
401:
$ref: 'responses.yaml#/401ErrorResponse'
404:
$ref: 'responses.yaml#/404ErrorResponse'
Loading
Loading