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

Four Tochki Products Laravel Package

baks-dev/four-tochki-products

Laravel/PHP 8.4+ модуль интеграции с 4tochki: импорт и синхронизация каталога продукции, работа со складами партнёра (идентификаторы через b2b.4tochki.ru). Установка через Composer, assets:install, миграции Doctrine; есть PHPUnit-тесты.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:

    composer require baks-dev/four-tochki-products
    
  2. Publish configuration and assets (required for API keys, warehouse IDs, and DB schema):

    php artisan baks:assets:install
    
    • This generates:
      • Config file (config/four-tochki.php) for API credentials and warehouse IDs.
      • Migration files for Doctrine (Laravel-compatible via Symfony bridge).
      • Optional: Service provider registration (if not auto-discovered).
  3. Configure your 4tochki credentials:

    • Edit config/four-tochki.php with:
      • api_key (from 4tochki B2B).
      • warehouse_ids (array of partner warehouse IDs).
      • default_warehouse (for fallback logic).
  4. Run migrations (adapt for Laravel):

    php artisan doctrine:migrations:diff
    php artisan doctrine:migrations:migrate
    
    • Note: If using pure Laravel, replace Doctrine with Eloquent by extending the bundle’s entities (see Implementation Patterns).
  5. First sync test:

    use BaksDev\FourTochki\Product\ProductService;
    
    $service = app(ProductService::class);
    $products = $service->fetchAll(); // Fetches from 4tochki API
    $service->syncToLocal();         // Updates local DB (if configured)
    

First Use Case: Product Catalog Sync

Goal: Sync a subset of 4tochki products to your Laravel app for a marketplace.

  1. Filter products by category (e.g., electronics):
    $products = $service->fetchByCategory('electronics', ['limit' => 50]);
    
  2. Map to your local Product model:
    foreach ($products as $remoteProduct) {
        $localProduct = \App\Models\Product::updateOrCreate(
            ['sku' => $remoteProduct->getSku()],
            [
                'name' => $remoteProduct->getName(),
                'price' => $remoteProduct->getPrice()->getAmount(),
                'warehouse_id' => $remoteProduct->getWarehouseId(),
                'attributes' => $remoteProduct->getAttributes()->toArray(),
            ]
        );
    }
    
  3. Handle images (if using Spatie Media Library):
    $remoteProduct->getImages()->each(function ($image) use ($localProduct) {
        $localProduct->addMediaFromUrl($image->getUrl())->toMediaCollection('4tochki_images');
    });
    

Where to Look First

  • Configuration: config/four-tochki.php (API keys, warehouse IDs).
  • Service Layer: src/Product/ProductService.php (core logic for fetching/syncing).
  • Entities: src/Entity/Product.php (Doctrine models; extend for Laravel).
  • Console Commands: src/Command/ (e.g., SyncProductsCommand for cron jobs).
  • Tests: tests/Unit/ (if any; otherwise, start with API contract tests).

Implementation Patterns

1. Hybrid Symfony-Laravel Integration

Pattern: Use the bundle in a Symfony microservice alongside Laravel, communicating via API.

  • Pros: Isolates Symfony dependencies; easier upgrades.
  • Implementation:
    1. Deploy the bundle in a Dockerized Symfony app (e.g., 4tochki-service).
    2. Expose endpoints for:
      • Product sync: POST /api/products/sync
      • Stock updates: GET /api/warehouses/{id}/stock
    3. Call from Laravel:
      $response = Http::post('http://4tochki-service/api/products/sync', [
          'category' => 'electronics',
      ]);
      

Alternative: Containerize the bundle in Laravel using symfony/console bridge:

// In Laravel service provider
$this->app->singleton('command.baks.install', function ($app) {
    return new \BaksDev\FourTochki\Command\InstallAssetsCommand();
});

2. Event-Driven Workflows

