Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing hyva compatibility #357

Merged
merged 1 commit into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Controller/Product/AddToCart.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public function execute()

$params = new DataObject($params);
$result = $quote->addProduct($product, $params);
$resultJson = $this->resultJsonFactory->create();

if (is_a($result, QuoteItem::class)) {
//Update totals
Expand All @@ -90,12 +91,13 @@ public function execute()
$quote->collectTotals();
$this->cartRepository->save($quote);
$session->replaceQuote($quote)->unsLastRealOrderId();

return $resultJson->setData(['success' => true]);
} else {
$this->logger->info("This product is variable, return the url");
$product_url = $product->getProductUrl();
$this->logger->info("Product url: ", ["product_url" => $product_url]);

$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData(['product_url' => $product_url]);
}
}
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "doofinder/doofinder-magento2",
"version": "0.15.0",
"version": "1.0.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think that this PR contains breaking changes to a degree that you have to declare it as a major version change? 😱

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Jaja, realmente no debería haber ningún breaking change, solamente "fixing" changes. Era porque estaba comentando con @sofia-doofinder que en algún momento podríamos poner la 1.0.0 y habíamos comentado que quizá era un bueno momento.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yo me esperaría a una más grande, pero bueno, como el código funciona lo apruebo 😄

"description": "Doofinder module for Magento 2",
"type": "magento2-module",
"require": {
Expand Down
2 changes: 1 addition & 1 deletion etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Doofinder_Feed" setup_version="0.15.0">
<module name="Doofinder_Feed" setup_version="1.0.0">
<sequence>
<module name="Magento_Integration" />
</sequence>
Expand Down
21 changes: 21 additions & 0 deletions view/frontend/layout/hyva_default.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?xml version="1.0"?>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ogomezba una pregunta, esto así se importa sólo cuando se detecta que existe el tema hyva?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hola @sofia-doofinder ! Sí, justo lo comentaba en la descripción del PR. Según comentan en la documentación de hyva aquí, una de las cosas que hace el tema es crear layout handles por cada uno de los que ya se tengan pero añadiendo el hyva_ delante. Aunque mi conocimiento de los detalles de Magento es el que es, por lo que he entendido, los handles vienen a ser los layout.xml que se usan y se calculan matcheando la ruta con el nombre del archivo layout (excepto el default que parece que afecta a todos). Entonces, como se matchea por nombre, al llamarse el archivo hyva_default.xml, en temas normales no va a matchear nada por lo que no se carga. No obstante, el tema hyva parece que modifica este comportamiento y matchea también "hyva_lo_que_toque_por_ruta.xml". Entonces, para temas hyva sí que se añade.

De todas formas, he probado este comportamiento en la tienda del cliente con hyva y en mi tienda local sin hyva y he visto que se comportaba así.

image

image

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<!-- For hyva themes, jQuery can't be used among other modifications.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent approach!! 🏆

In that case we use a different JS -->
<remove src="Doofinder_Feed::js/df_add_to_cart.js"/>
<script src="Doofinder_Feed::js/df_add_to_cart_hyva.js"/>
</head>
<body>
<referenceBlock name="head.additional">
<block
class="Doofinder\Feed\Block\Display\Layer"
name="doofinderfeed_display_layer"
as="doofinderfeed.display.layer"
template="Doofinder_Feed::display/layer.phtml"
ifconfig="doofinder_config_config/doofinder_layer/doofinder_layer_enabled"
after="-"/>
</referenceBlock>
</body>
</page>
60 changes: 60 additions & 0 deletions view/frontend/web/js/df_add_to_cart_hyva.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
class DoofinderAddToCartError extends Error {
constructor(reason, status = "") {
const message =
"Error adding an item to the cart. Reason: " +
reason +
". Status code: " +
status;
super(message);
this.name = "DoofinderAddToCartError";
}
}

document.addEventListener("doofinder.cart.add", function (event) {
const { item_id, amount, statusPromise } = event.detail;
addToCart(item_id, amount, statusPromise);
});

function addToCart(item_id, amount, statusPromise) {
amount = !amount ? 1 : parseInt(amount);
item_id = parseInt(item_id);

const params = new URLSearchParams({
form_key: hyva.getFormKey(),
id: item_id,
qty: amount,
});

fetch(`${BASE_URL}doofinderfeed/Product/AddToCart?${params.toString()}`, {
method: "POST",
})
.then((response) => {
if (!response.ok) {
return response.text().then((error) => {
throw new Error(error);
});
}

return response.json();
})
.then((data) => {
if (data.product_url) {
statusPromise.reject(
new DoofinderAddToCartError(
"Configurable product. Redirecting to product URL",
200,
),
);
window.location = data.product_url;
return;
}

statusPromise.resolve(
"The item has been successfully added to the cart.",
);
dispatchEvent(new Event("reload-customer-section-data"));
})
.catch((error) => {
statusPromise.reject(new DoofinderAddToCartError(error));
});
}
Loading