1. Главная
  2. Форумы
  3. Техподдержка Drupal
  4. FAQ

Как в Commerce отправить на email администратору список заказанных товаров и информацию о покупателе используя rules?

Главные вкладки

Создаю правило на событие Completing the checkout process

Все отправляется но:

[commerce-order:commerce-line-items] возвращает id заказа.

[commerce-order:commerce-customer-billing] возвращает id пользователя.

[commerce-order:commerce-order-total:amount] возвращает цену в 100 раз больше чем должна быть (вместо 220 рублей выводит 22,000.00)

Как вывести список товаров?
Как получить адрес?
Как вывести нужную сумму?

Комментарии

Аватар пользователя Navigator Navigator 10 марта 2013 в 1:29

1541 wrote:
Решение нашлось?

Временно решено так:
Включен модуль PHP filter и Entity.
В Rules > Actions > Send mail поле MESSAGE:


<?php
// Номер заказа
$order_id = $commerce_order->order_id; $wrapper = entity_metadata_wrapper('commerce_order', $commerce_order); // Список товаров
$line_items = $wrapper->commerce_line_items->value(); // Адрес (поле: field_address)
$field_address = $wrapper->commerce_customer_billing->field_address->value(); /*
Поля:
Имя (поле: field_first_name)
Фамилия (поле: field_second_name)
Отчество (поле: field_surname)
*/
$field_first_name = $wrapper->commerce_customer_billing->field_first_name->value();
$field_second_name = $wrapper->commerce_customer_billing->field_second_name->value();
$field_surname = $wrapper->commerce_customer_billing->field_surname->value(); // Полное имя
$fullName = $field_second_name.' '.$field_first_name.' '.$field_surname; // Поле телефон (поле: field_telephone)
$field_telephone = $wrapper->commerce_customer_billing->field_telephone->value(); // Сумма заказа
$products_total = commerce_currency_format(
$commerce_order->commerce_order_total['und'][0]['data']['components'][0]['price']['amount'],
$commerce_order->commerce_order_total['und'][0]['currency_code']
);

echo

"Заказ No ".$order_id;
echo
"\nФИО: ".$fullName;
echo
"\nАдрес: ".$field_address;
echo
"\nТелефон: ".$field_telephone;

echo

"Список товаров:\n";

foreach(

$line_items as $line_item){
if(
$line_item->type == 'product'){
$product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
// Количество
echo "\n".number_format($line_item->quantity)."x ";
// Заголовок
echo $product->title." ";
/*
Цена: commerce_currency_format($product->commerce_price['und']['0']['amount']
Код валюты(RUB, USD и т.д.): $product->commerce_price['und']['0']['currency_code']
*/
echo commerce_currency_format($product->commerce_price['und']['0']['amount'],$product->commerce_price['und']['0']['currency_code']);
}
}

echo

"\nCумма заказа: " . $products_total;
?>

Поле Address (commerce_customer_address) не использую

Аватар пользователя 1541 1541 10 марта 2013 в 1:31

А коммерц вообще пересылает информацию о заказе админу? А то что то я рыскал целый день не могу найти. Заказы сыпятся, но я о низ узнаю из отчетов платежных систем только.
Если да, то где?

Аватар пользователя Navigator Navigator 10 марта 2013 в 1:44

Создаем новое правило.
Event ставим Completing the checkout process.
Actions ставим Send mail.
Где:
TO Data selector ставим site:mail
SUBJECT ставим Order [commerce-order:order-number] at [site:name]
MESSAGE тот код что я писал выше

Аватар пользователя Navigator Navigator 10 марта 2013 в 1:50

{ "rules_send_an_order_notification_admin_" : {
"LABEL" : "Send an order notification admin ",
"PLUGIN" : "reaction rule",
"WEIGHT" : "10",
"REQUIRES" : [ "rules", "php", "commerce_checkout" ],
"ON" : [ "commerce_checkout_complete" ],
"DO" : [
{ "mail" : {
"to" : [ "site:mail" ],
"subject" : "Order [commerce-order:order-number] at [site:name]",
"message" : "",
"language" : [ "commerce-order:state" ]
}
}
]
}
}

Импортирует правило с пустым "message".

Аватар пользователя Navigator Navigator 10 марта 2013 в 11:33

Оно и не придет, если к Billing information не добавлены поля:

  • field_first_name
  • field_second_name
  • field_surname
  • field_address
  • field_telephone

Как у меня.

Чтобы заработал мой код нужно его изменить убрав все несуществующие поля и добавив свои. Ну или в "message" вставить это:

Заказ No [commerce-order:order-id]
Заказчик: [commerce-order:commerce-customer-billing]
Список товаров:


<?php
$wrapper
= entity_metadata_wrapper('commerce_order', $commerce_order);
// Список товаров
$line_items = $wrapper->commerce_line_items->value();
// Сумма заказа
$products_total = commerce_currency_format(
$commerce_order->commerce_order_total['und'][0]['data']['components'][0]['price']['amount'],
$commerce_order->commerce_order_total['und'][0]['currency_code']
);

foreach(

$line_items as $line_item){
if(
$line_item->type == 'product'){
$product = commerce_product_load($line_item->commerce_product['und'][0]['product_id']);
// Количество
echo "\n".number_format($line_item->quantity)."x ";
// Заголовок
echo $product->title." ";
/*
Цена: commerce_currency_format($product->commerce_price['und']['0']['amount']
Код валюты(RUB, USD и т.д.): $product->commerce_price['und']['0']['currency_code']
*/
echo commerce_currency_format($product->commerce_price['und']['0']['amount'],$product->commerce_price['und']['0']['currency_code']);
}
}

echo

"\nCумма заказа: " . $products_total;
?>
Аватар пользователя yegoren yegoren 2 августа 2013 в 10:41

Вообще, вопрос сейчас решается проще токенами.

Заказанные позиции: [commerce-order:commerce_line_items]
Общая сумма: [commerce-order:commerce_order_total]

Но есть проблема, что список высылается в ужасно раскиданном формате, не удобно смотреть. Вот как отформатировать высылаемый список ещё не нашел решений. Оформление письма, вроде можно сделать модулем http://drupal.org/project/mailsystem, вот здесь вычитал: http://www.drupal.ru/node/88673. Поставил модуль, но не могу разобраться с ним пока что.

А с кодом Navigator-а есть проблема в случае, если к стоимости товара применены скидки правилами - в письме уходит информация без скидки, что не совсем не айс. Может не к тем полям обращаемся?

Так и остается пока не решенным этот вопрос для меня... Sad

Аватар пользователя igorek igorek 13 декабря 2013 в 13:23

Я поставил сборку кикстарт2 и не парюсь оформлением - красивое письмо заказчику.
А чтобы adminu - добавляю мыло админа в хуке своего модуля (к письму заказчика)

<?php
/**
* Implements hook_mail_alter().
*/
function mymodule_mail_alter(&$message) {
dsm($message);
if(
$message['key'] == 'commerce_order_order_confirmation') {
$message['to'] .= ','.variable_get('site_mail');
}
}
?>
Логотип drupal.ru

Содержимое сайта публикуется на условиях CreativeCommons Attribution-ShareAlike 3.0 или более поздней версии. Программные коды в тексте статей — на условиях GNU GPL v2 или более поздней версии.

Документация по совместной работе с репозиторием drupal.ru – https://docs.drupal.ru/code

Drupal – торговая марка Дриса Бёйтарта

12+

AltStyle によって変換されたページ (->オリジナル) /