Weave 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

Sped Da Laravel Package

nfephp-org/sped-da

Biblioteca PHP para gerar PDFs de documentos auxiliares do Sped (DANFE, DACTE, DAMDFE) a partir de XML, baseada nas classes legadas do NFePHP. Foco em conformidade SEFAZ, simplicidade e escopo genérico, sem customizações de sistema.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require nfephp-org/sped-da
    

    Ensure your project uses PHP 7.4+ (last release compatibility).

  2. First Use Case: Generating a SpedDa File

    use NFePHP\Sped\DA\SpedDa;
    
    $spedDa = new SpedDa();
    $spedDa->setCnpj('12345678000100')
           ->setPeriodo('2023-01'); // MM-YYYY format
    
    $xml = $spedDa->generate();
    file_put_contents('sped_da.xml', $xml);
    
  3. Key Files to Explore

    • src/SpedDa.php: Core class for DA generation.
    • src/Entities/: Data models (e.g., Item, Estabelecimento).
    • tests/: Real-world examples and validation logic.

Implementation Patterns

Workflow: Building a DA File

  1. Initialize and Configure

    $da = new SpedDa();
    $da->setCnpj('12345678000100')
       ->setPeriodo('2023-01')
       ->setAmbiente('1'); // 1=Produção, 2=Homologação
    
  2. Add Establishments (Estabelecimento)

    $estabelecimento = new \NFePHP\Sped\DA\Entities\Estabelecimento();
    $estabelecimento->setCnpj('12345678000100')
                    ->setNome('EMPRESA TESTE LTDA')
                    ->setInscricaoEstadual('123456789')
                    ->setCnae('4711500'); // CNAE principal
    
    $da->addEstabelecimento($estabelecimento);
    
  3. Add Items (Item)

    $item = new \NFePHP\Sped\DA\Entities\Item();
    $item->setCodItem('001')
         ->setDescricao('PRODUTO TESTE')
         ->setCodBarra('7891234567890')
         ->setCodNcm('123456')
         ->setUnidade('UN')
         ->setAliquotaIcms(18.00)
         ->setAliquotaIpi(10.00);
    
    $da->addItem($item);
    
  4. Add Transactions (Transacao)

    $transacao = new \NFePHP\Sped\DA\Entities\Transacao();
    $transacao->setCodTransacao('0101') // Venda a vista
               ->setValor(1000.00)
               ->setQuantidade(10)
               ->setCodItem('001')
               ->setCodEstabelecimento('12345678000100');
    
    $da->addTransacao($transacao);
    
  5. Generate and Validate

    $xml = $da->generate();
    $validator = new \NFePHP\Sped\DA\Validator();
    $validator->validate($xml); // Returns array of errors/warnings
    

Integration Tips

  • Laravel Service Provider Bind the SpedDa class for dependency injection:

    $this->app->bind(\NFePHP\Sped\DA\SpedDa::class, function ($app) {
        return new \NFePHP\Sped\DA\SpedDa();
    });
    
  • Queue Jobs for Async Processing Use Laravel Queues to generate DA files in the background:

    class GenerateSpedDaJob implements ShouldQueue
    {
        public function handle()
        {
            $da = new SpedDa();
            // ... configure and generate
            Storage::put('sped_da.xml', $da->generate());
        }
    }
    
  • API Endpoint for DA Generation

    Route::post('/sped-da/generate', function (Request $request) {
        $da = new SpedDa();
        $da->setCnpj($request->cnpj)
           ->setPeriodo($request->periodo);
    
        // Add establishments/items/transactions from request data
        // ...
    
        return response()->streamDownload(
            function () use ($da) {
                echo $da->generate();
            },
            'sped_da.xml'
        );
    });
    

Gotchas and Tips

Pitfalls

  1. Date Format Strictness

    • setPeriodo() expects MM-YYYY (e.g., '01-2023'), not YYYY-MM.
    • Fix: Validate input with:
      if (!preg_match('/^\d{2}-\d{4}$/', $periodo)) {
          throw new \InvalidArgumentException('Formato inválido. Use MM-YYYY.');
      }
      
  2. CNPJ Validation

    • The package does not validate CNPJ format by default.
    • Fix: Use a library like rebn/laravel-cnpj-cpf or validate manually:
      if (!\NFePHP\Sped\DA\Utils::isValidCnpj($cnpj)) {
          throw new \InvalidArgumentException('CNPJ inválido.');
      }
      
  3. XML Namespaces

    • The generated XML uses the Sped DA namespace (http://www.spede.fazenda.gov.br/DA).
    • Tip: If parsing with SimpleXML, explicitly declare the namespace:
      $xml = simplexml_load_string($da->generate());
      $xml->registerXPathNamespace('da', 'http://www.spede.fazenda.gov.br/DA');
      
  4. Floating-Point Precision

    • Financial values (e.g., valor) must use 2 decimal places.
    • Fix: Round values before setting:
      $transacao->setValor(round($valor, 2));
      
  5. Large Files

    • Generating DA files for large datasets may hit memory limits.
    • Tip: Use setUseSimpleXml(false) to disable SimpleXML caching:
      $da->setUseSimpleXml(false);
      

Debugging

  • Enable Verbose Output Set the logger to debug mode:

    $da->setLogger(function ($message) {
        \Log::debug($message);
    });
    
  • Validate Against Schemas Use the built-in validator:

    $validator = new \NFePHP\Sped\DA\Validator();
    $errors = $validator->validate($xml);
    // $errors contains an array of validation issues
    
  • Check for Deprecated Methods The package is outdated (last release 2021). Some methods may be deprecated. Tip: Inspect the source code for @deprecated tags or check the GitHub issues.

Extension Points

  1. Custom Templates Override the default XML template by extending SpedDa:

    class CustomSpedDa extends \NFePHP\Sped\DA\SpedDa
    {
        protected function getTemplatePath()
        {
            return __DIR__ . '/custom_template.xml';
        }
    }
    
  2. Add Custom Entities Extend the Entities namespace to add domain-specific fields:

    namespace App\Sped\DA\Entities;
    
    use NFePHP\Sped\DA\Entities\Item as BaseItem;
    
    class Item extends BaseItem
    {
        protected $customField;
    
        public function setCustomField($value)
        {
            $this->customField = $value;
            return $this;
        }
    }
    
  3. Hooks for Pre/Post Generation Use Laravel events or method overriding:

    $da = new SpedDa();
    $da->setOnGenerate(function ($xml) {
        // Modify XML before generation
        return str_replace('<root>', '<root custom="true">', $xml);
    });
    
  4. Batch Processing For large datasets, implement chunked processing:

    $chunkSize = 1000;
    $transactions = Transaction::chunk($chunkSize, function ($chunk) use ($da) {
        foreach ($chunk as $transaction) {
            $da->addTransacao($transaction->toSpedDaEntity());
        }
        $da->generate()->saveToFile("sped_da_part_{$da->getPeriodo()}.xml");
        $da->reset(); // Clear for next chunk
    });
    
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.
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package