Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pointsbundle Laravel Package

atm/pointsbundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the bundle via Composer:

    composer require atm/pointsbundle
    

    Register the bundle in config/app.php under providers:

    Atm\PointsBundle\PointsBundle::class,
    

    Publish the bundle’s configuration:

    php artisan vendor:publish --provider="Atm\PointsBundle\PointsBundle" --tag=config
    
  2. Basic Setup

    • Configure points rules in config/points.php (e.g., default_points, expiration_days).
    • Define point types (e.g., purchase, referral) in the database via migrations or seeders.
    • Run migrations:
      php artisan migrate
      
  3. First Use Case: Awarding Points Use the PointsService to award points to a user:

    use Atm\PointsBundle\Services\PointsService;
    
    $pointsService = app(PointsService::class);
    $pointsService->awardPoints(
        userId: 1,
        type: 'purchase',
        amount: 100,
        metadata: ['order_id' => 123]
    );
    

Implementation Patterns

Core Workflows

  1. Awarding Points

    • Use PointsService::awardPoints() for dynamic point allocations.
    • Chain with validation (e.g., check user eligibility via events or middleware):
      event(new UserAwardedPoints($user, $type, $amount));
      
  2. Redeeming Points

    • Implement a RedeemPointsRequest with business logic (e.g., minimum balance checks):
      $redeemed = $pointsService->redeemPoints(
          userId: 1,
          amount: 50,
          redeemableId: 'discount_123'
      );
      
  3. Expiration Handling

    • Schedule a cron job to expire points via PointsService::expirePoints():
      * * * * * php artisan atm:points:expire
      
  4. Integration with Events

    • Listen for PointsAwarded or PointsRedeemed events to trigger side effects (e.g., notifications):
      public function handle(PointsAwarded $event) {
          Notification::send($event->user, new PointsNotification($event->amount));
      }
      

Advanced Patterns

  • Custom Point Types: Extend PointType model or use traits for domain-specific logic.
  • Batch Processing: Use PointsService::batchAward() for bulk operations (e.g., promotions):
    $pointsService->batchAward([
        ['user_id' => 1, 'type' => 'promo', 'amount' => 200],
        ['user_id' => 2, 'type' => 'promo', 'amount' => 200],
    ]);
    
  • API Endpoints: Wrap services in controllers for RESTful access:
    public function award(Request $request) {
        $this->pointsService->awardPoints($request->user(), $request->type, $request->amount);
        return response()->json(['success' => true]);
    }
    

Gotchas and Tips

Common Pitfalls

  1. Transaction Management

    • Always wrap point operations in transactions to avoid partial updates:
      DB::transaction(function () use ($pointsService) {
          $pointsService->awardPoints(...);
          // Other related DB operations
      });
      
  2. Expiration Logic

    • Ensure expiration_days in config aligns with business needs (e.g., null for never-expiring points).
    • Test edge cases where points expire during redemption.
  3. Metadata Serialization

    • Store metadata as JSON in the metadata column. Use json_encode()/json_decode() carefully to avoid type issues.
  4. Race Conditions

    • Use selectForUpdate() for critical operations (e.g., redeeming points):
      $userPoints = UserPoints::where('user_id', $userId)->lockForUpdate()->first();
      

Debugging Tips

  • Log Points Activity: Enable logging in config/points.php to track awards/redemptions:
    'logging' => [
        'enabled' => true,
        'channel' => 'points',
    ],
    
  • Query Debugging: Use Laravel Debugbar to inspect UserPoints queries.
  • Test Edge Cases: Validate behavior when:
    • Points exceed max_points_per_type.
    • A user redeems more points than they have.
    • The database connection drops mid-operation.

Extension Points

  1. Custom Validators Override Atm\PointsBundle\Validators\PointsValidator to add rules (e.g., blacklisted users):

    public function validateAward($user, $type, $amount) {
        if ($user->isBlacklisted()) {
            throw new \Exception("Blacklisted users cannot earn points.");
        }
        parent::validateAward($user, $type, $amount);
    }
    
  2. Event Listeners Extend the bundle’s events (e.g., PointsAwarded) to integrate with third-party services:

    public function handle(PointsAwarded $event) {
        Analytics::track($event->user, 'points_awarded', ['type' => $event->type]);
    }
    
  3. Custom Storage Replace the default UserPoints model with a trait or interface for alternative storage (e.g., Redis):

    class RedisUserPoints extends UserPoints {
        use \Atm\PointsBundle\Traits\RedisPointsStorage;
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware