Commit 733e96df authored by Gorodkov Denis's avatar Gorodkov Denis

commerce

parent 26c69ee8
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
"drupal/bootstrap": "^3.24", "drupal/bootstrap": "^3.24",
"drupal/commerce": "^2.30", "drupal/commerce": "^2.30",
"drupal/commerce_cart_api": "^1.5", "drupal/commerce_cart_api": "^1.5",
"drupal/commerce_shipping": "^2.4",
"drupal/commerce_stock": "^1.0",
"drupal/config_ignore": "^2.3", "drupal/config_ignore": "^2.3",
"drupal/config_pages": "^2.9", "drupal/config_pages": "^2.9",
"drupal/core": "^9.1", "drupal/core": "^9.1",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "da602181809e457541585060ee584c63", "content-hash": "d57ba08c5cb54e2299992757b090cecc",
"packages": [ "packages": [
{ {
"name": "asm89/stack-cors", "name": "asm89/stack-cors",
...@@ -2678,6 +2678,141 @@ ...@@ -2678,6 +2678,141 @@
"source": "https://git.drupalcode.org/project/commerce" "source": "https://git.drupalcode.org/project/commerce"
} }
}, },
{
"name": "drupal/commerce_shipping",
"version": "2.4.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/commerce_shipping.git",
"reference": "8.x-2.4"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/commerce_shipping-8.x-2.4.zip",
"reference": "8.x-2.4",
"shasum": "959f0b79bcd06d7f43776570c89d2a862075fa35"
},
"require": {
"drupal/commerce": "^2.29",
"drupal/commerce_order": "*",
"drupal/commerce_price": "*",
"drupal/core": "^9.2 || ^10",
"drupal/physical": "^1.0"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-2.4",
"datestamp": "1652265611",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0+"
],
"authors": [
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "googletorp",
"homepage": "https://www.drupal.org/user/386230"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
}
],
"description": "Provides shipping functionality for Commerce.",
"homepage": "http://drupal.org/project/commerce_shipping",
"support": {
"source": "https://git.drupalcode.org/project/commerce_shipping"
}
},
{
"name": "drupal/commerce_stock",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/commerce_stock.git",
"reference": "8.x-1.0"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/commerce_stock-8.x-1.0.zip",
"reference": "8.x-1.0",
"shasum": "16d267a34122a8c87a567c5eae5619b023288f5f"
},
"require": {
"drupal/commerce": "~2.0",
"drupal/commerce_order": "*",
"drupal/commerce_product": "*",
"drupal/core": "^8 || ^9"
},
"require-dev": {
"drupal/commerce_product": "*",
"drupal/commerce_stock_local": "*"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.0",
"datestamp": "1642166789",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0+"
],
"authors": [
{
"name": "guy_schneerson",
"homepage": "https://www.drupal.org/user/755184"
},
{
"name": "iAugur",
"homepage": "https://www.drupal.org/user/750068"
},
{
"name": "olafkarsten",
"homepage": "https://www.drupal.org/user/352745"
},
{
"name": "rfay",
"homepage": "https://www.drupal.org/user/30906"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
}
],
"description": "Provides a stock management framework based on rules to manage stock levels of commerce products",
"homepage": "https://www.drupal.org/project/commerce_stock",
"keywords": [
"Drupal"
],
"support": {
"source": "http://cgit.drupalcode.org/commerce_stock",
"issues": "http://drupal.org/project/issues/commerce_stock"
}
},
{ {
"name": "drupal/commerce_store", "name": "drupal/commerce_store",
"version": "2.30.0", "version": "2.30.0",
...@@ -4691,6 +4826,66 @@ ...@@ -4691,6 +4826,66 @@
"documentation": "https://www.drupal.org/docs/8/modules/pathauto" "documentation": "https://www.drupal.org/docs/8/modules/pathauto"
} }
}, },
{
"name": "drupal/physical",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/physical.git",
"reference": "8.x-1.1"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/physical-8.x-1.1.zip",
"reference": "8.x-1.1",
"shasum": "31cbf61c3ead4ab655b1ec56fdc3bcbe9331a751"
},
"require": {
"drupal/core": "^8.7.7 || ^9"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.1",
"datestamp": "1581940864",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0+"
],
"authors": [
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "czigor",
"homepage": "https://www.drupal.org/user/826222"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
}
],
"description": "Physical supplies such fields as physical weight and dimensions.",
"homepage": "http://drupal.org/project/physical",
"support": {
"source": "https://git.drupalcode.org/project/physical"
}
},
{ {
"name": "drupal/profile", "name": "drupal/profile",
"version": "1.4.0", "version": "1.4.0",
...@@ -8388,6 +8583,7 @@ ...@@ -8388,6 +8583,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"abandoned": "symfony/error-handler",
"time": "2022-04-12T15:19:55+00:00" "time": "2022-04-12T15:19:55+00:00"
}, },
{ {
......
add-cart:
js:
js/addCart.js: {}
dependencies:
- core/jquery
- core/jquery.once
...@@ -7,7 +7,10 @@ ...@@ -7,7 +7,10 @@
use Drupal\Core\Ajax\AlertCommand; use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Access\AccessResult; use Drupal\Core\Access\AccessResult;
use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityInterface;
/** /**
...@@ -66,27 +69,25 @@ function mymodule_form_contact_message_feedback_form_alter(&$form, \Drupal\Core\ ...@@ -66,27 +69,25 @@ function mymodule_form_contact_message_feedback_form_alter(&$form, \Drupal\Core\
} }
} }
function ajaxCallback($form, $form_state) {
$response = new AjaxResponse();
#$response->addCommand(new AlertCommand('Hello'));
return $response;
}
/** /**
* Implements hook_form_alter(). * Implements hook_form_alter().
*/ */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$user = Drupal::currentUser(); $user = Drupal::currentUser();
$store = Drupal::entityTypeManager()->getStorage('commerce_stock_location')->getEntityType('1');
$str = 'commerce_order_item_add_to_cart_form_commerce_product'; $str = 'commerce_order_item_add_to_cart_form_commerce_product';
if (strripos($form_id, $str) === 0) { if (strripos($form_id, $str) === 0) {
$form['#attributes']['class'][] = 'test'; unset($form['#submit']);
unset($form['actions']);
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';
$form['actions']['submit'] = array( $form['actions']['submit'] = array(
'#attributes' => [
'class' => 'add-cart-drupal-commerce'
],
'#type' => 'submit', '#type' => 'submit',
'#value' => 'Добавить в корзину', '#value' => 'Добавить в корзину',
'#ajax' => [ '#ajax' => [
'callback' => 'ajaxCallback', 'callback' => 'addProductInCart',
'event' => 'click', 'event' => 'click',
], ],
); );
...@@ -109,6 +110,19 @@ function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_ ...@@ -109,6 +110,19 @@ function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_
} }
} }
function addProductInCart(array &$form, FormStateInterface $form_state) {
$variation = $form_state->getValue('purchased_entity');
$variation = $variation[0]['variation'];
$response = new AjaxResponse();
$selector = "button[name*='op']";
$method = 'addProductInCart';
$arguments = [$variation];
$response->addCommand(new InvokeCommand($selector, $method, $arguments));
return $response;
}
/** /**
* Implements hook_node_view(). * Implements hook_node_view().
*/ */
......
...@@ -11,3 +11,8 @@ services: ...@@ -11,3 +11,8 @@ services:
arguments: ['@entity_type.manager'] arguments: ['@entity_type.manager']
tags: tags:
- { name: authentication_provider, provider_id: 'x-csrf', priority: 100, global: TRUE } - { name: authentication_provider, provider_id: 'x-csrf', priority: 100, global: TRUE }
mymodule.normalize:
class: Drupal\mymodule\Normalizer\CustomTypedDataNormalizer
arguments: ['@current_route_match']
tags:
- { name: normalizer, priority: 10 }
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class ProductForm extends FormBase {
public $id;
public $prices;
public function getFormId() {
return 'mymodule_product_form';
}
public function buildForm(array $form, FormStateInterface $form_state, $card = NULL) {
$this->prices = $card['price'];
$id = $card['id'];
$form[$id]['card']['title'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $card['title'],
'#attributes' => [
'class' => ["card_title-$id"]
]
];
$form[$id]['card']['price'] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $card['price'][0],
'#attributes' => [
'class' => ["card_price-$id"]
]
];
$form[$id]['card']['form']['size'] = [
'#type' => 'select',
'#title' => 'Size',
'#options' => $card['options'],
'#ajax' => [
'callback' => '::changePrice',
'event' => 'change',
],
];
$form[$id]['card']['form']['button'] = [
'#type' => 'submit',
'#value' => 'Добавить в корзину',
'#ajax' => [
'callback' => '::alert',
'event' => 'click',
],
'#attributes' => [
'class' => ["card_button-$id"]
]
];
return $form;
}
public function SubmitForm(array &$form, FormStateInterface $form_state) {
}
public function changePrice(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$count = $form_state->getValue('size');
$price = $this->prices;
$response->addCommand(new HtmlCommand(".card_price-$this->id", "$price[$count]"));
return $response;
}
public function alert(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$response->addCommand(new AlertCommand('Hello'));
return $response;
}
}
<?php
namespace Drupal\mymodule\Normalizer;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\serialization\Normalizer\NormalizerBase;
class CustomTypedDataNormalizer extends NormalizerBase {
protected $supportedInterfaceOrClass = 'Drupal\commerce_order\Entity\Order';
public function normalize($cart, $format = NULL, array $context = array()) {
$order_items = $cart->getItems();
$total_price = $cart->getTotalPrice()->toArray();
foreach ($order_items as $order_item) {
$price = $order_item->getTotalPrice()->toArray();
$referenses = $order_item->referencedEntities();
foreach ($referenses as $referens) {
$referens_arr = $referens->toArray();
if (!empty($referens_arr['attribute_size'])) {
$size = $referens->getAttributeValue('attribute_size')->label();
}
if (!empty($referens_arr['product_id'])) {
$product = $referens->getProduct();
if ($product->hasField('field_node')) {
$node = $product->get('field_node')->referencedEntities();
$node = $node[0];
$media = $node->get('field_media')->referencedEntities();
$media = $media[0];
$uri = $media->get('field_media_image')->entity->getFileUri();
$uri = explode('//', $uri);
}
}
}
$items[] = [
'name' => $product->label(),
'quantity' => $order_item->getQuantity(),
'attribute_size' => $size,
'item_total_price' => $price,
'uri' => $uri[1],
];
}
$data = [
'items' => $items,
'total_price' => $total_price,
];
return $data;
}
}
...@@ -23,7 +23,7 @@ class ContextDefinition extends BlockBase { ...@@ -23,7 +23,7 @@ class ContextDefinition extends BlockBase {
$node = $this->getContextValue('node'); $node = $this->getContextValue('node');
$term = $this->getContextValue('term'); $term = $this->getContextValue('term');
$build = ['#markup' => 'Hello, From mymodule/Block']; $build = ['#markup' => 'Hello, From mymodule/Block'];
if (!empty($node) and !empty($term)) { if (!empty($node) or !empty($term)) {
empty($node) ? $entiy = $term : $entiy = $node; empty($node) ? $entiy = $term : $entiy = $node;
empty($node) ? $entiy_type_id = 'taxonomy_term' : $entiy_type_id = 'node'; empty($node) ? $entiy_type_id = 'taxonomy_term' : $entiy_type_id = 'node';
$build = \Drupal::entityTypeManager()->getViewBuilder($entiy_type_id)->view($entiy, 'teaser'); $build = \Drupal::entityTypeManager()->getViewBuilder($entiy_type_id)->view($entiy, 'teaser');
......
...@@ -28,83 +28,66 @@ class ProductsSuggest extends BlockBase { ...@@ -28,83 +28,66 @@ class ProductsSuggest extends BlockBase {
public function build() { public function build() {
$node = $this->getContextValue('node'); $node = $this->getContextValue('node');
$node_id = $node->id(); $node_id = $node->id();
$card_id = 1;
$products = \Drupal::entityTypeManager() $products = \Drupal::entityTypeManager()
->getStorage('commerce_product') ->getStorage('commerce_product')
->loadByProperties(['field_node' => $node_id]); ->loadByProperties(['field_node' => $node_id]);
foreach ($products as $product) { foreach ($products as $product) {
$test = \Drupal::entityTypeManager() unset($card);
->getViewBuilder('commerce_product') $card['id'] = $card_id;
->view($product, 'cart'); $card['title'] = $product->label();
$label = $product->label();
$variations = $product->getVariations(); $variations = $product->getVariations();
unset($options);
foreach ($variations as $variation) { foreach ($variations as $variation) {
if (empty($price)) { $card['price'][] = $variation->getPrice();
$price = $variation->getPrice(); $price = $variation->getPrice();
}
$attribute = $variation->getAttributeValue('attribute_size'); $attribute = $variation->getAttributeValue('attribute_size');
$options[] = $attribute->label(); $card['options'][] = $attribute->label();
} }
#$build[$card_id][] = $this->buildForm($card);
$build[$label]['card'] = [ #$build[] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ProductForm', $card);
'#type' => 'container', #$card_id++;
'#attributes' => [ $build[] = \Drupal::entityTypeManager()->getViewBuilder('commerce_product')->view($product, 'cart');
'class' => ['card']
]
];
$build[$label]['card']['title'] = [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $label,
'#attributes' => [
'class' => ['card_title']
]
];
$build[$label]['card']['price'] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $price,
'#attributes' => [
'class' => ['card_price']
]
];
$build[$label]['card']['form'] = [
'#type' => 'form',
'#attributes' => [
'action' => '#'
]
];
$build[$label]['card']['form']['size'] = [
'#type' => 'select',
'#title' => 'Size',
'#options' => $options,
];
$build[$label]['card']['form']['button'] = [
'#type' => 'submit',
'#value' => 'Добавить в корзину',
'#ajax' => [
'callback' => '::changePrice',
'event' => 'click',
],
];
} }
empty($products) ? $build = ['#markup' => 'Ничего не найдено'] : ''; empty($products) ? $build = ['#markup' => 'Ничего не найдено'] : '';
return $build; return $build;
} }
public function changePrice() { public function buildForm($card) {
$response = new AjaxResponse(); $id = $card['id'];
$response->addCommand(new AlertCommand('Hello')); $build[$id]['card']['title'] = [
return $response; '#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $card['title'],
'#attributes' => [
'class' => ["card_title-$id"]
]
];
$build[$id]['card']['price'] = [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $card['price'][0],
'#attributes' => [
'class' => ["card_price-$id"]
]
];
$build[$id]['card']['form']['size'] = [
'#type' => 'select',
'#title' => 'Size',
'#options' => $card['options'],
];
$build[$id]['card']['form']['button'] = [
'#type' => 'submit',
'#value' => 'Добавить в корзину',
'#attributes' => [
'class' => ["card_button-$id"]
]
];
return $build;
} }
} }
(function ($) { (function ($) {
Drupal.behaviors.addCartBehavior = { Drupal.behaviors.addCartBehavior = {
attach: function (context, settings) { attach: function (context, settings) {
$(context).find('.custom-drupal-mymodule').once('hello').on("click", function () { $.prototype.addProductInCart = function (id) {
var src = '/sites/default/files/styles/large/public/';
var query_add_cart = [{
"purchased_entity_type": "commerce_product_variation",
"purchased_entity_id": id,
"quantity": "1"
}];
$.ajax({ $.ajax({
url: 'http://project.loc/cart?_format=json', url: '/cart/add?_format=json',
method: 'get', method: 'post',
dataType: 'html', data: JSON.stringify(query_add_cart),
headers: {'Content-type': 'application/json'}, headers: {'Content-Type': 'application/json'},
data: {text: 'Текст'},
success: function(data){ success: function(data){
alert(data); var order_id = data[0]['order_id'];
var get_request = '/cart/' + order_id + '?_format=json';
$.get(get_request, function(data) {
console.log(data);
var content = '<div class="cart">';
data['items'].forEach(function (item) {
img_attr = 'width="60" height="60" src="' + src + item['uri'] +'"';
img = '<div class="item-img-container"><img ' + img_attr + '></div>';
content = content + '<div class="card">'
content = content + '<div class="item-img-container">' + img + '</div>';
content = content + '<div class="item-name">Наименование товара: ' + item['name'] + '</div>';
content = content + '<div class="item-count">Количество: ' + Math.round(item['quantity']) + '</div>';
content = content + '<div class="item-attribute-size">Размер: ' + item['attribute_size'] + '</div>';
content = content + '<div class="item-price">Сумма: ' + parseFloat(item['item_total_price']['number']).toFixed(2) + ' ' + item['item_total_price']['currency_code'] + '</div>';
content = content + '</div>';
});
total_price_cart = data['total_price']['number'];
total_price_cart = parseFloat(total_price_cart).toFixed(2);
content = content + '<div class="total_price">';
content = content + 'Общая сумма: ' + total_price_cart + data['total_price']['currency_code'];
content = content + '</div>';
content = content + '</div>';
var myDialog = $(content).appendTo('body');
Drupal.dialog(myDialog, {
title: 'Cart',
buttons: [{
text: 'Close',
click: function() {
$(this).dialog('close');
}
}]
}).showModal();
});
} }
}); });
}) }
} }
}; };
})(jQuery); })(jQuery);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment