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

Materials Sign Laravel Package

baks-dev/materials-sign

Laravel/PHP модуль для работы с «Честным знаком» по сырью: импорт и обработка кодов маркировки, генерация/печать этикеток и штрихкодов. Поддерживает загрузку файлов, обрезку PDF (pdfcrop/ImageMagick) и установку ассетов/миграций.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install Dependencies

    composer require baks-dev/materials-sign baks-dev/barcode phpoffice/phpspreadsheet
    

    Ensure PHP 8.4+ is installed.

  2. Set Up File Storage Create and configure the upload directory:

    mkdir -p public/upload/material_sign_code
    chown -R www-data:www-data public/upload/material_sign_code  # Adjust user/group as needed
    
  3. Install System Tools On Ubuntu/Debian:

    sudo apt install pdftk imagemagick texlive-extra-utils
    

    Configure sudo for pdfcrop (add to /etc/sudoers):

    www-data ALL=(ALL) NOPASSWD: /usr/bin/pdfcrop
    

    Update ImageMagick policy (/etc/ImageMagick-6/policy.xml):

    <policy domain="coder" rights="read|write" pattern="PDF"/>
    
  4. Run Asset Installation

    php artisan baks:assets:install  # Assumes SymfonyBridge or custom Artisan wrapper
    
  5. Database Setup Generate and run migrations:

    php artisan doctrine:migrations:diff
    php artisan doctrine:migrations:migrate
    

    Note: Laravel users must adapt Doctrine commands to Eloquent or use a bridge like symfony/bridge.

  6. First Use Case Upload a material sign PDF via the package’s controller (e.g., MaterialSignController@upload). Verify:

    • Barcode generation (via baks-dev/barcode).
    • PDF cropping (check public/upload/material_sign_code/ for processed files).

Implementation Patterns

Core Workflows

1. Material Sign Upload & Processing

  • Workflow:
    1. User uploads a PDF (e.g., via MaterialSignController).
    2. Package validates the file, extracts metadata (e.g., material codes).
    3. Generates barcodes/QR codes (using baks-dev/barcode) and embeds them in the PDF.
    4. Crops whitespace using pdfcrop and saves to public/upload/material_sign_code/.
  • Code Example:
    // Pseudocode for Laravel integration
    use BaksDev\MaterialsSign\Services\MaterialSignProcessor;
    
    $processor = new MaterialSignProcessor();
    $processedPath = $processor->processUpload(
        $request->file('material_sign_pdf'),
        $materialId
    );
    

2. Batch Processing

  • Use the baks:material-sign:batch command (if available) or loop through files:
    foreach ($materialFiles as $file) {
        $processor->processUpload($file, $materialId);
    }
    
  • Tip: Queue long-running processes with Laravel Queues for large batches.

3. PDF Template Customization

  • Override default templates by publishing assets:
    php artisan vendor:publish --tag=materials-sign-assets
    
  • Modify resources/views/materials-sign/ templates to match branding.

4. Barcode Generation

  • Leverage baks-dev/barcode for dynamic codes:
    use BaksDev\Barcode\BarcodeGenerator;
    
    $barcode = BarcodeGenerator::generate(
        'DATA:' . $material->code,
        'QRCODE',
        ['margin' => 10]
    );
    $processor->embedBarcode($barcode, $pdfPath);
    

5. Database Integration

  • Store processed files in a material_signs table (migration example):
    // Schema for Laravel (adapt from Doctrine)
    Schema::create('material_signs', function (Blueprint $table) {
        $table->id();
        $table->string('material_code');
        $table->string('file_path');
        $table->string('barcode_data');
        $table->timestamps();
    });
    

Integration Tips

  • Symfony/Laravel Bridge: Use symfony/bridge or wrap Symfony components in Laravel services. Example:

    // app/Services/MaterialSignService.php
    class MaterialSignService {
        protected $processor;
    
        public function __construct() {
            $this->processor = new \BaksDev\MaterialsSign\Services\MaterialSignProcessor();
        }
    
        public function process($file) {
            return $this->processor->processUpload($file, auth()->id());
        }
    }
    
  • Event-Driven Workflows: Trigger actions after processing:

    event(new MaterialSignProcessed($materialSign));
    

    Listen for updates (e.g., send notifications):

    MaterialSignProcessed::listen(function ($event) {
        Notification::send($event->user, new MaterialSignReady($event->filePath));
    });
    
  • Testing: Mock PDF processing in unit tests:

    $processor = $this->mock(MaterialSignProcessor::class);
    $processor->shouldReceive('cropPdf')->andReturn('cropped.pdf');
    
  • API Endpoints: Expose processing via Laravel API:

    Route::post('/material-signs', [MaterialSignController::class, 'store']);
    
    // MaterialSignController.php
    public function store(Request $request) {
        $path = app(MaterialSignService::class)->process($request->file('pdf'));
        return response()->json(['path' => $path]);
    }
    

Gotchas and Tips

Pitfalls

  1. PDF Processing Dependencies:

    • Issue: pdftk/imagemagick may fail silently if permissions or policies are misconfigured.
    • Fix: Test locally with:
      sudo -u www-data pdfcrop input.pdf
      
      Check logs in /var/log/syslog for errors.
  2. Doctrine vs. Eloquent Conflicts:

    • Issue: Doctrine migrations won’t work out-of-the-box in Laravel.
    • Fix: Use doctrine/dbal for raw SQL or rewrite migrations with Eloquent:
      // Example: Convert Doctrine migration to Eloquent
      Schema::create('material_signs', function (Blueprint $table) {
          $table->id();
          $table->string('material_code')->unique();
          $table->string('file_path');
          $table->timestamps();
      });
      
  3. Barcode Generation Failures:

    • Issue: baks-dev/barcode may throw errors if fonts or libraries are missing.
    • Fix: Ensure libgd and libpng are installed:
      sudo apt install libgd-dev libpng-dev
      
  4. File Path Hardcoding:

    • Issue: Upload paths are hardcoded (public/upload/material_sign_code).
    • Fix: Override via config:
      // config/materials-sign.php
      'storage' => [
          'path' => storage_path('app/material_signs'),
      ],
      
      Update the service to use the config path.
  5. Memory Limits:

    • Issue: Large PDFs may exceed PHP’s memory_limit.
    • Fix: Increase in php.ini or process files in chunks:
      ini_set('memory_limit', '512M');
      
  6. Timezone Issues:

    • Issue: PDF timestamps may use server timezone instead of user’s.
    • Fix: Set timezone explicitly:
      date_default_timezone_set('Europe/Moscow'); // Adjust as needed
      

Debugging Tips

  • Log PDF Processing: Add logging to MaterialSignProcessor:

    \Log::info('PDF processing started', ['file' => $file->getPathname()]);
    \Log::debug('PDF crop command', ['command' => $this->getCropCommand($file)]);
    
  • Validate Barcodes: Use a QR/barcode scanner to verify generated codes match input data.

  • Check File Permissions: Ensure the web server user (e.g., www-data) has write access to upload directories:

    ls -la public/upload/material_sign_code
    
  • Test PDF Cropping: Manually run pdfcrop to isolate issues:

    pdfcrop --demo input.pdf output.pdf
    

Extension Points

  1. Custom PDF Templates:

    • Override resources/views/materials-sign/templates/ to modify layouts.
    • Extend the MaterialSignTemplate class to add dynamic content.
  2. Additional Barcode Types:

    • Extend BarcodeGenerator to support new formats (e.g., DataMatrix):
      public static function generateDataMatrix(string $data, array $options = []): string {
          // Custom implementation
      }
      
  3. Blockchain Integration:

    • Hook into the MaterialSignProcessed event to send data to a blockchain:
      MaterialSignProcessed::listen
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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