Pattern: Trigger actions on 4tochki API events (e.g., stock updates, order changes).

  • Example: Listen for ProductUpdated events to update Laravel cache.
    use BaksDev\FourTochki\Event\ProductUpdated;
    
    event(new ProductUpdated($remoteProduct));
    
  • Laravel Integration:
    // In EventServiceProvider
    protected $listen = [
        ProductUpdated::class => [
            \App\Listeners\UpdateLocalProduct::class,
        ],
    ];
    

Use Case: Real-time inventory updates without polling.


3. Warehouse-Specific Logic

Pattern: Route products/orders to the correct 4tochki warehouse.

  • Example: Auto-select warehouse based on customer region:
    $warehouseId = app(\BaksDev\FourTochki\Warehouse\WarehouseSelector::class)
        ->selectByRegion($customer->region);
    $product->setWarehouseId($warehouseId);
    

Extension: Create a strategy pattern for warehouse selection:

interface WarehouseStrategy {
    public function select(array $context): string;
}

class RegionBasedStrategy implements WarehouseStrategy {
    public function select(array $context): string {
        return WarehouseRepository::findByRegion($context['region']);
    }
}

4. Bulk Operations

Pattern: Use chunking for large product catalogs.

  • Example: Sync 10,000 products in batches:
    $service = app(ProductService::class);
    $service->syncInBatches(1000); // 1000 products per batch
    
  • Laravel Queue Integration:
    foreach ($products as $batch) {
        SyncProductsJob::dispatch($batch)->delay(now()->addMinutes(1));
    }
    

5. Custom Attributes Handling

Pattern: Map 4tochki’s dynamic attributes to Laravel’s JSON fields.

  • Example: Store attributes in a json column:
    $localProduct->attributes = json_encode([
        'brand' => $remoteProduct->getAttribute('brand'),
        'weight_kg' => $remoteProduct->getAttribute('weight')->getValue(),
    ]);
    
  • Accessors:
    public function getBrandAttribute() {
        return $this->attributes['brand'] ?? null;
    }
    

6. Testing Strategy

Pattern: Contract tests for API responses.

  • Example: Test product sync output:
    public function testProductSyncReturnsExpectedStructure() {
        $response = $this->call('POST', '/api/products/sync', ['category' => 'books']);
        $response->assertJsonStructure([
            'data' => [
                '*' => [
                    'id', 'sku', 'name', 'price', 'warehouse_id',
                    'attributes' => ['*'],
                    'images' => ['*'],
                ],
            ],
        ]);
    }
    

Gotchas and Tips

Pitfalls

  1. Doctrine vs. Eloquent Conflicts:

    • Issue: The bundle uses Doctrine ORM, which may clash with Laravel’s Eloquent.
    • Fix: Extend Doctrine entities to support Eloquent:
      use Doctrine\ORM\Mapping as ORM;
      use Illuminate\Database\Eloquent\Model;
      
      #[ORM\Entity]
      class Product extends Model {
          // Hybrid mapping
      }
      
    • Tip: Use laravel-doctrine/orm bridge for partial compatibility.
  2. API Rate Limits:

    • Issue: 4tochki’s API may throttle requests during bulk syncs.
    • Fix: Implement exponential backoff:
      use Symfony\Component\HttpClient\RetryableHttpClient;
      
      $client = new RetryableHttpClient(
          new \Symfony\Contracts\HttpClient\HttpClient(),
          [
              'max_retries' => 3,
              'delay' => 1000, // 1 second
          ]
      );
      
  3. Warehouse ID Mismatches:

    • Issue: Hardcoded warehouse IDs in config may not match 4tochki’s live system.
    • Fix: Fetch IDs dynamically:
      $warehouses = $service->fetchWarehouses();
      config(['four-tochki.warehouse_ids' => $warehouses->pluck('id')]);
      
  4. Timezone/Date Handling:

    • Issue: 4tochki uses UTC; Laravel may use a different timezone.
    • Fix: Normalize dates in config:
      config(['four-tochki.datetime_format' => 'Y-m-d\TH:i:s\Z']);
      
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.
besmartand-pro/php-quality-config
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