PHP code example of numerar / contable

1. Go to this page and download the library: Download numerar/contable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

numerar / contable example snippets


'web_prefix'     => 'contabilidad',           // /contabilidad/...
'web_middleware' => ['web', 'auth'],           // añade auth para proteger la UI
'api_prefix'     => 'api/contabilidad',
'api_middleware' => ['api', 'auth:sanctum'],

'features' => [
    'web' => true,   // interfaz Blade
    'api' => true,   // API REST JSON
],

use Illuminate\Support\Facades\Gate;

Gate::define('contable.access',  fn($u) => $u->hasRole(['admin', 'contador']));
Gate::define('contable.entries', fn($u) => $u->hasRole(['admin', 'contador']));
Gate::define('contable.reports', fn($u) => $u->hasRole(['admin', 'contador', 'auditor']));
Gate::define('contable.admin',   fn($u) => $u->hasRole('admin'));

// config/contable.php
'tenancy' => [
    'enabled' => true,
    'column'  => 'tenant_id',
],

use Numerar\Contable\Facades\Contable;

Contable::resolveTenantUsing(fn() => auth()->user()?->company_id);

// config/contable.php
'terceros' => [
    [
        'model'             => \App\Models\Proveedor::class,
        'label'             => 'Proveedores',
        'display_attribute' => 'razon_social',
        'search_attributes' => ['razon_social', 'nit'],
    ],
    [
        'model'             => \App\Models\Cliente::class,
        'label'             => 'Clientes',
        'display_attribute' => 'nombre',
        'search_attributes' => ['nombre', 'identificacion'],
    ],
],

// app/Models/MiCuenta.php
class MiCuenta extends \Numerar\Contable\Models\Account
{
    // tus personalizaciones
}

// config/contable.php
'models' => [
    'account' => \App\Models\MiCuenta::class,
    // el resto sigue igual...
],

use Numerar\Contable\Facades\Contable;

// Crear el periodo si aún no existe
Contable::createPeriod([
    'year'       => 2025,
    'month'      => 1,
    'start_date' => '2025-01-01',
    'end_date'   => '2025-01-31',
]);

$entry = Contable::createEntry([
    'entry_type'  => 'CI',          // código del tipo de comprobante
    'date'        => '2025-01-15',
    'description' => 'Venta de mercancía al contado',
    'created_by'  => auth()->id(),  // opcional

    'lines' => [
        [
            'account_id'  => 111,   // id de la cuenta Caja (1105)
            'debit'       => 1190000,
            'credit'      => 0,
            'description' => 'Recaudo en efectivo',
        ],
        [
            'account_id'  => 340,   // id de la cuenta IVA generado (240805)
            'debit'       => 0,
            'credit'      => 190000,
            'description' => 'IVA 19%',
        ],
        [
            'account_id'  => 210,   // id de la cuenta Ventas (4101)
            'debit'       => 0,
            'credit'      => 1000000,
            'description' => 'Venta mercancía',
            // opcional: tercero polimórfico
            'third_party_type' => \App\Models\Cliente::class,
            'third_party_id'   => 7,
            // opcional: centro de costo
            'cost_center_id'   => 2,
        ],
    ],
]);
// $entry->entry_number  → "CI-0001/2025"
// $entry->status        → EntryStatus::POSTED

Contable::updateEntry($entry, [
    'description' => 'Descripción corregida',
    'lines'       => [...],   // reemplaza todas las líneas
]);

Contable::voidEntry($entry);
// o por id:
Contable::voidEntry(42);

use Numerar\Contable\Exceptions\UnbalancedEntryException;
use Numerar\Contable\Exceptions\PeriodClosedException;

try {
    Contable::createEntry([...]);
} catch (PeriodClosedException $e) {
    // abrir el periodo primero
} catch (UnbalancedEntryException $e) {
    // $e->getMessage() incluye el valor de la diferencia
}
bash
php artisan contable:install
bash
# Cargar el catálogo completo PUC (973 cuentas)
php artisan contable:install --with-puc

# Reinstalar desde cero (¡destructivo: elimina las tablas!)
php artisan contable:install --fresh

# Instalar sin datos iniciales
php artisan contable:install --no-seed
bash
# Configuración
php artisan vendor:publish --tag=contable-config

# Migraciones
php artisan vendor:publish --tag=contable-migrations

# Vistas Blade (para personalizar la UI)
php artisan vendor:publish --tag=contable-views

# Assets CSS (se copia automáticamente con contable:install)
php artisan vendor:publish --tag=contable-assets --force

src/
├── ContableServiceProvider.php
├── Console/Commands/InstallCommand.php
├── Database/Seeders/
│   ├── AccountClassSeeder.php      # 9 clases PUC
│   └── EntryTypeSeeder.php         # CI, CE, CD, CA, CO, NC, CIE
├── Enums/                          # AccountNature, AccountType, EntryStatus...
├── Exceptions/                     # UnbalancedEntry, PeriodClosed...
├── Facades/Contable.php
├── Http/
│   ├── Controllers/                # Controladores Blade
│   ├── Controllers/Api/            # Controladores JSON
│   ├── Requests/                   # Form Requests
│   └── Resources/                  # API Resources
├── Models/                         # 10 modelos Eloquent
├── Services/
│   ├── AccountingService.php       # Façade principal, tenant resolver
│   ├── EntryService.php            # Crear, editar, anular comprobantes
│   ├── FiscalYearService.php       # Cierre de ejercicio y resultado
│   └── ReportService.php           # 7 reportes contables
├── Traits/
│   ├── HasTenancy.php
│   └── HasAuditFields.php
├── database/migrations/            # 10 migraciones
└── helpers.php