Reading https://nova.laravel.com/docs/metrics/defining-metrics.html#value-metrics docs in Laravel 10 / nova 4.27 app I added metrics with command :
php artisan nova:value OrdersCompleted
i need to calc only completed orders by completed_by_manager_at field.
Order model has scope :
public function scopeOnlyCompleted($query)
{
return $query->where($this->table . '.status', OrderStatusEnum::COMPLETED);
}
and in app/Nova/Metrics/OrdersCompleted.php I modified :
class OrdersCompleted extends Value
{
/**
* Calculate the value of the metric.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @return mixed
*/
public function calculate(NovaRequest $request)
{
return $this->count($request, Order::onlyCompleted());
}
Checking sql I see :
SELECT count(`orders`.`id`) AS aggregate
FROM `orders`
WHERE `orders`.`status` = 'O' AND `orders`.`created_at` between '2024-01-01 00:00:00' AND '2024-10-28 05:38:01'
In the docs I did not find how can I instead created_at field to use completed_by_manager_at field ?
MODIFIES # 1:
In order modal I added scope :
public function scopeGetCompletedByManagerAtBetweenDates($query, datetime $date1 = null, datetime $date2 = null): Builder
{
if( !empty($date1) and !empty($date2)) { // THESE conditions are false
\Log::info('$date1::');
\Log::info($date1);
$query->whereBetween($this->table . '.completed_by_manager_at', [$date1, $date2]);
}
return $query;
}
and use this scope in my OrdersCompleted metrix class :
public function calculate(NovaRequest $request)
{
\Log::info( '-1 OrdersCompleted $request->all()::' . print_r( $request->all(), true ) );
return $this->count($request, Order::onlyCompleted()->getCompletedByManagerAtBetweenDates());
}
In logs I see thaht $request->all() have values :
[timezone] => UTC
[range] => 30
How can I calc days of range for getCompletedByManagerAtBetweenDates method ?
Looking at the docs for the count()
method:
/**
* Return a value result showing the growth of an count aggregate over time.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Builder|class-string<\Illuminate\Database\Eloquent\Model> $model
* @param \Illuminate\Database\Query\Expression|string|null $column
* @param string|null $dateColumn
* @return \Laravel\Nova\Metrics\ValueResult
*/
public function count($request, $model, $column = null, $dateColumn = null) {
return $this->aggregate($request, $model, 'count', $column, $dateColumn);
}
The 4th parameter can specify which column to use for the date aggregation.
As such, try:
public function calculate(NovaRequest $request) {
return $this->count($request, Order::onlyCompleted(), null, 'completed_by_manager_at');
}