Repository navigation
Expand file tree
/
Copy pathCreateCommitPastel.php
More file actions
55 lines (43 loc) · 1.84 KB
/
Copy pathCreateCommitPastel.php
File metadata and controls
55 lines (43 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace App\Actions;
use App\Enums\CommitStatus;
use App\Enums\CommitUpdate;
use App\Enums\UserUpdate;
use App\Events\CommitsUpdated;
use App\Events\ProfilesUpdated;
use App\Events\UsersUpdated;
use App\Models\Commit;
use App\Models\User;
use Illuminate\Support\Facades\DB;
final readonly class CreateCommitPastel
{
public function handle(User $user, Commit $commit): bool
{
return DB::transaction(function () use ($user, $commit): bool {
$users = User::query()->whereKey([$user->id, $commit->user_id])
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$sender = $users->get($user->id);
assert($sender instanceof User);
$remaining = $sender->pasteisRemaining();
if ($remaining === 0) {
return false;
}
$recipientCommit = Commit::query()->lockForUpdate()->findOrFail($commit->id);
$sender->update([
'pasteis_given_on' => today()->toDateString(),
'pasteis_given_today' => User::DAILY_PASTEIS - $remaining + 1,
]);
$recipientCommit->increment('pasteis_count');
User::query()->whereKey($commit->user_id)->increment('pasteis_received');
// The count is everyone's to see, and the giver's other devices learn what they have left to give.
if ($recipientCommit->status === CommitStatus::Approved) {
event(new CommitsUpdated([$recipientCommit], CommitUpdate::Engagement));
}
event(new UsersUpdated([$sender->id], UserUpdate::Account));
// Who received it shows it on their profile, to whoever may see the total: each reads it again themselves.
event(new ProfilesUpdated([$commit->user_id]));
return true;
}, 3);
}
}