AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

CheckoutTest.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. $this->assertSame(3379, $order->total);
  91. $this->assertSame('MYR', $order->currency);
  92. $this->assertSame('fake', $order->payment_provider);
  93. $this->assertSame('cs_fake_1', $order->payment_checkout_id);
  94. $this->assertSame('Aminah binti Ali', $order->customer_name);
  95. $this->assertSame(['line1' => '12 Jalan Mawar', 'line2' => null, 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor', 'country' => 'MY'], $order->shipping_address);
  96. $this->assertSame(26, strlen($order->public_id));
  97. $this->assertCount(2, $order->items);
  98. $this->assertSame(['Sambal', 1290, 2, 2580], [$order->items[0]->name, $order->items[0]->unit_price, $order->items[0]->quantity, $order->items[0]->line_total]);
  99. // Nothing is taken from stock, and no email goes out, until the order is paid.
  100. $this->assertSame(10, $sambal->fresh()->stock);
  101. Mail::assertNothingSent();
  102. // The next order of the same store gets the next number.
  103. $this->placeOrder();
  104. $this->assertSame(1002, Order::latest('id')->firstOrFail()->number);
  105. }
  106. public function test_shopper_details_are_checked()
  107. {
  108. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
  109. $this->placeOrder([
  110. 'name' => '',
  111. 'email' => 'not-an-email',
  112. 'phone' => 'call me',
  113. 'line1' => '',
  114. 'city' => '',
  115. 'postcode' => '4000',
  116. 'state' => 'Atlantis',
  117. ])->assertSessionHasErrors(['name', 'email', 'phone', 'line1', 'city', 'postcode', 'state']);
  118. $this->assertSame(0, Order::count());
  119. }
  120. public function test_an_order_must_be_at_least_two_ringgit()
  121. {
  122. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 199]));
  123. $this->placeOrder()->assertSessionHasErrors('cart');
  124. $this->assertSame(0, Order::count());
  125. }
  126. public function test_if_the_payment_page_cannot_be_opened_no_order_is_left_behind()
  127. {
  128. $this->gateway->failToStart = true;
  129. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 1500]));
  130. $this->placeOrder()->assertSessionHasErrors('cart');
  131. $this->assertSame(0, Order::count());
  132. $this->get(route('stores.preview.cart', $this->store->slug))
  133. ->assertInertia(fn (Assert $page) => $page->where('cart.count', 1));
  134. }
  135. public function test_a_paid_order_is_marked_lowers_stock_empties_the_cart_and_emails_the_shopper_once()
  136. {
  137. $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
  138. $this->addToCart($product, 3);
  139. $this->placeOrder();
  140. $order = Order::firstOrFail();
  141. $this->gateway->pay($order);
  142. $this->orderPage($order)
  143. ->assertOk()
  144. ->assertInertia(fn (Assert $page) => $page
  145. ->where('view.type', 'order')
  146. ->where('view.order.status', 'paid')
  147. ->where('view.order.number', 1001)
  148. ->where('view.order.total', 38.7)
  149. ->has('view.order.items', 1)
  150. ->where('cart.count', 0));
  151. $order->refresh();
  152. $this->assertTrue($order->isPaid());
  153. $this->assertNotNull($order->paid_at);
  154. $this->assertSame('pi_fake_1', $order->payment_reference);
  155. $this->assertSame(7, $product->fresh()->stock);
  156. Mail::assertSent(OrderConfirmation::class, fn (OrderConfirmation $mail) => $mail->hasTo('aminah@example.com')
  157. && $mail->order->is($order));
  158. // Opening the page again must not take stock or send the email a second time.
  159. $this->orderPage($order)->assertOk();
  160. $this->assertSame(7, $product->fresh()->stock);
  161. Mail::assertSent(OrderConfirmation::class, 1);
  162. }
  163. public function test_an_unpaid_order_stays_pending_and_the_cart_is_kept()
  164. {
  165. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  166. $this->addToCart($product, 2);
  167. $this->placeOrder();
  168. $order = Order::firstOrFail();
  169. $this->orderPage($order)
  170. ->assertInertia(fn (Assert $page) => $page
  171. ->where('view.order.status', 'pending')
  172. ->where('cart.count', 2));
  173. $this->assertFalse($order->fresh()->isPaid());
  174. $this->assertSame(10, $product->fresh()->stock);
  175. Mail::assertNothingSent();
  176. }
  177. public function test_a_payment_of_the_wrong_amount_does_not_mark_the_order_paid()
  178. {
  179. $this->addToCart(Product::factory()->for($this->store)->create(['price' => 5000, 'stock' => 5]));
  180. $this->placeOrder();
  181. $order = Order::firstOrFail();
  182. $this->gateway->pay($order, amount: 500);
  183. $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
  184. Mail::assertNothingSent();
  185. }
  186. public function test_an_order_keeps_its_own_record_when_products_change_later()
  187. {
  188. $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 10]);
  189. $this->addToCart($product, 2);
  190. $this->placeOrder();
  191. $order = Order::firstOrFail();
  192. $product->update(['name' => 'Renamed', 'price' => 9900]);
  193. $product->delete();
  194. $item = $order->items()->firstOrFail();
  195. $this->assertNull($item->product_id);
  196. $this->assertSame(['Sambal', 1290, 2580], [$item->name, $item->unit_price, $item->line_total]);
  197. $this->assertSame(2580, $order->fresh()->total);
  198. // Paying for it still works, even though the product is gone.
  199. $this->gateway->pay($order);
  200. $this->orderPage($order)->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid'));
  201. }
  202. public function test_stock_never_goes_below_zero()
  203. {
  204. $product = Product::factory()->for($this->store)->create(['price' => 1000, 'stock' => 5]);
  205. $this->addToCart($product, 4);
  206. $this->placeOrder();
  207. $order = Order::firstOrFail();
  208. // The merchant sold some elsewhere while the shopper was paying.
  209. $product->update(['stock' => 1]);
  210. $this->gateway->pay($order);
  211. $this->orderPage($order);
  212. $this->assertSame(0, $product->fresh()->stock);
  213. }
  214. public function test_the_webhook_marks_an_order_paid_without_the_shopper_coming_back()
  215. {
  216. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  217. $this->addToCart($product, 1);
  218. $this->placeOrder();
  219. $order = Order::firstOrFail();
  220. $this->gateway->pay($order);
  221. auth()->logout();
  222. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'forged'])->assertStatus(400);
  223. $this->assertFalse($order->fresh()->isPaid());
  224. $this->postJson(route('stripe.webhook'), ['other' => 'event'], ['Stripe-Signature' => 'valid'])->assertOk();
  225. $this->assertFalse($order->fresh()->isPaid());
  226. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
  227. $this->postJson(route('stripe.webhook'), ['checkout_id' => 'cs_fake_1'], ['Stripe-Signature' => 'valid'])->assertOk();
  228. $this->assertTrue($order->fresh()->isPaid());
  229. $this->assertSame(9, $product->fresh()->stock);
  230. Mail::assertSent(OrderConfirmation::class, 1);
  231. }
  232. public function test_the_real_stripe_gateway_only_accepts_messages_signed_with_our_secret()
  233. {
  234. config(['services.stripe.webhook_secret' => 'whsec_test_secret']);
  235. $payload = (string) json_encode([
  236. 'id' => 'evt_1',
  237. 'object' => 'event',
  238. 'type' => 'checkout.session.completed',
  239. 'data' => ['object' => [
  240. 'id' => 'cs_test_123',
  241. 'object' => 'checkout.session',
  242. 'payment_status' => 'paid',
  243. 'payment_intent' => 'pi_123',
  244. 'amount_total' => 2580,
  245. ]],
  246. ]);
  247. $time = time();
  248. $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
  249. $status = (new StripeGateway)->readWebhook($payload, $sign('whsec_test_secret'));
  250. $this->assertSame('cs_test_123', $status->checkoutId);
  251. $this->assertTrue($status->paid);
  252. $this->assertSame('pi_123', $status->reference);
  253. $this->assertSame(2580, $status->amount);
  254. $this->expectException(PaymentException::class);
  255. (new StripeGateway)->readWebhook($payload, $sign('whsec_someone_else'));
  256. }
  257. public function test_the_confirmation_email_lists_the_order_in_the_store_language()
  258. {
  259. $order = Order::factory()->for($this->store)->paid()->create(['number' => 1007, 'total' => 2580]);
  260. $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
  261. $mail = new OrderConfirmation($order);
  262. $mail->assertHasSubject('Order #1007 confirmed - Kedai Ali');
  263. $mail->assertSeeInHtml('Sambal Hijau');
  264. $mail->assertSeeInHtml('RM 25.80');
  265. $mail->assertSeeInHtml('12 Jalan Mawar');
  266. $this->store->update(['language' => 'ms']);
  267. (new OrderConfirmation($order->fresh()))->assertHasSubject('Pesanan #1007 disahkan - Kedai Ali');
  268. }
  269. public function test_the_merchant_sees_the_stores_orders()
  270. {
  271. $paid = Order::factory()->for($this->store)->paid()->create(['number' => 1001, 'total' => 5000]);
  272. Order::factory()->for($this->store)->create(['number' => 1002]);
  273. Order::factory()->create();
  274. $this->get(route('stores.orders.index', $this->store->slug))
  275. ->assertOk()
  276. ->assertInertia(fn (Assert $page) => $page
  277. ->component('stores/orders/index')
  278. ->has('orders', 2)
  279. ->where('orders.0.number', 1002)
  280. ->where('orders.0.status', 'pending')
  281. ->where('orders.1.status', 'paid')
  282. ->where('orders.1.total', 50));
  283. $this->get(route('stores.orders.show', [$this->store->slug, $paid->id]))
  284. ->assertOk()
  285. ->assertInertia(fn (Assert $page) => $page
  286. ->component('stores/orders/show')
  287. ->where('order.number', 1001)
  288. ->where('order.customer_email', 'aminah@example.com'));
  289. }
  290. public function test_orders_of_another_store_cannot_be_seen()
  291. {
  292. $theirs = Store::factory()->create();
  293. $theirs->plan = SamplePlan::for($theirs);
  294. $theirs->save();
  295. $order = Order::factory()->for($theirs)->paid()->create();
  296. $this->get(route('stores.orders.index', $theirs->slug))->assertNotFound();
  297. $this->get(route('stores.orders.show', [$theirs->slug, $order->id]))->assertNotFound();
  298. // Their order id inside my own store's address must not work either.
  299. $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))->assertNotFound();
  300. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))->assertNotFound();
  301. $this->get(route('stores.preview.checkout', $theirs->slug))->assertNotFound();
  302. $this->post(route('stores.preview.checkout.store', $theirs->slug), $this->details())->assertNotFound();
  303. }
  304. }