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

OrderController.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commerce\Couriers;
  4. use App\Commerce\Shipping\EasyParcel\EasyParcel;
  5. use App\Commerce\Shipping\EasyParcel\EasyParcelException;
  6. use App\Commerce\Shipping\EasyParcel\Parcel;
  7. use App\Commerce\Shipping\EasyParcel\Quote;
  8. use App\Mail\OrderShipped;
  9. use App\Models\Order;
  10. use App\Models\Store;
  11. use App\Support\MalaysianPhone;
  12. use Carbon\CarbonInterface;
  13. use Illuminate\Http\RedirectResponse;
  14. use Illuminate\Http\Request;
  15. use Illuminate\Support\Facades\Mail;
  16. use Illuminate\Validation\Rule;
  17. use Inertia\Inertia;
  18. use Inertia\Response;
  19. /**
  20. * The merchant's view of a store's orders.
  21. */
  22. class OrderController extends Controller
  23. {
  24. public function index(Request $request, string $slug): Response
  25. {
  26. $store = $this->ownedStore($request, $slug);
  27. return Inertia::render('stores/orders/index', [
  28. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  29. 'orders' => $store->orders()
  30. ->with('items')
  31. ->latest('id')
  32. ->limit(200)
  33. ->get()
  34. ->map(fn (Order $order) => $order->toDisplay()),
  35. ]);
  36. }
  37. public function show(Request $request, string $slug, int $order, EasyParcel $easyparcel): Response
  38. {
  39. $store = $this->ownedStore($request, $slug);
  40. $order = $store->orders()->with('items')->whereKey($order)->firstOrFail();
  41. $customerWhatsapp = MalaysianPhone::normalize($order->customer_phone);
  42. $size = $store->parcel_size ?? self::DEFAULT_SIZE;
  43. return Inertia::render('stores/orders/show', [
  44. 'store' => ['name' => $store->name, 'slug' => $store->slug],
  45. 'order' => $order->toDisplay(),
  46. 'couriers' => Couriers::ALL,
  47. // Booking a courier through the merchant's EasyParcel account.
  48. 'easyparcel' => [
  49. 'connected' => $store->easyparcel()->exists(),
  50. 'has_pickup_address' => $store->pickup_address !== null,
  51. 'parcel' => ['weight' => $store->parcel_weight / 1000, ...$size],
  52. 'collection_date' => self::firstCollectionDate()->toDateString(),
  53. ],
  54. // Asked for only when the merchant clicks "See courier prices", with the parcel they typed.
  55. 'courier_quotes' => Inertia::optional(fn () => $this->quotes($request, $store, $order, $easyparcel)),
  56. // A chat with the shopper, with a first message already typed in the store's language.
  57. 'customer_whatsapp_url' => $customerWhatsapp !== null
  58. ? MalaysianPhone::whatsappLink($customerWhatsapp, $store->language->value === 'ms'
  59. ? "Hai {$order->customer_name}, terima kasih atas pesanan #{$order->number} daripada {$store->name}."
  60. : "Hi {$order->customer_name}, thank you for your order #{$order->number} from {$store->name}.")
  61. : null,
  62. ]);
  63. }
  64. /**
  65. * Record that a paid order was sent. The shopper is emailed the first time only;
  66. * later saves just correct the courier or tracking number.
  67. */
  68. public function ship(Request $request, string $slug, int $order): RedirectResponse
  69. {
  70. $store = $this->ownedStore($request, $slug);
  71. $order = $store->orders()->whereKey($order)->firstOrFail();
  72. abort_unless($order->isPaid(), 404);
  73. $validated = $request->validate([
  74. 'shipping_courier' => ['required', Rule::in(Couriers::ALL)],
  75. 'tracking_number' => ['nullable', 'string', 'max:80', 'regex:/^[A-Za-z0-9\-\s]+$/'],
  76. ], [
  77. 'tracking_number.regex' => __('Use only letters, numbers, spaces and dashes.'),
  78. ]);
  79. $firstTime = $order->shipped_at === null;
  80. $order->shipping_courier = $validated['shipping_courier'];
  81. $order->tracking_number = filled($validated['tracking_number'] ?? null) ? trim($validated['tracking_number']) : null;
  82. $order->shipped_at ??= now();
  83. $order->save();
  84. if ($firstTime) {
  85. Mail::to($order->customer_email)->send(new OrderShipped($order));
  86. }
  87. Inertia::flash('toast', ['type' => 'success', 'message' => $firstTime
  88. ? __('Marked as shipped. We emailed the customer.')
  89. : __('Shipping details saved.')]);
  90. return to_route('stores.orders.show', [$store->slug, $order->id]);
  91. }
  92. /**
  93. * Book the chosen courier on the merchant's EasyParcel account, and print its label.
  94. * The shopper gets the "on its way" email once the courier's tracking number is known.
  95. */
  96. public function book(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse
  97. {
  98. $store = $this->ownedStore($request, $slug);
  99. $order = $store->orders()->whereKey($order)->firstOrFail();
  100. abort_unless($order->isPaid(), 404);
  101. if ($order->shipment_number !== null) {
  102. Inertia::flash('toast', ['type' => 'error', 'message' => __('A courier is already booked for this order.')]);
  103. return to_route('stores.orders.show', [$store->slug, $order->id]);
  104. }
  105. $today = now(self::TIMEZONE)->startOfDay();
  106. $lastDay = $today->addDays(14);
  107. $validated = $request->validate([
  108. ...self::parcelRules(),
  109. 'service_id' => ['required', 'string', 'max:40'],
  110. 'courier' => ['nullable', 'string', 'max:60'],
  111. 'collection_date' => ['required', 'date_format:Y-m-d', 'after_or_equal:'.$today->toDateString(), 'before_or_equal:'.$lastDay->toDateString()],
  112. ], [
  113. 'collection_date.after_or_equal' => __('Choose today or a later day.'),
  114. 'collection_date.before_or_equal' => __('Choose a day within the next two weeks.'),
  115. ]);
  116. try {
  117. $easyparcel->book($store, $order, self::parcelFrom($validated), $validated['service_id'], $validated['collection_date'], $validated['courier'] ?? null);
  118. } catch (EasyParcelException $e) {
  119. return back()->withErrors(['booking' => $e->getMessage()]);
  120. }
  121. $emailed = $this->markShipped($order);
  122. Inertia::flash('toast', ['type' => 'success', 'message' => match (true) {
  123. $emailed => __('Courier booked. Print the label and stick it on the parcel. We emailed the customer.'),
  124. $order->tracking_number !== null => __('Courier booked. Print the label and stick it on the parcel.'),
  125. default => __('Courier booked. The label is being prepared; check again in a minute.'),
  126. }]);
  127. return to_route('stores.orders.show', [$store->slug, $order->id]);
  128. }
  129. /**
  130. * Some couriers give the label and tracking number a little after booking. Ask EasyParcel again.
  131. */
  132. public function refreshLabel(Request $request, string $slug, int $order, EasyParcel $easyparcel): RedirectResponse
  133. {
  134. $store = $this->ownedStore($request, $slug);
  135. $order = $store->orders()->whereKey($order)->whereNotNull('shipment_number')->firstOrFail();
  136. try {
  137. $easyparcel->refreshLabel($store, $order);
  138. } catch (EasyParcelException $e) {
  139. return back()->withErrors(['booking' => $e->getMessage()]);
  140. }
  141. $emailed = $this->markShipped($order);
  142. Inertia::flash('toast', $order->label_url !== null
  143. ? ['type' => 'success', 'message' => $emailed ? __('The label is ready. We emailed the customer.') : __('The label is ready.')]
  144. : ['type' => 'info', 'message' => __('The label is not ready yet. Try again in a minute.')]);
  145. return to_route('stores.orders.show', [$store->slug, $order->id]);
  146. }
  147. /** A box most small parcels fit, in cm, when the merchant has not set their own. */
  148. public const array DEFAULT_SIZE = ['length' => 20, 'width' => 15, 'height' => 10];
  149. private const string TIMEZONE = 'Asia/Kuala_Lumpur';
  150. /**
  151. * @return list<array<string, mixed>>|array{error: string}
  152. */
  153. private function quotes(Request $request, Store $store, Order $order, EasyParcel $easyparcel): array
  154. {
  155. $validator = validator($request->query(), self::parcelRules());
  156. if ($validator->fails()) {
  157. return ['error' => (string) $validator->errors()->first()];
  158. }
  159. try {
  160. return array_map(fn (Quote $quote) => $quote->toArray(), $easyparcel->quotes($store, $order, self::parcelFrom($validator->validated())));
  161. } catch (EasyParcelException $e) {
  162. return ['error' => $e->getMessage()];
  163. }
  164. }
  165. /**
  166. * @return array<string, list<string>>
  167. */
  168. private static function parcelRules(): array
  169. {
  170. return [
  171. 'weight' => ['required', 'numeric', 'min:0.01', 'max:70'],
  172. 'length' => ['required', 'integer', 'min:1', 'max:200'],
  173. 'width' => ['required', 'integer', 'min:1', 'max:200'],
  174. 'height' => ['required', 'integer', 'min:1', 'max:200'],
  175. ];
  176. }
  177. /**
  178. * @param array<string, mixed> $input
  179. */
  180. private static function parcelFrom(array $input): Parcel
  181. {
  182. return new Parcel((int) round(((float) $input['weight']) * 1000), (int) $input['length'], (int) $input['width'], (int) $input['height']);
  183. }
  184. /**
  185. * Couriers collect on working days, and same-day collection is only booked before noon.
  186. */
  187. private static function firstCollectionDate(): CarbonInterface
  188. {
  189. $now = now(self::TIMEZONE);
  190. $day = ($now->hour < 12 ? $now : $now->addDay())->startOfDay();
  191. return $day->isSunday() ? $day->addDay() : $day;
  192. }
  193. /**
  194. * Once a booked parcel has its tracking number, the order counts as shipped and the shopper is emailed once.
  195. */
  196. private function markShipped(Order $order): bool
  197. {
  198. if ($order->shipped_at !== null || $order->tracking_number === null) {
  199. return false;
  200. }
  201. $order->shipped_at = now();
  202. $order->save();
  203. Mail::to($order->customer_email)->send(new OrderShipped($order));
  204. return true;
  205. }
  206. private function ownedStore(Request $request, string $slug): Store
  207. {
  208. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  209. }
  210. }