Add feature tests for shop functionality and organization purchases
Deploy Test / test (push) Successful in 1m38s
Deploy Test / deploy (push) Successful in 31s

- Implement OfferOptionAdminTest to validate offer option management, including price display, activation, and cancellation.
- Create OrganizationPurchaseTest to ensure correct handling of organization purchases, including access control and order processing.
- Add ShopProductPageTest to verify shop product listings, search functionality, and product page details.
- Introduce BuildsShop trait for seeding test data related to shop functionality.
- Implement MoneyTest to validate money parsing and formatting, ensuring correct handling of euro amounts.
This commit is contained in:
Lars committed 2026-11-21 12:06:24 +01:00
1 parent 6c8bbee363
commit 4e0760db1e
106 files changed
+4068 -76

No files matched your search

+5 -4
View File
@@ -249,7 +249,8 @@ public function test_one_offer_mask_activates_the_first_version_and_is_prefilled
->assertSee('Noch keine aktive Fassung')
->assertSee('Fassung aktivieren')
->mountAction('activate');
$this->assertSame('Erste Fassung aktivieren', $component->instance()->getMountedAction()->getModalHeading());
// Seit Etappe 1 nennt die Maske die betroffene Option (Wirkung nur auf diese Option).
$this->assertSame('Option „Merkblatt kostenlos“: erste Fassung aktivieren', $component->instance()->getMountedAction()->getModalHeading());
$component
->fillForm(['grant_kind' => 'auf_abruf', 'lines' => [['kind' => 'article', 'article_id' => $article->id, 'rights_id' => $rights->id]]])
->callMountedAction()
@@ -261,13 +262,13 @@ public function test_one_offer_mask_activates_the_first_version_and_is_prefilled
->test(ViewOffer::class, ['record' => $offer->getKey()])
->assertSee('Geänderte Fassung aktivieren')
->mountAction('activate');
$this->assertSame('Angebot ändern: Fassung 2 aktivieren', $component->instance()->getMountedAction()->getModalHeading());
$this->assertSame('Option „Merkblatt kostenlos“ ändern: Fassung 2 aktivieren', $component->instance()->getMountedAction()->getModalHeading());
$data = $component->get('mountedActions.0.data');
$this->assertSame('auf_abruf', $data['grant_kind']);
$this->assertSame((string) $article->id, (string) array_values($data['lines'])[0]['article_id']);
$this->assertSame((string) $rights->id, (string) array_values($data['lines'])[0]['rights_id']);
$component->fillForm(['grant_kind' => 'kauf', 'price_cents' => 500])
$component->fillForm(['grant_kind' => 'kauf', 'price_euro' => '5,00'])
->callMountedAction()
->assertHasNoFormErrors()
->assertSee('Fassung 2 aktiv · Kauf · 5,00 €')
@@ -384,7 +385,7 @@ public function test_changing_an_offer_keeps_terms_the_mask_does_not_show(): voi
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate')
->fillForm(['price_cents' => 1200])
->fillForm(['price_euro' => '12,00'])
->callMountedAction()
->assertHasNoFormErrors()
->assertSee('Fassung 2 aktiv · Kauf · 12,00 €');
+457
View File
@@ -0,0 +1,457 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\CompositionVersionDisplayEvent;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Commerce\Cart;
use App\Domain\Commerce\CartLine;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\Order;
use App\Domain\Commerce\StaleOverview;
use App\Domain\Entitlement\GrantIssuer;
use App\Models\User;
use App\Notifications\VerifyEmailAddress;
use Database\Seeders\ShopDemoSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\URL;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Etappe 1, Shop-Abnahme: Warenkorb vor der Anmeldung, Alternativoptionen, Preisänderung, zurückgezogene und bereits
* erworbene Positionen, serverseitige Prüfung und Bindung der Bestellung an die gezeigte Übersicht.
*/
class CartTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
public function test_a_guest_fills_the_cart_and_the_same_option_is_one_position(): void
{
$offer = $this->privateKonflikte();
$this->post(route('cart.add', $offer))->assertRedirect(route('public.program', $offer->composition_id));
$this->post(route('cart.add', $offer))->assertSessionHas('status');
$this->assertSame(1, app(Cart::class)->count());
$this->get(route('cart'))
->assertOk()
->assertSee('Konflikte im Training')
->assertSee('Privatlizenz')
->assertSee('49,00 €')
->assertSee('Anmelden und zur Kasse')
->assertSee('Dein Warenkorb bleibt dabei erhalten.');
}
public function test_the_header_cart_link_shows_the_number_of_positions(): void
{
$this->get(route('home'))->assertDontSee('<span class="shop-cart-badge"', false);
$this->post(route('cart.add', $this->privateKonflikte()));
$this->post(route('cart.add', $this->privateGrenzen()));
$this->get(route('home'))
->assertSee('<span class="shop-cart-badge" aria-hidden="true">2</span>', false)
->assertSee('Positionen</span>)', false);
}
public function test_alternative_options_of_one_product_page_are_replaced_only_after_confirmation(): void
{
$private = $this->privateKonflikte();
$club = $this->clubKonflikte();
$this->post(route('cart.add', $private));
$this->post(route('cart.add', $club))->assertSessionHas('shop.switch', $club->id);
$this->assertTrue(app(Cart::class)->has($private));
$this->assertFalse(app(Cart::class)->has($club));
$this->withSession(['shop.switch' => $club->id])
->get(route('public.program', $club->composition_id))
->assertSee('Optionen wechseln?')
->assertSee('Zu „Mehrfachlizenz für Vereine“ wechseln')
->assertSee('Bei „Privatlizenz“ bleiben');
$this->post(route('cart.switch', $club))->assertRedirect(route('cart'));
$this->assertFalse(app(Cart::class)->has($private));
$this->assertTrue(app(Cart::class)->has($club));
}
public function test_options_of_different_product_pages_and_an_independent_bundle_are_bought_together(): void
{
$cart = app(Cart::class);
$this->assertSame(Cart::ADDED, $cart->add($this->privateKonflikte()));
$this->assertSame(Cart::ADDED, $cart->add($this->privateGrenzen()));
$this->assertSame(Cart::ADDED, $cart->add($this->starter()));
$this->assertSame(3, $cart->count());
}
public function test_a_position_can_be_removed(): void
{
$offer = $this->privateKonflikte();
$this->post(route('cart.add', $offer));
$this->post(route('cart.remove', $offer))->assertRedirect(route('cart'));
$this->get(route('cart'))->assertSee('Dein Warenkorb ist leer')->assertSee('Zum Shop');
}
public function test_a_changed_price_shows_old_and_new_price_and_can_be_ordered_at_the_new_price(): void
{
$offer = $this->privateKonflikte();
$cart = app(Cart::class);
$cart->add($offer);
$this->reprice($offer, 3900);
$review = $cart->review($this->tina());
$line = $review->lines[0];
$this->assertSame(CartLine::PRICE_CHANGED, $line->state);
$this->assertSame(4900, $line->seenPriceCents);
$this->assertSame(3900, $line->currentPriceCents);
$this->actingAs($this->tina())
->get(route('cart'))
->assertSee('Preis geändert')
->assertSee('Bisher 49,00 €, jetzt 39,00 €');
$order = app(Checkout::class)->placeFromCart($this->tina(), $cart, null, $review->digest());
$this->assertSame(3900, $order->total_cents);
$this->assertSame(3900, $order->lines->first()->price_cents);
}
public function test_accepting_the_new_price_clears_the_notice(): void
{
$offer = $this->privateKonflikte();
$this->post(route('cart.add', $offer));
$this->reprice($offer, 3900);
$this->post(route('cart.accept', $offer))->assertSessionHas('status');
$this->assertSame(CartLine::OK, app(Cart::class)->review($this->tina())->lines[0]->state);
}
public function test_a_change_after_the_overview_was_shown_creates_no_order_and_shows_the_updated_overview(): void
{
$offer = $this->privateKonflikte();
$tina = $this->tina();
$cart = app(Cart::class);
$cart->add($offer);
$shown = $cart->review($tina)->digest();
$this->reprice($offer, 3500);
$this->actingAs($tina)
->post(route('checkout.place'), ['digest' => $shown])
->assertRedirect(route('checkout'))
->assertSessionHasErrors('checkout');
$this->assertSame(0, Order::query()->count());
$this->actingAs($tina)->get(route('checkout'))->assertSee('35,00 €')->assertSee('Preis geändert');
}
public function test_a_withdrawn_position_stays_visible_blocks_the_order_and_leaves_the_others_orderable(): void
{
$withdrawn = $this->privateKonflikte();
$other = $this->privateGrenzen();
$tina = $this->tina();
$cart = app(Cart::class);
$cart->add($withdrawn);
$cart->add($other);
app(OfferService::class)->end($withdrawn);
$review = $cart->review($tina);
$this->assertTrue($review->blocked());
$this->assertFalse($review->canOrder());
$this->actingAs($tina)
->get(route('cart'))
->assertSee('Nicht mehr erhältlich')
->assertSee('Konflikte im Training')
->assertSee('Entferne die Positionen, die nicht bestellt werden können');
$this->post(route('checkout.place'), ['digest' => $review->digest()])->assertSessionHasErrors('checkout');
$this->assertSame(0, Order::query()->count());
$cart->remove($withdrawn);
$order = app(Checkout::class)->placeFromCart($tina, $cart, null, $cart->review($tina)->digest());
$this->assertSame(1, $order->lines->count());
$this->assertSame($other->id, $order->lines->first()->offerVersion->offer_id);
}
public function test_an_already_owned_position_is_marked_excluded_from_the_total_and_creates_no_order_line(): void
{
$tina = $this->tina();
$this->ownByPurchase($tina, $this->privateGrenzen());
$cart = app(Cart::class);
$cart->add($this->privateGrenzen());
$cart->add($this->privateKonflikte());
$review = $cart->review($tina);
$states = collect($review->lines)->mapWithKeys(fn (CartLine $line): array => [$line->offer->name => $line->state]);
$this->assertSame(CartLine::OWNED, $states['Grenzen setzen: Privatlizenz']);
$this->assertSame(CartLine::OK, $states['Konflikte im Training: Privatlizenz']);
$this->assertSame(4900, $review->totalCents());
$this->actingAs($tina)
->get(route('cart'))
->assertSee('Bereits erworben · Wird nicht mitbestellt')
->assertSee('Zur Bibliothek')
->assertSee('Entfernen');
$order = app(Checkout::class)->placeFromCart($tina, $cart, null, $review->digest());
$this->assertSame(1, $order->lines->count());
$this->assertSame(4900, $order->total_cents);
}
public function test_when_everything_is_already_owned_the_checkout_stays_blocked(): void
{
$tina = $this->tina();
$this->ownByPurchase($tina, $this->privateGrenzen());
$cart = app(Cart::class);
$cart->add($this->privateGrenzen());
$review = $cart->review($tina);
$this->assertTrue($review->empty());
$this->assertFalse($review->canOrder());
$this->actingAs($tina)->get(route('cart'))->assertSee('Es gibt nichts zu bestellen');
$this->actingAs($tina)->post(route('checkout.place'), ['digest' => $review->digest()])->assertSessionHasErrors('checkout');
$this->assertSame(1, Order::query()->count(), 'Nur die Vorbestellung existiert.');
}
public function test_the_ownership_is_checked_again_when_the_order_is_placed(): void
{
$tina = $this->tina();
$cart = app(Cart::class);
$cart->add($this->privateGrenzen());
$cart->add($this->privateKonflikte());
$shown = $cart->review($tina)->digest();
$this->ownByPurchase($tina, $this->privateGrenzen());
$this->expectException(StaleOverview::class);
app(Checkout::class)->placeFromCart($tina, $cart, null, $shown);
}
public function test_a_bundle_with_additional_content_stays_purchasable_as_a_unit(): void
{
$tina = $this->tina();
$this->ownByPurchase($tina, $this->privateKonflikte());
$this->ownByPurchase($tina, $this->privateGrenzen());
$cart = app(Cart::class);
$cart->add($this->starter());
$line = $cart->review($tina)->lines[0];
$this->assertSame(CartLine::OK, $line->state, 'Die Einführung ist noch nicht erworben.');
$order = app(Checkout::class)->placeFromCart($tina, $cart, null, $cart->review($tina)->digest());
$this->assertSame(5900, $order->total_cents, 'Das Paket wird als Einheit zum angebotenen Preis bestellt.');
$this->assertSame(3, $order->lines->first()->scopeItems->count());
}
public function test_a_bundle_whose_whole_scope_is_owned_with_identical_rights_is_excluded(): void
{
$tina = $this->tina();
$starter = $this->starter();
$this->ownByPurchase($tina, $starter);
$cart = app(Cart::class);
$cart->add($starter);
$this->assertSame(CartLine::OWNED, $cart->review($tina)->lines[0]->state);
}
public function test_different_rights_or_an_owner_other_than_the_holder_do_not_count_as_owned(): void
{
$tina = $this->tina();
$offers = app(OfferService::class);
$commercial = $offers->createRightsProfile('Kommerziell', 'kommerziell', [
'film' => ['streamen', 'laden'],
'pdf' => ['ansehen', 'laden'],
]);
$this->ownByPurchase($tina, $this->privateGrenzen());
$commercialOffer = $offers->create('Grenzen kommerziell');
$offers->activate($commercialOffer, [['target' => $this->article('shop-grenzen'), 'rights' => $commercial]], ['grant_kind' => 'kauf', 'price_cents' => 9900]);
$cart = app(Cart::class);
$cart->add($commercialOffer);
$this->assertSame(CartLine::OK, $cart->review($tina)->lines[0]->state, 'Rechte mehrerer Erwerbe oder anderer Zwecke werden nicht verrechnet.');
// Der Erwerb der Person zählt nicht für den Verein.
$cart->clear();
$this->ownByPurchase($this->vera(), $this->privateKonflikte());
$cart->add($this->clubKonflikte());
$this->assertSame(CartLine::OK, $cart->review($this->vera(), $this->club()->id)->lines[0]->state);
}
public function test_the_rights_order_does_not_matter_when_comparing_owned_scope(): void
{
$tina = $this->tina();
$offers = app(OfferService::class);
$reordered = $offers->createRightsProfile('Gleiche Rechte, andere Reihenfolge', 'ehrenamtlich', [
'pdf' => ['laden', 'ansehen'],
'film' => ['laden', 'streamen'],
]);
$this->ownByPurchase($tina, $this->privateGrenzen());
$same = $offers->create('Grenzen gleiche Rechte');
$offers->activate($same, [['target' => $this->article('shop-grenzen'), 'rights' => $reordered]], ['grant_kind' => 'kauf', 'price_cents' => 1900]);
$cart = app(Cart::class);
$cart->add($same);
$this->assertSame(CartLine::OWNED, $cart->review($tina)->lines[0]->state);
}
public function test_free_grants_and_manual_grants_count_as_owned_but_expired_or_revoked_do_not(): void
{
$tina = $this->tina();
$offers = app(OfferService::class);
$rights = $offers->createRightsProfile('Ehrenamtlich identisch', 'ehrenamtlich', [
'film' => ['streamen', 'laden'],
'pdf' => ['ansehen', 'laden'],
]);
$free = $offers->create('Grenzen gratis');
$offers->activate($free, [['target' => $this->article('shop-grenzen'), 'rights' => $rights]], ['grant_kind' => 'auf_abruf']);
$acquisition = app(GrantIssuer::class)->claim($tina, $free);
$cart = app(Cart::class);
$cart->add($this->privateGrenzen());
$this->assertSame(CartLine::OWNED, $cart->review($tina)->lines[0]->state);
$acquisition->grants()->update(['valid_until' => now()->subDay()]);
$this->assertSame(CartLine::OK, $cart->review($tina)->lines[0]->state, 'Abgelaufen zählt nicht.');
$acquisition->grants()->update(['valid_until' => null, 'status' => 'widerrufen']);
$this->assertSame(CartLine::OK, $cart->review($tina)->lines[0]->state, 'Widerrufen zählt nicht.');
}
public function test_the_cart_survives_login_and_the_checkout_is_reached_in_the_same_session(): void
{
$offer = $this->privateKonflikte();
$this->post(route('cart.add', $offer));
$this->get(route('checkout'))->assertRedirect(route('login'));
$this->post('/anmelden', ['email' => 'tina.trainerin@example.test', 'password' => ShopDemoSeeder::PASSWORD])
->assertRedirect(route('checkout'));
$this->get(route('checkout'))->assertOk()->assertSee('Konflikte im Training')->assertSee('Bestellung anlegen');
}
public function test_the_cart_survives_registration_and_email_confirmation(): void
{
Notification::fake();
$this->post(route('cart.add', $this->privateKonflikte()));
$this->get(route('checkout'))->assertRedirect(route('login'));
$this->post('/registrieren', [
'name' => 'Neu Trainerin',
'email' => 'neu.trainerin@example.test',
'password' => 'ein-langes-passwort-1',
'password_confirmation' => 'ein-langes-passwort-1',
'adult' => '1',
])->assertRedirect(route('verification.notice'));
$user = User::query()->where('email', 'neu.trainerin@example.test')->firstOrFail();
$this->get(route('checkout'))->assertRedirect(route('verification.notice'));
$url = URL::temporarySignedRoute('verification.verify', now()->addHour(), ['id' => $user->id, 'hash' => sha1($user->email)], absolute: false);
$this->get($url)->assertRedirect(route('checkout'));
$this->get(route('checkout'))->assertOk()->assertSee('Konflikte im Training')->assertSee('Neu Trainerin');
$this->assertSame(1, app(Cart::class)->count());
Notification::assertSentTo($user, VerifyEmailAddress::class);
}
public function test_a_forged_or_foreign_digest_is_refused(): void
{
$cart = app(Cart::class);
$cart->add($this->privateKonflikte());
$foreign = $cart->review($this->max())->digest();
foreach (['gefaelscht', $foreign] as $digest) {
try {
app(Checkout::class)->placeFromCart($this->tina(), $cart, null, $digest);
$this->fail('Die Bestellung hätte abgelehnt werden müssen.');
} catch (StaleOverview) {
$this->addToAssertionCount(1);
}
}
$this->assertSame(0, Order::query()->count());
}
public function test_a_new_version_at_the_same_price_shows_updated_terms_and_can_be_accepted(): void
{
$offer = $this->privateKonflikte();
$cart = app(Cart::class);
$cart->add($offer);
$this->reprice($offer, 4900);
$line = $cart->review($this->tina())->lines[0];
$this->assertSame(CartLine::TERMS_CHANGED, $line->state);
$this->actingAs($this->tina())->get(route('cart'))
->assertSee('Bedingungen aktualisiert')
->assertSee('Neue Bedingungen übernehmen');
$this->get(route('checkout'))->assertSee('Bedingungen aktualisiert');
$this->post(route('cart.accept', $offer))->assertSessionHas('status', 'Die aktuellen Bedingungen sind übernommen.');
$this->assertSame(CartLine::OK, $cart->review($this->tina())->lines[0]->state);
}
public function test_the_checkout_says_so_when_no_holder_is_allowed(): void
{
$this->post(route('cart.add', $this->clubKonflikte()));
$this->actingAs($this->max())
->get(route('checkout', ['bestellen_als' => $this->club()->id]))
->assertSee('Für diesen Lizenzinhaber kannst du nicht bestellen')
->assertDontSee('Alle Positionen sind bereits erworben');
}
public function test_only_options_with_a_public_product_page_can_be_put_into_the_cart(): void
{
$this->privateGrenzen()->update(['composition_id' => null]);
$this->post(route('cart.add', $this->privateGrenzen()))->assertSessionHasErrors('shop');
$program = $this->program('Konflikte im Training');
$program->versions()->each(fn ($version) => $version->displayEvents()->create([
'event' => CompositionVersionDisplayEvent::REVOKED,
'actor_id' => $this->tina()->id,
'occurred_at' => now()->addSecond(),
]));
$this->post(route('cart.add', $this->privateKonflikte()))->assertSessionHasErrors('shop');
$this->assertSame(0, app(Cart::class)->count());
}
public function test_changing_one_option_leaves_the_other_options_purchasable(): void
{
$cart = app(Cart::class);
$cart->add($this->privateGrenzen());
$this->reprice($this->privateKonflikte(), 100);
$this->assertSame(CartLine::OK, $cart->review($this->tina())->lines[0]->state);
$this->assertNotNull($cart->purchasable($this->clubKonflikte()));
$this->assertNotNull($cart->purchasable($this->privateKonflikte()));
}
private function reprice(Offer $offer, int $cents): void
{
$active = app(OfferService::class)->currentActiveVersion($offer);
$lines = $active->lines()->with('article', 'bundleVersion', 'rights')->get()->map(fn ($line): array => [
'target' => $line->article ?? $line->bundleVersion,
'rights' => $line->rights,
])->all();
app(OfferService::class)->activate($offer, $lines, [
'grant_kind' => 'kauf',
'price_cents' => $cents,
'holder_kind' => $active->holder_kind,
]);
}
private function ownByPurchase(User $user, Offer $offer): Order
{
$order = $this->orderOf($user, [$offer]);
app(Checkout::class)->confirmTestPayment($order, 'test-'.$order->id.'-'.$offer->id);
app(Cart::class)->clear();
return $order->refresh();
}
}
+9 -4
View File
@@ -135,6 +135,8 @@ public function test_public_page_is_identical_for_guests_and_members(): void
public function test_global_layout_has_header_navigation_mobile_menu_and_footer(): void
{
// Der Warenkorb gehört zum Shop (Etappe 1, nur Testzahlung). Ohne aktiven Shop erscheint kein Kaufknopf.
config(['services.payment.driver' => 'stripe']);
$html = $this->get('/praevention')->assertOk()->getContent();
$this->assertStringContainsString('<a class="skip" href="#inhalt">', $html);
@@ -148,16 +150,19 @@ public function test_global_layout_has_header_navigation_mobile_menu_and_footer(
$this->assertStringContainsString('class="site-footer scope-dark"', $html);
$this->assertStringContainsString('<h2 id="fuss-footer">Service</h2>', $html);
$this->assertStringContainsString('Impressum', $html);
$this->assertStringNotContainsString('Warenkorb', $html, 'Ohne Warenkorb erscheint kein funktionsloser Kaufknopf.');
$this->assertStringNotContainsString('Warenkorb', $html, 'Ohne aktiven Shop erscheint kein Kaufknopf.');
$this->assertStringNotContainsString('fonts.bunny.net', $html);
$this->assertStringNotContainsString('fonts.googleapis.com', $html);
}
public function test_cart_entry_appears_only_when_enabled(): void
public function test_cart_entry_appears_only_when_the_shop_is_enabled(): void
{
config(['cms.cart.enabled' => true, 'cms.cart.url' => '/warenkorb']);
// Seit Etappe 1 ist der Warenkorb umgesetzt: Der Eintrag folgt dem Shop (Testzahlung, nie Produktion)
// statt der früheren Vorbereitung über cms.cart.*.
$this->get('/praevention')->assertSee('Warenkorb')->assertSee('href="'.route('cart').'"', false);
$this->get('/praevention')->assertSee('Warenkorb')->assertSee('href="/warenkorb"', false);
config(['services.payment.driver' => 'stripe']);
$this->get('/praevention')->assertDontSee('Warenkorb');
}
public function test_submenus_footer_groups_and_hidden_parents(): void
+312
View File
@@ -0,0 +1,312 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferService;
use App\Domain\Commerce\Cart;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\Order;
use App\Domain\Commerce\OrderLine;
use App\Domain\Commerce\Payment;
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\Domain\Identity\Party;
use App\Http\SignedLink;
use App\Mail\OrderConfirmed;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Etappe 1, Shop-Abnahme: Mehrangebotskauf einer Einzelperson. Eine Bestellung, zwei Positionen mit Konditionen und
* Umfang, Freischaltung genau einmal je Position, lizenzgeprüfter Download nach Testzahlung.
*/
class MultiLineCheckoutTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
public function test_two_offers_become_one_order_with_two_positions_that_keep_their_conditions_and_scope(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte(), $this->privateGrenzen()]);
$this->assertSame('offen', $order->status);
$this->assertSame($tina->id, $order->user_id, 'Das handelnde Konto steht an der Bestellung.');
$this->assertSame($tina->party_id, $order->party_id, 'Lizenzinhaber ist hier die Person selbst.');
$this->assertSame('person', $order->holder_kind);
$this->assertSame(7800, $order->total_cents);
$this->assertSame('EUR', $order->currency);
$this->assertSame(2, $order->lines->count());
$first = $order->lines->firstWhere('offer_name', 'Konflikte im Training: Privatlizenz');
$this->assertSame(4900, $first->price_cents);
$this->assertSame('EUR', $first->currency);
$this->assertSame('dauerhaft', $first->term_rule);
$this->assertSame('alle_freigegebenen_fassungen', $first->update_promise);
$this->assertSame('kauf', $first->grant_kind);
$this->assertSame('person', $first->holder_kind);
$this->assertSame($tina->party_id, $first->holder_party_id);
$this->assertSame($this->privateKonflikte()->versions()->first()->id, $first->offer_version_id);
$this->assertSame(1, $first->scopeItems->count());
$this->assertSame('ehrenamtlich', $first->scopeItems->first()->rights_snapshot['purpose']);
$this->assertEqualsCanonicalizing(['streamen', 'laden'], $first->scopeItems->first()->rights_snapshot['capabilities']['film']);
$this->assertSame(0, Grant::query()->count(), 'Vor der Zahlung gibt es keine Berechtigung.');
}
public function test_the_confirmed_test_payment_issues_every_position_exactly_once(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte(), $this->privateGrenzen(), $this->starter()]);
$checkout = app(Checkout::class);
$checkout->confirmTestPayment($order, 'test-1');
$checkout->confirmTestPayment($order->fresh(), 'test-2');
$checkout->confirmTestPayment($order->fresh(), 'test-3');
$this->assertSame('bezahlt', $order->fresh()->status);
$this->assertSame(1, Payment::query()->count());
$this->assertSame(3, Acquisition::query()->count(), 'Ein Erwerb je Bestellposition.');
// Konflikte 1 + Grenzen 1 + Paket 3 Artikel
$this->assertSame(5, Grant::query()->where('status', GrantStatus::Aktiv)->count());
foreach ($order->lines as $line) {
$acquisition = Acquisition::query()->where(['reference_type' => 'order_line', 'reference_id' => $line->id])->firstOrFail();
$this->assertSame($tina->party_id, $acquisition->party_id);
$this->assertSame($tina->id, $acquisition->acting_user_id);
$this->assertSame($line->scopeItems->count(), $acquisition->grants->count());
}
Mail::assertSent(OrderConfirmed::class, 1);
}
public function test_a_failure_while_issuing_leaves_no_payment_and_no_partial_rights_and_a_retry_succeeds(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte(), $this->privateGrenzen()]);
$this->app->bind(GrantIssuer::class, fn () => new class(app(OfferService::class)) extends GrantIssuer
{
public int $calls = 0;
public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor): Acquisition
{
if (++$this->calls === 2) {
throw new RuntimeException('simulierter Ausfall bei der zweiten Position');
}
return parent::issueFromOrderLine($line, $holder, $actor);
}
});
try {
app(Checkout::class)->confirmTestPayment($order, 'test-ausfall');
$this->fail('Der simulierte Ausfall wurde nicht geworfen.');
} catch (RuntimeException $exception) {
$this->assertStringContainsString('simulierter Ausfall', $exception->getMessage());
}
$this->assertSame('offen', $order->fresh()->status);
$this->assertSame(0, Payment::query()->count());
$this->assertSame(0, Acquisition::query()->count());
$this->assertSame(0, Grant::query()->count());
Mail::assertNothingSent();
$this->app->bind(GrantIssuer::class, fn () => new GrantIssuer(app(OfferService::class)));
app(Checkout::class)->confirmTestPayment($order->fresh(), 'test-ausfall');
$this->assertSame('bezahlt', $order->fresh()->status);
$this->assertSame(2, Acquisition::query()->count());
$this->assertSame(2, Grant::query()->count());
}
public function test_a_rejected_test_payment_issues_nothing_and_refuses_a_later_confirmation(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte(), $this->privateGrenzen()]);
$checkout = app(Checkout::class);
$checkout->failTestPayment($order, 'test-fail-1');
$this->assertSame('fehlgeschlagen', $order->fresh()->status);
$this->assertSame(0, Grant::query()->count());
$this->expectException(DomainRuleException::class);
$checkout->confirmTestPayment($order->fresh(), 'test-spaet');
}
public function test_an_open_order_without_a_payment_stays_without_rights_and_the_cart_is_emptied(): void
{
$this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->assertSame(0, Grant::query()->count());
$this->assertSame(0, app(Cart::class)->count(), 'Der Warenkorb ist nach der Bestellung geleert.');
}
public function test_an_older_order_keeps_its_price_and_version_after_the_offer_changes(): void
{
$offer = $this->privateKonflikte();
$order = $this->orderOf($this->tina(), [$offer]);
$oldVersion = $order->lines->first()->offer_version_id;
$active = app(OfferService::class)->currentActiveVersion($offer);
app(OfferService::class)->activate($offer, [['target' => $this->article('shop-konflikte'), 'rights' => $active->lines()->first()->rights]], [
'grant_kind' => 'kauf', 'price_cents' => 3900, 'holder_kind' => 'person',
]);
app(Checkout::class)->confirmTestPayment($order->fresh(), 'test-alt');
$line = $order->fresh()->lines->first();
$this->assertSame(4900, $line->price_cents);
$this->assertSame($oldVersion, $line->offer_version_id);
$this->assertSame(1, Grant::query()->count());
$this->assertSame($oldVersion, Acquisition::query()->first()->conditions['offer_version_id']);
$second = $this->orderOf($this->max(), [$offer]);
$this->assertSame(3900, $second->lines->first()->price_cents);
}
public function test_a_refund_revokes_all_positions_and_keeps_other_acquisition_sources(): void
{
$tina = $this->tina();
$free = app(OfferService::class)->create('Konflikte gratis testen');
$rights = app(OfferService::class)->createRightsProfile('Vorschau', 'ehrenamtlich', ['pdf' => ['ansehen']]);
app(OfferService::class)->activate($free, [['target' => $this->article('shop-konflikte'), 'rights' => $rights]], ['grant_kind' => 'auf_abruf']);
$freeAcquisition = app(GrantIssuer::class)->claim($tina, $free);
$earlier = $this->orderOf($tina, [$this->privateGrenzen()]);
app(Checkout::class)->confirmTestPayment($earlier, 'test-frueher');
$order = $this->orderOf($tina, [$this->privateKonflikte(), $this->starter()]);
app(Checkout::class)->confirmTestPayment($order, 'test-neu');
app(Checkout::class)->refund($order->fresh(), 'Widerruf im Test');
$this->assertSame('erstattet', $order->fresh()->status);
foreach ($order->lines as $line) {
$acquisition = Acquisition::query()->where(['reference_type' => 'order_line', 'reference_id' => $line->id])->firstOrFail();
$this->assertSame(0, $acquisition->grants()->where('status', GrantStatus::Aktiv)->count());
$this->assertSame($acquisition->grants()->count(), $acquisition->grants()->where('status', GrantStatus::Widerrufen)->count());
}
$this->assertSame(1, $freeAcquisition->grants()->where('status', GrantStatus::Aktiv)->count(), 'Die kostenlose Vergabe bleibt.');
$earlierAcquisition = Acquisition::query()->where(['reference_type' => 'order_line', 'reference_id' => $earlier->lines->first()->id])->firstOrFail();
$this->assertSame(1, $earlierAcquisition->grants()->where('status', GrantStatus::Aktiv)->count(), 'Der frühere Kauf bleibt.');
}
public function test_film_and_companion_material_are_downloadable_only_after_the_test_payment_and_only_by_the_buyer(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte()]);
[$article, $release, $film, $sheet] = $this->parts('shop-konflikte');
// Vor Geldeingang auch der direkte Abruf aus der geprüften Bestellung: gesperrt.
$this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $film, 'laden'))->assertForbidden();
$this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $sheet, 'laden'))->assertForbidden();
app(Checkout::class)->confirmTestPayment($order, 'test-download');
$filmResponse = $this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $film, 'laden'))->assertOk();
$this->assertStringContainsString('attachment', $filmResponse->headers->get('Content-Disposition'));
$this->assertSame('Platzhalter für den Film Konflikte im Training', $filmResponse->streamedContent());
$this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $sheet, 'laden'))->assertOk();
// Ein anderes Konto mit eigener Signatur bleibt ausgeschlossen, ebenso die Signatur der Käuferin.
$max = $this->max();
$this->actingAs($max)->get($this->mediaUrl($max, $article, $release, $film, 'laden'))->assertForbidden();
$this->actingAs($max)->get($this->mediaUrl($tina, $article, $release, $film, 'laden'))->assertForbidden();
}
public function test_the_library_shows_the_allowed_downloads_after_payment_and_none_before(): void
{
$tina = $this->tina();
$program = $this->program('Konflikte im Training');
$order = $this->orderOf($tina, [$this->privateKonflikte()]);
$this->actingAs($tina)->get(route('member.library'))->assertOk()->assertDontSee('Konflikte im Training');
app(Checkout::class)->confirmTestPayment($order, 'test-bibliothek');
$this->actingAs($tina)->get(route('member.library'))->assertOk()->assertSee('Konflikte im Training');
$page = $this->actingAs($tina)->get(route('member.program', $program))->assertOk();
$this->assertSame(2, substr_count($page->getContent(), '>Laden</a>'), 'Film und Begleitmaterial haben je eine Download-Aktion.');
}
public function test_a_purchase_covers_only_its_own_article(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte()]);
app(Checkout::class)->confirmTestPayment($order, 'test-fremd');
[$article, $release, $film] = $this->parts('shop-grenzen');
$this->assertFalse(app(DecideAccess::class)($tina, $article, $release, $film, 'laden')->allowed);
$this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $film, 'laden'))->assertForbidden();
}
public function test_the_order_page_lists_positions_holder_and_total(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte(), $this->privateGrenzen()]);
$this->actingAs($tina)->get(route('member.order', $order))
->assertOk()
->assertSee('Konflikte im Training: Privatlizenz')
->assertSee('Grenzen setzen: Privatlizenz')
->assertSee('78,00 €')
->assertSee('Tina Trainerin')
->assertSee('Testzahlung bestätigen');
$this->actingAs($this->max())->get(route('member.order', $order))->assertForbidden();
}
public function test_the_checkout_page_places_the_order_through_the_http_flow(): void
{
$tina = $this->tina();
$this->actingAs($tina)->post(route('cart.add', $this->privateKonflikte()));
$this->post(route('cart.add', $this->privateGrenzen()));
$page = $this->get(route('checkout'))->assertOk()->assertSee('Summe')->assertSee('78,00 €');
preg_match('/name="digest" value="([a-f0-9]{64})"/', $page->getContent(), $match);
$this->assertNotEmpty($match);
$this->post(route('checkout.place'), ['digest' => $match[1]])->assertRedirect(route('member.order', Order::query()->latest('id')->first() ?? 1));
$order = Order::query()->latest('id')->firstOrFail();
$this->post(route('member.order.confirm', $order))->assertRedirect(route('member.library'));
$this->assertSame('bezahlt', $order->fresh()->status);
$this->assertSame(2, Acquisition::query()->count());
$this->assertSame(0, app(Cart::class)->count());
}
/**
* @return array{0: LicenseArticle, 1: ArticleRelease, 2: ContentElementVersion, 3: ContentElementVersion}
*/
private function parts(string $code): array
{
$article = $this->article($code);
$release = $article->currentRelease()->with('contents.elementVersion.element')->firstOrFail();
$film = $release->contents->first(fn ($content) => $content->elementVersion->element->output_class === 'film')->elementVersion;
$sheet = $release->contents->first(fn ($content) => $content->elementVersion->element->output_class === 'pdf')->elementVersion;
return [$article, $release, $film, $sheet];
}
private function mediaUrl(User $reader, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $version, string $action): string
{
return SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'action' => $action,
'reader' => $reader->id,
]);
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\OfferStatus;
use App\Domain\Commerce\Cart;
use App\Domain\Commerce\CartLine;
use App\Filament\Resources\Offers\Pages\ListOffers;
use App\Filament\Resources\Offers\Pages\ViewOffer;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Etappe 1, Shop-Abnahme: „Lizenzoption im bestehenden Arbeitsplatz bearbeiten“. Die Maske ist vorbelegt, der Preis
* erscheint in Euro, Abbrechen verwirft die Eingaben, erst die Aktivierung wirkt, und andere Optionen bleiben kaufbar.
*/
class OfferOptionAdminTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
public function test_the_option_page_shows_price_in_euro_suitability_rights_content_and_status(): void
{
$offer = $this->privateKonflikte();
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->assertSee('Die Option auf einen Blick')
->assertSee('Preis: 49,00 €')
->assertSee('Geeignet für: Privatpersonen')
->assertSee('Ehrenamtlich: Film ansehen, Film herunterladen, PDF ansehen, PDF herunterladen')
->assertSee('Zugrunde liegender Inhalt: Konflikte im Training')
->assertSee('Status: Öffentlich kaufbar')
->assertSee('Produktseite: Konflikte im Training')
->assertSee('Geänderte Fassung aktivieren')
->assertSee('Aus dem Verkauf nehmen');
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $this->clubKonflikte()->getKey()])
->assertSee('Preis: 149,00 €')
->assertSee('Geeignet für: Organisationen und Vereine')
->assertSee('Institutionell:');
}
public function test_the_list_shows_price_and_suitability_per_option(): void
{
Livewire::actingAs($this->keeper(), 'staff')
->test(ListOffers::class)
->assertSee('Kauf · 49,00 €')
->assertSee('Für Privatpersonen')
->assertSee('Kauf · 149,00 €')
->assertSee('Für Organisationen');
}
public function test_the_mask_is_prefilled_names_the_option_and_states_the_effect(): void
{
$offer = $this->privateKonflikte();
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate');
$action = $component->instance()->getMountedAction();
$data = $component->get('mountedActions.0.data');
$this->assertSame('Option „Privatlizenz“ ändern: Fassung 2 aktivieren', $action->getModalHeading());
$description = (string) $action->getModalDescription();
$this->assertStringContainsString('Betroffen ist nur die Option „Privatlizenz“ der Produktseite „Konflikte im Training“', $description);
$this->assertStringContainsString('Andere Optionen derselben Produktseite bleiben unverändert kaufbar', $description);
$this->assertStringContainsString('„Abbrechen“ verwirft die Eingaben', $description);
$this->assertSame('Fassung 2 aktivieren', $action->getModalSubmitActionLabel());
$this->assertSame('Privatlizenz', $data['option_label']);
$this->assertSame((string) $offer->composition_id, (string) $data['composition_id']);
$this->assertSame('person', $data['holder_kind']);
$this->assertSame('kauf', $data['grant_kind']);
$this->assertSame('49,00', $data['price_euro'], 'Der Preis steht in Euro, nicht in Cent.');
$this->assertCount(1, $data['lines']);
}
public function test_cancelling_discards_the_open_input_and_creates_no_version(): void
{
$offer = $this->privateKonflikte();
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate')
->fillForm(['price_euro' => '1,00', 'option_label' => 'Geändert'])
->unmountAction();
$this->assertSame(1, $offer->versions()->count());
$this->assertSame(4900, $offer->versions()->first()->price_cents);
$this->assertSame('Privatlizenz', $offer->fresh()->option_label);
}
public function test_activating_changes_only_this_option_and_leaves_the_others_purchasable(): void
{
$offer = $this->privateKonflikte();
$club = $this->clubKonflikte();
$other = $this->privateGrenzen();
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate')
->fillForm(['price_euro' => '39,00', 'option_label' => 'Privatlizenz (neu)'])
->callMountedAction()
->assertHasNoFormErrors();
$versions = $offer->versions()->orderBy('number')->get();
$this->assertCount(2, $versions);
$this->assertSame(OfferStatus::Beendet, $versions[0]->status);
$this->assertSame(4900, $versions[0]->price_cents, 'Die frühere Fassung bleibt unverändert gespeichert.');
$this->assertSame(OfferStatus::Aktiv, $versions[1]->status);
$this->assertSame(3900, $versions[1]->price_cents);
$this->assertSame('Privatlizenz (neu)', $offer->fresh()->option_label);
foreach ([$club, $other] as $untouched) {
$this->assertSame(1, $untouched->versions()->count());
$this->assertNotNull(app(Cart::class)->purchasable($untouched));
}
$this->get(route('public.program', $offer->composition_id))
->assertSee('39,00 €')
->assertSee('Privatlizenz (neu)')
->assertSee('149,00 €');
}
public function test_an_open_cart_shows_the_activated_price_change(): void
{
$offer = $this->privateKonflikte();
$cart = app(Cart::class);
$cart->add($offer);
Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate')
->fillForm(['price_euro' => '39,00'])
->callMountedAction();
$line = $cart->review($this->tina())->lines[0];
$this->assertSame(CartLine::PRICE_CHANGED, $line->state);
$this->assertSame([4900, 3900], [$line->seenPriceCents, $line->currentPriceCents]);
}
public function test_the_price_is_entered_in_euro_and_an_invalid_amount_changes_nothing(): void
{
$offer = $this->privateKonflikte();
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('activate')
->fillForm(['price_euro' => 'zwölf Euro'])
->callMountedAction();
$this->assertSame(1, $offer->versions()->count());
$component->mountAction('activate')->fillForm(['price_euro' => '1.299,5'])->callMountedAction();
$this->assertSame(2, $offer->versions()->count());
$this->assertSame(129950, $offer->versions()->orderByDesc('number')->first()->price_cents);
}
public function test_a_purchase_needs_a_price_above_zero_and_below_the_limit(): void
{
$offer = $this->privateKonflikte();
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()]);
foreach (['0', '0,00', '', '1.000.001', '99999999999'] as $price) {
$component->mountAction('activate')->fillForm(['price_euro' => $price])->callMountedAction();
}
$this->assertSame(1, $offer->versions()->count());
}
public function test_the_holder_kind_is_chosen_in_the_mask_and_kept_by_a_change(): void
{
$club = $this->clubKonflikte();
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $club->getKey()])
->mountAction('activate');
$this->assertSame('organisation', $component->get('mountedActions.0.data.holder_kind'));
$this->assertSame('149,00', $component->get('mountedActions.0.data.price_euro'));
$component->fillForm(['price_euro' => '159,00'])->callMountedAction();
$this->assertSame('organisation', $club->versions()->orderByDesc('number')->first()->holder_kind);
}
public function test_withdrawing_an_option_ends_only_that_option_and_blocks_open_carts(): void
{
$offer = $this->privateKonflikte();
$club = $this->clubKonflikte();
$cart = app(Cart::class);
$cart->add($offer);
$component = Livewire::actingAs($this->keeper(), 'staff')
->test(ViewOffer::class, ['record' => $offer->getKey()])
->mountAction('end');
$description = (string) $component->instance()->getMountedAction()->getModalDescription();
$this->assertStringContainsString('Betroffen ist nur die Option „Privatlizenz“', $description);
$this->assertStringContainsString('blockiert den Abschluss', $description);
$component->callMountedAction();
$this->assertNull($offer->versions()->where('status', OfferStatus::Aktiv)->first());
$this->assertSame(OfferStatus::Beendet, $offer->versions()->first()->status);
$this->assertNotNull(app(Cart::class)->purchasable($club));
$this->assertSame(CartLine::WITHDRAWN, $cart->review($this->tina())->lines[0]->state);
}
public function test_a_redaktion_account_without_catalog_role_has_no_access_to_the_option(): void
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
$this->actingAs($editor, 'staff')->get('/verwaltung/offers/'.$this->privateKonflikte()->getKey())->assertForbidden();
}
private function keeper(): User
{
$keeper = User::factory()->katalogverwalter()->create();
$keeper->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $keeper;
}
}
+299
View File
@@ -0,0 +1,299 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Commerce\Cart;
use App\Domain\Commerce\CartLine;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\Order;
use App\Domain\Entitlement\Acquisition;
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Identity\Membership;
use App\Http\SignedLink;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Etappe 1, Shop-Abnahme: Mehrfachlizenz für einen vorbereiteten Verein. Der Verein ist Lizenzinhaber, das
* bestellende Konto wird getrennt festgehalten, und nur dieses Konto lädt aus der Bestellung herunter.
*/
class OrganizationPurchaseTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
public function test_the_club_is_license_holder_and_the_ordering_account_is_recorded_separately(): void
{
$vera = $this->vera();
$order = $this->orderOf($vera, [$this->clubKonflikte()]);
$this->assertSame($vera->id, $order->user_id, 'Handelndes Konto');
$this->assertSame($this->club()->id, $order->party_id, 'Lizenzinhaber');
$this->assertNotSame($vera->party_id, $order->party_id);
$this->assertSame('organisation', $order->holder_kind);
$line = $order->lines->first();
$this->assertSame($this->club()->id, $line->holder_party_id);
$this->assertSame('organisation', $line->holder_kind);
$this->assertSame(14900, $line->price_cents);
$this->assertSame('institutionell', $line->scopeItems->first()->rights_snapshot['purpose']);
app(Checkout::class)->confirmTestPayment($order, 'test-verein');
$acquisition = Acquisition::query()->firstOrFail();
$this->assertSame($this->club()->id, $acquisition->party_id);
$this->assertSame($vera->id, $acquisition->acting_user_id);
$this->assertSame(1, Grant::query()->where('status', GrantStatus::Aktiv)->count());
$this->assertSame(0, Acquisition::query()->where('party_id', $vera->party_id)->count(), 'Nichts geht an die Person.');
}
public function test_only_the_ordering_account_downloads_from_the_club_purchase(): void
{
$vera = $this->vera();
$order = $this->orderOf($vera, [$this->clubKonflikte()]);
[$article, $release, $film, $sheet] = $this->parts();
$this->actingAs($vera)->get($this->mediaUrl($vera, $article, $release, $film))->assertForbidden();
app(Checkout::class)->confirmTestPayment($order, 'test-verein');
$this->actingAs($vera)->get($this->mediaUrl($vera, $article, $release, $film))->assertOk();
$this->actingAs($vera)->get($this->mediaUrl($vera, $article, $release, $sheet))->assertOk();
// Zweites Konto desselben Vereins: auch der direkte Abruf aus dieser Bestellung ist nicht möglich.
$max = $this->max();
$this->actingAs($max)->get($this->mediaUrl($max, $article, $release, $film))->assertForbidden();
$this->actingAs($max)->get($this->mediaUrl($vera, $article, $release, $film))->assertForbidden();
$this->actingAs($max)->get(route('member.order', $order))->assertForbidden();
$this->actingAs($max)->get(route('member.library'))->assertOk()->assertDontSee('Konflikte im Training');
$this->assertFalse(app(DecideAccess::class)($max, $article, $release, $film, 'laden')->allowed);
// Ein fremdes Konto ohne jede Verbindung.
$tina = $this->tina();
$this->actingAs($tina)->get($this->mediaUrl($tina, $article, $release, $film))->assertForbidden();
}
public function test_a_second_ordering_member_of_the_same_club_gets_nothing_from_the_order_of_the_first(): void
{
$anna = $this->secondOrderer();
$vera = $this->vera();
$order = $this->orderOf($vera, [$this->clubKonflikte()]);
app(Checkout::class)->confirmTestPayment($order, 'test-verein');
[$article, $release, $film, $sheet] = $this->parts();
$this->assertTrue(app(DecideAccess::class)($vera, $article, $release, $film, 'laden')->allowed);
foreach ([$film, $sheet] as $version) {
$this->assertFalse(app(DecideAccess::class)($anna, $article, $release, $version, 'laden')->allowed);
$this->actingAs($anna)->get($this->mediaUrl($anna, $article, $release, $version))->assertForbidden();
$this->actingAs($anna)->get($this->mediaUrl($vera, $article, $release, $version))->assertForbidden();
}
$this->actingAs($anna)->get(route('member.order', $order))->assertForbidden();
$this->actingAs($anna)->get(route('member.library'))->assertOk()->assertDontSee('Konflikte im Training');
$this->actingAs($anna)->get(route('member.program', $this->program('Konflikte im Training')))->assertOk()->assertDontSee('>Laden</a>', false);
$program = $this->program('Konflikte im Training');
$program->forceFill(['thumbnail_path' => 'vorschau/konflikte.jpg'])->save();
Storage::disk('media_derived')->put('vorschau/konflikte.jpg', 'bild');
$thumbnail = route('member.thumbnail', ['kind' => 'komposition', 'subject' => $program->id]);
$this->actingAs($anna)->get($thumbnail)->assertForbidden();
$this->actingAs($vera)->get($thumbnail)->assertOk();
}
public function test_membership_boundaries_decide_the_club_access(): void
{
$vera = $this->vera();
app(Checkout::class)->confirmTestPayment($this->orderOf($vera, [$this->clubKonflikte()]), 'test-verein');
[$article, $release, $film] = $this->parts();
$membership = fn () => Membership::query()->where(['user_id' => $vera->id, 'party_id' => $this->club()->id]);
$allowed = fn (): bool => app(DecideAccess::class)($vera, $article, $release, $film, 'laden')->allowed;
$this->travelTo(now()->startOfDay()->addHours(12));
$membership()->update(['valid_until' => today()]);
$this->assertTrue($allowed(), 'Der letzte Tag gilt noch.');
$membership()->update(['valid_until' => today()->subDay()]);
$this->assertFalse($allowed(), 'Gestern beendet.');
$membership()->update(['valid_until' => null, 'valid_from' => today()]);
$this->assertTrue($allowed(), 'Der erste Tag gilt schon.');
$membership()->update(['valid_from' => today()->addDay()]);
$this->assertFalse($allowed(), 'Beginnt erst morgen.');
// Neue Regel (Entscheidung 6): Ohne Bestellberechtigung entfällt auch der Abruf.
$membership()->update(['valid_from' => null, 'may_order' => false]);
$this->assertFalse($allowed());
$membership()->update(['may_order' => true]);
$this->assertTrue($allowed());
}
public function test_an_owned_club_license_is_marked_for_a_second_orderer_who_cannot_download_it(): void
{
$anna = $this->secondOrderer();
app(Checkout::class)->confirmTestPayment($this->orderOf($this->vera(), [$this->clubKonflikte()]), 'test-verein');
$this->actingAs($anna)->post(route('cart.add', $this->clubKonflikte()));
$this->get(route('cart'))
->assertSee('Bereits erworben · Wird nicht mitbestellt')
->assertSee('gehört dem Verein bereits')
->assertSee('Herunterladen kann nur das Konto, das die Lizenz bestellt hat')
->assertDontSee('Zur Bibliothek');
}
public function test_the_library_of_the_ordering_account_lists_the_club_purchase_with_downloads(): void
{
$vera = $this->vera();
app(Checkout::class)->confirmTestPayment($this->orderOf($vera, [$this->clubKonflikte()]), 'test-verein');
$page = $this->actingAs($vera)->get(route('member.program', $this->program('Konflikte im Training')))->assertOk();
$this->assertSame(2, substr_count($page->getContent(), '>Laden</a>'));
}
public function test_the_access_ends_with_the_membership(): void
{
$vera = $this->vera();
app(Checkout::class)->confirmTestPayment($this->orderOf($vera, [$this->clubKonflikte()]), 'test-verein');
[$article, $release, $film] = $this->parts();
$this->assertTrue(app(DecideAccess::class)($vera, $article, $release, $film, 'laden')->allowed);
Membership::query()->where(['user_id' => $vera->id, 'party_id' => $this->club()->id])->update(['valid_until' => now()->subDay()]);
$this->assertFalse(app(DecideAccess::class)($vera, $article, $release, $film, 'laden')->allowed);
$this->actingAs($vera)->get($this->mediaUrl($vera, $article, $release, $film))->assertForbidden();
}
public function test_only_an_ordering_member_can_order_for_the_club(): void
{
foreach ([$this->tina(), $this->max()] as $user) {
$cart = app(Cart::class);
$cart->clear();
$cart->add($this->clubKonflikte());
$digest = $cart->review($user)->digest();
try {
app(Checkout::class)->placeFromCart($user, $cart, $this->club()->id, $digest);
$this->fail($user->name.' darf nicht für den Verein bestellen.');
} catch (DomainRuleException $exception) {
$this->assertStringContainsString('nicht bestellberechtigt', $exception->getMessage());
}
}
$this->assertSame(0, Order::query()->count());
}
public function test_an_ended_membership_cannot_order_for_the_club_any_more(): void
{
Membership::query()->where('user_id', $this->vera()->id)->update(['valid_until' => now()->subDay()]);
$cart = app(Cart::class);
$cart->add($this->clubKonflikte());
$this->assertNull($cart->review($this->vera(), $this->club()->id)->holder);
}
public function test_options_for_the_wrong_holder_kind_are_blocked_and_never_shown_as_the_other_kind(): void
{
$vera = $this->vera();
$cart = app(Cart::class);
$cart->add($this->clubKonflikte());
$cart->add($this->privateGrenzen());
$asClub = $cart->review($vera, $this->club()->id);
$states = collect($asClub->lines)->mapWithKeys(fn (CartLine $line): array => [$line->offer->name => $line->state]);
$this->assertSame(CartLine::OK, $states['Konflikte im Training: Vereinslizenz']);
$this->assertSame(CartLine::WRONG_HOLDER, $states['Grenzen setzen: Privatlizenz']);
$this->assertTrue($asClub->blocked());
$asPerson = $cart->review($vera, $vera->party_id);
$states = collect($asPerson->lines)->mapWithKeys(fn (CartLine $line): array => [$line->offer->name => $line->state]);
$this->assertSame(CartLine::WRONG_HOLDER, $states['Konflikte im Training: Vereinslizenz']);
$this->assertSame(CartLine::OK, $states['Grenzen setzen: Privatlizenz']);
$this->expectException(DomainRuleException::class);
app(Checkout::class)->placeFromCart($vera, $cart, $this->club()->id, $asClub->digest());
}
public function test_the_checkout_offers_the_choice_between_person_and_club_and_names_the_holder(): void
{
$vera = $this->vera();
$this->actingAs($vera)->post(route('cart.add', $this->clubKonflikte()));
$this->get(route('checkout'))
->assertOk()
->assertSee('Testverein Musterstadt e. V.')
->assertSee('Verein oder Organisation')
->assertSee('Der Verein ist Lizenzinhaber')
->assertSee('149,00 €');
$this->get(route('checkout', ['bestellen_als' => $vera->party_id]))
->assertOk()
->assertSee('Passt nicht zum Lizenzinhaber')
->assertSee('Diese Option ist für Organisationen');
}
public function test_the_refund_of_the_club_order_revokes_only_that_purchase(): void
{
$vera = $this->vera();
app(Checkout::class)->confirmTestPayment($this->orderOf($vera, [$this->privateGrenzen()], $vera->party_id), 'test-privat');
$order = $this->orderOf($vera, [$this->clubKonflikte()]);
app(Checkout::class)->confirmTestPayment($order, 'test-verein');
app(Checkout::class)->refund($order->fresh(), 'Widerruf im Test');
$this->assertSame(0, Grant::query()->whereHas('acquisition', fn ($query) => $query->where('party_id', $this->club()->id))->where('status', GrantStatus::Aktiv)->count());
$this->assertSame(1, Grant::query()->whereHas('acquisition', fn ($query) => $query->where('party_id', $vera->party_id))->where('status', GrantStatus::Aktiv)->count());
}
public function test_the_seeded_offers_pair_holder_kind_and_rights_purpose(): void
{
foreach (OfferVersion::query()->with('resolvedScopes.rights')->get() as $version) {
$purposes = $version->resolvedScopes->pluck('rights.purpose')->unique()->values()->all();
$this->assertSame(
$version->holder_kind === 'organisation' ? ['institutionell'] : ['ehrenamtlich'],
$purposes,
'Die Testangebote koppeln Inhaberart und Zweck (das System erzwingt das nicht).',
);
}
}
/** Zweites bestellberechtigtes Mitglied desselben Vereins. */
private function secondOrderer(): User
{
$anna = User::factory()->create(['name' => 'Anna Zweitbestellerin']);
Membership::query()->create(['user_id' => $anna->id, 'party_id' => $this->club()->id, 'role' => 'org_admin', 'may_order' => true]);
return $anna;
}
/**
* @return array{0: LicenseArticle, 1: ArticleRelease, 2: ContentElementVersion, 3: ContentElementVersion}
*/
private function parts(): array
{
$article = $this->article('shop-konflikte');
$release = $article->currentRelease()->with('contents.elementVersion.element')->firstOrFail();
$film = $release->contents->first(fn ($content) => $content->elementVersion->element->output_class === 'film')->elementVersion;
$sheet = $release->contents->first(fn ($content) => $content->elementVersion->element->output_class === 'pdf')->elementVersion;
return [$article, $release, $film, $sheet];
}
private function mediaUrl(User $reader, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $version): string
{
return SignedLink::temporary('member.media', now()->addMinutes(5), [
'article' => $article->id,
'release' => $release->id,
'version' => $version->id,
'action' => 'laden',
'reader' => $reader->id,
]);
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\OfferService;
use App\Domain\Commerce\Shop;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Etappe 1, Shop-Abnahme: „Kachel oder Shop-Suche öffnen: dieselbe Angebotsseite mit fachlichem Umfang, Bestandteilen
* und kaufbaren Optionen“ sowie der Schutz vor Produktivbetrieb.
*/
class ShopProductPageTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
}
public function test_the_shop_lists_products_with_the_lowest_price_and_opens_the_product_page(): void
{
$page = $this->get(route('shop'))->assertOk();
$page->assertSee('Konflikte im Training')
->assertSee('Grenzen setzen im Verein')
->assertSee('ab 49,00 €')
->assertSee('2 Lizenzoptionen')
->assertSee('ab 29,00 €')
->assertSee('3 Produkte');
$page->assertSee(route('public.program', $this->program('Konflikte im Training')), false);
}
public function test_the_shop_search_filters_and_shows_an_empty_state(): void
{
$this->get(route('shop', ['suche' => 'Grenzen']))
->assertOk()
->assertSee('Grenzen setzen im Verein')
->assertDontSee('Konflikte im Training')
->assertSee('1 Produkt');
$this->get(route('shop', ['suche' => 'gibt-es-nicht']))
->assertOk()
->assertSee('Keine Treffer')
->assertSee('Suche zurücksetzen');
}
public function test_the_product_page_shows_content_and_options_with_price_rights_and_term(): void
{
$response = $this->get(route('public.program', $this->program('Konflikte im Training')))->assertOk();
$response->assertSee('Konflikte erkennen, benennen und gemeinsam lösen.')
->assertSee('Film: Film Konflikte im Training')
->assertSee('Lizenzoptionen')
->assertSee('Privatlizenz')
->assertSee('49,00 €')
->assertSee('Privatpersonen')
->assertSee('Dauerhaft nutzbar')
->assertSee('Ehrenamtlich: Film ansehen, Film herunterladen, PDF ansehen, PDF herunterladen')
->assertSee('Mehrfachlizenz für Vereine')
->assertSee('149,00 €')
->assertSee('Organisationen und Vereine')
->assertSee('Institutionell: Film ansehen, Film herunterladen, PDF ansehen, PDF herunterladen')
->assertSee('Konflikte im Training', false);
// Die zugrunde liegende Artikel erscheint mit Titel, nicht mit der Kennung.
$response->assertDontSee('shop-konflikte');
}
public function test_a_withdrawn_option_disappears_while_the_other_options_stay_purchasable(): void
{
app(OfferService::class)->end($this->privateKonflikte());
$this->get(route('public.program', $this->program('Konflikte im Training')))
->assertOk()
->assertDontSee('Privatlizenz')
->assertSee('Mehrfachlizenz für Vereine')
->assertSee('149,00 €');
}
public function test_free_and_unpriced_offers_are_not_shown_as_purchasable(): void
{
$free = app(OfferService::class)->create('Kostenloses Merkblatt');
$article = $this->article('shop-konflikte');
$rights = app(OfferService::class)->createRightsProfile('Frei', 'ehrenamtlich', ['pdf' => ['ansehen']]);
app(OfferService::class)->activate($free, [['target' => $article, 'rights' => $rights]], ['grant_kind' => 'auf_abruf']);
app(OfferService::class)->assignProduct($free, $this->program('Konflikte im Training')->id, 'Kostenlos testen');
$this->get(route('public.program', $this->program('Konflikte im Training')))
->assertOk()
->assertDontSee('Kostenlos testen');
}
public function test_the_shop_exists_only_with_test_payment_and_never_in_production(): void
{
$this->assertTrue(Shop::enabled());
config(['services.payment.driver' => 'stripe']);
$this->get(route('shop'))->assertNotFound();
$this->get(route('cart'))->assertNotFound();
$this->post(route('cart.add', $this->privateKonflikte()))->assertNotFound();
$this->get(route('public.program', $this->program('Konflikte im Training')))
->assertOk()
->assertDontSee('Lizenzoptionen')
->assertDontSee('In den Warenkorb');
config(['services.payment.driver' => 'test']);
$this->app['env'] = 'production';
$this->assertFalse(Shop::enabled());
$this->get(route('shop'))->assertNotFound();
}
public function test_an_option_without_a_product_page_is_not_listed_in_the_shop(): void
{
$this->privateGrenzen()->update(['composition_id' => null]);
$this->get(route('shop'))
->assertOk()
->assertDontSee('Grenzen setzen im Verein')
->assertSee('Konflikte im Training');
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Tests\Support;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Commerce\Cart;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\Order;
use App\Domain\Identity\Party;
use App\Models\User;
use Database\Seeders\ShopDemoSeeder;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
/**
* Testdaten des Testkaufs (Etappe 1) aus dem ShopDemoSeeder: zwei Programme mit Film und Begleitmaterial, ein
* Starterpaket, Optionen für Privatpersonen und Verein, drei Konten und ein Testverein. Der Medienspeicher ist ein Fake.
*/
trait BuildsShop
{
protected function seedShop(): void
{
Storage::fake('media_derived');
Mail::fake();
$this->seed(ShopDemoSeeder::class);
}
protected function offerNamed(string $name): Offer
{
return Offer::query()->where('name', $name)->firstOrFail();
}
protected function privateKonflikte(): Offer
{
return $this->offerNamed('Konflikte im Training: Privatlizenz');
}
protected function clubKonflikte(): Offer
{
return $this->offerNamed('Konflikte im Training: Vereinslizenz');
}
protected function privateGrenzen(): Offer
{
return $this->offerNamed('Grenzen setzen: Privatlizenz');
}
protected function starter(): Offer
{
return $this->offerNamed('Starterpaket: Privatlizenz');
}
protected function tina(): User
{
return User::query()->where('email', 'tina.trainerin@example.test')->firstOrFail();
}
protected function vera(): User
{
return User::query()->where('email', 'vera.vorstand@example.test')->firstOrFail();
}
protected function max(): User
{
return User::query()->where('email', 'max.mitglied@example.test')->firstOrFail();
}
protected function club(): Party
{
return Party::query()->where('display_name', 'Testverein Musterstadt e. V.')->firstOrFail();
}
protected function article(string $code): LicenseArticle
{
return LicenseArticle::query()->where('code', $code)->firstOrFail();
}
protected function program(string $title): Composition
{
return Composition::query()->where('designation', $title)->firstOrFail();
}
/**
* Legt eine Bestellung mit den Optionen aus dem Warenkorb des Kontos an und gibt sie zurück.
*
* @param list<Offer> $offers
*/
protected function orderOf(User $user, array $offers, ?int $holderPartyId = null): Order
{
$cart = app(Cart::class);
$cart->clear();
foreach ($offers as $offer) {
$cart->add($offer);
}
$review = $cart->review($user, $holderPartyId);
return app(Checkout::class)->placeFromCart($user, $cart, $holderPartyId, $review->digest());
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace Tests\Unit;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Commerce\Money;
use PHPUnit\Framework\TestCase;
class MoneyTest extends TestCase
{
public function test_euro_input_is_parsed_to_cents(): void
{
$this->assertSame(4900, Money::parse('49'));
$this->assertSame(4900, Money::parse('49,00'));
$this->assertSame(1250, Money::parse('12,50'));
$this->assertSame(1250, Money::parse('12.50'));
$this->assertSame(129900, Money::parse('1.299'));
$this->assertSame(129950, Money::parse('1.299,5'));
$this->assertSame(500, Money::parse(' 5 € '));
$this->assertSame(0, Money::parse('0'));
$this->assertSame(Money::MAX_CENTS, Money::parse('1.000.000'));
$this->assertNull(Money::parse(''));
$this->assertNull(Money::parse(null));
}
public function test_an_invalid_amount_is_rejected(): void
{
foreach (['zwölf', '12,555', '-5', '1,2,3', '1.000.001', '99999999999'] as $input) {
try {
Money::parse($input);
$this->fail('Eingabe ohne Fehler angenommen: '.$input);
} catch (DomainRuleException) {
$this->addToAssertionCount(1);
}
}
}
public function test_cents_are_formatted_in_german_euro(): void
{
$this->assertSame('49,00 €', Money::format(4900));
$this->assertSame('1.299,50 €', Money::format(129950));
$this->assertSame('0,05 €', Money::format(5));
$this->assertSame('–', Money::format(null));
}
}