AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace Tests\Feature\Malaysia;
  3. use App\Mail\OrderShipped;
  4. use App\Models\EasyParcelAccount;
  5. use App\Models\Order;
  6. use App\Models\Store;
  7. use App\Models\User;
  8. use Illuminate\Foundation\Testing\RefreshDatabase;
  9. use Illuminate\Http\Client\Request;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Http;
  12. use Illuminate\Support\Facades\Mail;
  13. use Illuminate\Testing\TestResponse;
  14. use Inertia\Testing\AssertableInertia as Assert;
  15. use Tests\TestCase;
  16. /**
  17. * Booking couriers through the merchant's own EasyParcel account. EasyParcel itself is pretend (Http::fake).
  18. */
  19. class EasyParcelTest extends TestCase
  20. {
  21. use RefreshDatabase;
  22. private const string API = 'https://api.easyparcel.com/open_api/2026-09/';
  23. private User $user;
  24. private Store $store;
  25. protected function setUp(): void
  26. {
  27. parent::setUp();
  28. Mail::fake();
  29. Http::preventStrayRequests();
  30. config(['services.easyparcel.client_id' => 'test-client', 'services.easyparcel.client_secret' => 'test-secret']);
  31. $this->user = User::factory()->create(['email' => 'owner@example.com']);
  32. $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
  33. $this->actingAs($this->user);
  34. }
  35. private function connectStore(array $tokens = []): EasyParcelAccount
  36. {
  37. return $this->store->easyparcel()->create([
  38. 'account_name' => 'Kedai Ali Sdn Bhd',
  39. 'access_token' => 'access-1',
  40. 'refresh_token' => 'refresh-1',
  41. 'expires_at' => now()->addHours(5),
  42. ...$tokens,
  43. ]);
  44. }
  45. private function addPickup(): void
  46. {
  47. $this->store->pickup_address = [
  48. 'name' => 'Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null,
  49. 'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang',
  50. ];
  51. $this->store->save();
  52. }
  53. private function paidOrder(): Order
  54. {
  55. $order = Order::factory()->paid()->for($this->store)->create(['number' => 1042, 'shipping_total' => 800]);
  56. $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau 250g', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
  57. return $order;
  58. }
  59. private static function quotation(string $serviceId, string $courier, float $price, array $extra = []): array
  60. {
  61. return [
  62. 'courier' => [
  63. 'service_id' => $serviceId, 'service_name' => "{$courier} (Pick Up)", 'courier_name' => $courier,
  64. 'courier_logo' => 'https://example.com/logo.png', 'delivery_duration' => '1-3 working days',
  65. 'is_pickup' => true, 'is_dropoff' => false, 'is_deliver_to_point' => false, ...$extra,
  66. ],
  67. 'pricing' => ['currency' => 'MYR', 'total_amount' => $price],
  68. ];
  69. }
  70. private function book(Order $order, array $overrides = []): TestResponse
  71. {
  72. return $this->post(route('stores.orders.book', [$this->store->slug, $order->id]), [
  73. 'service_id' => 'EP-CS0J1', 'courier' => 'J&T Express', 'weight' => '1.2', 'length' => '20', 'width' => '15', 'height' => '10',
  74. 'collection_date' => now('Asia/Kuala_Lumpur')->addDay()->toDateString(),
  75. ...$overrides,
  76. ]);
  77. }
  78. public function test_connecting_sends_the_merchant_to_easyparcel_and_saves_the_account_when_they_come_back()
  79. {
  80. Http::fake([
  81. 'api.easyparcel.com/oauth/token' => Http::response(['token_type' => 'Bearer', 'access_token' => 'access-new', 'refresh_token' => 'refresh-new', 'expires_in' => 36000]),
  82. self::API.'account/get_account_information' => Http::response(['status_code' => 200, 'data' => ['account' => ['name' => 'Kedai Ali Sdn Bhd']]]),
  83. ]);
  84. $response = $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
  85. $response->assertStatus(409);
  86. $location = $response->headers->get('X-Inertia-Location');
  87. $this->assertStringStartsWith('https://api.easyparcel.com/oauth/login?', $location);
  88. parse_str((string) parse_url($location, PHP_URL_QUERY), $query);
  89. $this->assertSame('test-client', $query['client_id']);
  90. $this->assertSame(route('easyparcel.callback'), $query['redirect_uri']);
  91. $this->assertSame('S256', $query['code_challenge_method']);
  92. $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $query['state']]))
  93. ->assertRedirect(route('stores.settings', $this->store->slug));
  94. $account = $this->store->fresh()->easyparcel;
  95. $this->assertSame('Kedai Ali Sdn Bhd', $account->account_name);
  96. $this->assertSame('access-new', $account->access_token);
  97. $this->assertSame('refresh-new', $account->refresh_token);
  98. // Tokens are kept encrypted in the database.
  99. $this->assertStringNotContainsString('access-new', (string) DB::table('easyparcel_accounts')->value('access_token'));
  100. Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token'
  101. && $request['grant_type'] === 'authorization_code'
  102. && $request['code'] === 'the-code'
  103. && $request->hasHeader('Authorization', 'Basic '.base64_encode('test-client:test-secret')));
  104. }
  105. public function test_a_callback_with_the_wrong_state_is_refused()
  106. {
  107. Http::fake();
  108. $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
  109. $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => 'not-the-one']))->assertRedirect(route('dashboard'));
  110. $this->assertNull($this->store->fresh()->easyparcel);
  111. Http::assertNothingSent();
  112. }
  113. public function test_another_merchant_cannot_use_the_callback_for_this_store()
  114. {
  115. Http::fake();
  116. $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
  117. $state = session('easyparcel.connect.state');
  118. $this->actingAs(User::factory()->create());
  119. $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $state]))->assertRedirect(route('dashboard'));
  120. $this->assertNull($this->store->fresh()->easyparcel);
  121. }
  122. public function test_settings_save_the_pickup_address_and_show_the_connection()
  123. {
  124. $this->connectStore();
  125. Http::fake([self::API.'wallet' => Http::response(['status_code' => 200, 'data' => ['wallet' => [['balance' => 54.3, 'currency' => 'MYR']]]])]);
  126. $this->put(route('stores.settings.update', $this->store->slug), [
  127. 'shipping_west' => '8', 'shipping_east' => '15',
  128. 'pickup_phone' => '012-345 6789', 'pickup_line1' => '1 Jalan Bukit', 'pickup_city' => 'Bayan Lepas',
  129. 'pickup_postcode' => '11950', 'pickup_state' => 'Pulau Pinang',
  130. 'parcel_weight' => '0.5', 'parcel_length' => '25', 'parcel_width' => '18', 'parcel_height' => '8',
  131. ])->assertSessionHasNoErrors();
  132. $store = $this->store->fresh();
  133. $this->assertSame(['name' => 'Kedai Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null, 'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang'], $store->pickup_address);
  134. $this->assertSame(500, $store->parcel_weight);
  135. $this->assertSame(['length' => 25, 'width' => 18, 'height' => 8], $store->parcel_size);
  136. $this->get(route('stores.settings', $this->store->slug))
  137. ->assertInertia(fn (Assert $page) => $page
  138. ->where('easyparcel.connected', true)
  139. ->where('easyparcel.account_name', 'Kedai Ali Sdn Bhd')
  140. ->where('settings.pickup.postcode', '11950')
  141. ->missing('easyparcelBalance')
  142. ->loadDeferredProps(fn (Assert $reload) => $reload->where('easyparcelBalance.amount', 54.3)));
  143. }
  144. public function test_a_half_filled_pickup_address_is_refused()
  145. {
  146. $this->put(route('stores.settings.update', $this->store->slug), [
  147. 'shipping_west' => '8', 'shipping_east' => '15', 'pickup_line1' => '1 Jalan Bukit',
  148. ])->assertSessionHasErrors(['pickup_phone', 'pickup_city', 'pickup_postcode', 'pickup_state']);
  149. }
  150. public function test_the_merchant_sees_courier_prices_cheapest_first()
  151. {
  152. $this->connectStore();
  153. $this->addPickup();
  154. $order = $this->paidOrder();
  155. Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
  156. 'status' => 'success',
  157. 'quotations' => [
  158. self::quotation('EP-CS0PL', 'Poslaju National Courier', 9.5, ['service_name' => 'Poslaju (Pick Up with min 3 parcel(s)) (From Door to Door)', 'delivery_duration' => '{"type":"days","value":"3"}']),
  159. self::quotation('EP-CS0J1', 'J&T Express', 6.8),
  160. self::quotation('EP-CS0PT', 'Collect at point', 4.0, ['is_deliver_to_point' => true]),
  161. ],
  162. ]]])]);
  163. $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
  164. ->assertOk()
  165. ->assertInertia(fn (Assert $page) => $page
  166. ->where('easyparcel.connected', true)
  167. ->where('easyparcel.has_pickup_address', true)
  168. ->missing('courier_quotes'));
  169. // "See courier prices" reloads only the prices, with the parcel the merchant typed.
  170. $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1.2', 'length' => 20, 'width' => 15, 'height' => 10]))
  171. ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
  172. ->has('courier_quotes', 2)
  173. ->where('courier_quotes.0.courier', 'J&T Express')
  174. ->where('courier_quotes.0.price', 6.8)
  175. ->where('courier_quotes.0.delivery', '1-3 working days')
  176. ->where('courier_quotes.1.courier', 'Poslaju')
  177. ->where('courier_quotes.1.delivery', 'About 3 days')
  178. ->where('courier_quotes.1.note', 'Pickup needs at least 3 parcels')));
  179. Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations')
  180. && $request->hasHeader('Authorization', 'Bearer access-1')
  181. && $request['shipment'][0]['sender'] === ['postcode' => '11950', 'subdivision_code' => 'MY-07', 'country' => 'MY']
  182. && $request['shipment'][0]['receiver'] === ['postcode' => '40000', 'subdivision_code' => 'MY-10', 'country' => 'MY']
  183. && $request['shipment'][0]['weight'] === 1.2);
  184. }
  185. public function test_booking_a_courier_saves_the_label_and_emails_the_shopper()
  186. {
  187. $this->connectStore();
  188. $this->addPickup();
  189. $order = $this->paidOrder();
  190. Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
  191. 'order_details' => ['order_number' => 'EI-2611-AAAAA'],
  192. 'shipments' => [[
  193. 'status' => 'success', 'shipment_number' => 'ES-2611-BBBBB', 'courier' => 'J&T Express',
  194. 'awb_number' => '630012345678', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-BBBBB',
  195. 'tracking_url' => 'https://app.easyparcel.com/tools/easytrack/details?awb=630012345678',
  196. 'pricing_breakdown' => ['total_paid_amount' => '6.80'],
  197. ]],
  198. ]]])]);
  199. $this->book($order)->assertRedirect(route('stores.orders.show', [$this->store->slug, $order->id]));
  200. $order->refresh();
  201. $this->assertSame('ES-2611-BBBBB', $order->shipment_number);
  202. $this->assertSame('EI-2611-AAAAA', $order->shipment_order_number);
  203. $this->assertSame(680, $order->shipment_cost);
  204. $this->assertSame('J&T Express', $order->shipping_courier);
  205. $this->assertSame('630012345678', $order->tracking_number);
  206. $this->assertSame('https://app.easyparcel.com/label/ES-2611-BBBBB', $order->label_url);
  207. $this->assertNotNull($order->shipped_at);
  208. Mail::assertSent(OrderShipped::class, fn (OrderShipped $mail) => $mail->hasTo('aminah@example.com'));
  209. Http::assertSent(function (Request $request) {
  210. $shipment = $request['shipment'][0];
  211. return $shipment['service_id'] === 'EP-CS0J1'
  212. && $shipment['sender']['phone_number'] === '123456789'
  213. && $shipment['sender']['subdivision_code'] === 'MY-07'
  214. && $shipment['sender']['email'] === 'owner@example.com'
  215. && $shipment['receiver']['name'] === 'Aminah binti Ali'
  216. && $shipment['receiver']['subdivision_code'] === 'MY-10'
  217. && $shipment['item'][0]['content'] === 'Sambal Hijau 250g'
  218. && $shipment['item'][0]['quantity'] === 2
  219. && $shipment['reference'] === 'Kedai Ali #1042';
  220. });
  221. // A second booking is refused.
  222. $this->book($order);
  223. Http::assertSentCount(1);
  224. }
  225. public function test_a_label_that_comes_later_is_fetched_and_the_shopper_emailed_then()
  226. {
  227. $this->connectStore();
  228. $this->addPickup();
  229. $order = $this->paidOrder();
  230. Http::fake([
  231. self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
  232. 'shipments' => [['status' => 'success', 'shipment_number' => 'ES-2611-CCCCC', 'courier' => 'Aramex', 'awb_number' => null, 'awb_url' => '', 'tracking_url' => null]],
  233. ]]]),
  234. self::API.'shipment/details' => Http::response(['status_code' => 200, 'data' => [[
  235. 'shipment_details' => ['awb_number' => '7028021894', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-CCCCC', 'tracking_url' => 'https://app.easyparcel.com/track/7028021894'],
  236. ]]]),
  237. ]);
  238. $this->book($order);
  239. $order->refresh();
  240. $this->assertSame('ES-2611-CCCCC', $order->shipment_number);
  241. $this->assertNull($order->tracking_number);
  242. $this->assertNull($order->shipped_at);
  243. Mail::assertNothingSent();
  244. $this->post(route('stores.orders.label', [$this->store->slug, $order->id]))->assertSessionHasNoErrors();
  245. $order->refresh();
  246. $this->assertSame('7028021894', $order->tracking_number);
  247. $this->assertSame('https://app.easyparcel.com/label/ES-2611-CCCCC', $order->label_url);
  248. $this->assertNotNull($order->shipped_at);
  249. Mail::assertSent(OrderShipped::class, 1);
  250. }
  251. public function test_an_easyparcel_error_is_shown_and_nothing_is_saved()
  252. {
  253. $this->connectStore();
  254. $this->addPickup();
  255. $order = $this->paidOrder();
  256. Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
  257. 'status' => 'error', 'errors' => ['The receiver postcode field is required.'],
  258. ]]])]);
  259. $this->book($order)->assertSessionHasErrors(['booking' => 'EasyParcel: The receiver postcode field is required.']);
  260. $this->assertNull($order->fresh()->shipment_number);
  261. Mail::assertNothingSent();
  262. }
  263. public function test_the_price_shown_leaves_out_extras_we_do_not_book()
  264. {
  265. $this->connectStore();
  266. $this->addPickup();
  267. $order = $this->paidOrder();
  268. // As the sandbox sent it for Pos MELPlus: RM 7.63 in total, of which RM 0.60 is tracking extras. Booking cost RM 7.03.
  269. Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
  270. 'status' => 'success',
  271. 'quotations' => [[
  272. 'courier' => ['service_id' => 'EP-CS09E', 'service_name' => 'Pos MELPlus (Pick Up) (From Door to Door)', 'courier_name' => 'Pos Malaysia Berhad (Melplus)', 'is_pickup' => true, 'is_dropoff' => false, 'is_deliver_to_point' => false, 'delivery_duration' => null],
  273. 'pricing' => ['total_amount' => 7.63, 'shipment_price' => 6.63, 'shipment_tax' => 0.4, 'total_features_price' => 0.57, 'total_features_tax' => 0.03],
  274. ]],
  275. ]]])]);
  276. $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
  277. ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
  278. ->where('courier_quotes.0.courier', 'Pos MELPlus')
  279. ->where('courier_quotes.0.price', 7.03)));
  280. }
  281. public function test_not_enough_credit_says_how_much_the_parcel_needs()
  282. {
  283. $this->connectStore();
  284. $this->addPickup();
  285. $order = $this->paidOrder();
  286. // The shape the EasyParcel sandbox really sends: the error list is wrapped in another list.
  287. Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
  288. 'order_details' => ['account_id' => '11043151'],
  289. 'shipments' => [[
  290. 'status' => 'error',
  291. 'errors' => [[['message' => 'Insufficient Credit Balance', 'code' => 'InsufficientCreditBalance', 'data' => ['current_balance' => 0, 'total_amount' => 7.03]]]],
  292. ]],
  293. ]]])]);
  294. $this->book($order)->assertSessionHasErrors(['booking' => 'Not enough EasyParcel credit: this parcel needs RM 7.03. Top up your EasyParcel account and try again.']);
  295. $this->assertNull($order->fresh()->shipment_number);
  296. }
  297. public function test_an_expired_token_is_renewed_and_the_call_tried_again()
  298. {
  299. $this->connectStore(['expires_at' => now()->subMinute()]);
  300. $this->addPickup();
  301. $order = $this->paidOrder();
  302. Http::fake([
  303. 'api.easyparcel.com/oauth/token' => Http::response(['access_token' => 'access-2', 'expires_in' => 36000]),
  304. self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [['status' => 'success', 'quotations' => []]]]),
  305. ]);
  306. $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
  307. ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload->where('courier_quotes', [])));
  308. $account = $this->store->easyparcel()->first();
  309. $this->assertSame('access-2', $account->access_token);
  310. // EasyParcel sent no new refresh token, so the old one is kept.
  311. $this->assertSame('refresh-1', $account->refresh_token);
  312. Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token' && $request['grant_type'] === 'refresh_token' && $request['refresh_token'] === 'refresh-1');
  313. Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations') && $request->hasHeader('Authorization', 'Bearer access-2'));
  314. }
  315. public function test_a_revoked_connection_asks_the_merchant_to_connect_again()
  316. {
  317. $this->connectStore();
  318. $this->addPickup();
  319. $order = $this->paidOrder();
  320. Http::fake([
  321. 'api.easyparcel.com/oauth/token' => Http::response(['error' => 'invalid_grant'], 400),
  322. self::API.'*' => Http::response(['message' => 'Unauthorized'], 401),
  323. ]);
  324. $this->book($order)->assertSessionHasErrors(['booking' => 'Your EasyParcel connection has expired. Connect EasyParcel again in Settings.']);
  325. }
  326. public function test_unpaid_orders_and_other_merchants_cannot_book()
  327. {
  328. $this->connectStore();
  329. $this->addPickup();
  330. Http::fake();
  331. $unpaid = Order::factory()->for($this->store)->create();
  332. $this->book($unpaid)->assertNotFound();
  333. $order = $this->paidOrder();
  334. $this->actingAs(User::factory()->create());
  335. $this->book($order)->assertNotFound();
  336. Http::assertNothingSent();
  337. }
  338. public function test_disconnecting_removes_the_account()
  339. {
  340. $this->connectStore();
  341. $this->delete(route('stores.easyparcel.disconnect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
  342. $this->assertNull($this->store->fresh()->easyparcel);
  343. }
  344. public function test_without_the_app_keys_connecting_explains_instead()
  345. {
  346. config(['services.easyparcel.client_id' => null]);
  347. $this->post(route('stores.easyparcel.connect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
  348. $this->get(route('stores.settings', $this->store->slug))->assertInertia(fn (Assert $page) => $page->where('easyparcel.available', false));
  349. }
  350. }