with('vatTotals')->where('day', $day->format('Y-m-d'))->first(); return $model === null ? CashDay::open($day) : $this->toEntity($model); } public function lockForDay(DateTimeImmutable $day): CashDay { CashDayModel::query()->insertOrIgnore(['day' => $day->format('Y-m-d'), 'created_at' => now(), 'updated_at' => now()]); $model = CashDayModel::query()->with('vatTotals')->where('day', $day->format('Y-m-d'))->lockForUpdate()->firstOrFail(); return $this->toEntity($model); } public function save(CashDay $cashDay): CashDay { $model = CashDayModel::query()->firstOrNew(['day' => $cashDay->day()->format('Y-m-d')]); $balance = $cashDay->balance() ?? CashDayBalance::empty(); $model->fill([ 'closed_by' => $cashDay->closedBy(), 'closed_at' => $cashDay->closedAt()?->format('Y-m-d H:i:s'), 'sale_count' => $balance->saleCount, 'cash_cents' => $balance->cashCents, 'card_cents' => $balance->cardCents, 'total_cents' => $balance->totalCents(), 'reopened_by' => $cashDay->reopenedBy(), 'reopened_at' => $cashDay->reopenedAt()?->format('Y-m-d H:i:s'), ])->save(); CashDayVatTotalModel::query()->where('cash_day_id', $model->id)->delete(); foreach ($balance->vatTotals as $total) { CashDayVatTotalModel::query()->create([ 'cash_day_id' => $model->id, 'vat_basis_points' => $total->vatBasisPoints, 'gross_cents' => $total->grossCents, 'net_cents' => $total->netCents, 'vat_cents' => $total->vatCents, ]); } return $this->toEntity($model->load('vatTotals')); } private function toEntity(CashDayModel $model): CashDay { $balance = $model->closed_at === null ? null : new CashDayBalance( $model->sale_count, $model->cash_cents, $model->card_cents, $model->vatTotals->map(fn (CashDayVatTotalModel $total): VatTotal => new VatTotal( $total->vat_basis_points, $total->gross_cents, $total->net_cents, $total->vat_cents, ))->values()->all(), ); return CashDay::reconstitute( $model->id, new DateTimeImmutable($model->day), $balance, $model->closed_by, $model->closed_at === null ? null : DateTimeImmutable::createFromInterface($model->closed_at), $model->reopened_by, $model->reopened_at === null ? null : DateTimeImmutable::createFromInterface($model->reopened_at), ); } }