Skip to content

Commit

Permalink
Merge branch 'extension/referral-rewards' of https://github.com/AW000…
Browse files Browse the repository at this point in the history
…5/lorekeeper-extensions into extension/referral-rewards

# Conflicts:
#	app/Helpers/AssetHelpers.php
#	app/Http/Controllers/Auth/RegisterController.php
#	app/Models/Notification.php
#	app/Models/User/User.php
#	app/Services/LinkService.php
#	app/Services/UserService.php
#	config/lorekeeper/admin_sidebar.php
#	resources/views/auth/register.blade.php
  • Loading branch information
ScuffedNewt committed Aug 16, 2024
2 parents b182421 + 64d680a commit ebc02e3
Show file tree
Hide file tree
Showing 20 changed files with 481 additions and 29 deletions.
11 changes: 6 additions & 5 deletions app/Actions/Fortify/CreateNewUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ public function create(array $input) {
(new UserService)->validator($input)->validate();

$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
'rank_id' => 2,
'birthday' => $input['dob'],
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
'rank_id' => 2,
'birthday' => $input['dob'],
'referred_by' => $input['referred_by'] ?? null,
]);
$user->settings()->create([
'user_id' => $user->id,
Expand Down
30 changes: 30 additions & 0 deletions app/Helpers/AssetHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -409,3 +409,33 @@ function createRewardsString($array) {

return implode(', ', array_slice($string, 0, count($string) - 1)).(count($string) > 2 ? ', and ' : ' and ').end($string);
}

/**
* Encodes an asset array for storage in a data column.
*/
function encodeForDataColumn($data) {
// The data will be stored as an asset table, json_encode()d.
// First build the asset table, then prepare it for storage.
$assets = createAssetsArray();
foreach ($data['rewardable_type'] as $key => $r) {
switch ($r) {
case 'Item':
$type = 'App\Models\Item\Item';
break;
case 'Currency':
$type = 'App\Models\Currency\Currency';
break;
case 'LootTable':
$type = 'App\Models\Loot\LootTable';
break;
case 'Raffle':
$type = 'App\Models\Raffle\Raffle';
break;
}
$asset = $type::find($data['rewardable_id'][$key]);
addAsset($assets, $asset, $data['quantity'][$key]);
}
$assets = getDataReadyAssets($assets);

return json_encode($assets);
}
138 changes: 138 additions & 0 deletions app/Http/Controllers/Admin/Data/ReferralController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php

namespace App\Http\Controllers\Admin\Data;

use Illuminate\Http\Request;

use Auth;

use App\Models\Item\Item;
use App\Models\Currency\Currency;
use App\Models\Loot\LootTable;
use App\Models\Raffle\Raffle;

use App\Http\Controllers\Controller;
use App\Models\Referral;
use Illuminate\Support\Facades\DB;

class ReferralController extends Controller {
/*
|--------------------------------------------------------------------------
| Admin / Referral Controller
|--------------------------------------------------------------------------
|
| Handles creation/editing of referral conditions
|
*/

/**
* Shows the prompt category index.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Contracts\Support\Renderable
*/
public function getIndex(Request $request) {

return view('admin.referrals.referrals', [
'referrals' => Referral::orderBy('referral_count')->get()->paginate(20)
]);
}

/**
* Shows the create referral page.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function getCreate() {
return view('admin.referrals.create_edit', [
'referral' => new Referral,
'items' => Item::orderBy('name')->pluck('name', 'id'),
'currencies' => Currency::where('is_user_owned', 1)->orderBy('name')->pluck('name', 'id'),
'tables' => LootTable::orderBy('name')->pluck('name', 'id'),
'raffles' => Raffle::where('rolled_at', null)->where('is_active', 1)->orderBy('name')->pluck('name', 'id'),
]);
}

/**
* Shows the edit referral page.
*
* @param int $id
* @return \Illuminate\Contracts\Support\Renderable
*/
public function getEdit($id) {
$referral = Referral::find($id);
if (!$referral) abort(404);
return view('admin.referrals.create_edit', [
'referral' => $referral,
'items' => Item::orderBy('name')->pluck('name', 'id'),
'currencies' => Currency::where('is_user_owned', 1)->orderBy('name')->pluck('name', 'id'),
'tables' => LootTable::orderBy('name')->pluck('name', 'id'),
'raffles' => Raffle::where('rolled_at', null)->where('is_active', 1)->orderBy('name')->pluck('name', 'id'),
]);
}

/**
* Creates or edits a referral.
*
* @param \Illuminate\Http\Request $request
* @param App\Services\PromptService $service
* @param int|null $id
* @return \Illuminate\Http\RedirectResponse
*/
public function postCreateEdit(Request $request, $id = null) {

$data = $request->only([
'referral_count', 'days_active'
]);
$data['data'] = encodeForDataColumn($request->only(['rewardable_type', 'rewardable_id', 'quantity']));
$data['is_active'] = $request->get('is_active') !== null;
$data['on_every'] = $request->get('on_every') !== null;

DB::beginTransaction();
try {
if ($id) $referral = Referral::find($id)->update($data);
else $referral = Referral::create($data);
DB::commit();

flash('Referral saved successfully.')->success();
return redirect()->to('admin/data/referrals/edit/' . ($id ?? $referral->id));
} catch (\Exception $e) {
DB::rollback();
flash($e->getMessage())->error();
return redirect()->back();
}
}

/**
* Gets the prompt deletion modal.
*
* @param int $id
* @return \Illuminate\Contracts\Support\Renderable
*/
public function getDelete($id) {
$referral = Referral::find($id);
return view('admin.referrals._delete', [
'referral' => $referral,
]);
}

/**
* Deletes a prompt.
*
* @param \Illuminate\Http\Request $request
* @param App\Services\PromptService $service
* @param int $id
* @return \Illuminate\Http\RedirectResponse
*/
public function postDelete(Request $request, $id) {
try {
Referral::find($id)->delete();
DB::commit();
flash('Prompt deleted successfully.')->success();
} catch (\Exception $e) {
DB::rollback();
flash($e->getMessage())->error();
}
return redirect()->to('admin/data/referrals');
}
}
3 changes: 2 additions & 1 deletion app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public function getRegisterWithDriver($provider) {

return view('auth.register_with_driver', [
'userCount' => User::count(),
'users' => User::orderBy('name')->pluck('name', 'id')->toArray(),
'provider' => $provider,
'user' => $userData->nickname ?? null,
'token' => $userData->token ?? null,
Expand Down Expand Up @@ -101,7 +102,7 @@ public function postRegisterWithDriver(LinkService $service, Request $request, $
protected function create(array $data) {
DB::beginTransaction();
$service = new UserService;
$user = $service->createUser(Arr::only($data, ['name', 'email', 'password', 'dob']));
$user = $service->createUser(Arr::only($data, ['name', 'email', 'password', 'dob', 'referred_by']));
if (!Settings::get('is_registration_open')) {
(new InvitationService)->useInvitation(Invitation::where('code', $data['code'])->first(), $user);
}
Expand Down
1 change: 1 addition & 0 deletions app/Models/Notification.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,5 @@ public static function getNotificationId($type) {
public const GALLERY_SUBMISSION_STAFF_COMMENTS = 513;
public const GALLERY_SUBMISSION_EDITED = 514;
public const GALLERY_SUBMISSION_PARTICIPANT = 515;
public const REFERRAL = 905;
}
50 changes: 50 additions & 0 deletions app/Models/Referral.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Models;

use Config;
use App\Models\Model;

use App\Traits\Commentable;

class Referral extends Model {
use Commentable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'referral_count', 'data', 'is_active', 'days_active', 'on_every'
];

/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'referrals';

public function getDataAttribute($data) {
$rewards = [];
if ($data) {
$assets = parseAssetData(json_decode($data));
foreach ($assets as $type => $a) {
$class = getAssetModelString($type, false);
foreach ($a as $id => $asset) {
$rewards[] = (object)[
'rewardable_type' => $class,
'rewardable_id' => $id,
'quantity' => $asset['quantity']
];
}
}
}
return $rewards;
}

public function getParsedDataAttribute() {
return json_decode($this->attributes['data']);
}
}
2 changes: 1 addition & 1 deletion app/Models/User/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class User extends Authenticatable implements MustVerifyEmail {
*/
protected $fillable = [
'name', 'alias', 'rank_id', 'email', 'email_verified_at', 'password', 'is_news_unread', 'is_banned', 'has_alias', 'avatar', 'is_sales_unread', 'birthday',
'is_deactivated', 'deactivater_id',
'is_deactivated', 'deactivater_id', 'referred_by'
];

/**
Expand Down
1 change: 1 addition & 0 deletions app/Providers/FortifyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public function boot() {
});
Fortify::registerView(fn () => view('auth.register', [
'userCount' => User::count(),
'users' => User::orderBy('name')->pluck('name', 'id')->toArray(),
'altRegistrations' => $altRegistrations,
]));

Expand Down
1 change: 1 addition & 0 deletions app/Providers/Socialite/ToyhouseProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ protected function mapUserToObject(array $user) {
return (new User)->setRaw($user)->map([
'id' => $user['id'], 'nickname' => $user['username'],
'name' => null, 'email' => null, 'avatar' => $user['avatar'],
'referred_by' => null,
]);
}
}
28 changes: 28 additions & 0 deletions app/Services/LinkService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace App\Services;

use App\Facades\Notifications;
use App\Models\Referral;
use App\Models\User\User;
use App\Services\Service;
use App\Models\User\UserAlias;
use App\Models\User\UserUpdateLog;
use Illuminate\Support\Facades\DB;
Expand Down Expand Up @@ -74,6 +78,30 @@ public function saveProvider($provider, $result, $user) {
'user_snowflake' => $result->id ?? $result->nickname,
]);

// If this is the users first alias and they were referred, then we want to act on referral data
if ($user->has_alias == 0 && isset($user->referred_by)) {
// plus 1 because the user currently registering their alias isn't counted yet
$referralCount = User::where('referred_by', $user->referred_by)->where('has_alias', 1)->count() + 1;
$userReferred = User::find($user->referred_by);
$referralConditions = Referral::where('is_active', 1)->get()->filter(function ($query) use ($referralCount) {
// On every needs to be modded to see if it's been x referrals since the last time it was rewarded.
return ($query->on_every && $referralCount % $query->referral_count === 0) || $referralCount == $query->referral_count;
});
$rewards = '';
if (count($referralConditions) > 0) {
foreach ($referralConditions as $referralCondition) {
$rewards = $rewards . getRewardsString(fillUserAssets(parseAssetData($referralCondition->parsedData), null, $userReferred, 'Referral Rewards', [
'data' => 'Received rewards for referral of ' . $user->name
]));
}
}

Notifications::create('REFERRAL', $userReferred, [
'count' => $referralCount,
'rewards' => $rewards
]);
}

// Save that the user has an alias
$user->has_alias = 1;
$user->save();
Expand Down
13 changes: 7 additions & 6 deletions app/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,13 @@ public function createUser($data) {
$formatDate = Carbon::parse($data['dob']);

$user = User::create([
'name' => $data['name'],
'email' => $data['email'] ?? null,
'rank_id' => $data['rank_id'],
'password' => isset($data['password']) ? Hash::make($data['password']) : null,
'birthday' => $formatDate,
'has_alias' => $data['has_alias'] ?? false,
'name' => $data['name'],
'email' => $data['email'] ?? null,
'rank_id' => $data['rank_id'],
'password' => isset($data['password']) ? Hash::make($data['password']) : null,
'birthday' => $formatDate,
'has_alias' => $data['has_alias'] ?? false,
'referred_by' => $data['referred_by'],
// Verify the email if we're logging them in with their social
'email_verified_at' => (!isset($data['password']) && !isset($data['email'])) ? now() : null,
]);
Expand Down
4 changes: 4 additions & 0 deletions config/lorekeeper/admin_sidebar.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@
'name' => 'Items',
'url' => 'admin/data/items',
],
[
'name' => 'Referrals',
'url' => 'admin/data/referrals'
]
],
],
'Raffles' => [
Expand Down
7 changes: 7 additions & 0 deletions config/lorekeeper/notifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -437,4 +437,11 @@
'message' => '<a href="{sender_url}">{sender}</a> has added you as a participant on a gallery submission. (<a href="{url}">View Submission</a>)',
'url' => 'gallery/view/{submission_id}',
],

// REFERRAL
905 => [
'name' => 'Referral Rewards',
'message' => 'You\'ve received the following rewards for referring {count} user(s): {rewards}',
'url' => ''
]
];
Loading

0 comments on commit ebc02e3

Please sign in to comment.