$eventDate->syncValidityTime()); static::created(fn (self $eventDate) => $eventDate->syncTenantDateText()); static::updated(function (self $eventDate): void { if ($eventDate->wasChanged(['date', 'time_start', 'time_end'])) { $eventDate->syncValidityTime(); } $eventDate->syncTenantDateText(); }); static::deleted(function (self $eventDate): void { $eventDate->syncTenantDateText(); ValidityTime::query() ->whereKey($eventDate->validity_time_id) ->whereDoesntHave('ticketValidityGroups') ->delete(); }); } protected function casts(): array { return [ 'date' => 'date:Y-m-d', 'validity_time_id' => 'integer', ]; } /** @return BelongsTo */ public function tenant(): BelongsTo { return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo'); } /** @return BelongsTo */ public function validityTime(): BelongsTo { return $this->belongsTo(ValidityTime::class); } /** @return HasMany */ public function variants(): HasMany { return $this->hasMany(Variant::class); } /** @return BelongsToMany */ public function selectedByVariants(): BelongsToMany { return $this->belongsToMany( Variant::class, 'variant_event_dates', 'event_date_id', 'variant_id', ); } public function startsAt(): CarbonInterface { return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_start); } public function endsAt(): CarbonInterface { return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_end); } private function syncTenantDateText(): void { $tenant = $this->tenant()->first(); if (! $tenant) { return; } $tenant->update([ 'event_date_text' => app(EventDateTextFormatter::class)->format( $tenant->eventDates()->pluck('date') ), ]); } private function syncValidityTime(): void { $startsAt = $this->startsAt(); $expiresAt = $this->endsAt(); if ($expiresAt->lessThanOrEqualTo($startsAt)) { $expiresAt = $expiresAt->addDay(); } $attributes = [ 'type' => ValidityTimeType::FixedWindow, 'start_time' => null, 'end_time' => null, 'fixed_starts_at' => $startsAt, 'fixed_expires_at' => $expiresAt, ]; if ($this->validity_time_id === null) { $validityTime = ValidityTime::query()->create($attributes); $this->validity_time_id = $validityTime->getKey(); $this->setRelation('validityTime', $validityTime); return; } $this->validityTime()->update($attributes); $this->unsetRelation('validityTime'); } }