validate([ 'message' => ['required', 'string', 'max:2000'], 'history' => ['nullable', 'array', 'max:20'], 'history.*.role' => ['nullable', 'string'], 'history.*.text' => ['nullable', 'string'], ]); if (! $afia->enabled()) { return response()->json(['message' => 'Afia is not available right now.'], 503); } try { $reply = $afia->chat(trim($validated['message']), $validated['history'] ?? [], $this->context($request)); } catch (\Throwable $e) { report($e); return response()->json(['message' => 'Afia could not respond right now. Please try again.'], 502); } return response()->json(['reply' => $reply]); } /** @return array */ private function context(Request $request): array { $owner = $this->ownerRef($request); $currency = strtoupper((string) config('pos.default_currency', 'GHS')); $todaySales = PosSale::owned($owner) ->where('status', PosSale::STATUS_PAID) ->where('paid_at', '>=', now()->startOfDay()); $todayTotalMinor = (int) (clone $todaySales)->sum('total_minor'); return [ 'signed_in' => 'yes', 'today_takings' => $currency.' '.number_format($todayTotalMinor / 100, 2), 'today_sales_count' => (clone $todaySales)->count(), 'active_products' => PosProduct::owned($owner)->active()->count(), 'pending_sales' => PosSale::owned($owner)->where('status', PosSale::STATUS_PENDING)->count(), ]; } }