Coder Social home page Coder Social logo

michael-rubel / laravel-couponables Goto Github PK

View Code? Open in Web Editor NEW
174.0 4.0 8.0 398 KB

Coupons/promocodes leveraging Eloquent's polymorphic relationships

License: MIT License

PHP 100.00%
laravel php looking-for-contributors coupon coupon-code-generator coupon-service coupons

laravel-couponables's Introduction

Laravel Couponables

Laravel Couponables

Latest Version on Packagist Tests Code Quality Code Coverage Infection Larastan

This package provides coupons/promocodes functionality for your Laravel application leveraging Eloquent's polymorphic relationships.

The package requires PHP 8.1 or higher and Laravel 10 or higher.


#StandWithUkraine

SWUbanner


Installation

Install the package using composer:

composer require michael-rubel/laravel-couponables

Publish the migrations:

php artisan vendor:publish --tag="couponables-migrations"

Publish the config file:

php artisan vendor:publish --tag="couponables-config"

Usage

After publishing migrations, apply a trait in the model you want to use as a $redeemer:

use HasCoupons;

Artisan command

You can add coupons to your database using Artisan command:

php artisan make:coupon YourCouponCode

Optionally, you can pass the next arguments:

'--value'         // The 'value' to perform calculations based on the coupon provided
'--type'          // The 'type' to point out the calculation strategy
'--limit'         // Limit how many times the coupon can be applied by the model
'--quantity'      // Limit how many coupons are available overall (this value will decrement)
'--expires_at'    // Set expiration time for the coupon
'--redeemer_type' // Polymorphic model type. Can as well be morph-mapped value, i.e. 'users'
'--redeemer_id'   // Redeemer model ID
'--data'          // JSON column to store any metadata you want for this particular coupon

Adding coupons using model

You can as well add coupons simply using model:

Coupon::create([
    'code'  => '...',
    'type'  => '...'
    'value' => '...',
    ...
]);
  • Note: type and value columns are used for cost calculations (this is optional).
    If the type column is null, the subtraction strategy will be chosen.

Basic operations

Verify the coupon code:

$redeemer->verifyCoupon($code);

Redeem the coupon:

$redeemer->redeemCoupon($code);

Redeem the coupon in context of another model:

$redeemer
  ->redeemCoupon($code)
  ->for($course);

Combined redeemCoupon and for behavior (assuming the $course includes HasCoupons trait):

$course->redeemBy($redeemer, $code);

If something's going wrong, methods verifyCoupon and redeemCoupon will throw an exception:

CouponDisabledException     // Coupon is disabled (`is_enabled` column).
CouponExpiredException      // Coupon is expired (`expires_at` column).
InvalidCouponException      // Coupon is not found in the database.
InvalidCouponTypeException  // Wrong coupon type found in the database (`type` column).
InvalidCouponValueException // Wrong coupon value passed from the database (`value` column).
NotAllowedToRedeemException // Coupon is assigned to the specific model (`redeemer` morphs).
OverLimitException          // Coupon is over the limit for the specific model (`limit` column).
OverQuantityException       // Coupon is exhausted (`quantity` column).
CouponException             // Generic exception for all cases.

If you want to bypass the exception and do something else:

$redeemer->verifyCouponOr($code, function ($code, $exception) {
    // Your action with $code or $exception!
});
$redeemer->redeemCouponOr($code, function ($code, $exception) {
    // Your action with $code or $exception!
});

Redeemer checks

Check if this coupon is already used by the model:

$redeemer->isCouponAlreadyUsed($code);

Check if the coupon is over the limit for the model:

$redeemer->isCouponOverLimit($code);

Coupon checks

public function isExpired(): bool;
public function isNotExpired(): bool;
public function isDisposable(): bool;
public function isOverQuantity(): bool;
public function isRedeemedBy(Model $redeemer): bool;
public function isOverLimitFor(Model $redeemer): bool;

This method references the model assigned to redeem the coupon:

public function redeemer(): ?Model;

Calculations

