Skip to content

Commit

Permalink
Normalized event products data
Browse files Browse the repository at this point in the history
  • Loading branch information
Franck Allimant committed Nov 20, 2023
1 parent 324b2ab commit 7857ac4
Show file tree
Hide file tree
Showing 8 changed files with 252 additions and 172 deletions.
24 changes: 0 additions & 24 deletions Api/BrevoClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,28 +150,4 @@ public function unsubscribe(string $email)

return $change ? $this->contactApi->getContactInfoWithHttpInfo($email) : $contact;
}

/**
* @throws \JsonException
*/
public function getCustomerAttribute($customerId): array
{
$mappingString = ConfigQuery::read(Brevo::BREVO_ATTRIBUTES_MAPPING);

if (empty($mappingString)) {
return [];
}

if (null === $mapping = json_decode($mappingString, true)) {
throw new TheliaProcessException('Customer attribute mapping error: JSON data seems invalid, pleas echeck syntax.');
}

return $this->getMappedValues(
$mapping,
'customer_query',
'customer',
'customer.id',
$customerId,
);
}
}
2 changes: 1 addition & 1 deletion Config/module.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<language>en_US</language>
<language>fr_FR</language>
</languages>
<version>1.1.12</version>
<version>1.1.13</version>
<authors>
<author>
<name>Chabreuil Antoine</name>
Expand Down
49 changes: 20 additions & 29 deletions EventListeners/CartListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Brevo\Services\BrevoApiService;
use Brevo\Services\BrevoOrderService;
use Brevo\Services\BrevoProductService;
use Brevo\Trait\DataExtractorTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Thelia\Core\Event\Cart\CartEvent;
Expand All @@ -28,6 +29,8 @@

