with(['lines', 'credit']) ->where('sold_on', $day) ->when($sellerId !== null, fn ($query) => $query->where('user_id', $sellerId)) ->orderByDesc('sold_at') ->orderByDesc('id') ->get(); return $this->summaries($models); } public function findSale(int $id): ?QuickSaleSummary { $model = QuickSaleModel::query()->with(['lines', 'credit'])->find($id); return $model === null ? null : $this->summaries(collect([$model]))[0]; } public function cashDay(string $day): CashDaySummary { $date = new DateTimeImmutable($day); $cashDay = $this->cashDays->forDay($date); $names = $this->users->namesByIds(array_values(array_filter([$cashDay->closedBy(), $cashDay->reopenedBy()]))); return new CashDaySummary( day: $day, isClosed: $cashDay->isClosed(), balance: $cashDay->balance() ?? CashDayBalance::of($this->sales->forDay($date)), closedByName: $cashDay->closedBy() === null ? null : ($names[$cashDay->closedBy()] ?? ''), closedAt: $this->localTime($cashDay->closedAt()), reopenedByName: $cashDay->reopenedBy() === null ? null : ($names[$cashDay->reopenedBy()] ?? ''), reopenedAt: $this->localTime($cashDay->reopenedAt()), ); } public function unclosedDaysBefore(string $day): array { $closed = CashDayModel::query()->whereNotNull('closed_at')->select('day'); return QuickSaleModel::query() ->where('sold_on', '<', $day) ->whereNotIn('sold_on', $closed) ->distinct() ->orderBy('sold_on') ->pluck('sold_on') ->map(fn ($value): string => substr((string) $value, 0, 10)) ->values() ->all(); } /** * @param Collection $models * @return list */ private function summaries(Collection $models): array { $sellerNames = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); $customerNames = $this->customers->namesByIds($models->pluck('customer_id')->filter()->unique()->values()->all()); return $models->map(fn (QuickSaleModel $model): QuickSaleSummary => new QuickSaleSummary( id: $model->id, soldAt: (string) $this->localTime($model->sold_at), sellerId: $model->user_id, sellerName: $sellerNames[$model->user_id] ?? '', customerName: $model->customer_id === null ? null : ($customerNames[$model->customer_id] ?? ''), paymentMethod: $model->payment_method, totalCents: $model->total_cents, lines: $model->lines->map(fn (QuickSaleLineModel $line): QuickSaleLineSummary => new QuickSaleLineSummary( $line->product_name, $line->quantity, $line->unit_price_cents, $line->quantity * $line->unit_price_cents, $line->vat_basis_points, ))->values()->all(), creditsSaleId: $model->credits_quick_sale_id, creditedBySaleId: $model->credit?->id, ))->values()->all(); } private function localTime(?DateTimeInterface $moment): ?string { return $moment === null ? null : Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'); } }