AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

StoreSettingsController.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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, 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. 'easyparcel' => [
  66. // False until the app's own EasyParcel keys are in .env.local.
  67. 'available' => $easyparcel->isConfigured(),
  68. 'connected' => $account !== null,
  69. 'account_name' => $account?->account_name,
  70. 'redirect_uri' => $easyparcel->redirectUri(),
  71. ],
  72. // Asked from EasyParcel after the page shows, so a slow answer never holds up Settings.
  73. 'easyparcelBalance' => $account !== null ? Inertia::defer(fn () => self::balance($easyparcel, $account)) : null,
  74. // What the store adds by itself today, so the merchant sees the whole bar.
  75. 'automaticAnnouncements' => Announcements::automatic($store, $store->automaticDiscounts()->where('active', true)->orderByDesc('value')->get()->filter->isLive()->values()),
  76. ]);
  77. }
  78. public function update(Request $request, string $slug): RedirectResponse
  79. {
  80. $store = $this->ownedStore($request, $slug);
  81. $validated = $request->validate([
  82. 'whatsapp_number' => ['nullable', 'string', 'max:30'],
  83. 'contact_email' => ['nullable', 'email', 'max:160'],
  84. 'shipping_west' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
  85. 'shipping_east' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:9999.99'],
  86. 'free_shipping_over' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
  87. 'announcement_enabled' => ['boolean'],
  88. // One message per line.
  89. 'announcement_messages' => ['nullable', 'string', 'max:400'],
  90. // Where couriers collect parcels. All or nothing.
  91. 'pickup_name' => ['nullable', 'string', 'max:60'],
  92. 'pickup_phone' => ['nullable', 'string', 'max:30', 'required_with:pickup_line1'],
  93. 'pickup_line1' => ['nullable', 'string', 'max:100', 'required_with:pickup_name,pickup_phone,pickup_city,pickup_postcode'],
  94. 'pickup_line2' => ['nullable', 'string', 'max:100'],
  95. 'pickup_city' => ['nullable', 'string', 'max:60', 'required_with:pickup_line1'],
  96. 'pickup_postcode' => ['nullable', 'regex:/^\d{5}$/', 'required_with:pickup_line1'],
  97. 'pickup_state' => ['nullable', Rule::in(MalaysianStates::ALL), 'required_with:pickup_line1'],
  98. 'parcel_weight' => ['nullable', 'numeric', 'min:0.01', 'max:70'],
  99. 'parcel_length' => ['nullable', 'integer', 'min:1', 'max:200'],
  100. 'parcel_width' => ['nullable', 'integer', 'min:1', 'max:200'],
  101. 'parcel_height' => ['nullable', 'integer', 'min:1', 'max:200'],
  102. ], [
  103. 'pickup_postcode.regex' => __('Enter a 5-digit postcode.'),
  104. 'pickup_line1.required_with' => __('Enter the street address.'),
  105. 'pickup_phone.required_with' => __('Enter a phone number the courier can call.'),
  106. 'pickup_city.required_with' => __('Enter the town or city.'),
  107. 'pickup_postcode.required_with' => __('Enter the postcode.'),
  108. 'pickup_state.required_with' => __('Choose the state.'),
  109. ]);
  110. $pickup = null;
  111. if (filled($validated['pickup_line1'] ?? null)) {
  112. $phone = MalaysianPhone::normalize($validated['pickup_phone'] ?? null);
  113. if ($phone === null) {
  114. throw ValidationException::withMessages(['pickup_phone' => __('Enter a Malaysian phone number, such as 012-345 6789.')]);
  115. }
  116. $pickup = [
  117. 'name' => trim((string) ($validated['pickup_name'] ?? '')) ?: $store->name,
  118. 'phone' => $phone,
  119. 'line1' => trim($validated['pickup_line1']),
  120. 'line2' => filled($validated['pickup_line2'] ?? null) ? trim($validated['pickup_line2']) : null,
  121. 'city' => trim($validated['pickup_city']),
  122. 'postcode' => $validated['pickup_postcode'],
  123. 'state' => $validated['pickup_state'],
  124. ];
  125. }
  126. $messages = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($validated['announcement_messages'] ?? '')) ?: [])));
  127. if (count($messages) > Announcements::MAX_OWN) {
  128. throw ValidationException::withMessages(['announcement_messages' => __('Write at most :count messages, one per line.', ['count' => Announcements::MAX_OWN])]);
  129. }
  130. foreach ($messages as $message) {
  131. if (mb_strlen($message) > Announcements::MAX_LENGTH) {
  132. throw ValidationException::withMessages(['announcement_messages' => __('Keep each message to :count characters or fewer.', ['count' => Announcements::MAX_LENGTH])]);
  133. }
  134. }
  135. $whatsapp = null;
  136. if (filled($validated['whatsapp_number'] ?? null)) {
  137. $whatsapp = MalaysianPhone::normalize($validated['whatsapp_number']);
  138. if ($whatsapp === null) {
  139. throw ValidationException::withMessages([
  140. 'whatsapp_number' => __('Enter a Malaysian mobile number, such as 012-345 6789.'),
  141. ]);
  142. }
  143. }
  144. $store->whatsapp_number = $whatsapp;
  145. // Left as it was when the form does not send it.
  146. if (array_key_exists('contact_email', $validated)) {
  147. $store->contact_email = filled($validated['contact_email']) ? mb_strtolower(trim($validated['contact_email'])) : null;
  148. }
  149. $store->shipping_west = self::sen($validated['shipping_west']);
  150. $store->shipping_east = self::sen($validated['shipping_east']);
  151. $store->free_shipping_over = filled($validated['free_shipping_over'] ?? null) ? self::sen($validated['free_shipping_over']) : null;
  152. $store->announcement_enabled = (bool) ($validated['announcement_enabled'] ?? false);
  153. $store->announcement_messages = $messages === [] ? null : $messages;
  154. $store->pickup_address = $pickup;
  155. // The usual parcel. Left as it was when the form does not send it.
  156. if (filled($validated['parcel_weight'] ?? null)) {
  157. $store->parcel_weight = (int) round(((float) $validated['parcel_weight']) * 1000);
  158. }
  159. if (filled($validated['parcel_length'] ?? null) && filled($validated['parcel_width'] ?? null) && filled($validated['parcel_height'] ?? null)) {
  160. $store->parcel_size = [
  161. 'length' => (int) $validated['parcel_length'],
  162. 'width' => (int) $validated['parcel_width'],
  163. 'height' => (int) $validated['parcel_height'],
  164. ];
  165. }
  166. $store->save();
  167. Inertia::flash('toast', ['type' => 'success', 'message' => __('Settings saved.')]);
  168. return to_route('stores.settings', $store->slug);
  169. }
  170. /**
  171. * @return array{amount: float|null, error: string|null}
  172. */
  173. private static function balance(EasyParcel $easyparcel, EasyParcelAccount $account): array
  174. {
  175. try {
  176. $sen = $easyparcel->balance($account);
  177. return ['amount' => $sen !== null ? $sen / 100 : null, 'error' => null];
  178. } catch (EasyParcelException $e) {
  179. return ['amount' => null, 'error' => $e->getMessage()];
  180. }
  181. }
  182. private static function sen(mixed $ringgit): int
  183. {
  184. return (int) round(((float) $ringgit) * 100);
  185. }
  186. private static function ringgit(int $sen): string
  187. {
  188. return number_format($sen / 100, 2, '.', '');
  189. }
  190. private function ownedStore(Request $request, string $slug): Store
  191. {
  192. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  193. }
  194. }