AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

StoreSettingsController.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commerce\MalaysianStates;
  4. use App\Commerce\Payments\StripeConnect;
  5. use App\Commerce\Shipping\EasyParcel\EasyParcel;
  6. use App\Commerce\Shipping\EasyParcel\EasyParcelException;
  7. use App\Models\EasyParcelAccount;
  8. use App\Models\Store;
  9. use App\Storefront\Announcements;
  10. use App\Support\MalaysianPhone;
  11. use Illuminate\Http\RedirectResponse;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Validation\Rule;
  14. use Illuminate\Validation\ValidationException;
  15. use Inertia\Inertia;
  16. use Inertia\Response;
  17. /**
  18. * Store-wide settings that are not part of the design: getting paid (Stripe and HitPay), WhatsApp number, contact email, shipping fees, EasyParcel and the announcement bar.
  19. */
  20. class StoreSettingsController extends Controller
  21. {
  22. public function edit(Request $request, string $slug, EasyParcel $easyparcel, StripeConnect $stripe): Response
  23. {
  24. $store = $this->ownedStore($request, $slug);
  25. $payments = $stripe->current($store);
  26. $account = $store->easyparcel;
  27. $pickup = $store->pickup_address;
  28. $size = $store->parcel_size ?? OrderController::DEFAULT_SIZE;
  29. return Inertia::render('stores/settings', [
  30. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  31. 'settings' => [
  32. 'whatsapp_number' => $store->whatsapp_number,
  33. 'contact_email' => $store->contact_email,
  34. 'shipping_west' => self::ringgit($store->shipping_west),
  35. 'shipping_east' => self::ringgit($store->shipping_east),
  36. 'free_shipping_over' => $store->free_shipping_over !== null ? self::ringgit($store->free_shipping_over) : null,
  37. 'announcement_enabled' => $store->announcement_enabled,
  38. // One line per message, the way the form edits them.
  39. 'announcement_messages' => implode("\n", $store->announcement_messages ?? []),
  40. 'pickup' => [
  41. 'name' => $pickup['name'] ?? '',
  42. 'phone' => $pickup['phone'] ?? '',
  43. 'line1' => $pickup['line1'] ?? '',
  44. 'line2' => $pickup['line2'] ?? '',
  45. 'city' => $pickup['city'] ?? '',
  46. 'postcode' => $pickup['postcode'] ?? '',
  47. 'state' => $pickup['state'] ?? '',
  48. ],
  49. 'parcel_weight' => rtrim(rtrim(number_format($store->parcel_weight / 1000, 2, '.', ''), '0'), '.'),
  50. 'parcel_length' => (string) $size['length'],
  51. 'parcel_width' => (string) $size['width'],
  52. 'parcel_height' => (string) $size['height'],
  53. ],
  54. 'states' => MalaysianStates::ALL,
  55. // Suggested for the contact email, never used unless the merchant saves it.
  56. 'accountEmail' => $request->user()->email,
  57. // The merchant's own Stripe account, where shoppers' payments go.
  58. 'payments' => [
  59. 'available' => $stripe->isConfigured(),
  60. 'connected' => $payments !== null,
  61. 'details_submitted' => (bool) $payments?->details_submitted,
  62. 'can_take_payments' => (bool) $payments?->charges_enabled,
  63. 'payouts_enabled' => (bool) $payments?->payouts_enabled,
  64. ],
  65. // The merchant's own HitPay account, for DuitNow QR and e-wallets. The key itself is never sent to the page.
  66. 'hitpay' => [
  67. 'connected' => $store->hitpayAccount !== null,
  68. 'methods' => $store->hitpayAccount->methods ?? [],
  69. // Ticked methods HitPay refused when a shopper tried to pay: switched off in the merchant's HitPay account.
  70. 'refused' => $store->hitpayAccount->refused_methods ?? [],
  71. 'refused_at' => $store->hitpayAccount?->refused_at?->toIso8601String(),
  72. 'sandbox' => (bool) config('services.hitpay.sandbox'),
  73. ],
  74. 'easyparcel' => [
  75. // False until the app's own EasyParcel keys are in .env.local.
  76. 'available' => $easyparcel->isConfigured(),
  77. 'connected' => $account !== null,
  78. 'account_name' => $account?->account_name,
  79. 'redirect_uri' => $easyparcel->redirectUri(),
  80. ],
  81. // Asked from EasyParcel after the page shows, so a slow answer never holds up Settings.
  82. 'easyparcelBalance' => $account !== null ? Inertia::defer(fn () => self::balance($easyparcel, $account)) : null,
  83. // What the store adds by itself today, so the merchant sees the whole bar.
  84. 'automaticAnnouncements' => Announcements::automatic($store, $store->automaticDiscounts()->where('active', true)->orderByDesc('value')->get()->filter->isLive()->values()),
  85. ]);
  86. }
  87. public function update(Request $request, string $slug): RedirectResponse
  88. {
  89. $store = $this->ownedStore($request, $slug);
  90. $validated = $request->validate([
  91. 'whatsapp_number' => ['nullable', 'string', 'max:30'],
  92. 'contact_email' => ['nullable', 'email', 'max:160'],
  93. 'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
  94. 'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
  95. 'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  96. 'announcement_enabled' => ['boolean'],
  97. // One message per line.
  98. 'announcement_messages' => ['nullable', 'string', 'max:400'],
  99. // Where couriers collect parcels. All or nothing.
  100. 'pickup_name' => ['nullable', 'string', 'max:60'],
  101. 'pickup_phone' => ['nullable', 'string', 'max:30', 'required_with:pickup_line1'],
  102. 'pickup_line1' => ['nullable', 'string', 'max:100', 'required_with:pickup_name,pickup_phone,pickup_city,pickup_postcode'],
  103. 'pickup_line2' => ['nullable', 'string', 'max:100'],
  104. 'pickup_city' => ['nullable', 'string', 'max:60', 'required_with:pickup_line1'],
  105. 'pickup_postcode' => ['nullable', 'regex:/^\d{5}$/', 'required_with:pickup_line1'],
  106. 'pickup_state' => ['nullable', Rule::in(MalaysianStates::ALL), 'required_with:pickup_line1'],
  107. 'parcel_weight' => ['nullable', 'numeric', 'min:0.01', 'max:70'],
  108. 'parcel_length' => ['nullable', 'integer', 'min:1', 'max:200'],
  109. 'parcel_width' => ['nullable', 'integer', 'min:1', 'max:200'],
  110. 'parcel_height' => ['nullable', 'integer', 'min:1', 'max:200'],
  111. ], [
  112. 'pickup_postcode.regex' => __('Enter a 5-digit postcode.'),
  113. 'pickup_line1.required_with' => __('Enter the street address.'),
  114. 'pickup_phone.required_with' => __('Enter a phone number the courier can call.'),
  115. 'pickup_city.required_with' => __('Enter the town or city.'),
  116. 'pickup_postcode.required_with' => __('Enter the postcode.'),
  117. 'pickup_state.required_with' => __('Choose the state.'),
  118. ]);
  119. $pickup = null;
  120. if (filled($validated['pickup_line1'] ?? null)) {
  121. $phone = MalaysianPhone::normalize($validated['pickup_phone'] ?? null);
  122. if ($phone === null) {
  123. throw ValidationException::withMessages(['pickup_phone' => __('Enter a Malaysian phone number, such as 012-345 6789.')]);
  124. }
  125. $pickup = [
  126. 'name' => trim((string) ($validated['pickup_name'] ?? '')) ?: $store->name,
  127. 'phone' => $phone,
  128. 'line1' => trim($validated['pickup_line1']),
  129. 'line2' => filled($validated['pickup_line2'] ?? null) ? trim($validated['pickup_line2']) : null,
  130. 'city' => trim($validated['pickup_city']),
  131. 'postcode' => $validated['pickup_postcode'],
  132. 'state' => $validated['pickup_state'],
  133. ];
  134. }
  135. $messages = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($validated['announcement_messages'] ?? '')) ?: [])));
  136. if (count($messages) > Announcements::MAX_OWN) {
  137. throw ValidationException::withMessages(['announcement_messages' => __('Write at most :count messages, one per line.', ['count' => Announcements::MAX_OWN])]);
  138. }
  139. foreach ($messages as $message) {
  140. if (mb_strlen($message) > Announcements::MAX_LENGTH) {
  141. throw ValidationException::withMessages(['announcement_messages' => __('Keep each message to :count characters or fewer.', ['count' => Announcements::MAX_LENGTH])]);
  142. }
  143. }
  144. $whatsapp = null;
  145. if (filled($validated['whatsapp_number'] ?? null)) {
  146. $whatsapp = MalaysianPhone::normalize($validated['whatsapp_number']);
  147. if ($whatsapp === null) {
  148. throw ValidationException::withMessages([
  149. 'whatsapp_number' => __('Enter a Malaysian mobile number, such as 012-345 6789.'),
  150. ]);
  151. }
  152. }
  153. $store->whatsapp_number = $whatsapp;
  154. // Left as it was when the form does not send it.
  155. if (array_key_exists('contact_email', $validated)) {
  156. $store->contact_email = filled($validated['contact_email']) ? mb_strtolower(trim($validated['contact_email'])) : null;
  157. }
  158. $store->shipping_west = self::sen($validated['shipping_west']);
  159. $store->shipping_east = self::sen($validated['shipping_east']);
  160. $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
  161. $store->announcement_enabled = (bool) ($validated['announcement_enabled'] ?? false);
  162. $store->announcement_messages = $messages === [] ? null : $messages;
  163. $store->pickup_address = $pickup;
  164. // The usual parcel. Left as it was when the form does not send it.
  165. if (filled($validated['parcel_weight'] ?? null)) {
  166. $store->parcel_weight = (int) round(((float) $validated['parcel_weight']) * 1000);
  167. }
  168. if (filled($validated['parcel_length'] ?? null) && filled($validated['parcel_width'] ?? null) && filled($validated['parcel_height'] ?? null)) {
  169. $store->parcel_size = [
  170. 'length' => (int) $validated['parcel_length'],
  171. 'width' => (int) $validated['parcel_width'],
  172. 'height' => (int) $validated['parcel_height'],
  173. ];
  174. }
  175. $store->save();
  176. Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
  177. return to_route('stores.settings', $store->slug);
  178. }
  179. /**
  180. * @return array{amount: float|null, error: string|null}
  181. */
  182. private static function balance(EasyParcel $easyparcel, EasyParcelAccount $account): array
  183. {
  184. try {
  185. $sen = $easyparcel->balance($account);
  186. return ['amount' => $sen !== null ? $sen / 100 : null, 'error' => null];
  187. } catch (EasyParcelException $e) {
  188. return ['amount' => null, 'error' => $e->getMessage()];
  189. }
  190. }
  191. private static function sen(mixed $ringgit): int
  192. {
  193. return (int) round(((float) $ringgit) * 100);
  194. }
  195. private static function ringgit(int $sen): string
  196. {
  197. return number_format($sen / 100, 2, '.', '');
  198. }
  199. private function ownedStore(Request $request, string $slug): Store
  200. {
  201. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  202. }
  203. }