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

feat: endpoint for user stats #99

Merged
merged 8 commits into from
Mar 19, 2024
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
34 changes: 34 additions & 0 deletions src/app/Http/Controllers/UserStatsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\ResponseController;
use App\Http\Resources\UserStatsResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class UserStatsController extends ResponseController
{
public function show(int $id): JsonResponse
{
try {
$data = DB::select('SELECT * FROM user_stats_view WHERE UserId = ?', [$id]);

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

// cast all as integer
$collection = collect($data[0])->map(function ($value) {
return is_numeric($value) ? (int) $value : $value;
});

$resource = new UserStatsResource($collection);

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

}
13 changes: 13 additions & 0 deletions src/app/Http/Resources/UserStatsResource.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 UserStatsResource extends JsonResource
{
public function toArray($request): array
{
return parent::toArray($request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

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

return new class extends Migration
{
public function up(): void
{
// seed new ScoreTypeId
DB::table('ScoreType')->insertOrIgnore([
[
'ScoreTypeId' => 5,
'Name' => 'HTR-Transcription',
'Rate' => 0.0033
]
]);

DB::statement('
CREATE VIEW user_stats_view AS
SELECT
s.UserId,
COUNT(DISTINCT s.ItemId) AS Items,
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 * st.Rate) + 0.5, 0) AS Miles
FROM
Score s
JOIN
ScoreType st ON s.ScoreTypeId = st.ScoreTypeId
GROUP BY
UserId;
');
}

public function down(): void
{
DB::statement('DROP VIEW IF EXISTS user_stats_view');
}
};
2 changes: 2 additions & 0 deletions src/routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use App\Http\Controllers\StoryStatsController;
use App\Http\Controllers\TeamController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\UserStatsController;
use App\Http\Controllers\ScoreController;

/*
Expand Down Expand Up @@ -72,6 +73,7 @@

Route::get('/users', [UserController::class, 'index']);
Route::get('/users/{id}', [UserController::class, 'show']);
Route::get('/users/{id}/statistics', [UserStatsController::class, 'show']);

Route::get('/scores', [ScoreController::class, 'index']);
Route::post('/scores', [ScoreController::class, 'store']);
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.0.3

info:
version: 1.31.0
version: 1.32.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 @@ -101,6 +101,8 @@ paths:
$ref: 'users-path.yaml'
/users/{UserId}:
$ref: 'users-userId-path.yaml'
/users/{UserId}/statistics:
$ref: 'users-userId-statistics-path.yaml'

/teams:
$ref: 'teams-path.yaml'
Expand Down
37 changes: 37 additions & 0 deletions src/storage/api-docs/users-statistics-schema.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
UserStatisticsGetResponseSchema:
allOf:
- type: object
- description: The data object of a single response entry
properties:
UserId:
type: integer
description: ID of the User
example: 2
Items:
type: integer
description: Number of items the user has participated in
example: 4
Locations:
type: integer
description: Number of locations and places the user has geolocated
example: 12
ManualTranscriptions:
type: integer
description: Number of chars the user has transcribed manually
example: 2365
Enrichments:
type: integer
description: Number of enrichments the user has created
example: 12
Descriptions:
type: integer
description: Number of chars of the descriptions the user has created
example: 513
HTRTranscriptions:
type: integer
description: Number of chars the user has transcribed with HTR
example: 1285
Miles:
type: integer
description: Number of points the user has so far
example: 23655
29 changes: 29 additions & 0 deletions src/storage/api-docs/users-userId-statistics-path.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
get:
tags:
- statistics
- users
summary: Get stored statistics data of an user
description: The returned data is single object
parameters:
- in: path
name: UserId
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: 'users-statistics-schema.yaml#/UserStatisticsGetResponseSchema'
400:
$ref: 'responses.yaml#/400ErrorResponse'
401:
$ref: 'responses.yaml#/401ErrorResponse'
404:
$ref: 'responses.yaml#/404ErrorResponse'
152 changes: 152 additions & 0 deletions src/tests/Feature/UserStatsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Support\Facades\DB;

class UserStatsTest extends TestCase
{
private static $scoreTypeTableName = 'ScoreType';

private static $scoreTypeTableData = [
[
'ScoreTypeId' => 1,
'Name' => 'Location',
'Rate' => 0.2
],
[
'ScoreTypeId' => 2,
'Name' => 'Transcription',
'Rate' => 0.0033
],
[
'ScoreTypeId' => 3,
'Name' => 'Enrichment',
'Rate' => 0.2
],
[
'ScoreTypeId' => 4,
'Name' => 'Description',
'Rate' => 0.2
],
[
'ScoreTypeId' => 5,
'Name' => 'HTR-Transcription',
'Rate' => 0.0033
]
];

private static $tableName = 'Score';

private static $tableData = [
[
'ScoreId' => 1,
'ItemId' => 1,
'UserId' => 1,
'ScoreTypeId' => 2,
'Amount' => 55,
'Timestamp' => '2021-01-01T12:00:00.000000Z'
],
[
'ScoreId' => 2,
'ItemId' => 2,
'UserId' => 2,
'ScoreTypeId' => 2,
'Amount' => 0,
'Timestamp' => '2021-02-01T12:00:00.000000Z'
],
[
'ScoreId' => 3,
'ItemId' => 3,
'UserId' => 1,
'ScoreTypeId' => 3,
'Amount' => 0,
'Timestamp' => '2021-03-01T12:00:00.000000Z'
]
];

public function setUp(): void
{
parent::setUp();
self::populateTable();
}

public static function populateTable (): void
{
DB::table(self::$scoreTypeTableName)->insertOrIgnore(self::$scoreTypeTableData);
DB::table(self::$tableName)->insert(self::$tableData);
}

public function testGetNotFoundOnNonExistentUser(): void
{
$userId = 0;
$endpoint = '/users/' . $userId . '/statistics';
$queryParams = '?limit=1&page=1&orderBy=ScoreId&orderDir=desc';
$awaitedSuccess = ['success' => false];

$response = $this->get($endpoint . $queryParams);

$response
->assertNotFound()
->assertJson($awaitedSuccess);
}

public function testGetStatisticsForAnUser(): void
{
$userId = 1;
$endpoint = '/users/' . $userId . '/statistics';
$queryParams = '?limit=1&page=1&orderBy=ScoreId&orderDir=desc';
$awaitedSuccess = ['success' => true];
$userFiltered = array_filter(self::$tableData, function($entry) use ($userId) {
return $entry['UserId'] == $userId;
});
function scoreFiltered (array $array, int $scoreTypeId): int
{
return array_sum(
array_column(
array_filter($array, function($entry) use ($scoreTypeId) {
return $entry['ScoreTypeId'] === $scoreTypeId;
}),
'Amount'
)
);
}
$awaitedData = [
'data' => [
'UserId' => $userId,
'Items' => count(
array_unique(array_column(array_filter($userFiltered), 'ItemId'))
),
'Locations' => scoreFiltered($userFiltered, 1),
'ManualTranscriptions' => scoreFiltered($userFiltered, 2),
'Enrichments' => scoreFiltered($userFiltered, 3),
'Descriptions' => scoreFiltered($userFiltered, 4),
'HTRTranscriptions' => scoreFiltered($userFiltered, 5)
]
];
function rate (array $array, int $scoreTypeId): float
{
$filtered = array_filter($array, function ($entry) use ($scoreTypeId) {
return $entry['ScoreTypeId'] === $scoreTypeId;
});
$filtered = reset($filtered);

return $filtered['Rate'];
}
$awaitedData['data']['Miles'] = ceil(
$awaitedData['data']['Locations'] * rate(self::$scoreTypeTableData, 1) +
$awaitedData['data']['ManualTranscriptions'] * rate(self::$scoreTypeTableData, 2) +
$awaitedData['data']['Enrichments'] * rate(self::$scoreTypeTableData, 3) +
$awaitedData['data']['Descriptions'] * rate(self::$scoreTypeTableData, 4) +
$awaitedData['data']['HTRTranscriptions'] * rate(self::$scoreTypeTableData, 5)
);

$response = $this->get($endpoint . $queryParams);

$response
->assertOk()
->assertJson($awaitedSuccess)
->assertJson($awaitedData);
}
}
9 changes: 9 additions & 0 deletions src/tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@ protected function setUp(): void

$this->makeMigrations();

// and then the rest for all migration are just created or the test
// (for all already existing databases)
$this->artisan('migrate', ['--path' => 'database/testMigrations']);

// since we cannot use all migrations from the begining select here specific ones
$this->artisan(
'migrate',
['--path' => 'database/migrations/2024_03_18_103600_create_user_stats_view.php']
);

}

protected function makeMigrations(): void
Expand Down
Loading