PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.7.1
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.7.1
1.7.1 1.7.0 1.6.6 1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 All 51 releases
← All changes | app/Http/Controllers/OrderController.php +282 -255 1.5.0 → 1.7.1 View file →
@@ -5,15 +5,11 @@
5 5
6 6 use FluentCart\Api\Resource\CustomerResource;
7 7 use FluentCart\Api\Resource\OrderResource;
8 8 use FluentCart\Api\StoreSettings;
9 -use FluentCart\App\Events\Order\OrderBulkAction;
10 -use FluentCart\App\Events\Subscription\SubscriptionActivated;
11 9 use FluentCart\App\Events\Order\OrderCreated;
12 10 use FluentCart\App\Events\Order\OrderDeleting;
13 11 use FluentCart\App\Events\Order\OrderDeleted;
14 -use FluentCart\App\Events\Order\OrderPaid;
15 -use FluentCart\App\Events\Order\OrderStatusUpdated;
16 12 use FluentCart\App\Events\Order\RenewalOrderDeleted;
17 13 use FluentCart\App\Helpers\CartHelper;
18 14 use FluentCart\App\Helpers\Helper;
19 15 use FluentCart\App\Helpers\OrderItemHelper;
@@ -40,12 +36,10 @@
40 36 use FluentCart\App\Models\OrderDownloadPermission;
41 37 use FluentCart\App\Models\Subscription;
42 38 use FluentCart\App\Models\SubscriptionMeta;
43 39 use FluentCart\App\Services\Filter\OrderFilter;
44 -use FluentCart\App\Modules\Subscriptions\Services\SubscriptionService;
45 40 use FluentCart\App\Services\Payments\PaymentHelper;
46 41 use FluentCart\App\Services\Reminders\ReminderService;
47 -use FluentCart\App\Services\DateTime\DateTime;
48 42 use FluentCart\App\Services\Payments\Refund;
49 43 use FluentCart\App\Services\URL;
50 44 use FluentCart\Framework\Http\Request\Request;
51 45 use FluentCart\Framework\Support\Arr;
@@ -80,14 +74,27 @@
80 74 public function store(OrderRequest $request)
81 75 {
82 76 $data = $request->getSafe($request->sanitize());
83 77 $type = 'payment';
84 - $hasSubscription = static::hasSubscription(Arr::get($data, 'order_items', []));
78 + $orderItems = Arr::get($data, 'order_items', []);
79 +
80 + $variationPaymentTypes = static::getVariationPaymentTypes($orderItems);
81 +
82 + foreach ($orderItems as $item) {
83 + $paymentTypeError = static::getPaymentTypeConflict($item, $variationPaymentTypes);
84 + if ($paymentTypeError) {
85 + return $this->sendError([
86 + 'message' => $paymentTypeError
87 + ], 400);
88 + }
89 + }
90 +
91 + $hasSubscription = static::hasSubscription($orderItems);
85 92 if ($hasSubscription) {
86 93 $type = 'subscription';
87 94 // right now we don't support subscription with manual order
88 - $isSubscriptionAllowedInManualOrder = apply_filters('fluent_cart/order/is_subscription_allowed_in_manual_order', false, [
89 - 'order_items' => Arr::get($data, 'order_items', [])
95 + $isSubscriptionAllowedInManualOrder = apply_filters('fluent_cart/order/is_subscription_allowed_in_manual_order', true, [
96 + 'order_items' => $orderItems
90 97 ]);
91 98
92 99 if (!$isSubscriptionAllowedInManualOrder) {
93 100 return $this->sendError([
@@ -115,20 +122,86 @@
115 122 'uuid' => $order->uuid
116 123 ]);
117 124 }
118 125
119 -
120 126 public static function hasSubscription($orderItems): bool
121 127 {
122 - // check order items for subscription, payment_type == subscription
123 128 foreach ($orderItems as $item) {
124 129 if (Arr::get($item, 'payment_type') == 'subscription' || Arr::get($item, 'other_info.payment_type') == 'subscription') {
125 130 return true;
126 131 }
127 132 }
133 +
128 134 return false;
129 135 }
130 136
137 + /**
138 + * The variation row decides whether a line is recurring, so every label the payload
139 + * carries has to agree with it. A recurring line must additionally be labelled in
140 + * other_info: that is the only copy AdminOrderProcessor reads, and the interval and
141 + * installment count travel beside it.
142 + *
143 + * @return string empty when the line is consistent, else the rejection message
144 + */
145 + protected static function getPaymentTypeConflict($item, $variationPaymentTypes): string
146 + {
147 + $variationId = (int)Arr::get($item, 'object_id', 0);
148 +
149 + if (!isset($variationPaymentTypes[$variationId])) {
150 + return '';
151 + }
152 +
153 + $isSubscriptionVariation = $variationPaymentTypes[$variationId] === 'subscription';
154 +
155 + foreach (['payment_type', 'other_info.payment_type'] as $labelKey) {
156 + $label = Arr::get($item, $labelKey);
157 + if (is_null($label) || $label === '') {
158 + continue;
159 + }
160 +
161 + if (($label === 'subscription') !== $isSubscriptionVariation) {
162 + return $isSubscriptionVariation
163 + ? __('Subscription product cannot be placed as a one time item.', 'fluent-cart')
164 + : __('One time product cannot be placed as a subscription item.', 'fluent-cart');
165 + }
166 + }
167 +
168 + if ($isSubscriptionVariation && Arr::get($item, 'other_info.payment_type') !== 'subscription') {
169 + return __('Subscription product must be placed as a subscription item.', 'fluent-cart');
170 + }
171 +
172 + return '';
173 + }
174 +
175 + /**
176 + * @return array variation id => stored payment_type, for the lines that resolve
177 + */
178 + protected static function getVariationPaymentTypes($orderItems): array
179 + {
180 + $variationIds = [];
181 + foreach ($orderItems as $item) {
182 + $variationId = (int)Arr::get($item, 'object_id', 0);
183 + if ($variationId > 0) {
184 + $variationIds[$variationId] = $variationId;
185 + }
186 + }
187 +
188 + if (!$variationIds) {
189 + return [];
190 + }
191 +
192 + $variations = ProductVariation::query()
193 + ->whereIn('id', $variationIds)
194 + ->get(['id', 'payment_type']);
195 +
196 + $paymentTypes = [];
197 + foreach ($variations as $variation) {
198 + $paymentTypes[(int)$variation->id] = $variation->payment_type;
199 + }
200 +
201 + return $paymentTypes;
202 + }
203 +
131 204 public function updateOrder(OrderRequest $request, $order_id)
132 205 {
133 206 $order = Order::query()->find($order_id);
134 207
@@ -138,9 +211,12 @@
138 211 ], 400);
139 212 }
140 213
141 214
142 - $requestData = $request->getSafe($request->sanitize());
215 + $requestData = array_intersect_key(
216 + $request->getSafe($request->sanitize()),
217 + $request->all()
218 + );
143 219
144 220 $totalPaid = Arr::get($request->all(), 'total_paid');
145 221 $updatedTotal = Arr::get($requestData, 'total_amount');
146 222
@@ -161,9 +237,9 @@
161 237 // if new shipping total is already adjusted in total amount, then no need to adjust again, right now not adjusted before
162 238 // ToDo: adjust changed shipping total in total amount prior to this
163 239 $shippingTotal = Arr::get($requestData, 'shipping_total', 0);
164 240 $oldShippingTotal = Arr::get($order, 'shipping_total', 0);
165 - if ($shippingTotal != $oldShippingTotal) {
241 + if (array_key_exists('shipping_total', $requestData) && $shippingTotal != $oldShippingTotal) {
166 242 $diff = $shippingTotal - $oldShippingTotal;
167 243 if ($diff < 0) {
168 244 $requestData['total_amount'] = $updatedTotal - abs($diff);
169 245 } else {
@@ -223,9 +299,9 @@
223 299 ])
224 300 ->first();
225 301
226 302 return $this->sendSuccess([
227 - 'message' => 'Address updated successfully',
303 + 'message' => __('Address updated successfully', 'fluent-cart'),
228 304 'order' => $freshOrder,
229 305 ]);
230 306 }
231 307
@@ -252,8 +328,14 @@
252 328
253 329 }
254 330
255 331 /**
332 + * Refund against an order transaction.
333 + *
334 + * `refund_info.amount` is in CENTS, matching every money value in a read response and
335 + * the stored column. So {"amount": 2500} refunds $25.00. roundCent() below only
336 + * normalizes float artifacts; it does not scale. See dev-docs/PRICING-AND-TAX.md §6.
337 + *
256 338 * @throws ValidationException
257 339 */
258 340 public function refundOrder(Request $request, $orderId)
259 341 {
@@ -264,11 +346,16 @@
264 346 'message' => __('Order can not be refunded.', 'fluent-cart')
265 347 ], 400);
266 348 }
267 349
268 - $refundInfo = $request->get('refund_info', []);
350 + $refundInfo = (array)$request->get('refund_info', []);
269 351
270 - $this->validate($refundInfo, [
352 + // $this->validate() reports failures only by exception, and outside a
353 + // REST_REQUEST context the framework swallows that exception (no
354 + // handle_exception listener) — execution would continue and crash on
355 + // $refundInfo['transaction_id'] below. Fail closed: run the validator
356 + // directly and return the per-field 422 payload in every context.
357 + $validator = $this->app->validator->make($refundInfo, [
271 358 'transaction_id' => 'required',
272 359 'amount' => 'required',
273 360 ], [
274 361 'transaction_id.required' => __('Transaction ID is required', 'fluent-cart'),
@@ -274,10 +361,14 @@
274 361 'transaction_id.required' => __('Transaction ID is required', 'fluent-cart'),
275 362 'amount.required' => __('Refund amount is required', 'fluent-cart'),
276 363 ]);
277 364
365 + if ($validator->validate()->fails()) {
366 + return $this->sendError($validator->errors(), 422);
367 + }
368 +
278 369 $transaction = OrderTransaction::query()->where('order_id', $orderId)->findOrFail($refundInfo['transaction_id']);
279 - $refundAmount = Helper::toCent($refundInfo['amount']);
370 + $refundAmount = Helper::roundCent($refundInfo['amount']);
280 371
281 372 // refund on our end
282 373 $result = (new Refund())->processRefund($transaction, $refundAmount, $refundInfo);
283 374
@@ -643,16 +734,57 @@
643 734
644 735 return $data;
645 736 }
646 737
738 + public function getTransactionDetails($orderId, $transactionId)
739 + {
740 + $orderId = (int)$orderId;
741 + $transactionId = (int)$transactionId;
742 +
743 + $belongsToOrder = OrderTransaction::query()
744 + ->where('id', $transactionId)
745 + ->where('order_id', $orderId)
746 + ->exists();
747 +
748 + if (!$belongsToOrder) {
749 + return $this->entityNotFoundError(
750 + __('Transaction not found', 'fluent-cart'),
751 + __('Back to orders', 'fluent-cart'),
752 + '/orders'
753 + );
754 + }
755 +
756 + $data = $this->getDetails($orderId);
757 +
758 + if (!is_array($data) || empty($data['order'])) {
759 + return $data;
760 + }
761 +
762 + // The path names one transaction, so the sibling rows on the same order
763 + // are not part of this response.
764 + $data['order']['transactions'] = array_values(array_filter(
765 + (array)Arr::get($data, 'order.transactions', []),
766 + function ($transaction) use ($transactionId) {
767 + return (int)Arr::get($transaction, 'id') === $transactionId;
768 + }
769 + ));
770 +
771 + return $data;
772 + }
773 +
647 774 public function createCustom(Request $request, OrderItemHelper $orderItemHelper, Order $order)
648 775 {
649 776 try {
650 - return $orderItemHelper->processCustom(
777 + $orderItem = $orderItemHelper->processCustom(
651 778 $request->product,
652 779 $order->id
653 780 );
654 781
782 + return $this->sendSuccess([
783 + 'message' => __('Custom item has been added to the order!', 'fluent-cart'),
784 + 'order_item' => $orderItem
785 + ]);
786 +
655 787 } catch (\Exception $e) {
656 788 return $this->sendError([
657 789 'message' => $e->getMessage()
658 790 ], 423);
@@ -697,97 +829,107 @@
697 829
698 830
699 831 public function markAsPaid(Request $request, Order $order)
700 832 {
701 - $dueAmount = intval($order->total_amount - $order->total_paid);
833 + $db = Order::query()->getConnection();
834 + $db->beginTransaction();
702 835
703 - if ($dueAmount <= 0) {
704 - return $this->sendError([
705 - 'message' => __('Order has already been paid', 'fluent-cart')
706 - ], 423);
707 - }
836 + try {
837 + $locked = Order::query()
838 + ->where('id', $order->id)
839 + ->lockForUpdate()
840 + ->first();
708 841
709 - if (Arr::get($order, 'status') === 'canceled') {
710 - return $this->sendError([
711 - 'message' => __('Unable to mark paid for canceled order', 'fluent-cart')
712 - ], 423);
713 - }
842 + if (!$locked) {
843 + $db->rollBack();
844 + return $this->sendError([
845 + 'message' => __('Order not found', 'fluent-cart')
846 + ], 404);
847 + }
714 848
715 - $transaction = $order->transactions->where('status', Status::TRANSACTION_PENDING)
716 - ->where('payment_method', 'offline_payment')
717 - ->first();
849 + $dueAmount = intval($locked->total_amount - $locked->total_paid);
718 850
719 - $newTransactionData = [
720 - 'total' => $dueAmount,
721 - 'status' => Status::TRANSACTION_SUCCEEDED,
722 - 'payment_method' => sanitize_text_field($request->payment_method),
723 - 'vendor_charge_id' => sanitize_text_field($request->vendor_charge_id),
724 - 'payment_mode' => sanitize_text_field($order->mode),
725 - 'payment_method_type' => sanitize_text_field($request->payment_method),
726 - 'order_type' => sanitize_text_field($order->type),
727 - 'transaction_type' => sanitize_text_field($request->transaction_type),
728 - 'currency' => sanitize_text_field($order->currency),
729 - ];
851 + if ($dueAmount <= 0) {
852 + $db->rollBack();
853 + return $this->sendError([
854 + 'message' => __('Order has already been paid', 'fluent-cart')
855 + ], 423);
856 + }
730 857
731 - if ($transaction) {
732 - $transaction->update($newTransactionData);
733 - } else {
734 - $transaction = OrderTransaction::query()->create(
735 - array_merge($newTransactionData, [
736 - 'order_id' => $order->id
737 - ])
738 - );
739 - }
858 + if ($locked->status === Status::ORDER_CANCELED) {
859 + $db->rollBack();
860 + return $this->sendError([
861 + 'message' => __('Unable to mark paid for canceled order', 'fluent-cart')
862 + ], 423);
863 + }
740 864
741 - $order->note = sanitize_text_field($request->get('mark_paid_note', ''));
865 + // Reuse an existing pending transaction without vendor_charge_id instead of
866 + // creating a new one. Queried fresh (not via the route-bound relation) so it
867 + // reflects the state under the lock.
868 + $transaction = OrderTransaction::query()
869 + ->where('order_id', $locked->id)
870 + ->where('status', Status::TRANSACTION_PENDING)
871 + ->where(function ($query) {
872 + $query->whereNull('vendor_charge_id')
873 + ->orWhere('vendor_charge_id', '');
874 + })
875 + ->orderBy('id', 'asc')
876 + ->lockForUpdate()
877 + ->first();
742 878
743 - $oldStatus = $order->status;
879 + $newTransactionData = [
880 + 'total' => $dueAmount,
881 + 'status' => Status::TRANSACTION_SUCCEEDED,
882 + 'payment_method' => sanitize_text_field($request->payment_method),
883 + 'vendor_charge_id' => sanitize_text_field($request->vendor_charge_id),
884 + 'payment_mode' => sanitize_text_field($locked->mode),
885 + 'payment_method_type' => sanitize_text_field($request->payment_method),
886 + 'order_type' => sanitize_text_field($locked->type),
887 + 'currency' => sanitize_text_field($locked->currency),
888 + ];
744 889
745 - if ($order->payment_status !== 'partially_refunded') {
746 - $order->payment_status = Status::PAYMENT_PAID;
747 - }
890 + if ($transaction) {
891 + // Don't include transaction_type in the update — the existing value is always 'charge'
892 + // and overwriting it with the request value would break syncSubscriptionStates bill_count.
893 + $transaction->update($newTransactionData);
894 + } else {
895 + $transaction = OrderTransaction::query()->create(
896 + array_merge($newTransactionData, [
897 + 'order_id' => $locked->id,
898 + 'transaction_type' => Status::TRANSACTION_TYPE_CHARGE,
899 + ])
900 + );
901 + }
748 902
749 - $order->status = Status::ORDER_PROCESSING;
750 - $order->total_paid = $order->total_amount;
751 - $order->save();
903 + // Persist the settled balance while the row lock is held so the next request
904 + // to acquire it computes due = 0. payment_status is deliberately left alone:
905 + // syncOrderStatuses() owns the atomic pending → paid claim that dispatches
906 + // OrderPaid exactly once, and it runs after commit so third-party hook
907 + // callbacks (emails, integrations, subscription activation) never execute
908 + // while the order row is locked.
909 + $locked->total_paid = (int) OrderTransaction::query()
910 + ->where('order_id', $locked->id)
911 + ->whereIn('status', Status::getTransactionSuccessStatuses())
912 + ->sum('total');
752 913
753 - $actionActivity = [
754 - 'title' => __('Order status updated', 'fluent-cart'),
755 - 'content' => sprintf(
756 - /* translators: 1: old status, 2: new status */
757 - __('Order status has been updated from %1$s to %2$s', 'fluent-cart'), $oldStatus, $order->status)
758 - ];
914 + $locked->save();
759 915
760 - // dispatching events related to order status update and payment paid
761 - (new OrderPaid($order, $order->customer, $transaction))->dispatch();
762 -
763 - (new OrderStatusUpdated($order, $oldStatus, $order->status, true, $actionActivity, 'order_status'))->dispatch();
764 -
765 - if ($order->type === 'subscription') {
766 - $subscription = Subscription::query()->where('parent_order_id', $order->id)->first();
767 - if ($subscription) {
768 - $oldSubStatus = $subscription->status;
769 - $subscription = SubscriptionService::syncSubscriptionStates($subscription, ['status' => Status::SUBSCRIPTION_ACTIVE]);
770 - if ($oldSubStatus !== Status::SUBSCRIPTION_ACTIVE && $subscription->status === Status::SUBSCRIPTION_ACTIVE) {
771 - (new SubscriptionActivated($subscription, $order, $order->customer))->dispatch();
772 - }
773 - }
916 + $db->commit();
917 + } catch (\Throwable $e) {
918 + $db->rollBack();
919 + throw $e;
774 920 }
775 921
776 - // if digital
777 - if ($order->fulfillment_type == 'digital' && $order->status === Status::ORDER_PROCESSING) {
778 - $order->status = Status::ORDER_COMPLETED;
779 - $order->completed_at = DateTime::gmtNow();
780 - $order->save();
922 + (new StatusHelper($locked))->syncOrderStatuses($transaction);
781 923
782 - $actionActivity = [
783 - 'title' => __('Order status updated', 'fluent-cart'),
784 - 'content' => sprintf(
785 - /* translators: 1: old status, 2: new status */
786 - __('Order status has been updated from %1$s to %2$s', 'fluent-cart'), Status::ORDER_PROCESSING, $order->status)
787 - ];
788 -
789 - (new OrderStatusUpdated($order, Status::ORDER_PROCESSING, $order->status, true, $actionActivity, 'order_status'))->dispatch();
924 + $paymentNote = sanitize_textarea_field($request->get('mark_paid_note', ''));
925 + if ($paymentNote) {
926 + $locked->addLog(
927 + __('Payment note', 'fluent-cart'),
928 + nl2br(esc_html($paymentNote)),
929 + 'info',
930 + wp_get_current_user()->display_name
931 + );
790 932 }
791 933
792 934 return $this->response->sendSuccess([
793 935 'message' => __('Order has been marked as paid', 'fluent-cart')
@@ -815,11 +957,8 @@
815 957 'message' => __('Orders selection is required', 'fluent-cart')
816 958 ]);
817 959 }
818 960
819 - $orders = Order::query()->whereIn('id', $orderIds)->get();
820 -
821 -
822 961 if ($action == 'delete_orders') {
823 962
824 963 $isDeleted = OrderResource::bulkDeleteByOrderIds($orderIds);
825 964
@@ -851,168 +990,17 @@
851 990 // }
852 991
853 992
854 993 }
855 - if ($action == 'change_shipping_status') {
856 - $newStatus = sanitize_text_field($request->get('new_status', ''));
857 - if (!$newStatus) {
858 - return $this->sendError([
859 - 'message' => __('Please select status', 'fluent-cart')
860 - ]);
861 - }
862 994
863 - $validStatuses = Helper::getShippingStatuses();
864 - if (!isset($validStatuses[$newStatus])) {
865 - return $this->sendError([
866 - 'message' => __('Provided shipping status is not valid', 'fluent-cart')
867 - ]);
868 - }
995 + // The capture_payments branch was removed: it called
996 + // $order->capturePayments(), a method that has never existed anywhere
997 + // in the codebase, so the action fataled on the first order (audit
998 + // item #43). No UI sends it — the orders bulk bar submits
999 + // delete_test_orders only. Bulk payment capture, if wanted, is a
1000 + // gateway feature to design (authorize/capture per gateway), not a
1001 + // branch to resurrect as-is.
869 1002
870 - // foreach ($orders as $order) {
871 - // $order->updateShippingStatus($newStatus);
872 - // }
873 -
874 - return [
875 - 'message' => __('Shipping Status has been changed for the selected orders', 'fluent-cart')
876 - ];
877 -
878 - }
879 - if ($action == 'change_order_status') {
880 -
881 - $newStatus = sanitize_text_field($request->get('new_status', ''));
882 - if (!$newStatus) {
883 - return $this->sendError([
884 - 'message' => __('Please select status', 'fluent-cart')
885 - ]);
886 - }
887 -
888 - $validStatuses = Status::getEditableOrderStatuses();
889 - if (!isset($validStatuses[$newStatus])) {
890 - return $this->sendError([
891 - 'message' => __('Provided order status is not valid', 'fluent-cart')
892 - ]);
893 - }
894 -
895 - $failedOrderIds = [];
896 - $updatedOrderIds = [];
897 -
898 - foreach ($orders as $order) {
899 - // $order->updateStatus('status', $newStatus);
900 - $isUpdated = OrderResource::updateStatuses([
901 - 'order' => $order,
902 - 'action' => 'change_order_status',
903 - 'statuses.order_status' => $newStatus,
904 - 'manage_stock' => sanitize_text_field($request->get('manage_stock')),
905 - ]);
906 -
907 - if (is_wp_error($isUpdated)) {
908 - $failedOrderIds[] = $order->id;
909 - } else {
910 - $updatedOrderIds[] = $order->id;
911 - }
912 - }
913 -
914 - if (count($failedOrderIds) > 0) {
915 - $failedOrderIds = implode(' , ', $failedOrderIds);
916 - return count($updatedOrderIds) > 0
917 - ? $this->sendSuccess([
918 - 'message' => sprintf(
919 - /* translators: %s is the order ids */
920 - __("The order ID - %s cannot be updated because they are either already cancelled or have the same status. And remaining order status has been successfully changed", 'fluent-cart'), $failedOrderIds)
921 - ])
922 - :
923 - $this->sendError([
924 - 'message' => sprintf(
925 - /* translators: %s is the order ids */
926 - __("The order ID - %s cannot be updated because they are either already cancelled or have the same status.", 'fluent-cart'), $failedOrderIds)
927 - ], 423);
928 - }
929 -
930 - if (count($updatedOrderIds) > 0 && count($failedOrderIds) < 1) {
931 - return $this->sendSuccess([
932 - 'message' => __('Order Status has been changed for the selected orders', 'fluent-cart')
933 - ]);
934 - }
935 - }
936 -
937 - if ($action == 'capture_payments') {
938 - foreach ($orders as $order) {
939 - $order->capturePayments();
940 - }
941 -
942 - return [
943 - 'message' => __('Selected payments has been successfully captured', 'fluent-cart')
944 - ];
945 - }
946 -
947 - if ($action == 'change_payment_status') {
948 - $newStatus = sanitize_text_field($request->get('new_status', ''));
949 - if (!$newStatus) {
950 - return $this->sendError([
951 - 'message' => __('Please select status', 'fluent-cart')
952 - ]);
953 - }
954 -
955 - $validStatuses = Status::getEditableTransactionStatuses();
956 - if (!isset($validStatuses[$newStatus])) {
957 - return $this->sendError([
958 - 'message' => __('Provided payment status is not valid', 'fluent-cart')
959 - ]);
960 - }
961 -
962 - $failedOrderIds = [];
963 - $updatedOrderIds = [];
964 - $count = 0;
965 - $customerIds = [];
966 -
967 - foreach ($orders as $order) {
968 - $transaction = $order->latest_transaction;
969 - $isUpdated = OrderResource::updatePaymentStatus([
970 - 'order' => $order,
971 - 'status' => $newStatus,
972 - 'transaction' => $transaction,
973 - ]);
974 -
975 - if (is_wp_error($isUpdated)) {
976 - $failedOrderIds[] = $order->id;
977 - } else {
978 - $updatedOrderIds[] = $order->id;
979 - $count++;
980 - $customerIds[] = $order->customer_id;
981 - }
982 - }
983 -
984 - if ($count > 0 && count($customerIds) > 0) {
985 - (new OrderBulkAction($customerIds))->dispatch();
986 - }
987 -
988 - if (count($failedOrderIds) > 0) {
989 - $failedOrderIds = implode(' , ', $failedOrderIds);
990 - return count($updatedOrderIds) > 0
991 - ? $this->sendSuccess([
992 - 'message' => sprintf(
993 - /* translators: %s is the order ids */
994 - __("The order ID - %s cannot be updated at the moment because the transaction either already has the same status or does not match the provided order. The remaining order statuses have been updated successfully.", 'fluent-cart'), $failedOrderIds)
995 - ])
996 - :
997 - $this->sendError([
998 - 'message' => sprintf(
999 - /* translators: %s is the order ids */
1000 - __("The order ID - %s cannot be updated at the moment because its payment status is either the same as before or has already been refunded.", 'fluent-cart'), $failedOrderIds)
1001 - ], 423);
1002 - }
1003 -
1004 - if (count($updatedOrderIds) > 0 && count($failedOrderIds) < 1) {
1005 - return $this->sendSuccess([
1006 - 'message' => sprintf(
1007 - /* translators: %s is the payment status */
1008 - __("Selected orders payment status has been marked as %s", 'fluent-cart'),
1009 - $newStatus
1010 - )
1011 - ]);
1012 - }
1013 - }
1014 -
1015 1003 return $this->sendError([
1016 1004 'message' => __('Selected action is invalid', 'fluent-cart')
1017 1005 ]);
1018 1006
@@ -1112,15 +1100,54 @@
1112 1100 'message' => __('The selected transaction does not match with the provided order', 'fluent-cart')
1113 1101 ]);
1114 1102 }
1115 1103
1104 + // Money already counted into the order cannot be changed from a dropdown; returning
1105 + // it is a refund, which records a refund transaction through the refund action (FC-SEC-09).
1106 + if ($transaction->status === Status::TRANSACTION_SUCCEEDED) {
1107 + return $this->sendError([
1108 + 'message' => __('A succeeded transaction cannot be changed here. Use the refund action to return the payment.', 'fluent-cart')
1109 + ], 422);
1110 + }
1111 +
1116 1112 $transaction->updateStatus($newStatus);
1117 - $order->updatePaymentStatus($newStatus);
1118 1113
1114 + if ($newStatus === Status::TRANSACTION_SUCCEEDED) {
1115 + // 'succeeded' is a transaction word, not an order payment status: derive the
1116 + // order's paid state and total_paid from its transactions, as mark-as-paid does.
1117 + (new StatusHelper($order))->syncOrderStatuses($transaction);
1118 + } else {
1119 + $order->updatePaymentStatus($newStatus);
1120 + }
1121 +
1119 1122 return [
1120 1123 'transaction' => $transaction,
1121 1124 'message' => __('Payment status has been successfully updated', 'fluent-cart')
1122 1125 ];
1126 + }
1127 +
1128 + public function syncPendingTransaction(Request $request, $order, OrderTransaction $transaction)
1129 + {
1130 + $order = Order::query()->find($order);
1131 +
1132 + if (!$order || $transaction->order_id != $order->id) {
1133 + return $this->sendError([
1134 + 'message' => __('The selected transaction does not match with the provided order', 'fluent-cart')
1135 + ]);
1136 + }
1137 +
1138 + $result = $transaction->syncPendingTransaction();
1139 +
1140 + if (is_wp_error($result)) {
1141 + return $this->sendError([
1142 + 'message' => $result->get_error_message()
1143 + ]);
1144 + }
1145 +
1146 + return $this->sendSuccess([
1147 + 'message' => __('Transaction has been synced from the payment gateway successfully!', 'fluent-cart'),
1148 + 'transaction' => $result
1149 + ]);
1123 1150 }
1124 1151
1125 1152 public function getStats($orderUuid): \WP_REST_Response
1126 1153 {