class CartListener implements EventSubscriberInterface
{
use DataExtractorTrait;

public function __construct(
private RequestStack $requestStack,
private BrevoApiService $brevoApiService,
Expand All @@ -40,17 +43,21 @@ public static function getSubscribedEvents()
{
return [
TheliaEvents::CART_ADDITEM => ['trackUpdateCartEvent', 128],
TheliaEvents::CART_UPDATEITEM => ['trackUpdateCartEvent', 128],
TheliaEvents::CART_DELETEITEM => ['trackUpdateCartEvent', 128],

TheliaEvents::CART_CLEAR => ['trackDeleteCartEvent', 128],

TheliaEvents::ORDER_PAY => ['trackNewOrderEvent', 110],

TheliaEvents::ORDER_UPDATE_STATUS => ['updateStatus', 110],
];
}

public function updateStatus(OrderEvent $orderEvent): void
{
/** @var Lang $lang */
$lang = $this->requestStack->getCurrentRequest()?->getSession()->get('thelia.current.lang');
$lang = $this->requestStack->getCurrentRequest()?->getSession()->getLang();

$order = $orderEvent->getOrder();

Expand All @@ -73,34 +80,22 @@ public function trackNewOrderEvent(OrderEvent $event): void

$customer = $order->getCustomer();

$properties = [];

$email = null;
$properties = $this->getCustomerAttribute($customer->getId());

if ($customer !== null) {
$email = $customer->getEmail();
$properties = [
'email' => $customer->getEmail(),
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
];
}

/** @var Currency $currency */
$currency = $order->getCurrency();

/** @var Lang $lang */
$lang = $this->requestStack->getCurrentRequest()?->getSession()->get('thelia.current.lang');
$lang = $this->requestStack->getCurrentRequest()?->getSession()->getLang();

$data = [
'email' => $email,
'email' => $customer->getEmail(),
'properties' => $properties,
'eventdata' => [
'id' => sprintf('order:%s', $order->getId()),
'id' => $order->getRef(),
'data' => [
'total' => $order->getTotalAmount($tax, true, true),
'currency' => $currency->getCode(),
'items' => $this->brevoProductService->getItemsByOrder($order, $lang->getLocale()),
'items' => $this->brevoProductService->getOrderItems($order),
],
],
];
Expand All @@ -117,21 +112,17 @@ public function trackNewOrderEvent(OrderEvent $event): void
protected function trackCart(CartEvent $event, $eventName): void
{
/** @var Customer $customer */
$customer = $this->requestStack->getCurrentRequest()?->getSession()?->get('thelia.customer_user');
if (null === $customer = $this->requestStack->getCurrentRequest()?->getSession()?->getCustomerUser()) {
// No tracking if customer is not logged in, as Brevo requires an email in e-commerce tracking events.
return;
}

$cart = $event->getCart();

$properties = [];

$email = null;

if ($customer !== null) {
$email = $customer->getEmail();
$properties = [
'email' => $customer->getEmail(),
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
];
$properties = $this->getCustomerAttribute($customer->getId());
}

/** @var Currency $currency */
Expand All @@ -143,14 +134,14 @@ protected function trackCart(CartEvent $event, $eventName): void
$lang = $this->requestStack->getCurrentRequest()?->getSession()->get('thelia.current.lang');

$data = [
'email' => $email,
'email' => $customer->getEmail(),
'properties' => $properties,
'eventdata' => [
'id' => sprintf('cart:%s', $cart->getId()),
'data' => [
'total' => $cart->getTaxedAmount($country),
'currency' => $currency->getCode(),
'items' => $this->brevoProductService->getItemsByCart($cart, $lang->getLocale(), $country),
'items' => $this->brevoProductService->getCartItems($cart, $lang->getLocale(), $country),
],
],
];
Expand Down
9 changes: 7 additions & 2 deletions Form/BrevoConfigurationForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ protected function buildForm(): void
$defaultCustomerMapping = <<< END
{
"customer_query": {
"_comment" : "You can map here Brevo contact attributes to Thelia customer data."
"EMAIL" : {
"select" : "customer.email"
}
Expand All @@ -70,6 +71,10 @@ protected function buildForm(): void
$defaultMetadataMapping = <<< END
{
"product_query": {
"_comment" : "You can add here some fields to standard Brevo data, or override some standard fields (e.g., 'price')"
},
"product_metadata_query": {
"_comment" : "You can define here some metat data attributes, that will be placed in the 'metaInfo' field"
}
}
END;
Expand Down Expand Up @@ -142,14 +147,14 @@ protected function buildForm(): void
'data' => ConfigQuery::read(Brevo::BREVO_ATTRIBUTES_MAPPING, $defaultCustomerMapping),
])
->add('metadata_mapping', TextareaType::class, [
'label' => $translator->trans('Products metadata attributes mapping', [], Brevo::MESSAGE_DOMAIN),
'label' => $translator->trans('Products attributes mapping', [], Brevo::MESSAGE_DOMAIN),
'attr' => [
'rows' => 10
],
'label_attr' => [
'for' => 'attributes_mapping',
'help' => Translator::getInstance()->trans(
'This is a mapping of Brevo products meta-data attributes with Thelia products attributes. Do not change anything here if you do not know exactly what you are doing',
'This is a mapping of Brevo products data and meta-data attributes with Thelia products attributes. Do not change anything here if you do not know exactly what you are doing',
[],
Brevo::MESSAGE_DOMAIN
)
Expand Down
18 changes: 12 additions & 6 deletions Services/BrevoApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,25 @@ private function sendRequest($method, $url, $data = [], $headers = [])
$rawResponse = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);

$jsonResponse = json_decode($rawResponse, true);

$response = [
'data' => $rawResponse,
'data' => $jsonResponse,
'status' => $status,
];

$error = curl_error($curl);

$response['success'] = !$error && $status == 200;
$response['success'] = !$error && substr((string) $status, 0, 1) === '2';

if (! $response['success']) {
$errorMessage = !empty($error) ? $error : (($jsonResponse && $jsonResponse['message']) ? $jsonResponse['message'] : 'Undefined error');

if ($error) {
Tlog::getInstance()->error($error);
Tlog::getInstance()->error(
"Brevo API call error : Status: $status, error: $errorMessage"
);

$response['error'] = $error;
$response['error'] = $errorMessage;
}

curl_close($curl);
Expand All @@ -100,4 +106,4 @@ public function enableEcommerce()
{
return $this->sendPostEvent('https://api.brevo.com/v3/ecommerce/activate');
}
}
}
49 changes: 25 additions & 24 deletions Services/BrevoOrderService.php
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
<?php

/*
* This file is part of the Thelia package.
* http://www.thelia.net
*
* (c) OpenStudio <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Brevo\Services;

use Brevo\Api\BrevoClient;
use Thelia\Log\Tlog;
use Thelia\Model\Base\ProductQuery;
use Thelia\Model\Cart;
use Thelia\Model\Category;
use Thelia\Model\CategoryQuery;
use Thelia\Model\Country;
use Thelia\Model\Currency;
use Thelia\Model\Order;
use Thelia\Model\OrderProduct;
use Thelia\Model\Product;
use Thelia\Model\ProductImageQuery;
use Thelia\Model\ProductSaleElementsQuery;
use Thelia\Tools\URL;
use function Clue\StreamFilter\fun;

class BrevoOrderService
{
public function __construct(private BrevoApiService $brevoApiService)
public function __construct(
private BrevoApiService $brevoApiService,
private BrevoProductService $brevoProductService,
)
{
}

public function exportOrder(Order $order, $locale)
public function exportOrder(Order $order, $locale): void
{
$data = $this->getOrderData($order, $locale);

Expand All @@ -35,7 +38,7 @@ public function exportOrder(Order $order, $locale)
}
}

public function exportOrderInBatch($limit, $offset, $locale)
public function exportOrderInBatch($limit, $offset, $locale): void
{
$orders = ProductQuery::create()
->setLimit($limit)
Expand All @@ -58,7 +61,7 @@ public function exportOrderInBatch($limit, $offset, $locale)
}
}

public function getOrderData(Order $order, $locale)
protected function getOrderData(Order $order, $locale)
{
$invoiceAddress = $order->getOrderAddressRelatedByInvoiceOrderAddressId();
$addressCountry = $invoiceAddress->getCountry();
Expand All @@ -69,6 +72,7 @@ public function getOrderData(Order $order, $locale)
}, $order->getOrderCoupons()->toArray());

return [
'email' => $order->getCustomer()->getEmail(),
'products' => $this->getOrderProductsData($order),
'billing' => [
'address' => $invoiceAddress->getAddress1(),
Expand All @@ -80,29 +84,26 @@ public function getOrderData(Order $order, $locale)
'region' => $addressCountry->getTitle(),
],
'coupon' => $coupons,
'id' => (string)$order->getId(),
'createdAt' => $order->getCreatedAt()->format("Y-m-d\TH:m:s\Z"),
'updatedAt' => $order->getUpdatedAt()->format("Y-m-d\TH:m:s\Z"),
'id' => $order->getRef(),
'createdAt' => $order->getCreatedAt()?->format("Y-m-d\TH:m:s\Z"),
'updatedAt' => $order->getUpdatedAt()?->format("Y-m-d\TH:m:s\Z"),
'status' => $order->getOrderStatus()->getCode(),
'amount' => round($order->getTotalAmount($tax), 2),
'email' => $order->getCustomer()->getEmail()
];
}

protected function getOrderProductsData(Order $order)
{
$orderProductsData = [];
foreach ($order->getOrderProducts() as $orderProduct) {
$pse = ProductSaleElementsQuery::create()->findPk($orderProduct->getProductSaleElementsId());
$orderProductsData[] = [
'productId' => (string)$pse->getId(),
'productId' => $orderProduct->getProductRef(),
'quantity' => $orderProduct->getQuantity(),
'variantId' => (string)$orderProduct->getProductSaleElementsId(),
'price' => round((float)$orderProduct->getPrice(), 2)
// 'variantId' => (string) $orderProduct->getProductSaleElementsId(),
'price' => round((float) $orderProduct->getPrice(), 2),
];
}

return $orderProductsData;
}

}
}
Loading

0 comments on commit 7857ac4

Please sign in to comment.