| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386 |
- <?php
-
- namespace Tests\Feature\Stores;
-
- use App\Commerce\Payments\PaymentException;
- use App\Commerce\Payments\PaymentGateway;
- use App\Commerce\Payments\StripeGateway;
- use App\Enums\OrderStatus;
- use App\Mail\OrderConfirmation;
- use App\Models\Order;
- use App\Models\Product;
- use App\Models\Store;
- use App\Models\User;
- use App\StorePlan\SamplePlan;
- use Illuminate\Foundation\Testing\RefreshDatabase;
- use Illuminate\Support\Facades\Mail;
- use Inertia\Testing\AssertableInertia as Assert;
- use Tests\Support\FakeGateway;
- use Tests\TestCase;
-
- class CheckoutTest extends TestCase
- {
- use RefreshDatabase;
-
- private User $user;
-
- private Store $store;
-
- private FakeGateway $gateway;
-
- protected function setUp(): void
- {
- parent::setUp();
-
- Mail::fake();
-
- $this->gateway = new FakeGateway;
- $this->app->instance(PaymentGateway::class, $this->gateway);
-
- $this->user = User::factory()->create();
- $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
- $this->store->plan = SamplePlan::for($this->store);
- $this->store->save();
- $this->actingAs($this->user);
- }
-
- /**
- * @return array<string, string>
- */
- private function details(array $overrides = []): array
- {
- return [
- 'name' => 'Aminah binti Ali',
- 'email' => 'aminah@example.com',
- 'phone' => '012-345 6789',
- 'line1' => '12 Jalan Mawar',
- 'line2' => '',
- 'city' => 'Shah Alam',
- 'postcode' => '40000',
- 'state' => 'Selangor',
- ...$overrides,
- ];
- }
-
- private function addToCart(Product $product, int $quantity = 1): void
- {
- $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity]);
- }
-
- private function placeOrder(array $overrides = [])
- {
- return $this->post(route('stores.preview.checkout.store', $this->store->slug), $this->details($overrides));
- }
-
- private function orderPage(Order $order)
- {
- return $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
- }
-
- public function test_checkout_needs_something_in_the_cart()
- {
- $this->get(route('stores.preview.checkout', $this->store->slug))
- ->assertRedirect(route('stores.preview.cart', $this->store->slug));
-
- $this->placeOrder()->assertSessionHasErrors('cart');
-
- $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
-
- $this->get(route('stores.preview.checkout', $this->store->slug))
- ->assertOk()
- ->assertInertia(fn (Assert $page) => $page
- ->where('view.type', 'checkout')
- ->has('view.states', 16)
- ->where('cart.count', 1));
- }
-
- public function test_placing_an_order_saves_it_and_sends_the_shopper_to_the_payment_page()
- {
- $sambal = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
- $kerepek = Product::factory()->for($this->store)->create(['name' => 'Kerepek', 'price' => 799, 'stock' => 10]);
- $this->addToCart($sambal, 2);
- $this->addToCart($kerepek, 1);
-
- $this->placeOrder()->assertRedirect('https://pay.test/cs_fake_1');
-
- $order = Order::with('items')->firstOrFail();
-
- $this->assertSame($this->store->id, $order->store_id);
- $this->assertSame(1001, $order->number);
- $this->assertSame(OrderStatus::Pending, $order->status);
- $this->assertSame(3379, $order->subtotal);
- // Selangor is in Peninsular Malaysia: the store's default RM 8.00 fee.
- $this->assertSame(800, $order->shipping_total);
- $this->assertSame(4179, $order->total);
- $this->assertSame('MYR', $order->currency);
- $this->assertSame('fake', $order->payment_provider);
- $this->assertSame('cs_fake_1', $order->payment_checkout_id);
- $this->assertSame('Aminah binti Ali', $order->customer_name);
- $this->assertSame(['line1' => '12 Jalan Mawar', 'line2' => null, 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor', 'country' => 'MY'], $order->shipping_address);
- $this->assertSame(26, strlen($order->public_id));
- $this->assertCount(2, $order->items);
- $this->assertSame(['Sambal', 1290, 2, 2580], [$order->items[0]->name, $order->items[0]->unit_price, $order->items[0]->quantity, $order->items[0]->line_total]);
-
- // Nothing is taken from stock, and no email goes out, until the order is paid.
- $this->assertSame(10, $sambal->fresh()->stock);
- Mail::assertNothingSent();
-
- // The next order of the same store gets the next number.
- $this->placeOrder();
- $this->assertSame(1002, Order::latest('id')->firstOrFail()->number);
- }
-
- public function test_shopper_details_are_checked()
- {
- $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
-
- $this->placeOrder([
- 'name' => '',
- 'email' => 'not-an-email',
- 'phone' => 'call me',
- 'line1' => '',
- 'city' => '',
- 'postcode' => '4000',
- 'state' => 'Atlantis',
- ])->assertSessionHasErrors(['name', 'email', 'phone', 'line1', 'city', 'postcode', 'state']);
-
- $this->assertSame(0, Order::count());
- }
-
- public function test_an_order_must_be_at_least_two_ringgit()
- {
- $this->addToCart(Product::factory()->for($this->store)->create(['price' => 199]));
-
- $this->placeOrder()->assertSessionHasErrors('cart');
-
- $this->assertSame(0, Order::count());
- }
-
- public function test_if_the_payment_page_cannot_be_opened_no_order_is_left_behind()
- {
- $this->gateway->failToStart = true;
- $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
-
- $this->placeOrder()->assertSessionHasErrors('cart');
-
- $this->assertSame(0, Order::count());
- $this->get(route('stores.preview.cart', $this->store->slug))
- ->assertInertia(fn (Assert $page) => $page->where('cart.count', 1));
- }
-
- public function test_a_paid_order_is_marked_lowers_stock_empties_the_cart_and_emails_the_shopper_once()
- {
- $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
- $this->addToCart($product, 3);
- $this->placeOrder();
- $order = Order::firstOrFail();
-
- $this->gateway->pay($order);
-
- $this->orderPage($order)
- ->assertOk()
- ->assertInertia(fn (Assert $page) => $page
- ->where('view.type', 'order')
- ->where('view.order.status', 'paid')
- ->where('view.order.number', 1001)
- ->where('view.order.subtotal', 38.7)
- ->where('view.order.shipping_total', 8)
- ->where('view.order.total', 46.7)
- ->has('view.order.items', 1)
- ->where('cart.count', 0));
-
- $order->refresh();
-
- $this->assertTrue($order->isPaid());
- $this->assertNotNull($order->paid_at);
- $this->assertSame('pi_fake_1', $order->payment_reference);
- $this->assertSame(7, $product->fresh()->stock);
-
- Mail::assertSent(OrderConfirmation::class, fn (OrderConfirmation $mail) => $mail->hasTo('aminah@example.com')
- && $mail->order->is($order));
-
- // Opening the page again must not take stock or send the email a second time.
- $this->orderPage($order)->assertOk();
-
- $this->assertSame(7, $product->fresh()->stock);
- Mail::assertSent(OrderConfirmation::class, 1);
- }
-
- public function test_an_unpaid_order_stays_pending_and_the_cart_is_kept()
- {
- $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
- $this->addToCart($product, 2);
- $this->placeOrder();
- $order = Order::firstOrFail();
-
- $this->orderPage($order)
- ->assertInertia(fn (Assert $page) => $page
- ->where('view.order.status', 'pending')
- ->where('cart.count', 2));
-
- $this->assertFalse($order->fresh()->isPaid());
- $this->assertSame(10, $product->fresh()->stock);
- Mail::assertNothingSent();
- }
-
- public function test_a_payment_of_the_wrong_amount_does_not_mark_the_order_paid()
- {
- $this->addToCart(Product::factory()->for($this->store)->create(['price' => 5000, 'stock' => 5]));
- $this->placeOrder();
- $order = Order::firstOrFail();
-
- $this->gateway->pay($order, amount: 500);
-
- $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
-
- Mail::assertNothingSent();
- }
-
- public function test_an_order_keeps_its_own_record_when_products_change_later()
- {
- $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
- $this->addToCart($product, 2);
- $this->placeOrder();
- $order = Order::firstOrFail();
-
- $product->update(['name' => 'Renamed', 'price' => 9900]);
- $product->delete();
-
- $item = $order->items()->firstOrFail();
-
- $this->assertNull($item->product_id);
- $this->assertSame(['Sambal', 1290, 2580], [$item->name, $item->unit_price, $item->line_total]);
- $this->assertSame(2580, $order->fresh()->subtotal);
- $this->assertSame(3380, $order->fresh()->total);
-
- // Paying for it still works, even though the product is gone.
- $this->gateway->pay($order);
- $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid'));
- }
-
- public function test_stock_never_goes_below_zero()
- {
- $product = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 5]);
- $this->addToCart($product, 4);
- $this->placeOrder();
- $order = Order::firstOrFail();
-
- // The merchant sold some elsewhere while the shopper was paying.
- $product->update(['stock' => 1]);
- $this->gateway->pay($order);
- $this->orderPage($order);
-
- $this->assertSame(0, $product->fresh()->stock);
- }
-
- public function test_the_webhook_marks_an_order_paid_without_the_shopper_coming_back()
- {
- $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
- $this->addToCart($product, 1);
- $this->placeOrder();
- $order = Order::firstOrFail();
- $this->gateway->pay($order);
-
- auth()->logout();
-
- $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'forged'])->assertStatus(400);
- $this->assertFalse($order->fresh()->isPaid());
-
- $this->postJson(route('stripe.webhook'), ['other' => 'event'], ['Stripe-Signature' => 'valid'])->assertOk();
- $this->assertFalse($order->fresh()->isPaid());
-
- $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
- $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
-
- $this->assertTrue($order->fresh()->isPaid());
- $this->assertSame(9, $product->fresh()->stock);
- Mail::assertSent(OrderConfirmation::class, 1);
- }
-
- public function test_the_real_stripe_gateway_only_accepts_messages_signed_with_our_secret()
- {
- config(['services.stripe.webhook_secret' => 'whsec_test_secret']);
-
- $payload = (string) json_encode([
- 'id' => 'evt_1',
- 'object' => 'event',
- 'type' => 'checkout.session.completed',
- 'data' => ['object' => [
- 'id' => 'cs_test_123',
- 'object' => 'checkout.session',
- 'payment_status' => 'paid',
- 'payment_intent' => 'pi_123',
- 'amount_total' => 2580,
- ]],
- ]);
- $time = time();
- $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
-
- $status = (new StripeGateway)->readWebhook($payload, $sign('whsec_test_secret'));
-
- $this->assertSame('cs_test_123', $status->checkoutId);
- $this->assertTrue($status->paid);
- $this->assertSame('pi_123', $status->reference);
- $this->assertSame(2580, $status->amount);
-
- $this->expectException(PaymentException::class);
- (new StripeGateway)->readWebhook($payload, $sign('whsec_someone_else'));
- }
-
- public function test_the_confirmation_email_lists_the_order_in_the_store_language()
- {
- $order = Order::factory()->for($this->store)->paid()->create(['number' => 1007, 'total' => 2580]);
- $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
-
- $mail = new OrderConfirmation($order);
-
- $mail->assertHasSubject('Order #1007 confirmed - Kedai Ali');
- $mail->assertSeeInHtml('Sambal Hijau');
- $mail->assertSeeInHtml('RM 25.80');
- $mail->assertSeeInHtml('12 Jalan Mawar');
-
- $this->store->update(['language' => 'ms']);
-
- (new OrderConfirmation($order->fresh()))->assertHasSubject('Pesanan #1007 disahkan - Kedai Ali');
- }
-
- public function test_the_merchant_sees_the_stores_orders()
- {
- $paid = Order::factory()->for($this->store)->paid()->create(['number' => 1001, 'total' => 5000]);
- Order::factory()->for($this->store)->create(['number' => 1002]);
- Order::factory()->create();
-
- $this->get(route('stores.orders.index', $this->store->slug))
- ->assertOk()
- ->assertInertia(fn (Assert $page) => $page
- ->component('stores/orders/index')
- ->has('orders', 2)
- ->where('orders.0.number', 1002)
- ->where('orders.0.status', 'pending')
- ->where('orders.1.status', 'paid')
- ->where('orders.1.total', 50));
-
- $this->get(route('stores.orders.show', [$this->store->slug, $paid->id]))
- ->assertOk()
- ->assertInertia(fn (Assert $page) => $page
- ->component('stores/orders/show')
- ->where('order.number', 1001)
- ->where('order.customer_email', 'aminah@example.com'));
- }
-
- public function test_orders_of_another_store_cannot_be_seen()
- {
- $theirs = Store::factory()->create();
- $theirs->plan = SamplePlan::for($theirs);
- $theirs->save();
- $order = Order::factory()->for($theirs)->paid()->create();
-
- $this->get(route('stores.orders.index', $theirs->slug))->assertNotFound();
- $this->get(route('stores.orders.show', [$theirs->slug, $order->id]))->assertNotFound();
- // Their order id inside my own store's address must not work either.
- $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))->assertNotFound();
- $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))->assertNotFound();
- $this->get(route('stores.preview.checkout', $theirs->slug))->assertNotFound();
- $this->post(route('stores.preview.checkout.store', $theirs->slug), $this->details())->assertNotFound();
- }
- }
|