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

Products Stocks Telegram Laravel Package

baks-dev/products-stocks-telegram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require baks-dev/products-stocks-telegram
    php bin/console baks:assets:install
    
    • This installs the package and publishes config/files (e.g., migrations, views, or assets).
  2. Run Migrations:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
    • Ensures database tables for stock tracking (e.g., product_stocks, telegram_notifications) are created.
  3. Configure Telegram Bot:

    • Edit config/products-stocks-telegram.php to set:
      • bot_token: Your Telegram bot token (from @BotFather).
      • admin_chat_ids: Array of Telegram user IDs to notify (e.g., [12345678, 87654321]).
      • low_stock_threshold: Trigger value (e.g., 5) for stock alerts.
  4. First Use Case:

    • Manual Stock Update:
      use BaksDev\ProductsStocksTelegram\Services\StockService;
      
      $stockService = app(StockService::class);
      $stockService->updateStock($productId, $quantity);
      
    • Trigger a Telegram Alert:
      $stockService->checkAndNotifyLowStock();
      

Implementation Patterns

Core Workflows

  1. Stock Management:

    • CRUD Operations: Use the StockService facade (or inject StockService) to manage product quantities:
      // Update stock via API/CLI
      StockService::updateStock($productId, $newQuantity);
      
      // Get stock for a product
      $stock = StockService::getStock($productId);
      
    • Bulk Updates:
      StockService::bulkUpdate([$productId1 => $qty1, $productId2 => $qty2]);
      
  2. Telegram Notifications:

    • Automated Alerts: Schedule checkAndNotifyLowStock() via Laravel’s scheduler (app/Console/Kernel.php):
      $schedule->command('baks:stocks:check')->dailyAt('9:00');
      
    • Manual Triggers:
      StockService::notifyAdmin($productId, $message);
      
  3. Integration with E-Commerce:

    • Listen to Order Events: Hook into Laravel events (e.g., order.placed) to deduct stock:
      use BaksDev\ProductsStocksTelegram\Listeners\DeductStockOnOrder;
      
      // Register in EventServiceProvider
      protected $listen = [
          'order.placed' => [DeductStockOnOrder::class],
      ];
      
    • Sync with Inventory: Use StockService::syncWithInventory() to reconcile stock with a third-party system.
  4. API Endpoints:

    • Expose Stock Data: Create a controller to return stock levels:
      use BaksDev\ProductsStocksTelegram\Http\Controllers\StockController;
      
      Route::get('/api/stock/{productId}', [StockController::class, 'getStock']);
      
  5. Telegram Bot Commands:

    • Custom Commands: Extend the bot’s command handler (app/Commands/StockCommands.php):
      protected $commands = [
          'stock' => 'BaksDev\ProductsStocksTelegram\Commands\StockCommand',
          'update' => 'App\Commands\CustomUpdateCommand', // Your custom command
      ];
      

Gotchas and Tips

Pitfalls

  1. Telegram Bot Token Security:

    • Never hardcode the bot_token in config. Use Laravel’s .env:
      TELEGRAM_BOT_TOKEN=your_token_here
      
    • Restrict bot permissions to avoid abuse.
  2. Race Conditions:

    • Stock updates via multiple sources (e.g., API + Telegram) can cause inconsistencies.
    • Solution: Use database transactions or optimistic locking:
      DB::transaction(function () use ($productId, $quantity) {
          StockService::updateStock($productId, $quantity);
      });
      
  3. Low Stock Threshold:

    • Default threshold may not suit all products (e.g., perishables vs. electronics).
    • Tip: Override globally in config or per-product via a stock_threshold column.
  4. Timezone Issues:

    • Scheduled notifications may fire at unexpected times if the server’s timezone isn’t set in .env:
      APP_TIMEZONE=UTC
      
  5. Missing Product Handling:

    • StockService::updateStock() assumes the product exists. Add validation:
      if (!$product = Product::find($productId)) {
          throw new \InvalidArgumentException("Product not found");
      }
      

Debugging

  1. Telegram Notifications:

    • Check if the bot is muted or blocked by admins. Test with:
      php bin/console baks:telegram:send-test
      
    • Enable debug logs in config/logging.php for baks-dev/products-stocks-telegram.
  2. Stock Mismatches:

    • Compare stock in the database with physical inventory:
      $stock = StockService::getStock($productId);
      $physicalCount = InventoryService::getPhysicalCount($productId);
      
  3. Command Failures:

    • Telegram commands may fail silently. Add error handling:
      try {
          StockService::processCommand($update);
      } catch (\Exception $e) {
          \Log::error("Telegram command failed: " . $e->getMessage());
      }
      

Extension Points

  1. Custom Notifications:

    • Extend the NotificationService to send emails/SMS alongside Telegram:
      class CustomNotificationService extends \BaksDev\ProductsStocksTelegram\Services\NotificationService
      {
          public function sendLowStockAlert($product, $stockLevel)
          {
              parent::sendLowStockAlert($product, $stockLevel);
              Mail::to('admin@example.com')->send(new LowStockMail($product));
          }
      }
      
    • Bind the service in config/products-stocks-telegram.php:
      'notification_service' => \App\Services\CustomNotificationService::class,
      
  2. Additional Stock Sources:

    • Integrate with ERP systems by implementing StockSourceInterface:
      class ErpStockSource implements StockSourceInterface
      {
          public function getStock($productId): int
          {
              return $this->erpClient->fetchStock($productId);
          }
      }
      
    • Register in the service provider:
      $this->app->bind(StockSourceInterface::class, ErpStockSource::class);
      
  3. UI Integration:

    • Publish and extend the package’s views:
      php artisan vendor:publish --tag=products-stocks-telegram-views
      
    • Override templates in resources/views/vendor/baks-dev/products-stocks-telegram/.
  4. Webhook for Real-Time Updates:

    • Add a webhook endpoint to receive stock updates from external systems:
      Route::post('/webhook/stock', function (Request $request) {
          $data = $request->validate(['product_id' => 'required', 'quantity' => 'required']);
          StockService::updateStock($data['product_id'], $data['quantity']);
      });
      
  5. Localization:

    • Translate Telegram messages by extending the language files:
      php artisan vendor:publish --tag=products-stocks-telegram-lang
      
    • Add custom translations to resources/lang/en/products-stocks-telegram.php.
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky