mirror of
https://github.com/crater-invoice/crater.git
synced 2025-10-28 12:11:08 -04:00
122 lines
2.8 KiB
PHP
122 lines
2.8 KiB
PHP
<?php
|
|
namespace Crater;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Crater\InvoiceItem;
|
|
use Crater\EstimateItem;
|
|
use Carbon\Carbon;
|
|
|
|
class Item extends Model
|
|
{
|
|
protected $fillable = [
|
|
'name',
|
|
'unit',
|
|
'price',
|
|
'company_id',
|
|
'description'
|
|
];
|
|
|
|
protected $casts = [
|
|
'price' => 'integer'
|
|
];
|
|
|
|
protected $appends = [
|
|
'formattedCreatedAt'
|
|
];
|
|
|
|
public function unit()
|
|
{
|
|
return $this->belongsTo(Unit::class);
|
|
}
|
|
|
|
public function scopeWhereSearch($query, $search)
|
|
{
|
|
return $query->where('items.name', 'LIKE', '%'.$search.'%');
|
|
}
|
|
|
|
public function scopeWherePrice($query, $price)
|
|
{
|
|
return $query->where('items.price', $price);
|
|
}
|
|
|
|
public function scopeWhereUnit($query, $unit_id)
|
|
{
|
|
return $query->where('items.unit_id', $unit_id);
|
|
}
|
|
|
|
public function scopeWhereOrder($query, $orderByField, $orderBy)
|
|
{
|
|
$query->orderBy($orderByField, $orderBy);
|
|
}
|
|
|
|
public function scopeApplyFilters($query, array $filters)
|
|
{
|
|
$filters = collect($filters);
|
|
|
|
if ($filters->get('search')) {
|
|
$query->whereSearch($filters->get('search'));
|
|
}
|
|
|
|
if ($filters->get('price')) {
|
|
$query->wherePrice($filters->get('price'));
|
|
}
|
|
|
|
if ($filters->get('unit_id')) {
|
|
$query->whereUnit($filters->get('unit_id'));
|
|
}
|
|
|
|
if ($filters->get('orderByField') || $filters->get('orderBy')) {
|
|
$field = $filters->get('orderByField') ? $filters->get('orderByField') : 'name';
|
|
$orderBy = $filters->get('orderBy') ? $filters->get('orderBy') : 'asc';
|
|
$query->whereOrder($field, $orderBy);
|
|
}
|
|
}
|
|
|
|
public function getFormattedCreatedAtAttribute($value)
|
|
{
|
|
$dateFormat = CompanySetting::getSetting('carbon_date_format', $this->company_id);
|
|
return Carbon::parse($this->created_at)->format($dateFormat);
|
|
}
|
|
|
|
public function taxes()
|
|
{
|
|
return $this->hasMany(Tax::class);
|
|
}
|
|
|
|
public function scopeWhereCompany($query, $company_id)
|
|
{
|
|
$query->where('items.company_id', $company_id);
|
|
}
|
|
|
|
public function invoiceItems()
|
|
{
|
|
return $this->hasMany(InvoiceItem::class);
|
|
}
|
|
|
|
public function estimateItems()
|
|
{
|
|
return $this->hasMany(EstimateItem::class);
|
|
}
|
|
|
|
public static function deleteItem($id)
|
|
{
|
|
$item = Item::find($id);
|
|
|
|
if ($item->taxes()->exists() && $item->taxes()->count() > 0) {
|
|
return false;
|
|
}
|
|
|
|
if ($item->invoiceItems()->exists() && $item->invoiceItems()->count() > 0) {
|
|
return false;
|
|
}
|
|
|
|
if ($item->estimateItems()->exists() && $item->estimateItems()->count() > 0) {
|
|
return false;
|
|
}
|
|
|
|
$item->delete();
|
|
|
|
return true;
|
|
}
|
|
}
|