where('code', $code)->first(); } /** * @param list $lines nur Positionen, die in die Bestellung eingehen */ public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult { $now ??= now(); $timing = $code->stateAt($now); if ($timing !== 'aktiv') { return new DiscountResult($code, $timing, match ($timing) { 'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.', 'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.', default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').', }); } if ($code->restricted()) { if ($user === null) { return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.'); } if ($this->activeRelease($code, $user, $now, $lock) === null) { return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.'); } } $matching = []; foreach ($lines as $line) { if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) { $matching[$line->offer->id] = (int) $line->currentPriceCents; } } if ($matching === []) { return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection() ? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.' : 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.'); } $perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching); $payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer); if ($payable < self::MIN_PAYABLE_CENTS) { return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.'); } return new DiscountResult($code, DiscountResult::OK, null, $perOffer); } /** * Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der * Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht * rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig. */ public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool { if (! $code->forSelection()) { return true; } $targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all()); if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) { return true; } $version->loadMissing('lines.bundleVersion'); foreach ($version->lines as $line) { if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) { return true; } if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) { return true; } } return false; } public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease { $now ??= now(); $query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at'); if ($lock) { $query->lockForUpdate(); } return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now)); } /** * Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten. * * @param array $data * @param list $targets */ public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode { $code = DiscountCode::normalise((string) ($data['code'] ?? '')); $label = trim((string) ($data['label'] ?? '')); if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) { throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.'); } if ($label === '') { throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.'); } if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) { throw new DomainRuleException('Diesen Code gibt es schon.'); } $kind = (string) ($data['kind'] ?? ''); $percent = null; $amount = null; if ($kind === DiscountCode::PERCENT) { $percent = (int) ($data['percent'] ?? 0); if ($percent < 1 || $percent > 100) { throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.'); } } elseif ($kind === DiscountCode::AMOUNT) { $amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null)); if ($amount === null || $amount <= 0) { throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.'); } } else { throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.'); } $scope = (string) ($data['scope'] ?? ''); $eligibility = (string) ($data['eligibility'] ?? ''); if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) { throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.'); } if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) { throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.'); } $targets = $this->cleanTargets($targets); if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) { throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.'); } $from = $this->date($data['valid_from'] ?? null); $until = $this->date($data['valid_until'] ?? null); if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) { throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.'); } return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode { $model = $existing ?? new DiscountCode; $model->fill([ 'code' => $code, 'label' => $label, 'kind' => $kind, 'percent' => $percent, 'amount_cents' => $amount, 'scope' => $scope, 'eligibility' => $eligibility, 'valid_from' => $from, 'valid_until' => $until, 'active' => (bool) ($data['active'] ?? true), 'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null, ]); $model->save(); $model->targets()->delete(); if ($scope === DiscountCode::SCOPE_SELECTED) { foreach ($targets as $target) { $model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]); } } return $model->load('targets'); }); } public function setActive(DiscountCode $code, bool $active): DiscountCode { $code->active = $active; $code->save(); return $code; } /** * Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht. */ public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease { if (! $code->restricted()) { throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.'); } if ($member->party_id === null) { throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.'); } return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease { DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail(); if ($this->activeRelease($code, $member) !== null) { throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.'); } if ($until !== null && $until->lessThanOrEqualTo(now())) { throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.'); } return DiscountRelease::query()->create([ 'discount_code_id' => $code->id, 'user_id' => $member->id, 'granted_by' => $actor?->id, 'granted_at' => now(), 'valid_until' => $until, 'reason' => filled($reason) ? trim((string) $reason) : null, ]); }); } /** * Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert. */ public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease { return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease { $release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id); if ($release->revoked_at !== null) { throw new DomainRuleException('Diese Freigabe ist bereits entzogen.'); } $release->revoked_at = now(); $release->revoked_by = $actor?->id; $release->reason = filled($reason) ? trim((string) $reason) : $release->reason; $release->save(); return $release; }); } /** * @param list $targets * @return list */ private function cleanTargets(array $targets): array { $clean = []; foreach ($targets as $target) { $type = (string) ($target['type'] ?? ''); $id = (int) ($target['id'] ?? 0); $exists = match ($type) { DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(), DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(), DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(), default => false, }; if (! $exists) { throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).'); } $clean[$type.':'.$id] = ['type' => $type, 'id' => $id]; } return array_values($clean); } private function date(mixed $value): ?CarbonInterface { return filled($value) ? Carbon::parse((string) $value, config('app.timezone')) : null; } }