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

Relay Checkin Bundle Laravel Package

dbp/relay-checkin-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the Bundle**
   ```bash
   composer require dbp/relay-checkin-bundle
   php artisan vendor:publish --provider="Dbp\RelayCheckinBundle\RelayCheckinBundle" --tag="config"
  • Publish the default config to config/relay_checkin.php.
  1. Configure Required Services

    • Update config/relay_checkin.php with:
      • campus_qr_api_url (your CampusQR instance endpoint).
      • database_connection (if using local storage for check-ins).
      • encryption_key (for secure QR code generation).
    • Ensure the CAMPUS_QR_API_KEY environment variable is set.
  2. Run Migrations

    php artisan migrate
    
    • The bundle includes tables for checkins, locations, and users (if using local storage).
  3. First Use Case: Register a Location

    use Dbp\RelayCheckinBundle\Service\LocationService;
    
    $locationService = app(LocationService::class);
    $location = $locationService->create([
        'name' => 'Main Campus Building',
        'code' => 'BUILDING_01',
    ]);
    
    • This generates a QR code for the location (stored in storage/app/qr_codes/).

Implementation Patterns

Core Workflows

1. Handling Check-Ins

  • Frontend Integration:

    • The frontend app (checkin-app) scans QR codes and sends check-in data to this bundle via API.
    • Expose an API endpoint (e.g., /api/checkin) using Laravel’s Route::post:
      Route::post('/api/checkin', [CheckinController::class, 'store']);
      
    • Validate incoming data (e.g., user_id, location_id, timestamp):
      use Dbp\RelayCheckinBundle\DTO\CheckinDTO;
      
      public function store(Request $request) {
          $dto = new CheckinDTO(
              $request->user_id,
              $request->location_id,
              $request->timestamp ?? now()
          );
          $checkinService = app(CheckinService::class);
          $checkin = $checkinService->create($dto);
          return response()->json($checkin);
      }
      
  • Sync with CampusQR:

    • Use the CampusQRApiService to relay check-ins to CampusQR:
      $apiService = app(CampusQRApiService::class);
      $apiService->relayCheckin($checkin->user_id, $checkin->location_id, $checkin->timestamp);
      

2. Location Management

  • Bulk Location Setup:
    $locationService = app(LocationService::class);
    $locations = [
        ['name' => 'Lab A', 'code' => 'LAB_A'],
        ['name' => 'Lab B', 'code' => 'LAB_B'],
    ];
    foreach ($locations as $data) {
        $locationService->create($data);
    }
    
  • QR Code Generation:
    • QR codes are auto-generated on location creation and stored in storage/app/qr_codes/{location_code}.png.
    • Customize the QR content (e.g., include a salt for security):
      $locationService->setQrContentGenerator(function ($location) {
          return "LOCATION:{$location->code}:SALT_" . config('app.key');
      });
      

3. User Checkin History

  • Fetch a user’s check-in history:
    $checkinService = app(CheckinService::class);
    $history = $checkinService->getUserHistory($userId, now()->subDays(7));
    
  • Export history to CSV for reporting:
    use Illuminate\Support\Facades\Storage;
    
    $csv = $checkinService->exportUserHistory($userId);
    Storage::put('exports/checkin_history_{$userId}.csv', $csv);
    

4. Contact Tracing Alerts

  • Subscribe to CampusQR webhooks for COVID-19 alerts:
    Route::post('/api/campusqr/webhook', [CampusQRWebhookController::class, 'handle']);
    
  • Trigger alerts for exposed users:
    $alertService = app(AlertService::class);
    $alertService->notifyExposedUsers($exposedUserId, now()->subHours(2));
    

Integration Tips

Laravel Ecosystem

  • Events:
    • Listen to CheckinCreated events for real-time processing:
      Event::listen(CheckinCreated::class, function ($event) {
          // Send Slack notification or log to a third-party system
      });
      
  • Jobs:
    • Offload CampusQR sync to a queue job:
      RelayCheckinToCampusQR::dispatch($checkin);
      
  • Testing:
    • Mock CampusQRApiService in unit tests:
      $this->partialMock(CampusQRApiService::class, function ($mock) {
          $mock->shouldReceive('relayCheckin')->once();
      });
      

Frontend Sync

  • API Versioning:
    • Version your API endpoints (e.g., /api/v1/checkin) to avoid breaking changes.
  • Rate Limiting:
    • Protect check-in endpoints:
      Route::middleware(['throttle:60,1'])->post('/api/checkin', ...);
      

Gotchas and Tips

Pitfalls

  1. CampusQR API Dependencies:

    • The bundle requires a running CampusQR instance. Test locally using Docker or a staging environment:
      docker-compose up -d dbp/check-in/campus-qr
      
    • Error: ClientException if the API URL or key is misconfigured. Verify with:
      curl -X GET {campus_qr_api_url}/health -H "Authorization: Bearer $CAMPUS_QR_API_KEY"
      
  2. QR Code Security:

    • Gotcha: Hardcoded QR content may expose location data. Always include a salt or timestamp:
      $locationService->setQrContentGenerator(function ($location) {
          return "LOCATION:{$location->code}:{$location->updated_at->timestamp}";
      });
      
    • Tip: Use Laravel’s Str::random(32) for dynamic salts.
  3. Database Schema Mismatches:

    • Gotcha: Custom migrations may conflict with the bundle’s default schema. Use:
      php artisan vendor:publish --tag="migrations"
      
      to publish the bundle’s migrations before running php artisan migrate.
  4. Timezone Handling:

    • Gotcha: Check-in timestamps must match CampusQR’s timezone. Configure in config/relay_checkin.php:
      'timezone' => 'Europe/Vienna', // Default in CampusQR
      
    • Tip: Use Carbon’s setTimezone() when processing timestamps:
      $checkin->timestamp->setTimezone(config('relay_checkin.timezone'));
      
  5. Webhook Delays:

    • Gotcha: CampusQR webhooks may have latency. Implement retry logic:
      use Illuminate\Support\Facades\Http;
      
      $response = Http::withOptions(['timeout' => 10])
          ->post($campusQrUrl, $payload)
          ->throw();
      

Debugging

  1. Logging:

    • Enable debug mode in config/relay_checkin.php:
      'debug' => env('APP_ENV') === 'local',
      
    • Log API responses:
      $apiService->setDebugMode(true);
      
  2. Common Errors:

    • InvalidLocationException: Thrown if a location code doesn’t exist. Validate with:
      if (!$locationService->exists($locationCode)) {
          throw new InvalidLocationException("Location {$locationCode} not found.");
      }
      
    • DuplicateCheckinException: Prevent duplicates by checking:
      if ($checkinService->existsForUserAndLocation($userId, $locationId, $timestamp)) {
          throw new DuplicateCheckinException("Already checked in.");
      }
      
  3. Performance:

    • Tip: Index checkins table for large datasets:
      Schema::table('checkins', function (Blueprint $table) {
          $table->index(['user_id', 'location_id', 'timestamp']);
      });
      

Extension Points

  1. Custom Checkin Logic:
    • Override the CheckinService to add validation:
      $checkinService = app(CheckinService::class);
      $checkinService->setValidator(function ($dto) {
      
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