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: service to upload an avatar #500

Merged
merged 7 commits into from
Jan 17, 2021
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
10 changes: 10 additions & 0 deletions app/Helpers/LogHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,12 @@ public static function processAuditLog(AuditLog $log): string
]);
break;

case 'employee_avatar_set':
$sentence = trans('account.log_employee_avatar_set', [
'employee_id' => $log->object->{'employee_id'},
]);
break;

default:
$sentence = '';
break;
Expand Down Expand Up @@ -1511,6 +1517,10 @@ public static function processEmployeeLog(EmployeeLog $log): string
]);
break;

case 'employee_avatar_set':
$sentence = trans('account.employee_log_employee_avatar_set');
break;

default:
$sentence = '';
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public static function index(Project $project, Employee $employee): Collection
$messages = $project->messages()
->select('id', 'title', 'content', 'created_at', 'author_id')
->with('author')
->latest()
->orderBy('id')
->get();

$messageReadStatuses = DB::table('project_message_read_status')
Expand Down
7 changes: 6 additions & 1 deletion app/Models/Company/Employee.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ class Employee extends Model
'phone_number',
'locked',
'avatar',
'avatar_original_filename',
'avatar_extension',
'avatar_size',
'avatar_height',
'avatar_width',
'holiday_balance',
'default_dashboard_view',
'can_manage_expenses',
Expand Down Expand Up @@ -639,7 +644,7 @@ public function getNameAttribute($value): string
public function getListOfManagers(): Collection
{
$managersCollection = collect([]);
foreach ($this->managers()->get() as $directReport) {
foreach ($this->managers()->orderBy('id')->get() as $directReport) {
$managersCollection->push($directReport->manager);
}

Expand Down
98 changes: 98 additions & 0 deletions app/Services/User/Avatar/UploadAvatar.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

namespace App\Services\User\Avatar;

use Carbon\Carbon;
use App\Models\User\Avatar;
use App\Jobs\LogAccountAudit;
use App\Services\BaseService;
use App\Jobs\LogEmployeeAudit;
use App\Models\Company\Employee;

class UploadAvatar extends BaseService
{
private array $data;

private Employee $employee;

/**
* Get the validation rules that apply to the service.
*
* @return array
*/
public function rules(): array
{
return [
'company_id' => 'required|integer|exists:companies,id',
'author_id' => 'required|integer|exists:employees,id',
'employee_id' => 'required|integer|exists:employees,id',
'photo' => 'file|image',
];
}

/**
* Upload an avatar.
*
* @param array $data
*
* @return Employee
*/
public function execute(array $data): Employee
{
$this->data = $data;

$this->validate();
$this->save();
$this->log();

return $this->employee;
}

private function validate(): void
{
$this->validateRules($this->data);

$this->author($this->data['author_id'])
->inCompany($this->data['company_id'])
->asAtLeastHR()
->canBypassPermissionLevelIfEmployee($this->data['employee_id'])
->canExecuteService();

$this->employee = $this->validateEmployeeBelongsToCompany($this->data);
}

private function save(): void
{
Employee::where('id', $this->data['employee_id'])
->update([
'avatar' => $this->data['photo']->storePublicly('avatars', config('filesystems.default')),
'avatar_original_filename' => $this->data['photo']->getClientOriginalName(),
'avatar_extension' => $this->data['photo']->extension(),
'avatar_size' => $this->data['photo']->getSize(),
]);
}

private function log(): void
{
LogAccountAudit::dispatch([
'company_id' => $this->data['company_id'],
'action' => 'employee_avatar_set',
'author_id' => $this->author->id,
'author_name' => $this->author->name,
'audited_at' => Carbon::now(),
'objects' => json_encode([
'employee_id' => $this->employee->id,
'employee_name' => $this->employee->name,
]),
])->onQueue('low');

LogEmployeeAudit::dispatch([
'employee_id' => $this->employee->id,
'action' => 'employee_avatar_set',
'author_id' => $this->author->id,
'author_name' => $this->author->name,
'audited_at' => Carbon::now(),
'objects' => json_encode([]),
])->onQueue('low');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ class CreateTimeTrackingTable extends Migration
*/
public function up()
{
// necessary for SQLlite
Schema::enableForeignKeyConstraints();

Schema::create('timesheets', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('company_id')->nullable();
Expand Down
25 changes: 25 additions & 0 deletions database/migrations/2021_01_15_012428_create_avatars_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

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

class CreateAvatarsTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
// necessary for SQLlite
Schema::enableForeignKeyConstraints();

Schema::table('employees', function (Blueprint $table) {
$table->string('avatar_original_filename')->after('avatar')->nullable();
$table->string('avatar_extension')->after('avatar_original_filename')->nullable();
$table->bigInteger('avatar_size')->after('avatar_extension')->nullable();
$table->integer('avatar_height')->after('avatar_size')->nullable();
$table->integer('avatar_width')->after('avatar_height')->nullable();
});
}
}
2 changes: 2 additions & 0 deletions resources/lang/en/account.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@
'log_timesheet_submitted' => 'Submitted the timesheet of the week started on :started_at for :employee_name.',
'log_timesheet_approved' => 'Approved the timesheet of the week started on :started_at for :employee_name.',
'log_timesheet_rejected' => 'Rejected the timesheet of the week started on :started_at for :employee_name.',
'log_employee_avatar_set' => 'Set the avatar of :employee_name.',

// employee logs
'employee_log_employee_created' => 'Created this employee entry.',
Expand Down Expand Up @@ -350,6 +351,7 @@
'employee_log_timesheet_submitted' => 'Submitted the timesheet of the week started on :started_at.',
'employee_log_timesheet_approved' => 'Approved the timesheet of the week started on :started_at.',
'employee_log_timesheet_rejected' => 'Rejected the timesheet of the week started on :started_at.',
'employee_log_employee_avatar_set' => 'Set a new avatar.',

// team logs
'team_log_team_created' => 'Created the team.',
Expand Down
111 changes: 111 additions & 0 deletions tests/Unit/Services/User/Avatar/UploadAvatarTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

namespace Tests\Unit\Services\User\Avatar;

use Tests\TestCase;
use App\Jobs\LogAccountAudit;
use App\Jobs\LogEmployeeAudit;
use App\Models\Company\Employee;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use App\Services\User\Avatar\UploadAvatar;
use Illuminate\Validation\ValidationException;
use App\Exceptions\NotEnoughPermissionException;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class UploadAvatarTest extends TestCase
{
use DatabaseTransactions;

/** @test */
public function it_uploads_an_avatar_as_administrator(): void
{
$michael = $this->createAdministrator();
$dwight = $this->createAnotherEmployee($michael);
$this->executeService($michael, $dwight);
}

/** @test */
public function it_uploads_an_avatar_as_hr(): void
{
$michael = $this->createHR();
$dwight = $this->createAnotherEmployee($michael);
$this->executeService($michael, $dwight);
}

/** @test */
public function it_uploads_an_avatar_as_normal_user(): void
{
$michael = $this->createEmployee();
$this->executeService($michael, $michael);
}

/** @test */
public function it_cant_upload_an_avatar_as_normal_user_for_another_user(): void
{
$michael = $this->createEmployee();
$dwight = $this->createAnotherEmployee($michael);

$this->expectException(NotEnoughPermissionException::class);
$this->executeService($michael, $dwight);
}

/** @test */
public function it_fails_if_wrong_parameters_are_given(): void
{
$michael = factory(Employee::class)->create([]);

$request = [
'company_id' => $michael->company_id,
];

$this->expectException(ValidationException::class);
(new UploadAvatar)->execute($request);
}

private function executeService(Employee $michael, Employee $dwight): void
{
Queue::fake();
Storage::fake('avatars');

$file = UploadedFile::fake()->image('image.png');

$request = [
'company_id' => $michael->company_id,
'author_id' => $michael->id,
'employee_id' => $dwight->id,
'photo' => $file,
];

$employee = (new UploadAvatar)->execute($request);

$this->assertDatabaseHas('employees', [
'id' => $employee->id,
'company_id' => $michael->company_id,
'avatar_original_filename' => 'image.png',
'avatar_extension' => 'png',
'avatar_size' => 91,
]);

$this->assertInstanceOf(
Employee::class,
$employee
);

Queue::assertPushed(LogAccountAudit::class, function ($job) use ($michael, $dwight) {
return $job->auditLog['action'] === 'employee_avatar_set' &&
$job->auditLog['author_id'] === $michael->id &&
$job->auditLog['objects'] === json_encode([
'employee_id' => $dwight->id,
'employee_name' => $dwight->name,
]);
});

Queue::assertPushed(LogEmployeeAudit::class, function ($job) use ($michael) {
return $job->auditLog['action'] === 'employee_avatar_set' &&
$job->auditLog['author_id'] === $michael->id &&
$job->auditLog['objects'] === json_encode([]);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public function it_gets_a_collection_of_messages(): void
]);

$collection = ProjectMessagesViewHelper::index($project, $michael);

$this->assertEquals(
[
0 => [
Expand Down