find($id); return $model === null ? null : $this->toEntity($model); } public function save(Expense $expense): Expense { $model = $expense->id() === null ? new ExpenseModel : ExpenseModel::query()->findOrFail($expense->id()); $details = $expense->details(); $model->fill([ 'customer_job_id' => $expense->jobId(), 'user_id' => $expense->userId(), 'recorded_by' => $expense->recordedBy(), 'category' => $details->category, 'paid_by' => $details->paidBy, 'spent_on' => $details->spentOn->format('Y-m-d'), 'description' => $details->description, 'cost_cents' => $details->cost->cents, 'kilometers' => $details->kilometers === null ? null : $details->kilometers->tenths / 10, 'destination' => $details->destination, 'purpose' => $details->purpose, 'is_billable' => $details->isBillable(), 'markup_basis_points' => $details->billing?->markup?->basisPoints, 'billed_amount_cents' => $details->billing?->amount->cents, ])->save(); return $this->toEntity($model->refresh()); } public function delete(Expense $expense): void { ExpenseModel::query()->whereKey($expense->id())->delete(); } public function markBillableAsBilled(int $jobId, int $billingExportId): array { $ids = ExpenseModel::query() ->where('customer_job_id', $jobId) ->where('is_billable', true) ->whereNotNull('billed_amount_cents') ->whereNull('billing_export_id') ->orderBy('spent_on') ->orderBy('id') ->pluck('id') ->map(fn ($id): int => (int) $id) ->all(); ExpenseModel::query()->whereKey($ids)->update(['billing_export_id' => $billingExportId]); return $ids; } private function toEntity(ExpenseModel $model): Expense { $billing = $model->is_billable && $model->billed_amount_cents !== null ? ExpenseBilling::for( Money::fromCents($model->cost_cents), $model->markup_basis_points === null ? null : new MarkupPercentage($model->markup_basis_points), Money::fromCents($model->billed_amount_cents), ) : null; return Expense::reconstitute( $model->id, $model->customer_job_id, $model->user_id, $model->recorded_by, ExpenseDetails::reconstitute( $model->category, $model->paid_by, DateTimeImmutable::createFromInterface($model->spent_on), $model->description, Money::fromCents($model->cost_cents), $model->kilometers === null ? null : new Kilometers((int) round((float) $model->kilometers * 10)), $model->destination, $model->purpose, $billing, ), $model->billing_export_id, ); } }