# Script de Criação das Tabelas de Nota Fiscal (NFS-e)

Para implementar a lógica da Nota Fiscal Eletrônica no outro projeto, você precisará desta estrutura no banco de dados. Abaixo estão as opções em **Laravel Migration (PHP)** e em **SQL puro** (caso o projeto não use Laravel).

O conceito fundamental é guardar o "Contas a Receber" e os status e anexos retornados pela Digisan.

---

## Opção 1: Laravel Migration (PHP)
Salve este código como uma nova migration, por exemplo: `database/migrations/2026_05_01_000000_create_fin_contas_e_nfse_table.php`.

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // 1. Cria a Tabela Principal (Faturas/Contas a Receber)
        Schema::create('fin_contas_receber', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('empresa_id')->comment('ID do Cliente associado');
            $table->decimal('valor_total', 15, 2)->comment('Valor dos servicos faturados');
            $table->date('data_vencimento')->comment('Vencimento do boleto/fatura');
            $table->date('data_pagamento')->nullable();
            $table->tinyInteger('status')->default(1)->comment('1=pendente, 2=vencido, 3=pago, 4=cancelado');
            
            // ============================================
            // CAMPOS ESPECÍFICOS PARA A NOTA FISCAL (NFS-e)
            // ============================================
            $table->enum('status_faturamento', ['A_FATURAR', 'EM_PROCESSAMENTO', 'FATURADO', 'CANCELADO', 'ERRO'])
                  ->default('A_FATURAR')
                  ->comment('Status de integridade com a API Digisan');

            $table->string('id_faturamento')->nullable()
                  ->comment('ID Único de rastreamento retornado pela Digisan');

            $table->text('url_pdf_nfse')->nullable()
                  ->comment('Link público do PDF recebido pelo webhook da Digisan');

            $table->text('url_xml_nfse')->nullable()
                  ->comment('Link público do XML recebido pelo webhook da Digisan');

            $table->text('mensagem_erro_nfse')->nullable()
                  ->comment('Caso dê erro no webhook, grava o motivo de rejeição fiscal aqui');

            $table->text('observacoes')->nullable();
            $table->timestamps();

            // Chaves Estrangeiras, se necessário
            // $table->foreign('empresa_id')->references('id')->on('empresas')->onDelete('cascade');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('fin_contas_receber');
    }
};
```

---

## Opção 2: SQL Direto (MySQL / PostgreSQL)
Se preferir rodar no banco de dados diretamente via SGBD (DBeaver, MySQL Workbench, etc), execute o script:

```sql
CREATE TABLE `fin_contas_receber` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `empresa_id` bigint unsigned NOT NULL COMMENT 'ID do Cliente associado',
  `valor_total` decimal(15,2) NOT NULL COMMENT 'Valor dos servicos faturados',
  `data_vencimento` date NOT NULL,
  `data_pagamento` date DEFAULT NULL,
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '1=pendente, 2=vencido, 3=pago, 4=cancelado',
  
  -- Campos de Nota Fiscal (Integração Digisan)
  `status_faturamento` enum('A_FATURAR','EM_PROCESSAMENTO','FATURADO','CANCELADO','ERRO') NOT NULL DEFAULT 'A_FATURAR' COMMENT 'Status de integridade com a API Digisan',
  `id_faturamento` varchar(255) DEFAULT NULL COMMENT 'ID Unico de rastreamento retornado pela Digisan',
  `url_pdf_nfse` text DEFAULT NULL COMMENT 'Link publico do PDF recebido pelo webhook',
  `url_xml_nfse` text DEFAULT NULL COMMENT 'Link publico do XML recebido pelo webhook',
  `mensagem_erro_nfse` text DEFAULT NULL COMMENT 'Motivo de rejeicao fiscal',
  
  `observacoes` text,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  
  PRIMARY KEY (`id`),
  KEY `fin_contas_receber_empresa_id_index` (`empresa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

> **Dica**: Caso a tabela financeira do outro projeto **já exista**, você pode ignorar a criação inteira e usar apenas scripts do tipo `ALTER TABLE fin_contas_receber ADD COLUMN ...` com os campos focados em NFS-e.
