upsert( [['player_id' => $playerId, 'key' => $key, 'value' => $by]], ['player_id', 'key'], ['value' => DB::raw("value + $by")], ); } /** Note that something happened at least once, without a write on every repeat (map views). */ public static function mark(?int $playerId, string $key): void { if ($playerId !== null) { DB::table('player_counters')->insertOrIgnore(['player_id' => $playerId, 'key' => $key, 'value' => 1]); } } /** @return list */ public static function claimed(int $playerId): array { return DB::table('player_quests')->where('player_id', $playerId)->pluck('quest')->all(); } public static function facts(int $playerId): Facts { $buildings = Building::query() ->join('villages', 'villages.id', '=', 'buildings.village_id') ->where('villages.player_id', $playerId) ->get(['buildings.village_id', 'buildings.type', 'buildings.level']); $levels = []; $instances = []; foreach ($buildings->groupBy('type') as $type => $rows) { $levels[$type] = (int) $rows->max('level'); $instances[$type] = (int) $rows->countBy('village_id')->max(); } return new Facts( $levels, $instances, DB::table('player_counters')->where('player_id', $playerId)->pluck('value', 'key')->map(fn ($n) => (int) $n)->all(), ); } /** The badge in the village payload: quests to claim and level rewards to collect. */ public static function summary(Village $village): array { if ($village->player_id === null) { return ['claimable' => 0, 'rewards' => 0]; } $book = new QuestBook($village->world->gameConfig()); return [ 'claimable' => $book->claimableCount(self::claimed($village->player_id), self::facts($village->player_id)), 'rewards' => LevelReward::where('player_id', $village->player_id)->whereNull('claimed_at')->count(), ]; } /** * A finished order reached $level of $type: the first time for this player, part of * what it cost waits to be collected in this village. * * @param array $cost */ public static function reached(Village $village, string $type, int $level, array $cost, CarbonImmutable $at): void { if ($village->player_id === null) { return; } $reward = (new QuestBook($village->world->gameConfig()))->levelReward($cost); if (array_sum($reward) < 1) { return; } LevelReward::insertOrIgnore([ 'player_id' => $village->player_id, 'village_id' => $village->id, 'type' => $type, 'level' => $level, 'reward' => json_encode($reward), 'reached_at' => Engine::stamp($at), ]); } }