Sync 80 Systempay Refund First test

This commit is contained in:
Jérémy Munsch 2023-04-25 21:52:27 +02:00
parent 3dcda6191c
commit 6f4be83970
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
38 changed files with 1197 additions and 159 deletions

View file

@ -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;
}
/**

View file

@ -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<object> */
$orderedItems = \collect($order->basket);
/** @var \Illuminate\Support\Collection<object> */
$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}");
}
}

View file

@ -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
*

View file

@ -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);

View file

@ -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

View file

@ -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.

View file

@ -0,0 +1,120 @@
<?php
namespace App\Http\Requests\Bo;
use App\Models\Payment\Transaction;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\ValidationException;
class ResolveOrderRequest extends FormRequest
{
/**
* Order baskter items
*
* @var \Illuminate\Support\Collection<object>
*/
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'),
];
}
}

View file

@ -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()
);
}
}

View file

@ -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
*

View file

@ -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');
}

View file

@ -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())
);
}

View file

@ -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();

View file

@ -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;
}

View file

@ -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();
}

View file

@ -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;
}

View file

@ -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<object>
*/
public function getRemainingUnrefundedItems(): Collection
{
/** @var \Illuminate\Support\Collection<object> */
$orderedItems = \collect($this->basket);
/** @var \Illuminate\Support\Collection<object> */
$shippedItems = \collect($this->shipped_basket);
/** @var \Illuminate\Support\Collection<object> */
$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<string,integer> */
$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.
*

View file

@ -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();
}
}

View file

@ -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) {

View file

@ -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",

10
composer.lock generated
View file

@ -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": {

View file

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddNeedsValidationOnTransactions extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('transactions', function (Blueprint $table) {
$table->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');
});
}
}

View file

@ -0,0 +1,37 @@
<?php
use App\Models\Payment\Transaction;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddItemsToTransactions extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('transactions', function (Blueprint $table) {
$table->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');
});
}
}

@ -1 +1 @@
Subproject commit a1ddcf0484fb4aacf401c1123156ab05fd68247f
Subproject commit f444e88e0d3f85a9bd7aed1d1702280f912779da

View file

@ -12,3 +12,4 @@ import "./vue";
// PAGES
import "./pages/productForm";
import "./pages/discountForm";
import "./pages/resolveForm";

View file

@ -35,6 +35,7 @@
<thead>
<tr>
<th>{{ ucfirst(__("référence")) }}</th>
<th>{{ ucfirst(__("prix unitaire")) }}</th>
<th>{{ ucfirst(__("quantitée souhaitée")) }}</th>
<th>{{ ucfirst(__("quantitée fournie")) }}</th>
</tr>
@ -64,6 +65,15 @@
str_limit(basketItem.name, 65)
}}</span>
</td>
<td class="text-center align-middle">
{{
__(":price_ttc TTC", {
price_ttc: currencyFormatter(
basketItem.options.price_ttc / 100
),
})
}}
</td>
<td class="text-center align-middle">
<strong class="fs-4">{{ basketItem.qty }}</strong>
</td>
@ -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<Enum>;
basket: BasketItemList;
existingBasketPublishedProductIds: Array<number>;
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<HTMLInputElement>).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);
},

View file

@ -24,6 +24,8 @@ type BItemOptions = {
};
type BItem = {
/** Only used for refund transactions */
virtual: boolean;
/** basket internal id */
rowId: string;
/** model id */

View file

@ -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);
},
},
};

View file

@ -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;
},
},
};

View file

@ -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<HTMLTableCellElement>
)
.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<HTMLDivElement>
).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;
});
}
});

View file

@ -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();

View file

@ -3,6 +3,7 @@
<thead>
@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'],
])
</thead>
@ -27,6 +28,13 @@
@if ($orders->count())
@foreach ($orders as $orderModel)
<tr>
<td>
@if($orderModel->has_warning)
<i class="fa-solid fa-triangle-exclamation fa-beat"></i>
@else
<i class="fa-solid fa-circle-check"></i>
@endif
</td>
<td>{{ $orderModel->reference }}</td>
<td><span>{{ $orderModel->created_at->isoFormat('\L\e DD/MM/YYYY \à HH:mm') }}</span></td>
<td>{{ \App\Lib\Helpers\ToolboxHelper::fmtCurrency($orderModel->total_ttc, '') }}</td>

View file

@ -42,6 +42,8 @@
<a href="{{ route(request()->routeIs('bo.*') ? 'bo.orders.invoice' : 'account.orders.invoice', ['reference' => $order, 'transactionReference' => $transaction]) }}" class="btn btn-primary" target="_blank" role="button">{{
__('Télécharger la facture')
}}</a>
@elseif ($transaction->needs_validation)
<span class="text-info">{{ __('Pour télécharger cette facture la transaction doit être résolue') }}</span>
@endcan
</div>
</li>

View file

