| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222 |
- <?php
-
- namespace App\Http\Controllers;
-
- use App\Commerce\MalaysianStates;
- use App\Commerce\Payments\StripeConnect;
- use App\Commerce\Shipping\EasyParcel\EasyParcel;
- use App\Commerce\Shipping\EasyParcel\EasyParcelException;
- use App\Models\EasyParcelAccount;
- use App\Models\Store;
- use App\Storefront\Announcements;
- use App\Support\MalaysianPhone;
- use Illuminate\Http\RedirectResponse;
- use Illuminate\Http\Request;
- use Illuminate\Validation\Rule;
- use Illuminate\Validation\ValidationException;
- use Inertia\Inertia;
- use Inertia\Response;
-
- /**
- * Store-wide settings that are not part of the design: getting paid, WhatsApp number, contact email, shipping fees, EasyParcel and the announcement bar.
- */
- class StoreSettingsController extends Controller
- {
- public function edit(Request $request, string $slug, EasyParcel $easyparcel, StripeConnect $stripe): Response
- {
- $store = $this->ownedStore($request, $slug);
- $payments = $stripe->current($store);
- $account = $store->easyparcel;
- $pickup = $store->pickup_address;
- $size = $store->parcel_size ?? OrderController::DEFAULT_SIZE;
-
- return Inertia::render('stores/settings', [
- 'store' => ['name' => $store->name, 'slug' => $store->slug],
- 'settings' => [
- 'whatsapp_number' => $store->whatsapp_number,
- 'contact_email' => $store->contact_email,
- 'shipping_west' => self::ringgit($store->shipping_west),
- 'shipping_east' => self::ringgit($store->shipping_east),
- 'free_shipping_over' => $store->free_shipping_over !== null ? self::ringgit($store->free_shipping_over) : null,
- 'announcement_enabled' => $store->announcement_enabled,
- // One line per message, the way the form edits them.
- 'announcement_messages' => implode("\n", $store->announcement_messages ?? []),
- 'pickup' => [
- 'name' => $pickup['name'] ?? '',
- 'phone' => $pickup['phone'] ?? '',
- 'line1' => $pickup['line1'] ?? '',
- 'line2' => $pickup['line2'] ?? '',
- 'city' => $pickup['city'] ?? '',
- 'postcode' => $pickup['postcode'] ?? '',
- 'state' => $pickup['state'] ?? '',
- ],
- 'parcel_weight' => rtrim(rtrim(number_format($store->parcel_weight / 1000, 2, '.', ''), '0'), '.'),
- 'parcel_length' => (string) $size['length'],
- 'parcel_width' => (string) $size['width'],
- 'parcel_height' => (string) $size['height'],
- ],
- 'states' => MalaysianStates::ALL,
- // Suggested for the contact email, never used unless the merchant saves it.
- 'accountEmail' => $request->user()->email,
- // The merchant's own Stripe account, where shoppers' payments go.
- 'payments' => [
- 'available' => $stripe->isConfigured(),
- 'connected' => $payments !== null,
- 'details_submitted' => (bool) $payments?->details_submitted,
- 'can_take_payments' => (bool) $payments?->charges_enabled,
- 'payouts_enabled' => (bool) $payments?->payouts_enabled,
- ],
- 'easyparcel' => [
- // False until the app's own EasyParcel keys are in .env.local.
- 'available' => $easyparcel->isConfigured(),
- 'connected' => $account !== null,
- 'account_name' => $account?->account_name,
- 'redirect_uri' => $easyparcel->redirectUri(),
- ],
- // Asked from EasyParcel after the page shows, so a slow answer never holds up Settings.
- 'easyparcelBalance' => $account !== null ? Inertia::defer(fn () => self::balance($easyparcel, $account)) : null,
- // What the store adds by itself today, so the merchant sees the whole bar.
- 'automaticAnnouncements' => Announcements::automatic($store, $store->automaticDiscounts()->where('active', true)->orderByDesc('value')->get()->filter->isLive()->values()),
- ]);
- }
-
- public function update(Request $request, string $slug): RedirectResponse
- {
- $store = $this->ownedStore($request, $slug);
-
- $validated = $request->validate([
- 'whatsapp_number' => ['nullable', 'string', 'max:30'],
- 'contact_email' => ['nullable', 'email', 'max:160'],
- 'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
- 'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
- 'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
- 'announcement_enabled' => ['boolean'],
- // One message per line.
- 'announcement_messages' => ['nullable', 'string', 'max:400'],
- // Where couriers collect parcels. All or nothing.
- 'pickup_name' => ['nullable', 'string', 'max:60'],
- 'pickup_phone' => ['nullable', 'string', 'max:30', 'required_with:pickup_line1'],
- 'pickup_line1' => ['nullable', 'string', 'max:100', 'required_with:pickup_name,pickup_phone,pickup_city,pickup_postcode'],
- 'pickup_line2' => ['nullable', 'string', 'max:100'],
- 'pickup_city' => ['nullable', 'string', 'max:60', 'required_with:pickup_line1'],
- 'pickup_postcode' => ['nullable', 'regex:/^\d{5}$/', 'required_with:pickup_line1'],
- 'pickup_state' => ['nullable', Rule::in(MalaysianStates::ALL), 'required_with:pickup_line1'],
- 'parcel_weight' => ['nullable', 'numeric', 'min:0.01', 'max:70'],
- 'parcel_length' => ['nullable', 'integer', 'min:1', 'max:200'],
- 'parcel_width' => ['nullable', 'integer', 'min:1', 'max:200'],
- 'parcel_height' => ['nullable', 'integer', 'min:1', 'max:200'],
- ], [
- 'pickup_postcode.regex' => __('Enter a 5-digit postcode.'),
- 'pickup_line1.required_with' => __('Enter the street address.'),
- 'pickup_phone.required_with' => __('Enter a phone number the courier can call.'),
- 'pickup_city.required_with' => __('Enter the town or city.'),
- 'pickup_postcode.required_with' => __('Enter the postcode.'),
- 'pickup_state.required_with' => __('Choose the state.'),
- ]);
-
- $pickup = null;
-
- if (filled($validated['pickup_line1'] ?? null)) {
- $phone = MalaysianPhone::normalize($validated['pickup_phone'] ?? null);
-
- if ($phone === null) {
- throw ValidationException::withMessages(['pickup_phone' => __('Enter a Malaysian phone number, such as 012-345 6789.')]);
- }
-
- $pickup = [
- 'name' => trim((string) ($validated['pickup_name'] ?? '')) ?: $store->name,
- 'phone' => $phone,
- 'line1' => trim($validated['pickup_line1']),
- 'line2' => filled($validated['pickup_line2'] ?? null) ? trim($validated['pickup_line2']) : null,
- 'city' => trim($validated['pickup_city']),
- 'postcode' => $validated['pickup_postcode'],
- 'state' => $validated['pickup_state'],
- ];
- }
-
- $messages = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($validated['announcement_messages'] ?? '')) ?: [])));
-
- if (count($messages) > Announcements::MAX_OWN) {
- throw ValidationException::withMessages(['announcement_messages' => __('Write at most :count messages, one per line.', ['count' => Announcements::MAX_OWN])]);
- }
-
- foreach ($messages as $message) {
- if (mb_strlen($message) > Announcements::MAX_LENGTH) {
- throw ValidationException::withMessages(['announcement_messages' => __('Keep each message to :count characters or fewer.', ['count' => Announcements::MAX_LENGTH])]);
- }
- }
-
- $whatsapp = null;
-
- if (filled($validated['whatsapp_number'] ?? null)) {
- $whatsapp = MalaysianPhone::normalize($validated['whatsapp_number']);
-
- if ($whatsapp === null) {
- throw ValidationException::withMessages([
- 'whatsapp_number' => __('Enter a Malaysian mobile number, such as 012-345 6789.'),
- ]);
- }
- }
-
- $store->whatsapp_number = $whatsapp;
-
- // Left as it was when the form does not send it.
- if (array_key_exists('contact_email', $validated)) {
- $store->contact_email = filled($validated['contact_email']) ? mb_strtolower(trim($validated['contact_email'])) : null;
- }
-
- $store->shipping_west = self::sen($validated['shipping_west']);
- $store->shipping_east = self::sen($validated['shipping_east']);
- $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
- $store->announcement_enabled = (bool) ($validated['announcement_enabled'] ?? false);
- $store->announcement_messages = $messages === [] ? null : $messages;
- $store->pickup_address = $pickup;
-
- // The usual parcel. Left as it was when the form does not send it.
- if (filled($validated['parcel_weight'] ?? null)) {
- $store->parcel_weight = (int) round(((float) $validated['parcel_weight']) * 1000);
- }
-
- if (filled($validated['parcel_length'] ?? null) && filled($validated['parcel_width'] ?? null) && filled($validated['parcel_height'] ?? null)) {
- $store->parcel_size = [
- 'length' => (int) $validated['parcel_length'],
- 'width' => (int) $validated['parcel_width'],
- 'height' => (int) $validated['parcel_height'],
- ];
- }
- $store->save();
-
- Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
-
- return to_route('stores.settings', $store->slug);
- }
-
- /**
- * @return array{amount: float|null, error: string|null}
- */
- private static function balance(EasyParcel $easyparcel, EasyParcelAccount $account): array
- {
- try {
- $sen = $easyparcel->balance($account);
-
- return ['amount' => $sen !== null ? $sen / 100 : null, 'error' => null];
- } catch (EasyParcelException $e) {
- return ['amount' => null, 'error' => $e->getMessage()];
- }
- }
-
- private static function sen(mixed $ringgit): int
- {
- return (int) round(((float) $ringgit) * 100);
- }
-
- private static function ringgit(int $sen): string
- {
- return number_format($sen / 100, 2, '.', '');
- }
-
- private function ownedStore(Request $request, string $slug): Store
- {
- return $request->user()->stores()->where('slug', $slug)->firstOrFail();
- }
- }
|