| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- <?php
-
- namespace Tests\Feature\Malaysia;
-
- use App\Mail\OrderShipped;
- use App\Models\EasyParcelAccount;
- use App\Models\Order;
- use App\Models\Store;
- use App\Models\User;
- use Illuminate\Foundation\Testing\RefreshDatabase;
- use Illuminate\Http\Client\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Facades\Mail;
- use Illuminate\Testing\TestResponse;
- use Inertia\Testing\AssertableInertia as Assert;
- use Tests\TestCase;
-
- /**
- * Booking couriers through the merchant's own EasyParcel account. EasyParcel itself is pretend (Http::fake).
- */
- class EasyParcelTest extends TestCase
- {
- use RefreshDatabase;
-
- private const string API = 'https://api.easyparcel.com/open_api/2026-09/';
-
- private User $user;
-
- private Store $store;
-
- protected function setUp(): void
- {
- parent::setUp();
-
- Mail::fake();
- Http::preventStrayRequests();
- config(['services.easyparcel.client_id' => 'test-client', 'services.easyparcel.client_secret' => 'test-secret']);
-
- $this->user = User::factory()->create(['email' => 'owner@example.com']);
- $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
- $this->actingAs($this->user);
- }
-
- private function connectStore(array $tokens = []): EasyParcelAccount
- {
- return $this->store->easyparcel()->create([
- 'account_name' => 'Kedai Ali Sdn Bhd',
- 'access_token' => 'access-1',
- 'refresh_token' => 'refresh-1',
- 'expires_at' => now()->addHours(5),
- ...$tokens,
- ]);
- }
-
- private function addPickup(): void
- {
- $this->store->pickup_address = [
- 'name' => 'Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null,
- 'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang',
- ];
- $this->store->save();
- }
-
- private function paidOrder(): Order
- {
- $order = Order::factory()->paid()->for($this->store)->create(['number' => 1042, 'shipping_total' => 800]);
- $order->items()->create(['store_id' => $this->store->id, 'name' => 'Sambal Hijau 250g', 'unit_price' => 1290, 'quantity' => 2, 'line_total' => 2580]);
-
- return $order;
- }
-
- private static function quotation(string $serviceId, string $courier, float $price, array $extra = []): array
- {
- return [
- 'courier' => [
- 'service_id' => $serviceId, 'service_name' => "{$courier} (Pick Up)", 'courier_name' => $courier,
- 'courier_logo' => 'https://example.com/logo.png', 'delivery_duration' => '1-3 working days',
- 'is_pickup' => true, 'is_dropoff' => false, 'is_deliver_to_point' => false, ...$extra,
- ],
- 'pricing' => ['currency' => 'MYR', 'total_amount' => $price],
- ];
- }
-
- private function book(Order $order, array $overrides = []): TestResponse
- {
- return $this->post(route('stores.orders.book', [$this->store->slug, $order->id]), [
- 'service_id' => 'EP-CS0J1', 'courier' => 'J&T Express', 'weight' => '1.2', 'length' => '20', 'width' => '15', 'height' => '10',
- 'collection_date' => now('Asia/Kuala_Lumpur')->addDay()->toDateString(),
- ...$overrides,
- ]);
- }
-
- public function test_connecting_sends_the_merchant_to_easyparcel_and_saves_the_account_when_they_come_back()
- {
- Http::fake([
- 'api.easyparcel.com/oauth/token' => Http::response(['token_type' => 'Bearer', 'access_token' => 'access-new', 'refresh_token' => 'refresh-new', 'expires_in' => 36000]),
- self::API.'account/get_account_information' => Http::response(['status_code' => 200, 'data' => ['account' => ['name' => 'Kedai Ali Sdn Bhd']]]),
- ]);
-
- $response = $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
- $response->assertStatus(409);
- $location = $response->headers->get('X-Inertia-Location');
- $this->assertStringStartsWith('https://api.easyparcel.com/oauth/login?', $location);
- parse_str((string) parse_url($location, PHP_URL_QUERY), $query);
- $this->assertSame('test-client', $query['client_id']);
- $this->assertSame(route('easyparcel.callback'), $query['redirect_uri']);
- $this->assertSame('S256', $query['code_challenge_method']);
-
- $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $query['state']]))
- ->assertRedirect(route('stores.settings', $this->store->slug));
-
- $account = $this->store->fresh()->easyparcel;
- $this->assertSame('Kedai Ali Sdn Bhd', $account->account_name);
- $this->assertSame('access-new', $account->access_token);
- $this->assertSame('refresh-new', $account->refresh_token);
- // Tokens are kept encrypted in the database.
- $this->assertStringNotContainsString('access-new', (string) DB::table('easyparcel_accounts')->value('access_token'));
-
- Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token'
- && $request['grant_type'] === 'authorization_code'
- && $request['code'] === 'the-code'
- && $request->hasHeader('Authorization', 'Basic '.base64_encode('test-client:test-secret')));
- }
-
- public function test_a_callback_with_the_wrong_state_is_refused()
- {
- Http::fake();
- $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
-
- $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => 'not-the-one']))->assertRedirect(route('dashboard'));
-
- $this->assertNull($this->store->fresh()->easyparcel);
- Http::assertNothingSent();
- }
-
- public function test_another_merchant_cannot_use_the_callback_for_this_store()
- {
- Http::fake();
- $this->post(route('stores.easyparcel.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
- $state = session('easyparcel.connect.state');
-
- $this->actingAs(User::factory()->create());
- $this->get(route('easyparcel.callback', ['code' => 'the-code', 'state' => $state]))->assertRedirect(route('dashboard'));
-
- $this->assertNull($this->store->fresh()->easyparcel);
- }
-
- public function test_settings_save_the_pickup_address_and_show_the_connection()
- {
- $this->connectStore();
- Http::fake([self::API.'wallet' => Http::response(['status_code' => 200, 'data' => ['wallet' => [['balance' => 54.3, 'currency' => 'MYR']]]])]);
-
- $this->put(route('stores.settings.update', $this->store->slug), [
- 'shipping_west' => '8', 'shipping_east' => '15',
- 'pickup_phone' => '012-345 6789', 'pickup_line1' => '1 Jalan Bukit', 'pickup_city' => 'Bayan Lepas',
- 'pickup_postcode' => '11950', 'pickup_state' => 'Pulau Pinang',
- 'parcel_weight' => '0.5', 'parcel_length' => '25', 'parcel_width' => '18', 'parcel_height' => '8',
- ])->assertSessionHasNoErrors();
-
- $store = $this->store->fresh();
- $this->assertSame(['name' => 'Kedai Ali', 'phone' => '60123456789', 'line1' => '1 Jalan Bukit', 'line2' => null, 'city' => 'Bayan Lepas', 'postcode' => '11950', 'state' => 'Pulau Pinang'], $store->pickup_address);
- $this->assertSame(500, $store->parcel_weight);
- $this->assertSame(['length' => 25, 'width' => 18, 'height' => 8], $store->parcel_size);
-
- $this->get(route('stores.settings', $this->store->slug))
- ->assertInertia(fn (Assert $page) => $page
- ->where('easyparcel.connected', true)
- ->where('easyparcel.account_name', 'Kedai Ali Sdn Bhd')
- ->where('settings.pickup.postcode', '11950')
- ->missing('easyparcelBalance')
- ->loadDeferredProps(fn (Assert $reload) => $reload->where('easyparcelBalance.amount', 54.3)));
- }
-
- public function test_a_half_filled_pickup_address_is_refused()
- {
- $this->put(route('stores.settings.update', $this->store->slug), [
- 'shipping_west' => '8', 'shipping_east' => '15', 'pickup_line1' => '1 Jalan Bukit',
- ])->assertSessionHasErrors(['pickup_phone', 'pickup_city', 'pickup_postcode', 'pickup_state']);
- }
-
- public function test_the_merchant_sees_courier_prices_cheapest_first()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
- 'status' => 'success',
- 'quotations' => [
- 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"}']),
- self::quotation('EP-CS0J1', 'J&T Express', 6.8),
- self::quotation('EP-CS0PT', 'Collect at point', 4.0, ['is_deliver_to_point' => true]),
- ],
- ]]])]);
-
- $this->get(route('stores.orders.show', [$this->store->slug, $order->id]))
- ->assertOk()
- ->assertInertia(fn (Assert $page) => $page
- ->where('easyparcel.connected', true)
- ->where('easyparcel.has_pickup_address', true)
- ->missing('courier_quotes'));
-
- // "See courier prices" reloads only the prices, with the parcel the merchant typed.
- $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1.2', 'length' => 20, 'width' => 15, 'height' => 10]))
- ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
- ->has('courier_quotes', 2)
- ->where('courier_quotes.0.courier', 'J&T Express')
- ->where('courier_quotes.0.price', 6.8)
- ->where('courier_quotes.0.delivery', '1-3 working days')
- ->where('courier_quotes.1.courier', 'Poslaju')
- ->where('courier_quotes.1.delivery', 'About 3 days')
- ->where('courier_quotes.1.note', 'Pickup needs at least 3 parcels')));
-
- Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations')
- && $request->hasHeader('Authorization', 'Bearer access-1')
- && $request['shipment'][0]['sender'] === ['postcode' => '11950', 'subdivision_code' => 'MY-07', 'country' => 'MY']
- && $request['shipment'][0]['receiver'] === ['postcode' => '40000', 'subdivision_code' => 'MY-10', 'country' => 'MY']
- && $request['shipment'][0]['weight'] === 1.2);
- }
-
- public function test_booking_a_courier_saves_the_label_and_emails_the_shopper()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
- 'order_details' => ['order_number' => 'EI-2611-AAAAA'],
- 'shipments' => [[
- 'status' => 'success', 'shipment_number' => 'ES-2611-BBBBB', 'courier' => 'J&T Express',
- 'awb_number' => '630012345678', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-BBBBB',
- 'tracking_url' => 'https://app.easyparcel.com/tools/easytrack/details?awb=630012345678',
- 'pricing_breakdown' => ['total_paid_amount' => '6.80'],
- ]],
- ]]])]);
-
- $this->book($order)->assertRedirect(route('stores.orders.show', [$this->store->slug, $order->id]));
-
- $order->refresh();
- $this->assertSame('ES-2611-BBBBB', $order->shipment_number);
- $this->assertSame('EI-2611-AAAAA', $order->shipment_order_number);
- $this->assertSame(680, $order->shipment_cost);
- $this->assertSame('J&T Express', $order->shipping_courier);
- $this->assertSame('630012345678', $order->tracking_number);
- $this->assertSame('https://app.easyparcel.com/label/ES-2611-BBBBB', $order->label_url);
- $this->assertNotNull($order->shipped_at);
- Mail::assertSent(OrderShipped::class, fn (OrderShipped $mail) => $mail->hasTo('aminah@example.com'));
-
- Http::assertSent(function (Request $request) {
- $shipment = $request['shipment'][0];
-
- return $shipment['service_id'] === 'EP-CS0J1'
- && $shipment['sender']['phone_number'] === '123456789'
- && $shipment['sender']['subdivision_code'] === 'MY-07'
- && $shipment['sender']['email'] === 'owner@example.com'
- && $shipment['receiver']['name'] === 'Aminah binti Ali'
- && $shipment['receiver']['subdivision_code'] === 'MY-10'
- && $shipment['item'][0]['content'] === 'Sambal Hijau 250g'
- && $shipment['item'][0]['quantity'] === 2
- && $shipment['reference'] === 'Kedai Ali #1042';
- });
-
- // A second booking is refused.
- $this->book($order);
- Http::assertSentCount(1);
- }
-
- public function test_a_label_that_comes_later_is_fetched_and_the_shopper_emailed_then()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([
- self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'data' => [[
- 'shipments' => [['status' => 'success', 'shipment_number' => 'ES-2611-CCCCC', 'courier' => 'Aramex', 'awb_number' => null, 'awb_url' => '', 'tracking_url' => null]],
- ]]]),
- self::API.'shipment/details' => Http::response(['status_code' => 200, 'data' => [[
- 'shipment_details' => ['awb_number' => '7028021894', 'awb_url' => 'https://app.easyparcel.com/label/ES-2611-CCCCC', 'tracking_url' => 'https://app.easyparcel.com/track/7028021894'],
- ]]]),
- ]);
-
- $this->book($order);
- $order->refresh();
- $this->assertSame('ES-2611-CCCCC', $order->shipment_number);
- $this->assertNull($order->tracking_number);
- $this->assertNull($order->shipped_at);
- Mail::assertNothingSent();
-
- $this->post(route('stores.orders.label', [$this->store->slug, $order->id]))->assertSessionHasNoErrors();
-
- $order->refresh();
- $this->assertSame('7028021894', $order->tracking_number);
- $this->assertSame('https://app.easyparcel.com/label/ES-2611-CCCCC', $order->label_url);
- $this->assertNotNull($order->shipped_at);
- Mail::assertSent(OrderShipped::class, 1);
- }
-
- public function test_an_easyparcel_error_is_shown_and_nothing_is_saved()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
- 'status' => 'error', 'errors' => ['The receiver postcode field is required.'],
- ]]])]);
-
- $this->book($order)->assertSessionHasErrors(['booking' => 'EasyParcel: The receiver postcode field is required.']);
-
- $this->assertNull($order->fresh()->shipment_number);
- Mail::assertNothingSent();
- }
-
- public function test_the_price_shown_leaves_out_extras_we_do_not_book()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- // 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.
- Http::fake([self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [[
- 'status' => 'success',
- 'quotations' => [[
- '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],
- 'pricing' => ['total_amount' => 7.63, 'shipment_price' => 6.63, 'shipment_tax' => 0.4, 'total_features_price' => 0.57, 'total_features_tax' => 0.03],
- ]],
- ]]])]);
-
- $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
- ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload
- ->where('courier_quotes.0.courier', 'Pos MELPlus')
- ->where('courier_quotes.0.price', 7.03)));
- }
-
- public function test_not_enough_credit_says_how_much_the_parcel_needs()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- // The shape the EasyParcel sandbox really sends: the error list is wrapped in another list.
- Http::fake([self::API.'shipment/submit_orders' => Http::response(['status_code' => 200, 'message' => '0 requests success, 1 request error.', 'data' => [[
- 'order_details' => ['account_id' => '11043151'],
- 'shipments' => [[
- 'status' => 'error',
- 'errors' => [[['message' => 'Insufficient Credit Balance', 'code' => 'InsufficientCreditBalance', 'data' => ['current_balance' => 0, 'total_amount' => 7.03]]]],
- ]],
- ]]])]);
-
- $this->book($order)->assertSessionHasErrors(['booking' => 'Not enough EasyParcel credit: this parcel needs RM 7.03. Top up your EasyParcel account and try again.']);
- $this->assertNull($order->fresh()->shipment_number);
- }
-
- public function test_an_expired_token_is_renewed_and_the_call_tried_again()
- {
- $this->connectStore(['expires_at' => now()->subMinute()]);
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([
- 'api.easyparcel.com/oauth/token' => Http::response(['access_token' => 'access-2', 'expires_in' => 36000]),
- self::API.'shipment/quotations' => Http::response(['status_code' => 200, 'data' => [['status' => 'success', 'quotations' => []]]]),
- ]);
-
- $this->get(route('stores.orders.show', [$this->store->slug, $order->id, 'weight' => '1', 'length' => 20, 'width' => 15, 'height' => 10]))
- ->assertInertia(fn (Assert $page) => $page->reloadOnly('courier_quotes', fn (Assert $reload) => $reload->where('courier_quotes', [])));
-
- $account = $this->store->easyparcel()->first();
- $this->assertSame('access-2', $account->access_token);
- // EasyParcel sent no new refresh token, so the old one is kept.
- $this->assertSame('refresh-1', $account->refresh_token);
- Http::assertSent(fn (Request $request) => $request->url() === 'https://api.easyparcel.com/oauth/token' && $request['grant_type'] === 'refresh_token' && $request['refresh_token'] === 'refresh-1');
- Http::assertSent(fn (Request $request) => str_ends_with($request->url(), 'shipment/quotations') && $request->hasHeader('Authorization', 'Bearer access-2'));
- }
-
- public function test_a_revoked_connection_asks_the_merchant_to_connect_again()
- {
- $this->connectStore();
- $this->addPickup();
- $order = $this->paidOrder();
-
- Http::fake([
- 'api.easyparcel.com/oauth/token' => Http::response(['error' => 'invalid_grant'], 400),
- self::API.'*' => Http::response(['message' => 'Unauthorized'], 401),
- ]);
-
- $this->book($order)->assertSessionHasErrors(['booking' => 'Your EasyParcel connection has expired. Connect EasyParcel again in Settings.']);
- }
-
- public function test_unpaid_orders_and_other_merchants_cannot_book()
- {
- $this->connectStore();
- $this->addPickup();
- Http::fake();
-
- $unpaid = Order::factory()->for($this->store)->create();
- $this->book($unpaid)->assertNotFound();
-
- $order = $this->paidOrder();
- $this->actingAs(User::factory()->create());
- $this->book($order)->assertNotFound();
-
- Http::assertNothingSent();
- }
-
- public function test_disconnecting_removes_the_account()
- {
- $this->connectStore();
-
- $this->delete(route('stores.easyparcel.disconnect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
-
- $this->assertNull($this->store->fresh()->easyparcel);
- }
-
- public function test_without_the_app_keys_connecting_explains_instead()
- {
- config(['services.easyparcel.client_id' => null]);
-
- $this->post(route('stores.easyparcel.connect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
- $this->get(route('stores.settings', $this->store->slug))->assertInertia(fn (Assert $page) => $page->where('easyparcel.available', false));
- }
- }
|