@ -35,15 +35,25 @@
@include('back::pages.orders.parts.transactions', compact('order'))
</div>
</div>
@if($order->total_refund)
<div class="text-center p-2">
<span class="fs-3 badge-warning text-bg-warning">{{
__('Montant restant sur la transaction :amount', [
'amount' => \App\Lib\Helpers\ToolboxHelper::fmtCurrency($order->total_ttc - $order->total_refund)
])
}}</span>
</div>
@endif
<form action="{{ route('bo.orders.prepare-submit', $order) }}" method="POST" class="confirmSubmitJSPreparation">
@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'),

View file

@ -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')
<div class="card">
<div class="card-header">
<div class="row">
<div class="col">
<div class="row">
<div class="col">
<span class="h3">
<a href="{{ route('bo.orders.show', $order) }}" class="btn btn-sm btn-primary"><i class="fa-solid fa-arrow-left"></i></a>
{{ __('Résolution problème commande') }}
</span>
</div>
<div class="col text-end">
@include('back::pages.orders.parts.asked-delivery', compact('order'))
</div>
</div>
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
@include('back::pages.orders.parts.transactions', compact('order'))
</div>
</div>
<form action="{{ route('bo.orders.resolve-submit', $order) }}" method="POST" id="confirmSubmitJSPreparation">
@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
<input type="hidden" name="transaction_id" value="{{ $transactionModel->id }}">
<input id="transaction_amount" type="hidden" name="" value="{{ $transactionModel->amount->getAmount() }}" disabled>
<div>
<div class="h3">{{ __('Un remboursement pour la transaction :reference
à été émit par la banque.', [
'reference' => $transactionModel->reference
]) }}</div>
<div class="h4">{{ __('Il est nécéssaire d\'en spécifier la raison.') }}</div>
</div>
<div class="row mb-3">
<div class="col-12 col-lg-6">
{{-- 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')
])
</div>
</div>
<div class="row mb-3">
<div class="col-12 col-lg-6">
<h3>{{ __('Produits remboursables') }}</h3>
<small>{{ __('Si cette transaction a pour but de rembourser des produits, veuillez saisir les quantitée concernés ci-dessous.') }}</small><br>
<span class="h5 font-imprima text-bold">{{ __('Montant de la transaction :amount', [
'amount' => app('phpMoneyFormatter')->format($transactionModel->amount)
]) }}</span>
</div>
</div>
@if($remainingItems->count())
<div class="table-responsive">
<table class="table table-info table-striped">
<thead>
<tr>
<th>{{ __('Désignation') }}</th>
<th>{{ __('Prix unitaire') }}</th>
<th>{{ __('Quantité Remboursable') }}</th>
<th>{{ __('Quantité') }}</th>
</tr>
</thead>
<tbody>
@foreach ($remainingItems as $remainingItem)
<tr>
<td>
<strong>{{ __('Référence') }}&nbsp;:&nbsp;{{ $remainingItem->options->reference }}</strong><br>
<span class="fs-5">{{ $remainingItem->name }}</span>
</td>
<td>
<strong>{{ \App\Lib\Helpers\ToolboxHelper::fmtCurrency($remainingItem->options->price_ttc) }}</strong><br>
</td>
<td>
{{-- 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
])
</td>
<td
class="item_value"
data-price_ttc="{{ $remainingItem->options->price_ttc }}"
>
<div class="input-group">
<label class="input-group-text" for="{{ $remainingItem->rowId }}">
<div class="form-check form-switch ms-2 mt-2">
<input
id="{{ $remainingItem->rowId }}"
class="ml-2 form-check-input"
type="checkbox"
name="{{ "items[{$loop->index}][disabled]" }}"
value="1"
@if(old("items.{$loop->index}.disabled", 0))
checked
@endif
>
</div>
</label>
<input
type="hidden"
name="{{ "items[{$loop->index}][index]" }}"
value="{{ $remainingItem->rowId }}"
@if(!old("items.{$loop->index}.disabled", 0))
disabled
@endif
>
<input
class="form-control"
type="number"
name="{{ "items[{$loop->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"
])
</div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@else
<div class="row mb-3">
<div class="col-12 col-lg-6">
<span class="h5 badge-info text-bg-info">{{ __('Il ne reste plus de produit remboursable sur cette commande, il est seulement possible de fournir la raison du remboursement.') }}</span>
</div>
</div>
@endif
<div class="row">
<div class="col text-center">
<button type="submit" class="btn btn-warning"
title="{{ __('Enregister :model', [
'model' => Str::singular(__('models.classes.discounts')),
]) }}"
data-bs-toggle="tooltip">
<i class="fa-solid fa-triangle-exclamation fa-beat"></i>
{{ __('Enregister') }}
</button>
</div>
</div>
</form>
</div>
</div>
@endsection

View file

@ -17,6 +17,14 @@
</span>
</div>
<div class="col text-end">
@if($order->has_warning)
<span class="h3">
<a class="btn btn-warning" href="{{ route('bo.orders.resolve', $order) }}">
<i class="fa-solid fa-triangle-exclamation fa-beat"></i>
<strong>{{ __('Résoudre l\'issue') }}</strong>
</a>
</span>
@endif
@include('back::pages.orders.parts.asked-delivery', compact('order'))
</div>
</div>

View file

@ -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))
<label class="input-group-text">{{ $appendText }}</label>

View file

@ -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,

View file

@ -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');