From daccbfd8a560f07e0506f8e99b34c61b25a4f4bb Mon Sep 17 00:00:00 2001 From: GJHack Date: Thu, 15 Feb 2024 16:29:42 +1000 Subject: [PATCH] add more --- README.md | 43 +- exchangeStrapi/composer.json | 6 + exchangeStrapi/composer.lock | 746 ++++++++++++++++++++++++++++++ exchangeStrapi/index.php | 137 ++++++ package-lock.json | 353 +++----------- server/controllers/file_cheker.js | 575 ++++++++++++++++++++++- server/routes/index.js | 7 +- 7 files changed, 1517 insertions(+), 350 deletions(-) create mode 100644 exchangeStrapi/composer.json create mode 100644 exchangeStrapi/composer.lock create mode 100644 exchangeStrapi/index.php diff --git a/README.md b/README.md index 50739b6..37e9511 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ # STRAPI 1C EXCHANGE PLUGIN # Name: MegaExchange -# Version: 0.0.0.3; ## Author: Roman Agafonov / Роман Агафонов ## LICENSE: Apache 2.0 @@ -11,48 +10,36 @@ Если у Вас возникло желание поддержать мое начинание, то я с удовольствием приму любое пожертвование на карту :) -### 2200700818815853 +### 2200 7005 4323 7183 Роман А. Тинькофф ### Идея проекта Состоит в создании универсального плагина для обмена данными с 1С Предприятием и ему подобным релятивным шлаком, по протоколу CommerceML 2 / CommerceML EDI -### Что планируется: - -- авторизация -- UI интерфейс на основе bootstrap stapi -- автогенерация типов данных и их комплементация в единую абстракцию -- проверка изменений -- авторегенерация изображений - > Это динамический список. ### Что Сделано: -##### На стороне php -- Простейшая авторизация. На стороне PHP! -- Обработка файла приходящего от 1С и сохранение на бэке -- Послание сигнала, на роут плагина в strapi о том, что файл получен. +- авторизация +- создание сложного каталога +- создание товаров +- загрузка изображений +- установка разного типа цен +- и их апдейты -##### На стороне strapi -- Поиск, распаковка и получение папки с XMLками от 1C > Это динамический список. -### В процессе: -- Преобразование XML в JSON формат. -- Создание content-type +## INSTALATION / УСТАНОВКА -## HOT NEWS +### STEP -1 +папку exchangeStrapi, вместе со всеми зависямостями ставим туда куда удобно, попутно, настраиваем сервер так, чтобы был доступ внутрь. +Схема простая. Так как 1С = д***баеб и передает файлы в теле запроса потоково, JS с такого в полном ах..е. Мы будем использовать +стандартную пыху и получаем все файлы через нее сохраняя на бэк. -#### UPDATE 28.12.2023 -Беда оказалась в том, что 1С передает данные на сайт по дефолту через php, -а именно php://input -Сколько не пытался распарсить входные данные из под STRApi ничего не вышло. -Пришлость написать доп. обертку в виде php мидлваря, который сохраняет файлы -приходящие от 1С в публичную папку бэка. -Пока так, потом буду думать :) +Далее пыха дает гет на страпи и там внутри уже распарсиваем данные пока все в файле file_cheker.js + +Пока как есть сгорел ноут, деняк нет. Как появится продолжу апдейтить) -## INSTALATION / УСТАНОВКА ### STEP 0 ``` move all files in you strapi project - ..../'you_strapi_folder'/src/plugins/'you_plugin_folder' diff --git a/exchangeStrapi/composer.json b/exchangeStrapi/composer.json new file mode 100644 index 0000000..dd4701c --- /dev/null +++ b/exchangeStrapi/composer.json @@ -0,0 +1,6 @@ +{ + "require": { + "symfony/http-foundation": "^5.4", + "guzzlehttp/guzzle": "7.0" + } +} diff --git a/exchangeStrapi/composer.lock b/exchangeStrapi/composer.lock new file mode 100644 index 0000000..4db4e5c --- /dev/null +++ b/exchangeStrapi/composer.lock @@ -0,0 +1,746 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "0727757d97f6c09436a94b79fbcd9e06", + "packages": [ + { + "name": "guzzlehttp/guzzle", + "version": "7.0.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "414c24961042f6616fb43e23fa69a785f9fc053e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/414c24961042f6616fb43e23fa69a785f9fc053e", + "reference": "414c24961042f6616fb43e23fa69a785f9fc053e", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^1.0", + "guzzlehttp/psr7": "^1.6.1", + "php": "^7.2.5", + "psr/http-client": "^1.0" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.0", + "ext-curl": "*", + "php-http/client-integration-tests": "dev-phpunit8", + "phpunit/phpunit": "^8.5.5", + "psr/log": "^1.1" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "7.0-dev" + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "homepage": "http://guzzlephp.org/", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/master" + }, + "time": "2020-06-27T08:47:54+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "1.5.3", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "67ab6e18aaa14d753cc148911d273f6e6cb6721e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/67ab6e18aaa14d753cc148911d273f6e6cb6721e", + "reference": "67ab6e18aaa14d753cc148911d273f6e6cb6721e", + "shasum": "" + }, + "require": { + "php": ">=5.5" + }, + "require-dev": { + "symfony/phpunit-bridge": "^4.4 || ^5.1" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/1.5.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2023-05-21T12:31:43+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.9.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "e4490cabc77465aaee90b20cfc9a770f8c04be6b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/e4490cabc77465aaee90b20cfc9a770f8c04be6b", + "reference": "e4490cabc77465aaee90b20cfc9a770f8c04be6b", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/1.9.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2023-04-17T16:00:37+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-message", + "version": "1.1", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/cb6ce4845ce34a8ad9e68117c10ee90a29919eba", + "reference": "cb6ce4845ce34a8ad9e68117c10ee90a29919eba", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/1.1" + }, + "time": "2023-04-04T09:50:52+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v2.5.2", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "reference": "e8b495ea28c1d97b5e0c121748d6f9b53d075c66", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "2.5-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v2.5.2" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-01-02T09:53:40+00:00" + }, + { + "name": "symfony/http-foundation", + "version": "v5.4.32", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-foundation.git", + "reference": "cbcd80a4c36f59772d62860fdb0cb6a38da63fd2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/cbcd80a4c36f59772d62860fdb0cb6a38da63fd2", + "reference": "cbcd80a4c36f59772d62860fdb0cb6a38da63fd2", + "shasum": "" + }, + "require": { + "php": ">=7.2.5", + "symfony/deprecation-contracts": "^2.1|^3", + "symfony/polyfill-mbstring": "~1.1", + "symfony/polyfill-php80": "^1.16" + }, + "require-dev": { + "predis/predis": "~1.0", + "symfony/cache": "^4.4|^5.0|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/expression-language": "^4.4|^5.0|^6.0", + "symfony/http-kernel": "^5.4.12|^6.0.12|^6.1.4", + "symfony/mime": "^4.4|^5.0|^6.0", + "symfony/rate-limiter": "^5.2|^6.0" + }, + "suggest": { + "symfony/mime": "To use the file extension guesser" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpFoundation\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Defines an object-oriented layer for the HTTP specification", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-foundation/tree/v5.4.32" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-11-20T15:40:25+00:00" + }, + { + "name": "symfony/polyfill-mbstring", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-mbstring.git", + "reference": "42292d99c55abe617799667f454222c54c60e229" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/42292d99c55abe617799667f454222c54c60e229", + "reference": "42292d99c55abe617799667f454222c54c60e229", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-07-28T09:04:16+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.28.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "reference": "6caa57379c4aec19c0a12a38b59b26487dcfe4b5", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.28-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.28.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-26T09:26:14+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": [], + "prefer-stable": false, + "prefer-lowest": false, + "platform": [], + "platform-dev": [], + "plugin-api-version": "2.3.0" +} diff --git a/exchangeStrapi/index.php b/exchangeStrapi/index.php new file mode 100644 index 0000000..438bee4 --- /dev/null +++ b/exchangeStrapi/index.php @@ -0,0 +1,137 @@ + "Failure", + "data" => [$authString, 'SILINTE TOKEN'] + ]); + + $fw = fopen($_SERVER["DOCUMENT_ROOT"] . '/exchangeStrapi/log.txt', "a"); + $result = fwrite($fw, "GET" . var_export(["error" => "$authString : Переданный ключ. Авторизация ложна\n"], true)); + echo $_SERVER["DOCUMENT_ROOT"] . '/exchangeStrapi/log.txt'; + fclose($fw); + + break; + + } else { + $fw = fopen($_SERVER["DOCUMENT_ROOT"] . '/exchangeStrapi/log.txt', "a"); + $result = fwrite($fw, "GET " . var_export(["error" => "$authString : Успешная авторизация\n'"], true)); + fclose($fw); + echo "success\nCookie\ncookie"; + break; + } + + case "init" : + echo "zip=yes\nfile_limit=54005000"; + break; + + default: + echo("Failure GET"); + } + + } + + } + + if(isset($_POST)) { + + if(isset($_GET["mode"]) && isset($_GET["filename"])) { + + $mode = strval($_GET["mode"]); + $mode = str_replace (["\r\n", "\n", "\r" , " "], '', $mode); + $type = ($_GET["type"]) ? $_GET["type"] : "unknown"; + $filename = ($_GET["filename"]) ? $_GET["filename"] : "error_File.zip"; + + switch($mode) { + case "file" : + + $client = new \GuzzleHttp\Client(); + $file = file_get_contents('php://input'); + $url_strapi = $HTTP_PROCOL . "://" . $URL_API . "/exchange/new_files?filename=" . $filename . "&mode=" . $mode; + + ///usr/share/nginx/html/back/public/uploads/ + if(!file_exists('/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/' . $filename)){ + + $fw = fopen($_SERVER["DOCUMENT_ROOT"] . '/exchangeStrapi/log.txt', "a"); + $result = fwrite($fw, "POST: " . var_export(["error" => "$authString : Попытка записи архива на сервер. $filename'"], true)); + fclose($fw); + + $result_put = file_put_contents('/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/' . $filename, $file); + + try { + $response = $client->get($url_strapi); + if ($response->getStatusCode() == 200) { + echo "success"; + } + } catch (Exception $e) { + echo 'Выброшено исключение: ', $e->getMessage(), "\n"; + } + + + echo "Файл создан: $filename"; + + } else if (file_exists('/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/' . $filename)) { + + try { + $response = $client->get($url_strapi); + if ($response->getStatusCode() == 200) { + echo "success"; + } + } catch (Exception $e) { + echo 'Выброшено исключение: ', $e->getMessage(), "\n"; + } + + + echo("Failure Файл уже существует\n"); + echo("Failure MODE: FILE\n"); + + } else { + + echo("Failure\n"); + echo("Непредвиденная ошибка\n"); + echo("Failure MODE: FILE\n"); + + } + + + + + + echo "success"; + + break; + + default: + echo("Failure POST"); + } + + } + } + +// http://localhost/exchangeStrapi/index.php +?> diff --git a/package-lock.json b/package-lock.json index 9b3d113..9c7e1df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,19 +34,6 @@ "styled-components": "^5.3.6" } }, - "node_modules/@ampproject/remapping": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.1.tgz", - "integrity": "sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==", - "peer": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.0", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.23.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", @@ -59,55 +46,11 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/compat-data": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", - "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==", - "peer": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.6.tgz", - "integrity": "sha512-FxpRyGjrMJXh7X3wGLGhNDCRiwpWEF74sKjTLDJSG5Kyvow3QZaG0Adbqzi9ZrVjTWpsX+2cxWXD71NMg93kdw==", - "peer": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-compilation-targets": "^7.23.6", - "@babel/helper-module-transforms": "^7.23.3", - "@babel/helpers": "^7.23.6", - "@babel/parser": "^7.23.6", - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.6", - "@babel/types": "^7.23.6", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/core/node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "peer": true - }, "node_modules/@babel/generator": { "version": "7.23.6", "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", + "dev": true, "dependencies": { "@babel/types": "^7.23.6", "@jridgewell/gen-mapping": "^0.3.2", @@ -122,6 +65,7 @@ "version": "7.22.5", "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.22.5.tgz", "integrity": "sha512-LvBTxu8bQSQkcyKOU+a1btnNFQ1dMAd0R6PyW3arXes06F6QLWLIrd681bxRPIXlrMGR3XYnW9JyML7dP3qgxg==", + "dev": true, "dependencies": { "@babel/types": "^7.22.5" }, @@ -129,26 +73,11 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", - "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", - "peer": true, - "dependencies": { - "@babel/compat-data": "^7.23.5", - "@babel/helper-validator-option": "^7.23.5", - "browserslist": "^4.22.2", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/helper-environment-visitor": { "version": "7.22.20", "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", + "dev": true, "engines": { "node": ">=6.9.0" } @@ -157,6 +86,7 @@ "version": "7.23.0", "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", + "dev": true, "dependencies": { "@babel/template": "^7.22.15", "@babel/types": "^7.23.0" @@ -169,6 +99,7 @@ "version": "7.22.5", "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", + "dev": true, "dependencies": { "@babel/types": "^7.22.5" }, @@ -187,41 +118,11 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", - "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", - "peer": true, - "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, "node_modules/@babel/helper-plugin-utils": { "version": "7.22.5", "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", - "peer": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, + "dev": true, "engines": { "node": ">=6.9.0" } @@ -230,6 +131,7 @@ "version": "7.22.6", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", + "dev": true, "dependencies": { "@babel/types": "^7.22.5" }, @@ -253,29 +155,6 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-validator-option": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", - "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==", - "peer": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.6.tgz", - "integrity": "sha512-wCfsbN4nBidDRhpDhvcKlzHWCTlgJYUUdSJfzXb2NuBssDSIjc3xcb+znA7l+zYsFljAcGM0aFkN40cR3lXiGA==", - "peer": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/traverse": "^7.23.6", - "@babel/types": "^7.23.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/@babel/highlight": { "version": "7.23.4", "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", @@ -293,6 +172,7 @@ "version": "7.23.6", "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.6.tgz", "integrity": "sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ==", + "dev": true, "bin": { "parser": "bin/babel-parser.js" }, @@ -304,6 +184,7 @@ "version": "7.23.3", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.23.3.tgz", "integrity": "sha512-EB2MELswq55OHUoRZLGg/zC7QWUKfNLpE57m/S2yr1uEneIgsTgrSzXP3NXEsMkVn76OlaVVnzN+ugObuYGwhg==", + "dev": true, "dependencies": { "@babel/helper-plugin-utils": "^7.22.5" }, @@ -329,6 +210,7 @@ "version": "7.22.15", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz", "integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==", + "dev": true, "dependencies": { "@babel/code-frame": "^7.22.13", "@babel/parser": "^7.22.15", @@ -342,6 +224,7 @@ "version": "7.23.6", "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.6.tgz", "integrity": "sha512-czastdK1e8YByZqezMPFiZ8ahwVMh/ESl9vPgvgdB9AmFMGP5jfpFax74AQgl5zj4XHzqeYAg2l8PuUeRS1MgQ==", + "dev": true, "dependencies": { "@babel/code-frame": "^7.23.5", "@babel/generator": "^7.23.6", @@ -506,6 +389,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.2.1.tgz", "integrity": "sha512-61Mf7Ufx4aDxx1xlDeOm8aFFigGHE4z+0sKCa+IHCeZKiyP9RLD0Mmx7m8b9/Cf37f7NAvQOOJAbQQGVr5uERw==", + "dev": true, "dependencies": { "@emotion/memoize": "^0.8.1" } @@ -558,7 +442,8 @@ "node_modules/@emotion/stylis": { "version": "0.8.5", "resolved": "https://registry.npmjs.org/@emotion/stylis/-/stylis-0.8.5.tgz", - "integrity": "sha512-h6KtPihKFn3T9fuIrwvXXUOwlx3rfUvfZIcP5a6rh8Y7zjE3O06hT5Ss4S/YI1AYhuZ1kjaE/5EaOOI2NqSylQ==" + "integrity": "sha512-h6KtPihKFn3T9fuIrwvXXUOwlx3rfUvfZIcP5a6rh8Y7zjE3O06hT5Ss4S/YI1AYhuZ1kjaE/5EaOOI2NqSylQ==", + "dev": true }, "node_modules/@emotion/unitless": { "version": "0.8.1", @@ -723,6 +608,7 @@ "version": "0.3.3", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, "dependencies": { "@jridgewell/set-array": "^1.0.1", "@jridgewell/sourcemap-codec": "^1.4.10", @@ -736,6 +622,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, "engines": { "node": ">=6.0.0" } @@ -744,6 +631,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, "engines": { "node": ">=6.0.0" } @@ -751,12 +639,14 @@ "node_modules/@jridgewell/sourcemap-codec": { "version": "1.4.15", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true }, "node_modules/@jridgewell/trace-mapping": { "version": "0.3.20", "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", + "dev": true, "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -1689,6 +1579,7 @@ "version": "2.1.4", "resolved": "https://registry.npmjs.org/babel-plugin-styled-components/-/babel-plugin-styled-components-2.1.4.tgz", "integrity": "sha512-Xgp9g+A/cG47sUyRwwYxGM4bR/jDRg5N6it/8+HxCnbT5XNKSKDT9xm4oag/osgqjC2It/vH0yXsomOG6k558g==", + "dev": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.22.5", "@babel/helper-module-imports": "^7.22.5", @@ -1804,38 +1695,6 @@ "unload": "2.2.0" } }, - "node_modules/browserslist": { - "version": "4.22.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.2.tgz", - "integrity": "sha512-0UgcrvQmBDvZHFGdYUehrCNIazki7/lUP3kkoi/r3YB2amZbFM9J43ZRkJTXBUZK4gmx56+Sqk9+Vs9mwZx9+A==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "peer": true, - "dependencies": { - "caniuse-lite": "^1.0.30001565", - "electron-to-chromium": "^1.4.601", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.13" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, "node_modules/buffer-indexof-polyfill": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", @@ -1885,30 +1744,11 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.1.tgz", "integrity": "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==", + "dev": true, "funding": { "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/caniuse-lite": { - "version": "1.0.30001571", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001571.tgz", - "integrity": "sha512-tYq/6MoXhdezDLFZuCO/TKboTzuQ/xR5cFdgXPfDtM7/kchBO3b4VWghE/OAi/DV7tTdhmLjZiZBZi1fA/GheQ==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "peer": true - }, "node_modules/chainsaw": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", @@ -2031,6 +1871,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz", "integrity": "sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==", + "dev": true, "engines": { "node": ">=4" } @@ -2039,6 +1880,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", "integrity": "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ==", + "dev": true, "dependencies": { "camelize": "^1.0.0", "css-color-keywords": "^1.0.0", @@ -2069,6 +1911,7 @@ "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -2159,12 +2002,6 @@ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" }, - "node_modules/electron-to-chromium": { - "version": "1.4.616", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.616.tgz", - "integrity": "sha512-1n7zWYh8eS0L9Uy+GskE0lkBUNK83cXTVJI0pU3mGprFsbfSdAc15VTFbo+A+Bq4pwstmL30AVcEU3Fo463lNg==", - "peer": true - }, "node_modules/end-of-stream": { "version": "1.4.4", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", @@ -2181,15 +2018,6 @@ "is-arrayish": "^0.2.1" } }, - "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", - "peer": true, - "engines": { - "node": ">=6" - } - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -2319,15 +2147,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "peer": true, - "engines": { - "node": ">=6.9.0" - } - }, "node_modules/get-intrinsic": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", @@ -2373,6 +2192,7 @@ "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, "engines": { "node": ">=4" } @@ -2449,6 +2269,7 @@ "version": "4.10.1", "resolved": "https://registry.npmjs.org/history/-/history-4.10.1.tgz", "integrity": "sha512-36nwAD620w12kuzPAsyINPWJqlNbij+hpK1k9XRloDtym8mxzGYl2c17LnV6IAGB2Dmg4tEa7G7DlawS0+qjew==", + "dev": true, "dependencies": { "@babel/runtime": "^7.1.2", "loose-envify": "^1.2.0", @@ -2573,7 +2394,8 @@ "node_modules/isarray": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==" + "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==", + "dev": true }, "node_modules/js-sha3": { "version": "0.8.0", @@ -2589,6 +2411,7 @@ "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, "bin": { "jsesc": "bin/jsesc" }, @@ -2601,18 +2424,6 @@ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "peer": true, - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/lines-and-columns": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", @@ -2649,15 +2460,6 @@ "loose-envify": "cli.js" } }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "peer": true, - "dependencies": { - "yallist": "^3.0.2" - } - }, "node_modules/match-sorter": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/match-sorter/-/match-sorter-6.3.1.tgz", @@ -2737,7 +2539,8 @@ "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true }, "node_modules/nano-time": { "version": "1.0.0", @@ -2752,12 +2555,6 @@ "resolved": "https://registry.npmjs.org/nanoclone/-/nanoclone-0.2.1.tgz", "integrity": "sha512-wynEP02LmIbLpcYw8uBKpcfF6dmg2vcpKqxeH5UcoKEYdExslsdUA4ugFauuaeYdTB76ez6gJW8XAZ6CgkXYxA==" }, - "node_modules/node-releases": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", - "peer": true - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -2843,6 +2640,7 @@ "version": "1.8.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", + "dev": true, "dependencies": { "isarray": "0.0.1" } @@ -2855,16 +2653,11 @@ "node": ">=8" } }, - "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", - "peer": true - }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, "engines": { "node": ">=8.6" }, @@ -2906,7 +2699,8 @@ "node_modules/postcss-value-parser": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", - "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true }, "node_modules/process-nextick-args": { "version": "2.0.1", @@ -2987,6 +2781,7 @@ "version": "18.2.0", "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz", "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==", + "dev": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -2998,6 +2793,7 @@ "version": "18.2.0", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz", "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", + "dev": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.0" @@ -3056,12 +2852,6 @@ } } }, - "node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "peer": true - }, "node_modules/react-query": { "version": "3.39.3", "resolved": "https://registry.npmjs.org/react-query/-/react-query-3.39.3.tgz", @@ -3136,6 +2926,7 @@ "version": "5.3.4", "resolved": "https://registry.npmjs.org/react-router/-/react-router-5.3.4.tgz", "integrity": "sha512-Ys9K+ppnJah3QuaRiLxk+jDWOR1MekYQrlytiXxC1RyfbdsZkS5pvKAzCCr031xHixZwpnsYNT5xysdFHQaYsA==", + "dev": true, "dependencies": { "@babel/runtime": "^7.12.13", "history": "^4.9.0", @@ -3155,6 +2946,7 @@ "version": "5.3.4", "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-5.3.4.tgz", "integrity": "sha512-m4EqFMHv/Ih4kpcBCONHbkT68KoAeHN4p3lAGoNryfHi0dMy0kCzEZakiKRsvg5wHZ/JLrLW8o8KomWiz/qbYQ==", + "dev": true, "dependencies": { "@babel/runtime": "^7.12.13", "history": "^4.9.0", @@ -3171,7 +2963,8 @@ "node_modules/react-router/node_modules/react-is": { "version": "16.13.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", - "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "dev": true }, "node_modules/react-select": { "version": "5.7.0", @@ -3294,7 +3087,8 @@ "node_modules/resolve-pathname": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-pathname/-/resolve-pathname-3.0.0.tgz", - "integrity": "sha512-C7rARubxI8bXFNB/hqcp/4iUeIXJhJZvFPFPiSPRnhU5UPxzMFIl+2E6yY6c4k9giDJAhtV+enfA+G89N6Csng==" + "integrity": "sha512-C7rARubxI8bXFNB/hqcp/4iUeIXJhJZvFPFPiSPRnhU5UPxzMFIl+2E6yY6c4k9giDJAhtV+enfA+G89N6Csng==", + "dev": true }, "node_modules/rimraf": { "version": "3.0.2", @@ -3324,19 +3118,11 @@ "version": "0.23.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==", + "dev": true, "dependencies": { "loose-envify": "^1.1.0" } }, - "node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "peer": true, - "bin": { - "semver": "bin/semver.js" - } - }, "node_modules/set-function-length": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.1.1.tgz", @@ -3364,7 +3150,8 @@ "node_modules/shallowequal": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz", - "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==" + "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==", + "dev": true }, "node_modules/side-channel": { "version": "1.0.4", @@ -3438,6 +3225,7 @@ "version": "5.3.11", "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-5.3.11.tgz", "integrity": "sha512-uuzIIfnVkagcVHv9nE0VPlHPSCmXIUGKfJ42LNjxCCTDTL5sgnJ8Z7GZBq0EnLYGln77tPpEpExt2+qa+cZqSw==", + "dev": true, "dependencies": { "@babel/helper-module-imports": "^7.0.0", "@babel/traverse": "^7.4.5", @@ -3466,7 +3254,8 @@ "node_modules/styled-components/node_modules/@emotion/unitless": { "version": "0.7.5", "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.7.5.tgz", - "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==" + "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==", + "dev": true }, "node_modules/stylis": { "version": "4.2.0", @@ -3507,7 +3296,8 @@ "node_modules/tiny-invariant": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.1.tgz", - "integrity": "sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==" + "integrity": "sha512-AD5ih2NlSssTCwsMznbvwMZpJ1cbhkGd2uueNxzv2jDlEeZdU04JQfRnggJQ8DrcVBGjAsCKwFBbDlVNtEMlzw==", + "dev": true }, "node_modules/tiny-warning": { "version": "1.0.3", @@ -3594,36 +3384,6 @@ "setimmediate": "~1.0.4" } }, - "node_modules/update-browserslist-db": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", - "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "peer": true, - "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, "node_modules/use-callback-ref": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.0.tgz", @@ -3686,7 +3446,8 @@ "node_modules/value-equal": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/value-equal/-/value-equal-1.0.1.tgz", - "integrity": "sha512-NOJ6JZCAWr0zlxZt+xqCHNTEKOsrks2HQd4MqhP1qy4z1SkbEP467eNx6TgDKXMvUOb+OENfJCZwM+16n7fRfw==" + "integrity": "sha512-NOJ6JZCAWr0zlxZt+xqCHNTEKOsrks2HQd4MqhP1qy4z1SkbEP467eNx6TgDKXMvUOb+OENfJCZwM+16n7fRfw==", + "dev": true }, "node_modules/w3c-keyname": { "version": "2.2.8", @@ -3706,12 +3467,6 @@ "node": ">=0.4" } }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "peer": true - }, "node_modules/yaml": { "version": "1.10.2", "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", diff --git a/server/controllers/file_cheker.js b/server/controllers/file_cheker.js index 4941d0e..92dc623 100644 --- a/server/controllers/file_cheker.js +++ b/server/controllers/file_cheker.js @@ -1,10 +1,14 @@ 'use strict'; const unzipper = require('unzipper'); const fs = require('fs') -const convert = require('xml-js'); +const path = require('node:path'); +const xmlParser = require('xml2json'); const ABS_PATH = "/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/" +/// true = удалить все товары после прилета zip файла / false = нормальная работа +const erease = false + module.exports = { /** @@ -14,6 +18,11 @@ module.exports = { */ async checknew(ctx) { + if(erease) { + await clearProduct(100000, 160000) + return + } + const {type, mode, sessid, filename} = await ctx.request.query; if(filename) { @@ -35,7 +44,7 @@ module.exports = { if(await searchFolderResult) { const searchImportXMLs = await getAllFiles(ABS_PATH, filename.split('.')[0]) - console.log(`Результат получения всех файлов внутри: ${await searchImportXMLs}`); + console.log(`Ообнаружено товаров: ${await searchImportXMLs.length}`); } } } @@ -53,6 +62,7 @@ module.exports = { * @param {String} abspath - Абсолютный путь до папки * @returns {boolean} */ + async function unzip(filePath = "",absPath = "/", fileName = "text.zip") { if(!filePath || typeof filePath !== "string") return @@ -82,7 +92,7 @@ async function unzip(filePath = "",absPath = "/", fileName = "text.zip") { } /** - * + * @description Поиск по папке * @param {Context} ctx * @param {String} filePath - Путь до файла * @param {String} fileName - Имя файла @@ -93,7 +103,7 @@ async function searchInFolder(ctx, filePath = "", fileName = "text", extension = if(!filePath || typeof filePath !== "string") return const searchPath = (extension) ? filePath : filePath + fileName; - console.log(getAllNames) + try{ if(!extension) { // console.log(`Поиск папки ! ${searchPath}`) @@ -110,8 +120,10 @@ async function searchInFolder(ctx, filePath = "", fileName = "text", extension = return false; } } else { + + if(!getAllNames) { - console.log("IN SINGLE") + console.log("Получение одиночного файла") //console.log(`Поиск файла в ${searchPath}`) const promise = new Promise((resolve, reject) => { @@ -139,36 +151,561 @@ async function searchInFolder(ctx, filePath = "", fileName = "text", extension = } async function getAllFiles(absPath = "/", folderName = "test") { - const searchPath = absPath + folderName; - console.log(searchPath) + const searchPath = absPath + folderName; const promise = new Promise(async (resolve, reject) => { console.log("Получение всех файлов в папке.") const allFileNames = [] fs.readdirSync(searchPath).map(async checkName => { - const checkString = folderName - allFileNames.push({ - name: checkName, - dir: searchPath, - path: `${searchPath}/${checkName}`, - jsonData: await parseXML(`${searchPath}/${checkName}`) - }) + const checkString = folderName + const checkFolder = (typeof checkName.split('.')[1] != "undefined") ? true : false; + + if(checkFolder) { + let parseResult = await parseXML(`${searchPath}/${checkName}`, folderName); + allFileNames.push({ + name: checkName, + dir: searchPath, + path: `/usr/share/nginx/html/back/public${searchPath}/${checkName}`, + jsonData: await parseResult + }) + if(await parseResult) + resolve(allFileNames) + } else { + console.log(`Среди файлов обнаружена папка: ${checkName}`) + } }) - console.log(allFileNames) - resolve(allFileNames) }); return await promise } +async function parseXML(path = "/", checkFolder = "") { + let result, parseMode, productsList, file2; + + console.log(`Путь до файла с xml: ${path}`) + try { + + file2 = fs.readFileSync(path, (file) => file) + + result = xmlParser.toJson(file2).toString('utf-8'); + + result = result.replaceAll("$t",'t').replaceAll("ПакетПредложени�",'ПакетПредложений').replaceAll('\t','').replaceAll('\n','') + + console.log("РЕЗУЛЬТАТ ПАРСИНГА и преобразования в utf-8 ( END_TYPE: JSON )") + + result = JSON.parse(result) + + delete result.t; + } catch (e) { + console.log("ОШИБКА В ПОЛУЧЕНИИ ДАННЫХ ПРИ СОЗДАНИИ JSON") + console.log(JSON.parse(result)) + return '' + } + + + const testObjectProduct = { + name: '' + } + try { + ////ТУТ НАЧиНАЕТСЯ РАСПАРС JSONа с ТОВАРАМИ. #КАТАЛОГ + parseMode = (typeof result['КоммерческаяИнформация']['Каталог'] != 'undefined') ? "catalog" : "sales" + + console.log(parseMode) + + productsList = (parseMode == "catalog") + ? + result['КоммерческаяИнформация']['Каталог']['Товары']['Товар'] + : + result['КоммерческаяИнформация']['ПакетПредложений']['Предложения']['Предложение'] -async function parseXML(path = "/") { - let result; + console.log("PARSE MODE: " + parseMode) - console.log(result); + if(parseMode == "sales") { + //console.log(result['КоммерческаяИнформация']['ПакетПредложений']['Предложения']['Предложение']) + } + + } catch(e) { + + console.log("ОШИБКА В ПОЛУЧЕНИИ ДАННЫХ ИЗ РАСПАРСЕННОГО XML") + console.log("PARSE MODE: " + parseMode) + + return false; + } + + + ////Проверяем категории и создаем новые если не найдено совпадений + + if(parseMode == "catalog") + await createCatalog(productsList, checkFolder, result['КоммерческаяИнформация']['Классификатор']['Группы']['Группа']) + else + await salesWorking(productsList, result['КоммерческаяИнформация']['ПакетПредложений']['Склады']) + + ////Проверяем товары и создаем новые если не найдено совпадений + + //Создаем категории; + + //console.log(result['КоммерческаяИнформация']['Каталог']['Товары']['Товар'][0]['БазоваяЕдиница']['Пересчет']) + //console.log(testObjectProduct) return await result; } + +/** + * @description Создание каталога + * @param data + * @returns {Promise} + */ +const createCatalog = async (data = [{}], foldername = '', groups = false) => { + + if(!Array.isArray(data) || !groups) return false; + + //Инициализация + let creatorCategories; + + ////Создаем КАТЕГОРИЮ через итерацию + for(const category of groups) { + + const categoryFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: category['Ид']}, + }) + + //Если уже есть КАТЕГОРИЯ, обновляемся + if(await categoryFind && typeof(await categoryFind[0]) != "undefined") { + + const image = (data['Картинка']) ? true : false; + + try { + const updateEntry = await strapi.entityService.update('api::category.category', categoryFind[0].id, { + data: { + name: category['Наименование'], + id1c: category['Ид'], + }, + }) + + if(await updateEntry) { + console.log("Категория обновлена: ТИП: IMPORT : " + await updateEntry.toString()) + console.log(await updateEntry) + } + + } catch(e) { + console.log(e) + console.log("Ошибка в обновлении товара! file: IMPORT") + } + + } else { + + //Создаем основную категорию + creatorCategories = await strapi.entityService.create('api::category.category', { + data: { + name: category['Наименование'], + id1c: category['Ид'], + }, + }); + + //Выискиываем дочерние + const childs = (category['Группы'] && typeof(category['Группы']['Группа']) != "undefined") ? category['Группы']['Группа'] : false; + if(!childs) return false; + + for(const child of childs) { + + const creatorChilds = await strapi.entityService.create('api::category.category', { + data: { + name: child['Наименование'], + id1c: child['Ид'], + parent: { + connect: [creatorCategories.id] + } + }, + }); + + } + + } + + } + ////Чекаем товары и создаем их в категориях + for (const item of data) { + + const index = data.indexOf(item); + + if (item['ЗначенияРеквизитов']) { + + try { + + const categoryFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: item['Группы']['Ид']}, + }) + + if(await categoryFind && categoryFind[0]) { + //console.log(categoryFind) + console.log("Категория товара найдена! " + await categoryFind[0].id) + await createProduct(item,await categoryFind[0], foldername) + } else { + //console.log("Товар без категории. Ошибка в данных 99%") + } + + } catch (e) { + + console.log(e) + console.log(item) + console.log("Ошибка в создании каталога!") + continue; + + } + + } + } +} + +/** + * @description Работа с ценами и остатками + * @param data + * @returns {Promise} + */ +const salesWorking = async (data = [{}], placesArray = []) => { + + if(!Array.isArray(data)) return false; + + //const placeString2 = (Array.isArray(placesArray['Склад'])) ? placesArray['Склад'].filter((item, index) => item['Ид'] == data['Cклад'][index]['ИдСклада']) : "Нет склада" + console.log(data['Cклад']) + + const placeString = 'Нет склада' + + for (const item of data) { + + const index = data.indexOf(item); + + if(item['Ид']) { + try { + + const entries = await strapi.entityService.findMany('api::product.product', { + fields: ['id1c'], + filters: {'id1c': item['Ид']}, + }) + + if (await entries.length != false) { + + if (item['Цены']) { + //console.log("Попытка задать свойства товара") + if(typeof entries[0] != 'undefined') { + await updateProduct(item, entries[0].id, placeString) + } else { + //console.log("Ошибка поиска товара в БД") + } + } + + } else { + + //console.log("Продукт с таким 1CUid не обнаружен") + + } + + } catch (e) { + + console.log(e) + console.log(item) + console.log("Ошибка в обновлении товара!") + + continue; + } + + } + } +} + + +/** + * @description Создание товара + * @param data + * @param category + * @returns {Promise} + */ +const createProduct = async (data = { }, category = {}, foldername2 = '') => { + + if(!data) return false; + + const groupsToConnect = []; + + try { + + const entries = await strapi.entityService.findMany('api::product.product', { + fields: ['id1c'], + filters: { id1c: data['Ид'] }, + }) + console.log(await entries) + if(typeof await entries[0] == 'undefined') { + try { + if(!data['Ид']) return false + console.log("::::::НАЧАЛО СОЗДАНИЕ ТОВАРА С 1СИД::::::") + + console.log("=> Изображение товара <=") + console.log(data['Картинка']) + + const image = (data['Картинка']) ? true : false + + //Поиск группы и коннект + if(data['Группы']) { + if(Array.isArray(data['Группы'])) { + for(const group of data['Группы']) { + + const categoryManyFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: group['Ид']}, + }) + + if(typeof categoryManyFind[0] == 'undefined') { + groupsToConnect.push(await categoryManyFind[0].id) + } + console.log(categoryManyFind) + } + } else { + console.log(data['Группы']['Ид']) + const categorySoloFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: data['Группы']['Ид']}, + }) + + if(typeof await categorySoloFind[0] != 'undefined') { + console.log(await categorySoloFind) + groupsToConnect.push(await categorySoloFind[0].id) + } + console.log(categorySoloFind) + } + console.log("Дочерние группы товара: " + groupsToConnect.toString()) + } else { + console.log("Товар не привязан к подгруппе. Добавляем в группу") + } + const mainCat = data['ЗначенияРеквизитов']['ЗначениеРеквизита'][1]['Значение'] + + const mainFind = await strapi.entityService.findMany('api::category.category', { + fields: ['name'], + filters: {name: mainCat}, + }) + if(await mainFind) { + groupsToConnect.push(await mainFind[0].id) + } else { + console.log("Не найдена главная категория") + } + console.log("Все группы товара: " + groupsToConnect.toString()) + + let noFormatString = (data['Картинка']) ? data['Картинка'] : null; + + let arrayImages = [] + + if(typeof noFormatString == "string") { + noFormatString.split(',') + if(Array.isArray(noFormatString) && typeof noFormatString[0] != 'undefined') { + arrayImages = [...noFormatString[0]]; + } + } + if(typeof arrayImages[0] == 'undefined') arrayImages.push(noFormatString) + + if(Array.isArray(arrayImages[0])) { + arrayImages = arrayImages[0] + } + /* Создание нового товара через внутреннее api */ + const creatorProduct = await strapi.entityService.create('api::product.product', { + data: { + title: (data['Наименование']) ? `${data['Наименование']}` : "Нет наименования", + description: (typeof data['Описание'] == 'string') ? `${data['Описание'] }`: "Нет описания", + id1c: (data['Ид']) ? `${data['Ид']}` : null, + imgs: (image) ? await strapi.plugins['upload'].services.upload.upload( + { data: {fileInfo: {}}, files: { + path: (noFormatString) ? path.resolve(`/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/${foldername2}/${arrayImages[0]}`): null, // Put your file path + name: "${data['Картинка']", + type: 'image/jpg' + }} + ) : null, + //stock: ( data['Количество']) ? data['Количество'] : "Уточнять", + //storeplace: ( data['Город']) ? data['Город'] : "Склад неизвестен", + quantitySales: '0', + //price: ( data['Цена']) ? data['Цена'] : 0, + categories: { + connect: [...groupsToConnect] + } + //priceOpt: ( data['ЦенаОпт']) ? data['ЦенаОпт'] : 0, + }, + populate: ['categories'] + }); + if(arrayImages) { + console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!ТОВАР СОЗДАН!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + console.log("Товар создан") + console.log(creatorProduct) + console.log("Путь до картинки") + console.log(arrayImages) + } + } catch(e) { + console.log("!!!!!!!!!!!!!!Ошибка создания товара!!!!!!!!!!!!") + console.log(e) + } + } else { + /* Обновление существующего товара через внутреннее api */ + + if(typeof entries[0].id1c != 'undefined') { + console.log("Обновление товара из IMPORT") + //Поиск группы и коннект + //Поиск группы и коннект + if(data['Группы']) { + if(Array.isArray(data['Группы'])) { + for(const group of data['Группы']) { + + const categoryManyFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: group['Ид']}, + }) + + if(typeof categoryManyFind[0] == 'undefined') { + groupsToConnect.push(await categoryManyFind[0].id) + } + console.log(categoryManyFind) + } + } else { + console.log(data['Группы']['Ид']) + const categorySoloFind = await strapi.entityService.findMany('api::category.category', { + fields: ['id1c'], + filters: {id1c: data['Группы']['Ид']}, + }) + + if(typeof await categorySoloFind[0] != 'undefined') { + //console.log(await categorySoloFind) + groupsToConnect.push(await categorySoloFind[0].id) + } + //console.log(categorySoloFind) + } + //console.log("Дочерние группы товара: " + groupsToConnect.toString()) + } else { + //console.log("Товар не привязан к подгруппе. Добавляем в группу") + } + const mainCat = data['ЗначенияРеквизитов']['ЗначениеРеквизита'][1]['Значение'] + + const mainFind = await strapi.entityService.findMany('api::category.category', { + fields: ['name'], + filters: {name: mainCat}, + }) + if(await mainFind) { + groupsToConnect.push(await mainFind[0].id) + } else { + console.log("Не найдена главная категория") + } + console.log("Все группы товара: " + groupsToConnect.toString()) + + + let noFormatString = (data['Картинка']) ? data['Картинка'] : null; + + let arrayImages = [] + + if(typeof noFormatString == "string") { + noFormatString.split(',') + if(Array.isArray(noFormatString) && typeof noFormatString[0] != 'undefined') { + arrayImages = [...noFormatString[0]]; + } + } + if(typeof arrayImages[0] == 'undefined') arrayImages.push(noFormatString) + + if(Array.isArray(arrayImages[0])) { + arrayImages = arrayImages[0] + } + let image = (noFormatString) ? fs.readFileSync(`/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/${foldername2}/${arrayImages[0]}`, (file) => file) : null; + + if(data['Наименование']) { + const updateEntry = await strapi.entityService.update('api::product.product', entries[0].id, { + data: { + id1c: data['Ид'], + imgs: (image) ? await strapi.plugins['upload'].services.upload.upload( + { data: {fileInfo: {}}, files: { + path: (noFormatString) ? path.resolve(`/usr/share/nginx/html/back/public/uploads/exchangeStrapi/tempXMLS/${foldername2}/${arrayImages[0]}`) : null, // Put your file path + name: "${data['Картинка']", + type: 'image/jpg' + }} + ) : null, + categories: { + set: [...groupsToConnect] + } + }, + }); + if(arrayImages) { + console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!ТОВАР ОБНОВЛЕН!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") + console.log(await updateEntry) + console.log("Путь до картинки") + console.log(arrayImages) + } + } + /* Пишем тут что надо делать в случае найденного совпадения в каталоге*/ + + } else { + } + + } + + + } catch(e) { + console.log(e) + console.log("Ошибка в работе с товаром!") + } +} + +/** + * @description Обновление товара + * @param data + * @param category + * @returns {Promise} + */ +const updateProduct = async (data = { }, itemId = 0, storeplace = 'Не назначен') => { + + //console.log(":::::::::::::: SALES MODe UPDATE ТОВАР :::::::::::::::") + //console.log(data) + if(!data || !data['Ид']) return false; + + try { + if(data['Наименование']) { + if(Array.isArray(data['Цены']['Цена'])) { + const updateEntry = await strapi.entityService.update('api::product.product', itemId, { + data: { + stock:(typeof data['Количество'] != 'undefined') ? data['Количество'] : '0', + storeplace: (storeplace) ? `${storeplace}` : 'Не назначен', + price:(typeof data['Цены']['Цена'][0]['ЦенаЗаЕдиницу'] != 'undefined') ? `${data['Цены']['Цена'][0]['ЦенаЗаЕдиницу']}` : '0', + priceOpt: (typeof data['Цены']['Цена'][1]['ЦенаЗаЕдиницу'] != 'undefined') ? `${data['Цены']['Цена'][1]['ЦенаЗаЕдиницу']}` : '0', + }, + }); + //console.log("Товар обновлен: ТИП:sales: " + updateEntry.toString()) + //if(await updateEntry) console.log(updateEntry) + } else { + const updateEntry = await strapi.entityService.update('api::product.product', itemId, { + data: { + stock:(typeof data['Количество'] != 'undefined') ? data['Количество'] : '0', + storeplace: (storeplace) ? `${storeplace}` : 'Не назначен', + price:(typeof data['Цены']['Цена']['ЦенаЗаЕдиницу'] != 'undefined') ? `${data['Цены']['Цена']['ЦенаЗаЕдиницу']}` : '', + priceOpt: '', + }, + }); + //console.log("Товар обновлен: ТИП:sales: " + updateEntry.toString()) + if(await updateEntry) { + //console.log(updateEntry) + } + } + + } + } catch(e) { + console.log(e) + console.log("Ошибка в создании товара!") + } +} +/* + const categoryEntry = await strapi.entityService.create('api::category.category', { + data: { + title: 'My Article', + }, + }); + */ + +const clearProduct = async (start = 0, end = 1) => { + for(let i = start; i < end; i++ ) { + const deleteEntry = await strapi.entityService.delete('api::product.product', i); + console.log(deleteEntry) + } +} diff --git a/server/routes/index.js b/server/routes/index.js index 8fe7e01..397480a 100644 --- a/server/routes/index.js +++ b/server/routes/index.js @@ -1,10 +1,8 @@ - +// /exchange?type=catalog&mode=checkauth const fs = require("fs"); module.exports = [ - //Старый роут, сейчас не используется - //Так же надо будет удалить контроллер { method: 'GET', path: '/', @@ -14,8 +12,9 @@ module.exports = [ middlewares: [], } }, + /* - //РОУТ ДЛЯ php отчета о сохранение файла. + */ { method: 'GET', path: '/new_files',