Skip to content

Instantly share code, notes, and snippets.

@andronex
Last active November 15, 2019 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andronex/af54bd1f8859711ffe0eb50b1651b0d7 to your computer and use it in GitHub Desktop.
Save andronex/af54bd1f8859711ffe0eb50b1651b0d7 to your computer and use it in GitHub Desktop.
Обновление остатков товаров в системе MODX Revolution + miniShop2 из CRM Мой Склад
<?php
/*
* коннектор по пути assets/components/moysklad/action.php
*/
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/config.core.php';
define('MODX_REQP', false);
require_once MODX_CORE_PATH . 'config/' . MODX_CONFIG_KEY . '.inc.php';
require_once MODX_CONNECTORS_PATH . 'index.php';
$corePath = $modx->getOption('moysklad_core_path', null, $modx->getOption('core_path') . 'components/myskladlib/');
// Set HTTP_MODAUTH for web processors
if (defined('MODX_REQP') && MODX_REQP === false) {
$_SERVER['HTTP_MODAUTH'] = $modx->user->getUserToken($modx->context->get('key'));
}
$path = $corePath;
/** @var modConnectorRequest $request */
$modx->request->handleRequest(array(
'processors_path' => $path,
'location' => '',
'action' => 'index',
'product_id' => (int)$REQUEST['product_id'],
'event' => $REQUEST['event']
));
<?php
/*
* процессор по пути core/components/myskladlib/index.php
* юзается библиотека https://github.com/Tooyz/moysklad , которая установлена компосером и лежит по пути core/components/myskladlib/vendor/
* сист.настройки moysklad_login - логин для МойСклад , moysklad_pass - пароль для МойСклад , moysklad_step - через каждые n часов обновлять остатки, иначе брать из кеша , moysklad_stores = "Основной склад,Мятые коробки,Pony"
*/
header('Content-Type: application/json; charset=utf-8');
use MoySklad\Components\Http\RequestLog;
use MoySklad\Exceptions\RequestFailedException;
use MoySklad\Lists\EntityList;
use MoySklad\Entities\Documents\Inventory;
use MoySklad\Entities\Organization;
use MoySklad\Entities\Store;
use MoySklad\Components\Specs\QuerySpecs\QuerySpecs;
use MoySklad\Entities\Products\Product;
use MoySklad\Entities\Reports\StockReport;
use MoySklad\Components\Specs\QuerySpecs\Reports\StockReportQuerySpecs;
use MoySklad\Components\FilterQuery;
use MoySklad\MoySklad;
try {
$product_id = $modx->getOption('product_id', $scriptProperties);
$step = (int)$modx->getOption('moysklad_step', null, 3)?:3;
$cacheTime = $step * 3600;
$stamp = 'cache';
if((!$result = $modx->cacheManager->get('stock_prod_'.($product_id?:0))) || ($modx->getOption('event', $scriptProperties) == 'OnBeforeDocFormSave')){
require_once "vendor/autoload.php";
$stamp = 'notcache';
if (!$sklad = MoySklad::getInstance($modx->getOption('moysklad_login', null, 'market@***'), $modx->getOption('moysklad_pass', null, '***'))) {
throw new Exception('Нет подключения к MoySklad');
}
$list = Product::query($sklad)->filter(
(new FilterQuery())
->eq("code", $product_id?:0)
);
$stores = $modx->getOption('moysklad_stores', null, 'Основной склад');
$stores = array_map('mb_strtolower', array_map('trim', explode(',', $stores)));
//print_r($stores);
if($list[0]->id){
$stocks = StockReport::bystore($sklad, StockReportQuerySpecs::create([
"product.id" => $list[0]->id,
"groupBy" => 'product',
"stockMode" => 'all'
//"maxResults" => 1
]));
$stock = 0;
foreach($stocks->rows[0]->stockByStore as $store){
if(in_array(mb_strtolower(trim($store->name)), $stores)){
$stock = $stock + $store->stock;
}
}
$result = array('success' => true, 'stock' => $stock, 'error' => null);
$modx->cacheManager->set('stock_prod_'.($product_id?:0), $result, $cacheTime);
return json_encode(array_merge($result, ['stamp' => $stamp]));
}
$result = array('success' => false, 'stock' => -1, 'error' => null);
$modx->cacheManager->set('stock_prod_'.($product_id?:0), $result, $cacheTime);
return json_encode(array_merge($result, ['stamp' => $stamp]));
}
return json_encode(array_merge($result, ['stamp' => $stamp]));
} catch (Exception $e) {
return json_encode(array('success' => false, 'stock' => -1, 'error' => 'Нет подключения к MoySklad'));
}
return json_encode(array('success' => false, 'stock' => -1, 'error' => null));
//$organization = Organization::query($sklad)->getList()->get(0);
//$product = Product::query($sklad)->byId("291799eb-caaa-11e7-7a34-5acf00165ab4");
//print_r($stocks->rows[0]->stockByStore);
<?php
/*
* плагин stockMySklad на события OnBeforeDocFormSave или OnWebPageInit
*/
if ($modx->event->name == 'OnBeforeDocFormSave' || $modx->event->name == 'OnWebPageInit') {
if($resource = $resource?:$modx->getObject('msProduct', $modx->resourceIdentifier)){
if($resource->get('class_key') == 'msProduct' && $resource->get('from_crm')){
//$modx->log(1, 'Включено обновление остатков');
//$client = $modx->getService('rest.modRestCurlClient');
//$result = $client->request($modx->getOption('site_url') . 'assets/components/moysklad/action.php', '/', 'GET', $params = array('product_id' => $resource->get('id')));
$result = file_get_contents($modx->getOption('site_url') . 'assets/components/moysklad/action.php?product_id='.$resource->get('id').'&event='.$modx->event->name);
//$modx->log(1, print_r($result, true));
if(is_array(json_decode($result, true))){
$result = json_decode($result, true);
//$modx->log(1, print_r($result['stock'], true));
switch(true){
//если остатков больше 0 шт.
case $result['stock'] > 0:
//если обновление по событию OnWebPageInit и результат из кеша
if($result['stamp'] == 'cache' && $modx->resourceIdentifier) break;
$resource->set('stock', 1);
$resource->set('stock_count', $result['stock']);
//если обновление по событию OnWebPageInit
if($modx->resourceIdentifier){
$resource->save();
$cacheKey = $resource->getCacheKey();
$modx->cacheManager->refresh(array(
'resource' => array('key' => $cacheKey),
));
}
break;
//если остатков = 0 шт.
case $result['stock'] == 0:
//если обновление по событию OnWebPageInit и результат из кеша
if($result['stamp'] == 'cache' && $modx->resourceIdentifier) break;
$resource->set('stock', 0);
$resource->set('stock_count', 0);
//если обновление по событию OnWebPageInit
if($modx->resourceIdentifier){
$resource->save();
$cacheKey = $resource->getCacheKey();
$modx->cacheManager->refresh(array(
'resource' => array('key' => $cacheKey),
));
}
break;
}
}
}
}
}
return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment