'date', 'data_scadenza' => 'date', 'data_registrazione' => 'date', 'data_pagamento' => 'date', 'imponibile' => 'decimal:2', 'iva' => 'decimal:2', 'totale' => 'decimal:2', 'ritenuta_acconto' => 'decimal:2', 'netto_a_pagare' => 'decimal:2' ]; const TIPO_FATTURA = 'fattura'; const TIPO_RICEVUTA = 'ricevuta'; const TIPO_NOTA_CREDITO = 'nota_credito'; const TIPO_NOTA_DEBITO = 'nota_debito'; const STATO_EMESSA = 'emessa'; const STATO_PAGATA = 'pagata'; const STATO_SCADUTA = 'scaduta'; const STATO_STORNATA = 'stornata'; public function amministratore(): BelongsTo { return $this->belongsTo(Administrator::class); } public function stabile(): BelongsTo { return $this->belongsTo(StabileGescon::class); } public function fornitore(): BelongsTo { return $this->belongsTo(FornitoreGescon::class); } public function versamenti() { return $this->hasMany(VersamentoFiscale::class, 'fattura_id'); } public function scopePagate($query) { return $query->where('stato_pagamento', self::STATO_PAGATA); } public function scopeScadute($query) { return $query->where('data_scadenza', '<', now()) ->where('stato_pagamento', self::STATO_EMESSA); } public function scopeByTipo($query, $tipo) { return $query->where('tipo_documento', $tipo); } public function scopeByFornitore($query, $fornitoreId) { return $query->where('fornitore_id', $fornitoreId); } public function scopeByPeriodo($query, $dataInizio, $dataFine) { return $query->whereBetween('data_fattura', [$dataInizio, $dataFine]); } public function getIsScadutaAttribute() { return $this->data_scadenza < now() && $this->stato_pagamento === self::STATO_EMESSA; } public function getGiorniRitardoAttribute() { if (!$this->is_scaduta) { return 0; } return now()->diffInDays($this->data_scadenza); } public function getAliquotaIvaAttribute() { if ($this->imponibile <= 0) { return 0; } return round(($this->iva / $this->imponibile) * 100, 2); } public function getTipoDocumentoLabelAttribute() { $labels = [ self::TIPO_FATTURA => 'Fattura', self::TIPO_RICEVUTA => 'Ricevuta', self::TIPO_NOTA_CREDITO => 'Nota di Credito', self::TIPO_NOTA_DEBITO => 'Nota di Debito' ]; return $labels[$this->tipo_documento] ?? $this->tipo_documento; } }