Giter Site home page Giter Site logo

cjmellor / level-up Goto Github PK

View Code? Open in Web Editor NEW
540.0 540.0 40.0 224 KB

Level-Up is a Laravel package introducing gamification into your applications. Users earn experience points (XP) and levels through interactions, while also unlocking achievements. It promotes engagement, competition, and fun through its dynamic leaderboard feature. Customisable to fit your specific needs

License: MIT License

PHP 100.00%
achievements engagment experience gamification laravel leaderboard levelling

level-up's People

Contributors

7omi avatar cjmellor avatar dependabot[bot] avatar github-actions[bot] avatar guptarakesh198 avatar ibrunotome avatar joydeep-bhowmik avatar matthewscalf avatar mohamedalwhaidi avatar quintenjustus avatar theihasan avatar xmuntane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

level-up's Issues

fix: Customise Migration Constraints

Discussed in #11

Originally posted by matthewscalf July 21, 2023
When utilizing this package, the Achievements are cool idea but the migrations and Pivot models assume you have named the User model users. But you have the option to customize that for the other functions. Would be good to see the achievements utilize the same level of customization.

Add the config option for the User model in more places

[Bug]: First Migration Bug

What happened?

Just trying to do first migration and had a issue with streak_history_table.

I changed the migration table as a placebo, but since i just did it, no idea if will face bugs because of that, so just sharing.

            $table->id();
            $table->foreignId(column: config(key: 'level-up.user.foreign_key'))->constrained(table: config(key: 'level-up.user.users_table'))->cascadeOnDelete();
            $table->foreignIdFor(model: Activity::class)->constrained(table: 'streak_activities');
            $table->integer(column: 'count')->default(value: 1);
            $table->timestamp(column: 'started_at')**->nullable(**);
            $table->timestamp(column: 'ended_at'**)->nullable()**;
            $table->timestamps();

`PS C:\Users\tatia\Dropbox\Coding\Laravel\l96lab> php artisan migrate

INFO Running migrations.

2023_10_31_000158_create_streak_histories_table ...................................................... 11ms FAIL

Illuminate\Database\QueryException

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'ended_at' (Connection: mysql, SQL: create table streak_histories (id bigint unsigned not null auto_increment primary key, user_id bigint unsigned not null, activity_id bigint unsigned not null, count int not null default '1', started_at timestamp not null, ended_at timestamp not null, created_at timestamp null, updated_at timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')

at vendor\laravel\framework\src\Illuminate\Database\Connection.php:801
797▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
798▕ );
799▕ }
800▕
➜ 801▕ throw new QueryException(
802▕ $this->getName(), $query, $this->prepareBindings($bindings), $e
803▕ );
804▕ }
805▕ }

1 vendor\laravel\framework\src\Illuminate\Database\Connection.php:580
PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'ended_at'")

2 vendor\laravel\framework\src\Illuminate\Database\Connection.php:580
PDOStatement::execute()
`

How to reproduce the bug

Only did a migration on my actual project and had this error.

Package Version

1.1

PHP Version

8.2

Laravel Version

10

Which operating systems does with happen with?

No response

Notes

I made a pull request if that solution make sense. Ignore if dont.

Breaks when app\Multipliers is not present

Discussed in #9

Originally posted by Temian1 July 20, 2023
i tried to give user point and i got that issue

p\project\trendup\app\Multipliers" directory does not exist.
```</div>

[Bug]: $user->nextLevelAt(); returning 0

What happened?

Hey mate when I try to utilise $user->nextLevelAt(); it only ever returns 0 and when I add points to the user in question, it increments the level regardless of what the next_level_experience column has stored.

How to reproduce the bug

Seed the levels, add points to a user account and use the getLevel(), nextLevelAt() and getPoints() helper functions.

Package Version

^0.0.6

PHP Version

8.1

Laravel Version

10

Which operating systems does with happen with?

macOS

Notes

I think you just change the nextLevelAt() function in the trait to be:

$nextLevel = Level::firstWhere(column: 'level', operator: '=', value: is_null($checkAgainst) ? $this->getLevel() + 1 : $checkAgainst);

and it will work again. The check using ?? that is originally there passes null to the level where check and is breaking because it's checking for a null "level" column instead of a null "next_level_experience" column as intended.

[Bug]: Comparison fails in recordStreak

What happened?

I was testing streak continuation this morning and have found that the check at HasStreaks:51 for strict equality $diffInDays === 1.

If you see the screenshot attached you'll see that even though $diffInDays shows as 1, this evaluates to false. This is because $diffInDays is a float.

Untitled

How to reproduce the bug

Try with Laravel 11 / Carbon 3.

Package Version

1.2

PHP Version

8.2

Laravel Version

11.0

Which operating systems does with happen with?

Windows

Notes

After a quick search I found this article, breaking change in Carbon 3.0 is that these will be returned as floats now.

I cloned this repo and ran the test suite on a fresh install and can confirm that your tests are also failing on this.

Thank you for this library!

2024-06-05 09_13_23-C__Windows_System32_cmd exe

[Bug]: Auditing Reason not adding to Db

What happened?

First thing, I love this repo. Great job!

$user->addPoints(
    amount: 50,
    multiplier: 2,
    type: AuditType::Add->value,
    reason: "Some reason here",
);

Adds the amount and multiplier, but doesn't trigger the AuditType and reason.

How to reproduce the bug

$user->addPoints(
    amount: 50,
    multiplier: 2,
    type: AuditType::Add->value,
    reason: "Some reason here",
);

Package Version

0.0.6

PHP Version

8.2

Laravel Version

10.x

Which operating systems does with happen with?

macOS

Notes

No response

[Bug]: Event fired only once even when user has points for multiple levels

What happened?

Hello
I was messing around with your package and noticed very bad bug.
When points earned by user are enough to gain more than one level it gets increased only by one closest to level user currently has.
When next points are awarded next level is unlocked but it should be done in one run in my opinion as there may be along time before user earns next points and he will be stuck at lower level making functions like:

$user->nextLevelAt();

useless as they will display 0 as points requirements for next level are already met.
Is there any way to award multiple levels at one points increase operation?

How to reproduce the bug

  1. Setup default levels
Level::add(
    ['level' => 1, 'next_level_experience' => null],
    ['level' => 2, 'next_level_experience' => 100],
    ['level' => 3, 'next_level_experience' => 250],
);
  1. Award user 300 points
$user->addPoints(300);
  1. Only one UserLevelledUp event is fired with level 2
  2. Award one more point:
$user->addPoints(1);
  1. User level gets increased to level 3

Package Version

v0.0.10

PHP Version

8.1

Laravel Version

10.2

Which operating systems does with happen with?

Windows

Notes

No response

[Bug]: Deduct Points

What happened?

User's level is not changing when the points are reduced.
When a user gains certain amount of points the level changes and he will get to a higher level.
However if I deduct points for this user , his experience changes but his level stays the same even tho now it should be lower.

How to reproduce the bug

Add points to a user until he reaches a certain level. Then try to deduct his points. The experience will change however the level will stay the same

Package Version

2

PHP Version

8.2.0

Laravel Version

9.0.0

Which operating systems does with happen with?

macOS, Linux

Notes

No response

first migration [Bug]:

What happened?

Illuminate\Database\QueryException

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
for 'ended_at' (Connection: mysql, SQL: create table streak_histories (id bi
gint unsigned not null auto_increment primary key, user_id bigint unsigned not
null, activity_id bigint unsigned not null, count int not null default '1',
started_at timestamp not null, ended_at timestamp not null, created_at ti
mestamp null, updated_at timestamp null) default character set utf8mb4 collate
'utf8mb4_unicode_ci')

How to reproduce the bug

i try to do fresh migrate

Package Version

2

PHP Version

8

Laravel Version

10

Which operating systems does with happen with?

Windows

Notes

No response

[Bug]:

What happened?

If there is no experience record yet and you run getPoints() it returns the following:
App\Models\User::getPoints(): Return value must be of type int, null returned

How to reproduce the bug

try to run getPoints() while there are no points

Package Version

1.1.0

PHP Version

8.2.14

Laravel Version

10.41

Which operating systems does with happen with?

Linux

Notes

Fix could be:

public function getPoints(): int
    {
        return $this->experience->experience_points ?? 0;
    }

Where it will always return 0 if there are no XP points yet.
If you are fine with it I can shoot a PR including a test

[Bug]: Unknown named parameter $to

What happened?

screencapture-netisu-market-2024-03-20-14_54_33

How to reproduce the bug

When i add the points needed to level up to the next level i get this.

             $amount = 200;
             $Pointsamount = 400;
       
        $user->coins += $amount;
        $user->addPoints($Pointsamount);

Package Version

^1.2.3

PHP Version

8.2.7

Laravel Version

^10.0

Which operating systems does with happen with?

Linux

Notes

No response

[Bug]: Attempt to read property "status" on null at GiveExperience.php:103

What happened?

I am trying to integrate this package with my application.
However I am not able to pass through registering an user as package causes an error:
[2023-08-24 01:23:49] local.ERROR: Attempt to read property "status" on null {"userId":1,"exception":"[object] (ErrorException(code: 0): Attempt to read property "status" on null at C:\Users\username\Desktop\application_name\script\vendor\cjmellor\level-up\src\Concerns\GiveExperience.php:103)

How to reproduce the bug

I have added GiveExperience trait to Used model as instructed.
I have added custom name and reward columns into levels table.
I have seeded test levels:

$levelsArray = [
            [
                'name' => 'Rookie',
                'required_turnover' => null,
                'reward' => null
            ],
            [
                'name' => 'Seeker',
                'required_turnover' => '200000',
                'reward' => '5000'
            ],
        ];

        foreach ($levelsArray as $index => $level) {
            $levelRecord = new Level();
            $levelRecord->name = $level['name'];
            $levelRecord->level = $index+1;
            $levelRecord->next_level_experience = $level['required_turnover'];
            $levelRecord->reward = $level['reward'];
            $levelRecord->save();
        }

Then I am trying to seed first user

        $user = new User();
        $user->username = config('administrator.username');
        $user->email = config('administrator.email');
        $user->password = config('administrator.password');
        $user->status = UserStatus::active;
        $user->level_id = 1;
        $user->save();

        $user->addPoints(amount: 1);

        $userService = new UserService();
        $userService->createRequiredUsersTables($user->id);

And script is killed with error I have posted above.
What is causing this issue?
Same error happens when I add levels using package provided Level model method on "stock" table.

Package Version

^0.0.6

PHP Version

8.1

Laravel Version

10.2

Which operating systems does with happen with?

Windows

Notes

No response

fix: Attempt to read property "next_level_experience" on null

What happened?

Reaching max level and calling nextLevelAt function throws error Attempt to read property "next_level_experience" on null

How to reproduce the bug

I created 4 levels:

Level::add(
     ['level' => 1, 'next_level_experience' => null],
     ['level' => 2, 'next_level_experience' => 100],
     ['level' => 3, 'next_level_experience' => 250],
     ['level' => 4, 'next_level_experience' => 500],
);

implement a route where I do this:

$user = \App\Models\User::find(1);

$user->addPoints(50);
echo $user->getLevel();
echo $user->getPoints();
echo $user->nextLevelAt();

Run api calls to the route repeatedly

When the user reaches the maximum level, call the function nextLevelAt

Environment Variables

LEVEL_CAP_ENABLED=true
LEVEL_CAP=4
LEVEL_CAP_POINTS_CONTINUE=true
AUDIT_POINTS=true

Package Version

0.0.5

PHP Version

8.2.8

Laravel Version

10.10

Which operating systems does with happen with?

macOS

Notes

The error seems to be on line 152 of the vendor/cjmellor/level-up/src/Concerns/GiveExperience.php file when trying to look for a level higher than 4 which is the maximum set in my environment variables.

Could it be that I am missing some configuration?

I am using:

  • Docker version 20.10.17, build 100c701
  • PHP 8.2-fpm
  • Postgres 13

[Bug]: LeaderboardService has a hardcoded dependency on a "users" table

What happened?

The LeaderboardService.php has a hard-coded dependency on there being a users table, ignoring the configuration file with ->whereColumn('user_id', 'users.id').

<?php

namespace LevelUp\Experience\Services;

use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use LevelUp\Experience\Models\Experience;

class LeaderboardService
{
    private mixed $userModel;

    public function __construct()
    {
        $this->userModel = config(key: 'level-up.user.model');
    }

    public function generate(bool $paginate = false, int $limit = null): array|Collection|LengthAwarePaginator
    {
        return $this->userModel::query()
            ->with(relations: ['experience', 'level'])
            ->orderByDesc(
                column: Experience::select('experience_points')
                    ->whereColumn('user_id', 'users.id')
                    ->latest()
            )
            ->take($limit)
            ->when($paginate, fn (Builder $query) => $query->paginate(), fn (Builder $query) => $query->get());
    }
}

How to reproduce the bug

Use a table that isn't named 'users'.

Package Version

latest

PHP Version

8.2.11

Laravel Version

10

Which operating systems does with happen with?

No response

Notes

Two database migrations also have hardcoded references to users, while the rest read from the config.

[Bug]: User's level does not increase

What happened?

When creating 3 levels as the documentation indicates, I carried out tests loading 50 points in my user repeatedly and although the points reached 100 to go to level 2, this never happened.
When implementing the AUDIT_POINTS=true option I could notice as if the attempt to level up was marked but my experience record remained at 1 even though my points were 250

How to reproduce the bug

I created 3 levels as the documentation indicates:

Level::add(
     ['level' => 1, 'next_level_experience' => null],
     ['level' => 2, 'next_level_experience' => 100],
     ['level' => 3, 'next_level_experience' => 250],
);

implement a route where I do this:

$user = \App\Models\User::find(1);

$user->addPoints(50);
echo $user->getLevel();
echo $user->getPoints();

Run api calls to the route repeatedly

Environment Variables

LEVEL_CAP_ENABLED=true
LEVEL_CAP=3
LEVEL_CAP_POINTS_CONTINUE=true
AUDIT_POINTS=true

Package Version

0.0.4

PHP Version

8.2.8

Laravel Version

10.10

Which operating systems does with happen with?

macOS

Notes

When I ran into this error, I did some tests on the package code and realized that I wasn't updating my experience level record but my points were.

While debugging, I changed in the vendor/cjmellor/level-up/src/Concerns/GiveExperience.php file the line 160 in the levelUp method of and was able to solve my problem:

Before:

$this->experience->status()->associate(model: $nextLevel);

After:

$this->experience->status()->associate(model: $nextLevel)->save();

Could you tell me if I'm doing something wrong?

I am using:

  • Docker version 20.10.17, build 100c701
  • PHP 8.2-fpm
  • Postgres 13

[Bug]:

What happened?

Missing Listener for Points Decrease

I've noticed that the package has a listener for the PointsIncreased event (PointsIncreasedListener.php), but there is no dedicated listener for the PointsDecreased event.

Additionally, while the database migration for experience audits (create_experience_audits_table.php.stub) has a column for type that can be 'add', 'remove', 'reset', or 'level_up', it seems that the decrement case is not explicitly stored in the database through a listener.

This could be an important feature for tracking user activities related to points decrement.

Would it be possible to add a listener for the PointsDecreased event and store this information in the database?

How to reproduce the bug

When I deductPoints the decrement case is not explicitly stored in the database through a listener.

Package Version

0.0.13

PHP Version

8.2.0

Laravel Version

10.0.0

Which operating systems does with happen with?

No response

Notes

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.