[miniShop2] Дополнительная логика отправки писем при оформлении заказа

Добрый день!
Клиент просит сделать следующую логику отправки писем админу сайта при оформлении заказа:
1. Если при оформлении заказа была указана оплата при получении — отправлять письма как обычно.
2. Если при оформлении заказа была указана онлайн-оплата (положим id=2), то при создании заказа и присвоении статуса «Новый» — не отправлять ничего, а после оплаты и смены статуса заказа на «Оплачен» — отправлять письмо, которое должно было отправляться при создании заказа.
Как лучше такую доработку реализовать?
Giant Dad
5 часов назад
modx.pro
23
0

Комментарии: 1

Артур Шевченко
2 часа назад
0
Вариант 1
Переопределить метод msOrderHandler::submit() таким образом, чтобы там перед установлением статуса «Новый» проверялся способ оплаты и, если оплата при получении, статус устанавливать методом minishop2::changeOrderStatus(), иначе через modResource::save().

Вариант 2.
Ввести для оплаты при получении отдельный статус. Написать плагин на событие msOnChangeOrderStatus, в котором проверять способ оплаты и, если это оплата при получении, вызывать метод minishop2::changeOrderStatus() и устанавливать созданный для этого способа оплаты статус. При этом отправку писем для статуса «Новый» отключить в настройках минишопа.

Вариант 3.
Отключить стандартную отправку писем. Написать свой класс отправки писем и вызывать его в плагине на событие msOnChangeOrderStatus. Вот пример реализации такого класса
<?php

namespace CustomServices\Manage;

use CustomServices\Helpers\Mailer;

class MailingOrder extends Base
{
    private Mailer $mailer;

    private array $mailingStatuses = [
        2 => [
            'user' => [
                'subject' => 'ms2_email_subject_paid_user',
                'chunk' => 'msEmailPaid.user'
            ],
            'manager' => [],
        ],
        3 => [
            'user' => [
                'subject' => 'ms2_email_subject_sent_user',
                'chunk' => 'msEmail.sent.user'
            ],
            'manager' => [],
        ],
        108 => [
            'user' => [
                'subject' => 'ms2_email_subject_sent_user',
                'chunk' => 'msEmail.sent.user'
            ],
            'manager' => [],
        ],
        117 => [
            'user' => [
                'subject' => 'ms2_email_subject_paid_user',
                'chunk' => 'msEmailPaid.user'
            ],
            'manager' => [],
        ],
        103 => [
            'user' => [
                'subject' => 'ms2_email_subject_paid_user',
                'chunk' => 'msEmailPaid.user'
            ],
            'manager' => [],
        ],
    ];

    private array $statusData;

    public function __construct(\modX $modx, ?array $properties = [])
    {
        parent::__construct($modx, $properties);
        if ($properties['order'] && $properties['order']->get('context') !== $this->modx->context->get('key')) {
            $this->modx->switchContext($properties['order']->get('context'));
            $this->cultureKey = $this->modx->getOption('cultureKey', '', 'en');
        }
        $this->mailer = new Mailer($this->modx);
        $this->statusData = [];
    }

    public function send(): bool
    {
        $statusId = $this->properties['statusId'];
        if (!isset($this->mailingStatuses[$statusId])) {
            return false;
        }
        $this->statusData = $this->mailingStatuses[$statusId];

        if (!$this->properties['order']) {
            $this->logging->write([
                'msg' => "Mail not sent. Order not defined",
            ]);
            return false;
        }

        $pls = $this->getEmailPls();
        if (!empty($this->statusData['manager']) && $mgrMailerProps = $this->getMailerProperties($pls, 'manager')) {
            if(!$this->mailer->send($mgrMailerProps)){
                $this->logging->write([
                    'msg' => "Order {$pls['num']} was not sent to manager email",
                    'data'=> [
                        'mailerProps' => $mgrMailerProps
                    ]
                ]);
            }
        }

        if (!empty($this->statusData['user']) && $usrMailerProps = $this->getMailerProperties($pls)) {
            if(!$this->mailer->send($usrMailerProps)){
                $this->logging->write([
                    'msg' => "Order {$pls['num']} was not sent to customer email",
                    'data'=> [
                        'mailerProps' => $usrMailerProps
                    ]
                ]);
            }
        }
        return true;
    }

    public function getEmailPls(): array
    {
        $pls = $this->properties['order']->toArray();
        $pls['cost'] = $this->miniShop2->formatPrice($pls['cost']);
        $pls['cart_cost'] = $this->miniShop2->formatPrice($pls['cart_cost']);
        $pls['delivery_cost'] = $this->miniShop2->formatPrice($pls['delivery_cost']);
        $pls['weight'] = $this->miniShop2->formatWeight($pls['weight']);
        $pls['payment_link'] = $this->properties['paymentLink'] ?: '';
        return $pls;
    }

    public function getMailerProperties(array $pls, $type = 'user'): array
    {
        $mailerProperties = [];
        $mailerProperties['subject'] = $this->modx->lexicon($this->statusData[$type]['subject'], $pls, $this->cultureKey);
        if($mailerProperties['subject'] === $this->statusData[$type]['subject']){
            $mailerProperties['subject'] = $this->modx->lexicon($this->statusData[$type]['subject'], $pls, 'en');
        }
        $mailerProperties['body'] = $this->parser->runSnippet('msGetOrder', array_merge($pls, ['tpl' => $this->statusData[$type]['chunk']]));
        if ($this->properties['invoicePath'] && $type === 'user') {
            $mailerProperties['attachment'] = $this->properties['invoicePath'];
        }

        if (!$mailerProperties['to'] = $type === 'user' ? $this->getUserEmails($pls['user_id']) : $this->getManagerEmails()) {
            return [];
        }

        return $mailerProperties;
    }

    public function getUserEmails(int $userId): array
    {
        if (!$profile = $this->modx->getObject('modUserProfile', ['internalKey' => $userId])) {
            return [];
        }
        $email = $profile->get('email');
        if (!$email) {
            if (!$user = $this->modx->getObject('modUser', $userId)) {
                return [];
            }
            if (!$email = $user->get('username')) {
                return [];
            }
        }
        return [$email];
    }

    public function getManagerEmails(): array
    {
        return array_map(
            'trim',
            explode(
                ',',
                $this->modx->getOption('ms2_email_manager', null, $this->modx->getOption('emailsender'))
            )
        );
    }
}
    Авторизуйтесь или зарегистрируйтесь, чтобы оставлять комментарии.
    1