4

Using stable Sylius 1.2.0, how one can mark the order as paid after the offline payment method was selected?

Tried using an after-callback of the sylius_order_payment state-machine`, but it doesn't seem to fire on any transition:

winzou_state_machine:
    sylius_order_payment:
        callbacks:
            after:
                set_order_paid:
                    on: ['complete']
                    do: ['@AppBundle\Payment\StateMachine\Callback\CallbackClass', 'updateOrder']
                    args: ['object']

Is the state machine used at all? Maybe I'm using the wrong one. Any suggestions are welcome. Thank you for your patience.

Update 1

Tomorrow I'm going to try the Completing a Payment with a state machine transition chapter from the documentation. I'm thinking about putting this code inside an event listener listening on Order created resource event, albeit the state machine callback sounds like a better solution.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88

1 Answers1

6

Finally made it working:

state_machine.yml:

winzou_state_machine:
    sylius_order_checkout:
        callbacks:
            after:
                app_order_complete_set_paid:
                    on: ['complete']
                    do: ['@AppBundle\Order\StateMachine\Callback\OrderCompleteSetPaidCallback', 'setPaid']
                    args: ['object']

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true

    AppBundle\Order\StateMachine\Callback\OrderCompleteSetPaidCallback: ~

OrderCompleteSetPaidCallback.php:

<?php

namespace AppBundle\Order\StateMachine\Callback;

use SM\Factory\FactoryInterface;
use AppBundle\Infrastructure\CommandBus\CommandBus;
use AppBundle\Order\SetPaid\SetPaidCommand;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Payment\PaymentTransitions;

final class OrderCompleteSetPaidCallback
{
    private $stateMachineFactory;

    public function __construct(FactoryInterface $stateMachineFactory)
    {
        $this->stateMachineFactory = $stateMachineFactory;
    }

    public function setPaid(OrderInterface $order): void
    {
        if (!($lastPayment = $order->getLastPayment())) {
            return;
        }

        if ('cash_on_delivery' === $lastPayment->getMethod()->getCode()) {
            $this->transition($order);
        }
    }

    private function transition(OrderInterface $order): void
    {
        $stateMachine = $this->stateMachineFactory->get($order, OrderPaymentTransitions::GRAPH);
        $stateMachine->apply(OrderPaymentTransitions::TRANSITION_PAY);

        $payment = $order->getLastPayment();

        $stateMachine = $this->stateMachineFactory->get($payment, PaymentTransitions::GRAPH);
        $stateMachine->apply(PaymentTransitions::TRANSITION_COMPLETE);
    }
}
Mike Doe
  • 16,349
  • 11
  • 65
  • 88