pdv.backend/app/Models/Client.php

79 lines
1.8 KiB
PHP

<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Client extends Model
{
protected $fillable = [
'name',
'client_number',
'email',
'phone',
'address',
'rfc',
'razon_social',
'regimen_fiscal',
'cp_fiscal',
'uso_cfdi',
'tier_id',
'total_purchases',
'total_transactions',
'lifetime_returns',
'last_purchase_at',
];
protected $casts = [
'total_purchases' => 'decimal:2',
'total_transactions' => 'integer',
'lifetime_returns' => 'decimal:2',
'last_purchase_at' => 'datetime',
];
public function sales(): HasMany
{
return $this->hasMany(Sale::class);
}
/**
* Nivel o rango del cliente
*/
public function tier(): BelongsTo
{
return $this->belongsTo(ClientTier::class, 'tier_id');
}
/**
* Historial de cambios de nivel del cliente
*/
public function tierHistory(): HasMany
{
return $this->hasMany(ClientTierHistory::class)->orderBy('changed_at', 'desc');
}
/**
* Descuento aplicable según el nivel del cliente
*/
public function getDiscountPercentageAttribute(): float
{
return $this->tier?->discount_percentage ?? 0;
}
/**
* Compras netas del cliente (total compras - devoluciones)
*/
public function getNetPurchasesAttribute(): float
{
return $this->total_purchases - $this->lifetime_returns;
}
/**
* Solicitudes de factura del cliente
*/
public function invoiceRequests(): HasMany
{
return $this->hasMany(InvoiceRequest::class);
}
}