From 6f4be8397040e4a133075f1609481d34e514b357 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Tue, 25 Apr 2023 21:52:27 +0200 Subject: [PATCH] Sync 80 Systempay Refund First test --- app/Events/OrderIsRefunded.php | 18 +- app/Http/Controllers/Bo/OrderController.php | 267 +++++++++++++----- app/Http/Controllers/Controller.php | 21 ++ app/Http/Controllers/Fo/BasketController.php | 4 +- app/Http/Controllers/Fo/OrderController.php | 3 + app/Http/Requests/Bo/PrepareOrderRequest.php | 17 +- app/Http/Requests/Bo/ResolveOrderRequest.php | 120 ++++++++ app/Jobs/Order/RefundOrder.php | 26 +- app/Lib/Helpers/ToolboxHelper.php | 54 ++++ .../Adapters/InShopPaymentAdapter.php | 8 +- .../Adapters/StripePaymentAdapter.php | 13 +- .../Adapters/SystemPayPaymentAdapter.php | 17 +- app/Lib/Payments/PaymentAdapter.php | 7 +- .../PaymentIPN/SystempayEventListener.php | 75 +++-- app/Models/Payment/Transaction.php | 45 ++- app/Models/Shop/Order.php | 92 +++++- app/Policies/OrderPolicy.php | 21 ++ app/Policies/TransactionPolicy.php | 7 +- composer.json | 2 +- composer.lock | 10 +- ...8_add_needs_validation_on_transactions.php | 33 +++ ...04_25_104648_add_items_to_transactions.php | 37 +++ resources/theme | 2 +- resources/ts/bo.ts | 1 + .../ts/components/OrderPrepareComponent.vue | 62 +++- resources/ts/front-definition.d.ts | 2 + resources/ts/modules/formatters.ts | 29 ++ resources/ts/modules/sweetalertConfirm.ts | 22 ++ resources/ts/pages/resolveForm.ts | 105 +++++++ resources/ts/utilities/fontawesome.ts | 4 + .../views/pages/orders/indexList.blade.php | 10 +- .../pages/orders/parts/transactions.blade.php | 2 + .../views/pages/orders/prepare.blade.php | 14 +- .../views/pages/orders/resolve.blade.php | 191 +++++++++++++ resources/views/pages/orders/show.blade.php | 8 + .../partials/inputs/int-number.blade.php | 2 + .../views/partials/inputs/varchar.blade.php | 2 + routes/web-bo.php | 3 + 38 files changed, 1197 insertions(+), 159 deletions(-) create mode 100644 app/Http/Requests/Bo/ResolveOrderRequest.php create mode 100644 database/migrations/2023_04_25_093108_add_needs_validation_on_transactions.php create mode 100644 database/migrations/2023_04_25_104648_add_items_to_transactions.php create mode 100644 resources/ts/modules/formatters.ts create mode 100644 resources/ts/pages/resolveForm.ts create mode 100644 resources/views/pages/orders/resolve.blade.php diff --git a/app/Events/OrderIsRefunded.php b/app/Events/OrderIsRefunded.php index 5d4c55f..afe5b37 100644 --- a/app/Events/OrderIsRefunded.php +++ b/app/Events/OrderIsRefunded.php @@ -18,25 +18,17 @@ class OrderIsRefunded /** @var \App\Models\Payment\Transaction */ private $transaction; - /** - * The amount to refund. - * @var integer - */ - private $amountToRefund; - /** * Create a new event instance. * - * @param \App\Models\Shop\Order $order The order to refund. - * @param \App\Models\Payment\Transaction $transaction The transaction concerned by the refund. - * @param integer $amountToRefund The amount to refund. + * @param \App\Models\Shop\Order $order The order to refund. + * @param \App\Models\Payment\Transaction $transaction The transaction concerned by the refund. * @return void */ - public function __construct(Order $order, Transaction $transaction, int $amountToRefund) + public function __construct(Order $order, Transaction $transaction) { - $this->order = $order; - $this->transaction = $transaction; - $this->amountToRefund = $amountToRefund; + $this->order = $order; + $this->transaction = $transaction; } /** diff --git a/app/Http/Controllers/Bo/OrderController.php b/app/Http/Controllers/Bo/OrderController.php index d56821a..20d2221 100644 --- a/app/Http/Controllers/Bo/OrderController.php +++ b/app/Http/Controllers/Bo/OrderController.php @@ -13,9 +13,9 @@ use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Orders\ChangeOrderDeliveryStatusRequest; use App\Http\Requests\Bo\Orders\ChangeOrderValidationStatusRequest; use App\Http\Requests\Bo\PrepareOrderRequest; +use App\Http\Requests\Bo\ResolveOrderRequest; use App\Jobs\Order\RefundOrder; use App\Lib\Helpers\ToolboxHelper; -use App\Models\Merchandise\Product; use App\Models\Payment\Transaction; use App\Models\Shop\Order; use Gloudemans\Shoppingcart\CartItem; @@ -199,6 +199,96 @@ class OrderController extends Controller }); } + /** + * Show the order resolve form + * + * @param \App\Models\Shop\Order $order + * @return \Illuminate\View\View + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass + */ + public function resolve(Order $order): View + { + // phpcs:enable + $this->authorize('resolve', $order); + $transactionModel = $order->transactions()->where('needs_validation', true)->first(); + + // * Diff between Basket - (Delivered items - refunded transaction items) + $remainingItems = $order->getRemainingUnrefundedItems(); + + return \view('back::pages.orders.resolve', \compact('order', 'transactionModel', 'remainingItems')); + } + + /** + * Validate order resolution + * + * @param \App\Http\Requests\Bo\ResolveOrderRequest $request + * @param \App\Models\Shop\Order $order + * @return \Illuminate\Http\RedirectResponse + */ + public function resolveSubmit(ResolveOrderRequest $request, Order $order): RedirectResponse + { + return DB::transaction(function () use ($request, $order) { + $refundedItems = $request->collect('items')->pluck('quantity', 'index'); + /** @var \App\Models\Payment\Transaction */ + $transaction = $request->transaction; + /** @var \Illuminate\Support\Collection */ + $orderedItems = \collect($order->basket); + /** @var \Illuminate\Support\Collection */ + $refundedTransactionsItems = $orderedItems->map(function (object $basketItem) use ($refundedItems) { + if ($refundedItems->has($basketItem->rowId)) { + $basketItem->qty = \intval($refundedItems->get($basketItem->rowId)); + return $basketItem; + } + return null; + }); + + $refundedTransactionsItems = \collect(ToolboxHelper::updateBasketAmounts( + $orderedItems, + $refundedItems->all() + )); + + $montantRembourse = \intval($refundedTransactionsItems->sum('options.price_ttc')); + + // ? La transaction concerne des produits ? + if ($refundedTransactionsItems->count()) { + // * Estampiller les ligne avec la raison + $refundedTransactionsItems->map(function (object $basketItem) use ($request) { + $basketItem->name = "{$request->reason} - {$basketItem->name}"; + return $basketItem; + }); + } + // ? Le montant des produits remboursé est inférieur a celui de la transaction. + if ($montantRembourse < \intval($transaction->amount->getAmount())) { + // * Créer un dummy product pour représenter la transaction. + $cartItemOptions = \array_merge($this->cartItemOptionsSkel, [ + 'virtual' => true, + 'price_ttc' => \intval($transaction->amount->getAmount()) + ]); + + $cartItem = CartItem::fromArray([ + 'id' => \str_replace('.', '', \uniqid('', true)), + 'name' => $request->reason, + 'price' => \intval($transaction->amount->getAmount()) - $montantRembourse, + 'weight' => 0, + 'options' => $cartItemOptions + ]); + $cartItem->setQuantity(1); + + // * On envoie la ligne virtuelle en haut de la liste. + $refundedTransactionsItems->put($cartItem->rowId, (object)$cartItem->toArray()); + $refundedTransactionsItems = $refundedTransactionsItems->reverse(); + } + + $transaction->items = $refundedTransactionsItems; + $transaction->needs_validation = false; + + $transaction->saveOrFail(); + + return \response()->redirectToRoute('bo.orders.show', $order) + ->with('success', \trans('La transaction est marquée comme résolue')); + }); + } + /** * Show the order prepare form * @@ -210,7 +300,8 @@ class OrderController extends Controller { // phpcs:enable $this->authorize('prepare', $order); - return \view('back::pages.orders.prepare', \compact('order')); + $remainingItems = $order->getRemainingUnrefundedItems(); + return \view('back::pages.orders.prepare', \compact('order', 'remainingItems')); } /** @@ -224,55 +315,52 @@ class OrderController extends Controller { $this->authorize('prepare', $order); return DB::transaction(function () use ($request, $order) { - // * Stockage de la préparation de la commande. - // * FIXME: Same code here as in Models/Shop/Order::getPartialRefundedBasket. - // ! Ici on veux réutiliser le cart calculator. - $cart = ToolboxHelper::createVirtualCart(\collect($order->basket) - ->map(function (object $basketItem) { - $cartItem = ToolboxHelper::basketItemObjectToCartItem($basketItem); - $cartItem->associate(Product::query()->where('id', $cartItem->id)->first()); - return $cartItem; - }) - // * Enlever les produits qui ne seront pas livrés. - ->filter(function (CartItem $basketItem) { - return $basketItem->qty; - })); - // * Update virtual basket with actual content - \collect($order->basket)->each(function (object $basketItem) use ($request, $cart) { - /** @var \Gloudemans\Shoppingcart\CartItem $cartItem */ - $cartItem = $cart->search(function (CartItem $cartItem) use ($basketItem) { - return $cartItem->id === $basketItem->id; - })->first(); - $newQty = \intval($request->validated()['items'][$basketItem->id]); - // * Update Qty or remove item from the cart. - if (!$newQty) { - $cart->remove($cartItem->rowId); - return; - } - $cartItem->setQuantity($newQty); - // ! https://github.com/bumbummen99/LaravelShoppingcart/pull/181 - // * Note Lib is is actually refactoring for laravel 9 php8 only - // * https://github.com/bumbummen99/LaravelShoppingcart/pull/145 - // ! These lines are required to prevent amount bug. - $cartItem->setTaxRate($basketItem->options->tax_rate / 100); - $cartItem->setDiscountRate($basketItem->options->discount_rate); - }); + $remainingItems = $order->getRemainingUnrefundedItems(); + $shipped_basket = \collect(ToolboxHelper::updateBasketAmounts( + $remainingItems, + $request->items + )); - $virtualOrder = new Order(); - $virtualOrder->assignBasket($cart); + $itemsToRefund = $remainingItems->pluck('qty', 'id') + ->mapWithKeys(function ($qty, string $id) use ($request) { + return [ + $id => \intval($qty) - \intval(\collect($request->items)->get($id, 0)) + ]; + }); + $refundedTransactionsItems = \collect(ToolboxHelper::updateBasketAmounts( + $remainingItems, + $itemsToRefund->all() + )); // * Mettre a jour la commande. - $order->shipped_basket = $virtualOrder->basket; + $order->shipped_basket = $shipped_basket; $order->delivery_status = DeliveryStatus::ready(); $order->saveOrFail(); - if ($request->willNeedCompleteRefund) { - $transactionUsedForPayment = $order->getTransactionUsedForPayment(); + // ? Le montant va exceder ce que le client a payé ? + if ($request->willExceedOrderAmount) { + // * Annulation et remboursement du reste. + // * Créer un dummy product pour représenter la transaction. + $cartItemOptions = \array_merge($this->cartItemOptionsSkel, [ + 'virtual' => true, + 'price_ttc' => $order->total_ttc - $order->total_refund, + ]); + + $cartItem = CartItem::fromArray([ + 'id' => \str_replace('.', '', \uniqid('', true)), + 'name' => $request->reason, + 'price' => $order->total_ttc - $order->total_refund, + 'weight' => 0, + 'options' => $cartItemOptions + ]); + $cartItem->setQuantity(1); $this->refundTransaction( $order, - $transactionUsedForPayment, - intval($transactionUsedForPayment->amount->getAmount()) + $order->total_ttc - $order->total_refund, + \collect([ + $cartItem->rowId => (object)$cartItem->toArray() + ]) ); // * Cancel Order completely. /** @var \Illuminate\Http\RedirectResponse */ @@ -286,14 +374,35 @@ class OrderController extends Controller ), $order ]); - } + } //end if - if ($request->willNeedRefund) { - $transactionUsedForPayment = $order->getTransactionUsedForPayment(); + // ? La commande va devoir être remboursé completement ? + if ($request->willNeedCompleteRefund) { $this->refundTransaction( $order, - $transactionUsedForPayment, - $order->total_ttc - $virtualOrder->total_ttc + $order->total_ttc - $order->total_refund, + $order->getRemainingUnrefundedItems() + ); + // * Cancel Order completely. + /** @var \Illuminate\Http\RedirectResponse */ + return $this->callAction('changeValidationStatus', [ + ChangeOrderValidationStatusRequest::create( + \route('bo.orders.validation-status', $order), + 'POST', + [ + 'validation_status' => ValidationStatus::cancelled()->value + ] + ), + $order + ]); + } //end if + + // ? Il faudra emmtre un remboursment pour le reste ? + if ($request->willNeedRefund) { + $this->refundTransaction( + $order, + $shipped_basket->sum('subtotal'), + $refundedTransactionsItems ); } @@ -314,11 +423,10 @@ class OrderController extends Controller { $this->authorize('refund', $order); return DB::transaction(function () use ($order) { - $transactionUsedForPayment = $order->getTransactionUsedForPayment(); $this->refundTransaction( $order, - $transactionUsedForPayment, - $order->total_ttc - $order->total_refund + $order->total_ttc - $order->total_refund, + $order->getRemainingUnrefundedItems() ); // * Cancel Order completely. /** @var \Illuminate\Http\RedirectResponse */ @@ -345,11 +453,10 @@ class OrderController extends Controller { $this->authorize('refund', $order); return DB::transaction(function () use ($order) { - $transactionUsedForPayment = $order->getTransactionUsedForPayment(); $this->refundTransaction( $order, - $transactionUsedForPayment, - $order->total_ttc - $order->total_refund + $order->total_ttc - $order->total_refund, + $order->getRemainingUnrefundedItems() ); return \back()->with('bo.success', trans( ':model a été mis à jour', @@ -361,13 +468,21 @@ class OrderController extends Controller /** * Refund a transaction * - * @param \App\Models\Shop\Order $order - * @param \App\Models\Payment\Transaction $transaction - * @param integer $amount + * @param \App\Models\Shop\Order $order + * @param integer $amount + * @param object $items * @return void + * @throws \RuntimeException If the payment transaction cannot be fetched for the concerned order. */ - private function refundTransaction(Order $order, Transaction $transaction, int $amount): void - { + private function refundTransaction( + Order $order, + int $amount, + object $items + ): void { + if (!($transaction = $order->getTransactionUsedForPayment())) { + throw new \RuntimeException("Could not fetch paiment transaction for order {$order->id}"); + } + // ? Le paiment se fait en boutique ? if ($transaction->payment_mode->equals(PaymentModeEnum::inShop())) { // ? La validation est annulée et le montant a remboursé equivaut a montant de la commande ? @@ -387,22 +502,26 @@ class OrderController extends Controller 'La commande est marquée comme remboursée' ) . " {$previousMessage}"); }); - } else { - $previousMessage = session()->get('bo.error', ''); - session()->flash('bo.error', \trans( - 'Vous devrez rembourser vous-même le client au magasin' - ) . " {$previousMessage}"); + return; } - } else { - RefundOrder::dispatch( - $order, - $transaction, - $amount - )->onQueue('database'); - $previousMessage = session()->get('bo.info', ''); - session()->flash('bo.info', \trans( - 'Un remboursement va être émit au client' - ) . " \n{$previousMessage}"); - }//end if + $previousMessage = session()->get('bo.error', ''); + session()->flash( + 'bo.error', + \trans( + 'Vous devrez rembourser vous-même le client au magasin' + ) . " {$previousMessage}" + ); + return; + } //end if + RefundOrder::dispatch( + $order, + $transaction, + $amount, + $items + )->onConnection('database'); + $previousMessage = session()->get('bo.info', ''); + session()->flash('bo.info', \trans( + 'Un remboursement va être émit au client' + ) . " \n{$previousMessage}"); } } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 937b2ba..530faed 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -26,6 +26,27 @@ class Controller extends BaseController use DispatchesJobs; use ValidatesRequests; + /** + * Cart item options skel + * + * @var string[] + */ + protected $cartItemOptionsSkel = [ + 'virtual' => false, + 'reference' => '', + 'slug' => '', + 'picture' => '', + 'sell_unit' => '', + 'weight_with_unit' => '', + // * Prix ttc du produit + 'price_ttc' => 0, + // * Prix ttc du produit remisé + 'undiscounted_price_ttc' => 0, + 'tax_rate' => 0, + 'discount_type' => null, + 'discount_rate' => 0, + ]; + /** * Controller * diff --git a/app/Http/Controllers/Fo/BasketController.php b/app/Http/Controllers/Fo/BasketController.php index 17740a6..5c91b39 100644 --- a/app/Http/Controllers/Fo/BasketController.php +++ b/app/Http/Controllers/Fo/BasketController.php @@ -50,7 +50,7 @@ class BasketController extends Controller ]); } - $cartItemOptions = [ + $cartItemOptions = \array_merge($this->cartItemOptionsSkel, [ 'reference' => $product->reference, 'slug' => $product->slug, 'picture' => $product->picture, @@ -63,7 +63,7 @@ class BasketController extends Controller 'tax_rate' => $product->tax_rate->rate, 'discount_type' => \optional(\optional($product->discount)->type)->value, 'discount_rate' => $product->discount_rate, - ]; + ]); $cartItem = CartItem::fromBuyable($product, $cartItemOptions); $cartItem->setQuantity(1); diff --git a/app/Http/Controllers/Fo/OrderController.php b/app/Http/Controllers/Fo/OrderController.php index 50b8467..91ca781 100644 --- a/app/Http/Controllers/Fo/OrderController.php +++ b/app/Http/Controllers/Fo/OrderController.php @@ -403,6 +403,7 @@ class OrderController extends Controller Transaction::getNewInstance( $paymentMode, TransactionType::debit(), + $order->basket, $order->total_ttc, )); if ($transaction->exists) { @@ -423,6 +424,7 @@ class OrderController extends Controller $transaction = Transaction::getNewInstance( $paymentMode, TransactionType::debit(), + $order->basket, $order->total_ttc, ); } @@ -437,6 +439,7 @@ class OrderController extends Controller ->first() ?? Transaction::getNewInstance( $paymentMode, TransactionType::debit(), + $order->basket, $order->total_ttc, ); // * Remove other pending in shop transactions diff --git a/app/Http/Requests/Bo/PrepareOrderRequest.php b/app/Http/Requests/Bo/PrepareOrderRequest.php index 651e98a..3a08788 100644 --- a/app/Http/Requests/Bo/PrepareOrderRequest.php +++ b/app/Http/Requests/Bo/PrepareOrderRequest.php @@ -39,13 +39,23 @@ class PrepareOrderRequest extends FormRequest } return $basketItem->id; }); + $this->merge([ + 'willExceedOrderAmount' => ($this->order->total_ttc - + $this->order->total_refund - $this->basketItems->map(function (object $basketItem) { + return \intval(collect($this->items)->get($basketItem->id)) * $basketItem->options->price_ttc; + })->reduce(function ($carry, int $lineAmount) { + /** @var null|integer $carry */ + return ($carry ? $carry : 0) + $lineAmount; + }) + ) < 0 + ]); $this->merge([ 'willNeedCompleteRefund' => !collect($this->items)->reduce(function (?int $carry, $item) { - return $carry + \is_numeric($item) ? \intval($item) : 0; - }), + return $carry + (\is_numeric($item) ? \intval($item) : 0); + }) or $this->willExceedOrderAmount, 'willNeedRefund' => collect($this->items)->reduce(function (?int $carry, $item) { return $carry + $item; - }) !== $this->basketItems->sum('qty') + }) !== $this->basketItems->sum('qty'), ]); } @@ -59,6 +69,7 @@ class PrepareOrderRequest extends FormRequest return [ 'willNeedCompleteRefund' => 'required|boolean', 'willNeedRefund' => 'required|boolean', + 'willExceedOrderAmount' => 'required|boolean', 'items' => 'required|array', 'items.*' => [ // ! Submited Items must be in the basket. diff --git a/app/Http/Requests/Bo/ResolveOrderRequest.php b/app/Http/Requests/Bo/ResolveOrderRequest.php new file mode 100644 index 0000000..5c74944 --- /dev/null +++ b/app/Http/Requests/Bo/ResolveOrderRequest.php @@ -0,0 +1,120 @@ + + */ + private $basketItems; + + /** + * Order baskter items keyed by id + * + * @var \App\Models\Payment\Transaction|null + */ + private $transactionModel; + + /** + * Determine if the user is authorized to make this request. + * + * @return boolean + */ + public function authorize(): bool + { + return \auth('backend')->check(); + } + + /** + * Prepare the data for validation. + * + * @return void + */ + public function prepareForValidation(): void + { + $this->transactionModel = $this->transaction_id ? Transaction::query() + ->where('id', $this->transaction_id) + ->whereHas('order', function (Builder $q) { + $q->where('id', $this->order->id); + })->first() : null; + + + $this->basketItems = \collect(\optional(\optional($this->transactionModel)->order)->basket); + $this->merge([ + 'transaction' => $this->transactionModel, + 'items' => $this->items ?? [], + 'amountToRefund' => \intval($this->collect('items') + ->pluck('quantity', 'index')->map(function ($quantity, $index) { + return $this->basketItems->get($index)->options->price_ttc * \intval($quantity); + })->sum() ?? 0) + ]); + } + + /** + * Get the validation rules that apply to the request. + * + * @return array + * @throws \Illuminate\Validation\ValidationException If the refund amount is above transaction amount. + */ + public function rules() + { + + if ( + $this->transactionModel and $this->amountToRefund and + \intval($this->transactionModel->amount->getAmount()) < $this->amountToRefund + ) { + throw ValidationException::withMessages([ + 'error' => trans( + 'Le montant des objets devant être remboursé est supérieur au montant de la transaction' + ) + ]); + } + return [ + 'reason' => 'required|string|min:3|max:80', + 'transaction' => 'required', + 'amountToRefund' => 'required|numeric|min:0', + 'items' => 'present', + 'items.*' => 'array', + 'items.*.index' => [ + // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed + 'required', function ($attribute, $inputValue, $fail) { + if (!$this->transactionModel) { + return; + } + if (!$this->basketItems->has($inputValue)) { + $fail(\trans(':attribute :value ne fait pas partie de cette commande', [ + 'value' => $inputValue + ])); + return; + } + } + ], + 'items.*.disabled' => 'required|boolean', + 'items.*.quantity' => 'required|integer|min:1', + ]; + } + + /** + * Get custom attributes for validator errors. + * + * @return array + */ + public function attributes(): array + { + return [ + 'items' => trans('produits'), + 'items.*' => trans('produit'), + 'items.*.quantity' => trans('quantité du produit'), + 'items.*.index' => trans('index panier du produit'), + 'items.*.disabled' => trans('prendre en compte le produit'), + ]; + } +} diff --git a/app/Jobs/Order/RefundOrder.php b/app/Jobs/Order/RefundOrder.php index 694a123..090d4e5 100644 --- a/app/Jobs/Order/RefundOrder.php +++ b/app/Jobs/Order/RefundOrder.php @@ -11,7 +11,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use RuntimeException; class RefundOrder implements ShouldQueue { @@ -41,19 +40,32 @@ class RefundOrder implements ShouldQueue */ private $amountToRefund; + /** + * Items that are refunded + * + * @var object + */ + private $items; + /** * Create a new job instance. * * @param \App\Models\Shop\Order $order * @param \App\Models\Payment\Transaction $transaction * @param integer $amountToRefund + * @param object $items * @return void */ - public function __construct(Order $order, Transaction $transaction, int $amountToRefund) - { + public function __construct( + Order $order, + Transaction $transaction, + int $amountToRefund, + object $items + ) { $this->order = $order; $this->transaction = $transaction; $this->amountToRefund = $amountToRefund; + $this->items = $items; } /** @@ -67,12 +79,13 @@ class RefundOrder implements ShouldQueue { // phpcs:enable if ($this->transaction->payment_mode->equals(PaymentModeEnum::inShop())) { - throw new RuntimeException('An inShop transaction cannot be refunded by the platform'); + throw new \RuntimeException('An inShop transaction cannot be refunded by the platform'); } $refundTransaction = $this->transaction->getAdapter()->doRefundCustomer( $this->transaction, - $this->amountToRefund + $this->amountToRefund, + $this->items ); $refundTransaction->order()->associate($this->order); @@ -80,8 +93,7 @@ class RefundOrder implements ShouldQueue OrderIsRefunded::dispatch( $this->order->refresh(), - $refundTransaction->refresh(), - $this->amountToRefund + $refundTransaction->refresh() ); } } diff --git a/app/Lib/Helpers/ToolboxHelper.php b/app/Lib/Helpers/ToolboxHelper.php index ecf874e..c064dd3 100644 --- a/app/Lib/Helpers/ToolboxHelper.php +++ b/app/Lib/Helpers/ToolboxHelper.php @@ -5,6 +5,7 @@ namespace App\Lib\Helpers; use App\Enums\Discount\DiscountType; use App\Enums\Product\TaxRate; use App\Models\Merchandise\Product; +use App\Models\Shop\Order; use Gloudemans\Shoppingcart\Cart; use Gloudemans\Shoppingcart\CartItem; use Illuminate\Database\Eloquent\Model; @@ -22,6 +23,59 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ToolboxHelper { + /** + * Update basket quantities using cart caluculator + * + * @param object $basket + * @param array $newQuantities Array of [id => qty] or [rowId => qty]. + * @return object + * @throws \Illuminate\Validation\ValidationException If a product from the basket is not accessible anymore. + */ + public static function updateBasketAmounts(object $basket, array $newQuantities): object + { + $newQuantities = \collect($newQuantities); + // ! Ici on veux réutiliser le cart calculator. + $cart = self::createVirtualCart(\collect($basket) + ->map(function (object $basketItem) { + $cartItem = self::basketItemObjectToCartItem($basketItem); + $cartItem->associate(Product::query()->where('id', $cartItem->id)->first()); + return $cartItem; + }) + // * Enlever les produits qui ne seront pas livrés. + ->filter(function (CartItem $basketItem) { + return $basketItem->qty; + })); + + // * Update virtual basket with actual content + \collect($basket)->each(function (object $basketItem) use ($newQuantities, $cart) { + /** @var \Gloudemans\Shoppingcart\CartItem $cartItem */ + $cartItem = $cart->search(function (CartItem $cartItem) use ($basketItem) { + return $cartItem->id === $basketItem->id; + })->first(); + $newQty = \intval( + $newQuantities->get($basketItem->id, $newQuantities->get($basketItem->rowId)) + ); + // * Update Qty or remove item from the cart. + if (!$newQty) { + $cart->remove($cartItem->rowId); + return; + } + $cartItem->setQuantity($newQty); + // ! https://github.com/bumbummen99/LaravelShoppingcart/pull/181 + // * Note Lib is is actually refactoring for laravel 9 php8 only + // * https://github.com/bumbummen99/LaravelShoppingcart/pull/145 + // ! These lines are required to prevent amount bug. + $cartItem->setTaxRate($basketItem->options->tax_rate / 100); + $cartItem->setDiscountRate($basketItem->options->discount_rate); + }); + + $virtualOrder = new Order(); + $virtualOrder->assignBasket($cart); + + // * Mettre a jour la commande. + return (object)$virtualOrder->basket; + } + /** * Crete a virtual cart to use calculator * diff --git a/app/Lib/Payments/Adapters/InShopPaymentAdapter.php b/app/Lib/Payments/Adapters/InShopPaymentAdapter.php index f70f88b..b7004e5 100644 --- a/app/Lib/Payments/Adapters/InShopPaymentAdapter.php +++ b/app/Lib/Payments/Adapters/InShopPaymentAdapter.php @@ -60,13 +60,17 @@ class InShopPaymentAdapter extends PaymentAdapter * * @param \App\Models\Payment\Transaction $transaction * @param integer $amount + * @param object $items * @phpcs:ignore Squiz.Commenting.FunctionComment.InvalidNoReturn * @return \App\Models\Payment\Transaction The new refund transaction. * @throws \Error As this is unhandled. * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed */ - public function doRefundCustomer(Transaction $transaction, int $amount): Transaction - { + public function doRefundCustomer( + Transaction $transaction, + int $amount, + object $items + ): Transaction { // phpcs:enable throw new \Error('In shop transaction cannot be refunded at this time'); } diff --git a/app/Lib/Payments/Adapters/StripePaymentAdapter.php b/app/Lib/Payments/Adapters/StripePaymentAdapter.php index 82b9fdf..67292da 100644 --- a/app/Lib/Payments/Adapters/StripePaymentAdapter.php +++ b/app/Lib/Payments/Adapters/StripePaymentAdapter.php @@ -140,14 +140,18 @@ class StripePaymentAdapter extends PaymentAdapter * * @param \App\Models\Payment\Transaction $transaction * @param integer $amount + * @param object $items * @return \App\Models\Payment\Transaction The new refund transaction. * @phpcs:ignore Squiz.Commenting.FunctionComment.ThrowsNoFullStop * @throws \Illuminate\Validation\ValidationException If doing the refund fails. */ - public function doRefundCustomer(Transaction $transaction, int $amount): Transaction - { + public function doRefundCustomer( + Transaction $transaction, + int $amount, + object $items + ): Transaction { try { - return DB::transaction(function () use ($transaction, $amount) { + return DB::transaction(function () use ($transaction, $amount, $items) { $amountToRefund = new Money($amount, $transaction->currency); $isComplete = $transaction->amount->equals($amountToRefund); $descLabel = $isComplete ? 'complet' : 'partiel'; @@ -186,7 +190,8 @@ class StripePaymentAdapter extends PaymentAdapter $refundTransaction = Transaction::getNewInstance( $transaction->payment_mode, TransactionType::credit(), - \intval($amountToRefund->getAmount()), + $items, + \intval($amountToRefund->getAmount()) ); } diff --git a/app/Lib/Payments/Adapters/SystemPayPaymentAdapter.php b/app/Lib/Payments/Adapters/SystemPayPaymentAdapter.php index 4c14a7e..51b1534 100644 --- a/app/Lib/Payments/Adapters/SystemPayPaymentAdapter.php +++ b/app/Lib/Payments/Adapters/SystemPayPaymentAdapter.php @@ -137,14 +137,18 @@ class SystemPayPaymentAdapter extends PaymentAdapter * * @param \App\Models\Payment\Transaction $transaction * @param integer $amount + * @param object $items * @return \App\Models\Payment\Transaction The new refund transaction. * @phpcs:ignore Squiz.Commenting.FunctionComment.ThrowsNoFullStop * @throws \Illuminate\Validation\ValidationException If doing the refund fails. */ - public function doRefundCustomer(Transaction $transaction, int $amount): Transaction - { + public function doRefundCustomer( + Transaction $transaction, + int $amount, + object $items + ): Transaction { try { - return DB::transaction(function () use ($transaction, $amount) { + return DB::transaction(function () use ($transaction, $amount, $items) { $amountToRefund = new Money($amount, $transaction->currency); $systemPay = $this->getPayment(); @@ -160,7 +164,7 @@ class SystemPayPaymentAdapter extends PaymentAdapter $refund_foreign_id = Transaction::getPaymentForeignKeyName( PaymentModeEnum::systemPay(), - $refundTransactionResponse->get('vads_trans_uuid') + data_get($refundTransactionResponse, 'answer.uuid') ); // * Find an existing refund transaction or Create a new transaction as a refund. @@ -176,12 +180,13 @@ class SystemPayPaymentAdapter extends PaymentAdapter $refundTransaction = Transaction::getNewInstance( $transaction->payment_mode, TransactionType::credit(), - \intval($amountToRefund->getAmount()), + $items, + \intval($amountToRefund->getAmount()) ); } $refundTransaction->status = TransactionStatus::pending(); - $refundTransaction->assignRefundId($refund_foreign_id); + $refundTransaction->assignRefundId(data_get($refundTransactionResponse, 'answer.uuid')); $refundTransaction->order()->associate($concernedOrder); $refundTransaction->saveOrFail(); $concernedOrder->refresh(); diff --git a/app/Lib/Payments/PaymentAdapter.php b/app/Lib/Payments/PaymentAdapter.php index 37536ea..ddf62ab 100644 --- a/app/Lib/Payments/PaymentAdapter.php +++ b/app/Lib/Payments/PaymentAdapter.php @@ -105,8 +105,13 @@ abstract class PaymentAdapter * * @param \App\Models\Payment\Transaction $transaction * @param integer $amount + * @param object $items * @return \App\Models\Payment\Transaction The new refund transaction. * @throws \Illuminate\Validation\ValidationException If doing the refund fails. */ - abstract public function doRefundCustomer(Transaction $transaction, int $amount): Transaction; + abstract public function doRefundCustomer( + Transaction $transaction, + int $amount, + object $items + ): Transaction; } diff --git a/app/Listeners/PaymentIPN/SystempayEventListener.php b/app/Listeners/PaymentIPN/SystempayEventListener.php index f1050e2..5b190a7 100644 --- a/app/Listeners/PaymentIPN/SystempayEventListener.php +++ b/app/Listeners/PaymentIPN/SystempayEventListener.php @@ -6,8 +6,10 @@ use App\Enums\Order\PaymentModeEnum; use App\Enums\Order\PaymentStatus; use App\Enums\Order\TransactionStatus; use App\Enums\Order\TransactionType; +use App\Enums\Order\ValidationStatus; use App\Events\OrderIsCreated; use App\Events\OrderIsPaid; +use App\Events\OrderIsRefunded; use App\Models\Payment\Transaction; use App\Models\Shop\Order; use Illuminate\Database\Eloquent\Builder; @@ -47,12 +49,16 @@ class SystempayEventListener $this->reponse = $this->event->getResponse(); $this->reponseType = $this->reponse->getType(); - Log::debug(__CLASS__); - Log::debug(\json_encode($this->reponse->getPayload())); + Log::info(__CLASS__); + Log::info(\json_encode($this->reponse->getPayload())); + + Log::info('Response type ' . $this->reponseType->label); if ($this->transactionIsRefund()) { + Log::info('CREDIT'); $this->handleCreditCall(); } else { + Log::info('DEBIT'); $this->handleDebitCall(); } @@ -140,24 +146,26 @@ class SystempayEventListener */ private function transactionCreditSucceeded(): void { - $transaction = $this->fetchTransactionFromPaymentIntent(); - // * Si la transaction récupéré est un debit alors que la demande est un crédit. - if ($transaction->type->equals(TransactionType::debit())) { - // * Alors la transaction viens du BO system pay => sauvegarde d'une nouvelle transaction. - $transaction = $this->createCreditTransactionFromCredit( - $transaction, - $this->fetchTransactionAmount() - ); - } + DB::transaction(function () { + $order = $this->fetchTransactionOrder(); + $transaction = $this->fetchTransactionFromPaymentIntent(); + + // * Si la transaction récupéré est un debit alors que la demande est un crédit. + if ($transaction->type->equals(TransactionType::debit())) { + // * Alors la transaction viens du BO system pay => sauvegarde d'une nouvelle transaction. + $transaction = $this->createCreditTransactionFromCredit( + $transaction, + $this->fetchTransactionAmount() + ); + // * Mise a jour de total_refund sur la commande (car non transaction non initiée par la boutique). + $order->total_refund = $order->total_refund + \intval($transaction->amount->getAmount()); + } - DB::transaction(function () use ($transaction) { $transaction->assignRefundId($this->reponse->getTransactionUuid()); $transaction->status = TransactionStatus::validated(); $transaction->saveOrFail(); $transaction->mutateOrderStatus(); - /** @var \App\Models\Shop\Order $order */ - $order = $this->fetchTransactionOrder(); // * Mise a jour du statut de la commande. $isCompleteRefunded = false; @@ -168,16 +176,23 @@ class SystempayEventListener TransactionType::credit() ); } - $order->payment_status = $isCompleteRefunded ? PaymentStatus::refunded() : ($isRefunded ? PaymentStatus::refundedPartial() : PaymentStatus::failed()); - if ($order->payment_status->equals(PaymentStatus::failed())) { $message = __CLASS__ . ' Failed to determine refund status'; \report(new \RuntimeException($message)); SystempayResponse::deny($message)->throwResponse(); } + if ($isCompleteRefunded) { + $order->total_refund = $order->total_ttc; + $order->validation_status = ValidationStatus::cancelled(); + } $order->saveOrFail(); + + OrderIsRefunded::dispatch( + $order, + $transaction + ); }); } @@ -221,6 +236,7 @@ class SystempayEventListener { $transaction = $this->fetchTransactionFromPaymentIntent(); DB::transaction(function () use ($transaction) { + $transaction->assignPaymentId($this->reponse->getTransactionUuid()); $transaction->status = TransactionStatus::validated(); $transaction->saveOrFail(); $transaction->mutateOrderStatus(); @@ -242,7 +258,18 @@ class SystempayEventListener { $transaction = $this->fetchTransactionFromPaymentIntent(); DB::transaction(function () use ($transaction) { - $transaction->status = TransactionStatus::validated(); + /** @var \App\Models\Shop\Order $order */ + $order = $this->fetchTransactionOrder(); + + // ? The order payment has previously been validated ? + if ($order->mail_sent) { + // * Mark the order as validated. + $order->validation_status = ValidationStatus::cancelled(); + $order->saveOrFail(); + } + + $transaction->assignPaymentId($this->reponse->getTransactionUuid()); + $transaction->status = TransactionStatus::failed(); $transaction->saveOrFail(); $transaction->mutateOrderStatus(); }); @@ -263,10 +290,12 @@ class SystempayEventListener $transaction = Transaction::getNewInstance( $originalDebitTransaction->payment_mode, TransactionType::credit(), + (object)[], \intval($amount->getAmount()) ); - $transaction->amount = $amount; + $transaction->amount = $amount; + $transaction->needs_validation = true; $transaction->assignRefundId($this->reponse->getTransactionId()); $transaction->order()->associate($order); return $transaction; @@ -306,17 +335,19 @@ class SystempayEventListener PaymentModeEnum::systemPay(), $this->reponse->getTransactionId() ); + $concernedOrder = $this->fetchTransactionOrder(); $transaction_reference = $this->reponse->getLyraResponse()->get('vads_ext_info_transaction'); - $transactionQuery = Transaction::query()->whereHas('order', function (Builder $q) { - $q->where('reference', $this->fetchTransactionOrder()->reference); + $transactionQuery = Transaction::query()->whereHas('order', function (Builder $q) use ($concernedOrder) { + $q->where('reference', $concernedOrder->reference); }); - $transaction = $transactionQuery->where('foreign_id', $foreign_id)->first(); + $transaction = (clone $transactionQuery)->where('foreign_id', $foreign_id)->first(); $transaction = $transaction ?: $transactionQuery->where('reference', $transaction_reference)->first(); /** @var \App\Models\Payment\Transaction|null $transaction */; if (!$transaction) { + Log::info($transactionQuery->toSql()); $message = __CLASS__ . " {$this->reponseType} : Cannot find transaction - '{$foreign_id}' ref '{$transaction_reference}'"; + '{$foreign_id}' ref '{$transaction_reference}' order ref '{$concernedOrder->reference}'"; \report(new \RuntimeException($message)); SystempayResponse::deny($message)->throwResponse(); } diff --git a/app/Models/Payment/Transaction.php b/app/Models/Payment/Transaction.php index eed75e2..07e9265 100644 --- a/app/Models/Payment/Transaction.php +++ b/app/Models/Payment/Transaction.php @@ -31,6 +31,10 @@ use Mpdf\Config\FontVariables; * @property-read string $foreign_id The transaction id of the selected payment system. * @property-read string $foreign_refund_id The refund transaction id of the selected * payment system, (for webhook usage) + * @property object $items The serialized basket items + * concerned by the transaction. + * @property boolean $needs_validation The transaction has to be validated + * before performing any action. * * @property \App\Enums\Order\PaymentModeEnum $payment_mode The Payment mode for this transaction. * @property \App\Enums\Order\TransactionStatus $status The transaction status. @@ -55,6 +59,25 @@ class Transaction extends Model 'type' => TransactionType::class, ]; + /** + * The attributes that should be cast. + * + * @var string[] + */ + protected $casts = [ + 'needs_validation' => 'bool', + 'items' => 'object' + ]; + + /** + * The model's attributes. + * + * @var array + */ + protected $attributes = [ + 'items' => '{}', + ]; + /** * The attributes that are mass assignable. * @@ -105,16 +128,18 @@ class Transaction extends Model /** * Create a new instance of the given model. * - * @param \App\Enums\Order\PaymentModeEnum $mode - * @param \App\Enums\Order\TransactionType $type - * @param integer $amount - * @param array $attributes + * @param \App\Enums\Order\PaymentModeEnum $mode The payment mode. + * @param \App\Enums\Order\TransactionType $type The transaction type (credit or debit). + * @param object $items The basket items concerned by the transaction. + * @param integer $amount The amount of the transaction. + * @param array $attributes Initial attributes to pass on to the model. * @return static * @throws \RuntimeException If amount is below 0. */ public static function getNewInstance( PaymentModeEnum $mode, TransactionType $type, + object $items, int $amount = 0, array $attributes = [] ): self { @@ -123,11 +148,13 @@ class Transaction extends Model throw new \RuntimeException('Amount cannot be negative'); } - $transaction = new self($attributes); - $transaction->amount = new Money($amount, app('phpMoneyCurrency')); - $transaction->status = TransactionStatus::pending(); - $transaction->type = $type; - $transaction->payment_mode = $mode; + $transaction = new self($attributes); + $transaction->amount = new Money($amount, app('phpMoneyCurrency')); + $transaction->status = TransactionStatus::pending(); + $transaction->type = $type; + $transaction->payment_mode = $mode; + $transaction->needs_validation = false; + $transaction->items = $items; return $transaction; } diff --git a/app/Models/Shop/Order.php b/app/Models/Shop/Order.php index f81d32b..b832fad 100644 --- a/app/Models/Shop/Order.php +++ b/app/Models/Shop/Order.php @@ -48,6 +48,7 @@ use Money\Money; * * @property-read boolean $can_be_cancelled Can the order be cancelled ? * @property-read boolean $can_be_refund Can the order be refund ? + * @property-read boolean $has_warning The order has a warning ? * * @package App\Models */ @@ -292,10 +293,25 @@ class Order extends Model return $this->total_ttc > $this->total_refund; } + /** + * Getter has_warning + * + * Une des transactions de la commande doit être validée avant de continuer. + * + * @return boolean + */ + public function getHasWarningAttribute(): bool + { + return $this->transactions() + ->where('needs_validation', true) + ->where('type', TransactionType::credit()) + ->exists(); + } + // * SETTER /** - * Getter reference + * Setter reference * * @return void * @throws \RuntimeException This is readonly. @@ -304,9 +320,83 @@ class Order extends Model { throw new \RuntimeException('Reference is readonly'); } + /** + * Setter has_warning + * + * @return void + * @throws \RuntimeException This is readonly. + */ + public function setHasWarningAttribute(): void + { + throw new \RuntimeException('has_warning is readonly'); + } // * METHODS + /** + * Get remaining unrefunded items + * + * * Diff between Basket - (Delivered items - refunded transaction items) + * + * @return \Illuminate\Support\Collection + */ + public function getRemainingUnrefundedItems(): Collection + { + /** @var \Illuminate\Support\Collection */ + $orderedItems = \collect($this->basket); + /** @var \Illuminate\Support\Collection */ + $shippedItems = \collect($this->shipped_basket); + /** @var \Illuminate\Support\Collection */ + $refundedTransactionsItems = $this->transactions()->where('type', TransactionType::credit()) + ->pluck('items')->map(function (object $basketItems) { + return (object)\collect($basketItems) + ->filter(function (object $basketItem) { + return !\optional($basketItem->options)->virtual; + })->toArray(); + }); + + // * Collect refunded transaction items. + $refundedTransactionsQtys = \collect(); + $refundedTransactionsItems->each(function (object $basktemItems) use ($refundedTransactionsQtys) { + \collect($basktemItems)->each(function (object $basktemItem) use ($refundedTransactionsQtys) { + $qty = 0; + if ($refundedTransactionsQtys->has($basktemItem->rowId)) { + $qty = $refundedTransactionsQtys->get($basktemItem->rowId)->qty; + } + $basktemItem->qty += $qty; + $refundedTransactionsQtys->put($basktemItem->rowId, $basktemItem); + }); + }); + + /** @var \Illuminate\Support\Collection */ + $remainingItems = \collect(); + $orderedItems->each(function ( + object $basketItem + ) use ( + $shippedItems, + $refundedTransactionsQtys, + $remainingItems + ) { + $qty = $basketItem->qty; + if ($shippedItems->contains('id', $basketItem->id)) { + $qty -= $shippedItems->where('id', $basketItem->id)->first()->qty; + } + if ($refundedTransactionsQtys->contains('id', $basketItem->id)) { + $qty -= $refundedTransactionsQtys->where('id', $basketItem->id)->first()->qty; + } + $remainingItems->put( + $basketItem->rowId, + $qty + ); + }); + $remainingItems = $remainingItems->filter(); + + return \collect(ToolboxHelper::updateBasketAmounts( + $orderedItems, + $remainingItems->toArray() + )); + } + /** * Check if the Order is or will be completely refunded using a transaction. * diff --git a/app/Policies/OrderPolicy.php b/app/Policies/OrderPolicy.php index a6f988d..541cc64 100644 --- a/app/Policies/OrderPolicy.php +++ b/app/Policies/OrderPolicy.php @@ -84,6 +84,7 @@ class OrderPolicy extends Policy if ( // ! Limit to only order where mail has been sent (order-tunnel has completed). $order->mail_sent and + !$order->has_warning and $order->validation_status->equals(ValidationStatus::cancelled()) or $order->delivery_status->value >= DeliveryStatus::ready()->value ) { @@ -106,6 +107,7 @@ class OrderPolicy extends Policy if ( // ! Limit to only order where mail has been sent (order-tunnel has completed). !$order->mail_sent or + $order->has_warning or $order->validation_status->equals(ValidationStatus::cancelled()) or !$transaction ) { @@ -128,6 +130,7 @@ class OrderPolicy extends Policy if ( // ! Limit to only order where mail has been sent (order-tunnel has completed). !$order->mail_sent or + $order->has_warning or $order->validation_status->equals(ValidationStatus::pending()) ) { return Response::deny(); @@ -152,6 +155,7 @@ class OrderPolicy extends Policy // ! Limit to only order where mail has been sent (order-tunnel has completed). !$order->mail_sent or !$order->can_be_refund or + $order->has_warning or !$transaction or $transaction->payment_mode->equals(PaymentModeEnum::inShop()) ) { @@ -159,4 +163,21 @@ class OrderPolicy extends Policy } return Response::allow(); } + + /** + * Order can be resolved + * + * @param \App\Models\User $user + * @param \App\Models\Shop\Order $order + * @return \Illuminate\Auth\Access\Response + * @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed + */ + public function resolve(User $user, Order $order): Response + { + // phpcs:enable + if (!$order->has_warning) { + return Response::deny(); + } + return Response::allow(); + } } diff --git a/app/Policies/TransactionPolicy.php b/app/Policies/TransactionPolicy.php index 59cd8b1..35e6e6f 100644 --- a/app/Policies/TransactionPolicy.php +++ b/app/Policies/TransactionPolicy.php @@ -15,6 +15,7 @@ class TransactionPolicy extends Policy * * ! Only owner customer or a Bo user * ! + a validated transaction. + * ! + a !needs_validation transaction. * * @param \App\Models\Customer\Customer|\App\Models\User|null $user * @param \App\Models\Payment\Transaction|null $transaction @@ -26,7 +27,11 @@ class TransactionPolicy extends Policy $user = null, Transaction $transaction = null ): Response { - if (!$transaction or !$transaction->status->equals(TransactionStatus::validated())) { + if ( + !$transaction or + !$transaction->status->equals(TransactionStatus::validated()) or + $transaction->needs_validation + ) { return Response::deny(); } if ($user and $user instanceof User) { diff --git a/composer.json b/composer.json index 12d8708..aed8806 100644 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "laravel/framework": "^8.83", "laravel/tinker": "^2.5", "laravel/ui": "^3.4", - "ldc/laravel-systempay": "^0.0.3", + "ldc/laravel-systempay": "^0.0.4", "ldc/ldccrmv2client": "^3.0", "ldc/web-status-checker-laravel": "^1.0", "mews/purifier": "^3.3", diff --git a/composer.lock b/composer.lock index 6ff1d1a..47d9fe4 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "cf89ce05dc35b73446e9b6cfe6e8ad6b", + "content-hash": "f041ff75d75f094ad51f87c0cc19a1e6", "packages": [ { "name": "asm89/stack-cors", @@ -2525,16 +2525,16 @@ }, { "name": "ldc/laravel-systempay", - "version": "0.0.3", + "version": "0.0.4", "source": { "type": "git", "url": "https://lab.s-web.fr/ldc-web/projets/laravel-systempay.git", - "reference": "6f09ed70432c9a946fd6e6035820ce63a2bb57eb" + "reference": "405974033779e05f14833c5b686b646fc40bf435" }, "dist": { "type": "zip", - "url": "https://lab.s-web.fr/api/v4/projects/86/packages/composer/archives/ldc/laravel-systempay.zip?sha=6f09ed70432c9a946fd6e6035820ce63a2bb57eb", - "reference": "6f09ed70432c9a946fd6e6035820ce63a2bb57eb", + "url": "https://lab.s-web.fr/api/v4/projects/86/packages/composer/archives/ldc/laravel-systempay.zip?sha=405974033779e05f14833c5b686b646fc40bf435", + "reference": "405974033779e05f14833c5b686b646fc40bf435", "shasum": "" }, "require": { diff --git a/database/migrations/2023_04_25_093108_add_needs_validation_on_transactions.php b/database/migrations/2023_04_25_093108_add_needs_validation_on_transactions.php new file mode 100644 index 0000000..7e78ab6 --- /dev/null +++ b/database/migrations/2023_04_25_093108_add_needs_validation_on_transactions.php @@ -0,0 +1,33 @@ +boolean('needs_validation')->after('status') + ->comment('The transaction was generated from the bank, therefore it has to be cleared'); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('transactions', function (Blueprint $table) { + $table->dropColumn('needs_validation'); + }); + } +} diff --git a/database/migrations/2023_04_25_104648_add_items_to_transactions.php b/database/migrations/2023_04_25_104648_add_items_to_transactions.php new file mode 100644 index 0000000..fa8d13e --- /dev/null +++ b/database/migrations/2023_04_25_104648_add_items_to_transactions.php @@ -0,0 +1,37 @@ +json('items')->after('type')->comment('Items concerned by the transaction.'); + }); + Transaction::query()->get()->each(function (Transaction $transaction) { + $transaction->items = []; + $transaction->saveQuietly(); + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::table('transactions', function (Blueprint $table) { + $table->dropColumn('items'); + }); + } +} diff --git a/resources/theme b/resources/theme index a1ddcf0..f444e88 160000 --- a/resources/theme +++ b/resources/theme @@ -1 +1 @@ -Subproject commit a1ddcf0484fb4aacf401c1123156ab05fd68247f +Subproject commit f444e88e0d3f85a9bd7aed1d1702280f912779da diff --git a/resources/ts/bo.ts b/resources/ts/bo.ts index adc6713..7a21b1a 100644 --- a/resources/ts/bo.ts +++ b/resources/ts/bo.ts @@ -12,3 +12,4 @@ import "./vue"; // PAGES import "./pages/productForm"; import "./pages/discountForm"; +import "./pages/resolveForm"; diff --git a/resources/ts/components/OrderPrepareComponent.vue b/resources/ts/components/OrderPrepareComponent.vue index 162f989..a74cc19 100644 --- a/resources/ts/components/OrderPrepareComponent.vue +++ b/resources/ts/components/OrderPrepareComponent.vue @@ -35,6 +35,7 @@ {{ ucfirst(__("référence")) }} + {{ ucfirst(__("prix unitaire")) }} {{ ucfirst(__("quantitée souhaitée")) }} {{ ucfirst(__("quantitée fournie")) }} @@ -64,6 +65,15 @@ str_limit(basketItem.name, 65) }} + + {{ + __(":price_ttc TTC", { + price_ttc: currencyFormatter( + basketItem.options.price_ttc / 100 + ), + }) + }} + {{ basketItem.qty }} @@ -106,11 +116,12 @@ import { defineComponent } from "vue"; import trans from "../modules/trans"; import route from "../modules/route"; +import formatters from "../modules/formatters"; import sweetalertConfirm from "../modules/sweetalertConfirm"; export default defineComponent({ emits: ["input"], - mixins: [trans, route, sweetalertConfirm], + mixins: [trans, route, formatters, sweetalertConfirm], beforeMount() { if (!this.$attrs.json) { throw new Error("this component requires json"); @@ -122,6 +133,7 @@ export default defineComponent({ this.transaction = data.transaction; this.paymentModeEnums = data.paymentModeEnums; this.basket = data.basket; + this.remainingAmount = data.remainingAmount; this.existingBasketPublishedProductIds = data.existingBasketPublishedProductIds; @@ -143,6 +155,7 @@ export default defineComponent({ paymentModeEnums: Array; basket: BasketItemList; existingBasketPublishedProductIds: Array; + remainingAmount: number; } { return { bindedFormElement: document @@ -152,6 +165,7 @@ export default defineComponent({ paymentModeEnums: [], basket: {}, existingBasketPublishedProductIds: [], + remainingAmount: 0, }; }, watch: {}, @@ -164,16 +178,37 @@ export default defineComponent({ "confirmDoneJS can only be executed on an exising form" ); } + + if (this.willExceedOrderAmount()) { + this.confirm( + trans.methods.__( + "La commande ne pourras être traitée et va être complètement annulée" + ), + trans.methods.__( + "Vous devrez gérer ce cas directement avec le client, car un remboursement arbitraire à été effectué sur l'interface de la banque" + ), + this.bindedFormElement, + (response) => { + if (response.isConfirmed) { + this.askForSubmit(); + } + }, + { icon: "error" } + ); + return false; + } const refundMessage = this.willBefullyRefunded() - ? "La commande fera l'objet d'un remboursement complet et ne sera pas honorée" + ? trans.methods.__( + "La commande fera l'objet d'un remboursement complet et ne sera pas honorée" + ) : this.willBeRefunded() - ? "La commande fera l'objet d'un remboursement" + ? trans.methods.__("La commande fera l'objet d'un remboursement") : null; if (refundMessage) { this.confirm( trans.methods.__(refundMessage), trans.methods.__( - "Si le payement est fait sur le site le remboursement sera automatique." + "Si le paiement est fait sur le site le remboursement sera automatique." ), this.bindedFormElement, (response) => { @@ -218,6 +253,25 @@ export default defineComponent({ ? inputsTotallyFullFilled !== totalInputsCount : !inputs.filter((input) => Number.parseInt(input.value)).length; }, + willExceedOrderAmount(): boolean { + const preparationAmount = Object.values(this.basket) + .map((basketItem) => { + return ( + Number.parseInt( + String( + ( + (this.$refs.inputs as Array).find( + (input: HTMLInputElement) => + input.name === `items[${basketItem.id}]` + ) as HTMLInputElement + ).value + ) + ) * basketItem.options.price_ttc + ); + }) + .reduce((prev, curr) => prev + curr); + return preparationAmount > this.remainingAmount; + }, willBefullyRefunded(): boolean { return this.willBeRefunded(true); }, diff --git a/resources/ts/front-definition.d.ts b/resources/ts/front-definition.d.ts index a110cb6..11bfbd0 100644 --- a/resources/ts/front-definition.d.ts +++ b/resources/ts/front-definition.d.ts @@ -24,6 +24,8 @@ type BItemOptions = { }; type BItem = { + /** Only used for refund transactions */ + virtual: boolean; /** basket internal id */ rowId: string; /** model id */ diff --git a/resources/ts/modules/formatters.ts b/resources/ts/modules/formatters.ts new file mode 100644 index 0000000..aa3410c --- /dev/null +++ b/resources/ts/modules/formatters.ts @@ -0,0 +1,29 @@ +export default { + methods: { + currencyFormatter(num: number): string { + if (isNaN(num)) { + return String(num); + } + return new Intl.NumberFormat("fr-FR", { + style: "currency", + currency: "EUR", + }).format(num); + }, + numFormatter(num: number): string { + return new Intl.NumberFormat("fr-FR", { + style: "decimal", + minimumFractionDigits: 2, + }).format(num); + }, + dateFormatter(str: string) { + const d = new Date(str), + options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", + } as Intl.DateTimeFormatOptions; + return d.toLocaleDateString("fr-FR", options); + }, + }, +}; diff --git a/resources/ts/modules/sweetalertConfirm.ts b/resources/ts/modules/sweetalertConfirm.ts index 124421c..dee5039 100644 --- a/resources/ts/modules/sweetalertConfirm.ts +++ b/resources/ts/modules/sweetalertConfirm.ts @@ -62,5 +62,27 @@ export default { }); return false; }, + message( + title: string, + text: string = "", + options: SweetAlertOptions = {} + ) { + const icon = options.icon ?? "warning"; + Swal.fire({ + title: title, + text: text, + icon: icon, + showCancelButton: false, + confirmButtonText: + options.confirmButtonText ?? trans.default.methods.__("Ok"), + reverseButtons: true, + // * Bootstrap Styling + customClass: { + confirmButton: "btn btn-lg btn-success ms-3 me-3", + }, + buttonsStyling: false, + }); + return false; + }, }, }; diff --git a/resources/ts/pages/resolveForm.ts b/resources/ts/pages/resolveForm.ts new file mode 100644 index 0000000..639d6e2 --- /dev/null +++ b/resources/ts/pages/resolveForm.ts @@ -0,0 +1,105 @@ +import sweetalertConfirm from "../modules/sweetalertConfirm"; +import trans from "../modules/trans"; + +document.addEventListener("DOMContentLoaded", function () { + const confirmSubmitJSPreparation = document.getElementById( + "confirmSubmitJSPreparation" + ) as HTMLFormElement | null, + transaction_amount = document.getElementById( + "transaction_amount" + ) as HTMLInputElement | null; + if (confirmSubmitJSPreparation) { + if (!transaction_amount) { + throw Error("Missing id input transaction_amount"); + } + // * Calcule la somme des produits que l'on veux déclarer comme remboursés. + const fetchRefundTotal = (): number => { + return Array.from( + confirmSubmitJSPreparation.getElementsByClassName( + "item_value" + ) as HTMLCollectionOf + ) + .map((tdElement) => { + const checked = ( + tdElement.querySelector( + "input[type=\"checkbox\"]" + ) as HTMLInputElement + ).checked, + price_ttc = Number.parseInt( + String(tdElement.dataset["price_ttc"]) + ), + qty = Number.parseInt( + String( + ( + tdElement.querySelector( + "input[type=\"number\"]" + ) as HTMLInputElement + ).value + ) + ); + return checked ? price_ttc * qty : 0; + }) + .reduce((prev, curr) => prev + curr); + }; + + // * Handle switches + ( + confirmSubmitJSPreparation.querySelectorAll( + ".input-group" + ) as NodeListOf + ).forEach((divElement) => { + const iptCheckbox = divElement.querySelector( + "input[type=\"checkbox\"]" + ) as HTMLInputElement | null, + iptIndex = divElement.querySelector( + "input[type=\"hidden\"]" + ) as HTMLInputElement | null, + iptQty = divElement.querySelector( + "input[type=\"number\"]" + ) as HTMLInputElement | null; + if (!iptCheckbox) { + throw Error("Missing input[type=\"checkbox\"]"); + } + if (!iptQty) { + throw Error("Missing input[type=\"number\"]"); + } + if (!iptIndex) { + throw Error("Missing input[type=\"hidden\"]"); + } + iptCheckbox.addEventListener("change", () => { + iptIndex.disabled = !iptCheckbox.checked; + iptQty.disabled = !iptCheckbox.checked; + }); + }); + + // * On submit + confirmSubmitJSPreparation.addEventListener("submit", function (e) { + e.preventDefault(); + const wantToRefund = fetchRefundTotal(), + transactionAmount = Number.parseInt(transaction_amount.value); + + // ? Le montant des objets remboursés est inférieur au montant de la transaction ? + if (wantToRefund > transactionAmount) { + sweetalertConfirm.methods.message( + trans.methods.__("Confirmez"), + trans.methods.__( + "Il ne reste pas assez sur la transaction pour dire que les produits sélectionnés sont remboursés" + ), + { icon: "warning" } + ); + return; + } + // ? Confirmer la résolution ? + sweetalertConfirm.methods.confirm( + trans.methods.__("Confirmez"), + trans.methods.__( + "Les produits sélectionnés seront inclus dans la facture de remboursement." + ), + this as HTMLFormElement, + () => (this as HTMLFormElement).submit(), + { icon: "warning" } + ); + return false; + }); + } +}); diff --git a/resources/ts/utilities/fontawesome.ts b/resources/ts/utilities/fontawesome.ts index f6395dc..9ff3a6a 100644 --- a/resources/ts/utilities/fontawesome.ts +++ b/resources/ts/utilities/fontawesome.ts @@ -79,6 +79,8 @@ import { faArrowRightFromBracket, faCircleExclamation, faXmark, + faTriangleExclamation, + faCircleCheck, } from "@fortawesome/free-solid-svg-icons"; // import { faXm } from "@fortawesome/free-brands-svg-icons"; import { @@ -181,5 +183,7 @@ library.add(faArrowRightFromBracket); library.add(faCircleExclamation); library.add(faMagnifyingGlass); library.add(faXmark); +library.add(faTriangleExclamation); +library.add(faCircleCheck); dom.watch(); diff --git a/resources/views/pages/orders/indexList.blade.php b/resources/views/pages/orders/indexList.blade.php index 5aa54d4..b15bed2 100644 --- a/resources/views/pages/orders/indexList.blade.php +++ b/resources/views/pages/orders/indexList.blade.php @@ -3,6 +3,7 @@ @php $cols = [ + 'needs_validation' => __('⚠'), 'reference' => __('Référence'), 'created_at' => __('Date'), 'total' => __('Total TTC en €'), @@ -19,7 +20,7 @@ @endphp @include('back::modules.tableColSorter', [ 'cols' => $cols, - 'ignore' => ['total', 'timeslot_date', 'shop'], + 'ignore' => ['needs_validation', 'total', 'timeslot_date', 'shop'], 'mobileHide' => ['shop'], ]) @@ -27,6 +28,13 @@ @if ($orders->count()) @foreach ($orders as $orderModel) + + @if($orderModel->has_warning) + + @else + + @endif + {{ $orderModel->reference }} {{ $orderModel->created_at->isoFormat('\L\e DD/MM/YYYY \à HH:mm') }} {{ \App\Lib\Helpers\ToolboxHelper::fmtCurrency($orderModel->total_ttc, '') }} diff --git a/resources/views/pages/orders/parts/transactions.blade.php b/resources/views/pages/orders/parts/transactions.blade.php index 972d1cb..df8327e 100644 --- a/resources/views/pages/orders/parts/transactions.blade.php +++ b/resources/views/pages/orders/parts/transactions.blade.php @@ -42,6 +42,8 @@ {{ __('Télécharger la facture') }} + @elseif ($transaction->needs_validation) + {{ __('Pour télécharger cette facture la transaction doit être résolue') }} @endcan diff --git a/resources/views/pages/orders/prepare.blade.php b/resources/views/pages/orders/prepare.blade.php index 00e65f1..799fc27 100644 --- a/resources/views/pages/orders/prepare.blade.php +++ b/resources/views/pages/orders/prepare.blade.php @@ -35,15 +35,25 @@ @include('back::pages.orders.parts.transactions', compact('order')) + @if($order->total_refund) +
+ {{ + __('Montant restant sur la transaction :amount', [ + 'amount' => \App\Lib\Helpers\ToolboxHelper::fmtCurrency($order->total_ttc - $order->total_refund) + ]) + }} +
+ @endif
@csrf @php $data = [ + 'remainingAmount' => $order->total_ttc - $order->total_refund, 'transaction' => $order->getTransactionUsedForPayment(), 'paymentModeEnums' => \App\Enums\Order\PaymentModeEnum::toArray(), - 'basket' => $order->basket, + 'basket' => $remainingItems, 'existingBasketPublishedProductIds' => \App\Models\Merchandise\Product::query() - ->whereIn('id', collect($order->basket) + ->whereIn('id', collect($remainingItems) ->map(function ($basketItem) { return $basketItem->id; }))->where('status', true)->pluck('id'), diff --git a/resources/views/pages/orders/resolve.blade.php b/resources/views/pages/orders/resolve.blade.php new file mode 100644 index 0000000..94c7bd8 --- /dev/null +++ b/resources/views/pages/orders/resolve.blade.php @@ -0,0 +1,191 @@ +@extends('back::backend', ['brParam' => $order]) + +@section('title', sprintf('%s - %s %s', Str::ucfirst(__('détails')), __('Résolution problème commande'), $order->name)) + +@section('breadcrumb', request()->route()->getName()) + +@section('content') +
+
+
+
+
+
+ + + {{ __('Résolution problème commande') }} + +
+
+ @include('back::pages.orders.parts.asked-delivery', compact('order')) +
+
+
+
+
+
+
+
+ @include('back::pages.orders.parts.transactions', compact('order')) +
+
+ + @csrf + @php + $data = [ + 'transaction' => $order->getTransactionUsedForPayment(), + 'paymentModeEnums' => \App\Enums\Order\PaymentModeEnum::toArray(), + 'basket' => $order->basket, + 'existingBasketPublishedProductIds' => \App\Models\Merchandise\Product::query() + ->whereIn('id', collect($order->basket) + ->map(function ($basketItem) { + return $basketItem->id; + }))->where('status', true)->pluck('id'), + ]; + @endphp + + + +
+
{{ __('Un remboursement pour la transaction :reference + à été émit par la banque.', [ + 'reference' => $transactionModel->reference + ]) }}
+
{{ __('Il est nécéssaire d\'en spécifier la raison.') }}
+
+ +
+
+ {{-- NAME --}} + @include('back::partials.inputs.varchar', [ + 'id' => 'productName', + 'hasWordCounter' => true, + 'name' => 'reason', + 'required' => true, + 'model' => $transactionModel ?? null, + 'label' => __('Raison du remboursement'), + 'helper' => __('Sera affiché sur la facture d\'avoir') + ]) +
+
+
+
+

{{ __('Produits remboursables') }}

+ {{ __('Si cette transaction a pour but de rembourser des produits, veuillez saisir les quantitée concernés ci-dessous.') }}
+ {{ __('Montant de la transaction :amount', [ + 'amount' => app('phpMoneyFormatter')->format($transactionModel->amount) + ]) }} +
+
+ @if($remainingItems->count()) +
+ + + + + + + + + + + @foreach ($remainingItems as $remainingItem) + + + + + + + @endforeach + +
{{ __('Désignation') }}{{ __('Prix unitaire') }}{{ __('Quantité Remboursable') }}{{ __('Quantité') }}
+ {{ __('Référence') }} : {{ $remainingItem->options->reference }}
+ {{ $remainingItem->name }} +
+ {{ \App\Lib\Helpers\ToolboxHelper::fmtCurrency($remainingItem->options->price_ttc) }}
+
+ {{-- QTY --}} + @include('back::partials.inputs.int-number', [ + 'id' => '', + 'name' => "disabled[{$remainingItem->rowId}]", + 'required' => false, + 'unsigned' => true, + 'readonly' => true, + 'disabled' => true, + 'value' => $remainingItem->qty, + 'label' => false, + 'helper' => false + ]) + +
+ + index}][index]" }}" + value="{{ $remainingItem->rowId }}" + @if(!old("items.{$loop->index}.disabled", 0)) + disabled + @endif + > + index}][quantity]" }}" + min="0" + max="{{ $remainingItem->qty }}" + value="{{ old("items.{$loop->index}.quantity", 0) }}" + @if(!old("items.{$loop->index}.disabled", 0)) + disabled + @endif + > + @include('back::modules.input-error', [ + 'inputName' => "items.{$loop->index}.index" + ]) + @include('back::modules.input-error', [ + 'inputName' => "items.{$loop->index}.disabled" + ]) + @include('back::modules.input-error', [ + 'inputName' => "items.{$loop->index}.quantity" + ]) +
+
+
+ @else +
+
+ {{ __('Il ne reste plus de produit remboursable sur cette commande, il est seulement possible de fournir la raison du remboursement.') }} +
+
+ @endif +
+
+ +
+
+ +
+
+@endsection diff --git a/resources/views/pages/orders/show.blade.php b/resources/views/pages/orders/show.blade.php index 0c98278..db4e494 100644 --- a/resources/views/pages/orders/show.blade.php +++ b/resources/views/pages/orders/show.blade.php @@ -17,6 +17,14 @@
+ @if($order->has_warning) + + + + {{ __('Résoudre l\'issue') }} + + + @endif @include('back::pages.orders.parts.asked-delivery', compact('order'))
diff --git a/resources/views/partials/inputs/int-number.blade.php b/resources/views/partials/inputs/int-number.blade.php index db698d9..7492f9c 100644 --- a/resources/views/partials/inputs/int-number.blade.php +++ b/resources/views/partials/inputs/int-number.blade.php @@ -29,6 +29,8 @@ min="{{ !empty($unsigned) ? '0' : '-2147483648' }}" @endif @if(!empty($required))required @endif + @if(!empty($readonly))readonly @endif + @if(!empty($disabled))disabled @endif > @if(isset($appendText)) diff --git a/resources/views/partials/inputs/varchar.blade.php b/resources/views/partials/inputs/varchar.blade.php index bfd9780..3a28108 100644 --- a/resources/views/partials/inputs/varchar.blade.php +++ b/resources/views/partials/inputs/varchar.blade.php @@ -11,6 +11,8 @@ aria-describedby="{{ $id }}Help" placeholder="{{ $placeholder ?? __('Un nom beau et explicite') }}" @if(!empty($required))required @endif + @if(!empty($readonly))readonly @endif + @if(!empty($disabled))disabled @endif > @include('back::modules.input-error', [ 'inputName' => $name, diff --git a/routes/web-bo.php b/routes/web-bo.php index bd646ad..9c7bcae 100644 --- a/routes/web-bo.php +++ b/routes/web-bo.php @@ -144,6 +144,9 @@ Route::prefix('bo')->name('bo.')->group(function () { Route::put('/orders/{order}/set-delivery', [ OrderController::class, 'changeDeliveryStatus' ])->name('orders.delivery-status'); + Route::get('/orders/{order}/resolve', [OrderController::class, 'resolve'])->name('orders.resolve'); + Route::post('/orders/{order}/resolve', [OrderController::class, 'resolveSubmit']) + ->name('orders.resolve-submit'); Route::get('/orders/{order}/prepare', [OrderController::class, 'prepare'])->name('orders.prepare'); Route::post('/orders/{order}/prepare', [OrderController::class, 'prepareSubmit']) ->name('orders.prepare-submit');