AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CheckoutTest.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. namespace Tests\Feature\Stores;
  3. use App\Commerce\Payments\PaymentException;
  4. use App\Commerce\Payments\PaymentGateway;
  5. use App\Commerce\Payments\StripeGateway;
  6. use App\Enums\OrderStatus;
  7. use App\Mail\OrderConfirmation;
  8. use App\Models\Order;
  9. use App\Models\Product;
  10. use App\Models\Store;
  11. use App\Models\User;
  12. use App\StorePlan\SamplePlan;
  13. use Illuminate\Foundation\Testing\RefreshDatabase;
  14. use Illuminate\Support\Facades\Mail;
  15. use Inertia\Testing\AssertableInertia as Assert;
  16. use Tests\Support\FakeGateway;
  17. use Tests\TestCase;
  18. class CheckoutTest extends TestCase
  19. {
  20. use RefreshDatabase;
  21. private User $user;
  22. private Store $store;
  23. private FakeGateway $gateway;
  24. protected function setUp(): void
  25. {
  26. parent::setUp();
  27. Mail::fake();
  28. $this->gateway = new FakeGateway;
  29. $this->app->instance(PaymentGateway::class, $this->gateway);
  30. $this->user = User::factory()->create();
  31. $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
  32. $this->store->plan = SamplePlan::for($this->store);
  33. $this->store->save();
  34. $this->actingAs($this->user);
  35. }
  36. /**
  37. * @return array<string, string>
  38. */
  39. private function details(array $overrides = []): array
  40. {
  41. return [
  42. 'name' => 'Aminah binti Ali',
  43. 'email' => 'aminah@example.com',
  44. 'phone' => '012-345 6789',
  45. 'line1' => '12 Jalan Mawar',
  46. 'line2' => '',
  47. 'city' => 'Shah Alam',
  48. 'postcode' => '40000',
  49. 'state' => 'Selangor',
  50. ...$overrides,
  51. ];
  52. }
  53. private function addToCart(Product $product, int $quantity = 1): void
  54. {
  55. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity]);
  56. }
  57. private function placeOrder(array $overrides = [])
  58. {
  59. return $this->post(route('stores.preview.checkout.store', $this->store->slug), $this->details($overrides));
  60. }
  61. private function orderPage(Order $order)
  62. {
  63. return $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
  64. }
  65. public function test_checkout_needs_something_in_the_cart()
  66. {
  67. $this->get(route('stores.preview.checkout', $this->store->slug))
  68. ->assertRedirect(route('stores.preview.cart', $this->store->slug));
  69. $this->placeOrder()->assertSessionHasErrors('cart');
  70. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
  71. $this->get(route('stores.preview.checkout', $this->store->slug))
  72. ->assertOk()
  73. ->assertInertia(fn (Assert $page) => $page
  74. ->where('view.type', 'checkout')
  75. ->has('view.states', 16)
  76. ->where('cart.count', 1));
  77. }
  78. public function test_placing_an_order_saves_it_and_sends_the_shopper_to_the_payment_page()
  79. {
  80. $sambal = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
  81. $kerepek = Product::factory()->for($this->store)->create(['name' => 'Kerepek', 'price' => 799, 'stock' => 10]);
  82. $this->addToCart($sambal, 2);
  83. $this->addToCart($kerepek, 1);
  84. $this->placeOrder()->assertRedirect('https://pay.test/cs_fake_1');
  85. $order = Order::with('items')->firstOrFail();
  86. $this->assertSame($this->store->id, $order->store_id);
  87. $this->assertSame(1001, $order->number);
  88. $this->assertSame(OrderStatus::Pending, $order->status);
  89. $this->assertSame(3379, $order->subtotal);
  90. // Selangor is in Peninsular Malaysia: the store's default RM 8.00 fee.
  91. $this->assertSame(800, $order->shipping_total);
  92. $this->assertSame(4179, $order->total);
  93. $this->assertSame('MYR', $order->currency);
  94. $this->assertSame('fake', $order->payment_provider);
  95. $this->assertSame('cs_fake_1', $order->payment_checkout_id);
  96. $this->assertSame('Aminah binti Ali', $order->customer_name);
  97. $this->assertSame(['line1' => '12 Jalan Mawar', 'line2' => null, 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor', 'country' => 'MY'], $order->shipping_address);
  98. $this->assertSame(26, strlen($order->public_id));
  99. $this->assertCount(2, $order->items);
  100. $this->assertSame(['Sambal', 1290, 2, 2580], [$order->items[0]->name, $order->items[0]->unit_price, $order->items[0]->quantity, $order->items[0]->line_total]);
  101. // Nothing is taken from stock, and no email goes out, until the order is paid.
  102. $this->assertSame(10, $sambal->fresh()->stock);
  103. Mail::assertNothingSent();
  104. // The next order of the same store gets the next number.
  105. $this->placeOrder();
  106. $this->assertSame(1002, Order::latest('id')->firstOrFail()->number);
  107. }
  108. public function test_shopper_details_are_checked()
  109. {
  110. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
  111. $this->placeOrder([
  112. 'name' => '',
  113. 'email' => 'not-an-email',
  114. 'phone' => 'call me',
  115. 'line1' => '',
  116. 'city' => '',
  117. 'postcode' => '4000',
  118. 'state' => 'Atlantis',
  119. ])->assertSessionHasErrors(['name', 'email', 'phone', 'line1', 'city', 'postcode', 'state']);
  120. $this->assertSame(0, Order::count());
  121. }
  122. public function test_an_order_must_be_at_least_two_ringgit()
  123. {
  124. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 199]));
  125. $this->placeOrder()->assertSessionHasErrors('cart');
  126. $this->assertSame(0, Order::count());
  127. }
  128. public function test_if_the_payment_page_cannot_be_opened_no_order_is_left_behind()
  129. {
  130. $this->gateway->failToStart = true;
  131. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
  132. $this->placeOrder()->assertSessionHasErrors('cart');
  133. $this->assertSame(0, Order::count());
  134. $this->get(route('stores.preview.cart', $this->store->slug))
  135. ->assertInertia(fn (Assert $page) => $page->where('cart.count', 1));
  136. }
  137. public function test_a_paid_order_is_marked_lowers_stock_empties_the_cart_and_emails_the_shopper_once()
  138. {
  139. $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
  140. $this->addToCart($product, 3);
  141. $this->placeOrder();
  142. $order = Order::firstOrFail();
  143. $this->gateway->pay($order);
  144. $this->orderPage($order)
  145. ->assertOk()
  146. ->assertInertia(fn (Assert $page) => $page
  147. ->where('view.type', 'order')
  148. ->where('view.order.status', 'paid')
  149. ->where('view.order.number', 1001)
  150. ->where('view.order.subtotal', 38.7)
  151. ->where('view.order.shipping_total', 8)
  152. ->where('view.order.total', 46.7)
  153. ->has('view.order.items', 1)
  154. ->where('cart.count', 0));
  155. $order->refresh();
  156. $this->assertTrue($order->isPaid());
  157. $this->assertNotNull($order->paid_at);
  158. $this->assertSame('pi_fake_1', $order->payment_reference);
  159. $this->assertSame(7, $product->fresh()->stock);
  160. Mail::assertSent(OrderConfirmation::class, fn (OrderConfirmation $mail) => $mail->hasTo('aminah@example.com')
  161. && $mail->order->is($order));
  162. // Opening the page again must not take stock or send the email a second time.
  163. $this->orderPage($order)->assertOk();
  164. $this->assertSame(7, $product->fresh()->stock);
  165. Mail::assertSent(OrderConfirmation::class, 1);
  166. }
  167. public function test_an_unpaid_order_stays_pending_and_the_cart_is_kept()
  168. {
  169. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  170. $this->addToCart($product, 2);
  171. $this->placeOrder();
  172. $order = Order::firstOrFail();
  173. $this->orderPage($order)
  174. ->assertInertia(fn (Assert $page) => $page
  175. ->where('view.order.status', 'pending')
  176. ->where('cart.count', 2));
  177. $this->assertFalse($order->fresh()->isPaid());
  178. $this->assertSame(10, $product->fresh()->stock);
  179. Mail::assertNothingSent();
  180. }
  181. public function test_a_payment_of_the_wrong_amount_does_not_mark_the_order_paid()
  182. {
  183. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 5000, 'stock' => 5]));
  184. $this->placeOrder();
  185. $order = Order::firstOrFail();
  186. $this->gateway->pay($order, amount: 500);
  187. $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
  188. Mail::assertNothingSent();
  189. }
  190. public function test_an_order_keeps_its_own_record_when_products_change_later()
  191. {
  192. $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
  193. $this->addToCart($product, 2);
  194. $this->placeOrder();
  195. $order = Order::firstOrFail();
  196. $product->update(['name' => 'Renamed', 'price' => 9900]);
  197. $product->delete();
  198. $item = $order->items()->firstOrFail();
  199. $this->assertNull($item->product_id);
  200. $this->assertSame(['Sambal', 1290, 2580], [$item->name, $item->unit_price, $item->line_total]);
  201. $this->assertSame(2580, $order->fresh()->subtotal);
  202. $this->assertSame(3380, $order->fresh()->total);
  203. // Paying for it still works, even though the product is gone.
  204. $this->gateway->pay($order);
  205. $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid'));
  206. }
  207. public function test_stock_never_goes_below_zero()
  208. {
  209. $product = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 5]);
  210. $this->addToCart($product, 4);
  211. $this->placeOrder();
  212. $order = Order::firstOrFail();
  213. // The merchant sold some elsewhere while the shopper was paying.
  214. $product->update(['stock' => 1]);
  215. $this->gateway->pay($order);
  216. $this->orderPage($order);
  217. $this->assertSame(0, $product->fresh()->stock);
  218. }
  219. public function test_the_webhook_marks_an_order_paid_without_the_shopper_coming_back()
  220. {
  221. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  222. $this->addToCart($product, 1);
  223. $this->placeOrder();
  224. $order = Order::firstOrFail();
  225. $this->gateway->pay($order);
  226. auth()->logout();
  227. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'forged'])->assertStatus(400);
  228. $this->assertFalse($order->fresh()->isPaid());
  229. $this->postJson(route('stripe.webhook'), ['other' => 'event'], ['Stripe-Signature' => 'valid'])->assertOk();
  230. $this->assertFalse($order->fresh()->isPaid());
  231. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
  232. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
  233. $this->assertTrue($order->fresh()->isPaid());
  234. $this->assertSame(9, $product->fresh()->stock);
  235. Mail::assertSent(OrderConfirmation::class, 1);
  236. }
  237. public function test_the_real_stripe_gateway_only_accepts_messages_signed_with_our_secret()
  238. {
  239. config(['services.stripe.webhook_secret' => 'whsec_test_secret']);
  240. $payload = (string) json_encode([
  241. 'id' => 'evt_1',
  242. 'object' => 'event',
  243. 'type' => 'checkout.session.completed',
  244. 'data' => ['object' => [
  245. 'id' => 'cs_test_123',
  246. 'object' => 'checkout.session',
  247. 'payment_status' => 'paid',
  248. 'payment_intent' => 'pi_123',
  249. 'amount_total' => 2580,
  250. ]],
  251. ]);
  252. $time = time();
  253. $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
  254. $status = (new StripeGateway)->readWebhook($payload, $sign('whsec_test_secret'));
  255. $this->assertSame('cs_test_123', $status->checkoutId);
  256. $this->assertTrue($status->paid);
  257. $this->assertSame('pi_123', $status->reference);
  258. $this->assertSame(2580, $status->amount);
  259. $this->expectException(PaymentException::class);
  260. (new StripeGateway)->readWebhook($payload, $sign('whsec_someone_else'));
  261. }
  262. public function test_the_confirmation_email_lists_the_order_in_the_store_language()
  263. {
  264. $order = Order::factory()->for($this->store)->paid()->create(['number' => 1007, 'total' => 2580]);
  265. $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
  266. $mail = new OrderConfirmation($order);
  267. $mail->assertHasSubject('Order #1007 confirmed - Kedai Ali');
  268. $mail->assertSeeInHtml('Sambal Hijau');
  269. $mail->assertSeeInHtml('RM 25.80');
  270. $mail->assertSeeInHtml('12 Jalan Mawar');
  271. $this->store->update(['language' => 'ms']);
  272. (new OrderConfirmation($order->fresh()))->assertHasSubject('Pesanan #1007 disahkan - Kedai Ali');
  273. }
  274. public function test_the_merchant_sees_the_stores_orders()
  275. {
  276. $paid = Order::factory()->for($this->store)->paid()->create(['number' => 1001, 'total' => 5000]);
  277. Order::factory()->for($this->store)->create(['number' => 1002]);
  278. Order::factory()->create();
  279. $this->get(route('stores.orders.index', $this->store->slug))
  280. ->assertOk()
  281. ->assertInertia(fn (Assert $page) => $page
  282. ->component('stores/orders/index')
  283. ->has('orders', 2)
  284. ->where('orders.0.number', 1002)
  285. ->where('orders.0.status', 'pending')
  286. ->where('orders.1.status', 'paid')
  287. ->where('orders.1.total', 50));
  288. $this->get(route('stores.orders.show', [$this->store->slug, $paid->id]))
  289. ->assertOk()
  290. ->assertInertia(fn (Assert $page) => $page
  291. ->component('stores/orders/show')
  292. ->where('order.number', 1001)
  293. ->where('order.customer_email', 'aminah@example.com'));
  294. }
  295. public function test_orders_of_another_store_cannot_be_seen()
  296. {
  297. $theirs = Store::factory()->create();
  298. $theirs->plan = SamplePlan::for($theirs);
  299. $theirs->save();
  300. $order = Order::factory()->for($theirs)->paid()->create();
  301. $this->get(route('stores.orders.index', $theirs->slug))->assertNotFound();
  302. $this->get(route('stores.orders.show', [$theirs->slug, $order->id]))->assertNotFound();
  303. // Their order id inside my own store's address must not work either.
  304. $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))->assertNotFound();
  305. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))->assertNotFound();
  306. $this->get(route('stores.preview.checkout', $theirs->slug))->assertNotFound();
  307. $this->post(route('stores.preview.checkout.store', $theirs->slug), $this->details())->assertNotFound();
  308. }
  309. }