Files
laraundfelix/tests/Feature/CartTest.php
T
Lars 4e0760db1e
Deploy Test / test (push) Successful in 1m38s
Deploy Test / deploy (push) Successful in 31s
Add feature tests for shop functionality and organization purchases
- 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.
2026-11-21 12:06:24 +01:00

458 lines
19 KiB
PHP

<?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();
}
}