$coupon = Coupon::create([
    'code'  => 'my-generated-coupon-code-to-use',
    'type'  => CouponContract::TYPE_PERCENTAGE, // 'percentage'
    'value' => '10', // <-- %10
]);

$coupon->calc(using: 300); // 270.00

The package supports three types of item cost calculations:

  • subtraction - subtracts the given value from the value defined in the coupon model;
  • percentage - subtracts the given value by the percentage defined in the coupon model;
  • fixed - completely ignores the given value and takes the coupon model value instead.

Note: you can find constants for coupon types in the CouponContract

Listeners

If you go event-driven, you can handle package events:


Extending package functionality

Traits DefinesColumns and DefinesPivotColumns contain the methods that define column names to use by the package, so you can use inheritance to override them.

If you need to override the entire classes, use the config values or container bindings. All the classes in the package have their own contract (interface), so you're free to modify it as you wish.

CouponService has the Macroable trait, This way you can inject the methods to interact with the service without overriding anything.

Contributing

If you see any ways we can improve the package, PRs are welcome. But remember to write tests for your use cases.

Testing

composer test

laravel-couponables's People

Contributors

dependabot[bot] avatar michael-rubel avatar syamsoul 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

laravel-couponables's Issues

isAllowedToRedeemBy cannot check the owner

my coupon:
redeemer_type: App\Models\Member,
redeemer_id: 30,

$redeemer = Member::find(18);
$redeemer->verifyCoupon($coupon_code); //return no exception

no matter which redeemer it is, always pass the validation.

i found the issue in this function.

public function isAllowedToRedeemBy(Model $redeemer): bool
    {
        return with(static::$bindable, function ($coupon) use ($redeemer) {
            if ($coupon->isMorphColumnsFilled() && ! $coupon->redeemer?->is($redeemer)) {
                return false;
            }

            if ($coupon->isOnlyRedeemerTypeFilled() && ! $coupon->isSameRedeemerModel($redeemer)) {
                return false;
            }

            return true;
        });
    }

$coupon is always null inside this function >> $coupon->redeemer_type and $coupon->redeemer_id are null >> always return true.

and if i use $this instead of static::$bindable, everything works.

Please help to fix this issue, thanks!

Dose not check the owner of the coupon

I assigned the coupon to $redeemer by saving

redeemer_type=members
redeemer_id=46 (in this case)

I try to use another member to verifyCoupon the coupon and it returns true

$member = Member::find(47);
$coupon = $member->verifyCoupon($code); << it return no exception

verifyCouponOr doesn't return exceptions

Hi,

I try this code

$user->verifyCouponOr("ABC123", function($exception){
    dump($exception);
});

I expected the output will be the exception (e.g MichaelRubel\Couponables\Exceptions\OverQuantityException The coupon is exhausted.)

.

but instead, it return the coupon code:

"ABC123"

.

check if coupon is valid

i want to give users the oppourtunity to check if coupon is still valid, before user redeem, but my code isnt working

 public $code;
    public function check($id)
    {
        $user = User::find($id);
        $user->verifyCouponOr($this->code, function ($exception) {
            throw ValidationException::withMessages(['code' => 'Your coupon code is already use',]);
        });

        $user->isCouponAlreadyUsed($this->code);
    }

blade

<div class="my-5">
    <div class="bg-white rounded-md p-3 mx-2">
        <form wire:submit="check({{ auth()->user()->id }})" action="" class="space-y-3">
            <input wire:model="code" placeholder="Check If Coupon Is Valid" type="text" class="px-4 py-2 rounded-md w-full">
            <button class="bg-blue-500 rounded-md  py-2 px-3">Check Coupon</button>
        </form>
        @error($code)
            {{ $message }}
        @enderror
    </div>
</div>

Unknown column 'couponables.couponable_id'

I encountered error with this line.

$course->coupons()->get();

Column not found: 1054 Unknown column 'couponables.couponable_id' in 'field list'

Simple solution would be to rename column name in couponables table.
Rename the morph field couponables to couponable ?

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.