Skip to content

Instantly share code, notes, and snippets.

@andronex
Last active June 17, 2019 13:34
Show Gist options
  • Save andronex/ec60aa0e1669eb30c7d4ee2775e6eb38 to your computer and use it in GitHub Desktop.
Save andronex/ec60aa0e1669eb30c7d4ee2775e6eb38 to your computer and use it in GitHub Desktop.
msMiniDiscount - организация скидок в miniShop2 (для MODX) по одноразовым купонам.

1. Создать конфигурацию MIGX с импортом конфига migx.json
2. Создать TV типа migx с указанием названия созданной конфигурации MIGX
3. В конфиге MIGX в коде для кнопки button заменить в селекторе #migxdb-panel-object-80 число 80 на ID нужного TV поля из пункта 2
4. Подключить в админке jQuery и jQuery Mask Plugin с помощью MODX плагина adminka.php
5. Добавить на страницу оформления заказа поле для ввода кода купона: <div class="form-group input-parent"> <input type="koupon_code" id="koupon_code" placeholder="Скидочный купон" name="koupon_code" value="[[+koupon_code]]" class="koupon-code form-control"> </div>
6. Добавить обработку и вывод в заказе введённого кода купона плагином coupons.php
7. Добавить JS код из custom.js для пересчёта стоимости товаров в корзине после корректного ввода кода купона
8. Добавить в лексиконы ms2_properties_название_поля_купона (в примере ms2_properties_koupon_code) - для отображения в карточке заказа
VK / i.modx@ya.ru
<?php
$eventName = $modx->event->name;
switch($eventName) {
case 'OnDocFormPrerender':
$modx->controller->addHtml('<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>');
break;
}
return;
<?php
/*
* Изменить логику скидки и ID TV / ID Resource под свои нужды
*/
switch ($modx->event->name) {
case 'msOnBeforeAddToOrder':
if ($key == 'koupon_code' && !empty($value)) {
$check = false;
$tvr = $modx->getObject('modTemplateVarResource', array(
'tmplvarid' => 80,
'contentid' => 1
));
if ($tvr) {
$value_tv = $tvr->get('value');
}
else{
$modx->event->output('Неверный код купона!');
return;
}
if(stristr($value_tv, $value) === FALSE) {
$check = false;
}
else{
$tv_array = json_decode($value_tv, true);
foreach($tv_array as $tv_val){
if($tv_val['code'] == $value && !$tv_val['active']){
$check = true;
break;
}
}
}
if ($check !== true) {
$modx->event->output('Неверный код купона!');
}
}
break;
case 'msOnGetOrderCost':
if (!empty($with_cart) && !empty($cost)) {
if ($data = $order->get()) {
if (!empty($data['koupon_code'])) {
$tvr = $modx->getObject('modTemplateVarResource', array(
'tmplvarid' => 80,
'contentid' => 1
));
if ($tvr) {
$value_tv = $tvr->get('value');
if(stristr($value_tv, $data['koupon_code']) === FALSE) {
$check = false;
}
else{
$tv_array = json_decode($value_tv, true);
$discount = 0;
$cost_all = $cost_full = 0;
foreach($tv_array as $tv_val){
if($tv_val['code'] == $data['koupon_code'] && !$tv_val['active']){
$check = true;
$discount = $tv_val['percent'];
$cart_goods = $cart->get();
foreach($cart_goods as $cart_good){
if($good = $modx->getObject('msProduct', $cart_good['id'])){
if($good->get('price') < $good->get('old_price')){
$cost_full = $cost_full + $cart_good['price'] * $cart_good['count'];
continue;
}
$cost_all = $cost_all + $cart_good['price'] * $cart_good['count'];
}
}
break;
}
}
if($cost_all){
$newcost = $cost_all - $discount;
$percent = ($cost_all - $newcost) / $cost_all * 100;
$newcost = $newcost + $cost_full;
if ($newcost >= 0 && $percent <= 15) {
$modx->event->returnedValues['cost'] = $newcost;
}
}
}
}
}
}
}
break;
case 'msOnCreateOrder':
if ($data = $order->get()) {
if (!empty($data['koupon_code'])) {
$tvr = $modx->getObject('modTemplateVarResource', array(
'tmplvarid' => 80,
'contentid' => 1
));
if ($tvr) {
$value_tv = $tvr->get('value');
if(stristr($value_tv, $data['koupon_code']) === FALSE) {
$check = false;
}
else{
$tv_array = json_decode($value_tv, true);
foreach($tv_array as &$tv_val){
if($tv_val['code'] == $data['koupon_code'] && !$tv_val['active']){
$check = true;
$tv_val['active'] = 1;
$tv_val['activatedon'] = date('Y-m-d H:i:s');
$tv_val['order_id'] = $msOrder->get('id');
break;
}
}
if($check){
$tv_array = json_encode($tv_array);
$tvr->set('value', $tv_array);
$tvr->save();
$properties = $msOrder->get('properties');
if (!is_array($properties)) {
$properties = array();
}
$properties['koupon_code'] = $data['koupon_code'];
$msOrder->set('properties', $properties);
$msOrder->save();
}
}
}
}
}
break;
case 'msOnManagerCustomCssJs':
if ($page != 'orders') return;
$modx->controller->addHtml("
<script type='text/javascript'>
Ext.ComponentMgr.onAvailable('minishop2-window-order-update', function(){
if (miniShop2.config['order_grid_fields'].in_array('properties')){
if (this.record.properties){
var key;
for (key in this.record.properties) {
this.fields.items[0].items[3].items[1].items.push(
{
xtype: 'displayfield',
name: 'properties_'+key,
fieldLabel: _('ms2_properties_'+key),
anchor: '100%',
style: 'border:1px solid #efefef;width:95%;padding:5px;',
html: this.record.properties[key]
}
);
}
}
}
});
</script>");
break;
}
return;
$(function() {
miniShop2.Callbacks.Order.add.ajax.done = function(res) {
var res = res.responseJSON;
if (typeof(res.data['koupon_code']) != 'undefined') {
miniShop2.Order.getcost();
};
};
});
{
"formtabs":[
{
"MIGX_id":5,
"caption":"\u041a\u0443\u043f\u043e\u043d\u044b",
"print_before_tabs":"0",
"fields":[
{
"MIGX_id":6,
"field":"code",
"caption":"\u041a\u043e\u0434 \u043a\u0443\u043f\u043e\u043d\u0430",
"description":"",
"description_is_code":"0",
"inputTV":"",
"inputTVtype":"",
"validation":"required",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"",
"default":"",
"useDefaultIfEmpty":"0",
"pos":1
},
{
"MIGX_id":7,
"field":"button",
"caption":"\u041a\u043d\u043e\u043f\u043a\u0430 \u0433\u0435\u043d\u0435\u0440\u0430\u0446\u0438\u0438 \u043a\u043e\u0434\u0430",
"description":"<span class=\"input-group-btn\"><button type=\"button\" class=\"btn btn-default getNewPass\"><span class=\"fa fa-refresh\"><\/span><\/button><\/span>\n<link rel=\"stylesheet\" href=\"\/\/maxcdn.bootstrapcdn.com\/font-awesome\/4.2.0\/css\/font-awesome.min.css\">\n<script>\n\/\/ Generate a password string\nfunction randString(id){\nvar char = \"A-Z,0-9\";\nvar size = 14;\n var dataSet = char.split(','); \n var possible = '';\n if($.inArray('A-Z', dataSet) >= 0){\n possible += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n }\n if($.inArray('0-9', dataSet) >= 0){\n possible += '0123456789';\n }\n var text = '';\n for(var i=0; i < size; i++) {\nif(i == 4 || i == 9){\ntext += '-';\n}else{\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n}\n }\n return text;\n}\n\n\/\/ Create a new password on page load\n$('#migxdb-panel-object-80 .column input:eq(1)').each(function(){\nif($(this).val().length <= 0){\n $(this).val(randString($(this)));\n}\n});\n\n\/\/ Create a new password\n$(\".getNewPass\").click(function(){\n var field = $('#migxdb-panel-object-80 .column input:eq(1)');\n field.val(randString(field));\n});\n\n\/\/ Auto Select Pass On Focus\n$('#migxdb-panel-object-80 .column input:eq(1)').on(\"click\", function () {\n $(this).select();\n});\n\n$('#migxdb-panel-object-80 .column input:eq(1)').mask(\"ZZZZ-ZZZZ-ZZZZ\", {\n translation: {\n 'Z': {\n pattern: \/[0-9,A-Z]\/,\n optional: true\n },\n placeholder: \"****-****-****\"\n }\n });\n<\/script>",
"description_is_code":1,
"inputTV":"",
"inputTVtype":"",
"validation":"",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"",
"default":"",
"useDefaultIfEmpty":"0",
"pos":2
},
{
"MIGX_id":8,
"field":"percent",
"caption":"\u0421\u043a\u0438\u0434\u043a\u0430 \u0432 \u0440\u0443\u0431\u043b\u044f\u0445",
"description":"",
"description_is_code":"0",
"inputTV":"",
"inputTVtype":"number",
"validation":"",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"",
"default":500,
"useDefaultIfEmpty":"0",
"pos":3
},
{
"MIGX_id":9,
"field":"active",
"caption":"\u0410\u043a\u0442\u0438\u0432\u0438\u0440\u043e\u0432\u0430\u043d?",
"description":"",
"description_is_code":"0",
"inputTV":"",
"inputTVtype":"checkbox",
"validation":"",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"\u0414\u0430==1",
"default":"0",
"useDefaultIfEmpty":"0",
"pos":4
},
{
"MIGX_id":10,
"field":"activatedon",
"caption":"\u0414\u0430\u0442\u0430 \u0430\u043a\u0442\u0438\u0432\u0430\u0446\u0438\u0438",
"description":"",
"description_is_code":"0",
"inputTV":"",
"inputTVtype":"",
"validation":"",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"",
"default":"",
"useDefaultIfEmpty":"0",
"pos":5
},
{
"MIGX_id":11,
"field":"order_id",
"caption":"\u041d\u043e\u043c\u0435\u0440 \u0437\u0430\u043a\u0430\u0437\u0430",
"description":"",
"description_is_code":"0",
"inputTV":"",
"inputTVtype":"",
"validation":"",
"configs":"",
"restrictive_condition":"",
"display":"",
"sourceFrom":"config",
"sources":"",
"inputOptionValues":"",
"default":"",
"useDefaultIfEmpty":"0",
"pos":6
}
],
"pos":1
}
],
"contextmenus":"edit_migx||remove_migx",
"actionbuttons":"",
"columnbuttons":"",
"filters":"",
"extended":{
"migx_add":"\u0414\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u043a\u0443\u043f\u043e\u043d",
"disable_add_item":"",
"add_items_directly":"",
"formcaption":"",
"update_win_title":"",
"win_id":"koupons",
"maxRecords":"",
"addNewItemAt":"bottom",
"media_source_id":"",
"multiple_formtabs":"",
"multiple_formtabs_label":"",
"multiple_formtabs_field":"",
"multiple_formtabs_optionstext":"",
"multiple_formtabs_optionsvalue":"",
"actionbuttonsperrow":4,
"winbuttonslist":"",
"extrahandlers":"",
"filtersperrow":4,
"packageName":"",
"classname":"",
"task":"",
"getlistsort":"",
"getlistsortdir":"",
"sortconfig":"",
"gridpagesize":"",
"use_custom_prefix":"0",
"prefix":"",
"grid":"",
"gridload_mode":1,
"check_resid":1,
"check_resid_TV":"",
"join_alias":"",
"has_jointable":"yes",
"getlistwhere":"",
"joins":"",
"hooksnippets":"",
"cmpmaincaption":"",
"cmptabcaption":"",
"cmptabdescription":"",
"cmptabcontroller":"",
"winbuttons":"",
"onsubmitsuccess":"",
"submitparams":""
},
"columns":[
{
"MIGX_id":1,
"header":"\u041a\u043e\u0434 \u043a\u0443\u043f\u043e\u043d\u0430",
"dataIndex":"code",
"width":"",
"sortable":"false",
"show_in_grid":1,
"customrenderer":"",
"renderer":"",
"clickaction":"",
"selectorconfig":"",
"renderchunktpl":"",
"renderoptions":"",
"editor":""
},
{
"MIGX_id":2,
"header":"\u0421\u043a\u0438\u0434\u043a\u0430",
"dataIndex":"percent",
"width":"",
"sortable":"false",
"show_in_grid":1,
"customrenderer":"",
"renderer":"",
"clickaction":"",
"selectorconfig":"",
"renderchunktpl":"",
"renderoptions":"",
"editor":"this.textEditor"
},
{
"MIGX_id":3,
"header":"\u0410\u043a\u0442\u0438\u0432\u0438\u0440\u043e\u0432\u0430\u043d?",
"dataIndex":"active",
"width":"",
"sortable":"false",
"show_in_grid":1,
"customrenderer":"",
"renderer":"this.renderCrossTick",
"clickaction":"",
"selectorconfig":"",
"renderchunktpl":"",
"renderoptions":"",
"editor":""
},
{
"MIGX_id":4,
"header":"\u0417\u0430\u043a\u0430\u0437",
"dataIndex":"order_id",
"width":"",
"sortable":"false",
"show_in_grid":1,
"customrenderer":"",
"renderer":"",
"clickaction":"",
"selectorconfig":"",
"renderchunktpl":"",
"renderoptions":"",
"editor":""
},
{
"MIGX_id":5,
"header":"\u0414\u0430\u0442\u0430",
"dataIndex":"activatedon",
"width":"",
"sortable":"false",
"show_in_grid":1,
"customrenderer":"",
"renderer":"",
"clickaction":"",
"selectorconfig":"",
"renderchunktpl":"",
"renderoptions":"",
"editor":""
}
],
"category":""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment