Öffne Katalog, Bibliothek und Testkauf für den MVP.
Deploy Test / test (push) Successful in 12s
Deploy Test / deploy (push) Successful in 21s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-11-15 09:04:08 +01:00
1 parent 463851d402
commit fd6860efda
51 files changed
+2331 -31

No files matched your search

+2
View File
@@ -64,6 +64,8 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
PAYMENT_DRIVER=test
# Leer lassen. Lokal gilt dann storage/. Im Container setzt Compose den Host-Mount (/srv/luf/<env>/media/...).
MEDIA_PUBLIC_PATH=
MEDIA_DERIVED_PATH=
+11 -3
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Catalog;
use App\Jobs\StoreContentFile;
use App\Models\User;
use Illuminate\Support\Facades\DB;
@@ -29,10 +30,10 @@ public function publishElementVersion(
}
$number = ((int) $element->versions()->max('number')) + 1;
return $element->versions()->create([
$incoming = $metadata['incoming'] ?? null;
$version = $element->versions()->create([
'number' => $number,
'status' => ContentVersionStatus::Bereit,
'status' => is_string($incoming) && $incoming !== '' ? ContentVersionStatus::Entwurf : ContentVersionStatus::Bereit,
'content_hash' => hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
@@ -41,6 +42,13 @@ public function publishElementVersion(
'metadata' => $metadata === [] ? null : $metadata,
'change_note' => $changeNote,
]);
if (is_string($incoming) && $incoming !== '') {
StoreContentFile::dispatch($version->id, $incoming);
$version->refresh();
}
return $version;
}
/**
+187
View File
@@ -0,0 +1,187 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Entitlement\Acquisition;
use App\Domain\Entitlement\AcquisitionType;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Identity\AccountStatus;
use App\Mail\OrderConfirmed;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class Checkout
{
public function __construct(private readonly GrantIssuer $grants) {}
public function place(User $user, Offer $offer): Order
{
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
}
$version = $offer->versions()->where('status', OfferStatus::Aktiv)->orderByDesc('number')->first();
if ($version === null || $version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
throw new DomainRuleException('Dieses Angebot kann nicht als persönlicher Kauf bestellt werden.');
}
if ($version->price_cents === null) {
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
}
return DB::transaction(function () use ($user, $version): Order {
$order = Order::query()->create([
'user_id' => $user->id,
'party_id' => $user->party_id,
'status' => 'offen',
'holder_kind' => 'person',
]);
$line = $order->lines()->create([
'offer_version_id' => $version->id,
'price_cents' => $version->price_cents,
'term_rule' => $version->term_rule,
'update_promise' => $version->update_promise,
'holder_kind' => $version->holder_kind,
]);
$version->load('resolvedScopes.rights');
foreach ($version->resolvedScopes as $scope) {
$line->scopeItems()->create([
'license_article_id' => $scope->license_article_id,
'rights_profile_version_id' => $scope->rights_profile_version_id,
'rights_snapshot' => [
'purpose' => $scope->rights->purpose,
'capabilities' => $scope->rights->capabilities,
'options' => $scope->rights->options ?? [],
],
]);
}
return $order->load('lines.scopeItems');
});
}
public function confirmTestPayment(Order $order, string $reference): Order
{
$this->assertTestDriver();
$reference = trim($reference);
if ($reference === '') {
throw new DomainRuleException('Die Zahlungsreferenz fehlt.');
}
$paidNow = false;
$order = DB::transaction(function () use ($order, $reference, &$paidNow): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
if ($order->status === 'bezahlt') {
return $order->load('lines', 'payments');
}
if ($order->status !== 'offen') {
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
}
$order->payments()->create([
'provider' => 'test',
'status' => 'bestaetigt',
'provider_reference' => $reference,
]);
$order->status = 'bezahlt';
$order->save();
$paidNow = true;
$line = $order->lines()->firstOrFail();
$this->grants->issue(
$order->user,
$line->offerVersion,
AcquisitionType::Bestellposition,
'order_line',
$line->id,
);
return $order->load('lines', 'payments');
});
if ($paidNow) {
Mail::to($order->user)->send(new OrderConfirmed($order));
}
return $order;
}
public function failTestPayment(Order $order, string $reference): Order
{
$this->assertTestDriver();
return DB::transaction(function () use ($order, $reference): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
if ($order->status !== 'offen') {
return $order;
}
$order->payments()->create([
'provider' => 'test',
'status' => 'fehlgeschlagen',
'provider_reference' => $reference,
]);
$order->status = 'fehlgeschlagen';
$order->save();
return $order;
});
}
public function refund(Order $order, string $reason): Order
{
$reason = trim($reason);
if ($reason === '') {
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
}
return DB::transaction(function () use ($order, $reason): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
if ($order->status !== 'bezahlt') {
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
}
$line = $order->lines()->firstOrFail();
$acquisition = Acquisition::query()->where([
'type' => AcquisitionType::Bestellposition,
'reference_type' => 'order_line',
'reference_id' => $line->id,
])->first();
if ($acquisition !== null) {
foreach ($acquisition->grants as $grant) {
if ($grant->status === GrantStatus::Aktiv) {
$grant->status = GrantStatus::Widerrufen;
$grant->status_reason = $reason;
$grant->save();
}
}
}
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
$order->status = 'erstattet';
$order->save();
return $order->refresh();
});
}
private function assertTestDriver(): void
{
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
throw new DomainRuleException('Der Testzahlungsweg ist nicht aktiv.');
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Identity\Party;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Order extends Model
{
protected $fillable = [
'user_id',
'party_id',
'status',
'holder_kind',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function party(): BelongsTo
{
return $this->belongsTo(Party::class);
}
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class);
}
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\OfferVersion;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class OrderLine extends Model
{
protected $fillable = [
'order_id',
'offer_version_id',
'price_cents',
'term_rule',
'update_promise',
'holder_kind',
];
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
public function offerVersion(): BelongsTo
{
return $this->belongsTo(OfferVersion::class);
}
public function scopeItems(): HasMany
{
return $this->hasMany(OrderScopeItem::class);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\LicenseArticle;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OrderScopeItem extends Model
{
protected $fillable = [
'order_line_id',
'license_article_id',
'rights_profile_version_id',
'rights_snapshot',
];
protected function casts(): array
{
return [
'rights_snapshot' => 'array',
];
}
public function line(): BelongsTo
{
return $this->belongsTo(OrderLine::class, 'order_line_id');
}
public function article(): BelongsTo
{
return $this->belongsTo(LicenseArticle::class, 'license_article_id');
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Domain\Commerce;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Payment extends Model
{
protected $fillable = [
'order_id',
'provider',
'status',
'provider_reference',
];
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace App\Domain\Entitlement;
class AccessResult
{
public function __construct(
public readonly bool $allowed,
public readonly ?Grant $grant = null,
public readonly string $reason = '',
) {}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Domain\Entitlement;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\ReleaseStatus;
use App\Domain\Identity\AccountStatus;
use App\Models\User;
class DecideAccess
{
public function __invoke(
User $user,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
): AccessResult {
if ($user->status !== AccountStatus::Aktiv) {
return new AccessResult(false, null, 'Das Konto ist nicht aktiv.');
}
if ($release->license_article_id !== $article->id) {
return new AccessResult(false, null, 'Der Stand gehört zu einem anderen Artikel.');
}
if (! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) {
return new AccessResult(false, null, 'Dieser Stand ist nicht freigegeben.');
}
$contained = $release->contents()->where('content_element_version_id', $version->id)->exists();
if (! $contained) {
return new AccessResult(false, null, 'Die Fassung gehört nicht zum fixierten Inhalt dieses Stands.');
}
if ($version->status === ContentVersionStatus::Gesperrt) {
return new AccessResult(false, null, 'Die Fassung ist gesperrt.');
}
$version->loadMissing('element');
$outputClass = $version->element->output_class;
$now = now();
$candidates = Grant::query()
->where('license_article_id', $article->id)
->where('status', GrantStatus::Aktiv)
->whereHas('acquisition', fn ($query) => $query->where('party_id', $user->party_id))
->get()
->filter(function (Grant $grant) use ($now): bool {
if ($grant->valid_from !== null && $grant->valid_from->greaterThan($now)) {
return false;
}
return $grant->valid_until === null || $grant->valid_until->greaterThan($now);
})
->filter(function (Grant $grant) use ($outputClass, $action): bool {
$capabilities = $grant->rights_snapshot['capabilities'] ?? [];
$actions = $capabilities[$outputClass] ?? [];
return in_array($action, $actions, true);
})
->sort(function (Grant $left, Grant $right): int {
$leftUntil = $left->valid_until?->getTimestamp() ?? PHP_INT_MAX;
$rightUntil = $right->valid_until?->getTimestamp() ?? PHP_INT_MAX;
return $leftUntil === $rightUntil ? $right->id <=> $left->id : $leftUntil <=> $rightUntil;
})
->values();
$grant = $candidates->last();
if ($grant === null) {
return new AccessResult(false, null, 'Keine passende Berechtigung.');
}
return new AccessResult(true, $grant);
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Domain\Entitlement;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Catalog\OfferVersion;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class GrantIssuer
{
public function claim(User $user, Offer $offer): Acquisition
{
$version = $this->activeVersion($offer);
if (! in_array($version->grant_kind, ['auf_abruf', 'bei_registrierung'], true)) {
throw new DomainRuleException('Dieses Angebot wird nicht frei vergeben.');
}
if ($version->holder_kind !== 'person') {
throw new DomainRuleException('Dieses Angebot richtet sich nicht an Personen.');
}
return $this->issue($user, $version, AcquisitionType::FreierAbruf, 'offer', $offer->id);
}
public function grantRegistrationOffers(User $user): void
{
OfferVersion::query()
->where('status', OfferStatus::Aktiv)
->where('grant_kind', 'bei_registrierung')
->where('holder_kind', 'person')
->with('offer')
->get()
->each(function (OfferVersion $version) use ($user): void {
$this->issue($user, $version, AcquisitionType::FreierAbruf, 'offer', $version->offer_id);
});
}
public function grantManually(User $user, Offer $offer, User $actor, string $reason): Acquisition
{
$reason = trim($reason);
if ($reason === '') {
throw new DomainRuleException('Eine manuelle Vergabe braucht eine Begründung.');
}
$version = $this->activeVersion($offer);
if ($version->holder_kind !== 'person') {
throw new DomainRuleException('Dieses Angebot richtet sich nicht an Personen.');
}
return DB::transaction(function () use ($user, $offer, $actor, $reason, $version): Acquisition {
$operation = ManualGrant::query()->create([
'actor_id' => $actor->id,
'party_id' => $user->party_id,
'offer_id' => $offer->id,
'reason' => $reason,
]);
return $this->issue($user, $version, AcquisitionType::ManuelleVergabe, 'manual_grant', $operation->id);
});
}
public function issue(
User $user,
OfferVersion $version,
AcquisitionType $type,
string $referenceType,
int $referenceId,
): Acquisition {
return DB::transaction(function () use ($user, $version, $type, $referenceType, $referenceId): Acquisition {
$existing = Acquisition::query()->where([
'party_id' => $user->party_id,
'type' => $type,
'reference_type' => $referenceType,
'reference_id' => $referenceId,
])->first();
if ($existing !== null) {
return $existing->load('grants');
}
$acquisition = Acquisition::query()->create([
'party_id' => $user->party_id,
'type' => $type,
'reference_type' => $referenceType,
'reference_id' => $referenceId,
'conditions' => [
'term_rule' => $version->term_rule,
'update_promise' => $version->update_promise,
'holder_kind' => $version->holder_kind,
'offer_version_id' => $version->id,
],
]);
$version->load('resolvedScopes.rights', 'resolvedScopes.article');
foreach ($version->resolvedScopes as $scope) {
$rights = $scope->rights;
$acquisition->grants()->create([
'license_article_id' => $scope->license_article_id,
'rights_profile_version_id' => $rights->id,
'rights_snapshot' => [
'purpose' => $rights->purpose,
'capabilities' => $rights->capabilities,
'options' => $rights->options ?? [],
],
'release_at_grant_id' => $scope->article->current_release_id,
'status' => GrantStatus::Aktiv,
'valid_from' => now(),
]);
}
return $acquisition->load('grants');
});
}
private function activeVersion(Offer $offer): OfferVersion
{
$version = $offer->versions()->where('status', OfferStatus::Aktiv)->orderByDesc('number')->first();
if ($version === null) {
throw new DomainRuleException('Das Angebot hat keine aktive Fassung.');
}
return $version;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Domain\Entitlement;
use App\Domain\Catalog\Offer;
use App\Domain\Identity\Party;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ManualGrant extends Model
{
protected $fillable = [
'actor_id',
'party_id',
'offer_id',
'reason',
];
public function actor(): BelongsTo
{
return $this->belongsTo(User::class, 'actor_id');
}
public function party(): BelongsTo
{
return $this->belongsTo(Party::class);
}
public function offer(): BelongsTo
{
return $this->belongsTo(Offer::class);
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Resources\Bundles;
use App\Domain\Catalog\Bundle;
use App\Filament\Resources\Bundles\Pages\ListBundles;
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class BundleResource extends Resource
{
protected static ?string $model = Bundle::class;
protected static string|\UnitEnum|null $navigationGroup = 'Katalog';
protected static ?string $navigationLabel = 'Pakete';
protected static ?string $modelLabel = 'Paket';
protected static ?string $pluralModelLabel = 'Pakete';
protected static ?string $recordTitleAttribute = 'name';
public static function canViewAny(): bool
{
return LicenseArticleResource::keeper();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('versions_count')->counts('versions')->label('Fassungen'),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListBundles::route('/'),
];
}
}
@@ -0,0 +1,58 @@
<?php
namespace App\Filament\Resources\Bundles\Pages;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\BundleService;
use App\Domain\Catalog\LicenseArticle;
use App\Filament\Resources\Bundles\BundleResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
class ListBundles extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = BundleResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')->label('Paket anlegen')->schema([
TextInput::make('name')->label('Name')->required(),
])->action(function (array $data): void {
$this->report(function () use ($data): void {
app(BundleService::class)->create($data['name']);
}, 'Das Paket ist angelegt.');
}),
Action::make('publish')->label('Fassung veröffentlichen')->schema([
Select::make('bundle_id')->label('Paket')->options(fn (): array => CatalogOptions::bundles())->required(),
CheckboxList::make('articles')->label('Lizenzartikel')->options(fn (): array => CatalogOptions::articles()),
CheckboxList::make('bundles')->label('Enthaltene Pakete')->options(fn (): array => CatalogOptions::bundles()),
])->action(function (array $data): void {
$this->report(function () use ($data): void {
$items = [];
foreach ($data['articles'] ?? [] as $id) {
$items[] = LicenseArticle::query()->findOrFail($id);
}
foreach ($data['bundles'] ?? [] as $id) {
if ((int) $id === (int) $data['bundle_id']) {
continue;
}
$items[] = Bundle::query()->findOrFail($id);
}
app(BundleService::class)->publish(Bundle::query()->findOrFail($data['bundle_id']), $items);
}, 'Die Paketfassung ist veröffentlicht.');
}),
];
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Resources\Compositions;
use App\Domain\Catalog\Composition;
use App\Filament\Resources\Compositions\Pages\ListCompositions;
use App\Filament\Resources\ContentElements\ContentElementResource;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class CompositionResource extends Resource
{
protected static ?string $model = Composition::class;
protected static string|\UnitEnum|null $navigationGroup = 'Redaktion';
protected static ?string $navigationLabel = 'Kompositionen';
protected static ?string $modelLabel = 'Komposition';
protected static ?string $pluralModelLabel = 'Kompositionen';
protected static ?string $recordTitleAttribute = 'designation';
public static function canViewAny(): bool
{
return ContentElementResource::editor();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('designation')->label('Bezeichnung')->searchable(),
TextColumn::make('versions_count')->counts('versions')->label('Fassungen'),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListCompositions::route('/'),
];
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Filament\Resources\Compositions\Pages;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Filament\Resources\Compositions\CompositionResource;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
class ListCompositions extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = CompositionResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Komposition anlegen')
->visible(fn (): bool => ContentElementResource::editor())
->schema([
TextInput::make('designation')->label('Bezeichnung')->required(),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
app(ContentService::class)->createComposition($data['designation']);
}, 'Die Komposition ist angelegt.');
}),
Action::make('publish')
->label('Fassung veröffentlichen')
->visible(fn (): bool => ContentElementResource::editor())
->schema([
Select::make('composition_id')->label('Komposition')->options(fn (): array => CatalogOptions::compositions())->required(),
Repeater::make('members')->label('Mitglieder')->schema([
TextInput::make('role')->label('Rolle')->required(),
Select::make('target')->label('Fassung')->options(fn (): array => CatalogOptions::readyTargets())->required(),
])->minItems(1),
TextInput::make('note')->label('Bestätigungsnotiz'),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
$members = [];
foreach ($data['members'] as $member) {
[$type, $id] = explode(':', $member['target'], 2);
$target = $type === 'composition'
? CompositionVersion::query()->findOrFail($id)
: ContentElementVersion::query()->findOrFail($id);
$members[] = ['role' => $member['role'], 'target' => $target];
}
app(ContentService::class)->publishComposition(
Composition::query()->findOrFail($data['composition_id']),
$members,
auth()->user(),
$data['note'] ?? null,
);
}, 'Die Kompositionsfassung ist bestätigt und bereit.');
}),
];
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Filament\Resources\ContentElements;
use App\Domain\Catalog\ContentElement;
use App\Domain\Identity\StaffRole;
use App\Filament\Resources\ContentElements\Pages\ListContentElements;
use App\Models\User;
use Filament\Facades\Filament;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class ContentElementResource extends Resource
{
protected static ?string $model = ContentElement::class;
protected static string|\UnitEnum|null $navigationGroup = 'Redaktion';
protected static ?string $navigationLabel = 'Inhaltselemente';
protected static ?string $modelLabel = 'Inhaltselement';
protected static ?string $pluralModelLabel = 'Inhaltselemente';
protected static ?string $recordTitleAttribute = 'working_title';
public static function canViewAny(): bool
{
return self::editor();
}
public static function editor(): bool
{
$user = Filament::auth()->user();
return $user instanceof User && $user->hasStaffRole(StaffRole::Redakteur);
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('working_title')->label('Arbeitstitel')->searchable(),
TextColumn::make('kind')->label('Art'),
TextColumn::make('output_class')->label('Ausgabeklasse'),
TextColumn::make('versions_count')->counts('versions')->label('Fassungen'),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListContentElements::route('/'),
];
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Filament\Resources\ContentElements\Pages;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentService;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
class ListContentElements extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = ContentElementResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Element anlegen')
->visible(fn (): bool => ContentElementResource::editor())
->schema([
TextInput::make('working_title')->label('Arbeitstitel')->required(),
Select::make('kind')->label('Art')->options([
'film' => 'Film',
'audio' => 'Audio',
'bild' => 'Bild',
'pdf' => 'PDF',
'text' => 'Text',
'aufgabe' => 'Aufgabe',
])->required(),
Select::make('output_class')->label('Ausgabeklasse')->options([
'film' => 'Film',
'audio' => 'Audio',
'bild' => 'Bild',
'pdf' => 'PDF',
'text' => 'Text',
])->required(),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
app(ContentService::class)->createElement($data['kind'], $data['output_class'], $data['working_title']);
}, 'Das Inhaltselement ist angelegt.');
}),
Action::make('version')
->label('Fassung veröffentlichen')
->visible(fn (): bool => ContentElementResource::editor())
->schema([
Select::make('element_id')->label('Element')->options(fn (): array => CatalogOptions::elements())->required(),
Textarea::make('body')->label('Text'),
FileUpload::make('incoming')->label('Datei')->disk('cms_incoming')->directory('inhalte'),
TextInput::make('change_note')->label('Änderungsnotiz'),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
$metadata = filled($data['incoming'] ?? null) ? ['incoming' => $data['incoming']] : [];
app(ContentService::class)->publishElementVersion(
ContentElement::query()->findOrFail($data['element_id']),
$data['body'] ?? null,
$metadata,
$data['change_note'] ?? null,
);
}, 'Die Fassung ist gespeichert.');
}),
];
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Filament\Resources\LicenseArticles;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Identity\StaffRole;
use App\Filament\Resources\LicenseArticles\Pages\ListLicenseArticles;
use App\Models\User;
use Filament\Facades\Filament;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class LicenseArticleResource extends Resource
{
protected static ?string $model = LicenseArticle::class;
protected static string|\UnitEnum|null $navigationGroup = 'Katalog';
protected static ?string $navigationLabel = 'Lizenzartikel';
protected static ?string $modelLabel = 'Lizenzartikel';
protected static ?string $pluralModelLabel = 'Lizenzartikel';
protected static ?string $recordTitleAttribute = 'code';
public static function canViewAny(): bool
{
return self::keeper();
}
public static function keeper(): bool
{
$user = Filament::auth()->user();
return $user instanceof User && $user->hasStaffRole(StaffRole::Katalogverwalter);
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('code')->label('Kennung')->searchable(),
TextColumn::make('product_line')->label('Produktlinie'),
TextColumn::make('currentRelease.number')->label('Aktueller Stand'),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListLicenseArticles::route('/'),
];
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Filament\Resources\LicenseArticles\Pages;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\LicenseArticle;
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
class ListLicenseArticles extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = LicenseArticleResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')
->label('Artikel anlegen')
->schema([
TextInput::make('code')->label('Kennung')->required(),
TextInput::make('product_line')->label('Produktlinie'),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
app(ArticleService::class)->create($data['code'], $data['product_line'] ?? null);
}, 'Der Lizenzartikel ist angelegt.');
}),
Action::make('release')
->label('Stand veröffentlichen')
->schema([
Select::make('article_id')->label('Artikel')->options(fn (): array => CatalogOptions::articles())->required(),
Select::make('root')->label('Wurzel')->options(fn (): array => CatalogOptions::readyTargets())->required(),
Textarea::make('classification')->label('Einordnung')->required(),
TextInput::make('change_note')->label('Änderungshinweis'),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
[$type, $id] = explode(':', $data['root'], 2);
$root = $type === 'composition'
? CompositionVersion::query()->findOrFail($id)
: ContentElementVersion::query()->findOrFail($id);
app(ArticleService::class)->publishRelease(
LicenseArticle::query()->findOrFail($data['article_id']),
$root,
$data['classification'],
$data['change_note'] ?? null,
);
}, 'Der Artikel-Stand ist veröffentlicht.');
}),
];
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Resources\Offers;
use App\Domain\Catalog\Offer;
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
use App\Filament\Resources\Offers\Pages\ListOffers;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class OfferResource extends Resource
{
protected static ?string $model = Offer::class;
protected static string|\UnitEnum|null $navigationGroup = 'Katalog';
protected static ?string $navigationLabel = 'Angebote';
protected static ?string $modelLabel = 'Angebot';
protected static ?string $pluralModelLabel = 'Angebote';
protected static ?string $recordTitleAttribute = 'name';
public static function canViewAny(): bool
{
return LicenseArticleResource::keeper();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('versions.status')->label('Fassungen')->badge(),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListOffers::route('/'),
];
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Filament\Resources\Offers\Pages;
use App\Domain\Catalog\BundleVersion;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\RightsProfileVersion;
use App\Filament\Resources\Offers\OfferResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Utilities\Get;
class ListOffers extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = OfferResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')->label('Angebot anlegen')->schema([
TextInput::make('name')->label('Name')->required(),
])->action(function (array $data): void {
$this->report(function () use ($data): void {
app(OfferService::class)->create($data['name']);
}, 'Das Angebot ist angelegt.');
}),
Action::make('activate')->label('Fassung aktivieren')->schema([
Select::make('offer_id')->label('Angebot')->options(fn (): array => CatalogOptions::offers())->required(),
Select::make('grant_kind')->label('Vergabe')->options([
'kauf' => 'Kauf',
'auf_abruf' => 'Auf Abruf',
'bei_registrierung' => 'Bei Registrierung',
])->required(),
TextInput::make('price_cents')->label('Preis in Cent')->numeric(),
Repeater::make('lines')->label('Positionen')->schema([
Select::make('kind')->label('Ziel')->options([
'article' => 'Lizenzartikel',
'bundle' => 'Paketfassung',
])->required()->live(),
Select::make('article_id')->label('Artikel')->options(fn (): array => CatalogOptions::articles())
->visible(fn (Get $get): bool => $get('kind') === 'article'),
Select::make('bundle_version_id')->label('Paketfassung')->options(fn (): array => CatalogOptions::bundleVersions())
->visible(fn (Get $get): bool => $get('kind') === 'bundle'),
Select::make('rights_id')->label('Rechte')->options(fn (): array => CatalogOptions::rights())->required(),
])->minItems(1),
])->action(function (array $data): void {
$this->report(function () use ($data): void {
$lines = [];
foreach ($data['lines'] as $line) {
$target = $line['kind'] === 'bundle'
? BundleVersion::query()->findOrFail($line['bundle_version_id'])
: LicenseArticle::query()->findOrFail($line['article_id']);
$lines[] = [
'target' => $target,
'rights' => RightsProfileVersion::query()->findOrFail($line['rights_id']),
];
}
app(OfferService::class)->activate(Offer::query()->findOrFail($data['offer_id']), $lines, [
'grant_kind' => $data['grant_kind'],
'price_cents' => $data['price_cents'] === null || $data['price_cents'] === '' ? null : (int) $data['price_cents'],
'holder_kind' => 'person',
]);
}, 'Die Angebotsfassung ist aktiv.');
}),
];
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Filament\Resources\RightsProfiles\Pages;
use App\Domain\Catalog\OfferService;
use App\Filament\Resources\RightsProfiles\RightsProfileResource;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ListRecords;
class ListRightsProfiles extends ListRecords
{
use ReportsDomainRules;
protected static string $resource = RightsProfileResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('create')->label('Rechteprofil anlegen')->schema([
TextInput::make('name')->label('Name')->required(),
Select::make('purpose')->label('Zweck')->options([
'ehrenamtlich' => 'Ehrenamtlich',
'kommerziell' => 'Kommerziell',
'institutionell' => 'Institutionell',
])->required(),
CheckboxList::make('capabilities')->label('Fähigkeiten')->options([
'film:streamen' => 'Film streamen',
'film:ansehen' => 'Film ansehen',
'audio:streamen' => 'Audio streamen',
'pdf:ansehen' => 'PDF ansehen',
'pdf:laden' => 'PDF laden',
'text:ansehen' => 'Text ansehen',
'bild:ansehen' => 'Bild ansehen',
])->required(),
])->action(function (array $data): void {
$this->report(function () use ($data): void {
$capabilities = [];
foreach ($data['capabilities'] as $entry) {
[$class, $action] = explode(':', $entry, 2);
$capabilities[$class][] = $action;
}
app(OfferService::class)->createRightsProfile($data['name'], $data['purpose'], $capabilities);
}, 'Das Rechteprofil ist angelegt.');
}),
];
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Filament\Resources\RightsProfiles;
use App\Domain\Catalog\RightsProfile;
use App\Filament\Resources\LicenseArticles\LicenseArticleResource;
use App\Filament\Resources\RightsProfiles\Pages\ListRightsProfiles;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class RightsProfileResource extends Resource
{
protected static ?string $model = RightsProfile::class;
protected static string|\UnitEnum|null $navigationGroup = 'Katalog';
protected static ?string $navigationLabel = 'Rechteprofile';
protected static ?string $modelLabel = 'Rechteprofil';
protected static ?string $pluralModelLabel = 'Rechteprofile';
protected static ?string $recordTitleAttribute = 'name';
public static function canViewAny(): bool
{
return LicenseArticleResource::keeper();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('versions.purpose')->label('Zwecke')->badge(),
])->recordUrl(null);
}
public static function getPages(): array
{
return [
'index' => ListRightsProfiles::route('/'),
];
}
}
@@ -2,14 +2,53 @@
namespace App\Filament\Resources\Users\Pages;
use App\Domain\Catalog\Offer;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Identity\StaffRole;
use App\Filament\Resources\Users\UserResource;
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\ReportsDomainRules;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;
class EditUser extends EditRecord
{
use ReportsDomainRules;
protected static string $resource = UserResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('grant')
->label('Berechtigung vergeben')
->visible(function (): bool {
$actor = Filament::auth()->user();
return $actor instanceof User && $actor->hasStaffRole(StaffRole::Kundenbetreuung);
})
->schema([
Select::make('offer_id')->label('Angebot')->options(fn (): array => CatalogOptions::offers())->required(),
Textarea::make('reason')->label('Begründung')->required(),
])
->action(function (array $data): void {
$this->report(function () use ($data): void {
app(GrantIssuer::class)->grantManually(
$this->record,
Offer::query()->findOrFail($data['offer_id']),
Filament::auth()->user(),
$data['reason'],
);
}, 'Die Berechtigung ist vergeben.');
}),
];
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\BundleStatus;
use App\Domain\Catalog\BundleVersion;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\RightsProfileVersion;
class CatalogOptions
{
/**
* @return array<int, string>
*/
public static function elements(): array
{
return ContentElement::query()->orderBy('working_title')->pluck('working_title', 'id')->all();
}
/**
* @return array<string, string>
*/
public static function readyTargets(): array
{
$options = [];
foreach (ContentElementVersion::query()->where('status', ContentVersionStatus::Bereit)->with('element')->orderBy('id')->get() as $version) {
$options['element:'.$version->id] = $version->element->working_title.' · Fassung '.$version->number;
}
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition')->orderBy('id')->get() as $version) {
$options['composition:'.$version->id] = $version->composition->designation.' · Fassung '.$version->number;
}
return $options;
}
/**
* @return array<int, string>
*/
public static function compositions(): array
{
return Composition::query()->orderBy('designation')->pluck('designation', 'id')->all();
}
/**
* @return array<int, string>
*/
public static function articles(): array
{
return LicenseArticle::query()->orderBy('code')->pluck('code', 'id')->all();
}
/**
* @return array<int, string>
*/
public static function bundles(): array
{
return Bundle::query()->orderBy('name')->pluck('name', 'id')->all();
}
/**
* @return array<int, string>
*/
public static function bundleVersions(): array
{
return BundleVersion::query()
->where('status', BundleStatus::Veroeffentlicht)
->with('bundle')
->orderBy('id')
->get()
->mapWithKeys(fn (BundleVersion $version): array => [$version->id => $version->bundle->name.' · Fassung '.$version->number])
->all();
}
/**
* @return array<int, string>
*/
public static function rights(): array
{
return RightsProfileVersion::query()->with('profile')->orderBy('id')->get()
->mapWithKeys(fn (RightsProfileVersion $version): array => [$version->id => $version->profile->name.' · '.$version->purpose])
->all();
}
/**
* @return array<int, string>
*/
public static function offers(): array
{
return Offer::query()->orderBy('name')->pluck('name', 'id')->all();
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\DomainRuleException;
use Filament\Notifications\Notification;
trait ReportsDomainRules
{
protected function report(callable $callback, string $success): void
{
try {
$callback();
Notification::make()->title($success)->success()->send();
} catch (DomainRuleException $exception) {
Notification::make()->title($exception->getMessage())->danger()->send();
}
}
}
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Auth;
use App\Domain\Entitlement\GrantIssuer;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
@@ -22,6 +23,7 @@ public function notice(Request $request): View|RedirectResponse
public function verify(EmailVerificationRequest $request): RedirectResponse
{
$request->fulfill();
app(GrantIssuer::class)->grantRegistrationOffers($request->user());
return redirect()->route('member.dashboard');
}
@@ -0,0 +1,100 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\Order;
use App\Domain\Entitlement\GrantIssuer;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class CheckoutController extends Controller
{
public function offers(): View
{
$offers = Offer::query()
->whereHas('versions', fn ($query) => $query->where('status', OfferStatus::Aktiv)->where('holder_kind', 'person'))
->with(['versions' => fn ($query) => $query->where('status', OfferStatus::Aktiv)])
->orderBy('name')
->get();
return view('member.offers', ['offers' => $offers]);
}
public function claim(Request $request, Offer $offer, GrantIssuer $issuer): RedirectResponse
{
try {
$issuer->claim($request->user(), $offer);
} catch (DomainRuleException $exception) {
return back()->withErrors(['offer' => $exception->getMessage()]);
}
return redirect()->route('member.library')->with('status', 'Das Angebot liegt in Ihrer Bibliothek.');
}
public function place(Request $request, Offer $offer, Checkout $checkout): RedirectResponse
{
try {
$order = $checkout->place($request->user(), $offer);
} catch (DomainRuleException $exception) {
return back()->withErrors(['offer' => $exception->getMessage()]);
}
return redirect()->route('member.order', $order);
}
public function show(Request $request, Order $order): View
{
abort_unless($order->user_id === $request->user()->id, 403);
$order->load('lines.offerVersion.offer', 'payments');
return view('member.order', [
'order' => $order,
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
]);
}
public function confirm(Request $request, Order $order, Checkout $checkout): RedirectResponse
{
abort_unless($order->user_id === $request->user()->id, 403);
try {
$checkout->confirmTestPayment($order, 'test-'.$order->id);
} catch (DomainRuleException $exception) {
return back()->withErrors(['payment' => $exception->getMessage()]);
}
return redirect()->route('member.library')->with('status', 'Die Testzahlung ist bestätigt. Die Inhalte sind in der Bibliothek.');
}
public function fail(Request $request, Order $order, Checkout $checkout): RedirectResponse
{
abort_unless($order->user_id === $request->user()->id, 403);
try {
$checkout->failTestPayment($order, 'test-fail-'.$order->id);
} catch (DomainRuleException $exception) {
return back()->withErrors(['payment' => $exception->getMessage()]);
}
return redirect()->route('member.order', $order)->with('status', 'Die Testzahlung wurde abgelehnt. Es wurde keine Berechtigung vergeben.');
}
public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse
{
abort_unless($order->user_id === $request->user()->id, 403);
try {
$checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus');
} catch (DomainRuleException $exception) {
return back()->withErrors(['payment' => $exception->getMessage()]);
}
return redirect()->route('member.order', $order)->with('status', 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.');
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;
class LibraryController extends Controller
{
public function index(Request $request): View
{
return view('member.library', [
'grants' => $this->grantQuery($request)->with('article.currentRelease')->get(),
]);
}
public function materials(Request $request): View
{
return view('member.materials', [
'grants' => $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion.element')->get(),
]);
}
public function grants(Request $request): View
{
return view('member.grants', [
'grants' => $this->grantQuery($request)->get(),
]);
}
public function show(Request $request, LicenseArticle $article): View
{
$release = $article->currentRelease()->with('contents.elementVersion.element')->first();
$entries = [];
if ($release !== null) {
foreach ($release->contents as $content) {
$version = $content->elementVersion;
$class = $version->element->output_class;
$action = $class === 'film' || $class === 'audio' ? 'streamen' : 'ansehen';
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
$entries[] = [
'content' => $content,
'version' => $version,
'action' => $action,
'allowed' => $decision->allowed,
'reason' => $decision->reason,
'url' => $decision->allowed
? URL::temporarySignedRoute('member.media', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'action' => $action,
'reader' => $request->user()->id,
])
: null,
];
}
}
return view('member.article', [
'article' => $article,
'release' => $release,
'entries' => $entries,
]);
}
public function media(
Request $request,
LicenseArticle $article,
ArticleRelease $release,
ContentElementVersion $version,
string $action,
): View|StreamedResponse {
abort_unless(in_array($action, ['ansehen', 'streamen', 'laden'], true), 404);
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
abort_unless($decision->allowed, 403, $decision->reason);
$version->loadMissing('element');
$file = $version->metadata['file'] ?? null;
if (! is_string($file) || $file === '' || str_contains($file, '..')) {
return view('member.read', [
'article' => $article,
'version' => $version,
]);
}
$disk = Storage::disk('media_derived');
abort_unless($disk->exists($file), 404);
return $disk->response($file, basename($file), [
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
]);
}
private function grantQuery(Request $request)
{
return Grant::query()
->where('status', GrantStatus::Aktiv)
->whereHas('acquisition', fn ($query) => $query->where('party_id', $request->user()->party_id))
->with('article.currentRelease')
->orderBy('id');
}
}
@@ -15,21 +15,6 @@ public function dashboard(): View
return view('member.dashboard');
}
public function library(): View
{
return view('member.library');
}
public function materials(): View
{
return view('member.materials');
}
public function grants(): View
{
return view('member.grants');
}
public function profile(): View
{
return view('member.profile');
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Jobs;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentVersionStatus;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
class StoreContentFile implements ShouldQueue
{
use Queueable;
public function __construct(
public readonly int $versionId,
public readonly string $source,
) {}
public function handle(): void
{
if (! str_starts_with($this->source, 'inhalte/') || str_contains($this->source, '..')) {
return;
}
$version = ContentElementVersion::query()->find($this->versionId);
if ($version === null || $version->status !== ContentVersionStatus::Entwurf) {
return;
}
$name = basename($this->source);
if (preg_match('/^[A-Za-z0-9._-]+$/', $name) !== 1) {
return;
}
$target = 'inhalte/'.$version->id.'/'.$name;
$incoming = Storage::disk('cms_incoming');
if (! $incoming->exists($this->source)) {
return;
}
Storage::disk('media_derived')->put($target, $incoming->get($this->source));
$metadata = $version->metadata ?? [];
unset($metadata['incoming']);
$metadata['file'] = $target;
$version->metadata = $metadata;
$version->content_hash = hash('sha256', json_encode([
'body' => $version->body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->status = ContentVersionStatus::Bereit;
$version->save();
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Mail;
use App\Domain\Commerce\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class OrderConfirmed extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Order $order) {}
public function envelope(): Envelope
{
return new Envelope(subject: 'Bestellung bestätigt');
}
public function content(): Content
{
return new Content(text: 'mail.order-confirmed');
}
}
+4
View File
@@ -28,6 +28,10 @@
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'payment' => [
'driver' => env('PAYMENT_DRIVER', 'test'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
@@ -0,0 +1,71 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('manual_grants', function (Blueprint $table) {
$table->id();
$table->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$table->foreignId('party_id')->constrained()->restrictOnDelete();
$table->foreignId('offer_id')->constrained()->restrictOnDelete();
$table->text('reason');
$table->timestamps();
});
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->restrictOnDelete();
$table->foreignId('party_id')->constrained()->restrictOnDelete();
$table->string('status');
$table->string('holder_kind');
$table->timestamps();
});
Schema::create('order_lines', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id')->constrained()->cascadeOnDelete();
$table->foreignId('offer_version_id')->constrained()->restrictOnDelete();
$table->unsignedInteger('price_cents');
$table->string('term_rule');
$table->string('update_promise');
$table->string('holder_kind');
$table->timestamps();
$table->unique(['order_id', 'offer_version_id']);
});
Schema::create('order_scope_items', function (Blueprint $table) {
$table->id();
$table->foreignId('order_line_id')->constrained()->cascadeOnDelete();
$table->foreignId('license_article_id')->constrained()->restrictOnDelete();
$table->foreignId('rights_profile_version_id')->constrained()->restrictOnDelete();
$table->json('rights_snapshot');
$table->timestamps();
$table->unique(['order_line_id', 'license_article_id', 'rights_profile_version_id'], 'order_scope_unique');
});
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id')->constrained()->cascadeOnDelete();
$table->string('provider');
$table->string('status');
$table->string('provider_reference')->unique();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('payments');
Schema::dropIfExists('order_scope_items');
Schema::dropIfExists('order_lines');
Schema::dropIfExists('orders');
Schema::dropIfExists('manual_grants');
}
};
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace Database\Seeders;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\BundleService;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferService;
use Illuminate\Database\Seeder;
class DemoCatalogSeeder extends Seeder
{
public function run(): void
{
if (LicenseArticle::query()->where('code', 'demo-merkblatt')->exists()) {
return;
}
$content = app(ContentService::class);
$articles = app(ArticleService::class);
$bundles = app(BundleService::class);
$offers = app(OfferService::class);
$sheet = $content->publishElementVersion(
$content->createElement('pdf', 'pdf', 'Merkblatt Alltag'),
'Kurzer Hinweis für die Erprobung. Kein echtes Kursmaterial.',
);
$film = $content->publishElementVersion(
$content->createElement('film', 'film', 'Übungsfilm Alltag'),
'Für die geschützte Wiedergabe in der Verwaltung eine Filmdatei als weitere Fassung hochladen.',
);
$inner = $content->publishComposition(
$content->createComposition('Materialsatz Alltag'),
[['role' => 'Merkblatt', 'target' => $sheet]],
);
$exercise = $content->publishComposition(
$content->createComposition('Übung Alltag'),
[
['role' => 'Film', 'target' => $film],
['role' => 'Materialsatz', 'target' => $inner],
],
);
$sheetArticle = $articles->create('demo-merkblatt', 'Erprobung');
$articles->publishRelease($sheetArticle, $sheet, 'Eigenständiges Merkblatt für die Erprobung.');
$exerciseArticle = $articles->create('demo-uebung', 'Erprobung');
$articles->publishRelease($exerciseArticle, $exercise, 'Übung aus Film und Materialsatz, zur Erprobung.');
$basis = $bundles->create('Demo Basis');
$bundles->publish($basis, [$sheetArticle->fresh()]);
$program = $bundles->create('Demo Programm');
$programVersion = $bundles->publish($program, [$basis, $exerciseArticle->fresh()]);
$rights = $offers->createRightsProfile('Erprobung lesen und ansehen', 'ehrenamtlich', [
'pdf' => ['ansehen', 'laden'],
'film' => ['streamen', 'ansehen'],
'text' => ['ansehen'],
]);
$free = $offers->create('Kostenloses Merkblatt');
$offers->activate($free, [
['target' => $sheetArticle->fresh(), 'rights' => $rights],
], ['grant_kind' => 'auf_abruf']);
$paid = $offers->create('Testkauf Programm');
$offers->activate($paid, [
['target' => $programVersion, 'rights' => $rights],
], ['grant_kind' => 'kauf', 'price_cents' => 500]);
}
}
+3
View File
@@ -24,4 +24,7 @@ MAIL_MAILER=log
MAIL_FROM_ADDRESS="noreply@example.invalid"
MAIL_FROM_NAME="${APP_NAME}"
# test bleibt der lokale Testweg. Ein echter Zahlungsdienst ist noch nicht festgelegt.
PAYMENT_DRIVER=test
# Medienpfade setzt Compose auf den Host-Mount (/srv/luf/<env>/media/...). Hier nichts eintragen.
+25
View File
@@ -0,0 +1,25 @@
# MVP-Stand
Fortschritt für die fachliche Erprobung auf `develop`. Kein Ersatz für die Spezifikation.
## Bedienbar
- Öffentliche Seiten unter `/verwaltung` als Redakteur: Entwurf, Veröffentlichung, Wiederherstellung.
- Inhaltselemente, Fassungen und Kompositionen als Redakteur. Eine Datei wird von der Queue nach `derived/` kopiert.
- Lizenzartikel, verschachtelte Pakete, Rechteprofile und Angebote als Katalogverwalter.
- Manuelle Vergabe als Kundenbetreuung, am Benutzer in der Verwaltung.
- Registrierung, Anmeldung, kostenloser Abruf, Testkauf, Ablehnung und Widerruf im Mitgliederbereich.
- Bibliothek entscheidet je Abruf erneut. Filme mit Datei werden im Player geladen, Texte und PDF über einen kurz signierten Abruf.
Der Systemverwalter vergibt diese Rollen und kann sie dem eigenen Konto geben. Ein Konto darf mehrere Rollen tragen.
## Testdaten
`DemoCatalogSeeder` legt auf der Testumgebung Merkblatt, verschachtelte Übung, zwei Pakete, ein kostenloses Angebot und den Testkauf „Testkauf Programm“ für 5,00 € an. Der Betrag ist eine Erprobungsmarke, keine Preisentscheidung. Der Seeder läuft nur bei `LUF_ENV=test` und legt nichts ein zweites Mal an.
## Noch nicht der Zielschnitt
- Kein adaptives Streaming, keine persönliche PDF-Kennzeichnung, kein Ausgabenachweis.
- Zahlungsdienst ist der Testweg (`PAYMENT_DRIVER=test`). Ein Anbieter ist nicht festgelegt. In Produktion ist die Testbestätigung abgewiesen.
- Organisationen, Sitzplätze, Community, Rechnungen und Erstattungen über einen Zahlungsdienst fehlen.
- Echte NAS-Dateien werden nicht automatisch eingebunden. Eine Filmdatei wird in der Verwaltung als Fassung hochgeladen.
+20
View File
@@ -261,6 +261,26 @@ .member-nav a[aria-current='page'] {
text-underline-offset: 0.3rem;
}
.catalog {
list-style: none;
padding: 0;
display: grid;
gap: 1rem;
}
.catalog li {
background: white;
border: 1px solid var(--color-line);
padding: 1rem 1.1rem;
display: grid;
gap: 0.4rem;
}
.catalog video {
width: min(100%, 40rem);
background: #111;
}
.empty {
background: white;
border: 1px solid var(--color-line);
@@ -0,0 +1 @@
Ihre Bestellung {{ $order->id }} ist bezahlt. Die dazugehörigen Inhalte liegen in der Bibliothek.
+29
View File
@@ -0,0 +1,29 @@
@extends('layouts.site')
@section('title', $article->code)
@section('content')
@include('member.partials.nav')
<h1>{{ $article->code }}</h1>
@if ($release === null)
<div class="empty"><p>Für diesen Artikel ist noch kein Stand veröffentlicht.</p></div>
@else
<p>Stand {{ $release->number }}@if ($release->change_note) · {{ $release->change_note }}@endif</p>
<ul class="catalog">
@foreach ($entries as $entry)
<li>
<strong>{{ $entry['content']->path }}</strong>
@if ($entry['allowed'] && $entry['url'])
@if ($entry['action'] === 'streamen' && filled($entry['version']->metadata['file'] ?? null))
<video controls preload="metadata" src="{{ $entry['url'] }}">Der Film kann hier abgespielt werden.</video>
@else
<a href="{{ $entry['url'] }}">Öffnen</a>
@endif
@else
<span>{{ $entry['reason'] }}</span>
@endif
</li>
@endforeach
</ul>
@endif
@endsection
+1 -1
View File
@@ -5,5 +5,5 @@
@section('content')
@include('member.partials.nav')
<h1>Guten Tag, {{ auth()->user()->name }}</h1>
<p class="lede">Hier liegen später die Materialien, die eine Berechtigung für Sie freigibt.</p>
<p class="lede">In der Bibliothek liegen die Inhalte Ihrer Berechtigungen. Angebote können Sie abrufen oder im Testmodus kaufen.</p>
@endsection
+15 -3
View File
@@ -5,7 +5,19 @@
@section('content')
@include('member.partials.nav')
<h1>Berechtigungen</h1>
<div class="empty">
<p>Ihnen ist noch keine Lizenz zugeordnet.</p>
</div>
@if ($grants->isEmpty())
<div class="empty">
<p>Ihnen ist noch keine Lizenz zugeordnet.</p>
</div>
@else
<ul class="catalog">
@foreach ($grants as $grant)
<li>
<strong>{{ $grant->article->code }}</strong>
<span>{{ $grant->rights_snapshot['purpose'] ?? '' }}</span>
<span>seit {{ $grant->valid_from?->timezone(config('app.timezone'))->format('d.m.Y') }}</span>
</li>
@endforeach
</ul>
@endif
@endsection
+15 -3
View File
@@ -5,7 +5,19 @@
@section('content')
@include('member.partials.nav')
<h1>Bibliothek</h1>
<div class="empty">
<p>Ihnen ist noch kein Material zugeordnet. Sobald eine Berechtigung vorliegt, erscheinen die freigegebenen Inhalte hier. Eine Rolle allein öffnet nichts.</p>
</div>
@if ($grants->isEmpty())
<div class="empty">
<p>Ihnen ist noch kein Material zugeordnet. Sobald eine Berechtigung vorliegt, erscheinen die freigegebenen Inhalte hier. Eine Rolle allein öffnet nichts.</p>
<p><a href="{{ route('member.offers') }}">Angebote ansehen</a></p>
</div>
@else
<ul class="catalog">
@foreach ($grants as $grant)
<li>
<a href="{{ route('member.article', $grant->article) }}">{{ $grant->article->code }}</a>
<span>{{ $grant->article->currentRelease?->change_note ?: 'Aktueller Stand' }}</span>
</li>
@endforeach
</ul>
@endif
@endsection
+18 -3
View File
@@ -5,7 +5,22 @@
@section('content')
@include('member.partials.nav')
<h1>Filme und Materialien</h1>
<div class="empty">
<p>Es sind noch keine Filme oder Materialien für Ihr Konto freigegeben.</p>
</div>
@php
$films = $grants->filter(function ($grant) {
return $grant->article->currentRelease?->contents->contains(
fn ($content) => in_array($content->elementVersion->element->output_class, ['film', 'audio'], true),
);
});
@endphp
@if ($films->isEmpty())
<div class="empty">
<p>Unter Ihren Berechtigungen ist gerade kein Film oder Hörstück.</p>
</div>
@else
<ul class="catalog">
@foreach ($films as $grant)
<li><a href="{{ route('member.article', $grant->article) }}">{{ $grant->article->code }}</a></li>
@endforeach
</ul>
@endif
@endsection
+36
View File
@@ -0,0 +1,36 @@
@extends('layouts.site')
@section('title', 'Angebote')
@section('content')
@include('member.partials.nav')
<h1>Angebote</h1>
@if ($errors->any())
<div class="errors" role="alert">{{ $errors->first() }}</div>
@endif
@if ($offers->isEmpty())
<div class="empty"><p>Gerade ist kein persönliches Angebot aktiv.</p></div>
@else
<ul class="catalog">
@foreach ($offers as $offer)
@php $version = $offer->versions->first(); @endphp
<li>
<strong>{{ $offer->name }}</strong>
@if ($version)
<span>
@if ($version->grant_kind === 'kauf')
{{ number_format($version->price_cents / 100, 2, ',', '.') }} € · Testzahlung
@else
Kostenlos
@endif
</span>
<form method="post" action="{{ $version->grant_kind === 'kauf' ? route('member.offers.buy', $offer) : route('member.offers.claim', $offer) }}">
@csrf
<button class="button" type="submit">{{ $version->grant_kind === 'kauf' ? 'Kaufen' : 'In die Bibliothek' }}</button>
</form>
@endif
</li>
@endforeach
</ul>
@endif
@endsection
+31
View File
@@ -0,0 +1,31 @@
@extends('layouts.site')
@section('title', 'Bestellung')
@section('content')
@include('member.partials.nav')
<h1>Bestellung {{ $order->id }}</h1>
@if ($errors->any())
<div class="errors" role="alert">{{ $errors->first() }}</div>
@endif
<p>Status: {{ $order->status }}</p>
@foreach ($order->lines as $line)
<p>{{ $line->offerVersion->offer->name ?? 'Angebot' }} · {{ number_format($line->price_cents / 100, 2, ',', '.') }} €</p>
@endforeach
@if ($testPayment && $order->status === 'offen')
<form method="post" action="{{ route('member.order.confirm', $order) }}">
@csrf
<button class="button" type="submit">Testzahlung bestätigen</button>
</form>
<form method="post" action="{{ route('member.order.fail', $order) }}">
@csrf
<button class="button" type="submit">Testzahlung ablehnen</button>
</form>
@endif
@if ($order->status === 'bezahlt')
<form method="post" action="{{ route('member.order.refund', $order) }}">
@csrf
<button class="button" type="submit">Widerrufen</button>
</form>
@endif
@endsection
@@ -3,6 +3,7 @@
<a href="{{ route('member.library') }}" @if(request()->routeIs('member.library')) aria-current="page" @endif>Bibliothek</a>
<a href="{{ route('member.materials') }}" @if(request()->routeIs('member.materials')) aria-current="page" @endif>Filme und Materialien</a>
<a href="{{ route('member.grants') }}" @if(request()->routeIs('member.grants')) aria-current="page" @endif>Berechtigungen</a>
<a href="{{ route('member.offers') }}" @if(request()->routeIs('member.offers')) aria-current="page" @endif>Angebote</a>
<a href="{{ route('member.profile') }}" @if(request()->routeIs('member.profile')) aria-current="page" @endif>Profil</a>
<form method="post" action="{{ route('logout') }}">
@csrf
+11
View File
@@ -0,0 +1,11 @@
@extends('layouts.site')
@section('title', $article->code)
@section('content')
@include('member.partials.nav')
<h1>{{ $version->element->working_title }}</h1>
<article class="prose">
{!! nl2br(e($version->body)) !!}
</article>
@endsection
+16 -3
View File
@@ -4,6 +4,8 @@
use App\Http\Controllers\Auth\PasswordResetController;
use App\Http\Controllers\Auth\RegistrationController;
use App\Http\Controllers\Auth\SessionController;
use App\Http\Controllers\Member\CheckoutController;
use App\Http\Controllers\Member\LibraryController;
use App\Http\Controllers\Member\MemberController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\PublicMediaController;
@@ -39,9 +41,20 @@
Route::middleware(['auth', 'verified'])->prefix('bereich')->name('member.')->group(function () {
Route::get('/', [MemberController::class, 'dashboard'])->name('dashboard');
Route::get('/bibliothek', [MemberController::class, 'library'])->name('library');
Route::get('/materialien', [MemberController::class, 'materials'])->name('materials');
Route::get('/berechtigungen', [MemberController::class, 'grants'])->name('grants');
Route::get('/bibliothek', [LibraryController::class, 'index'])->name('library');
Route::get('/bibliothek/{article}', [LibraryController::class, 'show'])->name('article');
Route::get('/ausgabe/{article}/{release}/{version}/{action}', [LibraryController::class, 'media'])
->middleware('signed')
->name('media');
Route::get('/materialien', [LibraryController::class, 'materials'])->name('materials');
Route::get('/berechtigungen', [LibraryController::class, 'grants'])->name('grants');
Route::get('/angebote', [CheckoutController::class, 'offers'])->name('offers');
Route::post('/angebote/{offer}/abrufen', [CheckoutController::class, 'claim'])->name('offers.claim');
Route::post('/angebote/{offer}/kaufen', [CheckoutController::class, 'place'])->name('offers.buy');
Route::get('/bestellung/{order}', [CheckoutController::class, 'show'])->name('order');
Route::post('/bestellung/{order}/bestaetigen', [CheckoutController::class, 'confirm'])->name('order.confirm');
Route::post('/bestellung/{order}/ablehnen', [CheckoutController::class, 'fail'])->name('order.fail');
Route::post('/bestellung/{order}/widerrufen', [CheckoutController::class, 'refund'])->name('order.refund');
Route::get('/profil', [MemberController::class, 'profile'])->name('profile');
Route::post('/profil', [MemberController::class, 'updateProfile'])->name('profile.update');
});
+4
View File
@@ -111,6 +111,10 @@ deploy() {
wait_for_db || return 1
echo "=== Migrationen ==="
dc run --rm --no-deps -T app php artisan migrate --force || return 1
if [ "$LUF_ENV" = test ]; then
dc run --rm --no-deps -T app php artisan db:seed --class=Database\\Seeders\\DemoCatalogSeeder --force || return 1
echo "✓ Testdaten geprüft"
fi
echo "=== Start ==="
dc up -d --remove-orphans || return 1
wait_for_web || return 1
+187
View File
@@ -0,0 +1,187 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Commerce\Checkout;
use App\Domain\Entitlement\Acquisition;
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Entitlement\GrantStatus;
use App\Mail\OrderConfirmed;
use App\Models\User;
use Database\Seeders\DemoCatalogSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Tests\TestCase;
class MembershipAccessTest extends TestCase
{
use RefreshDatabase;
public function test_a_free_offer_is_claimed_once_per_member(): void
{
[$article, $offer] = $this->freeOffer();
$member = User::factory()->create();
$other = User::factory()->create();
$issuer = app(GrantIssuer::class);
$first = $issuer->claim($member, $offer);
$again = $issuer->claim($member, $offer);
$issuer->claim($other, $offer);
$this->assertSame($first->id, $again->id);
$this->assertSame(2, Acquisition::query()->count());
$this->assertSame(1, Grant::query()->where('acquisition_id', $first->id)->count());
$this->assertTrue(app(DecideAccess::class)(
$member,
$article,
$article->currentRelease,
$article->currentRelease->contents->first()->elementVersion,
'ansehen',
)->allowed);
}
public function test_a_grant_does_not_open_a_foreign_release(): void
{
[$article, $offer] = $this->freeOffer();
$foreign = app(ArticleService::class);
$content = app(ContentService::class);
$otherArticle = $foreign->create('fremd');
$version = $content->publishElementVersion($content->createElement('text', 'text', 'Fremd'), 'Nicht enthalten');
$release = $foreign->publishRelease($otherArticle, $version, 'Eigenständiger Artikel.');
$member = User::factory()->create();
app(GrantIssuer::class)->claim($member, $offer);
$decision = app(DecideAccess::class)(
$member,
$article,
$release,
$version,
'ansehen',
);
$this->assertFalse($decision->allowed);
}
public function test_test_payment_grants_once_and_a_failure_grants_nothing(): void
{
Mail::fake();
[$article, $offer] = $this->paidOffer();
$member = User::factory()->create();
$checkout = app(Checkout::class);
$order = $checkout->place($member, $offer);
$checkout->confirmTestPayment($order, 'test-1');
$checkout->confirmTestPayment($order->fresh(), 'test-2');
$this->assertSame(1, Grant::query()->where('license_article_id', $article->id)->count());
Mail::assertSent(OrderConfirmed::class, 1);
$second = $checkout->place($member, $offer);
$checkout->failTestPayment($second, 'test-fail-1');
$this->assertSame('fehlgeschlagen', $second->fresh()->status);
$this->assertSame(1, Grant::query()->count());
}
public function test_a_member_can_read_an_entitled_text_and_a_stranger_cannot(): void
{
Storage::fake('media_derived');
Storage::disk('media_derived')->put('inhalte/demo.txt', 'geschuetzter text');
[$article, $offer] = $this->freeOffer(file: 'inhalte/demo.txt');
$member = User::factory()->create();
$stranger = User::factory()->create();
app(GrantIssuer::class)->claim($member, $offer);
$release = $article->currentRelease;
$version = $release->contents->first()->elementVersion;
$this->actingAs($member)->get(route('member.article', $article))->assertOk()->assertSee($article->code);
$url = URL::temporarySignedRoute('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'action' => 'ansehen',
'reader' => $member->id,
]);
$response = $this->actingAs($member)->get($url);
$response->assertOk();
$this->assertSame('geschuetzter text', $response->streamedContent());
$this->actingAs($stranger)->get($url)->assertForbidden();
}
public function test_demo_catalog_can_be_seeded_twice(): void
{
$this->seed(DemoCatalogSeeder::class);
$this->seed(DemoCatalogSeeder::class);
$this->assertSame(1, LicenseArticle::query()->where('code', 'demo-merkblatt')->count());
$this->assertSame(1, Offer::query()->where('name', 'Testkauf Programm')->count());
}
public function test_refund_revokes_the_grant(): void
{
Mail::fake();
[, $offer] = $this->paidOffer();
$member = User::factory()->create();
$checkout = app(Checkout::class);
$order = $checkout->place($member, $offer);
$checkout->confirmTestPayment($order, 'test-refund');
$checkout->refund($order->fresh(), 'Testwiderruf');
$this->assertSame(GrantStatus::Widerrufen, Grant::query()->first()->status);
}
/**
* @return array{0: LicenseArticle, 1: Offer}
*/
private function freeOffer(?string $file = null): array
{
return $this->offer('auf_abruf', null, $file);
}
/**
* @return array{0: LicenseArticle, 1: Offer}
*/
private function paidOffer(): array
{
return $this->offer('kauf', 500);
}
/**
* @return array{0: LicenseArticle, 1: Offer}
*/
private function offer(string $kind, ?int $price, ?string $file = null): array
{
$content = app(ContentService::class);
$articles = app(ArticleService::class);
$offers = app(OfferService::class);
$metadata = $file === null ? [] : ['file' => $file];
$body = $file === null ? 'Lesetext' : null;
$version = $content->publishElementVersion(
$content->createElement('text', 'text', 'Blatt '.$kind),
$body,
$metadata,
);
$article = $articles->create('artikel-'.$kind.'-'.($file === null ? 'text' : 'datei'));
$articles->publishRelease($article, $version, 'Testdaten, kein Produktpreis.');
$rights = $offers->createRightsProfile('Lesen '.$kind, 'ehrenamtlich', [
'text' => ['ansehen', 'laden'],
]);
$offer = $offers->create('Angebot '.$kind);
$offers->activate($offer, [
['target' => $article->fresh(), 'rights' => $rights],
], [
'grant_kind' => $kind,
'price_cents' => $price,
]);
return [$article->fresh(), $offer];
}
}