mirror of
https://github.com/retailcrm/opencart-module.git
synced 2025-04-05 22:33:37 +03:00
Compare commits
189 commits
Author | SHA1 | Date | |
---|---|---|---|
|
b1d013dd30 | ||
|
c5916fc8f2 | ||
|
2c6cccc3b1 | ||
|
c893cf24fb | ||
|
d5f29dc5fe | ||
|
3a30986e4b | ||
|
571263ca2c | ||
|
a375804086 | ||
|
a56ce789ed | ||
|
f5f55dd449 | ||
|
62605b11ed | ||
|
22a9c2d819 | ||
|
a2a4eca8c7 | ||
|
63f625b329 | ||
|
6a7f395116 | ||
|
792546d007 | ||
|
7d3390bc02 | ||
|
ef6d09c03a | ||
|
e4cfdd8c9f | ||
|
8b7522ca6c | ||
|
b6181ab426 | ||
|
3e1c19fd8d | ||
|
090a5783c5 | ||
|
feaeca458f | ||
|
b22941cc3e | ||
|
6790cf7b0e | ||
463485509e | |||
|
78806e4aef | ||
|
4f15310fbb | ||
a1f97bc996 | |||
|
d058173aa4 | ||
|
4e09c021c8 | ||
f4e892d71a | |||
|
92d94c919e | ||
|
8445980d5a | ||
|
072b3a95b0 | ||
|
a0337479ae | ||
|
9e85d3bffb | ||
|
60998ad74f | ||
|
08df9043fa | ||
|
7cdab05aa2 | ||
|
4359f084bd | ||
|
6391f49d2b | ||
|
828cc72930 | ||
|
7ed233450c | ||
|
24222d66ca | ||
|
ff87f7939e | ||
|
bb23c4cc40 | ||
|
cd7f63562d | ||
|
29bdecfc96 | ||
|
75fc11c6f9 | ||
|
fb7290f865 | ||
|
c2abd5acd8 | ||
|
579150ea08 | ||
|
769f35f379 | ||
|
1d9110c364 | ||
|
28391f4134 | ||
|
2dbb56897e | ||
|
85f47c1984 | ||
2dbccd8a02 | |||
|
739c2775b5 | ||
|
6b2d6aeb80 | ||
|
6a221ab5f8 | ||
|
bc16a2a6f3 | ||
|
85de4835d5 | ||
|
d73219fcbb | ||
|
2981afb05a | ||
|
fb5d969ccc | ||
|
434ec7b431 | ||
|
caf55f67ad | ||
|
53767392e9 | ||
|
0d0f0aa1d0 | ||
|
fa3b9e44b3 | ||
|
b57ff08d31 | ||
|
ce07e06b55 | ||
|
41da8fe862 | ||
|
dc2bee57d4 | ||
|
5e695863a3 | ||
|
14e6584abf | ||
|
b921bc8c37 | ||
|
e7270aac4b | ||
|
a48ef3e1ea | ||
|
440e16b50b | ||
|
8c8ee17c3d | ||
|
fc7c004988 | ||
|
84ed83f887 | ||
|
24cc5e57a6 | ||
|
d7221ecd9b | ||
|
9c8ad156c7 | ||
|
5b58d030c9 | ||
|
752b11a2b6 | ||
|
1971aa0cb4 | ||
|
27af27c1eb | ||
|
3b6b3d0d9d | ||
|
4b57be19e1 | ||
|
137c83aa66 | ||
|
f0f3b65c02 | ||
|
266e8de11e | ||
|
5d6fd908f2 | ||
|
6bf58537ee | ||
|
c0f46cb672 | ||
|
d0467c020e | ||
|
74a36756f6 | ||
|
dc9458f434 | ||
|
670e7ecfbd | ||
|
2551e11e4c | ||
|
4a8875dc8d | ||
|
b29b4e1a51 | ||
|
2014deda25 | ||
|
1317770335 | ||
|
f8b651c70f | ||
|
04da58c185 | ||
|
bc0d3660ad | ||
|
5f60b761f0 | ||
|
24413ee15b | ||
|
353557effe | ||
|
7c0f4d5197 | ||
|
1cce01d50e | ||
|
6d1cfa4d0c | ||
|
979fdf58b6 | ||
|
c8690e8252 | ||
|
de3a1ae7e7 | ||
|
2f099d477c | ||
|
9e1edf2fcc | ||
|
090a4b6cfa | ||
|
033bac97cf | ||
|
799c260189 | ||
|
3516378d7e | ||
|
484d738e70 | ||
|
2b5faed85b | ||
|
1caf5860a8 | ||
|
9d90c32b17 | ||
|
3d055a01fe | ||
|
81d1d5e94e | ||
|
81737b4df3 | ||
|
2da9acf18d | ||
|
1c5053d81f | ||
|
30e6cb9886 | ||
|
268e5b4279 | ||
|
82ff3628cd | ||
|
60b65cc6d4 | ||
|
f4ced73be4 | ||
|
90e7c8913c | ||
|
0e90d26dee | ||
|
9e5b1ba2d8 | ||
|
74a5d2c642 | ||
|
f71002f4d6 | ||
|
93bacf9b7b | ||
bc0469f8cf | |||
|
a69c4be480 | ||
|
eb83212094 | ||
|
39d596e49d | ||
|
1852d5cb08 | ||
|
4313505fe5 | ||
66d3963dd5 | |||
|
702c18d757 | ||
|
3d9b51704e | ||
|
c057540b9d | ||
|
adf390c286 | ||
|
41ac83aeff | ||
|
d58b66a01b | ||
|
08d071edda | ||
|
068c444c73 | ||
|
03679ea62e | ||
|
9fedcb096c | ||
|
48ccded014 | ||
|
8a823cf3ad | ||
|
6443e10330 | ||
|
24c6de76ec | ||
|
3521bb603e | ||
|
f79ed21018 | ||
|
615d9c7c17 | ||
|
db80810584 | ||
|
c27383154b | ||
|
ed5de5186e | ||
|
ee36226b31 | ||
|
dfd6c4a76d | ||
|
d54e5e8c19 | ||
|
0498e4d761 | ||
|
cfcac1e013 | ||
|
3e55de0e3a | ||
|
bceb2069ac | ||
|
5b700332b6 | ||
|
9fb324188b | ||
|
bca86cc51c | ||
|
0787d4a997 | ||
|
75aed59403 | ||
|
273499acdc | ||
|
0854d36155 |
119 changed files with 8761 additions and 7495 deletions
58
.docker/Dockerfile
Normal file
58
.docker/Dockerfile
Normal file
|
@ -0,0 +1,58 @@
|
|||
FROM php:7.1-apache
|
||||
|
||||
RUN apt-get update
|
||||
|
||||
RUN apt-get install -y netcat zlib1g-dev libpq-dev git libicu-dev libxml2-dev libpng-dev libjpeg-dev libmcrypt-dev libxslt-dev libfreetype6-dev unzip \
|
||||
&& docker-php-ext-configure intl \
|
||||
&& docker-php-ext-install intl \
|
||||
&& docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
|
||||
&& docker-php-ext-install mysqli pdo pdo_mysql \
|
||||
&& docker-php-ext-install zip \
|
||||
&& docker-php-ext-install xml \
|
||||
&& docker-php-ext-configure gd --with-png-dir=/usr/local/ --with-jpeg-dir=/usr/local/ --with-freetype-dir=/usr/local/ \
|
||||
&& docker-php-ext-install gd \
|
||||
&& docker-php-ext-install mcrypt \
|
||||
&& docker-php-ext-install bcmath \
|
||||
&& docker-php-ext-install soap \
|
||||
&& docker-php-ext-install xsl \
|
||||
&& docker-php-ext-install mbstring
|
||||
|
||||
RUN apt-get install -y wget
|
||||
|
||||
RUN wget -O /usr/bin/phpunit https://phar.phpunit.de/phpunit-7.phar && chmod +x /usr/bin/phpunit
|
||||
RUN curl --insecure https://getcomposer.org/download/1.9.3/composer.phar -o /usr/bin/composer && chmod +x /usr/bin/composer
|
||||
|
||||
# Set timezone
|
||||
RUN rm /etc/localtime && \
|
||||
ln -s /usr/share/zoneinfo/Europe/Moscow /etc/localtime && \
|
||||
"date"
|
||||
|
||||
ARG TEST_SUITE
|
||||
ARG OPENCART
|
||||
ARG SERVER_PORT
|
||||
ARG OC_DB_HOSTNAME
|
||||
ARG OC_DB_USERNAME
|
||||
ARG OC_DB_PASSWORD
|
||||
ARG OC_DB_DATABASE
|
||||
ARG OC_USERNAME
|
||||
ARG OC_PASSWORD
|
||||
ARG OC_EMAIL
|
||||
|
||||
ENV TEST_SUITE=${TEST_SUITE}
|
||||
ENV OPENCART=${OPENCART}
|
||||
ENV PORT=${SERVER_PORT}
|
||||
ENV OC_DB_HOSTNAME=${OC_DB_HOSTNAME}
|
||||
ENV OC_DB_USERNAME=${OC_DB_USERNAME}
|
||||
ENV OC_DB_PASSWORD=${OC_DB_PASSWORD}
|
||||
ENV OC_DB_DATABASE=${OC_DB_DATABASE}
|
||||
ENV OC_USERNAME=${OC_USERNAME}
|
||||
ENV OC_PASSWORD=${OC_PASSWORD}
|
||||
ENV OC_EMAIL=${OC_EMAIL}
|
||||
|
||||
ADD .docker/entrypoint.sh /usr/local/bin/docker-php-entrypoint
|
||||
|
||||
RUN chmod +x /usr/local/bin/docker-php-entrypoint
|
||||
|
||||
RUN sed -i "s/80/$PORT/g" /etc/apache2/sites-enabled/000-default.conf /etc/apache2/ports.conf && \
|
||||
sed -i 's/var\/www\/html/opencart-module\/www/g' /etc/apache2/sites-enabled/000-default.conf && \
|
||||
sed -i 's/var\/www/opencart-module/g' /etc/apache2/apache2.conf
|
28
.docker/entrypoint.sh
Normal file
28
.docker/entrypoint.sh
Normal file
|
@ -0,0 +1,28 @@
|
|||
#!/bin/sh
|
||||
|
||||
until nc -z -v -w30 mysql 3306
|
||||
do
|
||||
echo "Waiting for database connection..."
|
||||
sleep 5
|
||||
done
|
||||
|
||||
make -C /opencart-module run
|
||||
|
||||
mkdir -p /opencart-module/www/system/storage/session
|
||||
|
||||
sed -i 's/\?>//g' /opencart-module/www/config.php
|
||||
sed -i 's/\?>//g' /opencart-module/www/admin/config.php
|
||||
echo '\nini_set("session.save_path", DIR_SYSTEM . "storage/session");' >> /opencart-module/www/config.php
|
||||
echo '\nini_set("session.save_path", DIR_SYSTEM . "storage/session");' >> /opencart-module/www/admin/config.php
|
||||
|
||||
#chown -R www-data:www-data /opencart-module \
|
||||
# && find /opencart-module -type d -exec chmod 755 {} \; \
|
||||
# && find /opencart-module -type f -exec chmod 644 {} \;
|
||||
|
||||
# first arg is `-f` or `--some-option`
|
||||
if [ "${1#-}" != "$1" ]; then
|
||||
set -- apache2-foreground "$@"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
|
18
.env-dist
Normal file
18
.env-dist
Normal file
|
@ -0,0 +1,18 @@
|
|||
# OpenCart Database connection values
|
||||
OC_DB_HOSTNAME=mysql
|
||||
OC_DB_USERNAME=opencart
|
||||
OC_DB_PASSWORD=opencart
|
||||
OC_DB_DATABASE=opencart
|
||||
OC_DB_DRIVER=mysqli
|
||||
|
||||
# OpenCart Administration user
|
||||
OC_USERNAME=admin
|
||||
OC_PASSWORD=admin
|
||||
OC_EMAIL=you@example.com
|
||||
|
||||
# Server Specification
|
||||
SERVER_PORT=8080
|
||||
SERVER_URL=http://localhost
|
||||
|
||||
TEST_SUITE=3
|
||||
OPENCART=3.0.2.0
|
202
.github/workflows/ci.yml
vendored
Normal file
202
.github/workflows/ci.yml
vendored
Normal file
|
@ -0,0 +1,202 @@
|
|||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
tags-ignore:
|
||||
- '*.*'
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
OC_DB_HOSTNAME: 127.0.0.1
|
||||
OC_DB_USERNAME: root
|
||||
OC_DB_PASSWORD: root
|
||||
OC_DB_DATABASE: tests_opencart
|
||||
OC_DB_DRIVER: mysqli
|
||||
OC_USERNAME: admin
|
||||
OC_PASSWORD: admin
|
||||
OC_EMAIL: test@test.com
|
||||
SERVER_PORT: 80
|
||||
SERVER_URL: http://localhost
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.1.1'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.1.2'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.2.0'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.0'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.1'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.2'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.3'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.4'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.5'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.6'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.7'
|
||||
- php-version: '7.3'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.8'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.1.1'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.1.2'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.2.0'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.0'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.1'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.2'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.3'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.4'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.5'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.6'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.7'
|
||||
- php-version: '7.4'
|
||||
test-suite: '3'
|
||||
oc: '3.0.3.8'
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:5.7
|
||||
env:
|
||||
MYSQL_ALLOW_EMPTY_PASSWORD: false
|
||||
MYSQL_ROOT_PASSWORD: ${{ env.OC_DB_PASSWORD }}
|
||||
MYSQL_DATABASE: ${{ env.OC_DB_DATABASE }}
|
||||
ports:
|
||||
- 3306:3306
|
||||
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=5
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup PHP ${{ matrix.php-version }}
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: ${{ matrix.php-version }}
|
||||
coverage: xdebug
|
||||
tools: composer:v1
|
||||
extensions: gd, mbstring, mysqli, zip, mcrypt, mysql, pdo_mysql, dom
|
||||
- name: Install Opencart
|
||||
env:
|
||||
TEST_SUITE: ${{ matrix.test-suite }}
|
||||
OPENCART: ${{ matrix.oc }}
|
||||
run: make before_script
|
||||
- name: Run tests
|
||||
env:
|
||||
TEST_SUITE: ${{ matrix.test-suite }}
|
||||
OPENCART: ${{ matrix.oc }}
|
||||
run: composer test
|
||||
- name: Coverage
|
||||
env:
|
||||
COVERAGE: ${{ matrix.coverage }}
|
||||
if: env.COVERAGE == 1
|
||||
run: |
|
||||
make coverage
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
phpcs:
|
||||
needs: ['test']
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup PHP 7.2
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '7.2'
|
||||
tools: composer:v1
|
||||
- name: Install dependencies
|
||||
run: composer install
|
||||
- name: Check compatibility
|
||||
run: make phpcomp
|
||||
deploy:
|
||||
needs: ['phpcs']
|
||||
if: success() && github.event_name == 'push' && github.repository_owner == 'retailcrm' && github.ref == 'refs/heads/master'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Setup PHP 7.2
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '7.2'
|
||||
tools: composer:v1
|
||||
- name: Build release
|
||||
run: |
|
||||
git fetch origin --unshallow --tags
|
||||
export LAST_TAG=`git describe --abbrev=0 --tags`
|
||||
export VERSION=`cat VERSION`
|
||||
export ARCHIVE_NAME=retailcrm-$VERSION.ocmod.zip
|
||||
export ARCHIVE_PATH="/tmp/$ARCHIVE_NAME"
|
||||
export RELEASE_TAG=v$VERSION
|
||||
export LAST_COMMIT=`git log --oneline --format=%B -n 1 HEAD | head -n 1`
|
||||
echo RELEASE_TAG=$RELEASE_TAG >> $GITHUB_ENV
|
||||
echo LAST_TAG=$LAST_TAG >> $GITHUB_ENV
|
||||
echo LAST_COMMIT=$LAST_COMMIT >> $GITHUB_ENV
|
||||
echo ARCHIVE_PATH=$ARCHIVE_PATH >> $GITHUB_ENV
|
||||
echo ARCHIVE_NAME=$ARCHIVE_NAME >> $GITHUB_ENV
|
||||
make build_archive
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
if: env.LAST_TAG != env.RELEASE_TAG
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ env.RELEASE_TAG }}
|
||||
release_name: ${{ env.RELEASE_TAG }}
|
||||
body: ${{ env.LAST_COMMIT }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
- name: Upload Release Asset
|
||||
id: upload-release-asset
|
||||
if: env.LAST_TAG != env.RELEASE_TAG
|
||||
uses: actions/upload-release-asset@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: ${{ env.ARCHIVE_PATH }}
|
||||
asset_name: ${{ env.ARCHIVE_NAME }}
|
||||
asset_content_type: application/zip
|
||||
- name: Cleanup
|
||||
if: env.LAST_TAG != env.RELEASE_TAG
|
||||
run: make delete_archive
|
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -7,3 +7,4 @@
|
|||
/www
|
||||
/bin
|
||||
.env
|
||||
composer.lock
|
42
.travis.yml
42
.travis.yml
|
@ -1,42 +0,0 @@
|
|||
language: php
|
||||
|
||||
sudo: false
|
||||
|
||||
php:
|
||||
- 7.1
|
||||
- 7.2
|
||||
|
||||
env:
|
||||
global:
|
||||
- OC_DB_HOSTNAME=localhost
|
||||
- OC_DB_USERNAME=root
|
||||
- OC_DB_PASSWORD=root
|
||||
- OC_DB_DATABASE=tests_opencart
|
||||
- OC_DB_DRIVER=mysqli
|
||||
- OC_USERNAME=admin
|
||||
- OC_PASSWORD=admin
|
||||
- OC_EMAIL=test@test.com
|
||||
- SERVER_PORT=8000
|
||||
- SERVER_URL=http://localhost
|
||||
|
||||
before_script:
|
||||
# Change MySQL root password
|
||||
- echo "USE mysql;\nUPDATE user SET password=PASSWORD('root') WHERE user='root';\nFLUSH PRIVILEGES;\n" | mysql -u root
|
||||
|
||||
- composer install
|
||||
- composer setup
|
||||
- bin/robo project:deploy
|
||||
- (php -S localhost:8000 -t www &) 2> /dev/null > /dev/null
|
||||
- sleep 2
|
||||
|
||||
script:
|
||||
- composer test
|
||||
|
||||
deploy:
|
||||
skip_cleanup: true
|
||||
provider: script
|
||||
script: make
|
||||
on:
|
||||
php: 7.1
|
||||
branch: master
|
||||
condition: "$DEPLOY = false"
|
189
CHANGELOG.md
189
CHANGELOG.md
|
@ -1,61 +1,182 @@
|
|||
## v4.1.19
|
||||
* Added option to round order amount
|
||||
|
||||
## v4.1.18
|
||||
* Fixed constant with version of module.
|
||||
|
||||
## v4.1.17
|
||||
* Added additional parameters to GET requests.
|
||||
|
||||
## v4.1.16
|
||||
* Support for services in ICML
|
||||
|
||||
## v4.1.15
|
||||
* Display module version
|
||||
|
||||
## v4.1.14
|
||||
* Added currency validation when configuring the module
|
||||
|
||||
## v4.1.13
|
||||
* Changed the logic of customer subscriptions to promotional newsletters
|
||||
|
||||
## v4.1.12
|
||||
* Added escaping for db query in method for getting zone
|
||||
|
||||
## v4.1.11
|
||||
* Fixed the transfer of the weight offers
|
||||
|
||||
## v4.1.10
|
||||
* Types of deliveries and payments are displayed only active status and available stores
|
||||
|
||||
## v4.1.9
|
||||
* Optimization of the history processing algorithm
|
||||
|
||||
## v4.1.8
|
||||
* Fixed customer externalId when creating a customer and sending it to RetailCRM
|
||||
|
||||
## v4.1.7
|
||||
* Fixed notices in ICML generation and while setting delivery type
|
||||
* Fixed incorrect data check before setting payment data
|
||||
* Some other minor improvements
|
||||
|
||||
## v4.1.6
|
||||
* Fix for typo in the history routine
|
||||
* Fix for incorrect protocol in the ICML product image links
|
||||
|
||||
## v4.1.5
|
||||
* Send discount details into the system
|
||||
* Prefix for payment external ID (to ensure that it's unique)
|
||||
* Make payment sum optional
|
||||
* Weight calculation based on product options
|
||||
|
||||
## v.4.1.4
|
||||
* Create payment only when the payment type is specified
|
||||
* Checking the availability of promotional price for the product when uploading the order
|
||||
|
||||
## v.4.1.3
|
||||
* Removed the ability to specify the API version
|
||||
|
||||
## v.4.1.2
|
||||
* Added accounting for a gift certificate price when creating an order and sending it to RetailCRM
|
||||
|
||||
## v.4.1.1
|
||||
* Updated the mechanics of processing customer addresses
|
||||
|
||||
## v.4.1.0
|
||||
* Added the ability to connect Online Consultant
|
||||
|
||||
## v.4.0.1
|
||||
* Fixed the transfer of coupon discounts
|
||||
* Fixed console commands
|
||||
|
||||
## v.4.0.0
|
||||
* Added support for corporate customers
|
||||
* Added support for changing the customer in the order
|
||||
|
||||
## v.3.3.9
|
||||
* Fixed prices in ICML
|
||||
|
||||
## v.3.3.8
|
||||
* Fixed warnings output when generating ICML
|
||||
|
||||
## v.3.3.7
|
||||
* Changed the configuration of travis-ci for build
|
||||
|
||||
## v.3.3.6
|
||||
* Minor bug fixes
|
||||
|
||||
## v.3.3.5
|
||||
* Added generation of dimensions in the catalog
|
||||
|
||||
## v.3.3.4
|
||||
* Fixed a bug with incorrect uploading of promotional prices for products with characteristics
|
||||
|
||||
## v.3.3.3
|
||||
* Added removal of product's price type for unidentified promotional prices
|
||||
|
||||
## v.3.3.2
|
||||
* Added the return of leftover product stocks when the order is canceled
|
||||
|
||||
## v.3.3.1
|
||||
* Fixed a bug with sending order data to RetailCRM when receiving the history of changes from RetailCRM
|
||||
|
||||
## v.3.3.0
|
||||
* Added setting for recording the history of order changes in Opencart
|
||||
* Fixed a bug with calling the order editing event when uploading the history of changes from RetailCRM
|
||||
* Added transfer of the price type when creating or editing an order
|
||||
|
||||
## v.3.2.4
|
||||
* Added the ability to transfer promotional prices for multiple user groups
|
||||
* Added the ability to transfer zero price for unspecified promotional prices
|
||||
* Removed the retailcrm base price from the price types conformity settings
|
||||
|
||||
## v.3.2.2
|
||||
* Removed generation of the customer's externalId when order was created without registeration on the website.
|
||||
|
||||
## v.3.2.1
|
||||
* Changed the logic for transferring data for orders and customers. Contact information for delivery is transferred to the order's card, and the payer's contact information is transferred to the customer's card.
|
||||
|
||||
## v.3.2.0
|
||||
* Added uploading images for categories in ICML
|
||||
* Added setting for selecting the currency in which the price will be uploaded in ICML
|
||||
|
||||
## v.3.1.6
|
||||
* Fixed getting events from the database for OC 3.0
|
||||
|
||||
## v.3.1.5
|
||||
* Добавлена генерация габаритов в катало
|
||||
* Bug fixes
|
||||
|
||||
## v.3.1.4
|
||||
* Добавлено удаление типа цены для неустановленных акционных цен
|
||||
|
||||
* Fixed incorrect combining of delivery types
|
||||
|
||||
## v.3.1.3
|
||||
* Добавлена возможность передачи акционных цен для нескольких групп пользователей
|
||||
* Добавлена передача нулевой цены для неустановленных акционных цен
|
||||
* Убрана базовая цена retailcrm из настроек соответствия типов цен
|
||||
* Added module activation in the RetailCRM marketplace
|
||||
|
||||
## v.3.1.2
|
||||
* Добавлен перевод на испанский язык
|
||||
* Переделан перевод на английский язык
|
||||
* Added Spanish translation
|
||||
* Reworked English translation
|
||||
|
||||
## v.3.1.1
|
||||
* Добавлено создание клиента при ручной выгрузке заказа из админки
|
||||
* Added customer creation when manually uploading an order from admin panel
|
||||
|
||||
## v.3.1.0
|
||||
* Переработан дизайн шаблона twig
|
||||
* Добавлена настройка передачи номера заказа в retailCRM
|
||||
* Улучшена механика передачи типа доставки в retailCRM
|
||||
* Исправлена ошибка при выгрузке единичного заказа в админ панели
|
||||
* Redesigned the twig template
|
||||
* Added a setting for transmitting the order number to RetailCRM
|
||||
* Improved mechanics of delivery type transfer to RetailCRM
|
||||
* Fixed an error when uploading a single order in admin panel
|
||||
|
||||
## v.3.0.5
|
||||
* Исправлены ошибки в шаблоне twig
|
||||
* Добавлена обработка истории изменений при сохранении настроек для установки текущего sinceId, если история в retailCRM пустая
|
||||
* Fixed errors in the twig template
|
||||
* Added processing of the history of changes when saving settings for setting the current sinceId, if the history in RetailCRM is empty
|
||||
|
||||
## v.3.0.4
|
||||
* Добавлена проверка группы пользователя в заказе при редактировании
|
||||
* Добавлена передача скидки по бонусным баллам
|
||||
* Added checking the user group in the order when editing
|
||||
* Added transfer of discount for bonus points
|
||||
|
||||
## v.3.0.3
|
||||
* Исправлена ошибка с изменением пароля пользователя
|
||||
* Fixed a bug with changing the user's password
|
||||
|
||||
## v.3.0.2
|
||||
* Улучшена механика выгрузки изменений из RetailCRM на сайт
|
||||
* Улучшена механика выборки типов доставки на сайте
|
||||
* Добавлена возможность периодической выгрузки акционных цен для товаров
|
||||
* Улучшена совместимость с Opencart 3.0
|
||||
* Improved the mechanics of uploading changes from RetailCRM to the site
|
||||
* Improved the mechanics of selecting delivery types on the site
|
||||
* Added the ability to periodically upload promotional prices for products
|
||||
* Improved compatibility with Opencart 3.0
|
||||
|
||||
## v.2.4.3
|
||||
* Устранены некоторые баги, добавлен вывод ошибок при выгрузке единичных заказов
|
||||
* Minor bug fixes, added error output when uploading individual orders
|
||||
|
||||
## v.2.4.2
|
||||
* Улучшена синхронизация кастомных полей
|
||||
* Добавлены настройки дефолтных способов доставки и оплаты
|
||||
* Улучшена настройка Daemon Collector
|
||||
* Доработан шаблон twig для совместимости с Opencart 3.0
|
||||
* Improved synchronization of custom fields
|
||||
* Added settings for default delivery and payment types
|
||||
* Improved Daemon Collector configuration
|
||||
* Improved the twig template for compatibility with Opencart 3.0
|
||||
|
||||
## v.2.4.1
|
||||
* Исправлена работа истории (доработана обработка адресов, добавлена обработка заказов с пустыми полями, доработана история по клиентам)
|
||||
* История теперь синхронизируется по sinceId
|
||||
* Проверка доступных версий API через метод /api/versions
|
||||
* Добавлена возможность сопоставления кастомных полей(для API v5)
|
||||
* Fixed history of changes (improved address processing, added order processing with empty fields, improved customer history)
|
||||
* History is now synced by sinceId
|
||||
* Checking available API versions using the /api/versions method
|
||||
* Added the ability to map custom fields (for API V5)
|
||||
|
||||
## v.2.4.0
|
||||
* Добавлена возможность работы на 3 версиях API (v3, v4, v5)
|
||||
* Добавлена совместимость с Opencart 3.0
|
||||
|
||||
* Added the ability to work on 3 API versions (v3, v4, v5)
|
||||
* Added compatibility with Opencart 3.0
|
||||
|
|
2
LICENSE
2
LICENSE
|
@ -1,6 +1,6 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 RetailDriver LLC
|
||||
Copyright (c) 2015-2021 RetailDriver LLC
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
|
43
Makefile
43
Makefile
|
@ -1,6 +1,8 @@
|
|||
FILE = $(TRAVIS_BUILD_DIR)/VERSION
|
||||
VERSION = `cat $(FILE)`
|
||||
ARCHIVE_NAME = '/tmp/retailcrm-'$(VERSION)'.zip'
|
||||
ROOT_DIR=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
|
||||
VERSION = `cat $(ROOT_DIR)/VERSION`
|
||||
ARCHIVE_NAME = '/tmp/retailcrm-'$(VERSION)'.ocmod.zip'
|
||||
|
||||
.PHONY: coverage
|
||||
|
||||
all: build_archive send_to_ftp delete_archive
|
||||
|
||||
|
@ -11,4 +13,37 @@ send_to_ftp:
|
|||
curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)
|
||||
|
||||
delete_archive:
|
||||
rm -f $(ARCHIVE_NAME)
|
||||
rm -f $(ARCHIVE_NAME)
|
||||
|
||||
before_script:
|
||||
mkdir coverage
|
||||
composer require --dev beyondit/opencart-test-suite:~$(TEST_SUITE)
|
||||
composer opencart:install
|
||||
bin/robo --load-from tests/RoboFile.php project:deploy
|
||||
(php -S localhost:80 -t www &) 2> /dev/null > /dev/null
|
||||
sleep 2
|
||||
|
||||
coverage:
|
||||
wget https://phar.phpunit.de/phpcov-2.0.2.phar && php phpcov-2.0.2.phar merge coverage/ --clover coverage.xml
|
||||
|
||||
robo_deploy:
|
||||
bin/robo --load-from tests/RoboFile.php project:deploy
|
||||
|
||||
run:
|
||||
composer require --dev beyondit/opencart-test-suite ~$(TEST_SUITE)
|
||||
composer opencart:install
|
||||
bin/robo --load-from tests/RoboFile.php project:deploy
|
||||
|
||||
run_test: run
|
||||
(php -S localhost:$(SERVER_PORT) -t www &) 2> /dev/null > /dev/null
|
||||
sleep 2
|
||||
composer test
|
||||
|
||||
test: robo_deploy
|
||||
composer test
|
||||
|
||||
phpcs-config:
|
||||
bin/phpcs --config-set installed_paths vendor/phpcompatibility/php-compatibility
|
||||
|
||||
phpcomp: phpcs-config
|
||||
@bin/phpcs -s -p ./src --standard=PHPCompatibility --runtime-set testVersion 7.3-7.4
|
||||
|
|
47
README.md
47
README.md
|
@ -1,11 +1,12 @@
|
|||
[](https://travis-ci.org/retailcrm/opencart-module)
|
||||
[](https://github.com/retailcrm/opencart-module/releases)
|
||||
[](https://php.net/)
|
||||
[](https://github.com/retailcrm/opencart-module/actions)
|
||||
[](https://codecov.io/gh/retailcrm/opencart-module)
|
||||
[](https://github.com/retailcrm/opencart-module/releases)
|
||||
[](https://php.net/)
|
||||
|
||||
Opencart module
|
||||
===============
|
||||
|
||||
Module allows integrate CMS Opencart >= 2.3 with [retailCRM](http://retailcrm.pro)
|
||||
This module allows to integrate CMS Opencart >= 2.3 with [RetailCRM](https://retailcrm.pro).
|
||||
|
||||
### Previous versions:
|
||||
|
||||
|
@ -15,47 +16,59 @@ Module allows integrate CMS Opencart >= 2.3 with [retailCRM](http://retailcrm.pr
|
|||
|
||||
#### Features:
|
||||
|
||||
* Export orders to retailCRM & fetch changes back
|
||||
* Export product catalog into [ICML](http://www.retailcrm.pro/docs/Developers/ICML) format
|
||||
* Export orders to RetailCRM & receive changes from RetailCRM.
|
||||
* Export product catalog to the [ICML](https://help.retailcrm.pro/Developers/ICML) format.
|
||||
|
||||
#### Install
|
||||
|
||||
Copy files to the site root
|
||||
**Note:** `/path/to/your/site` is just a placeholder. You should replace it with the actual path to your site root in the examples below. The module won't work if you'll use those examples without changing the path placeholder.
|
||||
|
||||
Copy module files to the site root (replace `/path/to/your/site` with the actual path to your site):
|
||||
|
||||
```
|
||||
unzip master.zip
|
||||
cp -r opencart-module/* /path/to/site/root
|
||||
cp -r opencart-module/src/* /path/to/your/site
|
||||
```
|
||||
|
||||
#### Setup
|
||||
|
||||
* Go to Admin -> Extensions -> Modules -> retailCRM
|
||||
* Fill you api url & api key
|
||||
* Go to Admin -> Extensions -> Modules -> RetailCRM
|
||||
* Fill you API URL & API key
|
||||
* Specify directories matching
|
||||
|
||||
#### Migrating to 4.* from early modules versions
|
||||
|
||||
It's necessary to remove the `/path/to/your/site/system/library/retailcrm` before copying current module into your site.
|
||||
|
||||
#### Getting changes in orders
|
||||
|
||||
Add to cron:
|
||||
Add to cron (replace `/path/to/your/site` with the actual path to your site):
|
||||
|
||||
```
|
||||
*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/storage/logs/cronjob_history.log 2>&1
|
||||
*/5 * * * * /usr/bin/php /path/to/your/site/system/library/retailcrm/cron/history.php >> /path/to/your/site/system/storage/logs/cronjob_history.log 2>&1
|
||||
```
|
||||
|
||||
#### Setting product catalog export
|
||||
|
||||
Add to cron:
|
||||
Add to cron (replace `/path/to/your/site` with the actual path to your site):
|
||||
|
||||
```
|
||||
* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/storage/logs/cronjob_icml.log 2>&1
|
||||
* */4 * * * /usr/bin/php /path/to/your/site/system/library/retailcrm/cron/icml.php >> /path/to/your/site/system/storage/logs/cronjob_icml.log 2>&1
|
||||
```
|
||||
|
||||
Your export file will be available by following url
|
||||
Your export file should be available by following url:
|
||||
|
||||
```
|
||||
http://youropencartsite.com/retailcrm.xml
|
||||
```
|
||||
|
||||
Replace `youropencartsite.com` with your site domain and `http` with your site scheme.
|
||||
|
||||
#### Export existing orders and customers
|
||||
|
||||
You want to run this command onecly:
|
||||
/usr/bin/php /path/to/opencart/system/cron/export.php
|
||||
Run this command (replace `/path/to/your/site` with the actual path to your site):
|
||||
```sh
|
||||
/usr/bin/php /path/to/your/site/system/library/retailcrm/cron/export.php
|
||||
```
|
||||
|
||||
You should run this command only once.
|
||||
|
|
73
README.ru.md
73
README.ru.md
|
@ -1,73 +0,0 @@
|
|||
Opencart module
|
||||
===============
|
||||
|
||||
Модуль интеграции CMS Opencart >= 2.3 c [retailCRM](https://retailcrm.ru)
|
||||
|
||||
Информация о [кастомизации](https://github.com/retailcrm/opencart-module/wiki/%D0%9A%D0%B0%D1%81%D1%82%D0%BE%D0%BC%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F-%D0%B8%D0%BD%D1%82%D0%B5%D0%B3%D1%80%D0%B0%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D0%BE%D0%B3%D0%BE-%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D0%B0)
|
||||
|
||||
### Предыдущие версии:
|
||||
|
||||
[v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x)
|
||||
|
||||
[v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2)
|
||||
|
||||
#### Модуль позволяет:
|
||||
|
||||
* Экспортировать в retailCRM данные о заказах и клиентах и получать обратно изменения по этим данным
|
||||
* Синхронизировать справочники (способы доставки и оплаты, статусы заказов и т.п.)
|
||||
* Выгружать каталог товаров в формате [ICML](http://www.retailcrm.ru/docs/Developers/ICML)
|
||||
|
||||
#### Установка
|
||||
|
||||
Установите модуль скопировав необходимые файлы в корень сайта
|
||||
|
||||
```
|
||||
unzip master.zip
|
||||
cp -r opencart-module/* /path/to/site/root
|
||||
```
|
||||
|
||||
#### Активируйте модуль
|
||||
|
||||
В списке модулей нажмите "Установить"
|
||||
|
||||
#### Настройте параметры интеграции
|
||||
|
||||
На странице настроек модуля укажите URL retailCRM и ключ авторизации, после сохранения этих данных укажите соответствия справочников типов доставок, оплат и статусов заказа.
|
||||
|
||||
#### Получение измений из retailCRM
|
||||
|
||||
Для получения изменений и новых данных добавьте в cron следующую запись:
|
||||
|
||||
```
|
||||
*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/storage/logs/cronjob_history.log 2>&1
|
||||
```
|
||||
|
||||
#### Настройка экспорта каталога
|
||||
|
||||
Для периодической выгрузки каталога добавьте в cron следующую запись:
|
||||
|
||||
```
|
||||
* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/storage/logs/cronjob_icml.log 2>&1
|
||||
```
|
||||
|
||||
В настройках retailCRM установите путь к файлу выгрузки
|
||||
|
||||
```
|
||||
http://youropencartsite.com/retailcrm.xml
|
||||
```
|
||||
#### Настройка выгрузки акционных цен
|
||||
|
||||
Для периодической выгрузки акционных цен в CRM в настройках модуля укажите тип цены, в который необходимо выгружать акционные цены, в крон добавьте следующую запись
|
||||
|
||||
```
|
||||
0 0 * * * /usr/bin/php /path/to/opencart/system/cron/prices.php >> /path/to/opencart/system/storage/logs/cronjob_prices.log 2>&1
|
||||
```
|
||||
|
||||
#### Выгрузка существующих заказов и покупателей
|
||||
|
||||
Запустите команду единожды:
|
||||
/usr/bin/php /path/to/opencart/system/cron/export.php
|
||||
|
||||
#### Кастомизация моделей
|
||||
|
||||
Для создания кастомных классов скопируйте файл модели в директорию custom, в новом файле измените название класса с "ModelExtensionRetailcrmFilename" на "ModelExtensionRetailcrmCustomFilename", где "Filename" - название файла с заглавной буквы. После этого модуль будет использовать методы кастомного класса.
|
177
RoboFile.php
177
RoboFile.php
|
@ -1,177 +0,0 @@
|
|||
<?php
|
||||
|
||||
require_once('vendor/autoload.php');
|
||||
if (file_exists(__DIR__.'/.env')) {
|
||||
Dotenv::load(__DIR__);
|
||||
}
|
||||
|
||||
class RoboFile extends \Robo\Tasks
|
||||
{
|
||||
use \Robo\Task\Development\loadTasks;
|
||||
use \Robo\Common\TaskIO;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $opencart_config;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $server_port = 80;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $server_url = 'http://localhost';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if ($_ENV) {
|
||||
foreach ($_ENV as $option => $value) {
|
||||
if (substr($option, 0, 3) === 'OC_') {
|
||||
$option = strtolower(substr($option, 3));
|
||||
$this->opencart_config[$option] = $value;
|
||||
} elseif ($option === 'SERVER_PORT') {
|
||||
$this->server_port = (int) $value;
|
||||
} elseif ($option === 'SERVER_URL') {
|
||||
$this->server_url = $value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$this->opencart_config = [
|
||||
'db_hostname' => getenv('OC_DB_HOSTNAME'),
|
||||
'db_username' => getenv('OC_DB_USERNAME'),
|
||||
'db_password' => getenv('OC_DB_PASSWORD'),
|
||||
'db_database' => getenv('OC_DB_DATABASE'),
|
||||
'db_driver' => getenv('OC_DB_DRIVER'),
|
||||
'username' => getenv('OC_USERNAME'),
|
||||
'password' => getenv('OC_PASSWORD'),
|
||||
'email' => getenv('OC_EMAIL')
|
||||
];
|
||||
}
|
||||
|
||||
$this->opencart_config['http_server'] = $this->server_url.':'.$this->server_port.'/';
|
||||
|
||||
$required = array('db_username', 'password', 'email');
|
||||
$missing = array();
|
||||
foreach ($required as $config) {
|
||||
if (empty($this->opencart_config[$config])) {
|
||||
$missing[] = 'OC_'.strtoupper($config);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($missing)) {
|
||||
$this->printTaskError("<error> Missing ".implode(', ', $missing));
|
||||
$this->printTaskError("<error> See .env.sample ");
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public function opencartSetup()
|
||||
{
|
||||
$this->taskDeleteDir('www')->run();
|
||||
$this->taskFileSystemStack()
|
||||
->mirror('vendor/opencart/opencart/upload', 'www')
|
||||
->copy('tests/test-config.php', 'www/system/config/test-config.php')
|
||||
->copy('vendor/beyondit/opencart-test-suite/src/upload/system/library/session/test.php', 'www/system/library/session/test.php')
|
||||
->copy('vendor/beyondit/opencart-test-suite/src/upload/admin/controller/startup/test_startup.php','www/admin/controller/startup/test_startup.php')
|
||||
->chmod('www', 0777, 0000, true)
|
||||
->rename('www/config-dist.php', 'www/config.php')
|
||||
->rename('www/admin/config-dist.php', 'www/admin/config.php')
|
||||
->run();
|
||||
|
||||
// Create new database, drop if exists already
|
||||
try {
|
||||
$conn = new PDO("mysql:host=".$this->opencart_config['db_hostname'], $this->opencart_config['db_username'], $this->opencart_config['db_password']);
|
||||
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$conn->exec("DROP DATABASE IF EXISTS `" . $this->opencart_config['db_database'] . "`");
|
||||
$conn->exec("CREATE DATABASE `" . $this->opencart_config['db_database'] . "`");
|
||||
}
|
||||
catch(PDOException $e)
|
||||
{
|
||||
$this->printTaskError("<error> Could not connect ot database...");
|
||||
}
|
||||
|
||||
$install = $this->taskExec('php')->arg('www/install/cli_install.php')->arg('install');
|
||||
foreach ($this->opencart_config as $option => $value) {
|
||||
$install->option($option, $value);
|
||||
}
|
||||
$install->run();
|
||||
$this->taskDeleteDir('www/install')->run();
|
||||
|
||||
if (isset($conn)) {
|
||||
$this->restoreSampleData($conn);
|
||||
}
|
||||
|
||||
$conn = null;
|
||||
}
|
||||
|
||||
public function opencartRun()
|
||||
{
|
||||
$this->taskServer($this->server_port)
|
||||
->dir('www')
|
||||
->run();
|
||||
}
|
||||
|
||||
public function projectDeploy()
|
||||
{
|
||||
$this->taskFileSystemStack()
|
||||
->mirror('src/upload', 'www')
|
||||
// ->copy('src/install.xml','www/system/install.ocmod.xml') if exist modification for OCMOD
|
||||
->run();
|
||||
}
|
||||
|
||||
public function projectWatch()
|
||||
{
|
||||
$this->projectDeploy();
|
||||
|
||||
$this->taskWatch()
|
||||
->monitor('composer.json', function () {
|
||||
$this->taskComposerUpdate()->run();
|
||||
$this->projectDeploy();
|
||||
})->monitor('src/', function () {
|
||||
$this->projectDeploy();
|
||||
})->run();
|
||||
}
|
||||
|
||||
public function projectPackage()
|
||||
{
|
||||
$this->taskDeleteDir('target')->run();
|
||||
$this->taskFileSystemStack()->mkdir('target')->run();
|
||||
|
||||
$zip = new ZipArchive();
|
||||
$filename = "target/build.ocmod.zip";
|
||||
|
||||
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
|
||||
$this->printTaskError("<error> Could not create ZipArchive");
|
||||
exit();
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator("src", \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile() && $file->isReadable()) {
|
||||
$zip->addFile($file->getPathname(),substr($file->getPathname(),4));
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
private function restoreSampleData($conn)
|
||||
{
|
||||
$sql = file_get_contents('tests/opencart_sample_data.sql');
|
||||
|
||||
$conn->exec("USE " . $this->opencart_config['db_database']);
|
||||
|
||||
foreach (explode(";\n", $sql) as $sql) {
|
||||
$sql = trim($sql);
|
||||
|
||||
if ($sql) {
|
||||
$conn->exec($sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
|||
3.1.0-alpha1
|
||||
4.1.19
|
||||
|
|
|
@ -6,18 +6,9 @@
|
|||
"authors": [
|
||||
{
|
||||
"name": "RetailDriverLLC",
|
||||
"email": "integration@retailcrm.ru"
|
||||
"email": "support@retailcrm.pro"
|
||||
}
|
||||
],
|
||||
"version": "3.1.0-alpha1",
|
||||
"require-dev": {
|
||||
"opencart/opencart" : "3.1.0.0_a1",
|
||||
"vlucas/phpdotenv": "~1.1.0",
|
||||
"phpunit/phpunit" : "^6",
|
||||
"beyondit/opencart-test-suite": "~3.0",
|
||||
"consolidation/robo": "~1",
|
||||
"henrikbjorn/lurker": "^1.2"
|
||||
},
|
||||
"config": {
|
||||
"bin-dir": "bin/",
|
||||
"preferred-install": "source"
|
||||
|
@ -26,14 +17,22 @@
|
|||
"opencart-dir" : "www"
|
||||
},
|
||||
"scripts" : {
|
||||
"test-library": "bin/phpunit --testsuite library-tests --colors=always",
|
||||
"test-admin": "bin/phpunit --testsuite admin-tests --colors=always",
|
||||
"test-catalog": "bin/phpunit --testsuite catalog-tests --colors=always",
|
||||
"test-admin": "bin/phpunit --coverage-php coverage/admin.cov --testsuite admin-tests --colors=always",
|
||||
"test-catalog": "bin/phpunit --coverage-php coverage/catalog.cov --testsuite catalog-tests --colors=always",
|
||||
"test-system": "bin/phpunit --coverage-php coverage/system.cov --testsuite system-tests --colors=always",
|
||||
"test": [
|
||||
"@test-library",
|
||||
"@test-admin",
|
||||
"@test-catalog"
|
||||
"@test-catalog",
|
||||
"@test-system"
|
||||
],
|
||||
"setup" : "bin/robo opencart:setup"
|
||||
"opencart:install" : "bin/robo --load-from tests/RoboFile.php opencart:install"
|
||||
},
|
||||
"require": {
|
||||
"ext-json": "*"
|
||||
},
|
||||
"require-dev": {
|
||||
"consolidation/robo": "~1.0",
|
||||
"phpcompatibility/php-compatibility": "^9.3",
|
||||
"beyondit/opencart-test-suite": "~3.0"
|
||||
}
|
||||
}
|
||||
|
|
3732
composer.lock
generated
3732
composer.lock
generated
File diff suppressed because it is too large
Load diff
6
doc/Update module.md
Normal file
6
doc/Update module.md
Normal file
|
@ -0,0 +1,6 @@
|
|||
### Обновление версии модуля
|
||||
|
||||
Для обновления версии модуля необходимо обновить следующие файлы:
|
||||
* VERSION
|
||||
* CHANGELOG.md
|
||||
* src/upload/admin/controller/extension/module/retailcrm.php
|
39
docker-compose.yml
Normal file
39
docker-compose.yml
Normal file
|
@ -0,0 +1,39 @@
|
|||
version: '3'
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./.docker/Dockerfile
|
||||
args:
|
||||
- TEST_SUITE=${TEST_SUITE}
|
||||
- OPENCART=${OPENCART}
|
||||
- SERVER_PORT=${SERVER_PORT}
|
||||
- OC_DB_HOSTNAME=${OC_DB_HOSTNAME}
|
||||
- OC_DB_USERNAME=${OC_DB_USERNAME}
|
||||
- OC_DB_PASSWORD=${OC_DB_PASSWORD}
|
||||
- OC_DB_DATABASE=${OC_DB_DATABASE}
|
||||
- OC_USERNAME=${OC_USERNAME}
|
||||
- OC_PASSWORD=${OC_PASSWORD}
|
||||
- OC_EMAIL=${OC_EMAIL}
|
||||
volumes:
|
||||
- ./:/opencart-module
|
||||
links:
|
||||
- "mysql"
|
||||
ports:
|
||||
- "${SERVER_PORT}:${SERVER_PORT}"
|
||||
depends_on:
|
||||
- mysql
|
||||
env_file:
|
||||
- .env
|
||||
working_dir: /opencart-module
|
||||
mysql:
|
||||
image: mysql:5.7
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- MYSQL_DATABASE=${OC_DB_DATABASE}
|
||||
- MYSQL_USER=${OC_DB_USERNAME}
|
||||
- MYSQL_PASSWORD=${OC_DB_PASSWORD}
|
||||
- MYSQL_ROOT_PASSWORD=root
|
||||
ports:
|
||||
- "3306:3306"
|
|
@ -6,7 +6,7 @@
|
|||
convertErrorsToExceptions="true"
|
||||
convertNoticesToExceptions="true"
|
||||
convertWarningsToExceptions="true"
|
||||
processIsolation="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
syntaxCheck="false">
|
||||
<testsuites>
|
||||
|
@ -16,13 +16,26 @@
|
|||
<testsuite name="admin-tests">
|
||||
<directory suffix="AdminTest.php">./tests/admin/</directory>
|
||||
</testsuite>
|
||||
<testsuite name="library-tests">
|
||||
<directory suffix="LibraryTest.php">./tests/library/</directory>
|
||||
<testsuite name="system-tests">
|
||||
<directory suffix="Test.php">./tests/system/</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<php>
|
||||
<env name="OC_ROOT" value="./www/" />
|
||||
<env name="HTTP_SERVER" value="http://localhost:8000/" />
|
||||
<env name="HTTP_SERVER" value="http://localhost:80/" />
|
||||
<env name="TEST_CONFIG" value="test-config" />
|
||||
</php>
|
||||
</phpunit>
|
||||
<filter>
|
||||
<whitelist addUncoveredFilesFromWhitelist="true">
|
||||
<directory suffix="retailcrm.php">./www/admin/controller</directory>
|
||||
<directory>./www/admin/model/extension/retailcrm</directory>
|
||||
<directory suffix="retailcrm.php">./www/catalog/controller</directory>
|
||||
<directory suffix="daemon_collector.php">./www/catalog/controller</directory>
|
||||
<directory>./www/catalog/model/extension/retailcrm</directory>
|
||||
<directory suffix=".php">./www/system/library/retailcrm</directory>
|
||||
<exclude>
|
||||
<directory suffix=".php">./www/system/library/retailcrm/lib/api</directory>
|
||||
</exclude>
|
||||
</whitelist>
|
||||
</filter>
|
||||
</phpunit>
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ControllerCronIcml extends Controller {
|
||||
public function index($cron_id, $code, $cycle, $date_added, $date_modified) {
|
||||
$this->load->controller('extension/module/retailcrm/icml');
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load diff
|
@ -1,8 +1,8 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'Retailcrm';
|
||||
$_['retailcrm_title'] = 'Retailcrm';
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Modules';
|
||||
|
@ -13,20 +13,20 @@ $_['retailcrm_dict_settings'] = 'Configuration of directories correspondence'
|
|||
$_['retailcrm_countries_settings'] = 'Setting of trade zones';
|
||||
$_['retailcrm_upload_order'] = 'Uploading one order';
|
||||
$_['daemon_collector'] = 'Daemon Collector';
|
||||
$_['consultant_tab_text'] = 'Online Consultant';
|
||||
$_['general_tab_text'] = 'Main';
|
||||
$_['references_tab_text'] = 'Directories';
|
||||
$_['collector_tab_text'] = 'Daemon Collector';
|
||||
$_['logs_tab_text'] = 'Logs';
|
||||
$_['collector_custom_text'] = 'Configuration of form fields';
|
||||
$_['custom_fields_tab_text'] = 'Custom fields';
|
||||
$_['retailcrm_apiversion'] = 'API Version';
|
||||
$_['retailcrm_url'] = 'URL of retailCRM';
|
||||
$_['retailcrm_apikey'] = 'API key of retailCRM';
|
||||
$_['retailcrm_url'] = 'URL of RetailCRM';
|
||||
$_['retailcrm_apikey'] = 'API key of RetailCRM';
|
||||
$_['corporate_enabled_label'] = 'Corporate customers support';
|
||||
$_['collector_site_key'] = 'Site key';
|
||||
$_['special_price_settings'] = 'Setting of uploading promotion price';
|
||||
$_['special_price'] = 'Price type to which the promotion price will be uploaded';
|
||||
|
||||
|
||||
$_['text_success_export'] = 'Orders and customers are uploaded successfully';
|
||||
$_['text_success_export_order'] = 'Order is uploaded successfully';
|
||||
$_['text_button_export'] = 'Upload all orders and customers';
|
||||
|
@ -50,17 +50,18 @@ $_['text_payment'] = 'Payment';
|
|||
$_['text_shipping'] = 'Delivery';
|
||||
$_['text_orders_custom_fields'] = 'Custom fields of orders';
|
||||
$_['text_customers_custom_fields'] = 'Custom fields of customers';
|
||||
$_['text_error_collector_fields']= 'Fill in the names of fields of Demon Collector form';
|
||||
$_['text_error_api'] = 'The selected API version is not available.';
|
||||
$_['text_error_custom_field'] = 'Create custom fields on a customer page in Opencart and retailCRM in order to set up their transfer';
|
||||
$_['text_error_collector_fields'] = 'Fill in the names of fields of Demon Collector form';
|
||||
$_['text_error_api_empty'] = 'The "RetailCRM URL" and "RetailCRM API key" fields cannot be empty, enter the correct value';
|
||||
$_['text_error_api_key'] = 'Invalid API key';
|
||||
$_['text_error_api_key_site'] = 'API key with one-shop access required';
|
||||
$_['text_error_api_key_currency'] = 'The currency of the site differs from the currency of the store in CRM. For the integration to work correctly, the currencies in CRM and CMS must match';
|
||||
$_['text_error_custom_field'] = 'Create custom fields on a customer page in Opencart and RetailCRM in order to set up their transfer';
|
||||
$_['text_error_cf_opencart'] = 'There are no custom fields in Opencart';
|
||||
$_['text_error_cf_retailcrm'] = 'There are no custom fields in retailCRM';
|
||||
$_['text_error_cf_retailcrm'] = 'There are no custom fields in RetailCRM';
|
||||
$_['text_error_save'] = 'Error when saving settings';
|
||||
$_['text_error_log'] = 'Log size is more than 2MB';
|
||||
$_['text_error_delivery'] = 'Delivery types are not found';
|
||||
$_['text_error_delivery'] = 'Delivery types are not found';
|
||||
$_['text_confirm_log'] = 'Are you sure that you want to clear the log?';
|
||||
$_['text_lenght'] = 'Setting of the unit of measurement';
|
||||
$_['text_lenght_label'] = 'Unit of measurement in ICML';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Delivery types';
|
||||
$_['retailcrm_dict_status'] = 'Statuses';
|
||||
|
@ -70,14 +71,28 @@ $_['retailcrm_dict_default'] = 'By default';
|
|||
$_['retailcrm_missing_status'] = 'Status of lost orders';
|
||||
|
||||
$_['order_number'] = 'Order number';
|
||||
$_['text_order_number'] = 'Upload the order number to retailCRM';
|
||||
|
||||
$_['debug'] = 'Debug mode';
|
||||
$_['text_debug'] = 'Enable debug mode';
|
||||
$_['text_order_number'] = 'Upload the order number to RetailCRM';
|
||||
$_['summ_around'] = 'Around total summ';
|
||||
$_['text_summ_around'] = 'Around the order total summ';
|
||||
$_['icml_settings'] = 'ICML settings';
|
||||
$_['icml_service_enabled_label'] = 'Upload services in ICML';
|
||||
$_['icml_service_description'] = 'When the option is enabled, all products for which delivery is disabled will be considered as services and uploaded to CRM as services';
|
||||
$_['text_currency_label'] = 'Currency of goods';
|
||||
$_['text_lenght'] = 'Setting of the unit of measurement';
|
||||
$_['text_lenght_label'] = 'Unit of measurement of goods';
|
||||
$_['status_changes'] = 'History of changes';
|
||||
$_['text_status_changes'] = 'Record changes to the order history of Opencart';
|
||||
|
||||
$_['column_total'] = 'Total';
|
||||
$_['product_summ'] = 'Sum';
|
||||
|
||||
$_['text_retailcrm_discount'] = 'RetailCRM discount';
|
||||
$_['text_retailcrm_label_discount'] = 'Label of RetailCRM discount in section total of order';
|
||||
$_['default_retailcrm_label_discount'] = 'Discount in RetailCRM';
|
||||
|
||||
$_['sum_payment'] = 'Sum payment';
|
||||
$_['text_sum_payment'] = 'Do not upload the sum payment to RetailCRM';
|
||||
|
||||
$_['article'] = 'Article';
|
||||
$_['color'] = 'Color';
|
||||
$_['weight'] = 'Weight';
|
||||
|
@ -85,5 +100,8 @@ $_['size'] = 'Size';
|
|||
|
||||
$_['text_yes'] = 'Yes';
|
||||
$_['text_no'] = 'No';
|
||||
|
||||
$_['entry_code'] = 'Online consultant code';
|
||||
$_['entry_status'] = 'Use code for online consultant';
|
||||
// Errors
|
||||
$_['error_permission'] = 'You do not have rights for changing the module settings';
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'retailcrm';
|
||||
$_['retailcrm_title'] = 'retailcrm';
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Módulos';
|
||||
|
@ -13,18 +13,19 @@ $_['retailcrm_dict_settings'] = 'Ajustes de coincidencia de directorios';
|
|||
$_['retailcrm_countries_settings'] = 'Configurar zonas comerciales';
|
||||
$_['retailcrm_upload_order'] = 'Exportación de un pedido';
|
||||
$_['daemon_collector'] = 'Daemon Collector';
|
||||
$_['consultant_tab_text'] = 'Online Consultant';
|
||||
$_['general_tab_text'] = 'Inicio';
|
||||
$_['references_tab_text'] = 'Directorios';
|
||||
$_['collector_tab_text'] = 'Daemon Collector';
|
||||
$_['logs_tab_text'] = 'Registro';
|
||||
$_['collector_custom_text'] = 'Configurar campos de formulario';
|
||||
$_['custom_fields_tab_text'] = 'Campos personalizados';
|
||||
$_['retailcrm_apiversion'] = 'Versión de la API';
|
||||
$_['retailcrm_url'] = 'Dirección del retailCRM';
|
||||
$_['retailcrm_apikey'] = 'Clave de la API del retailCRM';
|
||||
$_['retailcrm_url'] = 'Dirección del RetailCRM';
|
||||
$_['retailcrm_apikey'] = 'Clave de la API del RetailCRM';
|
||||
$_['corporate_enabled_label'] = 'Corporate customers support';
|
||||
$_['collector_site_key'] = 'Clave de la página web';
|
||||
$_['special_price_settings'] = 'Ajuste de la descarga del precio promocional';
|
||||
$_['special_price'] = 'Tipo de precio en el que se cargará el precio de promoción';
|
||||
$_['special_price'] = 'Tipo de precio en el que se cargará el precio de promoción';
|
||||
|
||||
$_['text_success_export'] = 'Los pedidos y los clientes han sido exportados con éxito';
|
||||
$_['text_success_export_order'] = 'El pedido ha sido exportado con éxito';
|
||||
|
@ -50,16 +51,17 @@ $_['text_shipping'] = 'Envío';
|
|||
$_['text_orders_custom_fields'] = 'Los campos de pedidos personalizados';
|
||||
$_['text_customers_custom_fields'] = 'Los campos de clientes personalizados';
|
||||
$_['text_error_collector_fields']= 'Rellene los nombres de los campos del formulario Daemon Collector';
|
||||
$_['text_error_api'] = 'La versión seleccionada de la API no está disponible.';
|
||||
$_['text_error_custom_field'] = 'Cree campos personalizados en la ficha del cliente en Opencart y retailCRM para configurar sus transmisión.';
|
||||
$_['text_error_api_empty'] = 'Los campos "URL de RetailCRM" y "Clave de API de RetailCRM" no pueden estar vacíos, ingrese el valor correcto';
|
||||
$_['text_error_api_key'] = 'Clave API del CRM no válida';
|
||||
$_['text_error_api_key_site'] = 'Se requiere clave API con acceso a una tienda';
|
||||
$_['text_error_api_key_currency'] = 'La moneda del sitio web es distinto a la tienda del CRM. Para el funcionamiento correcto de la integración, las monedas del CMS y CRM deben coincid';
|
||||
$_['text_error_custom_field'] = 'Cree campos personalizados en la ficha del cliente en Opencart y RetailCRM para configurar sus transmisión.';
|
||||
$_['text_error_cf_opencart'] = 'Faltan campos personalizados en Opencart';
|
||||
$_['text_error_cf_retailcrm'] = 'Faltan campos personalizados en retailCRM';
|
||||
$_['text_error_cf_retailcrm'] = 'Faltan campos personalizados en RetailCRM';
|
||||
$_['text_error_save'] = 'Error al guardar la configuración';
|
||||
$_['text_error_log'] = 'El Tamaño del registro es más de 2MB';
|
||||
$_['text_error_delivery'] = 'No se encontraron los métodos de envío';
|
||||
$_['text_error_delivery'] = 'No se encontraron los métodos de envío';
|
||||
$_['text_confirm_log'] = '¿Estás seguro de que quieres borrar el registro?';
|
||||
$_['text_lenght_label'] = 'Ajustar unidad de medida';
|
||||
$_['status_changes'] = 'Unidad de medida en ICML';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Métodos de envío';
|
||||
$_['retailcrm_dict_status'] = 'Estados';
|
||||
|
@ -69,11 +71,29 @@ $_['retailcrm_dict_default'] = 'Por defecto';
|
|||
$_['retailcrm_missing_status'] = 'Estado de pedidos perdidos';
|
||||
|
||||
$_['order_number'] = 'Número de pedido';
|
||||
$_['text_order_number'] = 'Transferir número de pedido a retailCRM';
|
||||
$_['text_order_number'] = 'Transferir número de pedido a RetailCRM';
|
||||
$_['summ_around'] = 'Redondeo del costo del pedido';
|
||||
$_['text_summ_around'] = 'Redondear los costos del pedido a RetailCRM';
|
||||
$_['icml_settings'] = 'Ajustes de ICML';
|
||||
$_['icml_service_enabled_label'] = 'Subir servicios de ICML';
|
||||
$_['icml_service_description'] = 'Si habilita la opción, todos los productos para los que la entrega está desactivada se tratarán como servicios y se cargarán en CRM como servicios';
|
||||
|
||||
$_['text_currency_label'] = 'Moneda de bienes';
|
||||
$_['text_lenght'] = 'Ajustar unidad de medida';
|
||||
$_['text_lenght_label'] = 'Unidad de medida de bienes';
|
||||
$_['status_changes'] = 'Historial de cambios';
|
||||
$_['text_status_changes'] = 'Registrar los cambios en el historial de pedidos de Opencart';
|
||||
|
||||
$_['column_total'] = 'Total';
|
||||
$_['product_summ'] = 'Importe';
|
||||
|
||||
$_['text_retailcrm_discount'] = 'RetailCRM descuento';
|
||||
$_['text_retailcrm_label_discount'] = 'Etiqueta de descuento de RetailCRM en la sección total del pedido';
|
||||
$_['default_retailcrm_label_discount'] = 'Descuento en RetailCRM';
|
||||
|
||||
$_['sum_payment'] = 'Suma de pago';
|
||||
$_['text_sum_payment'] = 'No transferir suma de pago a RetailCRM';
|
||||
|
||||
$_['article'] = 'Artículo';
|
||||
$_['color'] = 'Color';
|
||||
$_['weight'] = 'Peso';
|
||||
|
@ -81,5 +101,8 @@ $_['size'] = 'Tamaño';
|
|||
|
||||
$_['text_yes'] = 'Sí';
|
||||
$_['text_no'] = 'No';
|
||||
|
||||
$_['entry_code'] = 'Código para online consultant';
|
||||
$_['entry_status'] = 'Usar código para online consultant';
|
||||
// Errors
|
||||
$_['error_permission'] = 'No tiene suficientes permisos para cambiar la configuración del módulo';
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'Retailcrm';
|
||||
$_['retailcrm_title'] = 'Retailcrm';
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Модули';
|
||||
|
@ -16,12 +16,13 @@ $_['daemon_collector'] = 'Демон Collector';
|
|||
$_['general_tab_text'] = 'Главная';
|
||||
$_['references_tab_text'] = 'Справочники';
|
||||
$_['collector_tab_text'] = 'Daemon Collector';
|
||||
$_['consultant_tab_text'] = 'Online Consultant';
|
||||
$_['logs_tab_text'] = 'Логи';
|
||||
$_['collector_custom_text'] = 'Настройка полей формы';
|
||||
$_['custom_fields_tab_text'] = 'Пользовательские поля';
|
||||
$_['retailcrm_apiversion'] = 'Версия API';
|
||||
$_['retailcrm_url'] = 'Адрес RetailCRM';
|
||||
$_['retailcrm_apikey'] = 'Api ключ RetailCRM';
|
||||
$_['corporate_enabled_label'] = 'Поддержка корпоративных клиентов';
|
||||
$_['collector_site_key'] = 'Ключ сайта';
|
||||
$_['special_price_settings'] = 'Настройка выгрузки акционной цены';
|
||||
$_['special_price'] = 'Тип цены, в который будет выгружаться цена по акции';
|
||||
|
@ -49,8 +50,11 @@ $_['text_payment'] = 'Оплата';
|
|||
$_['text_shipping'] = 'Доставка';
|
||||
$_['text_orders_custom_fields'] = 'Кастомные поля заказов';
|
||||
$_['text_customers_custom_fields'] = 'Кастомные поля клиентов';
|
||||
$_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector';
|
||||
$_['text_error_api'] = 'Недоступна выбранная версия API.';
|
||||
$_['text_error_collector_fields'] = 'Заполните названия полей формы Демон Collector';
|
||||
$_['text_error_api_empty'] = 'Поля "URL RetailCRM" и "Ключ API RetailCRM" не могут быть пустыми, введите корректное значение';
|
||||
$_['text_error_api_key'] = 'Неверный API ключ';
|
||||
$_['text_error_api_key_site'] = 'Требуется API ключ с доступом к одному магазину';
|
||||
$_['text_error_api_key_currency'] = 'Валюта сайта отличается от валюты магазина в CRM. Для корректной работы интеграции, валюты в CRM и CMS должны совпадать';
|
||||
$_['text_error_custom_field'] = 'Создайте пользовательские поля в карточке клиента в Opencart и RetailCRM, чтобы настроить их передачу';
|
||||
$_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart';
|
||||
$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM';
|
||||
|
@ -58,8 +62,6 @@ $_['text_error_save'] = 'Ошибка сохранения настр
|
|||
$_['text_error_log'] = 'Размер лога более 2MB';
|
||||
$_['text_error_delivery'] = 'Не найдены типы доставки';
|
||||
$_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?';
|
||||
$_['text_lenght'] = 'Единица измерения в ICML';
|
||||
$_['text_lenght_label'] = 'История изменений';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Способы доставки';
|
||||
$_['retailcrm_dict_status'] = 'Статусы';
|
||||
|
@ -69,14 +71,28 @@ $_['retailcrm_dict_default'] = 'По умолчанию';
|
|||
$_['retailcrm_missing_status'] = 'Статус пропавших заказов';
|
||||
|
||||
$_['order_number'] = 'Номер заказа';
|
||||
$_['text_order_number'] = 'Передавать номер заказа в retailCRM';
|
||||
|
||||
$_['debug'] = 'Debug режим';
|
||||
$_['text_debug'] = 'Включить подробное логирование';
|
||||
$_['text_order_number'] = 'Передавать номер заказа в RetailCRM';
|
||||
$_['summ_around'] = 'Округление суммы заказа';
|
||||
$_['text_summ_around'] = 'Округлять сумму заказа';
|
||||
$_['icml_settings'] = 'Настройки ICML';
|
||||
$_['icml_service_enabled_label'] = 'Выгружать услуги в ICML';
|
||||
$_['icml_service_description'] = 'При включении опции все товары, для которых отключена доставка, будут рассматриваться как услуги и загружаться в CRM как услуги';
|
||||
$_['text_currency_label'] = 'Валюта товаров';
|
||||
$_['text_lenght'] = 'Настройка единицы измерения';
|
||||
$_['text_lenght_label'] = 'Единица измерения товаров';
|
||||
$_['status_changes'] = 'История изменений';
|
||||
$_['text_status_changes'] = 'Фиксировать изменения в истории заказа Opencart';
|
||||
|
||||
$_['column_total'] = 'Итого';
|
||||
$_['product_summ'] = 'Сумма';
|
||||
|
||||
$_['text_retailcrm_discount'] = 'Скидка RetailCRM';
|
||||
$_['text_retailcrm_label_discount'] = 'Подпись для скидки, установленной в RetailCRM, в итоговой секции заказа';
|
||||
$_['default_retailcrm_label_discount'] = 'Скидка в RetailCRM';
|
||||
|
||||
$_['sum_payment'] = 'Сумма платежа';
|
||||
$_['text_sum_payment'] = 'Не передавать сумму платежа в RetailCRM';
|
||||
|
||||
$_['article'] = 'Артикул';
|
||||
$_['color'] = 'Цвет';
|
||||
$_['weight'] = 'Вес';
|
||||
|
@ -86,3 +102,8 @@ $_['text_yes'] = 'Да';
|
|||
$_['text_no'] = 'Нет';
|
||||
// Errors
|
||||
$_['error_permission'] = 'У вас недостаточно прав на изменение настроек модуля';
|
||||
|
||||
//online consultant
|
||||
$_['entry_code'] = 'Код для online consultant';
|
||||
$_['entry_status'] = 'Использовать код для online consultant';
|
||||
|
||||
|
|
29
src/upload/admin/model/extension/retailcrm/customer.php
Normal file
29
src/upload/admin/model/extension/retailcrm/customer.php
Normal file
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmCustomer extends Model {
|
||||
/**
|
||||
* Upload customers
|
||||
*
|
||||
* @param array $customers
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function uploadToCrm($customers)
|
||||
{
|
||||
$customersToCrm = array();
|
||||
/** @var CustomerManager $customer_manager */
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
|
||||
foreach($customers as $customer) {
|
||||
$customersToCrm[] = $customer_manager->prepareCustomer($customer, array());
|
||||
}
|
||||
|
||||
$chunkedCustomers = array_chunk($customersToCrm, 50);
|
||||
|
||||
foreach($chunkedCustomers as $customersPart) {
|
||||
$customer_manager->uploadCustomers($customersPart);
|
||||
}
|
||||
|
||||
return $chunkedCustomers;
|
||||
}
|
||||
}
|
8
src/upload/admin/model/extension/retailcrm/event.php
Normal file
8
src/upload/admin/model/extension/retailcrm/event.php
Normal file
|
@ -0,0 +1,8 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmEvent extends Model{
|
||||
public function getEventByCode($code) {
|
||||
$query = $this->db->query("SELECT DISTINCT * FROM `" . DB_PREFIX . "event` WHERE `code` = '" . $this->db->escape($code) . "' LIMIT 1");
|
||||
return $query->row;
|
||||
}
|
||||
}
|
|
@ -1,19 +1,19 @@
|
|||
<?php
|
||||
|
||||
require_once 'order.php';
|
||||
|
||||
class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
||||
{
|
||||
class ModelExtensionRetailcrmHistory extends Model {
|
||||
protected $createResult;
|
||||
protected $settings;
|
||||
protected $moduleTitle;
|
||||
protected $opencartApiClient;
|
||||
|
||||
private $customFieldSetting;
|
||||
private $orders_history;
|
||||
private $customers_history;
|
||||
private $data_repository;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
public function __construct($registry) {
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->opencartApiClient = $this->retailcrm->getOcApiClient($registry);
|
||||
}
|
||||
|
||||
|
@ -23,8 +23,7 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function request($retailcrmApiClient)
|
||||
{
|
||||
public function request($retailcrmApiClient) {
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('setting/store');
|
||||
|
@ -38,78 +37,75 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
|
||||
$this->load->language('extension/module/retailcrm');
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
$this->data_repository = new \retailcrm\repository\DataRepository($this->registry);
|
||||
$this->orders_history = new retailcrm\history\Order(
|
||||
$this->data_repository,
|
||||
new \retailcrm\service\SettingsManager($this->registry),
|
||||
new \retailcrm\repository\ProductsRepository($this->registry),
|
||||
new \retailcrm\repository\OrderRepository($this->registry)
|
||||
);
|
||||
|
||||
$this->customers_history = new retailcrm\history\Customer(
|
||||
$this->data_repository,
|
||||
new \retailcrm\repository\CustomerRepository($this->registry),
|
||||
new \retailcrm\service\SettingsManager($this->registry)
|
||||
);
|
||||
|
||||
$this->orders_history->setOcDelivery(
|
||||
$this->model_extension_retailcrm_references->getOpercartDeliveryTypes()
|
||||
);
|
||||
|
||||
$this->orders_history->setOcPayment(
|
||||
$this->model_extension_retailcrm_references->getOpercartPaymentTypes()
|
||||
);
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
$history = $this->model_setting_setting->getSetting('retailcrm_history');
|
||||
$settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
|
||||
|
||||
$url = isset($settings[\Retailcrm\Retailcrm::MODULE . '_url']) ? $settings[\Retailcrm\Retailcrm::MODULE . '_url'] : null;
|
||||
$key = isset($settings[\Retailcrm\Retailcrm::MODULE . '_apikey']) ? $settings[\Retailcrm\Retailcrm::MODULE . '_apikey'] : null;
|
||||
$url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null;
|
||||
$key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null;
|
||||
|
||||
if (empty($url) || empty($key)) {
|
||||
$this->log->addNotice('You need to configure retailcrm module first.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null;
|
||||
$sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null;
|
||||
$sinceIdOrders = $history['retailcrm_history_orders'] ?? 0;
|
||||
$sinceIdCustomers = $history['retailcrm_history_customers'] ?? 0;
|
||||
$packsOrders = $retailcrmApiClient->ordersHistory(['sinceId' => $sinceIdOrders]);
|
||||
$packsCustomers = $retailcrmApiClient->customersHistory(['sinceId' => $sinceIdCustomers]);
|
||||
|
||||
$packsOrders = $retailcrmApiClient->ordersHistory(array(
|
||||
'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
|
||||
), 1, 100);
|
||||
$packsCustomers = $retailcrmApiClient->customersHistory(array(
|
||||
'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
|
||||
), 1, 100);
|
||||
|
||||
if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) {
|
||||
if (!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0
|
||||
&& !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$generatedAt = $packsOrders['generatedAt'];
|
||||
$orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history);
|
||||
$customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history);
|
||||
|
||||
$ordersHistory = $packsOrders->history;
|
||||
$customersHistory = $packsCustomers->history;
|
||||
|
||||
$lastChangeOrders = $ordersHistory ? end($ordersHistory) : null;
|
||||
$lastChangeCustomers = $customersHistory ? end($customersHistory) : null;
|
||||
|
||||
if ($lastChangeOrders !== null) {
|
||||
$sinceIdOrders = $lastChangeOrders['id'];
|
||||
}
|
||||
|
||||
if ($lastChangeCustomers !== null) {
|
||||
$sinceIdCustomers = $lastChangeCustomers['id'];
|
||||
if ($lastChangeOrders !== null && $lastChangeCustomers !== null) {
|
||||
$this->model_setting_setting->editSetting(
|
||||
'retailcrm_history',
|
||||
[
|
||||
'retailcrm_history_orders' => $lastChangeOrders['id'],
|
||||
'retailcrm_history_customers' => $lastChangeCustomers['id']
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$orders = RetailcrmHistoryHelper::assemblyOrder($ordersHistory);
|
||||
$customers = RetailcrmHistoryHelper::assemblyCustomer($customersHistory);
|
||||
$newOrders = [];
|
||||
$updatedOrders = [];
|
||||
$this->settings = $settings;
|
||||
$this->totalTitle = $this->totalTitles();
|
||||
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
|
||||
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
|
||||
$this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping');
|
||||
|
||||
$this->delivery = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_delivery']);
|
||||
$this->payment = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_payment']);
|
||||
$this->status = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_status']);
|
||||
$this->delivery_default = $settings[\Retailcrm\Retailcrm::MODULE . '_default_shipping'];
|
||||
$this->payment_default = $settings[\Retailcrm\Retailcrm::MODULE . '_default_payment'];
|
||||
$this->ocPayment = $this->model_extension_retailcrm_references
|
||||
->getOpercartPaymentTypes();
|
||||
|
||||
$this->ocDelivery = $this->model_extension_retailcrm_references
|
||||
->getOpercartDeliveryTypes($this->opencartApiClient);
|
||||
|
||||
$this->zones = $this->model_localisation_zone->getZones();
|
||||
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field'])) {
|
||||
$this->customFieldSetting = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']);
|
||||
}
|
||||
|
||||
$updatedOrders = array();
|
||||
$newOrders = array();
|
||||
$this->status = array_flip($settings[$this->moduleTitle . '_status']);
|
||||
|
||||
foreach ($orders as $order) {
|
||||
|
||||
if (isset($order['deleted'])) {
|
||||
continue;
|
||||
}
|
||||
|
@ -123,10 +119,9 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
|
||||
unset($orders);
|
||||
|
||||
$updateCustomers = array();
|
||||
$updateCustomers = [];
|
||||
|
||||
foreach ($customers as $customer) {
|
||||
|
||||
if (isset($customer['deleted'])) {
|
||||
continue;
|
||||
}
|
||||
|
@ -139,35 +134,27 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
unset($customers);
|
||||
|
||||
if (!empty($updateCustomers)) {
|
||||
$customers = $retailcrmApiClient->customersList($filter = array('ids' => $updateCustomers));
|
||||
$customers = $retailcrmApiClient->customersList(['ids' => $updateCustomers]);
|
||||
if ($customers) {
|
||||
$this->updateCustomers($customers['customers']);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($newOrders)) {
|
||||
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
|
||||
$orders = $retailcrmApiClient->ordersList(['ids' => $newOrders]);
|
||||
if ($orders) {
|
||||
$this->createResult = $this->createOrders($orders['orders']);
|
||||
$this->createResult = $this->createOrders($orders['orders'], $retailcrmApiClient);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($updatedOrders)) {
|
||||
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
|
||||
$orders = $retailcrmApiClient->ordersList(['ids' => $updatedOrders]);
|
||||
|
||||
if ($orders) {
|
||||
$this->updateOrders($orders['orders']);
|
||||
$this->updateOrders($orders['orders'], $retailcrmApiClient);
|
||||
}
|
||||
}
|
||||
|
||||
$this->model_setting_setting->editSetting(
|
||||
'retailcrm_history',
|
||||
array(
|
||||
'retailcrm_history_orders' => $sinceIdOrders,
|
||||
'retailcrm_history_customers' => $sinceIdCustomers,
|
||||
'retailcrm_history_datetime' => $generatedAt
|
||||
)
|
||||
);
|
||||
|
||||
if (!empty($this->createResult['customers'])) {
|
||||
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
|
||||
}
|
||||
|
@ -179,590 +166,62 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update orders from history
|
||||
*
|
||||
* @param array $orders
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function updateOrders($orders)
|
||||
{
|
||||
foreach ($orders as $order) {
|
||||
$ocOrder = $this->model_sale_order->getOrder($order['externalId']);
|
||||
|
||||
if (isset($order['payments']) && $order['payments']) {
|
||||
foreach ($order['payments'] as $orderPayment) {
|
||||
if (isset($orderPayment['externalId'])) {
|
||||
$payment = $orderPayment;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($payment) && count($order['payments']) == 1) {
|
||||
$payment = end($order['payments']);
|
||||
}
|
||||
} elseif (isset($order['paymentType'])) {
|
||||
$payment['type'] = $order['paymentType'];
|
||||
}
|
||||
|
||||
$data = array();
|
||||
|
||||
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
|
||||
$phone = isset($order['phone']) ? $order['phone'] : '';
|
||||
|
||||
if (!$phone) {
|
||||
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
|
||||
} else {
|
||||
$data['telephone'] = $phone;
|
||||
}
|
||||
|
||||
if (isset($order['customer']['externalId']) && $order['customer']['externalId']) {
|
||||
$customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']);
|
||||
}
|
||||
|
||||
$data['customer'] = $order['firstName'];
|
||||
$data['customer_id'] = (isset($customer)) ? $customer['customer_id'] : 0;
|
||||
$data['customer_group_id'] = (isset($customer)) ? $customer['customer_group_id'] : 1;
|
||||
$data['firstname'] = $order['firstName'];
|
||||
$data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
|
||||
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
|
||||
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
|
||||
$data['payment_address'] = '0';
|
||||
$data['payment_firstname'] = $order['firstName'];
|
||||
$data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
|
||||
$data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
|
||||
$data['payment_address_2'] = '';
|
||||
$data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'];
|
||||
$data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'];
|
||||
|
||||
$shippingZone = '';
|
||||
|
||||
if (is_int($order['delivery']['address']['region'])) {
|
||||
$shippingZone = $order['delivery']['address']['region'];
|
||||
} else {
|
||||
$shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
|
||||
|
||||
if ($shippingZone) {
|
||||
$shipping_zone_id = $shippingZone['zone_id'];
|
||||
} else {
|
||||
$shipping_zone_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($order['customer']['address']['region'])) {
|
||||
$paymentZone = $this->getZoneByName($order['customer']['address']['region']);
|
||||
|
||||
if ($paymentZone) {
|
||||
$payment_zone_id = $paymentZone['zone_id'];
|
||||
} else {
|
||||
$payment_zone_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($order['countryIso']) && !empty($order['countryIso'])) {
|
||||
$shippingCountry = $this->getCountryByIsoCode($order['countryIso']);
|
||||
}
|
||||
|
||||
if (isset($order['customer']['address']['countryIso']) && !empty($order['customer']['address']['countryIso'])) {
|
||||
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
|
||||
} else {
|
||||
$paymentCountry = $this->getCountryByIsoCode($order['countryIso']);
|
||||
}
|
||||
|
||||
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
|
||||
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : $ocOrder['payment_country_id'];
|
||||
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : $ocOrder['payment_country'];
|
||||
$data['payment_zone_id'] = $payment_zone_id ? $payment_zone_id : $ocOrder['payment_zone_id'];
|
||||
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : $ocOrder['payment_zone'];
|
||||
$data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id'];
|
||||
$data['shipping_country'] = isset($shippingCountry) ? $shippingCountry['name'] : $ocOrder['shipping_country'];
|
||||
$data['shipping_zone_id'] = $shipping_zone_id ? $shipping_zone_id : $ocOrder['shipping_zone_id'];
|
||||
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $ocOrder['shipping_zone'];
|
||||
$data['shipping_address'] = '0';
|
||||
$data['shipping_firstname'] = $order['firstName'];
|
||||
$data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
|
||||
$data['shipping_address_1'] = $order['delivery']['address']['text'];
|
||||
$data['shipping_address_2'] = '';
|
||||
$data['shipping_company'] = '';
|
||||
$data['shipping_company_id'] = '';
|
||||
$data['shipping_city'] = $order['delivery']['address']['city'];
|
||||
$data['shipping_postcode'] = $order['delivery']['address']['index'];
|
||||
|
||||
if ($delivery !== null) {
|
||||
if (isset($this->settings[\Retailcrm\Retailcrm::MODULE . '_delivery'][$ocOrder['shipping_code']])
|
||||
&& isset($this->delivery[$delivery])
|
||||
) {
|
||||
$data['shipping'] = $this->delivery[$delivery];
|
||||
|
||||
$shipping = explode('.', $data['shipping']);
|
||||
$shippingModule = $shipping[0];
|
||||
|
||||
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
|
||||
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
|
||||
} else {
|
||||
$data['shipping_method'] = $this->ocDelivery[$shippingModule]['title'];
|
||||
}
|
||||
|
||||
$data['shipping_code'] = $data['shipping'];
|
||||
} elseif (!isset($this->settings[\Retailcrm\Retailcrm::MODULE . '_delivery'][$ocOrder['shipping_code']])
|
||||
) {
|
||||
$data['shipping_method'] = $ocOrder['shipping_method'];
|
||||
$data['shipping_code'] = $ocOrder['shipping_code'];
|
||||
}
|
||||
} else {
|
||||
if (!isset($this->settings[$ocOrder['shipping_code']])
|
||||
|| !isset($this->delivery[$delivery])
|
||||
) {
|
||||
$data['shipping_method'] = $ocOrder['shipping_method'];
|
||||
$data['shipping_code'] = $ocOrder['shipping_code'];
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($payment)) {
|
||||
$data['payment'] = $this->payment[$payment['type']];
|
||||
$data['payment_method'] = isset($this->ocPayment[$data['payment']]) ? $this->ocPayment[$data['payment']] : $ocOrder['payment_method'];
|
||||
$data['payment_code'] = isset($this->payment[$payment['type']]) ? $this->payment[$payment['type']] : $ocOrder['payment_code'];
|
||||
} else {
|
||||
$data['payment_method'] = $ocOrder['payment_method'];
|
||||
$data['payment_code'] = $ocOrder['payment_code'];
|
||||
}
|
||||
|
||||
// this data will not retrive from crm for now
|
||||
$data['tax'] = '';
|
||||
$data['tax_id'] = '';
|
||||
$data['product'] = '';
|
||||
$data['product_id'] = '';
|
||||
$data['reward'] = '';
|
||||
$data['affiliate'] = '';
|
||||
$data['affiliate_id'] = '';
|
||||
$data['payment_tax_id'] = '';
|
||||
$data['order_product_id'] = '';
|
||||
$data['payment_company'] = '';
|
||||
$data['payment_company_id'] = '';
|
||||
$data['company'] = '';
|
||||
$data['company_id'] = '';
|
||||
|
||||
$data['order_product'] = array();
|
||||
|
||||
$discount = false;
|
||||
|
||||
foreach ($order['items'] as $item) {
|
||||
$productId = $item['offer']['externalId'];
|
||||
$options = array();
|
||||
|
||||
if (isset($item['discountTotal']) && $item['discountTotal'] > 0) {
|
||||
$discount = true;
|
||||
}
|
||||
|
||||
if (mb_strpos($item['offer']['externalId'], '#') > 1) {
|
||||
$offer = explode('#', $item['offer']['externalId']);
|
||||
$productId = $offer[0];
|
||||
$optionsFromCRM = explode('_', $offer[1]);
|
||||
|
||||
foreach ($optionsFromCRM as $optionFromCRM) {
|
||||
$optionData = explode('-', $optionFromCRM);
|
||||
$productOptionId = $optionData[0];
|
||||
$optionValueId = $optionData[1];
|
||||
|
||||
$productOptions = $this->model_catalog_product->getProductOptions($productId);
|
||||
|
||||
foreach($productOptions as $productOption) {
|
||||
if($productOptionId == $productOption['product_option_id']) {
|
||||
foreach($productOption['product_option_value'] as $productOptionValue) {
|
||||
if($productOptionValue['option_value_id'] == $optionValueId) {
|
||||
$options[] = array(
|
||||
'product_option_id' => $productOptionId,
|
||||
'product_option_value_id' => $productOptionValue['product_option_value_id'],
|
||||
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
|
||||
'type' => $productOption['type'],
|
||||
'name' => $productOption['name'],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$product = $this->model_catalog_product->getProduct($productId);
|
||||
$rewards = $this->model_catalog_product->getProductRewards($productId);
|
||||
|
||||
$data['order_product'][] = array(
|
||||
'name' => $product['name'],
|
||||
'model' => $product['model'],
|
||||
'price' => $item['initialPrice'],
|
||||
'total' => (float)($item['initialPrice'] * $item['quantity']),
|
||||
'product_id' => $productId,
|
||||
'quantity' => $item['quantity'],
|
||||
'option' => $options,
|
||||
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($this->customFieldSetting) && $order['customFields']) {
|
||||
foreach ($order['customFields'] as $code => $value) {
|
||||
if (array_key_exists($code, $this->customFieldSetting)) {
|
||||
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
|
||||
$customFields[$fieldCode] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$data['custom_field'] = isset($customFields) ? $customFields : '';
|
||||
} else {
|
||||
$data['custom_field'] = $ocOrder['custom_field'];
|
||||
}
|
||||
|
||||
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
|
||||
|
||||
$data['total'] = $order['totalSumm'];
|
||||
$data['order_total'] = array(
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'sub_total',
|
||||
'title' => $this->language->get('product_summ'),
|
||||
'value' => $order['summ'],
|
||||
'text' => $order['summ'],
|
||||
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'shipping',
|
||||
'title' => $data['shipping_method'],
|
||||
'value' => $deliveryCost,
|
||||
'text' => $deliveryCost,
|
||||
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'total',
|
||||
'title' => $this->language->get('column_total'),
|
||||
'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
|
||||
'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
|
||||
'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order']
|
||||
)
|
||||
);
|
||||
|
||||
if ((isset($order['discount'])
|
||||
&& $order['discount'] > 0)
|
||||
|| $discount
|
||||
) {
|
||||
$orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']);
|
||||
foreach ($orderTotals as $orderTotal) {
|
||||
if ($orderTotal['code'] == 'coupon'
|
||||
|| $orderTotal['code'] == 'reward'
|
||||
) {
|
||||
$data['order_total'][] = $orderTotal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$data['fromApi'] = true;
|
||||
|
||||
if (array_key_exists($order['status'], $this->status)) {
|
||||
$data['order_status_id'] = $this->status[$order['status']];
|
||||
} else {
|
||||
$tmpOrder = $this->model_sale_order->getOrder($order['externalId']);
|
||||
$data['order_status_id'] = $tmpOrder['order_status_id'];
|
||||
}
|
||||
|
||||
$this->editOrder($order['externalId'], $data);
|
||||
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create orders from history
|
||||
*
|
||||
* @param array $orders
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function createOrders($orders)
|
||||
{
|
||||
protected function createOrders($orders, $retailcrmApiClient) {
|
||||
$customersIdsFix = array();
|
||||
$ordersIdsFix = array();
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$store = $this->config->get('config_store_id');
|
||||
$data = array();
|
||||
$corporateAddress = array();
|
||||
|
||||
if (isset($order['payments']) && $order['payments']) {
|
||||
$payment = end($order['payments']);
|
||||
} elseif (isset($order['paymentType'])) {
|
||||
$payment['type'] = $order['paymentType'];
|
||||
if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') {
|
||||
$customer = $order['contact'];
|
||||
if (empty($customer['address'])) {
|
||||
$corporateAddress = $this->getCorporateCustomerAddress($retailcrmApiClient, $order);
|
||||
|
||||
if (!empty($corporateAddress)) {
|
||||
$customer['address'] = $corporateAddress;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$customer = $order['customer'];
|
||||
}
|
||||
|
||||
$customer_id = (!empty($order['customer']['externalId']))
|
||||
? $order['customer']['externalId']
|
||||
$customer_id = (!empty($customer['externalId']))
|
||||
? $customer['externalId']
|
||||
: 0;
|
||||
|
||||
$data = array();
|
||||
if ($customer_id === 0) {
|
||||
$customer_data = array();
|
||||
|
||||
if ($customer_id == 0) {
|
||||
if (isset($order['customer']['address']['countryIso'])) {
|
||||
$customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
|
||||
} else {
|
||||
$customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
|
||||
}
|
||||
$this->customers_history->handleCustomer($customer_data, $customer);
|
||||
$address = $this->customers_history->handleAddress($customer, $order);
|
||||
$this->customers_history->handleCustomFields($customer_data, $customer);
|
||||
$customer_data['address'] = array($address);
|
||||
$customer_id = $this->model_customer_customer->addCustomer($customer_data);
|
||||
|
||||
if (isset($order['customer']['address']['region'])) {
|
||||
$customerZone = $this->getZoneByName($order['customer']['address']['region']);
|
||||
} else {
|
||||
$customerZone = $this->getZoneByName($order['delivery']['address']['region']);
|
||||
}
|
||||
|
||||
$cData = array(
|
||||
'store_id' => 0,
|
||||
'customer_group_id' => '1',
|
||||
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
|
||||
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
|
||||
'email' => $order['customer']['email'],
|
||||
'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
|
||||
'fax' => '',
|
||||
'newsletter' => 0,
|
||||
'password' => 'tmppass',
|
||||
'status' => 1,
|
||||
'approved' => 1,
|
||||
'safe' => 0,
|
||||
'affiliate' => '',
|
||||
'address' => array(
|
||||
array(
|
||||
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
|
||||
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
|
||||
'address_1' => $order['customer']['address']['text'],
|
||||
'address_2' => ' ',
|
||||
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'],
|
||||
'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'],
|
||||
'tax_id' => '1',
|
||||
'company' => '',
|
||||
'company_id' => '',
|
||||
'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
|
||||
'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
|
||||
'default' => '1'
|
||||
)
|
||||
),
|
||||
);
|
||||
|
||||
$customer_id = $this->model_customer_customer->addCustomer($cData);
|
||||
|
||||
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id);
|
||||
$customersIdsFix[] = array('id' => $customer['id'], 'externalId' => (int)$customer_id);
|
||||
}
|
||||
|
||||
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
|
||||
$phone = isset($order['phone']) ? $order['phone'] : '';
|
||||
|
||||
if (!$phone) {
|
||||
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
|
||||
} else {
|
||||
$data['telephone'] = $phone;
|
||||
}
|
||||
|
||||
$data['currency_code'] = $this->config->get('config_currency');
|
||||
$data['currency_value'] = $this->getCurrencyByCode($data['currency_code'], 'value');
|
||||
$data['currency_id'] = $this->getCurrencyByCode($data['currency_code'], 'currency_id');
|
||||
$data['language_id'] = $this->getLanguageByCode($this->config->get('config_language'), 'language_id');
|
||||
$data['store_id'] = $store == null ? 0 : $store;
|
||||
$data['store_name'] = $this->config->get('config_name');
|
||||
$data['customer'] = $order['firstName'];
|
||||
$this->orders_history->handleBaseOrderData($data, $order);
|
||||
$this->orders_history->handleShipping($data, $order);
|
||||
$this->orders_history->handlePayment($data, $order, $corporateAddress);
|
||||
$this->orders_history->handleProducts($data, $order);
|
||||
$this->orders_history->handleTotals($data, $order);
|
||||
$this->orders_history->handleCustomFields($data, $order);
|
||||
$data['customer_id'] = $customer_id;
|
||||
$data['customer_group_id'] = 1;
|
||||
$data['firstname'] = $order['firstName'];
|
||||
$data['lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
|
||||
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
|
||||
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
|
||||
$data['fax'] = '';
|
||||
$data['payment_address'] = '0';
|
||||
$data['payment_firstname'] = $order['firstName'];
|
||||
$data['payment_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
|
||||
$data['payment_address_1'] = $order['customer']['address']['text'];
|
||||
$data['payment_address_2'] = '';
|
||||
$data['payment_company'] = '';
|
||||
$data['payment_company_id'] = '';
|
||||
$data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'];
|
||||
$data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'];
|
||||
|
||||
$shippingZone = '';
|
||||
|
||||
if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) {
|
||||
$shippingZone = $order['delivery']['address']['region'];
|
||||
} else {
|
||||
$shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
|
||||
|
||||
if ($shippingZone) {
|
||||
$shipping_zone_id = $shippingZone['zone_id'];
|
||||
} else {
|
||||
$shipping_zone_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($order['customer']['address']['region'])) {
|
||||
$paymentZone = $this->getZoneByName($order['customer']['address']['region']);
|
||||
|
||||
if ($paymentZone) {
|
||||
$payment_zone_id = $paymentZone['zone_id'];
|
||||
} else {
|
||||
$payment_zone_id = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($order['countryIso'])) {
|
||||
$shippingCountry = $this->getCountryByIsoCode($order['countryIso']);
|
||||
}
|
||||
|
||||
if (isset($order['customer']['address']['countryIso'])) {
|
||||
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
|
||||
}
|
||||
|
||||
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
|
||||
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0;
|
||||
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : '';
|
||||
$data['payment_zone_id'] = $payment_zone_id;
|
||||
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : '';
|
||||
$data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0;
|
||||
$data['shipping_country'] = isset($shippingCountry) ? $shippingCountry['name'] : '';
|
||||
$data['shipping_zone_id'] = $shipping_zone_id;
|
||||
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $data['payment_zone'];
|
||||
$data['shipping_address'] = '0';
|
||||
$data['shipping_firstname'] = $order['firstName'];
|
||||
$data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
|
||||
$data['shipping_address_1'] = $order['delivery']['address']['text'];
|
||||
$data['shipping_address_2'] = '';
|
||||
$data['shipping_company'] = '';
|
||||
$data['shipping_company_id'] = '';
|
||||
$data['shipping_city'] = $order['delivery']['address']['city'];
|
||||
$data['shipping_postcode'] = $order['delivery']['address']['index'];
|
||||
$data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
|
||||
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
|
||||
|
||||
$shipping = explode('.', $data['shipping']);
|
||||
$shippingModule = $shipping[0];
|
||||
|
||||
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
|
||||
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
|
||||
} else {
|
||||
$data['shipping_method'] = $this->ocDelivery[$shippingModule]['title'];
|
||||
}
|
||||
|
||||
if (isset($payment)) {
|
||||
$data['payment'] = $this->payment[$payment['type']];
|
||||
$data['payment_method'] = $this->ocPayment[$data['payment']];
|
||||
$data['payment_code'] = $this->payment[$payment['type']];
|
||||
} else {
|
||||
$data['payment'] = $this->payment_default;
|
||||
$data['payment_method'] = $this->ocPayment[$data['payment']];
|
||||
$data['payment_code'] = $this->payment_default;
|
||||
}
|
||||
|
||||
// this data will not retrive from crm for now
|
||||
$data['tax'] = '';
|
||||
$data['tax_id'] = '';
|
||||
$data['product'] = '';
|
||||
$data['product_id'] = '';
|
||||
$data['reward'] = '';
|
||||
$data['affiliate'] = '';
|
||||
$data['affiliate_id'] = 0;
|
||||
$data['payment_tax_id'] = '';
|
||||
$data['order_product_id'] = '';
|
||||
$data['payment_company'] = '';
|
||||
$data['payment_company_id'] = '';
|
||||
$data['company'] = '';
|
||||
$data['company_id'] = '';
|
||||
|
||||
$data['order_product'] = array();
|
||||
|
||||
foreach ($order['items'] as $item) {
|
||||
$productId = $item['offer']['externalId'];
|
||||
$options = array();
|
||||
|
||||
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
|
||||
$offer = explode('#', $item['offer']['externalId']);
|
||||
$productId = $offer[0];
|
||||
$optionsFromCRM = explode('_', $offer[1]);
|
||||
|
||||
foreach ($optionsFromCRM as $optionFromCRM) {
|
||||
$optionData = explode('-', $optionFromCRM);
|
||||
$productOptionId = $optionData[0];
|
||||
$optionValueId = $optionData[1];
|
||||
|
||||
$productOptions = $this->model_catalog_product->getProductOptions($productId);
|
||||
|
||||
foreach($productOptions as $productOption) {
|
||||
if($productOptionId == $productOption['product_option_id']) {
|
||||
foreach($productOption['product_option_value'] as $productOptionValue) {
|
||||
if($productOptionValue['option_value_id'] == $optionValueId) {
|
||||
$options[] = array(
|
||||
'product_option_id' => $productOptionId,
|
||||
'product_option_value_id' => $productOptionValue['product_option_value_id'],
|
||||
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
|
||||
'type' => $productOption['type'],
|
||||
'name' => $productOption['name'],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$product = $this->model_catalog_product->getProduct($productId);
|
||||
$rewards = $this->model_catalog_product->getProductRewards($productId);
|
||||
|
||||
$data['order_product'][] = array(
|
||||
'name' => $product['name'],
|
||||
'model' => $product['model'],
|
||||
'price' => $item['initialPrice'],
|
||||
'total' => (float)($item['initialPrice'] * $item['quantity']),
|
||||
'product_id' => $productId,
|
||||
'quantity' => $item['quantity'],
|
||||
'option' => $options,
|
||||
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($this->customFieldSetting) && $order['customFields']) {
|
||||
foreach ($order['customFields'] as $code => $value) {
|
||||
if (array_key_exists($code, $this->customFieldSetting)) {
|
||||
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
|
||||
$customFields[$fieldCode] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$data['custom_field'] = isset($customFields) ? $customFields : '';
|
||||
}
|
||||
|
||||
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
|
||||
|
||||
$data['total'] = $order['totalSumm'];
|
||||
$data['order_total'] = array(
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'sub_total',
|
||||
'title' => $this->language->get('product_summ'),
|
||||
'value' => $order['summ'],
|
||||
'text' => $order['summ'],
|
||||
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'shipping',
|
||||
'title' => $data['shipping_method'],
|
||||
'value' => $deliveryCost,
|
||||
'text' => $deliveryCost,
|
||||
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'total',
|
||||
'title' => $this->language->get('column_total'),
|
||||
'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
|
||||
'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
|
||||
'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order']
|
||||
)
|
||||
);
|
||||
|
||||
$data['fromApi'] = true;
|
||||
$data['order_status_id'] = 1;
|
||||
|
||||
$order_id = $this->addOrder($data);
|
||||
$order_id = $this->data_repository->addOrder($data);
|
||||
|
||||
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
|
||||
}
|
||||
|
@ -770,56 +229,113 @@ class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
|
|||
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
|
||||
}
|
||||
|
||||
protected function updateCustomers($customers)
|
||||
{
|
||||
foreach ($customers as $customer) {
|
||||
$customer_id = $customer['externalId'];
|
||||
$customerData = $this->model_customer_customer->getCustomer($customer_id);
|
||||
$customerData['password'] = false;
|
||||
/**
|
||||
* Update orders from history
|
||||
*
|
||||
* @param array $orders
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function updateOrders($orders, $retailcrmApiClient) {
|
||||
foreach ($orders as $order) {
|
||||
$corporateAddress = array();
|
||||
$data = $this->model_sale_order->getOrder($order['externalId']);
|
||||
|
||||
$customerData['firstname'] = $customer['firstName'];
|
||||
$customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
|
||||
$customerData['email'] = $customer['email'];
|
||||
$customerData['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : '';
|
||||
if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') {
|
||||
$customer = $order['contact'];
|
||||
if (empty($customer['address'])) {
|
||||
$corporateAddress = $this->getCorporateCustomerAddress($retailcrmApiClient, $order);
|
||||
|
||||
$customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']);
|
||||
|
||||
if (isset($customer['address']['countryIso'])) {
|
||||
$customerCountry = $this->getCountryByIsoCode($customer['address']['countryIso']);
|
||||
}
|
||||
|
||||
if (isset($customer['address']['region'])) {
|
||||
$customerZone = $this->getZoneByName($customer['address']['region']);
|
||||
}
|
||||
|
||||
$customerAddress['firstname'] = isset($customer['patronymic']) ? $customer['firstName'] . ' ' . $customer['patronymic'] : $customer['firstName'];
|
||||
$customerAddress['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
|
||||
$customerAddress['address_1'] = $customer['address']['text'];
|
||||
$customerAddress['city'] = $customer['address']['city'];
|
||||
$customerAddress['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : '';
|
||||
|
||||
if (isset($customerCountry)) {
|
||||
$customerAddress['country_id'] = $customerCountry['country_id'];
|
||||
}
|
||||
|
||||
if (isset($customerZone) && isset($customerZone['zone_id'])) {
|
||||
$customerAddress['zone_id'] = $customerZone['zone_id'];
|
||||
}
|
||||
|
||||
$customerData['address'] = array($customerAddress);
|
||||
|
||||
if (isset($this->customFieldSetting) && $customer['customFields']) {
|
||||
foreach ($customer['customFields'] as $code => $value) {
|
||||
if (array_key_exists($code, $this->customFieldSetting)) {
|
||||
$fieldCode = str_replace('c_', '', $this->customFieldSetting[$code]);
|
||||
$customFields[$fieldCode] = $value;
|
||||
if (!empty($corporateAddress)) {
|
||||
$customer['address'] = $corporateAddress;
|
||||
}
|
||||
}
|
||||
|
||||
$customerData['custom_field'] = isset($customFields) ? $customFields : '';
|
||||
} else {
|
||||
$customer = $order['customer'];
|
||||
}
|
||||
|
||||
$this->model_customer_customer->editCustomer($customer_id, $customerData);
|
||||
$customer_id = (!empty($customer['externalId']))
|
||||
? $customer['externalId']
|
||||
: 0;
|
||||
|
||||
if ($customer_id === 0) {
|
||||
$customer_data = array();
|
||||
|
||||
$this->customers_history->handleCustomer($customer_data, $customer);
|
||||
$address = $this->customers_history->handleAddress($customer, $order);
|
||||
$this->customers_history->handleCustomFields($customer_data, $customer);
|
||||
$customer_data['address'] = array($address);
|
||||
$customer_id = $this->model_customer_customer->addCustomer($customer_data);
|
||||
|
||||
$this->createResult['customers'][] = array('id' => $customer['id'], 'externalId' => (int)$customer_id);
|
||||
}
|
||||
|
||||
$this->orders_history->handleBaseOrderData($data, $order);
|
||||
$this->orders_history->handleShipping($data, $order);
|
||||
$this->orders_history->handlePayment($data, $order, $corporateAddress);
|
||||
$this->orders_history->handleProducts($data, $order);
|
||||
$this->orders_history->handleTotals($data, $order);
|
||||
$this->orders_history->handleCustomFields($data, $order);
|
||||
|
||||
$data['customer_id'] = $customer_id;
|
||||
if (array_key_exists($order['status'], $this->status)) {
|
||||
$data['order_status_id'] = $this->status[$order['status']];
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_status_changes'])
|
||||
&& $this->settings[$this->moduleTitle . '_status_changes']
|
||||
) {
|
||||
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
|
||||
}
|
||||
|
||||
$this->data_repository->editOrder($order['externalId'], $data);
|
||||
}
|
||||
}
|
||||
|
||||
protected function updateCustomers($customers) {
|
||||
foreach ($customers as $customer) {
|
||||
$customer_id = $customer['externalId'];
|
||||
$customer_data = $this->model_customer_customer->getCustomer($customer_id);
|
||||
|
||||
$this->customers_history->handleCustomer($customer_data, $customer);
|
||||
$this->customers_history->handleCustomFields($customer_data, $customer);
|
||||
|
||||
if (empty($customer_data['address_id'])) {
|
||||
$address = $this->customers_history->handleAddress($customer, array());
|
||||
$addresses = $this->model_customer_customer->getAddresses($customer_id);
|
||||
$addresses[] = $address;
|
||||
$customer_data['address'] = $addresses;
|
||||
} else {
|
||||
$updateAddress = $this->customers_history->handleAddress($customer, array(), $customer_data['address_id']);
|
||||
$addresses = $this->model_customer_customer->getAddresses($customer_id);
|
||||
$addresses[$customer_data['address_id']] = $updateAddress;
|
||||
$customer_data['address'] = $addresses;
|
||||
}
|
||||
|
||||
$this->model_customer_customer->editCustomer($customer_id, $customer_data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
* @param array $order
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getCorporateCustomerAddress($retailcrmApiClient, $order) {
|
||||
$addresses = $retailcrmApiClient->customersCorporateAddresses(
|
||||
$order['customer']['id'],
|
||||
array('ids' => array($order['customer']['mainAddress'])),
|
||||
null,
|
||||
null,
|
||||
'id'
|
||||
);
|
||||
|
||||
if ($addresses->isSuccessful() && !empty($addresses['addresses'])) {
|
||||
return $addresses['addresses'][0];
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,6 +22,7 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
{
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('localisation/weight_class');
|
||||
}
|
||||
|
||||
public function generateICML()
|
||||
|
@ -77,15 +78,20 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
*/
|
||||
private function addCategories()
|
||||
{
|
||||
$categories = $this->model_catalog_category->getCategories(array());
|
||||
foreach($categories as $category) {
|
||||
$categories = $this->model_catalog_category->getCategories([]);
|
||||
foreach ($categories as $category) {
|
||||
$category = $this->model_catalog_category->getCategory($category['category_id']);
|
||||
|
||||
$e = $this->eCategories->appendChild(
|
||||
$this->dd->createElement(
|
||||
'category', $category['name']
|
||||
)
|
||||
);
|
||||
$c = $this->dd->createElement('category');
|
||||
|
||||
if ($category['image']) {
|
||||
$c->appendChild(
|
||||
$this->dd->createElement('picture', $this->generateImage($category['image']))
|
||||
);
|
||||
}
|
||||
|
||||
$c->appendChild($this->dd->createElement('name', $category['name']));
|
||||
$e = $this->eCategories->appendChild($c);
|
||||
|
||||
$e->setAttribute('id', $category['category_id']);
|
||||
|
||||
|
@ -96,15 +102,19 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
|
||||
}
|
||||
|
||||
private function addOffers()
|
||||
{
|
||||
$offerManufacturers = array();
|
||||
|
||||
$manufacturers = $this->model_catalog_manufacturer
|
||||
->getManufacturers(array());
|
||||
private function addOffers() {
|
||||
$offerManufacturers = [];
|
||||
$servicesForIcml = $this->retailcrm->useServicesForIcml();
|
||||
$currencyForIcml = $this->retailcrm->getCurrencyForIcml();
|
||||
$defaultCurrency = $this->getDefaultCurrency();
|
||||
$settingLenght = $this->retailcrm->getLenghtForIcml();
|
||||
$leghtsArray = $this->model_localisation_length_class
|
||||
->getLengthClasses();
|
||||
$leghtsArray = $this->model_localisation_length_class->getLengthClasses();
|
||||
$weightClassesMas = $this->model_localisation_weight_class->getWeightClasses();
|
||||
$weightClasses = [];
|
||||
|
||||
foreach ($weightClassesMas as $weightClass) {
|
||||
$weightClasses[$weightClass['weight_class_id']]['value'] = $weightClass['value'];
|
||||
}
|
||||
|
||||
foreach ($leghtsArray as $lenght) {
|
||||
if ($lenght['value'] == 1) {
|
||||
|
@ -112,20 +122,21 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
}
|
||||
}
|
||||
|
||||
$manufacturers = $this->model_catalog_manufacturer
|
||||
->getManufacturers([]);
|
||||
|
||||
foreach ($manufacturers as $manufacturer) {
|
||||
$offerManufacturers[
|
||||
$manufacturer['manufacturer_id']
|
||||
] = $manufacturer['name'];
|
||||
$offerManufacturers[$manufacturer['manufacturer_id']] = $manufacturer['name'];
|
||||
}
|
||||
|
||||
$products = $this->model_catalog_product->getProducts(array());
|
||||
$products = $this->model_catalog_product->getProducts([]);
|
||||
|
||||
foreach ($products as $product) {
|
||||
$offers = $this->retailcrm->getOffers($product);
|
||||
|
||||
foreach ($offers as $optionsString => $optionsValues) {
|
||||
$optionsString = explode('_', $optionsString);
|
||||
$options = array();
|
||||
$options = [];
|
||||
|
||||
foreach($optionsString as $optionString) {
|
||||
$option = explode('-', $optionString);
|
||||
|
@ -133,39 +144,50 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
|
||||
if ($optionString != '0:0-0') {
|
||||
$optionData = $this->getOptionData($optionIds[1], $option[1]);
|
||||
$options[$optionIds[0]] = array(
|
||||
'name' => $optionData['optionName'],
|
||||
'value' => $optionData['optionValue'],
|
||||
'value_id' => $option[1]
|
||||
);
|
||||
if (!empty($optionData)) {
|
||||
$options[$optionIds[0]] = array(
|
||||
'name' => $optionData['optionName'],
|
||||
'value' => $optionData['optionValue'],
|
||||
'value_id' => $option[1],
|
||||
'option_id' => $optionIds[1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($options);
|
||||
|
||||
$offerId = array();
|
||||
$offerId = [];
|
||||
|
||||
foreach($options as $optionKey => $optionData) {
|
||||
$offerId[] = $optionKey.'-'.$optionData['value_id'];
|
||||
}
|
||||
|
||||
$offerId = implode('_', $offerId);
|
||||
$e = $this->eOffers->appendChild($this->dd->createElement('offer'));
|
||||
$catalog = $this->eOffers->appendChild($this->dd->createElement('offer'));
|
||||
|
||||
if (!empty($offerId)) {
|
||||
$e->setAttribute('id', $product['product_id'] . '#' . $offerId);
|
||||
$e->setAttribute('productId', $product['product_id']);
|
||||
$e->setAttribute('quantity', $optionsValues['qty']);
|
||||
$catalog->setAttribute('id', $product['product_id'] . '#' . $offerId);
|
||||
$catalog->setAttribute('productId', $product['product_id']);
|
||||
$catalog->setAttribute('quantity', $optionsValues['qty']);
|
||||
} else {
|
||||
$e->setAttribute('id', $product['product_id']);
|
||||
$e->setAttribute('productId', $product['product_id']);
|
||||
$e->setAttribute('quantity', $product['quantity']);
|
||||
$catalog->setAttribute('id', $product['product_id']);
|
||||
$catalog->setAttribute('productId', $product['product_id']);
|
||||
$catalog->setAttribute('quantity', $product['quantity']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set type for offers
|
||||
*/
|
||||
$useServices = $servicesForIcml && isset($product['shipping']) && $product['shipping'] == 0;
|
||||
|
||||
$catalog->setAttribute('type', $useServices ? 'service' : 'product');
|
||||
|
||||
/**
|
||||
* Offer activity
|
||||
*/
|
||||
$activity = $product['status'] == 1 ? 'Y' : 'N';
|
||||
$e->appendChild(
|
||||
$catalog->appendChild(
|
||||
$this->dd->createElement('productActivity')
|
||||
)->appendChild(
|
||||
$this->dd->createTextNode($activity)
|
||||
|
@ -177,7 +199,7 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
->getProductCategories($product['product_id']);
|
||||
if (!empty($categories)) {
|
||||
foreach ($categories as $category) {
|
||||
$e->appendChild($this->dd->createElement('categoryId'))
|
||||
$catalog->appendChild($this->dd->createElement('categoryId'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode($category)
|
||||
);
|
||||
|
@ -186,27 +208,38 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
/**
|
||||
* Name & price
|
||||
*/
|
||||
$e->appendChild($this->dd->createElement('productName'))
|
||||
$catalog->appendChild($this->dd->createElement('productName'))
|
||||
->appendChild($this->dd->createTextNode($product['name']));
|
||||
if(!empty($options)) {
|
||||
$optionsString = array();
|
||||
if (!empty($options)) {
|
||||
$optionsString = [];
|
||||
foreach($options as $option) {
|
||||
$optionsString[] = $option['name'].': '.$option['value'];
|
||||
}
|
||||
$optionsString = ' ('.implode(', ', $optionsString).')';
|
||||
$e->appendChild($this->dd->createElement('name'))
|
||||
$catalog->appendChild($this->dd->createElement('name'))
|
||||
->appendChild($this->dd->createTextNode($product['name'].$optionsString));
|
||||
} else {
|
||||
$e->appendChild($this->dd->createElement('name'))
|
||||
$catalog->appendChild($this->dd->createElement('name'))
|
||||
->appendChild($this->dd->createTextNode($product['name']));
|
||||
}
|
||||
$e->appendChild($this->dd->createElement('price'))
|
||||
->appendChild($this->dd->createTextNode($product['price'] + $optionsValues['price']));
|
||||
|
||||
if ($currencyForIcml && $currencyForIcml != $defaultCurrency) {
|
||||
$price = $this->currency->convert(
|
||||
$product['price'] + $optionsValues['price'],
|
||||
$this->getDefaultCurrency(),
|
||||
$this->retailcrm->getCurrencyForIcml()
|
||||
);
|
||||
} else {
|
||||
$price = $product['price'] + $optionsValues['price'];
|
||||
}
|
||||
|
||||
$catalog->appendChild($this->dd->createElement('price'))
|
||||
->appendChild($this->dd->createTextNode($price));
|
||||
/**
|
||||
* Vendor
|
||||
*/
|
||||
if ($product['manufacturer_id'] != 0) {
|
||||
$e->appendChild($this->dd->createElement('vendor'))
|
||||
$catalog->appendChild($this->dd->createElement('vendor'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode(
|
||||
$offerManufacturers[$product['manufacturer_id']]
|
||||
|
@ -218,7 +251,7 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
* Dimensions
|
||||
*/
|
||||
if ((!empty($product['length']) && $product['length'] > 0) &&
|
||||
(!empty($product['width'] && $product['width'] > 0))
|
||||
(!empty($product['width']) && $product['width'] > 0)
|
||||
&& !empty($product['height']))
|
||||
{
|
||||
$lenghtArray = $this->model_localisation_length_class->getLengthClass($product['length_class_id']);
|
||||
|
@ -233,7 +266,7 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
$productHeight = $product['height'];
|
||||
}
|
||||
|
||||
if ($defaultLenght['length_class_id'] != $settingLenght) {
|
||||
if ($defaultLenght['length_class_id'] != $settingLenght && $settingLenght) {
|
||||
$unit = $this->model_localisation_length_class->getLengthClass($settingLenght);
|
||||
$productLength = $productLength * $unit['value'];
|
||||
$productWidth = $productWidth * $unit['value'];
|
||||
|
@ -247,7 +280,7 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
$productHeight
|
||||
);
|
||||
|
||||
$e->appendChild($this->dd->createElement('dimensions'))
|
||||
$catalog->appendChild($this->dd->createElement('dimensions'))
|
||||
->appendChild($this->dd->createTextNode($dimensions));
|
||||
}
|
||||
|
||||
|
@ -256,34 +289,32 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
*/
|
||||
if ($product['image']) {
|
||||
$image = $this->generateImage($product['image']);
|
||||
$e->appendChild($this->dd->createElement('picture'))
|
||||
$catalog->appendChild($this->dd->createElement('picture'))
|
||||
->appendChild($this->dd->createTextNode($image));
|
||||
}
|
||||
/**
|
||||
* Url
|
||||
*/
|
||||
$this->url = new Url(
|
||||
HTTP_CATALOG,
|
||||
$this->config->get('config_secure')
|
||||
? HTTP_CATALOG
|
||||
: HTTPS_CATALOG
|
||||
);
|
||||
$e->appendChild($this->dd->createElement('url'))
|
||||
$this->url = new Url(HTTP_CATALOG, HTTPS_CATALOG);
|
||||
$catalog->appendChild($this->dd->createElement('url'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode(
|
||||
$this->url->link(
|
||||
'product/product&product_id=' . $product['product_id']
|
||||
'product/product&product_id=' . $product['product_id'],
|
||||
'',
|
||||
(bool) $this->config->get('config_secure')
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// Options
|
||||
if(!empty($options)) {
|
||||
if (!empty($options)) {
|
||||
foreach($options as $optionKey => $optionData) {
|
||||
$param = $this->dd->createElement('param');
|
||||
$param->setAttribute('code', $optionKey);
|
||||
$param->setAttribute('code', $optionData['option_id']);
|
||||
$param->setAttribute('name', $optionData['name']);
|
||||
$param->appendChild($this->dd->createTextNode($optionData['value']));
|
||||
$e->appendChild($param);
|
||||
$catalog->appendChild($param);
|
||||
}
|
||||
}
|
||||
if ($product['sku']) {
|
||||
|
@ -291,18 +322,24 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
$sku->setAttribute('code', 'article');
|
||||
$sku->setAttribute('name', $this->language->get('article'));
|
||||
$sku->appendChild($this->dd->createTextNode($product['sku']));
|
||||
$e->appendChild($sku);
|
||||
$catalog->appendChild($sku);
|
||||
}
|
||||
if ($product['weight'] != '') {
|
||||
$weight = $this->dd->createElement('param');
|
||||
$weight->setAttribute('code', 'weight');
|
||||
$weight->setAttribute('name', $this->language->get('weight'));
|
||||
$weightValue = (isset($offer['weight_class']))
|
||||
? round($product['weight'], 3) . ' ' . $product['weight_class']
|
||||
: round($product['weight'], 3)
|
||||
$weight = $this->dd->createElement('weight');
|
||||
$coeffWeight = 1;
|
||||
|
||||
if (!empty($weightClasses[$product['weight_class_id']]['value'])) {
|
||||
$coeffWeight = $weightClasses[$product['weight_class_id']]['value'];
|
||||
}
|
||||
|
||||
$weightValue = !empty($optionsValues['weight'])
|
||||
? $product['weight'] + $optionsValues['weight']
|
||||
: $product['weight']
|
||||
;
|
||||
$weightValue = round($weightValue / $coeffWeight, 6);
|
||||
|
||||
$weight->appendChild($this->dd->createTextNode($weightValue));
|
||||
$e->appendChild($weight);
|
||||
$catalog->appendChild($weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -342,9 +379,23 @@ class ModelExtensionRetailcrmIcml extends Model
|
|||
$this->optionValues[$optionValueId] = $optionValue;
|
||||
}
|
||||
|
||||
return array(
|
||||
'optionName' => $option['name'],
|
||||
'optionValue' => $optionValue['name']
|
||||
);
|
||||
if (!empty($option['name']) && !empty($optionValue['name'])) {
|
||||
return array(
|
||||
'optionName' => $option['name'],
|
||||
'optionValue' => $optionValue['name']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function getDefaultCurrency() {
|
||||
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "currency");
|
||||
|
||||
foreach ($query->rows as $currency) {
|
||||
if ($currency['value'] == 1) {
|
||||
return $currency['code'];
|
||||
}
|
||||
}
|
||||
|
||||
return $query->rows[0]['code'];
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,188 +1,29 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmOrder extends Model
|
||||
{
|
||||
class ModelExtensionRetailcrmOrder extends Model {
|
||||
/**
|
||||
* Create order in OC
|
||||
* Upload orders to CRM
|
||||
*
|
||||
* @param array $order
|
||||
* @param array $orders
|
||||
*
|
||||
* @return int $order_id
|
||||
* @return mixed
|
||||
*/
|
||||
public function addOrder($order)
|
||||
public function uploadToCrm($orders)
|
||||
{
|
||||
$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()");
|
||||
$ordersToCrm = array();
|
||||
/** @var OrderManager $order_manager */
|
||||
$order_manager = $this->retailcrm->getOrderManager();
|
||||
|
||||
$order_id = $this->db->getLastId();
|
||||
|
||||
// Products
|
||||
if (isset($order['order_product']) && $order['order_product']) {
|
||||
$this->addOrderProducts($order_id, $order['order_product']);
|
||||
foreach ($orders as $order) {
|
||||
$ordersToCrm[] = $order_manager->prepareOrder($order, $order['products'], $order['totals']);
|
||||
}
|
||||
|
||||
// Totals
|
||||
if (isset($order['order_total'])) {
|
||||
$this->addOrderTotals($order_id, $order['order_total']);
|
||||
$chunkedOrders = array_chunk($ordersToCrm, 50);
|
||||
|
||||
foreach($chunkedOrders as $ordersPart) {
|
||||
$order_manager->uploadOrders($ordersPart);
|
||||
}
|
||||
|
||||
return $order_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit order in OC
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $order
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function editOrder($order_id, $order)
|
||||
{
|
||||
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
// Products
|
||||
if (isset($order['order_product']) && $order['order_product']) {
|
||||
$this->addOrderProducts($order_id, $order['order_product']);
|
||||
}
|
||||
|
||||
// Totals
|
||||
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
if (isset($order['order_total'])) {
|
||||
$this->addOrderTotals($order_id, $order['order_total']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add order products
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $products
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addOrderProducts($order_id, $products)
|
||||
{
|
||||
foreach ($products as $product) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "', reward = '" . (float)$product['reward'] . "'");
|
||||
|
||||
$order_product_id = $this->db->getLastId();
|
||||
|
||||
foreach ($product['option'] as $option) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add order totals
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $totals
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addOrderTotals($order_id, $totals)
|
||||
{
|
||||
foreach ($totals as $total) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total titles
|
||||
*
|
||||
* @return string $title
|
||||
*/
|
||||
protected function totalTitles()
|
||||
{
|
||||
return 'total_';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get country by iso code 2
|
||||
*
|
||||
* @param string $isoCode
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCountryByIsoCode($isoCode)
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
|
||||
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get zone by name
|
||||
*
|
||||
* @param string $name
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getZoneByName($name)
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
|
||||
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get currency
|
||||
*
|
||||
* @param string $code
|
||||
* @param string $field (default = '')
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getCurrencyByCode($code, $field = '')
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get language
|
||||
*
|
||||
* @param string $code
|
||||
* @param string $field (default = '')
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getLanguageByCode($code, $field = '')
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get product option value
|
||||
*
|
||||
* @param int $option_value_id
|
||||
* @param string $field
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getOptionValue($option_value_id, $field = '')
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
return $chunkedOrders;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,35 +3,46 @@
|
|||
class ModelExtensionRetailcrmPrices extends Model
|
||||
{
|
||||
protected $settings;
|
||||
|
||||
protected $moduleTitle;
|
||||
private $options;
|
||||
private $optionValues;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Registry $registry
|
||||
*/
|
||||
public function __construct($registry)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('catalog/option');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('customer/customer_group');
|
||||
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload prices to CRM
|
||||
*
|
||||
* @param array $products
|
||||
* @param \RetailcrmProxy $retailcrm_api_client
|
||||
* @param \Retailcrm\Retailcrm $retailcrm
|
||||
*
|
||||
* @param RetailcrmProxy $retailcrmApiClient
|
||||
* @return mixed bool | array
|
||||
*/
|
||||
public function uploadPrices($products, $retailcrm_api_client, $retailcrm)
|
||||
public function uploadPrices($products, $retailcrmApiClient)
|
||||
{
|
||||
$this->load->model('catalog/option');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('customer/customer_group');
|
||||
$prices = $this->getPrices($products, $retailcrmApiClient);
|
||||
|
||||
$prices = $this->getPrices($products, $retailcrm_api_client, $retailcrm);
|
||||
|
||||
if ($retailcrm_api_client === false || !$prices) {
|
||||
if ($retailcrmApiClient === false || !$prices) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pricesUpload = array_chunk($prices, 250);
|
||||
|
||||
foreach ($pricesUpload as $priceUpload) {
|
||||
$retailcrm_api_client->storePricesUpload($priceUpload);
|
||||
$retailcrmApiClient->storePricesUpload($priceUpload);
|
||||
}
|
||||
|
||||
return $pricesUpload;
|
||||
|
@ -41,31 +52,30 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
* Get prices
|
||||
*
|
||||
* @param array $products
|
||||
* @param \RetailcrmProxy $retailcrm_api_client
|
||||
* @param \Retailcrm\Retailcrm $retailcrm
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getPrices($products, $retailcrm_api_client, $retailcrm)
|
||||
protected function getPrices($products, $retailcrmApiClient)
|
||||
{
|
||||
$prices = array();
|
||||
$site = $this->getSite($retailcrm_api_client);
|
||||
$site = $this->getSite($retailcrmApiClient);
|
||||
|
||||
foreach ($products as $product) {
|
||||
$specials = $this->model_catalog_product->getProductSpecials($product['product_id']);
|
||||
|
||||
if (!$specials) {
|
||||
if ($specials) {
|
||||
$productPrice = array();
|
||||
|
||||
if (is_array($specials) && count($specials)) {
|
||||
$productPrice = $this->getSpecialPrice($specials);
|
||||
}
|
||||
|
||||
$prices = array_merge($this->getPriceRequest($product, $site, $productPrice), $prices);
|
||||
} else {
|
||||
$productPrice = $this->getEmptyPrice();
|
||||
$prices[] = $this->getPriceRequest($product, $site, $productPrice, $retailcrm);
|
||||
$prices = array_merge($prices, $this->getPriceRequest($product, $site, $productPrice));
|
||||
continue;
|
||||
}
|
||||
|
||||
$productPrice = array();
|
||||
|
||||
if (is_array($specials) && count($specials)) {
|
||||
$productPrice = $this->getSpecialPrice($specials);
|
||||
}
|
||||
|
||||
$prices[] = $this->getPriceRequest($product, $site, $productPrice, $retailcrm);
|
||||
}
|
||||
|
||||
return $prices;
|
||||
|
@ -77,15 +87,13 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
* @param $product
|
||||
* @param $site
|
||||
* @param $productPrice
|
||||
* @param \Retailcrm\Retailcrm $retailcrm
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getPriceRequest($product, $site, $productPrice, $retailcrm)
|
||||
private function getPriceRequest($product, $site, $productPrice)
|
||||
{
|
||||
$settings = $this->model_setting_setting->getSetting(\retailcrm\Retailcrm::MODULE);
|
||||
$offers = $retailcrm->getOffers($product);
|
||||
$pricesProduct = array();
|
||||
$offers = $this->retailcrm->getOffers($product);
|
||||
$pricesProducts = array();
|
||||
|
||||
foreach ($offers as $optionsString => $optionsValues) {
|
||||
$optionsString = explode('_', $optionsString);
|
||||
|
@ -117,40 +125,27 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
$price = array();
|
||||
|
||||
foreach($productPrice as $k => $v) {
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_special_' . $k])) {
|
||||
if (isset($v['price']) && ($v['price'] + $optionsValues['price'] == 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_special_' . $k])) {
|
||||
$price[] = array(
|
||||
'code' => $settings[\Retailcrm\Retailcrm::MODULE . '_special_' . $k],
|
||||
'code' => $this->settings[$this->moduleTitle . '_special_' . $k],
|
||||
'price' => !$v['remove'] ? $v['price'] + $optionsValues['price'] : 0,
|
||||
'remove' => $v['remove']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$pricesProduct = array(
|
||||
$pricesProducts[] = array(
|
||||
'externalId' => $offerId ? $product['product_id'] . '#' . $offerId : $product['product_id'],
|
||||
'site' => $site,
|
||||
'prices' => $price
|
||||
);
|
||||
}
|
||||
|
||||
return $pricesProduct;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get price for no special
|
||||
*
|
||||
* @return array $productPrice
|
||||
*/
|
||||
private function getEmptyPrice()
|
||||
{
|
||||
$customerGroups = $this->model_customer_customer_group->getCustomerGroups();
|
||||
$productPrice = array();
|
||||
|
||||
foreach ($customerGroups as $customerGroup) {
|
||||
$productPrice[$customerGroup['customer_group_id']]['remove'] = true;
|
||||
}
|
||||
|
||||
return $productPrice;
|
||||
return $pricesProducts;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -158,7 +153,7 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
*
|
||||
* @param array $specials
|
||||
*
|
||||
* @return float $productPrice
|
||||
* @return array $productPrice
|
||||
*/
|
||||
private function getSpecialPrice($specials)
|
||||
{
|
||||
|
@ -176,8 +171,8 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
) {
|
||||
$productPrice[$special['customer_group_id']]['price'] = $special['price'];
|
||||
$productPrice[$special['customer_group_id']]['remove'] = false;
|
||||
$priority = $special['priority'];
|
||||
$groupId = $special['customer_group_id'];
|
||||
$priority = $special['priority'];
|
||||
}
|
||||
} else {
|
||||
$productPrice[$special['customer_group_id']]['price'] = $special['price'];
|
||||
|
@ -198,6 +193,23 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
return $productPrice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get price for no special
|
||||
*
|
||||
* @return array $productPrice
|
||||
*/
|
||||
private function getEmptyPrice()
|
||||
{
|
||||
$customerGroups = $this->model_customer_customer_group->getCustomerGroups();
|
||||
$productPrice = array();
|
||||
|
||||
foreach ($customerGroups as $customerGroup) {
|
||||
$productPrice[$customerGroup['customer_group_id']]['remove'] = true;
|
||||
}
|
||||
|
||||
return $productPrice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get data option
|
||||
*
|
||||
|
@ -234,9 +246,9 @@ class ModelExtensionRetailcrmPrices extends Model
|
|||
*
|
||||
* @return mixed boolean | string
|
||||
*/
|
||||
private function getSite($retailcrm_api_client)
|
||||
private function getSite($retailcrmApiClient)
|
||||
{
|
||||
$response = $retailcrm_api_client->sitesList();
|
||||
$response = $retailcrmApiClient->sitesList();
|
||||
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$sites = $response->sites;
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmProducts extends Model {
|
||||
public function getProductOptions($product_id) {
|
||||
$this->load->model('catalog/product_option');
|
||||
|
||||
return $this->model_catalog_product_option->getProductOptionsByProductId($product_id);
|
||||
}
|
||||
}
|
|
@ -1,15 +1,34 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmReferences extends Model {
|
||||
class ModelExtensionRetailcrmReferences extends Model
|
||||
{
|
||||
protected $settings;
|
||||
protected $moduleTitle;
|
||||
protected $retailcrmApiClient;
|
||||
|
||||
private $opencartApiClient;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get opencart delivery methods
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOpercartDeliveryTypes($opencart_api_client)
|
||||
public function getOpercartDeliveryTypes()
|
||||
{
|
||||
return $opencart_api_client->getDeliveryTypes();
|
||||
$this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry);
|
||||
|
||||
return $this->opencartApiClient->getDeliveryTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -17,11 +36,13 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDeliveryTypes($opencart_api_client, $retailcrm_api_client)
|
||||
public function getDeliveryTypes()
|
||||
{
|
||||
$this->load->model('setting/store');
|
||||
|
||||
return array(
|
||||
'opencart' => $this->getOpercartDeliveryTypes($opencart_api_client),
|
||||
'retailcrm' => $this->getApiDeliveryTypes($retailcrm_api_client)
|
||||
'opencart' => $this->getOpercartDeliveryTypes(),
|
||||
'retailcrm' => $this->getApiDeliveryTypes()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -30,11 +51,11 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOrderStatuses($retailcrm_api_client)
|
||||
public function getOrderStatuses()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartOrderStatuses(),
|
||||
'retailcrm' => $this->getApiOrderStatuses($retailcrm_api_client)
|
||||
'retailcrm' => $this->getApiOrderStatuses()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -43,11 +64,11 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getPaymentTypes($retailcrm_api_client)
|
||||
public function getPaymentTypes()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartPaymentTypes(),
|
||||
'retailcrm' => $this->getApiPaymentTypes($retailcrm_api_client)
|
||||
'retailcrm' => $this->getApiPaymentTypes()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -56,11 +77,11 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCustomFields($retailcrm_api_client)
|
||||
public function getCustomFields()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpencartCustomFields(),
|
||||
'retailcrm' => $this->getApiCustomFields($retailcrm_api_client)
|
||||
'retailcrm' => $this->getApiCustomFields()
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -127,21 +148,43 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiDeliveryTypes($retailcrm_api_client)
|
||||
public function getApiDeliveryTypes()
|
||||
{
|
||||
$response = $retailcrm_api_client->deliveryTypesList();
|
||||
$response = $this->retailcrmApiClient->deliveryTypesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM available sites list
|
||||
*/
|
||||
public function getApiSite()
|
||||
{
|
||||
$response = $this->retailcrmApiClient->sitesList();
|
||||
|
||||
if (!$response || !$response->isSuccessful()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$sites = $response->sites;
|
||||
|
||||
return end($sites);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM order statuses
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiOrderStatuses($retailcrm_api_client)
|
||||
public function getApiOrderStatuses()
|
||||
{
|
||||
$response = $retailcrm_api_client->statusesList();
|
||||
$response = $this->retailcrmApiClient->statusesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->statuses;
|
||||
}
|
||||
|
@ -151,9 +194,12 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiPaymentTypes($retailcrm_api_client)
|
||||
public function getApiPaymentTypes()
|
||||
{
|
||||
$response = $retailcrm_api_client->paymentTypesList();
|
||||
$response = $this->retailcrmApiClient->paymentTypesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
|
||||
}
|
||||
|
@ -163,19 +209,22 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiCustomFields($retailcrm_api_client)
|
||||
public function getApiCustomFields()
|
||||
{
|
||||
$customers = $retailcrm_api_client->customFieldsList(array('entity' => 'customer'));
|
||||
$orders = $retailcrm_api_client->customFieldsList(array('entity' => 'order'));
|
||||
|
||||
$custom_fields_customers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
|
||||
$custom_fields_orders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
|
||||
|
||||
if (!$custom_fields_customers && !$custom_fields_orders) {
|
||||
$customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer'));
|
||||
$orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order'));
|
||||
if (!$customers || !$orders) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array('customers' => $custom_fields_customers, 'orders' => $custom_fields_orders);
|
||||
$customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
|
||||
$customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
|
||||
|
||||
if (!$customFieldsCustomers && !$customFieldsOrders) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -183,9 +232,12 @@ class ModelExtensionRetailcrmReferences extends Model {
|
|||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getPriceTypes($retailcrm_api_client)
|
||||
public function getPriceTypes()
|
||||
{
|
||||
$response = $retailcrm_api_client->priceTypesList();
|
||||
$response = $this->retailcrmApiClient->priceTypesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->priceTypes;
|
||||
}
|
||||
|
|
|
@ -1,5 +1,11 @@
|
|||
.retailcrm_unit {margin-bottom: 10px;}
|
||||
.retailcrm_unit input {width: 60%;}
|
||||
.retailcrm_disable_border {border: none !important;}
|
||||
.retailcrm_unit input {width: 30%;}
|
||||
.checkbox input{width: auto;}
|
||||
.retailcrm_unit input[type=checkbox] {width: 13px;}
|
||||
.retailcrm_unit select {max-width: 500px;}
|
||||
.retailcrm_unit select {max-width: 500px;}
|
||||
|
||||
.question-mark {
|
||||
cursor: help;
|
||||
position: relative;
|
||||
}
|
751
src/upload/admin/view/template/extension/module/retailcrm.tpl
Normal file
751
src/upload/admin/view/template/extension/module/retailcrm.tpl
Normal file
|
@ -0,0 +1,751 @@
|
|||
<?php echo $header; ?><?php echo $column_left;?>
|
||||
<div id="content">
|
||||
<div class="page-header">
|
||||
<div class="container-fluid">
|
||||
<div class="pull-right">
|
||||
<?php if ($export_file) : ?>
|
||||
<button type="button" id="export" data-toggle="tooltip" title="<?php echo $text_button_export; ?>" class="btn btn-success"><i class="fa fa-download"></i></button>
|
||||
<?php endif; ?>
|
||||
<button type="button" id="icml" data-toggle="tooltip" title="<?php echo $text_button_catalog; ?>" class="btn btn-success"><i class="fa fa-file-text-o"></i></button>
|
||||
<button type="submit" form="form-retailcrm" data-toggle="tooltip" title="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button>
|
||||
<a href="<?php echo $cancel; ?>" data-toggle="tooltip" title="<?php echo $button_cancel; ?>" class="btn btn-default"><i class="fa fa-reply"></i></a>
|
||||
</div>
|
||||
<h1><?php echo $heading_title; ?></h1>
|
||||
<ul class="breadcrumb">
|
||||
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
|
||||
<li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
|
||||
<?php } ?>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container-fluid">
|
||||
<?php if ($error_warning) : ?>
|
||||
<div class="alert alert-danger">
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php if (isset($saved_settings['retailcrm_url'])): ?>
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<?php echo $text_notice; ?>
|
||||
<a href="<?php echo $saved_settings['retailcrm_url']; ?>/admin/settings#t-main"><?php echo $saved_settings['retailcrm_url']; ?>/admin/settings#t-main</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-body">
|
||||
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-retailcrm" class="form-horizontal">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#tab-general" data-toggle="tab"><?php echo $general_tab_text; ?></a></li>
|
||||
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
|
||||
<li><a href="#tab-references" data-toggle="tab"><?php echo $references_tab_text; ?></a></li>
|
||||
<li><a href="#tab-collector" data-toggle="tab"><?php echo $collector_tab_text; ?></a></li>
|
||||
<li><a href="#tab-consultant" data-toggle="tab"><?php echo $consultant_tab_text; ?></a></li>
|
||||
<li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li>
|
||||
<li><a href="#tab-logs" data-toggle="tab"><?php echo $logs_tab_text; ?></a></li>
|
||||
<?php endif; ?>
|
||||
</ul>
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="tab-general">
|
||||
<input type="hidden" name="retailcrm_status" value="1">
|
||||
<fieldset>
|
||||
<legend><?php echo $retailcrm_base_settings; ?></legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_url"><?php echo $retailcrm_url; ?></label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input id="retailcrm_url" type="text" name="retailcrm_url" value="<?php if (isset($saved_settings['retailcrm_url'])): echo $saved_settings['retailcrm_url']; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_apikey"><?php echo $retailcrm_apikey; ?></label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_corporate_enabled"><?php echo $corporate_enabled_label; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_corporate_enabled" value="1"
|
||||
<?php if(isset($saved_settings['retailcrm_corporate_enabled']) && $saved_settings['retailcrm_corporate_enabled'] == 1): echo 'checked'; endif;?>/>
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_corporate_enabled" value="0"
|
||||
<?php if(!isset($saved_settings['retailcrm_corporate_enabled']) || $saved_settings['retailcrm_corporate_enabled'] == 0): echo 'checked'; endif;?>/>
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $retailcrm_countries_settings; ?></legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label">Страны</label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<div class="well well-sm" style="height: 150px; overflow: auto;">
|
||||
<?php foreach($countries as $country) : ?>
|
||||
<div class="checkbox">
|
||||
<label>
|
||||
<input type="checkbox" name="<?php echo 'retailcrm_country[]'; ?>" value="<?php echo $country['country_id']; ?>" <?php if(isset($saved_settings['retailcrm_country']) && in_array($country['country_id'], $saved_settings['retailcrm_country'])): echo 'checked'; endif;?>>
|
||||
<?php echo $country['name']; ?>
|
||||
</label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $icml_settings; ?></legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label question-mark" for="retailcrm_icml_service_enabled" title="When the option is enabled, all products for which delivery is disabled will be considered as services and uploaded to CRM as services"><?php echo $icml_service_enabled_label; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_icml_service_enabled value="1"
|
||||
<?php if(isset($saved_settings['retailcrm_icml_service_enabled']) && $saved_settings['retailcrm_icml_service_enabled'] == 1): echo 'checked'; endif;?>/>
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_icml_service_enabled" value="0"
|
||||
<?php if(!isset($saved_settings['retailcrm_icml_service_enabled']) || $saved_settings['retailcrm_icml_service_enabled'] == 0): echo 'checked'; endif;?>/>
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label"><?php echo $text_currency; ?></label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="retailcrm_currency" name="retailcrm_currency" class="form-control">
|
||||
<?php foreach ($currencies as $currency) :?>
|
||||
<?php if ($currency['status']) :?>
|
||||
<option value="<?php echo $currency['code']; ?>" <?php if(isset($saved_settings['retailcrm_currency']) && $saved_settings['retailcrm_currency'] == $currency['code']):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $currency['title']; ?>
|
||||
</option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label"><?php echo $text_lenght_label; ?></label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="retailcrm_lenght" name="retailcrm_lenght" class="form-control">
|
||||
<?php foreach ($lenghts as $lenght) :?>
|
||||
<option value="<?php echo $lenght['length_class_id']; ?>" <?php if(isset($saved_settings['retailcrm_lenght']) && $saved_settings['retailcrm_lenght'] == $lenght['length_class_id']):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $lenght['title']; ?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $status_changes; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_status_changes"><?php echo $text_status_changes; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_status_changes" value="1" <?php if (isset($saved_settings['retailcrm_status_changes']) &&
|
||||
$saved_settings['retailcrm_status_changes'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_status_changes" value="0" <?php if (!isset($saved_settings['retailcrm_status_changes']) ||
|
||||
$saved_settings['retailcrm_status_changes'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
|
||||
<?php if (!empty($retailcrm_errors)) : ?>
|
||||
<?php foreach($retailcrm_errors as $retailcrm_error): ?>
|
||||
<div class="warning"><?php echo $retailcrm_error ?></div>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<fieldset>
|
||||
<legend><?php echo $retailcrm_upload_order; ?></legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label"><?php echo $text_button_export_order; ?> №</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<div class="col-lg-3 col-md-6 col-sm-6">
|
||||
<input type="text" name="order_id" class="form-control" />
|
||||
</div>
|
||||
<div class="col-lg-3 col-md-4 col-sm-6">
|
||||
<button type="button" id="export_order" class="btn btn-success"><i class="fa fa-download"></i> <?php echo $text_button_export_order; ?></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $special_price_settings; ?></legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<?php foreach ($customerGroups as $customerGroup) :?>
|
||||
<?php $cid = $customerGroup['customer_group_id']?>
|
||||
<div class="row retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" style="text-align:right!important;" for="opencart_customer_group_<?php echo $customerGroup['customer_group_id']; ?>"><?php echo $customerGroup['name']; ?></label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="retailcrm_special_<?php echo $cid; ?>" name="retailcrm_special_<?php echo $cid; ?>" class="form-control">
|
||||
<option value="" <?php if (empty($saved_settings['retailcrm_special_' . $cid])) echo 'selected'; ?>>---</option>
|
||||
<?php foreach ($priceTypes as $k => $priceType): ?>
|
||||
<?php if ($priceType['active'] == true and $priceType['default'] == false) :?>
|
||||
<option value="<?php echo $priceType['code'];?>" <?php if(isset($saved_settings['retailcrm_special_' . $cid]) && $priceType['code'] == $saved_settings['retailcrm_special_' . $cid]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $priceType['name'];?>
|
||||
</option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $order_number; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_order_number"><?php echo $text_order_number; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_order_number" value="1" <?php if (isset($saved_settings['retailcrm_order_number']) &&
|
||||
$saved_settings['retailcrm_order_number'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_order_number" value="0" <?php if (!isset($saved_settings['retailcrm_order_number']) ||
|
||||
$saved_settings['retailcrm_order_number'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $summ_around; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_summ_around"><?php echo $text_summ_around; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_summ_around" value="1" <?php if (isset($saved_settings['retailcrm_summ_around']) &&
|
||||
$saved_settings['retailcrm_summ_around'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_summ_around" value="0" <?php if (!isset($saved_settings['retailcrm_summ_around']) ||
|
||||
$saved_settings['retailcrm_summ_around'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $text_retailcrm_discount; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="label_discount"><?php echo $text_retailcrm_label_discount ?></label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input name="retailcrm_label_discount" id="label_discount" class="form-control" value="<?php if (isset($saved_settings['retailcrm_label_discount'])): echo $saved_settings['retailcrm_label_discount']; else: echo $default_retailcrm_label_discount; endif ;?>">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend><?php echo $sum_payment; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_sum_payment"><?php echo $text_sum_payment?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_sum_payment" value="1" <?php if (isset($saved_settings['retailcrm_sum_payment']) &&
|
||||
$saved_settings['retailcrm_sum_payment'] == 1) :
|
||||
echo 'checked'; endif;?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_sum_payment" value="0" <?php if (!isset($saved_settings['retailcrm_sum_payment']) ||
|
||||
$saved_settings['retailcrm_sum_payment'] == 0) :
|
||||
echo 'checked'; endif;?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-references">
|
||||
<fieldset>
|
||||
<legend><?php echo $retailcrm_dict_settings; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_delivery; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<?php if ($delivery['opencart']) :?>
|
||||
<?php foreach($delivery['opencart'] as $value): ?>
|
||||
<div class="col-sm-12" style="margin-bottom:10px;">
|
||||
<div class="pm" style="margin-bottom:5px;"><?php echo $value['title'].':'; ?></div>
|
||||
<?php unset($value['title']); ?>
|
||||
<?php foreach ($value as $key => $val): ?>
|
||||
<div class="row retailcrm_unit">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_delivery_<?php echo $val['code']; ?>" name="retailcrm_delivery[<?php echo $val['code']; ?>]" class="form-control">
|
||||
<?php foreach ($delivery['retailcrm'] as $k => $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_delivery'][$key]) && $v['code'] == $saved_settings['retailcrm_delivery'][$key]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" style="text-align:left!important;" for="retailcrm_pm_<?php echo $val['code']; ?>"><?php echo $val['title']; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php else :?>
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<?php echo $text_error_delivery; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_status; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<?php foreach ($statuses['opencart'] as $status): ?>
|
||||
<?php $uid = $status['order_status_id']?>
|
||||
<div class="row retailcrm_unit">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_status_<?php echo $uid; ?>" name="retailcrm_status[<?php echo $uid; ?>]" class="form-control">
|
||||
<?php foreach ($statuses['retailcrm'] as $k => $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_status'][$uid]) && $v['code'] == $saved_settings['retailcrm_status'][$uid]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" style="text-align:left!important;" for="retailcrm_status_<?php echo $status['order_status_id']; ?>"><?php echo $status['name']; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_payment; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<?php foreach ($payments['opencart'] as $key => $value): ?>
|
||||
<div class="row retailcrm_unit">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_payment_<?php echo $key; ?>" name="retailcrm_payment[<?php echo $key; ?>]" class="form-control">
|
||||
<?php foreach ($payments['retailcrm'] as $k => $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_payment'][$key]) && $v['code'] == $saved_settings['retailcrm_payment'][$key]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_payment_<?php echo $key; ?>"><?php echo $value; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_default; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<div class="retailcrm_unit col-sm-12">
|
||||
<div class="row">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_default_payment" name="retailcrm_default_payment" class="form-control">
|
||||
<?php foreach ($payments['opencart'] as $k => $v): ?>
|
||||
<option value="<?php echo $k;?>" <?php if(isset($saved_settings['retailcrm_default_payment']) && $k == $saved_settings['retailcrm_default_payment']):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v;?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_default_payment"><?php echo $text_payment; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="retailcrm_unit col-sm-12">
|
||||
<div class="row">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_default_shipping" name="retailcrm_default_shipping" class="form-control">
|
||||
<?php foreach ($delivery['opencart'] as $key => $value): ?>
|
||||
<optgroup label="<?php echo $value['title']; ?>">
|
||||
<?php unset($value['title']); ?>
|
||||
<?php foreach ($value as $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_default_shipping']) && $v['code'] == $saved_settings['retailcrm_default_shipping']):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['title'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</optgroup>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_default_payment"><?php echo $text_shipping; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $retailcrm_missing_status; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_missing_status" name="retailcrm_missing_status" class="form-control">
|
||||
<option>-- Выберите --</option>
|
||||
<?php foreach ($statuses['retailcrm'] as $k => $v): ?>
|
||||
<option value="<?php echo $k;?>" <?php if(isset($saved_settings['retailcrm_missing_status']) && $k == $saved_settings['retailcrm_missing_status']):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-collector">
|
||||
<fieldset>
|
||||
<legend><?php echo $daemon_collector; ?></legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector_active"><?php echo $text_collector_activity; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector_active" value="1" <?php if (isset($saved_settings['retailcrm_collector_active']) &&
|
||||
$saved_settings['retailcrm_collector_active'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector_active" value="0" <?php if (!isset($saved_settings['retailcrm_collector_active']) ||
|
||||
$saved_settings['retailcrm_collector_active'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4"><?php echo $collector_site_key; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<input id="retailcrm_collector_site_key" type="text" name="retailcrm_collector[site_key]" value="<?php if (isset($saved_settings['retailcrm_collector']['site_key'])): echo $saved_settings['retailcrm_collector']['site_key']; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $text_collector_form_capture; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector[form_capture]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['form_capture']) &&
|
||||
$saved_settings['retailcrm_collector']['form_capture'] == 1) :
|
||||
echo 'checked'; endif; ?>>
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector[form_capture]" value="0" <?php if (!isset($saved_settings['retailcrm_collector']['form_capture']) ||
|
||||
$saved_settings['retailcrm_collector']['form_capture'] == 0) :
|
||||
echo 'checked'; endif; ?>>
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector_period" class="col-md-4"><?php echo $text_collector_period; ?></label>
|
||||
<div class="col-sm-4">
|
||||
<input id="retailcrm_collector_period" type="text" name="retailcrm_collector[period]" value="<?php if (isset($saved_settings['retailcrm_collector']['period'])): echo $saved_settings['retailcrm_collector']['period']; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector[]"><?php echo $text_label_promo; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<input id="retailcrm_collector[]" type="text" name="retailcrm_collector[label_promo]" value="<?php if (isset($saved_settings['retailcrm_collector']['label_promo'])): echo $saved_settings['retailcrm_collector']['label_promo']; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector_label_send"><?php echo $text_label_send; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<input id="retailcrm_collector_label_send" type="text" name="retailcrm_collector[label_send]" value="<?php if (isset($saved_settings['retailcrm_collector']['label_send'])): echo $saved_settings['retailcrm_collector']['label_send']; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $collector_custom_text; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector[custom_form]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['custom_form']) &&
|
||||
$saved_settings['retailcrm_collector']['custom_form'] == 1) :
|
||||
echo 'checked'; endif; ?>>
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_collector[custom_form]" value="0" <?php if (!isset($saved_settings['retailcrm_collector']['custom_form']) ||
|
||||
$saved_settings['retailcrm_collector']['custom_form'] == 0) :
|
||||
echo 'checked'; endif; ?>>
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<?php foreach ($collectorFields as $field => $label) : ?>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $label; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<div class="col-md-4 col-sm-6">
|
||||
<input id="retailcrm_collector" type="text" name="retailcrm_collector[custom][<?php echo $field; ?>]" value="<?php if (isset($saved_settings['retailcrm_collector']['custom'][$field])) : echo $saved_settings['retailcrm_collector']['custom'][$field]; endif; ?>" class="form-control" />
|
||||
</div>
|
||||
<div class="col-md-8 col-sm-6" style="margin-top: 8px;">
|
||||
<input style="margin-top: 0; vertical-align: middle;" type="checkbox" name="retailcrm_collector[require][<?php echo $field; ?>_require]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['require'][$field.'_require'])) : echo 'checked'; endif;?> />
|
||||
<label style="margin-bottom: 0; vertical-align: middle; margin-left: 5px;" for="retailcrm_collector"><?php echo $text_require; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-consultant">
|
||||
<fieldset>
|
||||
<legend><?php echo $consultant_tab_text; ?></legend>
|
||||
{* onlineConsultant *}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="input-code"><?php echo $entry_code;?></label>
|
||||
<div class="col-sm-10">
|
||||
<textarea name="retailcrm_online_consultant_code" rows="5" placeholder="<?php echo $entry_code;?>" id="retailcrm_entry_code" class="form-control">
|
||||
<?php if (isset($saved_settings['retailcrm_online_consultant_code'])): echo $saved_settings['retailcrm_online_consultant_code']; endif;?>
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_online_consultant_active"><?php echo $entry_status; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_online_consultant_active" value="1" <?php if (isset($saved_settings['retailcrm_online_consultant_active']) &&
|
||||
$saved_settings['retailcrm_online_consultant_active'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_online_consultant_active" value="0" <?php if (!isset($saved_settings['retailcrm_online_consultant_active']) ||
|
||||
$saved_settings['retailcrm_online_consultant_active'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-custom_fields">
|
||||
<fieldset>
|
||||
<legend><?php echo $retailcrm_dict_custom_fields; ?></legend>
|
||||
<?php if ($customFields['retailcrm'] && $customFields['opencart']) : ?>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_custom_field_active"><?php echo $text_custom_field_activity; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_custom_field_active" value="1" <?php if (isset($saved_settings['retailcrm_custom_field_active']) &&
|
||||
$saved_settings['retailcrm_custom_field_active'] == 1) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_yes; ?>
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="retailcrm_custom_field_active" value="0" <?php if (!isset($saved_settings['retailcrm_custom_field_active']) ||
|
||||
$saved_settings['retailcrm_custom_field_active'] == 0) :
|
||||
echo 'checked'; endif; ?> />
|
||||
<?php echo $text_no; ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $text_customers_custom_fields; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<?php foreach ($customFields['opencart'] as $customField) : ?>
|
||||
<div class="col-sm-12" style="margin-bottom:5px;">
|
||||
<div class="row">
|
||||
<?php $fid = 'c_' . $customField['custom_field_id'] ?>
|
||||
<div class="col-sm-4">
|
||||
<select id="retailcrm_custom_field_<?php echo $fid; ?>" name="retailcrm_custom_field[<?php echo $fid; ?>]" class="form-control">
|
||||
<?php foreach ($customFields['retailcrm']['customers'] as $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_custom_field'][$fid]) && $v['code'] == $saved_settings['retailcrm_custom_field'][$fid]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<label style="padding-top: 9px;" for="retailcrm_custom_field_<?php echo $fid; ?>"><?php echo $customField['name']; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"><?php echo $text_orders_custom_fields; ?></label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<?php foreach ($customFields['opencart'] as $customField) : ?>
|
||||
<div class="col-sm-12" style="margin-bottom:5px;">
|
||||
<div class="row">
|
||||
<?php $fid = 'o_' . $customField['custom_field_id'] ?>
|
||||
<div class="col-sm-4">
|
||||
<select id="retailcrm_custom_field_<?php echo $fid; ?>" name="retailcrm_custom_field[<?php echo $fid; ?>]" class="form-control">
|
||||
<?php foreach ($customFields['retailcrm']['orders'] as $v): ?>
|
||||
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_custom_field'][$fid]) && $v['code'] == $saved_settings['retailcrm_custom_field'][$fid]):?>selected="selected"<?php endif;?>>
|
||||
<?php echo $v['name'];?>
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<label style="padding-top: 9px;" for="retailcrm_custom_field_<?php echo $fid; ?>"><?php echo $customField['name']; ?></label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php elseif (!$customFields['retailcrm'] && !$customFields['opencart']) : ?>
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<?php echo $text_error_custom_field; ?>
|
||||
</div>
|
||||
<?php elseif (!$customFields['retailcrm']) : ?>
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<?php echo $text_error_cf_retailcrm; ?>
|
||||
</div>
|
||||
<?php elseif (!$customFields['opencart']) : ?>
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<?php echo $text_error_cf_opencart; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-logs">
|
||||
<fieldset style="margin-bottom: 30px;">
|
||||
<legend>RetailCRM API error log</legend>
|
||||
<div class="retailcrm_unit">
|
||||
<a onclick="confirm('<?php echo $text_confirm_log; ?>') ? location.href='<?php echo $clear_retailcrm; ?>' : false;" data-toggle="tooltip" title="<?php echo $button_clear; ?>" class="btn btn-danger"><i class="fa fa-eraser"></i> <span class="hidden-xs"><?php echo $button_clear; ?></span></a>
|
||||
</div>
|
||||
<?php if (isset($logs['retailcrm_log'])) : ?>
|
||||
<div class="row">
|
||||
<div class="col-sm-12">
|
||||
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['retailcrm_log']; ?></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<?php elseif (isset($logs['retailcrm_error'])) : ?>
|
||||
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> <?php echo $logs['retailcrm_error']; ?>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Opencart API error log</legend>
|
||||
<div class="retailcrm_unit">
|
||||
<a onclick="confirm('<?php echo $text_confirm_log; ?>') ? location.href='<?php echo $clear_opencart; ?>' : false;" data-toggle="tooltip" title="<?php echo $button_clear; ?>" class="btn btn-danger"><i class="fa fa-eraser"></i> <span class="hidden-xs"><?php echo $button_clear; ?></span></a>
|
||||
</div>
|
||||
<?php if (isset($logs['oc_api_log'])) : ?>
|
||||
<div class="row">
|
||||
<div class="col-sm-12">
|
||||
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['oc_api_log']; ?></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<?php elseif (isset($logs['oc_error'])) : ?>
|
||||
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> <?php echo $logs['oc_error']; ?>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php echo $footer; ?>
|
||||
|
||||
<script type="text/javascript">
|
||||
var token = '<?php echo $token; ?>';
|
||||
$('#icml').on('click', function() {
|
||||
$.ajax({
|
||||
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/icml&token=' + token,
|
||||
beforeSend: function() {
|
||||
$('#icml').button('loading');
|
||||
},
|
||||
complete: function() {
|
||||
$('.alert-success').remove();
|
||||
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i> <?php echo $text_success_catalog; ?></div>');
|
||||
$('#icml').button('reset');
|
||||
},
|
||||
error: function(){
|
||||
alert('error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#export').on('click', function() {
|
||||
$.ajax({
|
||||
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/export&token=' + token,
|
||||
beforeSend: function() {
|
||||
$('#export').button('loading');
|
||||
},
|
||||
complete: function() {
|
||||
$('.alert-success').remove();
|
||||
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i> <?php echo $text_success_export; ?></div>');
|
||||
$('#export').button('reset');
|
||||
},
|
||||
error: function(){
|
||||
alert('error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#export_order').on('click', function() {
|
||||
var order_id = $('input[name=\'order_id\']').val();
|
||||
if (order_id && order_id > 0) {
|
||||
$.ajax({
|
||||
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/exportOrder&token=' + token + '&order_id=' + order_id,
|
||||
beforeSend: function() {
|
||||
$('#export_order').button('loading');
|
||||
},
|
||||
error: function(xhr, ajaxOptions, thrownError) {
|
||||
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
|
||||
},
|
||||
success: function(data, textStatus, jqXHR) {
|
||||
response = JSON.parse(jqXHR['responseText']);
|
||||
if (response['status_code'] == '400') {
|
||||
$('.alert-danger').remove();
|
||||
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i><?php echo $text_error_order; ?>' + response['error_msg'] + '</div>');
|
||||
$('#export_order').button('reset');
|
||||
} else {
|
||||
$('.alert-success').remove();
|
||||
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i><?php echo $text_success_export_order; ?></div>');
|
||||
$('#export_order').button('reset');
|
||||
$('input[name=\'order_id\']').val('');
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
$('.alert-danger').remove();
|
||||
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $text_error_order_id; ?></div>');
|
||||
$('#export_order').button('reset');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
File diff suppressed because it is too large
Load diff
|
@ -12,15 +12,14 @@ class ControllerApiRetailcrm extends Controller
|
|||
$this->load->model('localisation/country');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$setting = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
|
||||
$response = array();
|
||||
|
||||
if (
|
||||
isset($setting[\Retailcrm\Retailcrm::MODULE . '_country'])
|
||||
&& $setting[\Retailcrm\Retailcrm::MODULE . '_country']
|
||||
) {
|
||||
foreach ($setting[\Retailcrm\Retailcrm::MODULE . '_country'] as $country) {
|
||||
$response = array_merge($response, $this->getDeliveryTypesByZones($country));
|
||||
if (isset($setting[$moduleTitle . '_country']) && $setting[$moduleTitle . '_country']) {
|
||||
foreach ($setting[$moduleTitle . '_country'] as $country) {
|
||||
$response = $this->mergeDeliveryTypes($country, $response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -46,7 +45,9 @@ class ControllerApiRetailcrm extends Controller
|
|||
$response = array('error' => 'Not found data');
|
||||
} else {
|
||||
$this->load->model('checkout/order');
|
||||
\retailcrm\Retailcrm::$history_run = true;
|
||||
$this->model_checkout_order->addOrderHistory($this->request->post['order_id'], $this->request->post['order_status_id']);
|
||||
\retailcrm\Retailcrm::$history_run = false;
|
||||
$response = array('success' => true);
|
||||
}
|
||||
|
||||
|
@ -76,8 +77,8 @@ class ControllerApiRetailcrm extends Controller
|
|||
$address = array(
|
||||
'country_id' => $country_id,
|
||||
'zone_id' => $zone['zone_id'],
|
||||
'iso_code_2' => $country['iso_code_2'],
|
||||
'iso_code_3' => $country['iso_code_3'],
|
||||
'iso_code_2' => $country['iso_code_2'] ?? '',
|
||||
'iso_code_3' => $country['iso_code_3'] ?? '',
|
||||
'zone_code' => $zone['code'],
|
||||
'postcode' => '',
|
||||
'city' => ''
|
||||
|
@ -133,6 +134,20 @@ class ControllerApiRetailcrm extends Controller
|
|||
return $deliveryTypes;
|
||||
}
|
||||
|
||||
private function mergeDeliveryTypes($country, $result) {
|
||||
$delivery_types = $this->getDeliveryTypesByZones($country);
|
||||
|
||||
foreach ($delivery_types as $shipping_module => $shipping_type) {
|
||||
if (isset($result[$shipping_module])) {
|
||||
$result[$shipping_module] = array_merge($result[$shipping_module], $shipping_type);
|
||||
} else {
|
||||
$result[$shipping_module] = $shipping_type;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function auth()
|
||||
{
|
||||
if (!isset($this->request->get['key'])
|
||||
|
@ -141,9 +156,17 @@ class ControllerApiRetailcrm extends Controller
|
|||
return array('error' => 'Not found api key');
|
||||
}
|
||||
|
||||
if (isset($this->request->get['key']) && !empty($this->request->get['key'])) {
|
||||
$this->load->model('extension/retailcrm/api');
|
||||
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
|
||||
if (isset($this->request->get['key'])
|
||||
&& !empty($this->request->get['key'])
|
||||
) {
|
||||
$this->load->model('account/api');
|
||||
|
||||
if ( version_compare(VERSION, '3.0', '<')) {
|
||||
$api = $this->model_account_api->getApiByKey($this->request->get['key']);
|
||||
} else {
|
||||
$this->load->model('extension/retailcrm/api');
|
||||
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
|
||||
}
|
||||
|
||||
if (!empty($api)) {
|
||||
return $api;
|
||||
|
@ -155,7 +178,14 @@ class ControllerApiRetailcrm extends Controller
|
|||
|
||||
private function loadModels()
|
||||
{
|
||||
$this->load->model('setting/extension');
|
||||
$this->modelExtension = 'setting_extension';
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$this->load->model('extension/extension');
|
||||
|
||||
$this->modelExtension = 'extension_extension';
|
||||
} else {
|
||||
$this->load->model('setting/extension');
|
||||
|
||||
$this->modelExtension = 'setting_extension';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,14 +1,17 @@
|
|||
<?php
|
||||
|
||||
class ControllerExtensionAnalyticsDaemonCollector extends Controller {
|
||||
public function index() {
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
$setting = $settings[\Retailcrm\Retailcrm::MODULE . '_collector'];
|
||||
$settings = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
$setting = $settings[$moduleTitle . '_collector'];
|
||||
$siteCode = isset($setting['site_key']) ? $setting['site_key'] : '';
|
||||
|
||||
if ($this->customer->isLogged()) $customerId = $this->customer->getID();
|
||||
|
||||
|
||||
$customer = isset($customerId) ? "'customerId': '" . $customerId . "'" : "";
|
||||
$labelPromo = !empty($setting['label_promo']) ? $setting['label_promo'] : null;
|
||||
$labelSend = !empty($setting['label_send']) ? $setting['label_send'] : null;
|
||||
|
@ -52,7 +55,7 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller {
|
|||
'period': " . $settings[$moduleTitle . '_collector']['period'] . ",
|
||||
" . $customForm . "
|
||||
});";
|
||||
}
|
||||
}
|
||||
} elseif ($labelPromo != null || $labelSend != null) {
|
||||
$captureForm = "_rc('require', 'capture-form', {
|
||||
" . $customForm . "
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
class ControllerExtensionAnalyticsOnlineConsultant extends Controller {
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function index() {
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$settings = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
$setting = trim($settings['module_retailcrm_online_consultant_code']);
|
||||
|
||||
return html_entity_decode($setting, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
}
|
|
@ -1,118 +1,177 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Class ControllerModule
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion5
|
||||
*/
|
||||
class ControllerExtensionModuleRetailcrm extends Controller {
|
||||
|
||||
private $retailcrmApiClient;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create order on event
|
||||
*
|
||||
* @param string $route
|
||||
* @param array $args
|
||||
* @param int $output
|
||||
* @param string $trigger
|
||||
* @param array $data
|
||||
* @param int $order_id order identificator
|
||||
*
|
||||
* @return boolean
|
||||
* @return void
|
||||
*/
|
||||
public function orderCreate($route, $args, $output) {
|
||||
if ($route != 'checkout/order/addOrder') {
|
||||
return false;
|
||||
public function order_create($trigger, $data, $order_id = null) {
|
||||
if (\retailcrm\Retailcrm::$history_run === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$data = $args[0];
|
||||
$data['order_id'] = $output;
|
||||
$retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
|
||||
|
||||
$retailcrm_order->prepare($data);
|
||||
$retailcrm_order->setField('externalId', $output);
|
||||
$retailcrm_order->create($this->retailcrm->getApiClient());
|
||||
$order_data = $this->model_checkout_order->getOrder($order_id);
|
||||
$products = $this->model_account_order->getOrderProducts($order_id);
|
||||
$totals = $this->model_account_order->getOrderTotals($order_id);
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
|
||||
return true;
|
||||
foreach ($products as $key => $product) {
|
||||
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$products[$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order_data['order_status'] = $status[$moduleTitle . '_status'][$order_data['order_status_id']];
|
||||
}
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/order');
|
||||
$order_data['products'] = $products;
|
||||
$order_data['totals'] = $totals;
|
||||
|
||||
$order = $this->model_extension_retailcrm_custom_order->processOrder($order_data);
|
||||
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, $order_data);
|
||||
} else {
|
||||
$order_manager = $this->retailcrm->getOrderManager();
|
||||
$order_manager->createOrder($order_data, $products, $totals);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update order on event
|
||||
*
|
||||
* @param string $route
|
||||
* @param array $args
|
||||
* @param string $trigger
|
||||
* @param array $parameter2
|
||||
*
|
||||
* @return boolean
|
||||
* @return void
|
||||
*/
|
||||
public function orderEdit($route, $args) {
|
||||
if ($route != 'checkout/order/editOrder') {
|
||||
return false;
|
||||
public function order_edit($trigger, $parameter2 = null) {
|
||||
if (\retailcrm\Retailcrm::$history_run === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order_id = $args[0];
|
||||
$data = $args[1];
|
||||
$order_id = $parameter2[0];
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('extension/module/retailcrm');
|
||||
|
||||
$order_status_id = $this->model_extension_module_retailcrm->getOrderStatusId($order_id);
|
||||
$data['order_status_id'] = $order_status_id;
|
||||
$retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$data = $this->model_checkout_order->getOrder($order_id);
|
||||
|
||||
$retailcrm_order->prepare($data);
|
||||
$retailcrm_order->setField('externalId', $order_id);
|
||||
$retailcrm_order->edit($this->retailcrm->getApiClient());
|
||||
if ($data['order_status_id'] == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
return true;
|
||||
$products = $this->model_account_order->getOrderProducts($order_id);
|
||||
$totals = $this->model_account_order->getOrderTotals($order_id);
|
||||
|
||||
foreach ($products as $key => $product) {
|
||||
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$products[$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($data['fromApi'])) {
|
||||
$status = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
|
||||
if ($data['order_status_id'] > 0) {
|
||||
$data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']];
|
||||
}
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/order');
|
||||
$data['products'] = $products;
|
||||
$data['totals'] = $totals;
|
||||
|
||||
$order = $this->model_extension_retailcrm_custom_order->processOrder($data, false);
|
||||
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, $data, false);
|
||||
} else {
|
||||
$order_manager = $this->retailcrm->getOrderManager();
|
||||
$order_manager->editOrder($data, $products, $totals);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create customer on event
|
||||
*
|
||||
* @param string $route
|
||||
* @param array $args
|
||||
* @param int $output
|
||||
* @param int $customerId customer identificator
|
||||
*
|
||||
* @return boolean
|
||||
* @return void
|
||||
*/
|
||||
public function customerCreate($route, $args, $output) {
|
||||
if ($route != 'account/customer/addCustomer') {
|
||||
return false;
|
||||
public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) {
|
||||
$customerId = $parameter3;
|
||||
$customer = $this->model_account_customer->getCustomer($customerId);
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/customer');
|
||||
$this->model_extension_retailcrm_custom_customer->sendToCrm($customer, $this->retailcrmApiClient);
|
||||
} else {
|
||||
$address = array();
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
$customer_manager->createCustomer($customer, $address);
|
||||
}
|
||||
}
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$retailcrm_customer = $this->retailcrm->createObject(\Retailcrm\Customer::class);
|
||||
public function customer_edit_newsletter($parameter1, $parameter2, $parameter3)
|
||||
{
|
||||
$customerId = $this->customer->getId();
|
||||
$customer = $this->model_account_customer->getCustomer($customerId);
|
||||
|
||||
$retailcrm_customer->prepare($args[0]);
|
||||
$retailcrm_customer->setField('externalId', $output);
|
||||
$retailcrm_customer->create($this->retailcrm->getApiClient());
|
||||
|
||||
return true;
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/customer');
|
||||
$this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient);
|
||||
} else {
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
$customer_manager->editCustomerNewsLetter($customer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update customer on event
|
||||
*
|
||||
* @param string $route
|
||||
* @param array $args
|
||||
* @return boolean
|
||||
* @param int $customerId customer identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function customerEdit($route, $args) {
|
||||
if ($route != 'account/customer/editCustomer') {
|
||||
return false;
|
||||
public function customer_edit($parameter1, $parameter2, $parameter3) {
|
||||
$customerId = $this->customer->getId();
|
||||
|
||||
$customer = $this->model_account_customer->getCustomer($customerId);
|
||||
$address = $this->model_account_address->getAddress($customer['address_id']);
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/customer');
|
||||
$customer['address'] = $address;
|
||||
$this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient);
|
||||
} else {
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
$customer_manager->editCustomer($customer, $address);
|
||||
}
|
||||
|
||||
$customer_id = $args[0];
|
||||
$data = $args[1];
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$retailcrm_customer = $this->retailcrm->createObject(\Retailcrm\Customer::class);
|
||||
|
||||
$retailcrm_customer->process($data);
|
||||
$retailcrm_customer->setField('externalId', $customer_id);
|
||||
$retailcrm_customer->edit($this->retailcrm->getApiClient());
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,449 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmOrder extends Model {
|
||||
public function getOrderStatusId($order_id) {
|
||||
$query = $this->db->query("SELECT order_status_id FROM " . DB_PREFIX . "order WHERE order_id = '" . (int)$order_id . "'");
|
||||
protected $settings;
|
||||
protected $moduleTitle;
|
||||
|
||||
return $query->rows;
|
||||
public function __construct($registry) {
|
||||
parent::__construct($registry);
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create order in CRM
|
||||
*
|
||||
* @param array $order
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
* @param array $data
|
||||
* @param bool $create (default = true)
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function sendToCrm($order, $retailcrmApiClient, $data, $create = true) {
|
||||
if ($retailcrmApiClient === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!isset($order['customer']['externalId'])) {
|
||||
$customer = $this->searchCustomer($order['phone'], $order['email'], $retailcrmApiClient);
|
||||
|
||||
if ($customer) {
|
||||
$order['customer']['id'] = $customer['id'];
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($order['customer']['externalId']) && !isset($order['customer']['id'])) {
|
||||
$res = $this->createCustomer($data, $retailcrmApiClient);
|
||||
if ($res->isSuccessful() && isset($res['id'])) {
|
||||
$order['customer']['id'] = $res['id'];
|
||||
}
|
||||
}
|
||||
|
||||
if ($create) {
|
||||
$order = self::filterRecursive($order);
|
||||
$response = $retailcrmApiClient->ordersCreate($order);
|
||||
if (isset($response['errors']['customer.externalId'])) {
|
||||
$res = $this->createCustomer($data, $retailcrmApiClient);
|
||||
if ($res->isSuccessful() && isset($res['id'])) {
|
||||
$order['customer']['id'] = $res['id'];
|
||||
}
|
||||
|
||||
$retailcrmApiClient->ordersCreate($order);
|
||||
}
|
||||
} else {
|
||||
$order_payment = reset($order['payments']);
|
||||
unset($order['payments']);
|
||||
$order = self::filterRecursive($order);
|
||||
$response = $retailcrmApiClient->ordersEdit($order);
|
||||
if (isset($response['errors']['customer.externalId'])) {
|
||||
$res = $this->createCustomer($data, $retailcrmApiClient);
|
||||
if ($res->isSuccessful() && isset($res['id'])) {
|
||||
$order['customer']['id'] = $res['id'];
|
||||
}
|
||||
|
||||
$response = $retailcrmApiClient->ordersEdit($order);
|
||||
}
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$this->updatePayment($order_payment, $order['externalId'], $retailcrmApiClient);
|
||||
}
|
||||
}
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process order
|
||||
*
|
||||
* @param array $order_data
|
||||
* @param bool $create (default = true)
|
||||
*
|
||||
* @return array $order
|
||||
*/
|
||||
public function processOrder($order_data, $create = true) {
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('account/customer');
|
||||
$this->load->model('extension/retailcrm/product');
|
||||
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
$order_id = $order_data['order_id'];
|
||||
|
||||
if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) {
|
||||
$payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']];
|
||||
} else {
|
||||
$payment_code = '';
|
||||
}
|
||||
|
||||
if (!empty($order_data['shipping_code'])) {
|
||||
$shippingCode = explode('.', $order_data['shipping_code']);
|
||||
$shippingModule = $shippingCode[0];
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
|
||||
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
|
||||
} elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) {
|
||||
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule];
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($delivery_code) && isset($shippingModule)) {
|
||||
if (isset($this->settings[$this->moduleTitle . '_delivery'])
|
||||
&& $this->settings[$this->moduleTitle . '_delivery']
|
||||
) {
|
||||
$deliveries = array_keys($this->settings[$this->moduleTitle . '_delivery']);
|
||||
$shipping_code = '';
|
||||
|
||||
array_walk($deliveries, function ($item, $key) use ($shippingModule, &$shipping_code) {
|
||||
if (strripos($item, $shippingModule) !== false) {
|
||||
$shipping_code = $item;
|
||||
}
|
||||
});
|
||||
|
||||
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shipping_code];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($order_data['shipping_iso_code_2'])) {
|
||||
$order['countryIso'] = $order_data['shipping_iso_code_2'];
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_order_number'])
|
||||
&& $this->settings[$this->moduleTitle . '_order_number'] == 1
|
||||
) {
|
||||
$order['number'] = $order_data['order_id'];
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_summ_around'])
|
||||
&& $this->settings[$this->moduleTitle . '_summ_around'] == 1
|
||||
) {
|
||||
$order['applyRound'] = true;
|
||||
}
|
||||
|
||||
$order['externalId'] = $order_id;
|
||||
$order['firstName'] = $order_data['shipping_firstname'];
|
||||
$order['lastName'] = $order_data['shipping_lastname'];
|
||||
$order['phone'] = $order_data['telephone'];
|
||||
$order['customerComment'] = $order_data['comment'];
|
||||
|
||||
if ($order_data['customer_id']) {
|
||||
$order['customer']['externalId'] = $order_data['customer_id'];
|
||||
}
|
||||
|
||||
if (!empty($order_data['email'])) {
|
||||
$order['email'] = $order_data['email'];
|
||||
}
|
||||
|
||||
$deliveryCost = 0;
|
||||
$couponTotal = 0;
|
||||
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
|
||||
|
||||
$totals = $this->explodeTotals($orderTotals);
|
||||
|
||||
if (isset($totals['shipping'])) {
|
||||
$deliveryCost = $totals['shipping'];
|
||||
}
|
||||
|
||||
if (isset($totals['coupon'])) {
|
||||
$couponTotal += abs($totals['coupon']);
|
||||
}
|
||||
|
||||
if (isset($totals['reward'])) {
|
||||
$couponTotal += abs($totals['reward']);
|
||||
}
|
||||
|
||||
$order['createdAt'] = $order_data['date_added'];
|
||||
if ($couponTotal > 0) {
|
||||
$order['discountManualAmount'] = $couponTotal;
|
||||
}
|
||||
|
||||
$country = isset($order_data['shipping_country']) ? $order_data['shipping_country'] : '' ;
|
||||
|
||||
$order['delivery'] = array(
|
||||
'code' => isset($delivery_code) ? $delivery_code : '',
|
||||
'address' => array(
|
||||
'index' => $order_data['shipping_postcode'],
|
||||
'city' => $order_data['shipping_city'],
|
||||
'countryIso' => $order_data['shipping_iso_code_2'],
|
||||
'region' => $order_data['shipping_zone'],
|
||||
'text' => implode(', ', array(
|
||||
$order_data['shipping_postcode'],
|
||||
$country,
|
||||
$order_data['shipping_city'],
|
||||
$order_data['shipping_address_1'],
|
||||
$order_data['shipping_address_2']
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
if (!empty($deliveryCost)){
|
||||
$order['delivery']['cost'] = $deliveryCost;
|
||||
}
|
||||
|
||||
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
|
||||
$offerOptions = array('select', 'radio');
|
||||
|
||||
foreach ($orderProducts as $product) {
|
||||
$offerId = '';
|
||||
|
||||
if (!empty($product['option'])) {
|
||||
$options = array();
|
||||
|
||||
$productOptions = $this->model_catalog_product->getProductOptions($product['product_id']);
|
||||
|
||||
foreach ($product['option'] as $option) {
|
||||
if ($option['type'] == 'checkbox') {
|
||||
$properties[] = array(
|
||||
'code' => $option['product_option_value_id'],
|
||||
'name' => $option['name'],
|
||||
'value' => $option['value']
|
||||
);
|
||||
}
|
||||
|
||||
if (!in_array($option['type'], $offerOptions)) continue;
|
||||
foreach($productOptions as $productOption) {
|
||||
if($productOption['product_option_id'] = $option['product_option_id']) {
|
||||
foreach($productOption['product_option_value'] as $productOptionValue) {
|
||||
if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
|
||||
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($options);
|
||||
|
||||
$offerId = array();
|
||||
foreach ($options as $optionKey => $optionValue) {
|
||||
$offerId[] = $optionKey.'-'.$optionValue;
|
||||
}
|
||||
$offerId = implode('_', $offerId);
|
||||
}
|
||||
|
||||
$item = array(
|
||||
'offer' => array(
|
||||
'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
|
||||
),
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity']
|
||||
);
|
||||
|
||||
$specials = $this->model_extension_retailcrm_product->getProductSpecials($product['product_id']);
|
||||
|
||||
if (!empty($specials)) {
|
||||
$customer = $this->model_account_customer->getCustomer($order_data['customer_id']);
|
||||
|
||||
foreach ($specials as $special) {
|
||||
if (isset($customer['customer_group_id'])) {
|
||||
if ($special['customer_group_id'] == $customer['customer_group_id']) {
|
||||
if ($this->settings[$this->moduleTitle . '_special_' . $customer['customer_group_id']]) {
|
||||
$item['priceType']['code'] = $this->settings[$this->moduleTitle . '_special_' . $customer['customer_group_id']];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($properties)) $item['properties'] = $properties;
|
||||
|
||||
$order['items'][] = $item;
|
||||
}
|
||||
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']];
|
||||
} elseif (isset($order_data['order_status_id']) && $order_data['order_status_id'] == 0) {
|
||||
$order['status'] = $this->settings[$this->moduleTitle . '_missing_status'];
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) {
|
||||
$customFields = $order_data['custom_field'];
|
||||
|
||||
foreach ($customFields as $key => $value) {
|
||||
if (isset($this->settings[$this->moduleTitle . '_custom_field']['o_' . $key])) {
|
||||
$customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['o_' . $key]] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($customFieldsToCrm)) {
|
||||
$order['customFields'] = $customFieldsToCrm;
|
||||
}
|
||||
}
|
||||
|
||||
$payment = array(
|
||||
'externalId' => $order_id,
|
||||
'type' => $payment_code,
|
||||
'amount' => $totals['total']
|
||||
);
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_sum_payment']) &&
|
||||
$this->settings[$this->moduleTitle . '_sum_payment'] == 1
|
||||
) {
|
||||
unset($payment['amount']);
|
||||
}
|
||||
|
||||
if (!$create) {
|
||||
$payment['order'] = array(
|
||||
'externalId' => $order_id
|
||||
);
|
||||
}
|
||||
|
||||
$order['payments'][] = $payment;
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update payment in CRM
|
||||
*
|
||||
* @param array $order_payment
|
||||
* @param int $orderId
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function updatePayment($order_payment, $orderId, $retailcrmApiClient) {
|
||||
$response_order = $retailcrmApiClient->ordersGet($orderId);
|
||||
|
||||
if ($response_order->isSuccessful()) {
|
||||
$order_info = $response_order['order'];
|
||||
}
|
||||
|
||||
foreach ($order_info['payments'] as $payment_data) {
|
||||
if (isset($payment_data['externalId']) && $payment_data['externalId'] == $orderId) {
|
||||
$payment = $payment_data;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($payment) && $payment['type'] != $order_payment['type']) {
|
||||
$response = $retailcrmApiClient->ordersPaymentDelete($payment['id']);
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$retailcrmApiClient->ordersPaymentCreate($order_payment);
|
||||
}
|
||||
} elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
|
||||
$retailcrmApiClient->ordersPaymentEdit($order_payment);
|
||||
}
|
||||
}
|
||||
|
||||
private function searchCustomer($phone, $email, $retailcrmApiClient) {
|
||||
$customer = array();
|
||||
|
||||
$response = $retailcrmApiClient->customersList(
|
||||
array(
|
||||
'name' => $phone,
|
||||
'email' => $email
|
||||
),
|
||||
1,
|
||||
100
|
||||
);
|
||||
|
||||
if ($response->isSuccessful() && isset($response['customers'])) {
|
||||
$customers = $response['customers'];
|
||||
|
||||
if ($customers) {
|
||||
$customer = end($customers);
|
||||
}
|
||||
}
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $totals
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function explodeTotals($totals)
|
||||
{
|
||||
$resultTotals = array();
|
||||
|
||||
foreach ($totals as $total) {
|
||||
$resultTotals[$total['code']] = $total['value'];
|
||||
}
|
||||
|
||||
return $resultTotals;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive array filter
|
||||
*
|
||||
* @param array $haystack input array
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function filterRecursive($haystack)
|
||||
{
|
||||
foreach ($haystack as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$haystack[$key] = self::filterRecursive($haystack[$key]);
|
||||
}
|
||||
if ($haystack[$key] === null
|
||||
|| $haystack[$key] === ''
|
||||
|| (is_array($haystack[$key]) && empty($haystack[$key]))
|
||||
) {
|
||||
unset($haystack[$key]);
|
||||
} elseif (!is_array($value)) {
|
||||
$haystack[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
return $haystack;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
private function createCustomer($data, $retailcrmApiClient)
|
||||
{
|
||||
$customer = array(
|
||||
'firstName' => $data['firstname'],
|
||||
'lastName' => $data['lastname'],
|
||||
'email' => $data['email'],
|
||||
'createdAt' => $data['date_added'],
|
||||
'externalId' => $data['customer_id'],
|
||||
'address' => array(
|
||||
'countryIso' => $data['payment_iso_code_2'],
|
||||
'index' => $data['payment_postcode'],
|
||||
'city' => $data['payment_city'],
|
||||
'region' => $data['payment_zone'],
|
||||
'text' => $data['payment_address_1'] . ' ' . $data['payment_address_2']
|
||||
)
|
||||
);
|
||||
|
||||
if (!empty($data['telephone'])) {
|
||||
$customer['phones'] = array(
|
||||
array(
|
||||
'number' => $data['telephone']
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $retailcrmApiClient->customersCreate($customer);
|
||||
}
|
||||
}
|
||||
|
|
10
src/upload/catalog/model/extension/retailcrm/product.php
Normal file
10
src/upload/catalog/model/extension/retailcrm/product.php
Normal file
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmProduct extends Model
|
||||
{
|
||||
public function getProductSpecials($product_id) {
|
||||
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY priority, price");
|
||||
|
||||
return $query->rows;
|
||||
}
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmProducts extends Model {
|
||||
public function getProductOptions($product_id) {
|
||||
$this->load->model('catalog/product');
|
||||
|
||||
return $this->model_catalog_product->getProductOptions($product_id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Class ModelExtensionTotalRetailcrmDiscount
|
||||
*
|
||||
* This class is unused in this module but used inside opencart as stub in file "catalog/model/checkout/order.php"
|
||||
* in method addOrderHistory()
|
||||
*/
|
||||
class ModelExtensionTotalRetailcrmDiscount extends Model
|
||||
{
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* PHP version 5.3
|
||||
*
|
||||
* Class CurlException
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
|
||||
*/
|
||||
class CurlException extends RuntimeException
|
||||
{
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* PHP version 5.3
|
||||
*
|
||||
* Class InvalidJsonException
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
|
||||
*/
|
||||
class InvalidJsonException extends DomainException
|
||||
{
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Class RequestProxy
|
||||
* @package RetailCrm\Component
|
||||
*/
|
||||
class RetailcrmProxy
|
||||
{
|
||||
private $api;
|
||||
private $log;
|
||||
private $debug;
|
||||
|
||||
public function __construct($url, $key, $log, $version = null, $debug = false)
|
||||
{
|
||||
switch ($version) {
|
||||
case 'v5':
|
||||
$this->api = new RetailcrmApiClient5($url, $key, $version);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->api = new RetailcrmApiClient5($url, $key, $version);
|
||||
break;
|
||||
}
|
||||
|
||||
$this->log = $log;
|
||||
$this->debug = $debug;
|
||||
}
|
||||
|
||||
public function __call($method, $arguments)
|
||||
{
|
||||
$date = date('[Y-m-d H:i:s]');
|
||||
|
||||
try {
|
||||
$response = call_user_func_array(array($this->api, $method), $arguments);
|
||||
|
||||
if ($this->debug) {
|
||||
$logger = new Log($method);
|
||||
$logger->write(
|
||||
array(
|
||||
'data' => $arguments,
|
||||
'response' => $response
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!$response->isSuccessful()) {
|
||||
error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log);
|
||||
if (isset($response['errors'])) {
|
||||
$error = implode("\n", $response['errors']);
|
||||
error_log($date .' '. $error . "\n", 3, $this->log);
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (CurlException $e) {
|
||||
error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log);
|
||||
return false;
|
||||
} catch (InvalidJsonException $e) {
|
||||
error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,213 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace Retailcrm;
|
||||
namespace retailcrm;
|
||||
|
||||
abstract class Base
|
||||
{
|
||||
/**
|
||||
* Class Base
|
||||
*
|
||||
* @property \Loader load
|
||||
* @property \DB db
|
||||
* @property \Config config
|
||||
* @property \Language language
|
||||
*/
|
||||
abstract class Base {
|
||||
protected $registry;
|
||||
protected $data = array();
|
||||
|
||||
/**
|
||||
* Send to crm
|
||||
*
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract public function create($retailcrm_api_client);
|
||||
|
||||
/**
|
||||
* Edit in crm
|
||||
*
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
abstract public function edit($retailcrm_api_client);
|
||||
|
||||
/**
|
||||
* Base constructor.
|
||||
*
|
||||
* @param $registry
|
||||
*/
|
||||
public function __construct($registry)
|
||||
{
|
||||
public function __construct(\Registry $registry) {
|
||||
$this->registry = $registry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $name
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name) {
|
||||
return $this->registry->get($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getData() {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $field
|
||||
* @param $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function setField($field, $value) {
|
||||
if (!array_key_exists($field, $this->data)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->data[$field] = $value;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $fields
|
||||
*/
|
||||
public function setFields($fields) {
|
||||
foreach ($fields as $field => $value) {
|
||||
$this->setField($field, $value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $data
|
||||
* @param $element
|
||||
*/
|
||||
public function setDataArray($data, $element) {
|
||||
if (is_array($data)) {
|
||||
$this->setField($element, $data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data array
|
||||
*
|
||||
* @param array $data
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function prepare($data)
|
||||
{
|
||||
unset($data);
|
||||
$this->data = Retailcrm::filterRecursive($this->data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload to CRM
|
||||
*
|
||||
* @param $retailcrm_api_client
|
||||
* @param array $data
|
||||
* @param string $method
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function upload($retailcrm_api_client, $data = array(), $method = 'orders')
|
||||
{
|
||||
if (!$data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$upload = array();
|
||||
$countOrders = count($data);
|
||||
$countIterations = (int) ($countOrders / 50);
|
||||
|
||||
foreach ($data as $key => $entity) {
|
||||
$this->prepare($entity);
|
||||
$upload[] = $this->data;
|
||||
$this->resetData();
|
||||
|
||||
if ($countIterations > 0) {
|
||||
unset($data[$key]);
|
||||
}
|
||||
|
||||
if (($countIterations == 0 && count($data) == count($upload))
|
||||
|| count($upload) == 50
|
||||
) {
|
||||
/** @var \RetailcrmApiClient5 $retailcrm_api_client */
|
||||
$retailcrm_api_client->{$method . 'Upload'}($upload);
|
||||
$upload = array();
|
||||
$countIterations--;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $custom_fields
|
||||
* @param array $setting
|
||||
* @param string $prefix
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function prepareCustomFields($custom_fields, $setting, $prefix) {
|
||||
$result = array();
|
||||
|
||||
if (!$custom_fields || empty($custom_fields)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach ($custom_fields as $loc => $custom_field) {
|
||||
if (\is_int($loc)) {
|
||||
$result = $this->getCustomFields($custom_field, $setting, $prefix);
|
||||
} elseif (\is_string($loc)) {
|
||||
foreach ($custom_field as $field) {
|
||||
if (!$field) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->getCustomFields($field, $setting, $prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $custom_fields
|
||||
* @param array $setting
|
||||
* @param string $prefix
|
||||
*
|
||||
* @return array $result
|
||||
*/
|
||||
private function getCustomFields($custom_fields, $setting, $prefix) {
|
||||
$result = array();
|
||||
|
||||
foreach ($custom_fields as $key => $field) {
|
||||
if (isset($setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key])) {
|
||||
$result[$setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key]] = $field;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset data on default
|
||||
*/
|
||||
private function resetData()
|
||||
{
|
||||
$numericValues = array(
|
||||
'externalId',
|
||||
'discountManualAmount'
|
||||
);
|
||||
|
||||
foreach ($this->data as $field => $value) {
|
||||
if (in_array($field, $numericValues)) {
|
||||
$this->data[$field] = 0;
|
||||
} elseif (is_array($value)) {
|
||||
$this->data[$field] = array();
|
||||
} else {
|
||||
$this->data[$field] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -62,13 +62,14 @@ class RetailcrmAutoloader
|
|||
$directory = new RecursiveDirectoryIterator(self::$pathTop);
|
||||
$fileIterator = new RecursiveIteratorIterator($directory);
|
||||
$filename = $className . self::$fileExt;
|
||||
$chunks = explode("\\", $filename);
|
||||
$filename = end($chunks);
|
||||
|
||||
foreach ($fileIterator as $file) {
|
||||
if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) {
|
||||
include_once $file->getPathname();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
|
@ -1,4 +1,4 @@
|
|||
<Files *.*>
|
||||
Allow from all
|
||||
Satisfy any
|
||||
</Files>
|
||||
Satisfy any
|
||||
</Files>
|
|
@ -11,8 +11,8 @@ if (!isset($cli_action)) {
|
|||
}
|
||||
|
||||
// Version
|
||||
$version = '3.1';
|
||||
$indexFile = file_get_contents(realpath(dirname(__FILE__)) . '/../../index.php');
|
||||
$version = '2.3.0';
|
||||
$indexFile = file_get_contents(realpath(dirname(__FILE__)) . '/../../../../index.php');
|
||||
preg_match("/define\([\s]*['\"]VERSION['\"][\s]*,[\s]*['\"](.*)['\"][\s]*\)[\s]*;/mi", $indexFile, $versionMatches);
|
||||
|
||||
if (isset($versionMatches[1])) {
|
||||
|
@ -22,7 +22,7 @@ if (isset($versionMatches[1])) {
|
|||
define('VERSION', $version);
|
||||
|
||||
// Configuration (note we're using the admin config)
|
||||
require_once(realpath(dirname(__FILE__)) . '/../../admin/config.php');
|
||||
require_once(realpath(dirname(__FILE__)) . '/../../../../admin/config.php');
|
||||
|
||||
// Configuration check
|
||||
if (!defined('DIR_APPLICATION')) {
|
||||
|
@ -132,13 +132,16 @@ $registry->set('cache', $cache);
|
|||
|
||||
$registry->set('response', $response);
|
||||
|
||||
$session = new Session($config->get('session_engine'), $registry);
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$session = new Session();
|
||||
} else {
|
||||
$session = new Session($config->get('session_engine'), $registry);
|
||||
}
|
||||
|
||||
$registry->set('session', $session);
|
||||
|
||||
$languages = array();
|
||||
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
|
||||
|
||||
foreach ($query->rows as $result) {
|
||||
$languages[$result['code']] = $result;
|
||||
}
|
||||
|
@ -146,24 +149,33 @@ foreach ($query->rows as $result) {
|
|||
$adminLanguageCode = $config->get('config_admin_language');
|
||||
$config->set('config_language_id', $languages[$adminLanguageCode]['language_id']);
|
||||
|
||||
$language = new Language($languages[$adminLanguageCode]['directory']);
|
||||
if (version_compare(VERSION, '2.3', '<')) {
|
||||
$language = new Language($languages[$adminLanguageCode]['directory']);
|
||||
} else {
|
||||
$language = new Language($adminLanguageCode);
|
||||
}
|
||||
|
||||
if(isset($languages[$adminLanguageCode]['filename'])) {
|
||||
$language->load($languages[$adminLanguageCode]['filename']);
|
||||
} else {
|
||||
$language->load($languages[$adminLanguageCode]['directory']);
|
||||
}
|
||||
|
||||
$registry->set('language', $language);
|
||||
|
||||
$document = new Document();
|
||||
$registry->set('document', $document);
|
||||
|
||||
|
||||
$registry->set('currency', new Cart\Currency($registry));
|
||||
$registry->set('weight', new Cart\Weight($registry));
|
||||
$registry->set('length', new Cart\Length($registry));
|
||||
$registry->set('user', new Cart\User($registry));
|
||||
|
||||
$controller = new Router($registry);
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$controller = new Front($registry);
|
||||
} else {
|
||||
$controller = new Router($registry);
|
||||
}
|
||||
|
||||
$action = new Action($cli_action);
|
||||
$controller->dispatch($action, new Action('error/not_found'));
|
3
src/upload/system/library/retailcrm/cron/icml.php
Normal file
3
src/upload/system/library/retailcrm/cron/icml.php
Normal file
|
@ -0,0 +1,3 @@
|
|||
<?php
|
||||
$cli_action = 'extension/module/retailcrm/icml';
|
||||
require_once('dispatch.php');
|
4
src/upload/system/library/retailcrm/cron/prices.php
Normal file
4
src/upload/system/library/retailcrm/cron/prices.php
Normal file
|
@ -0,0 +1,4 @@
|
|||
<?php
|
||||
$cli_action = 'extension/module/retailcrm/prices';
|
||||
require_once('dispatch.php');
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Retailcrm\Custom;
|
||||
|
||||
interface Base
|
||||
{
|
||||
/**
|
||||
* @param array $data
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function prepare(array $data);
|
||||
}
|
|
@ -1,93 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Retailcrm;
|
||||
|
||||
class Customer extends Base
|
||||
{
|
||||
protected $registry;
|
||||
protected $data = array(
|
||||
'externalId' => 0,
|
||||
'createdAt' => null,
|
||||
'firstName' => null,
|
||||
'lastName' => null,
|
||||
'patronymic' => null,
|
||||
'email' => null,
|
||||
'phones' => array(),
|
||||
'address' => array(),
|
||||
'customFields' => array()
|
||||
);
|
||||
|
||||
public function prepare($customer) {
|
||||
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom/customer.php')) {
|
||||
$custom = new \Retailcrm\Custom\Customer($this->registry);
|
||||
$this->data = $custom->prepare($customer);
|
||||
} else {
|
||||
$this->load->model('setting/setting');
|
||||
$setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
|
||||
if (isset($customer['firstname']) && $customer['firstname']) {
|
||||
$this->setField('firstName', $customer['firstname']);
|
||||
}
|
||||
|
||||
if (isset($customer['lastname']) && $customer['lastname']) {
|
||||
$this->setField('lastName', $customer['lastname']);
|
||||
}
|
||||
|
||||
if (isset($customer['telephone']) && $customer['telephone']) {
|
||||
$phones = array(
|
||||
array(
|
||||
'number' => $customer['telephone']
|
||||
)
|
||||
);
|
||||
$this->setDataArray($phones, 'phones');
|
||||
}
|
||||
|
||||
$this->setField('email', $customer['email']);
|
||||
$this->setField('createdAt', date('Y-m-d H:i:s'));
|
||||
|
||||
if (isset($customer['customer_id']) && !$this->data['externalId']) {
|
||||
$this->setField('externalId', $customer['customer_id']);
|
||||
}
|
||||
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $customer['custom_field']) {
|
||||
$custom_fields = $this->prepareCustomFields($customer['custom_field'], $setting, 'c_');
|
||||
|
||||
if ($custom_fields) {
|
||||
$this->setDataArray($custom_fields, 'customFields');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parent::prepare($customer);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function create($retailcrm_api_client) {
|
||||
if ($retailcrm_api_client === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$response = $retailcrm_api_client->customersCreate($this->data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function edit($retailcrm_api_client) {
|
||||
if ($retailcrm_api_client === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$response = $retailcrm_api_client->customersEdit($this->data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
41
src/upload/system/library/retailcrm/lib/ModelsProvider.php
Normal file
41
src/upload/system/library/retailcrm/lib/ModelsProvider.php
Normal file
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm;
|
||||
|
||||
class ModelsProvider extends Base {
|
||||
public function includeDependencies() {
|
||||
$dependencies = $this->getDependencies();
|
||||
|
||||
foreach ($dependencies[$this->getContext()] as $dependency) {
|
||||
$this->load->model($dependency);
|
||||
}
|
||||
}
|
||||
|
||||
private function getContext() {
|
||||
$match = preg_match('/\/catalog\/$/i', DIR_APPLICATION);
|
||||
|
||||
return $match === 1 ? 'catalog' : 'admin';
|
||||
}
|
||||
|
||||
private function getDependencies() {
|
||||
return array(
|
||||
'catalog' => array(
|
||||
'setting/setting',
|
||||
'checkout/order',
|
||||
'account/order',
|
||||
'account/customer',
|
||||
'account/address',
|
||||
'localisation/country',
|
||||
'localisation/zone',
|
||||
'account/address',
|
||||
'catalog/product',
|
||||
),
|
||||
'admin' => array(
|
||||
'setting/setting',
|
||||
'sale/order',
|
||||
'customer/customer',
|
||||
'catalog/product'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
34
src/upload/system/library/retailcrm/lib/Utils.php
Normal file
34
src/upload/system/library/retailcrm/lib/Utils.php
Normal file
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm;
|
||||
|
||||
class Utils {
|
||||
public static function filterRecursive($haystack) {
|
||||
foreach ($haystack as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$haystack[$key] = self::filterRecursive($haystack[$key]);
|
||||
}
|
||||
|
||||
if ($haystack[$key] === null
|
||||
|| $haystack[$key] === ''
|
||||
|| (is_array($haystack[$key]) && empty($haystack[$key]))
|
||||
) {
|
||||
unset($haystack[$key]);
|
||||
} elseif (!is_array($value)) {
|
||||
$haystack[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $haystack;
|
||||
}
|
||||
|
||||
public static function addressEquals($address1, $address2) {
|
||||
foreach ($address1 as $field => $value) {
|
||||
if (isset($address2[$field]) && $value !== $address2[$field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
<?php
|
||||
|
||||
class CurlException extends RuntimeException
|
||||
{
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
<?php
|
||||
|
||||
class InvalidJsonException extends DomainException
|
||||
{
|
||||
}
|
|
@ -14,11 +14,9 @@ class OpencartApiClient {
|
|||
|
||||
public function __construct(Registry &$registry) {
|
||||
$this->registry = $registry;
|
||||
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_apikey'])) {
|
||||
$this->cookieFileName = $settings[\Retailcrm\Retailcrm::MODULE . '_apikey'];
|
||||
}
|
||||
$moduleTitle = $this->getModuleTitle();
|
||||
$settings = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
$this->cookieFileName = $settings[$moduleTitle . '_apikey'];
|
||||
|
||||
$this->auth();
|
||||
}
|
||||
|
@ -33,7 +31,7 @@ class OpencartApiClient {
|
|||
|
||||
$cookies = array();
|
||||
foreach ($cookieFile as $line) {
|
||||
if (empty($line) OR $line{0} == '#') {
|
||||
if (empty($line) OR $line[0] == '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -49,19 +47,22 @@ class OpencartApiClient {
|
|||
}
|
||||
|
||||
private function request($method, $getParams, $postParams) {
|
||||
$this->load->model('setting/store');
|
||||
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
|
||||
|
||||
if ($this->apiToken !== false) {
|
||||
$getParams['key'] = $this->apiToken['key'];
|
||||
$getParams['username'] = $this->apiToken['username'];
|
||||
|
||||
if (isset($this->session->data['user_token'])) {
|
||||
$getParams['api_token'] = $this->session->data['user_token'];
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$getParams['key'] = $this->apiToken['key'];
|
||||
} else {
|
||||
$session = $this->registry->get('session');
|
||||
$session->start();
|
||||
$getParams['api_token'] = $session->getId();
|
||||
$getParams['key'] = $this->apiToken['key'];
|
||||
$getParams['username'] = $this->apiToken['username'];
|
||||
|
||||
if (isset($this->session->data['user_token'])) {
|
||||
$getParams['api_token'] = $this->session->data['user_token'];
|
||||
} else {
|
||||
$session = $this->registry->get('session');
|
||||
$session->start();
|
||||
$getParams['api_token'] = $session->getId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -142,7 +143,7 @@ class OpencartApiClient {
|
|||
|
||||
/**
|
||||
* Get delivery types
|
||||
*
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDeliveryTypes()
|
||||
|
@ -152,10 +153,10 @@ class OpencartApiClient {
|
|||
|
||||
/**
|
||||
* Add history order
|
||||
*
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param int $order_status_id
|
||||
*
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addHistory($order_id, $order_status_id)
|
||||
|
@ -165,7 +166,7 @@ class OpencartApiClient {
|
|||
|
||||
/**
|
||||
* Get module name
|
||||
*
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getModuleTitle()
|
|
@ -1,18 +1,11 @@
|
|||
<?php
|
||||
/**
|
||||
* PHP version 5.3
|
||||
*
|
||||
* API client class
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion5
|
||||
*/
|
||||
|
||||
class RetailcrmApiClient5
|
||||
{
|
||||
const VERSION = 'v5';
|
||||
|
||||
protected $client;
|
||||
protected $clientWithoutVersion;
|
||||
|
||||
/**
|
||||
* Site code
|
||||
|
@ -22,40 +15,39 @@ class RetailcrmApiClient5
|
|||
/**
|
||||
* Client creating
|
||||
*
|
||||
* @param string $url api url
|
||||
* @param string $url api url
|
||||
* @param string $apiKey api key
|
||||
* @param string $site site code
|
||||
* @param string $site site code
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __construct($url, $apiKey, $version = null, $site = null)
|
||||
public function __construct($url, $apiKey, $site = null)
|
||||
{
|
||||
if ('/' !== $url[strlen($url) - 1]) {
|
||||
$url .= '/';
|
||||
}
|
||||
|
||||
$url = $version == null ? $url . 'api' : $url . 'api/' . $version;
|
||||
|
||||
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
|
||||
$this->client = new RetailcrmHttpClient($url . 'api/' . static::VERSION, array('apiKey' => $apiKey));
|
||||
$this->clientWithoutVersion = new RetailcrmHttpClient($url . 'api', array('apiKey' => $apiKey));
|
||||
$this->siteCode = $site;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns api versions list
|
||||
*
|
||||
*
|
||||
* @throws \RetailCrm\Exception\InvalidJsonException
|
||||
* @throws \RetailCrm\Exception\CurlException
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function apiVersions()
|
||||
{
|
||||
return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET);
|
||||
return $this->clientWithoutVersion->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns users list
|
||||
*
|
||||
|
@ -190,7 +182,7 @@ class RetailcrmApiClient5
|
|||
$parameters
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create custom field
|
||||
*
|
||||
|
@ -223,7 +215,7 @@ class RetailcrmApiClient5
|
|||
array('customField' => json_encode($customField))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Edit custom field
|
||||
*
|
||||
|
@ -592,30 +584,18 @@ class RetailcrmApiClient5
|
|||
|
||||
/**
|
||||
* Get orders history
|
||||
*
|
||||
* @param array $filter
|
||||
* @param null $page
|
||||
* @param null $limit
|
||||
* @param int|null $limit
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function ordersHistory(array $filter = array(), $page = null, $limit = null)
|
||||
public function ordersHistory(array $filter = [], ?int $limit = 100)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/orders/history',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$parameters
|
||||
['filter' => $filter, 'limit' => $limit]
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -730,7 +710,7 @@ class RetailcrmApiClient5
|
|||
'Parameter `id` must be set'
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return $this->client->makeRequest(
|
||||
sprintf('/orders/payments/%s/delete', $id),
|
||||
RetailcrmHttpClient::METHOD_POST
|
||||
|
@ -916,30 +896,18 @@ class RetailcrmApiClient5
|
|||
|
||||
/**
|
||||
* Get customers history
|
||||
*
|
||||
* @param array $filter
|
||||
* @param null $page
|
||||
* @param null $limit
|
||||
* @param int|null $limit
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function customersHistory(array $filter = array(), $page = null, $limit = null)
|
||||
public function customersHistory(array $filter = [], ?int $limit = 100)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/customers/history',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$parameters
|
||||
['filter' => $filter, 'limit' => $limit]
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -1116,34 +1084,17 @@ class RetailcrmApiClient5
|
|||
/**
|
||||
* Get orders assembly history
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \RetailCrm\Exception\CurlException
|
||||
* @throws \RetailCrm\Exception\InvalidJsonException
|
||||
* @param array $filter
|
||||
* @param int|null $limit
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null)
|
||||
public function ordersPacksHistory(array $filter = [], ?int $limit = 100)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/orders/packs/history',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$parameters
|
||||
['filter' => $filter, 'limit' => $limit]
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -2324,6 +2275,34 @@ class RetailcrmApiClient5
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit module configuration
|
||||
*
|
||||
* @param array $configuration
|
||||
*
|
||||
* @throws \RetailCrm\Exception\InvalidJsonException
|
||||
* @throws \RetailCrm\Exception\CurlException
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function integrationModulesEdit(array $configuration)
|
||||
{
|
||||
if (!count($configuration) || empty($configuration['code'])) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Parameter `configuration` must contains a data & configuration `code` must be set'
|
||||
);
|
||||
}
|
||||
|
||||
$code = $configuration['code'];
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/integration-modules/$code/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array('integrationModule' => json_encode($configuration))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update CRM basic statistic
|
||||
*
|
||||
|
@ -2341,6 +2320,610 @@ class RetailcrmApiClient5
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns filtered corporate customers list
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateList(array $filter = [], $page = null, $limit = null)
|
||||
{
|
||||
$parameters = [];
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$parameters
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a corporate customer
|
||||
*
|
||||
* @param array $customerCorporate corporate customer data
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateCreate(array $customerCorporate, $site = null)
|
||||
{
|
||||
if (! count($customerCorporate)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Parameter `customerCorporate` must contains a data'
|
||||
);
|
||||
}
|
||||
|
||||
/* @noinspection PhpUndefinedMethodInspection */
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/create',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['customerCorporate' => json_encode($customerCorporate)])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save corporate customer IDs' (id and externalId) association in the CRM
|
||||
*
|
||||
* @param array $ids ids mapping
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateFixExternalIds(array $ids)
|
||||
{
|
||||
if (! count($ids)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Method parameter must contains at least one IDs pair'
|
||||
);
|
||||
}
|
||||
|
||||
/* @noinspection PhpUndefinedMethodInspection */
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/fix-external-ids',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
['customersCorporate' => json_encode($ids)]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get corporate customers history
|
||||
*
|
||||
* @param array $filter
|
||||
* @param int|null $limit
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function customersCorporateHistory(array $filter = [], ?int $limit = 100)
|
||||
{
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/history',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
['filter' => $filter, 'limit' => $limit]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns filtered corporate customers notes list
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateNotesList(array $filter = [], $page = null, $limit = null)
|
||||
{
|
||||
$parameters = [];
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/notes',
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$parameters
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create corporate customer note
|
||||
*
|
||||
* @param array $note (default: array())
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateNotesCreate($note, $site = null)
|
||||
{
|
||||
if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Customer identifier must be set'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/notes/create',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['note' => json_encode($note)])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete corporate customer note
|
||||
*
|
||||
* @param integer $id
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateNotesDelete($id)
|
||||
{
|
||||
if (empty($id)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Note id must be set'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/notes/$id/delete",
|
||||
RetailcrmHttpClient::METHOD_POST
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload array of the corporate customers
|
||||
*
|
||||
* @param array $customersCorporate array of corporate customers
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @return \ApiResponse
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function customersCorporateUpload(array $customersCorporate, $site = null)
|
||||
{
|
||||
if (!count($customersCorporate)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Parameter `customersCorporate` must contains array of the corporate customers'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/customers-corporate/upload',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['customersCorporate' => json_encode($customersCorporate)])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get corporate customer by id or externalId
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateGet($id, $by = 'externalId', $site = null)
|
||||
{
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id",
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$this->fillSite($site, ['by' => $by])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get corporate customer addresses by id or externalId
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateAddresses(
|
||||
$id,
|
||||
array $filter = [],
|
||||
$page = null,
|
||||
$limit = null,
|
||||
$by = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
$parameters = ['by' => $by];
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/addresses",
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$this->fillSite($site, $parameters)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create corporate customer address
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $address (default: array())
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null)
|
||||
{
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/addresses/create",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['address' => json_encode($address), 'by' => $by])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit corporate customer address
|
||||
*
|
||||
* @param string $customerId corporate customer identifier
|
||||
* @param string $addressId corporate customer identifier
|
||||
* @param array $address (default: array())
|
||||
* @param string $customerBy (default: 'externalId')
|
||||
* @param string $addressBy (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateAddressesEdit(
|
||||
$customerId,
|
||||
$addressId,
|
||||
array $address = [],
|
||||
$customerBy = 'externalId',
|
||||
$addressBy = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
$addressFiltered = array_filter($address);
|
||||
|
||||
if ((count(array_keys($addressFiltered)) <= 1)
|
||||
&& (!isset($addressFiltered['text'])
|
||||
|| (isset($addressFiltered['text']) && empty($addressFiltered['text']))
|
||||
)
|
||||
) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Parameter `address` must contain address text or all other address field'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$customerId/addresses/$addressId/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, [
|
||||
'address' => json_encode($address),
|
||||
'by' => $customerBy,
|
||||
'entityBy' => $addressBy
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get corporate customer companies by id or externalId
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateCompanies(
|
||||
$id,
|
||||
array $filter = [],
|
||||
$page = null,
|
||||
$limit = null,
|
||||
$by = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
$parameters = ['by' => $by];
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/companies",
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$this->fillSite($site, $parameters)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create corporate customer company
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $company (default: array())
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateCompaniesCreate($id, array $company = [], $by = 'externalId', $site = null)
|
||||
{
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/companies/create",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['company' => json_encode($company), 'by' => $by])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit corporate customer company
|
||||
*
|
||||
* @param string $customerId corporate customer identifier
|
||||
* @param string $companyId corporate customer identifier
|
||||
* @param array $company (default: array())
|
||||
* @param string $customerBy (default: 'externalId')
|
||||
* @param string $companyBy (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @return \ApiResponse
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
*/
|
||||
public function customersCorporateCompaniesEdit(
|
||||
$customerId,
|
||||
$companyId,
|
||||
array $company = [],
|
||||
$customerBy = 'externalId',
|
||||
$companyBy = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$customerId/companies/$companyId/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, [
|
||||
'company' => json_encode($company),
|
||||
'by' => $customerBy,
|
||||
'entityBy' => $companyBy
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get corporate customer contacts by id or externalId
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateContacts(
|
||||
$id,
|
||||
array $filter = [],
|
||||
$page = null,
|
||||
$limit = null,
|
||||
$by = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
$parameters = ['by' => $by];
|
||||
|
||||
if (count($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/contacts",
|
||||
RetailcrmHttpClient::METHOD_GET,
|
||||
$this->fillSite($site, $parameters)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create corporate customer contact
|
||||
*
|
||||
* @param string $id corporate customer identifier
|
||||
* @param array $contact (default: array())
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @return \ApiResponse
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function customersCorporateContactsCreate($id, array $contact = [], $by = 'externalId', $site = null)
|
||||
{
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$id/contacts/create",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, ['contact' => json_encode($contact), 'by' => $by])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit corporate customer contact
|
||||
*
|
||||
* @param string $customerId corporate customer identifier
|
||||
* @param string $contactId corporate customer identifier
|
||||
* @param array $contact (default: array())
|
||||
* @param string $customerBy (default: 'externalId')
|
||||
* @param string $contactBy (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @return \ApiResponse
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
*/
|
||||
public function customersCorporateContactsEdit(
|
||||
$customerId,
|
||||
$contactId,
|
||||
array $contact = [],
|
||||
$customerBy = 'externalId',
|
||||
$contactBy = 'externalId',
|
||||
$site = null
|
||||
) {
|
||||
return $this->client->makeRequest(
|
||||
"/customers-corporate/$customerId/contacts/$contactId/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, [
|
||||
'contact' => json_encode($contact),
|
||||
'by' => $customerBy,
|
||||
'entityBy' => $contactBy
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a corporate customer
|
||||
*
|
||||
* @param array $customerCorporate corporate customer data
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws \CurlException
|
||||
* @throws \InvalidJsonException
|
||||
*
|
||||
* @return \ApiResponse
|
||||
*/
|
||||
public function customersCorporateEdit(array $customerCorporate, $by = 'externalId', $site = null)
|
||||
{
|
||||
if (!count($customerCorporate)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'Parameter `customerCorporate` must contains a data'
|
||||
);
|
||||
}
|
||||
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
if (!array_key_exists($by, $customerCorporate)) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf('Corporate customer array must contain the "%s" parameter.', $by)
|
||||
);
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
sprintf('/customers-corporate/%s/edit', $customerCorporate[$by]),
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite(
|
||||
$site,
|
||||
['customerCorporate' => json_encode($customerCorporate), 'by' => $by]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return current site
|
||||
*
|
|
@ -1,15 +1,5 @@
|
|||
<?php
|
||||
/**
|
||||
* PHP version 5.3
|
||||
*
|
||||
* Response from retailCRM API
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
|
||||
*/
|
||||
|
||||
class RetailcrmApiResponse implements ArrayAccess
|
||||
{
|
||||
// HTTP response status code
|
|
@ -41,15 +41,13 @@ class RetailcrmHistoryHelper {
|
|||
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
|
||||
}
|
||||
|
||||
if (isset($change['oldValue'])
|
||||
&& empty($change['oldValue'])
|
||||
if (empty($change['oldValue'])
|
||||
&& $change['field'] == 'order_product'
|
||||
) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true;
|
||||
}
|
||||
|
||||
if (isset($change['newValue'])
|
||||
&& empty($change['newValue'])
|
||||
if (empty($change['newValue'])
|
||||
&& $change['field'] == 'order_product'
|
||||
) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true;
|
||||
|
@ -95,7 +93,7 @@ class RetailcrmHistoryHelper {
|
|||
{
|
||||
$customers = array();
|
||||
foreach ($customerHistory as $change) {
|
||||
$change['order'] = self::removeEmpty($change['customer']);
|
||||
$change['customer'] = self::removeEmpty($change['customer']);
|
||||
|
||||
if(!empty($customers[$change['customer']['id']]) && $customers[$change['customer']['id']]) {
|
||||
$customers[$change['customer']['id']] = array_merge($customers[$change['customer']['id']], $change['customer']);
|
|
@ -1,15 +1,7 @@
|
|||
<?php
|
||||
/**
|
||||
* PHP version 5.3
|
||||
*
|
||||
* HTTP client
|
||||
*
|
||||
* @category RetailCrm
|
||||
* @package RetailCrm
|
||||
* @author RetailCrm <integration@retailcrm.ru>
|
||||
* @license https://opensource.org/licenses/MIT MIT License
|
||||
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
|
||||
*/
|
||||
|
||||
use retailcrm\Retailcrm;
|
||||
|
||||
class RetailcrmHttpClient
|
||||
{
|
||||
const METHOD_GET = 'GET';
|
||||
|
@ -56,9 +48,9 @@ class RetailcrmHttpClient
|
|||
public function makeRequest(
|
||||
$path,
|
||||
$method,
|
||||
array $parameters = array()
|
||||
array $parameters = []
|
||||
) {
|
||||
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
|
||||
$allowedMethods = [self::METHOD_GET, self::METHOD_POST];
|
||||
|
||||
if (!in_array($method, $allowedMethods, false)) {
|
||||
throw new \InvalidArgumentException(
|
||||
|
@ -70,7 +62,16 @@ class RetailcrmHttpClient
|
|||
);
|
||||
}
|
||||
|
||||
$parameters = array_merge($this->defaultParameters, $parameters);
|
||||
|
||||
$parameters = self::METHOD_GET === $method
|
||||
? array_merge($this->defaultParameters, $parameters, [
|
||||
'cms_source' => 'OpenCart',
|
||||
'cms_version' => VERSION,
|
||||
'php_version' => function_exists('phpversion') ? phpversion() : '',
|
||||
'module_version' => Retailcrm::VERSION_MODULE,
|
||||
])
|
||||
: $parameters = array_merge($this->defaultParameters, $parameters);
|
||||
|
||||
|
||||
$url = $this->url . $path;
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Class RequestProxy
|
||||
*
|
||||
* @method ordersCreate($order, $site = null)
|
||||
* @method ordersEdit($order, $by = 'externalId', $site = null)
|
||||
* @method ordersGet($order, $by = 'externalId', $site = null)
|
||||
* @method ordersList(array $filter = [], $page = null, $limit = null)
|
||||
* @method customersCreate($customer, $site = null)
|
||||
* @method customersEdit($customer, $by = 'externalId', $site = null)
|
||||
* @method customersList(array $filter = [], $page = null, $limit = null)
|
||||
* @method customersGet($id, $by = 'externalId', $site = null)
|
||||
* @method customersCorporateList(array $filter = [], $page = null, $limit = null)
|
||||
* @method customersCorporateCreate(array $customerCorporate, $site = null)
|
||||
* @method customersCorporateAddresses($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
|
||||
* @method customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null)
|
||||
* @method customersCorporateAddressesEdit($customerId, $addressId, array $address = [], $customerBy = 'externalId', $addressBy = 'externalId', $site = null)
|
||||
* @method customersCorporateCompanies($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
|
||||
* @method customersCorporateCompaniesCreate($id, array $company = [], $by = 'externalId', $site = null)
|
||||
* @method customersCorporateCompaniesEdit($customerId, $companyId, array $company = [], $customerBy = 'externalId', $companyBy = 'externalId', $site = null)
|
||||
* @method customersCorporateContacts($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
|
||||
*/
|
||||
class RetailcrmProxy {
|
||||
private $api;
|
||||
private $log;
|
||||
|
||||
public function __construct($url, $key) {
|
||||
$this->api = new RetailcrmApiClient5($url, $key);
|
||||
$this->log = new \Log('retailcrm.log');
|
||||
}
|
||||
|
||||
public function __call($method, $arguments) {
|
||||
try {
|
||||
$response = call_user_func_array([$this->api, $method], $arguments);
|
||||
|
||||
if (!$response->isSuccessful()) {
|
||||
$this->log->write(sprintf("[%s] %s", $method, $response->getErrorMsg()));
|
||||
|
||||
if (isset($response['errors'])) {
|
||||
$error = implode("\n", $response['errors']);
|
||||
$this->log->write($error . "\n");
|
||||
}
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (CurlException $e) {
|
||||
$this->log->write(sprintf("[%s] %s", $method, $e->getMessage()));
|
||||
return false;
|
||||
} catch (InvalidJsonException $e) {
|
||||
$this->log->write(sprintf("[%s] %s", $method, $e->getMessage()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\factory;
|
||||
|
||||
use retailcrm\service\RetailcrmCustomerConverter;
|
||||
use retailcrm\service\SettingsManager;
|
||||
|
||||
class CustomerConverterFactory {
|
||||
public static function create(\Registry $registry) {
|
||||
return new RetailcrmCustomerConverter(new SettingsManager($registry));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\factory;
|
||||
|
||||
use retailcrm\service\RetailcrmOrderConverter;
|
||||
use retailcrm\service\SettingsManager;
|
||||
use retailcrm\repository\CustomerRepository;
|
||||
use retailcrm\repository\ProductsRepository;
|
||||
|
||||
class OrderConverterFactory {
|
||||
public static function create(\Registry $registry) {
|
||||
return new RetailcrmOrderConverter(
|
||||
new SettingsManager($registry),
|
||||
new CustomerRepository($registry),
|
||||
new ProductsRepository($registry)
|
||||
);
|
||||
}
|
||||
}
|
119
src/upload/system/library/retailcrm/lib/history/Customer.php
Normal file
119
src/upload/system/library/retailcrm/lib/history/Customer.php
Normal file
|
@ -0,0 +1,119 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\history;
|
||||
|
||||
use retailcrm\repository\CustomerRepository;
|
||||
use retailcrm\repository\DataRepository;
|
||||
use retailcrm\service\SettingsManager;
|
||||
|
||||
class Customer {
|
||||
private $data_repository;
|
||||
private $customer_repository;
|
||||
private $settings_manager;
|
||||
|
||||
public function __construct(
|
||||
DataRepository $data_repository,
|
||||
CustomerRepository $customer_repository,
|
||||
SettingsManager $settings_manager
|
||||
) {
|
||||
$this->data_repository = $data_repository;
|
||||
$this->customer_repository = $customer_repository;
|
||||
$this->settings_manager = $settings_manager;
|
||||
}
|
||||
|
||||
public function handleCustomer(&$customer_data, $customer) {
|
||||
// is new customer
|
||||
if (!$customer_data) {
|
||||
$customer_data['store_id'] = 0;
|
||||
$customer_data['customer_group_id'] = '1';
|
||||
$customer_data['fax'] = '';
|
||||
$customer_data['newsletter'] = 0;
|
||||
$customer_data['password'] = 'tmppass';
|
||||
$customer_data['status'] = 1;
|
||||
$customer_data['approved'] = 1;
|
||||
$customer_data['safe'] = 0;
|
||||
$customer_data['affiliate'] = '';
|
||||
} else {
|
||||
$customer_data['password'] = false;
|
||||
}
|
||||
|
||||
$customer_data['firstname'] = $customer['firstName'];
|
||||
$customer_data['lastname'] = $customer['lastName'] ?? '';
|
||||
$customer_data['email'] = $customer['email'];
|
||||
$customer_data['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : '';
|
||||
|
||||
if (!empty($customer['emailMarketingUnsubscribedAt'])) {
|
||||
$customer_data['newsletter'] = 0;
|
||||
}
|
||||
|
||||
$customer_data['affiliate'] = false;
|
||||
}
|
||||
|
||||
public function handleAddress($customer, $order, $address_id = 0) {
|
||||
if (empty($customer['address']) && !empty($order)) {
|
||||
$customer['address'] = $order['delivery']['address'];
|
||||
}
|
||||
|
||||
if ($address_id) {
|
||||
$customer_address = $this->customer_repository->getAddress($address_id);
|
||||
} else {
|
||||
$customer_address = array(
|
||||
'address_id' => ''
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($customer['address']['countryIso'])) {
|
||||
$customer_country = $this->data_repository->getCountryByIsoCode($customer['address']['countryIso']);
|
||||
}
|
||||
|
||||
if (isset($customer['address']['region'])) {
|
||||
$customer_zone = $this->data_repository->getZoneByName($customer['address']['region']);
|
||||
}
|
||||
|
||||
$customer_address['firstname'] = isset($customer['patronymic'])
|
||||
? $customer['firstName'] . ' ' . $customer['patronymic']
|
||||
: $customer['firstName'];
|
||||
$customer_address['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
|
||||
$customer_address['address_2'] = !empty($customer_address['address_2']) ? $customer_address['address_2'] : '';
|
||||
$customer_address['company'] = !empty($customer_address['company']) ? $customer_address['company'] : '';
|
||||
|
||||
if (!empty($customer['address'])) {
|
||||
$customer_address['address_1'] = !empty($customer['address']['text']) ? $customer['address']['text'] : '';
|
||||
$customer_address['city'] = !empty($customer['address']['city']) ? $customer['address']['city'] : '';
|
||||
$customer_address['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : '';
|
||||
}
|
||||
|
||||
$customer_address['zone_id'] = 0;
|
||||
$customer_address['country_id'] = 0;
|
||||
|
||||
if (isset($customer_country)) {
|
||||
$customer_address['country_id'] = $customer_country['country_id'];
|
||||
}
|
||||
|
||||
if (isset($customer_zone) && isset($customer_zone['zone_id'])) {
|
||||
$customer_address['zone_id'] = $customer_zone['zone_id'];
|
||||
}
|
||||
|
||||
$customer_address['default'] = true;
|
||||
|
||||
return $customer_address;
|
||||
}
|
||||
|
||||
public function handleCustomFields(&$customer_data, $customer) {
|
||||
$settings = $this->settings_manager->getSetting('custom_field');
|
||||
if (!empty($settings)) {
|
||||
$custom_field_setting = array_flip($settings);
|
||||
}
|
||||
|
||||
if (isset($custom_field_setting) && $customer['customFields']) {
|
||||
foreach ($customer['customFields'] as $code => $value) {
|
||||
if (array_key_exists($code, $custom_field_setting)) {
|
||||
$field_code = str_replace('c_', '', $custom_field_setting[$code]);
|
||||
$custom_fields[$field_code] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$customer_data['custom_field'] = $custom_fields ?? [];
|
||||
}
|
||||
}
|
||||
}
|
386
src/upload/system/library/retailcrm/lib/history/Order.php
Normal file
386
src/upload/system/library/retailcrm/lib/history/Order.php
Normal file
|
@ -0,0 +1,386 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\history;
|
||||
|
||||
use retailcrm\repository\DataRepository;
|
||||
use retailcrm\repository\OrderRepository;
|
||||
use retailcrm\repository\ProductsRepository;
|
||||
use retailcrm\Retailcrm;
|
||||
use retailcrm\service\SettingsManager;
|
||||
|
||||
class Order {
|
||||
private $data_repository;
|
||||
private $settings_manager;
|
||||
private $product_repository;
|
||||
private $order_repository;
|
||||
|
||||
private $payment;
|
||||
private $delivery;
|
||||
private $oc_payment;
|
||||
private $oc_delivery;
|
||||
|
||||
public function __construct(
|
||||
DataRepository $data_repository,
|
||||
SettingsManager $settings_manager,
|
||||
ProductsRepository $product_repository,
|
||||
OrderRepository $order_repository
|
||||
) {
|
||||
$this->data_repository = $data_repository;
|
||||
$this->settings_manager = $settings_manager;
|
||||
$this->product_repository = $product_repository;
|
||||
$this->order_repository = $order_repository;
|
||||
|
||||
$this->payment = array_flip($settings_manager->getPaymentSettings());
|
||||
$this->delivery = array_flip($settings_manager->getDeliverySettings());
|
||||
}
|
||||
|
||||
public function setOcPayment($oc_payment) {
|
||||
$this->oc_payment = $oc_payment;
|
||||
}
|
||||
|
||||
public function setOcDelivery($oc_delivery) {
|
||||
$this->oc_delivery = $oc_delivery;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
*/
|
||||
public function handleBaseOrderData(&$data, $order) {
|
||||
$mail = !empty($order['email']) ? $order['email'] : $order['customer']['email'];
|
||||
$phone = !empty($order['phone']) ? $order['phone'] : '';
|
||||
|
||||
if (!$phone) {
|
||||
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
|
||||
} else {
|
||||
$data['telephone'] = $phone;
|
||||
}
|
||||
|
||||
$data['currency_code'] = $this->data_repository->getConfig('config_currency');
|
||||
$data['currency_value'] = $this->data_repository->getCurrencyByCode($data['currency_code'], 'value');
|
||||
$data['currency_id'] = $this->data_repository->getCurrencyByCode($data['currency_code'], 'currency_id');
|
||||
$data['language_id'] = $this->data_repository->getLanguageByCode(
|
||||
$this->data_repository->getConfig('config_language'),
|
||||
'language_id'
|
||||
);
|
||||
$data['store_id'] = !is_null($this->data_repository->getConfig('config_store_id'))
|
||||
? $this->data_repository->getConfig('config_store_id') : 0;
|
||||
$data['store_name'] = $this->data_repository->getConfig('config_name');
|
||||
// $data['customer_id'] = $customer_id;
|
||||
$data['customer_group_id'] = 1;
|
||||
$data['firstname'] = $order['firstName'];
|
||||
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : $order['firstName'];
|
||||
$data['email'] = !empty($mail) ? $mail : uniqid() . '@retailrcm.ru';
|
||||
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
|
||||
|
||||
// this data will not retrive from crm for now
|
||||
$data['fax'] = '';
|
||||
$data['tax'] = '';
|
||||
$data['tax_id'] = '';
|
||||
$data['product'] = '';
|
||||
$data['product_id'] = '';
|
||||
$data['reward'] = '';
|
||||
$data['affiliate'] = '';
|
||||
$data['affiliate_id'] = 0;
|
||||
$data['payment_tax_id'] = '';
|
||||
$data['order_product_id'] = '';
|
||||
$data['payment_company'] = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
* @param array $corporateAddress
|
||||
*/
|
||||
public function handlePayment(&$data, $order, $corporateAddress = array()) {
|
||||
if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') {
|
||||
$customer = $order['contact'];
|
||||
|
||||
if (empty($customer['address'])) {
|
||||
$customer['address'] = $corporateAddress;
|
||||
}
|
||||
if (empty($customer['address'])) {
|
||||
$customer['address'] = $order['delivery']['address'];
|
||||
}
|
||||
} else {
|
||||
$customer = $order['customer'];
|
||||
}
|
||||
|
||||
$default_payment_country = !empty($data['payment_country']) ? $data['payment_country'] : '';
|
||||
$default_payment_country_id = !empty($data['payment_country_id']) ? $data['payment_country_id'] : 0;
|
||||
$default_payment_zone = !empty($data['payment_zone']) ? $data['payment_zone'] : '';
|
||||
$default_payment_zone_id = !empty($data['payment_zone_id']) ? $data['payment_zone_id'] : 0;
|
||||
if (isset($customer['address']['countryIso'])) {
|
||||
$payment_country = $this->data_repository->getCountryByIsoCode($customer['address']['countryIso']);
|
||||
}
|
||||
|
||||
if (isset($customer['address']['region'])) {
|
||||
$payment_zone = $this->data_repository->getZoneByName($customer['address']['region']);
|
||||
|
||||
if ($payment_zone) {
|
||||
$payment_zone_id = $payment_zone['zone_id'];
|
||||
}
|
||||
}
|
||||
|
||||
$data['payment_firstname'] = $customer['firstName'];
|
||||
$data['payment_lastname'] = (isset($customer['lastName'])) ? $customer['lastName'] : $customer['firstName'];
|
||||
$data['payment_address_2'] = '';
|
||||
|
||||
if (!empty($order['company'])) {
|
||||
$data['payment_company'] = $order['company']['name'];
|
||||
}
|
||||
|
||||
if (!empty($customer['address'])) {
|
||||
$data['payment_address_1'] = $customer['address']['text'];
|
||||
$data['payment_city'] = !empty($customer['address']['city'])
|
||||
? $customer['address']['city']
|
||||
: $order['delivery']['address']['city'];
|
||||
$data['payment_postcode'] = !empty($customer['address']['index'])
|
||||
? $customer['address']['index']
|
||||
: $order['delivery']['address']['index'];
|
||||
}
|
||||
|
||||
$data['payment_country_id'] = !empty($payment_country['country_id']) ? $payment_country['country_id'] : $default_payment_country_id;
|
||||
$data['payment_country'] = !empty($payment_country['name']) ? $payment_country['name'] : $default_payment_country;
|
||||
$data['payment_zone'] = isset($customer['address']['region']) ? $customer['address']['region'] : $default_payment_zone;
|
||||
$data['payment_zone_id'] = isset($payment_zone_id) ? $payment_zone_id : $default_payment_zone_id;
|
||||
|
||||
if (isset($order['payments']) && $order['payments']) {
|
||||
$payment = end($order['payments']);
|
||||
$data['payment_method'] = $this->oc_payment[$this->payment[$payment['type']]];
|
||||
$data['payment_code'] = $this->payment[$payment['type']];
|
||||
} elseif (empty($data['payment_code']) && empty($data['payment_method'])) {
|
||||
$data['payment_method'] = $this->oc_payment[$this->settings_manager->getSetting('default_payment')];
|
||||
$data['payment_code'] = $this->settings_manager->getSetting('default_payment');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
*/
|
||||
public function handleShipping(&$data, $order) {
|
||||
$default_shipping_country = !empty($data['shipping_country']) ? $data['shipping_country'] : '';
|
||||
$default_shipping_country_id = !empty($data['shipping_country_id']) ? $data['shipping_country_id'] : 0;
|
||||
$default_shipping_zone = !empty($data['shipping_zone']) ? $data['shipping_zone'] : '';
|
||||
$default_shipping_zone_id = !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0;
|
||||
if (!empty($order['delivery']['address']['region'])) {
|
||||
$shipping_zone = $this->data_repository->getZoneByName($order['delivery']['address']['region']);
|
||||
}
|
||||
|
||||
if (isset($order['countryIso'])) {
|
||||
$shipping_country = $this->data_repository->getCountryByIsoCode($order['countryIso']);
|
||||
}
|
||||
|
||||
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
|
||||
|
||||
$data['shipping_country_id'] = isset($shipping_country['country_id']) ? $shipping_country['country_id'] : $default_shipping_country_id;
|
||||
$data['shipping_country'] = isset($shipping_country['name']) ? $shipping_country['name'] : $default_shipping_country;
|
||||
$data['shipping_zone_id'] = isset($shipping_zone['zone_id']) ? $shipping_zone['zone_id'] : $default_shipping_zone_id;
|
||||
$data['shipping_zone'] = isset($shipping_zone['name']) ? $shipping_zone['name'] : $default_shipping_zone;
|
||||
$data['shipping_firstname'] = $order['firstName'];
|
||||
$data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
|
||||
$data['shipping_address_1'] = $order['delivery']['address']['text'];
|
||||
$data['shipping_address_2'] = '';
|
||||
$data['shipping_company'] = '';
|
||||
$data['shipping_city'] = $order['delivery']['address']['city'];
|
||||
$data['shipping_postcode'] = $order['delivery']['address']['index'];
|
||||
|
||||
if (!isset($data['shipping_code'])) {
|
||||
$data['shipping_code'] = $delivery != null
|
||||
? $this->delivery[$delivery]
|
||||
: $this->settings_manager->getSetting('default_shipping');
|
||||
|
||||
$shipping = explode('.', $data['shipping_code']);
|
||||
$shipping_module = $shipping[0];
|
||||
|
||||
if (isset($this->oc_delivery[$shipping_module][$data['shipping_code']]['title'])) {
|
||||
$data['shipping_method'] = $this->oc_delivery[$shipping_module][$data['shipping_code']]['title'];
|
||||
} else {
|
||||
$data['shipping_method'] = $this->oc_delivery[$shipping_module]['title'];
|
||||
}
|
||||
} else {
|
||||
if ($delivery !== null) {
|
||||
if (isset($this->settings_manager->getDeliverySettings()[$data['shipping_code']])
|
||||
&& isset($this->delivery[$delivery])
|
||||
) {
|
||||
$data['shipping_code'] = $this->delivery[$delivery];
|
||||
|
||||
$shipping = explode('.', $data['shipping_code']);
|
||||
$shippingModule = $shipping[0];
|
||||
|
||||
if (isset($this->oc_delivery[$shippingModule][$data['shipping_code']]['title'])) {
|
||||
$data['shipping_method'] = $this->oc_delivery[$shippingModule][$data['shipping_code']]['title'];
|
||||
} else {
|
||||
$data['shipping_method'] = $this->oc_delivery[$shippingModule]['title'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
*/
|
||||
public function handleProducts(&$data, $order) {
|
||||
$data['order_product'] = array();
|
||||
|
||||
foreach ($order['items'] as $item) {
|
||||
$product_id = $item['offer']['externalId'];
|
||||
$options = array();
|
||||
|
||||
if (mb_strpos($item['offer']['externalId'], '#', 0, mb_internal_encoding()) > 1) {
|
||||
$offer = explode('#', $item['offer']['externalId']);
|
||||
$product_id = $offer[0];
|
||||
$options_from_crm = explode('_', $offer[1]);
|
||||
|
||||
foreach ($options_from_crm as $option_from_crm) {
|
||||
$option_data = explode('-', $option_from_crm);
|
||||
$product_option_id = $option_data[0];
|
||||
$option_value_id = $option_data[1];
|
||||
|
||||
$product_options = $this->product_repository->getProductOptions($product_id);
|
||||
|
||||
foreach ($product_options as $product_option) {
|
||||
if ($product_option_id == $product_option['product_option_id']) {
|
||||
foreach ($product_option['product_option_value'] as $product_option_value) {
|
||||
if ($product_option_value['option_value_id'] == $option_value_id) {
|
||||
$options[] = array(
|
||||
'product_option_id' => $product_option_id,
|
||||
'product_option_value_id' => $product_option_value['product_option_value_id'],
|
||||
'value' => $this->data_repository->getOptionValue($product_option_value['option_value_id'], 'name'),
|
||||
'type' => $product_option['type'],
|
||||
'name' => $product_option['name'],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$product = $this->product_repository->getProduct($product_id);
|
||||
$rewards = $this->product_repository->getProductRewards($product_id);
|
||||
|
||||
$data['order_product'][] = array(
|
||||
'name' => $product['name'],
|
||||
'model' => $product['model'],
|
||||
'price' => $item['initialPrice'],
|
||||
'total' => (float)($item['initialPrice'] * $item['quantity']),
|
||||
'product_id' => $product_id,
|
||||
'quantity' => $item['quantity'],
|
||||
'option' => $options,
|
||||
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
*/
|
||||
public function handleTotals(&$data, $order) {
|
||||
$delivery_cost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
|
||||
|
||||
$subtotal_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'sub_total');
|
||||
$total_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'total');
|
||||
$shipping_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'shipping');
|
||||
$retailcrm_label_discount = $this->settings_manager->getSetting('label_discount')
|
||||
?: $this->data_repository->getLanguage('default_retailcrm_label_discount');
|
||||
|
||||
$totalDiscount = 0;
|
||||
foreach ($order['items'] as $item) {
|
||||
if ($item['discountTotal'] !== 0) {
|
||||
$totalDiscount += $item['discountTotal'] * $item['quantity'];
|
||||
}
|
||||
}
|
||||
|
||||
$data['total'] = $order['totalSumm'];
|
||||
$data['order_total'] = array(
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'sub_total',
|
||||
'title' => $this->data_repository->getLanguage('product_summ'),
|
||||
'value' => $order['summ'],
|
||||
'text' => $order['summ'],
|
||||
'sort_order' => $subtotal_settings['sub_total_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'shipping',
|
||||
'title' => $data['shipping_method'],
|
||||
'value' => $delivery_cost,
|
||||
'text' => $delivery_cost,
|
||||
'sort_order' => $shipping_settings[$this->data_repository->totalTitles() . 'shipping_sort_order']
|
||||
),
|
||||
array(
|
||||
'order_total_id' => '',
|
||||
'code' => 'total',
|
||||
'title' => $this->data_repository->getLanguage('column_total'),
|
||||
'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $delivery_cost,
|
||||
'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $delivery_cost,
|
||||
'sort_order' => $total_settings[$this->data_repository->totalTitles() . 'total_sort_order']
|
||||
)
|
||||
);
|
||||
|
||||
//TODO подкорректировать логику добавления скидки из RetailCRM
|
||||
//Если заказ создали со скидкой в RetailCRM, то добавить скидку
|
||||
if (!empty($totalDiscount)) {
|
||||
$data['order_total'][] = array(
|
||||
'order_total_id' => '',
|
||||
'code' => Retailcrm::RETAILCRM_DISCOUNT,
|
||||
'title' => $retailcrm_label_discount,
|
||||
'value' => -$totalDiscount,
|
||||
'sort_order' => Retailcrm::RETAILCRM_DISCOUNT_SORT_ORDER,
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($order['externalId'])) {
|
||||
$orderTotals = $this->order_repository->getOrderTotals($order['externalId']);
|
||||
|
||||
foreach ($orderTotals as $orderTotal) {
|
||||
if ($orderTotal['code'] == 'coupon'
|
||||
|| $orderTotal['code'] == 'reward'
|
||||
|| $orderTotal['code'] == 'voucher'
|
||||
) {
|
||||
$data['order_total'][] = $orderTotal;
|
||||
$totalDiscount -= abs($orderTotal['value']);
|
||||
}
|
||||
}
|
||||
|
||||
//TODO подкорректировать логику добавления скидки из RetailCRM
|
||||
$keyRetailCrmDiscount = array_search(Retailcrm::RETAILCRM_DISCOUNT, array_map(function ($item) {
|
||||
return $item['code'];
|
||||
}, $data['order_total']));
|
||||
|
||||
if ($totalDiscount > 0 && false !== $keyRetailCrmDiscount) {
|
||||
$data['order_total'][$keyRetailCrmDiscount]['value'] = -$totalDiscount;
|
||||
} elseif ($totalDiscount <= 0 && false !== $keyRetailCrmDiscount) {
|
||||
unset($data['order_total'][$keyRetailCrmDiscount]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data opencart order
|
||||
* @param array $order RetailCRM order
|
||||
*/
|
||||
public function handleCustomFields(&$data, $order) {
|
||||
$settings = $this->settings_manager->getSetting('custom_field');
|
||||
if (!empty($settings)) {
|
||||
$custom_field_setting = array_flip($settings);
|
||||
}
|
||||
|
||||
if (isset($custom_field_setting) && $order['customFields']) {
|
||||
foreach ($order['customFields'] as $code => $value) {
|
||||
if (array_key_exists($code, $custom_field_setting)) {
|
||||
$field_code = str_replace('o_', '', $custom_field_setting[$code]);
|
||||
$custom_fields[$field_code] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$data['custom_field'] = isset($custom_fields) ? $custom_fields : '';
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\repository;
|
||||
|
||||
class CustomerRepository extends \retailcrm\Base {
|
||||
public function getCustomer($customer_id) {
|
||||
if (null !== $this->model_account_customer) {
|
||||
return $this->model_account_customer->getCustomer($customer_id);
|
||||
}
|
||||
|
||||
if (null !== $this->model_customer_customer) {
|
||||
return $this->model_customer_customer->getCustomer($customer_id);
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
public function getAddress($address_id) {
|
||||
if (null !== $this->model_customer_customer) {
|
||||
$address_model = $this->model_customer_customer;
|
||||
} elseif (null !== $this->model_account_address) {
|
||||
$address_model = $this->model_account_address;
|
||||
} else {
|
||||
return array();
|
||||
}
|
||||
|
||||
return $address_model->getAddress($address_id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,206 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\repository;
|
||||
|
||||
class DataRepository extends \retailcrm\Base {
|
||||
/**
|
||||
* Create order in OC
|
||||
*
|
||||
* @param array $order
|
||||
*
|
||||
* @return int $order_id
|
||||
*/
|
||||
public function addOrder($order) {
|
||||
$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', payment_company = '" . $this->db->escape($order['payment_company']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()");
|
||||
|
||||
$order_id = $this->db->getLastId();
|
||||
|
||||
// Products
|
||||
if (isset($order['order_product']) && $order['order_product']) {
|
||||
$this->addOrderProducts($order_id, $order['order_product']);
|
||||
}
|
||||
|
||||
// Totals
|
||||
if (isset($order['order_total'])) {
|
||||
$this->addOrderTotals($order_id, $order['order_total']);
|
||||
}
|
||||
|
||||
return $order_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit order in OC
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $order
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function editOrder($order_id, $order) {
|
||||
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', payment_company = '" . $this->db->escape($order['payment_company']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
// Products
|
||||
if (isset($order['order_product']) && $order['order_product']) {
|
||||
$this->addOrderProducts($order_id, $order['order_product']);
|
||||
}
|
||||
|
||||
// Totals
|
||||
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
|
||||
|
||||
if (isset($order['order_total'])) {
|
||||
$this->addOrderTotals($order_id, $order['order_total']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add order products
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $products
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addOrderProducts($order_id, $products) {
|
||||
foreach ($products as $product) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "', reward = '" . (float)$product['reward'] . "'");
|
||||
|
||||
$order_product_id = $this->db->getLastId();
|
||||
|
||||
foreach ($product['option'] as $option) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add order totals
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param array $totals
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addOrderTotals($order_id, $totals) {
|
||||
foreach ($totals as $total) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get total titles
|
||||
*
|
||||
* @return string $title
|
||||
*/
|
||||
public function totalTitles() {
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$title = '';
|
||||
} else {
|
||||
$title = 'total_';
|
||||
}
|
||||
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get country by iso code 2
|
||||
*
|
||||
* @param string $isoCode
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCountryByIsoCode($isoCode) {
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
|
||||
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get zone by name
|
||||
*
|
||||
* @param string $name
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getZoneByName($name) {
|
||||
$name = $this->db->escape($name);
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
|
||||
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get currency
|
||||
*
|
||||
* @param string $code
|
||||
* @param string $field (default = '')
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getCurrencyByCode($code, $field = '') {
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get language
|
||||
*
|
||||
* @param string $code
|
||||
* @param string $field (default = '')
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getLanguageByCode($code, $field = '') {
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get product option value
|
||||
*
|
||||
* @param int $option_value_id
|
||||
* @param string $field
|
||||
*
|
||||
* @return mixed array | string
|
||||
*/
|
||||
public function getOptionValue($option_value_id, $field = '') {
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'");
|
||||
|
||||
if (!$field) {
|
||||
return $query->row;
|
||||
}
|
||||
|
||||
return $query->row[$field];
|
||||
}
|
||||
|
||||
public function getConfig($key) {
|
||||
return $this->config->get($key);
|
||||
}
|
||||
|
||||
public function getLanguage($key) {
|
||||
return $this->language->get($key);
|
||||
}
|
||||
|
||||
public function getDeliveryTypes() {
|
||||
$this->load->model('extension/retailcrm/references');
|
||||
|
||||
return $this->model_extension_retailcrm_references->getOpercartDeliveryTypes();
|
||||
}
|
||||
|
||||
public function getPaymentTypes() {
|
||||
$this->load->model('extension/retailcrm/references');
|
||||
|
||||
return $this->model_extension_retailcrm_references->getOpercartPaymentTypes();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\repository;
|
||||
|
||||
class OrderRepository extends \retailcrm\Base {
|
||||
public function getOrder($order_id) {
|
||||
if (null !== $this->model_sale_order) {
|
||||
return $this->model_sale_order->getOrder($order_id);
|
||||
}
|
||||
|
||||
if (null !== $this->model_checkout_order) {
|
||||
return $this->model_checkout_order->getOrder($order_id);
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
public function getOrderTotals($order_id) {
|
||||
if (null !== $this->model_sale_order) {
|
||||
return $this->model_sale_order->getOrderTotals($order_id);
|
||||
}
|
||||
|
||||
if (null !== $this->model_account_order) {
|
||||
return $this->model_account_order->getOrderTotals($order_id);
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\repository;
|
||||
|
||||
class ProductsRepository extends \retailcrm\Base {
|
||||
public function getProductSpecials($product_id) {
|
||||
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY priority, price");
|
||||
|
||||
return $query->rows;
|
||||
}
|
||||
|
||||
public function getProductOptions($product_id) {
|
||||
return $this->model_catalog_product->getProductOptions($product_id);
|
||||
}
|
||||
|
||||
public function getProduct($product_id) {
|
||||
return $this->model_catalog_product->getProduct($product_id);
|
||||
}
|
||||
|
||||
public function getProductRewards($product_id) {
|
||||
return $this->model_catalog_product->getProductRewards($product_id);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,227 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
use retailcrm\repository\CustomerRepository;
|
||||
use retailcrm\Utils;
|
||||
|
||||
class CorporateCustomer {
|
||||
private $api;
|
||||
private $customer_repository;
|
||||
|
||||
public function __construct(
|
||||
\RetailcrmProxy $api,
|
||||
CustomerRepository $customer_repository
|
||||
) {
|
||||
$this->api = $api;
|
||||
$this->customer_repository = $customer_repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order_data
|
||||
* @param $customer
|
||||
* @return int|null
|
||||
*/
|
||||
public function createCorporateCustomer($order_data, $customer) {
|
||||
if (!empty($customer['externalId'])) {
|
||||
return $this->createFromExistingCustomer($order_data, $customer);
|
||||
}
|
||||
|
||||
if (!empty($customer['id'])) {
|
||||
return $this->createFromNotExistingCustomer($order_data, $customer);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function buildFromExistingCustomer($customer_data, $order_data) {
|
||||
$builder = CorporateCustomerBuilder::create()
|
||||
->setCompany($order_data['payment_company'])
|
||||
->setCustomerExternalId($customer_data['customer_id']);
|
||||
|
||||
return $builder->build();
|
||||
}
|
||||
|
||||
public function buildCorporateCustomerFromOrder($order_data, $crm_customer_id) {
|
||||
$builder = CorporateCustomerBuilder::create()
|
||||
->setCompany($order_data['payment_company'])
|
||||
->setCustomerId($crm_customer_id);
|
||||
|
||||
return $builder->build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Search by provided filter, returns first found customer
|
||||
*
|
||||
* @param array $filter
|
||||
* @param bool $returnGroup Return all customers for group filter instead of first
|
||||
*
|
||||
* @return bool|array
|
||||
*/
|
||||
public function searchCorporateCustomer($filter, $returnGroup = false)
|
||||
{
|
||||
$search = $this->api->customersCorporateList($filter);
|
||||
|
||||
if ($search && $search->isSuccessful()) {
|
||||
$customer = false;
|
||||
|
||||
if (!empty($search['customersCorporate'])) {
|
||||
if ($returnGroup) {
|
||||
return $search['customersCorporate'];
|
||||
} else {
|
||||
$dataCorporateCustomers = $search['customersCorporate'];
|
||||
$customer = reset($dataCorporateCustomers);
|
||||
}
|
||||
}
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order_data
|
||||
* @param $customer
|
||||
* @return int|null
|
||||
*/
|
||||
private function createFromExistingCustomer($order_data, $customer) {
|
||||
$response = $this->api->customersGet($customer['externalId']);
|
||||
if (!$response || !$response->isSuccessful() || empty($response['customer'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$customer_data = $this->customer_repository->getCustomer($customer['externalId']);
|
||||
|
||||
$corp_client = $this->searchCorporateCustomer(array(
|
||||
'contactIds' => array($response['customer']['id']),
|
||||
'companyName' => $order_data['payment_company']
|
||||
));
|
||||
|
||||
if (empty($corp_client)) {
|
||||
$corp_client = $this->searchCorporateCustomer(array(
|
||||
'companyName' => $order_data['payment_company']
|
||||
));
|
||||
}
|
||||
|
||||
if ($corp_client) {
|
||||
$this->updateOrCreateAddress($order_data, $corp_client);
|
||||
|
||||
return $corp_client['id'];
|
||||
}
|
||||
|
||||
$response = $this->api->customersCorporateCreate($this->buildFromExistingCustomer($customer_data, $order_data));
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$this->createAddressAndCompany($order_data, $response['id']);
|
||||
|
||||
return $response['id'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order_data
|
||||
* @param $customer
|
||||
* @return int|null
|
||||
*/
|
||||
private function createFromNotExistingCustomer($order_data, $customer) {
|
||||
$corp_client = $this->searchCorporateCustomer(array(
|
||||
'contactIds' => array($customer['id']),
|
||||
'companyName' => $order_data['payment_company']
|
||||
));
|
||||
|
||||
if (empty($corp_client)) {
|
||||
$corp_client = $this->searchCorporateCustomer(array(
|
||||
'companyName' => $order_data['payment_company']
|
||||
));
|
||||
}
|
||||
|
||||
if ($corp_client) {
|
||||
$this->updateOrCreateAddress($order_data, $corp_client);
|
||||
|
||||
return $corp_client['id'];
|
||||
}
|
||||
|
||||
$response = $this->api->customersCorporateCreate(
|
||||
$this->buildCorporateCustomerFromOrder($order_data, $customer['id'])
|
||||
);
|
||||
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$this->createAddressAndCompany($order_data, $response['id']);
|
||||
|
||||
return $response['id'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function createAddressAndCompany($order_data, $corp_client_id) {
|
||||
$corp_address = CorporateCustomerBuilder::create(false)->buildAddress($order_data);
|
||||
$address_response = $this->api->customersCorporateAddressesCreate($corp_client_id, $corp_address, 'id');
|
||||
|
||||
if ($address_response && $address_response->isSuccessful()) {
|
||||
$company = CorporateCustomerBuilder::create(false)
|
||||
->setCompany($order_data['payment_company'])
|
||||
->setCompanyAddressId($address_response['id'])
|
||||
->buildCompany($order_data);
|
||||
|
||||
$this->api->customersCorporateCompaniesCreate($corp_client_id, $company, 'id');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order_data
|
||||
* @param $corp_client
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function updateOrCreateAddress($order_data, $corp_client) {
|
||||
$address_id = null;
|
||||
$addresses_response = $this->api->customersCorporateAddresses($corp_client['id'], array(), null, null, 'id');
|
||||
$corp_address = CorporateCustomerBuilder::create(false)->buildAddress($order_data);
|
||||
|
||||
if ($addresses_response && $addresses_response->isSuccessful() && !empty($addresses_response['addresses'])) {
|
||||
foreach ($addresses_response['addresses'] as $address) {
|
||||
if (Utils::addressEquals($corp_address, $address)) {
|
||||
$address_id = $address['id'];
|
||||
$exist_address = $address;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($exist_address)) {
|
||||
$response = $this->api->customersCorporateAddressesCreate(
|
||||
$corp_client['id'],
|
||||
$corp_address,
|
||||
'id'
|
||||
);
|
||||
|
||||
if ($response && $response->isSuccessful() && isset($response['id'])) {
|
||||
$address_id = $response['id'];
|
||||
}
|
||||
}
|
||||
|
||||
$company = CorporateCustomerBuilder::create(false)
|
||||
->setCompany($order_data['payment_company'])
|
||||
->setCompanyAddressId($address_id)
|
||||
->buildCompany($order_data);
|
||||
$companies = $this->api->customersCorporateCompanies($corp_client['id'], array(), null, null, 'id');
|
||||
|
||||
if ($companies && $companies->isSuccessful() && !empty($companies['companies'])) {
|
||||
foreach ($companies['companies'] as $crm_company) {
|
||||
if ($crm_company['name'] === $order_data['payment_company']) {
|
||||
$this->api->customersCorporateCompaniesEdit(
|
||||
$corp_client['id'],
|
||||
$crm_company['id'],
|
||||
$company,
|
||||
'id',
|
||||
'id'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
class CorporateCustomerBuilder {
|
||||
private $is_main_company = false;
|
||||
private $company_address_id = null;
|
||||
private $data = array();
|
||||
private $company;
|
||||
|
||||
public static function create($init = true) {
|
||||
$self = new self();
|
||||
|
||||
if ($init) {
|
||||
$self->initData();
|
||||
}
|
||||
|
||||
return $self;
|
||||
}
|
||||
|
||||
public function initData() {
|
||||
$this->data = array(
|
||||
'customerContacts' => array(
|
||||
array(
|
||||
'isMain' => true,
|
||||
'customer' => array()
|
||||
)
|
||||
),
|
||||
'companies' => array()
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function build() {
|
||||
$this->data['nickName'] = $this->company;
|
||||
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isMainCompany
|
||||
*
|
||||
* @return CorporateCustomerBuilder
|
||||
*/
|
||||
public function setIsMainCompany($isMainCompany)
|
||||
{
|
||||
$this->is_main_company = $isMainCompany;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $companyAddressId
|
||||
*
|
||||
* @return CorporateCustomerBuilder
|
||||
*/
|
||||
public function setCompanyAddressId($companyAddressId)
|
||||
{
|
||||
$this->company_address_id = $companyAddressId;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCompany($company) {
|
||||
$this->company = $company;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCustomerId($customer_id) {
|
||||
$this->setCustomer($customer_id);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCustomerExternalId($customer_external_id) {
|
||||
$this->setCustomer($customer_external_id, 'externalId');
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function buildAddress($data) {
|
||||
return array(
|
||||
'index' => $data['shipping_postcode'],
|
||||
'countryIso' => $data['shipping_iso_code_2'],
|
||||
'region' => $data['shipping_zone'],
|
||||
'city' => $data['shipping_city'],
|
||||
'name' => $data['payment_company'],
|
||||
'text' => $data['shipping_address_1'] . ' ' . $data['shipping_address_2']
|
||||
);
|
||||
}
|
||||
|
||||
public function addAddress($data) {
|
||||
$this->data['addresses'][] = $this->buildAddress($data);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function buildLegalAddress($data) {
|
||||
return sprintf(
|
||||
"%s %s %s %s %s",
|
||||
$data['payment_postcode'],
|
||||
$data['payment_zone'],
|
||||
$data['payment_city'],
|
||||
$data['payment_address_1'],
|
||||
$data['payment_address_2']
|
||||
);
|
||||
}
|
||||
|
||||
public function buildCompany($data) {
|
||||
$company = array(
|
||||
'name' => $this->company,
|
||||
'contragent' => array(
|
||||
'legalAddress' => $this->buildLegalAddress($data),
|
||||
'contragentType' => 'legal-entity',
|
||||
)
|
||||
);
|
||||
|
||||
if ($this->is_main_company) {
|
||||
$company['isMain'] = true;
|
||||
}
|
||||
|
||||
if (null !== $this->company_address_id) {
|
||||
$company['address'] = array('id' => $this->company_address_id);
|
||||
}
|
||||
|
||||
return $company;
|
||||
}
|
||||
|
||||
public function addCompany($data) {
|
||||
$this->data['companies'][] = $this->buildCompany($data);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function setCustomer($id, $field = 'id') {
|
||||
foreach ($this->data['customerContacts'] as $key => $customerContact) {
|
||||
if ($customerContact['isMain']) {
|
||||
$this->data['customerContacts'][$key]['customer'][$field] = $id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
class CustomerManager {
|
||||
protected $api;
|
||||
protected $customer_converter;
|
||||
|
||||
public function __construct(\RetailcrmProxy $proxy, RetailcrmCustomerConverter $customer_converter) {
|
||||
$this->api = $proxy;
|
||||
$this->customer_converter = $customer_converter;
|
||||
}
|
||||
|
||||
public function createCustomer($customer_data, $address) {
|
||||
$customer = $this->prepareCustomer($customer_data, $address, !empty($customer_data['newsletter']));
|
||||
|
||||
$this->api->customersCreate($customer);
|
||||
}
|
||||
|
||||
public function editCustomer($customer_data, $address) {
|
||||
$customer = $this->prepareCustomer($customer_data, $address);
|
||||
|
||||
$this->api->customersEdit($customer);
|
||||
}
|
||||
|
||||
public function editCustomerNewsLetter($customer_data) {
|
||||
$this->api->customersEdit(
|
||||
[
|
||||
'externalId' => $customer_data['customer_id'],
|
||||
'subscribed' => !empty($customer_data['newsletter']),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function uploadCustomers($customers) {
|
||||
$this->api->customersUpload($customers);
|
||||
}
|
||||
|
||||
public function prepareCustomer($customer_data, $address, $isSubscribed = null) {
|
||||
return $this->customer_converter
|
||||
->initCustomerData($customer_data, $address, $isSubscribed)
|
||||
->setCustomerData()
|
||||
->setAddress()
|
||||
->setCustomFields()
|
||||
->getCustomer();
|
||||
}
|
||||
|
||||
public function getCustomerForOrder($order_data) {
|
||||
$customer = $this->searchCustomer($order_data['telephone'], $order_data['email']);
|
||||
if ($customer) {
|
||||
return $customer;
|
||||
}
|
||||
|
||||
$new_customer = array(
|
||||
'firstName' => $order_data['firstname'],
|
||||
'lastName' => $order_data['lastname'],
|
||||
'email' => $order_data['email'],
|
||||
'createdAt' => $order_data['date_added'],
|
||||
'address' => array(
|
||||
'countryIso' => $order_data['payment_iso_code_2'],
|
||||
'index' => $order_data['payment_postcode'],
|
||||
'city' => $order_data['payment_city'],
|
||||
'region' => $order_data['payment_zone'],
|
||||
'text' => $order_data['payment_address_1'] . ' ' . $order_data['payment_address_2']
|
||||
)
|
||||
);
|
||||
|
||||
if (!empty($order_data['telephone'])) {
|
||||
$new_customer['phones'] = array(
|
||||
array(
|
||||
'number' => $order_data['telephone']
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$res = $this->api->customersCreate($new_customer);
|
||||
|
||||
$customer = array();
|
||||
if ($res && $res->isSuccessful() && isset($res['id'])) {
|
||||
$customer['id'] = $res['id'];
|
||||
}
|
||||
|
||||
return $customer;
|
||||
}
|
||||
|
||||
private function searchCustomer($phone, $email) {
|
||||
$customer = array();
|
||||
|
||||
$response = $this->api->customersList(
|
||||
array(
|
||||
'name' => $phone,
|
||||
'email' => $email
|
||||
),
|
||||
1,
|
||||
100
|
||||
);
|
||||
|
||||
if ($response && $response->isSuccessful() && isset($response['customers'])) {
|
||||
$customers = $response['customers'];
|
||||
|
||||
if ($customers) {
|
||||
$customer = end($customers);
|
||||
}
|
||||
}
|
||||
|
||||
return $customer;
|
||||
}
|
||||
}
|
184
src/upload/system/library/retailcrm/lib/service/OrderManager.php
Normal file
184
src/upload/system/library/retailcrm/lib/service/OrderManager.php
Normal file
|
@ -0,0 +1,184 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
class OrderManager {
|
||||
protected $api;
|
||||
protected $customer_manager;
|
||||
protected $order_converter;
|
||||
protected $corporate_customer_service;
|
||||
protected $settings_manager;
|
||||
|
||||
/**
|
||||
* OrderManager constructor.
|
||||
* @param \RetailcrmProxy $proxy
|
||||
* @param CustomerManager $customer_manager
|
||||
* @param RetailcrmOrderConverter $order_converter
|
||||
* @param CorporateCustomer $corporate_customer_service
|
||||
* @param SettingsManager $settings_manager
|
||||
*/
|
||||
public function __construct(
|
||||
\RetailcrmProxy $proxy,
|
||||
CustomerManager $customer_manager,
|
||||
RetailcrmOrderConverter $order_converter,
|
||||
CorporateCustomer $corporate_customer_service,
|
||||
SettingsManager $settings_manager
|
||||
) {
|
||||
$this->api = $proxy;
|
||||
$this->customer_manager = $customer_manager;
|
||||
$this->order_converter = $order_converter;
|
||||
$this->corporate_customer_service = $corporate_customer_service;
|
||||
$this->settings_manager = $settings_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $order_data
|
||||
* @param array $order_products
|
||||
* @param array $order_totals
|
||||
*/
|
||||
public function createOrder($order_data, $order_products, $order_totals) {
|
||||
$order = $this->prepareOrder($order_data, $order_products, $order_totals);
|
||||
|
||||
if (!isset($order['customer'])
|
||||
|| (isset($order['customer']['externalId'])
|
||||
&& !$this->checkExistCustomer($order['customer']['externalId']))
|
||||
) {
|
||||
$customer = $this->customer_manager->getCustomerForOrder($order_data);
|
||||
if (!empty($customer)) {
|
||||
$order['customer'] = $customer;
|
||||
}
|
||||
}
|
||||
|
||||
$order['contragent']['contragentType'] = 'individual';
|
||||
$this->handleCorporate($order, $order_data);
|
||||
|
||||
return $this->api->ordersCreate($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $order_data
|
||||
* @param array $order_products
|
||||
* @param array $order_totals
|
||||
*/
|
||||
public function editOrder($order_data, $order_products, $order_totals) {
|
||||
$order = $this->prepareOrder($order_data, $order_products, $order_totals);
|
||||
|
||||
if (!isset($order['customer'])) {
|
||||
$customer = $this->customer_manager->getCustomerForOrder($order_data);
|
||||
if (!empty($customer)) {
|
||||
$order['customer'] = array(
|
||||
'id' => $customer['id']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$order['contragent']['contragentType'] = 'individual';
|
||||
$this->handleCorporate($order, $order_data);
|
||||
|
||||
$payments = $order['payments'];
|
||||
unset($order['payments']);
|
||||
|
||||
$order_payment = $payments[0];
|
||||
$order = \retailcrm\Utils::filterRecursive($order);
|
||||
$response = $this->api->ordersEdit($order);
|
||||
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$this->updatePayment($order_payment, $order['externalId']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $orders
|
||||
*/
|
||||
public function uploadOrders($orders) {
|
||||
$this->api->ordersUpload($orders);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $order_data array of order fields
|
||||
* @param array $order_products array of order products
|
||||
* @param array $order_totals array of order totals
|
||||
* @return array
|
||||
*/
|
||||
public function prepareOrder($order_data, $order_products, $order_totals) {
|
||||
return $this->order_converter->initOrderData($order_data, $order_products, $order_totals)
|
||||
->setOrderData()
|
||||
->setDelivery()
|
||||
->setItems()
|
||||
->setPayment(false)
|
||||
->setDiscount()
|
||||
->setCustomFields()
|
||||
->getOrder();
|
||||
}
|
||||
|
||||
private function handleCorporate(&$order, $order_data) {
|
||||
if ($this->isCorporateOrder($order_data)
|
||||
&& !empty($order['customer'])
|
||||
&& $this->settings_manager->getSetting('corporate_enabled') == 1
|
||||
) {
|
||||
$order_data['payment_company'] = htmlspecialchars_decode($order_data['payment_company']);
|
||||
$corp_customer_id = $this->corporate_customer_service->createCorporateCustomer($order_data, $order['customer']);
|
||||
|
||||
if ($corp_customer_id) {
|
||||
$order = $this->order_converter->setCorporateCustomer($order, $corp_customer_id);
|
||||
$companiesResponse = $this->api->customersCorporateCompanies($corp_customer_id, array(), 1, 100, 'id');
|
||||
if ($companiesResponse && $companiesResponse->isSuccessful() && !empty($companiesResponse['companies'])) {
|
||||
foreach ($companiesResponse['companies'] as $company) {
|
||||
if ($company['name'] === $order_data['payment_company']) {
|
||||
$order['company'] = array(
|
||||
'id' => $company['id']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $order_data array of order fields
|
||||
* @return bool
|
||||
*/
|
||||
private function isCorporateOrder($order_data) {
|
||||
return !empty($order_data['payment_company']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $order_payment
|
||||
* @param int $orderId
|
||||
*/
|
||||
private function updatePayment($order_payment, $orderId) {
|
||||
$response_order = $this->api->ordersGet($orderId);
|
||||
|
||||
if ($response_order && $response_order->isSuccessful()) {
|
||||
$order_info = $response_order['order'];
|
||||
}
|
||||
|
||||
foreach ($order_info['payments'] as $payment_data) {
|
||||
if (isset($payment_data['externalId'])) {
|
||||
$payment = $payment_data;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($payment) && $payment['type'] != $order_payment['type']) {
|
||||
$response = $this->api->ordersPaymentDelete($payment['id']);
|
||||
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$this->api->ordersPaymentCreate($order_payment);
|
||||
}
|
||||
} elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
|
||||
$this->api->ordersPaymentEdit($order_payment);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $customerExternalId Customer's external id
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function checkExistCustomer($customerExternalId) {
|
||||
$result = $this->api->customersGet($customerExternalId);
|
||||
|
||||
return $result && $result->isSuccessful() && $result->offsetExists('customer');
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
class RetailcrmCustomerConverter {
|
||||
protected $data;
|
||||
protected $customer_data = [];
|
||||
protected $address = [];
|
||||
protected $isSubscribed;
|
||||
protected $settingsManager;
|
||||
|
||||
public function __construct(
|
||||
SettingsManager $settingsManager
|
||||
) {
|
||||
$this->settingsManager = $settingsManager;
|
||||
}
|
||||
|
||||
public function getCustomer() {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function initCustomerData($customer_data, $address, $isSubscribed) {
|
||||
$this->data = [];
|
||||
$this->customer_data = $customer_data;
|
||||
$this->address = $address;
|
||||
$this->isSubscribed = $isSubscribed;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCustomerData() {
|
||||
$this->data['externalId'] = $this->customer_data['customer_id'];
|
||||
$this->data['firstName'] = $this->customer_data['firstname'];
|
||||
$this->data['lastName'] = $this->customer_data['lastname'];
|
||||
$this->data['email'] = $this->customer_data['email'];
|
||||
$this->data['createdAt'] = $this->customer_data['date_added'];
|
||||
|
||||
if ($this->isSubscribed !== null) {
|
||||
$this->data['subscribed'] = $this->isSubscribed;
|
||||
}
|
||||
|
||||
if (!empty($this->customer_data['telephone'])) {
|
||||
$this->data['phones'] = [['number' => $this->customer_data['telephone']]];
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setAddress() {
|
||||
if (!empty($this->address)) {
|
||||
$this->data['address'] = [
|
||||
'index' => $this->address['postcode'],
|
||||
'countryIso' => $this->address['iso_code_2'],
|
||||
'region' => $this->address['zone'],
|
||||
'city' => $this->address['city'],
|
||||
'text' => $this->address['address_1'] . ' ' . $this->address['address_2']
|
||||
];
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCustomFields() {
|
||||
$settings = $this->settingsManager->getSetting('custom_field');
|
||||
if (!empty($settings) && $this->customer_data['custom_field']) {
|
||||
$customFields = json_decode($this->customer_data['custom_field']);
|
||||
|
||||
foreach ($customFields as $key => $value) {
|
||||
if (isset($settings['c_' . $key])) {
|
||||
$customFieldsToCrm[$settings['c_' . $key]] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($customFieldsToCrm)) {
|
||||
$this->data['customFields'] = $customFieldsToCrm;
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,331 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
use retailcrm\repository\CustomerRepository;
|
||||
use retailcrm\repository\ProductsRepository;
|
||||
|
||||
class RetailcrmOrderConverter {
|
||||
protected $data;
|
||||
protected $order_data = array();
|
||||
protected $order_products = array();
|
||||
protected $order_totals = array();
|
||||
|
||||
protected $settingsManager;
|
||||
protected $customerRepository;
|
||||
protected $productsRepository;
|
||||
|
||||
public function __construct(
|
||||
SettingsManager $settingsManager,
|
||||
CustomerRepository $customerRepository,
|
||||
ProductsRepository $productsRepository
|
||||
) {
|
||||
$this->settingsManager = $settingsManager;
|
||||
$this->customerRepository = $customerRepository;
|
||||
$this->productsRepository = $productsRepository;
|
||||
}
|
||||
|
||||
public function initOrderData($order_data, $order_products, $order_totals) {
|
||||
$this->data = array();
|
||||
$this->order_data = $order_data;
|
||||
$this->order_products = $order_products;
|
||||
$this->order_totals = $order_totals;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getOrder() {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function setOrderData() {
|
||||
if (!empty($this->order_data['shipping_iso_code_2'])) {
|
||||
$this->data['countryIso'] = $this->order_data['shipping_iso_code_2'];
|
||||
}
|
||||
|
||||
if ($this->settingsManager->getSetting('order_number') == 1) {
|
||||
$this->data['number'] = $this->order_data['order_id'];
|
||||
}
|
||||
|
||||
if ($this->settingsManager->getSetting('summ_around') == 1) {
|
||||
$this->data['applyRound'] = true;
|
||||
}
|
||||
|
||||
$this->data['externalId'] = $this->order_data['order_id'];
|
||||
$this->data['firstName'] = $this->order_data['shipping_firstname'];
|
||||
$this->data['lastName'] = $this->order_data['shipping_lastname'];
|
||||
$this->data['phone'] = $this->order_data['telephone'];
|
||||
$this->data['customerComment'] = $this->order_data['comment'];
|
||||
|
||||
if (!empty($this->order_data['customer_id'])) {
|
||||
$this->data['customer']['externalId'] = $this->order_data['customer_id'];
|
||||
}
|
||||
|
||||
if (!empty($this->order_data['email'])) {
|
||||
$this->data['email'] = $this->order_data['email'];
|
||||
}
|
||||
|
||||
$this->data['createdAt'] = $this->order_data['date_added'];
|
||||
|
||||
if (!empty($this->order_data['order_status_id'])) {
|
||||
$this->data['status'] = $this->settingsManager->getStatusSettings()[$this->order_data['order_status_id']];
|
||||
} elseif (isset($this->order_data['order_status_id']) && $this->order_data['order_status_id'] == 0) {
|
||||
$this->data['status'] = $this->settingsManager->getSetting('missing_status');
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setDiscount() {
|
||||
$discount = 0;
|
||||
$totalCoupon = $this->getTotal('coupon');
|
||||
$totalReward = $this->getTotal('reward');
|
||||
$totalVoucher = $this->getTotal('voucher');
|
||||
$retailcrmDiscount = $this->getTotal(\retailcrm\Retailcrm::RETAILCRM_DISCOUNT);
|
||||
|
||||
if (!empty($totalCoupon)) {
|
||||
$discount += abs($totalCoupon);
|
||||
}
|
||||
|
||||
if (!empty($totalReward)) {
|
||||
$discount += abs($totalReward);
|
||||
}
|
||||
|
||||
if (!empty($totalVoucher)) {
|
||||
$discount += abs($totalVoucher);
|
||||
}
|
||||
|
||||
if (!empty($retailcrmDiscount)) {
|
||||
$discount += abs($retailcrmDiscount);
|
||||
}
|
||||
|
||||
$this->data['discountManualAmount'] = $discount;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setPayment($create = true) {
|
||||
$settings = $this->settingsManager->getPaymentSettings();
|
||||
if (!empty($this->order_data['payment_code']) && isset($settings[$this->order_data['payment_code']])) {
|
||||
$payment_type = $settings[$this->order_data['payment_code']];
|
||||
}
|
||||
|
||||
$payment = array(
|
||||
'externalId' => uniqid($this->order_data['order_id'] . "-"),
|
||||
'amount' => $this->getTotal('total')
|
||||
);
|
||||
|
||||
if ($this->settingsManager->getSetting('sum_payment') &&
|
||||
$this->settingsManager->getSetting('sum_payment') == 1) {
|
||||
unset($payment['amount']);
|
||||
}
|
||||
|
||||
if (!empty($payment_type)) {
|
||||
$payment['type'] = $payment_type;
|
||||
}
|
||||
|
||||
if (!$create) {
|
||||
$payment['order'] = array(
|
||||
'externalId' => $this->order_data['order_id']
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($payment['type'])) {
|
||||
$this->data['payments'][] = $payment;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setDelivery() {
|
||||
$settings = $this->settingsManager->getDeliverySettings();
|
||||
|
||||
$this->data['delivery']['address'] = array(
|
||||
'index' => $this->order_data['shipping_postcode'],
|
||||
'city' => $this->order_data['shipping_city'],
|
||||
'countryIso' => $this->order_data['shipping_iso_code_2'],
|
||||
'region' => $this->order_data['shipping_zone'],
|
||||
'text' => implode(', ', array(
|
||||
$this->order_data['shipping_postcode'],
|
||||
$this->order_data['shipping_country'] ? $this->order_data['shipping_country'] : '',
|
||||
$this->order_data['shipping_city'],
|
||||
$this->order_data['shipping_address_1'],
|
||||
$this->order_data['shipping_address_2']
|
||||
))
|
||||
);
|
||||
|
||||
if (!empty($this->order_data['shipping_code'])) {
|
||||
$shippingCode = explode('.', $this->order_data['shipping_code']);
|
||||
$shippingModule = $shippingCode[0];
|
||||
|
||||
if (isset($settings[$this->order_data['shipping_code']])) {
|
||||
$delivery_code = $settings[$this->order_data['shipping_code']];
|
||||
} elseif (isset($settings[$shippingModule])) {
|
||||
$delivery_code = $settings[$shippingModule];
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($delivery_code) && isset($shippingModule)) {
|
||||
if (!empty($settings)) {
|
||||
$deliveries = array_keys($settings);
|
||||
$shipping_code = '';
|
||||
|
||||
array_walk($deliveries, function ($item, $key) use ($shippingModule, &$shipping_code) {
|
||||
if (strripos($item, $shippingModule) !== false) {
|
||||
$shipping_code = $item;
|
||||
}
|
||||
});
|
||||
|
||||
$delivery_code = $settings[$shipping_code];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($delivery_code)) {
|
||||
$this->data['delivery']['code'] = $delivery_code;
|
||||
}
|
||||
|
||||
$totalShipping = $this->getTotal('shipping');
|
||||
|
||||
if (!empty($totalShipping)) {
|
||||
$this->data['delivery']['cost'] = $totalShipping;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setItems() {
|
||||
$offerOptions = array('select', 'radio');
|
||||
|
||||
foreach ($this->order_products as $product) {
|
||||
$offerId = '';
|
||||
|
||||
if (!empty($product['option'])) {
|
||||
$options = array();
|
||||
|
||||
foreach ($product['option'] as $option) {
|
||||
if ($option['type'] == 'checkbox') {
|
||||
$properties[] = array(
|
||||
'code' => $option['product_option_value_id'],
|
||||
'name' => $option['name'],
|
||||
'value' => $option['value']
|
||||
);
|
||||
}
|
||||
|
||||
if (!in_array($option['type'], $offerOptions)) continue;
|
||||
|
||||
$productOptions = $this->productsRepository->getProductOptions($product['product_id']);
|
||||
|
||||
foreach ($productOptions as $productOption) {
|
||||
if ($productOption['product_option_id'] = $option['product_option_id']) {
|
||||
foreach ($productOption['product_option_value'] as $productOptionValue) {
|
||||
if ($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
|
||||
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($options);
|
||||
|
||||
$offerId = array();
|
||||
foreach ($options as $optionKey => $optionValue) {
|
||||
$offerId[] = $optionKey . '-' . $optionValue;
|
||||
}
|
||||
$offerId = implode('_', $offerId);
|
||||
}
|
||||
|
||||
$item = array(
|
||||
'offer' => array(
|
||||
'externalId' => !empty($offerId) ? $product['product_id'] . '#' . $offerId : $product['product_id']
|
||||
),
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity']
|
||||
);
|
||||
|
||||
$date = date('Y-m-d');
|
||||
$always = '0000-00-00';
|
||||
$specials = $this->productsRepository->getProductSpecials($product['product_id']);
|
||||
|
||||
if (!empty($specials)) {
|
||||
$customer = $this->customerRepository->getCustomer($this->order_data['customer_id']);
|
||||
|
||||
foreach ($specials as $special) {
|
||||
if (($special['date_start'] == $always && $special['date_end'] == $always)
|
||||
|| ($special['date_start'] <= $date && $special['date_end'] >= $date)
|
||||
) {
|
||||
if ((isset($priority) && $priority > $special['priority'])
|
||||
|| !isset($priority)) {
|
||||
if (empty($customer['customer_group_id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$specialSetting = $this->settingsManager->getSetting('special_' . $customer['customer_group_id']);
|
||||
if ($special['customer_group_id'] == $customer['customer_group_id'] && !empty($specialSetting)) {
|
||||
$item['priceType']['code'] = $specialSetting;
|
||||
$priority = $special['priority'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($properties)) $item['properties'] = $properties;
|
||||
|
||||
$this->data['items'][] = $item;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCorporateCustomer($order, $corp_customer_id) {
|
||||
$order['contragent']['contragentType'] = 'legal-entity';
|
||||
$order['contact'] = $order['customer'];
|
||||
unset($order['customer']);
|
||||
$order['customer'] = array(
|
||||
'id' => $corp_customer_id
|
||||
);
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
public function setCustomFields() {
|
||||
$settings = $this->settingsManager->getSetting('custom_field');
|
||||
if (!empty($settings) && $this->order_data['custom_field']) {
|
||||
$customFields = $this->order_data['custom_field'];
|
||||
|
||||
foreach ($customFields as $key => $value) {
|
||||
if (isset($settings['o_' . $key])) {
|
||||
$customFieldsToCrm[$settings['o_' . $key]] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($customFieldsToCrm)) {
|
||||
$this->data['customFields'] = $customFieldsToCrm;
|
||||
}
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function getTotal($total) {
|
||||
$totals = $this->getTotals();
|
||||
|
||||
if (!empty($totals[$total])) {
|
||||
return $totals[$total];
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private function getTotals() {
|
||||
$totals = array();
|
||||
|
||||
foreach ($this->order_totals as $total) {
|
||||
$totals[$total['code']] = $total['value'];
|
||||
}
|
||||
|
||||
return $totals;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm\service;
|
||||
|
||||
class SettingsManager extends \retailcrm\Base {
|
||||
private $settings;
|
||||
|
||||
public function getSettings() {
|
||||
if (!$this->settings) {
|
||||
$this->settings = $this->model_setting_setting->getSetting($this->retailcrm->getModuleTitle());
|
||||
}
|
||||
|
||||
return $this->settings;
|
||||
}
|
||||
|
||||
public function getSettingByKey($key) {
|
||||
return $this->model_setting_setting->getSetting($key);
|
||||
}
|
||||
|
||||
public function getSetting($key) {
|
||||
$settings = $this->getSettings();
|
||||
|
||||
if (!empty($settings[$this->retailcrm->getModuleTitle() . '_' . $key])) {
|
||||
return $settings[$this->retailcrm->getModuleTitle() . '_' . $key];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getPaymentSettings() {
|
||||
return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_payment'];
|
||||
}
|
||||
|
||||
public function getDeliverySettings() {
|
||||
return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_delivery'];
|
||||
}
|
||||
|
||||
public function getStatusSettings() {
|
||||
return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_status'];
|
||||
}
|
||||
}
|
|
@ -14,6 +14,7 @@
|
|||
<field id="cumulative_discount" group="customer">cumulativeDiscount</field>
|
||||
<field id="personal_discount" group="customer">personalDiscount</field>
|
||||
<field id="discount_card_number" group="customer">discountCardNumber</field>
|
||||
<field id="email_marketing_unsubscribed_at" group="customer">emailMarketingUnsubscribedAt</field>
|
||||
|
||||
<field id="address.index" group="customerAddress">index</field>
|
||||
<field id="address.country" group="customerAddress">country</field>
|
||||
|
|
|
@ -1,388 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Retailcrm;
|
||||
|
||||
class Order extends Base
|
||||
{
|
||||
protected $registry;
|
||||
protected $data = array(
|
||||
'number' => 0,
|
||||
'createdAt' => null,
|
||||
'countryIso' => null,
|
||||
'externalId' => 0,
|
||||
'customer' => array(),
|
||||
'status' => null,
|
||||
'firstName' => null,
|
||||
'lastName' => null,
|
||||
'patronymic' => null,
|
||||
'email' => null,
|
||||
'phone' => null,
|
||||
'discountManualAmount' => 0,
|
||||
'customerComment' => null,
|
||||
'items' => array(),
|
||||
'delivery' => array(),
|
||||
'customFields' => array(),
|
||||
'payments' => array()
|
||||
);
|
||||
|
||||
public function prepare($order) {
|
||||
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom/order.php')) {
|
||||
$custom = new \Retailcrm\Custom\Order($this->registry);
|
||||
$this->data = $custom->prepare($order);
|
||||
} else {
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('extension/retailcrm/products');
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
|
||||
$delivery_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_delivery'])
|
||||
? $settings[\Retailcrm\Retailcrm::MODULE . '_delivery']
|
||||
: array();
|
||||
$payments_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_payment'])
|
||||
? $settings[\Retailcrm\Retailcrm::MODULE . '_payment']
|
||||
: array();
|
||||
$status_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_status'])
|
||||
? $settings[\Retailcrm\Retailcrm::MODULE . '_status']
|
||||
: array();
|
||||
|
||||
$totals = $this->explodeTotals($order['totals']);
|
||||
$coupon_total = 0;
|
||||
$delivery_cost = 0;
|
||||
|
||||
if (isset($totals['shipping'])) {
|
||||
$delivery_cost = $totals['shipping'];
|
||||
}
|
||||
|
||||
if (isset($totals['coupon'])) {
|
||||
$coupon_total += abs($totals['coupon']);
|
||||
}
|
||||
|
||||
if (isset($totals['reward'])) {
|
||||
$coupon_total += abs($totals['reward']);
|
||||
}
|
||||
|
||||
if (isset($order['order_status_id']) && $order['order_status_id'] > 0) {
|
||||
$status = $status_settings[$order['order_status_id']];
|
||||
} elseif (!isset($order['order_status_id'])) {
|
||||
$status = $settings[\Retailcrm\Retailcrm::MODULE . '_missing_status'];
|
||||
}
|
||||
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_order_number'])
|
||||
&& $settings[\Retailcrm\Retailcrm::MODULE . '_order_number'] == 1
|
||||
) {
|
||||
$this->setField('number', $order['order_id']);
|
||||
}
|
||||
|
||||
$fields = array(
|
||||
'firstName' => $order['firstname'],
|
||||
'lastName' => $order['lastname'],
|
||||
'email' => $order['email'],
|
||||
'phone' => $order['telephone'],
|
||||
'customerComment' => $order['comment'],
|
||||
'createdAt' => isset($order['date_added']) ? $order['date_added'] : date('Y-m-d H:i:s'),
|
||||
'discountManualAmount' => $coupon_total,
|
||||
'status' => $status
|
||||
);
|
||||
|
||||
if (isset($order['order_id']) && !$this->data['externalId']) {
|
||||
$fields['externalId'] = $order['order_id'];
|
||||
}
|
||||
|
||||
$this->setFields($fields);
|
||||
|
||||
if (isset($order['shipping_code'])) {
|
||||
$delivery_code = $this->getDeliveryMethod($order['shipping_code'], $delivery_settings);
|
||||
}
|
||||
|
||||
$delivery = array(
|
||||
'address' => array(
|
||||
'index' => isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '',
|
||||
'city' => isset($order['shipping_city']) ? $order['shipping_city'] : '',
|
||||
'region' => isset($order['shipping_zone']) ? $order['shipping_zone'] : '',
|
||||
'text' => implode(', ', array(
|
||||
isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '',
|
||||
isset($order['shipping_country']) ? $order['shipping_country'] : '',
|
||||
isset($order['shipping_city']) ? $order['shipping_city'] : '',
|
||||
isset($order['shipping_address_1']) ? $order['shipping_address_1'] : '',
|
||||
isset($order['shipping_address_2']) ? $order['shipping_address_2'] : ''
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
if (isset($delivery_code)) {
|
||||
$delivery['code'] = $delivery_code;
|
||||
}
|
||||
|
||||
if ($delivery_cost) {
|
||||
$delivery['cost'] = $delivery_cost;
|
||||
}
|
||||
|
||||
$this->setDataArray($delivery, 'delivery');
|
||||
$this->setOrderProducts($order['products']);
|
||||
$payments = array();
|
||||
|
||||
if (isset($payments_settings[$order['payment_code']])) {
|
||||
$payment = array(
|
||||
'order' => array(
|
||||
'externalId' => $order['order_id']
|
||||
),
|
||||
'externalId' => $order['order_id'],
|
||||
'type' => $payments_settings[$order['payment_code']],
|
||||
'amount' => $order['total']
|
||||
);
|
||||
|
||||
$payments[] = $payment;
|
||||
}
|
||||
|
||||
$this->setDataArray($payments, 'payments');
|
||||
|
||||
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $order['custom_field']) {
|
||||
$custom_fields = $this->prepareCustomFields($order['custom_field'], $settings, 'o_');
|
||||
|
||||
if ($custom_fields) {
|
||||
$this->setDataArray($custom_fields, 'customFields');
|
||||
}
|
||||
}
|
||||
|
||||
if ($order['customer_id']) {
|
||||
$this->setDataArray(
|
||||
array(
|
||||
'externalId' => $order['customer_id']
|
||||
),
|
||||
'customer'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
parent::prepare($order);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return bool|mixed
|
||||
*/
|
||||
public function create($retailcrm_api_client) {
|
||||
if ($retailcrm_api_client === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$this->data['customer']) {
|
||||
$customer = $this->searchCustomer($this->data['phone'], $this->data['email'], $retailcrm_api_client);
|
||||
|
||||
if ($customer) {
|
||||
$this->setDataArray(
|
||||
array(
|
||||
'id' => $customer['id']
|
||||
),
|
||||
'customer'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$response = $retailcrm_api_client->ordersCreate($this->data);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return bool|mixed
|
||||
*/
|
||||
public function edit($retailcrm_api_client) {
|
||||
if ($retailcrm_api_client === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$order_payment = reset($this->data['payments']);
|
||||
unset($this->data['payments']);
|
||||
|
||||
$response = $retailcrm_api_client->ordersEdit($this->data);
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$this->updatePayment($order_payment, $this->data['externalId'], $retailcrm_api_client);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update payment in CRM
|
||||
*
|
||||
* @param array $order_payment
|
||||
* @param int $order_id
|
||||
* @param \RetailcrmProxy $retailcrm_api_client
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
private function updatePayment($order_payment, $order_id, $retailcrm_api_client) {
|
||||
$response_order = $retailcrm_api_client->ordersGet($order_id);
|
||||
|
||||
if (!$response_order->isSuccessful()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$order_info = $response_order['order'];
|
||||
|
||||
foreach ($order_info['payments'] as $payment_data) {
|
||||
if (isset($payment_data['externalId']) && $payment_data['externalId'] == $order_id) {
|
||||
$payment = $payment_data;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($payment) && $payment['type'] != $order_payment['type']) {
|
||||
$response = $retailcrm_api_client->ordersPaymentDelete($payment['id']);
|
||||
if ($response->isSuccessful()) {
|
||||
$retailcrm_api_client->ordersPaymentCreate($order_payment);
|
||||
}
|
||||
} elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
|
||||
$retailcrm_api_client->ordersPaymentEdit($order_payment);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $phone
|
||||
* @param $email
|
||||
* @param $retailcrm_api_client
|
||||
*
|
||||
* @return array|mixed
|
||||
*/
|
||||
private function searchCustomer($phone, $email, $retailcrm_api_client) {
|
||||
$customer = array();
|
||||
$response = $retailcrm_api_client->customersList(
|
||||
array(
|
||||
'name' => $phone,
|
||||
'email' => $email
|
||||
),
|
||||
1,
|
||||
100
|
||||
);
|
||||
|
||||
if ($response->isSuccessful() && isset($response['customers'])) {
|
||||
$customers = $response['customers'];
|
||||
if ($customers) {
|
||||
$customer = end($customers);
|
||||
}
|
||||
}
|
||||
return $customer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $shipping_code
|
||||
* @param array $deliveries
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
private function getDeliveryMethod($shipping_code, $deliveries) {
|
||||
if (!empty($shipping_code)) {
|
||||
$shipping_code_array = explode('.', $shipping_code);
|
||||
$shipping_module = $shipping_code_array[0];
|
||||
|
||||
if (isset($deliveries[$shipping_code])) {
|
||||
$delivery_code = $deliveries[$shipping_code];
|
||||
} elseif (isset($deliveries[$shipping_module])) {
|
||||
$delivery_code = $deliveries[$shipping_module];
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($delivery_code) && isset($shipping_module) && $deliveries) {
|
||||
$delivery = '';
|
||||
|
||||
array_walk($deliveries, function ($item, $key) use ($shipping_module, &$delivery) {
|
||||
if (strripos($item, $shipping_module) !== false) {
|
||||
$delivery = $item;
|
||||
}
|
||||
});
|
||||
|
||||
$delivery_code = $deliveries[$delivery];
|
||||
}
|
||||
|
||||
return isset($delivery_code) ? $delivery_code : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $products
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function setOrderProducts($products) {
|
||||
$offer_options = array('select', 'radio');
|
||||
$items = array();
|
||||
|
||||
foreach ($products as $product) {
|
||||
if (!empty($product['option'])) {
|
||||
$offer_id = '';
|
||||
$options = array();
|
||||
$properties = array();
|
||||
|
||||
foreach ($product['option'] as $option) {
|
||||
if ($option['type'] == 'checkbox') {
|
||||
$properties[] = array(
|
||||
'code' => $option['product_option_value_id'],
|
||||
'name' => $option['name'],
|
||||
'value' => $option['value']
|
||||
);
|
||||
}
|
||||
|
||||
if (!in_array($option['type'], $offer_options)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$productOptions = $this->model_extension_retailcrm_products->getProductOptions($product['product_id']);
|
||||
|
||||
foreach ($productOptions as $productOption) {
|
||||
if ($productOption['product_option_id'] == $option['product_option_id']) {
|
||||
foreach ($productOption['product_option_value'] as $productOptionValue) {
|
||||
if ($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
|
||||
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($options);
|
||||
|
||||
foreach ($options as $optionKey => $optionValue) {
|
||||
$offer_id .= $optionKey . '-' . $optionValue;
|
||||
}
|
||||
}
|
||||
|
||||
$item = array(
|
||||
'offer' => array(
|
||||
'externalId' => !empty($offer_id) ? $product['product_id'] . '#' . $offer_id : $product['product_id']
|
||||
),
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
|
||||
if (!empty($properties)) {
|
||||
$item['properties'] = $properties;
|
||||
}
|
||||
|
||||
$items[] = $item;
|
||||
}
|
||||
|
||||
$this->setDataArray($items, 'items');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $totals
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function explodeTotals($totals)
|
||||
{
|
||||
$resultTotals = array();
|
||||
|
||||
foreach ($totals as $total) {
|
||||
$resultTotals[$total['code']] = $total['value'];
|
||||
}
|
||||
|
||||
return $resultTotals;
|
||||
}
|
||||
}
|
|
@ -1,25 +1,57 @@
|
|||
<?php
|
||||
|
||||
namespace Retailcrm;
|
||||
namespace retailcrm;
|
||||
|
||||
require_once 'api/bootstrap.php';
|
||||
use retailcrm\repository\CustomerRepository;
|
||||
use retailcrm\service\CorporateCustomer;
|
||||
use retailcrm\service\CustomerManager;
|
||||
use retailcrm\service\OrderManager;
|
||||
use retailcrm\factory\OrderConverterFactory;
|
||||
use retailcrm\factory\CustomerConverterFactory;
|
||||
use retailcrm\service\SettingsManager;
|
||||
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
class Retailcrm {
|
||||
|
||||
const RETAILCRM_DISCOUNT = 'retailcrm_discount';
|
||||
const RETAILCRM_DISCOUNT_SORT_ORDER = 8;
|
||||
const VERSION_MODULE = '4.1.19';
|
||||
|
||||
protected $registry;
|
||||
|
||||
const MODULE = 'module_retailcrm';
|
||||
/** @var bool */
|
||||
public static $history_run = false;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
|
||||
|
||||
public function __construct(\Registry $registry) {
|
||||
$this->registry = $registry;
|
||||
|
||||
$modelsProvider = new ModelsProvider($this->registry);
|
||||
$modelsProvider->includeDependencies();
|
||||
}
|
||||
|
||||
public function __get($name) {
|
||||
return $this->registry->get($name);
|
||||
}
|
||||
|
||||
public function createObject($object) {
|
||||
return new $object($this->registry);
|
||||
public function getCustomerManager() {
|
||||
return new CustomerManager($this->getApiClient(), CustomerConverterFactory::create($this->registry));
|
||||
}
|
||||
|
||||
public function getOrderManager() {
|
||||
return new OrderManager(
|
||||
$this->getApiClient(),
|
||||
$this->getCustomerManager(),
|
||||
OrderConverterFactory::create($this->registry),
|
||||
$this->getCorporateCustomerService(),
|
||||
new SettingsManager($this->registry)
|
||||
);
|
||||
}
|
||||
|
||||
public function getCorporateCustomerService() {
|
||||
return new CorporateCustomer($this->getApiClient(), new CustomerRepository($this->registry));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -27,36 +59,31 @@ class Retailcrm {
|
|||
*
|
||||
* @param string $apiUrl (default = null)
|
||||
* @param string $apiKey (default = null)
|
||||
* @param string $apiVersion (default = null)
|
||||
*
|
||||
* @return mixed object | boolean
|
||||
*/
|
||||
public function getApiClient($apiUrl = null, $apiKey = null, $apiVersion = null)
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
public function getApiClient($apiUrl = null, $apiKey = null) {
|
||||
if (!$this->registry->has('RetailcrmProxy')) {
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
$setting = $this->model_setting_setting->getSetting(self::MODULE);
|
||||
if ($apiUrl === null && $apiKey === null) {
|
||||
$apiUrl = isset($setting[$this->getModuleTitle() . '_url'])
|
||||
? $setting[$this->getModuleTitle() . '_url'] : '';
|
||||
$apiKey = isset($setting[$this->getModuleTitle() . '_apikey'])
|
||||
? $setting[$this->getModuleTitle() . '_apikey'] : '';
|
||||
}
|
||||
|
||||
if ($apiUrl === null && $apiKey === null) {
|
||||
$apiUrl = isset($setting[self::MODULE . '_url'])
|
||||
? $setting[self::MODULE . '_url'] : '';
|
||||
$apiKey = isset($setting[self::MODULE . '_apikey'])
|
||||
? $setting[self::MODULE . '_apikey'] : '';
|
||||
$apiVersion = isset($setting[self::MODULE . '_apiversion'])
|
||||
? $setting[self::MODULE . '_apiversion'] : '';
|
||||
if (!$apiUrl || !$apiKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->registry->set(
|
||||
'RetailcrmProxy',
|
||||
new \RetailcrmProxy($apiUrl, $apiKey)
|
||||
);
|
||||
}
|
||||
|
||||
$debug = false;
|
||||
|
||||
if (isset($setting[self::MODULE . '_debug_mode']) && $setting[self::MODULE . '_debug_mode']) {
|
||||
$debug = true;
|
||||
}
|
||||
|
||||
if ($apiUrl && $apiKey) {
|
||||
return new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion, $debug);
|
||||
}
|
||||
|
||||
return false;
|
||||
return $this->registry->get('RetailcrmProxy');
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -66,22 +93,49 @@ class Retailcrm {
|
|||
*
|
||||
* @return \OpencartApiClient
|
||||
*/
|
||||
public function getOcApiClient($registry)
|
||||
{
|
||||
public function getOcApiClient($registry) {
|
||||
return new \OpencartApiClient($registry);
|
||||
}
|
||||
|
||||
public function getOffers($product)
|
||||
{
|
||||
$this->load->model('extension/retailcrm/products');
|
||||
// Формируем офферы отнсительно доступных опций
|
||||
$options = $this->model_extension_retailcrm_products->getProductOptions($product['product_id']);
|
||||
/**
|
||||
* Get module title for this version
|
||||
*
|
||||
* @return string $title
|
||||
*/
|
||||
public function getModuleTitle() {
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$title = 'retailcrm';
|
||||
} else {
|
||||
$title = 'module_retailcrm';
|
||||
}
|
||||
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token param name
|
||||
*
|
||||
* @return string $token
|
||||
*/
|
||||
public function getTokenTitle() {
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$token = 'token';
|
||||
} else {
|
||||
$token = 'user_token';
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
public function getOffers($product) {
|
||||
// Build offers by available options
|
||||
$options = $this->model_catalog_product->getProductOptions($product['product_id']);
|
||||
$offerOptions = array('select', 'radio');
|
||||
$requiredOptions = array();
|
||||
$notRequiredOptions = array();
|
||||
// Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет
|
||||
foreach ($options as $option) {
|
||||
if (in_array($option['type'], $offerOptions)) {
|
||||
// Handle & sort mandatory options
|
||||
foreach($options as $option) {
|
||||
if(in_array($option['type'], $offerOptions)) {
|
||||
if($option['required']) {
|
||||
$requiredOptions[] = $option;
|
||||
} else {
|
||||
|
@ -91,55 +145,56 @@ class Retailcrm {
|
|||
}
|
||||
|
||||
$offers = array();
|
||||
// Сначала совмещаем все обязательные опции
|
||||
foreach ($requiredOptions as $requiredOption) {
|
||||
// Если первая итерация
|
||||
if (empty($offers)) {
|
||||
foreach ($requiredOption['product_option_value'] as $optionValue) {
|
||||
|
||||
foreach($requiredOptions as $requiredOption) {
|
||||
if(empty($offers)) {
|
||||
foreach($requiredOption['product_option_value'] as $optionValue) {
|
||||
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
|
||||
'price' => (float)$optionValue['price'],
|
||||
'qty' => $optionValue['quantity']
|
||||
'price' => (float)$this->getOptionPrice($optionValue),
|
||||
'qty' => $optionValue['quantity'],
|
||||
'weight' => round($this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
foreach ($offers as $optionKey => $optionAttr) {
|
||||
foreach($offers as $optionKey => $optionAttr) {
|
||||
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
|
||||
foreach ($requiredOption['product_option_value'] as $optionValue) {
|
||||
foreach($requiredOption['product_option_value'] as $optionValue) {
|
||||
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
|
||||
'price' => $optionAttr['price'] + (float)$optionValue['price'],
|
||||
'price' => $optionAttr['price'] + (float)$this->getOptionPrice($optionValue),
|
||||
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
|
||||
$optionValue['quantity'] : $optionAttr['qty']
|
||||
$optionValue['quantity'] : $optionAttr['qty'],
|
||||
'weight' => round($optionAttr['weight'] + $this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть.
|
||||
foreach ($notRequiredOptions as $notRequiredOption) {
|
||||
// Если обязательных опцией не оказалось и первая итерация
|
||||
if (empty($offers)) {
|
||||
$offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию
|
||||
foreach ($notRequiredOption['product_option_value'] as $optionValue) {
|
||||
foreach($notRequiredOptions as $notRequiredOption) {
|
||||
if(empty($offers)) {
|
||||
$offers['0:0-0'] = 0; // Add empty option for mandatory data
|
||||
foreach($notRequiredOption['product_option_value'] as $optionValue) {
|
||||
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
|
||||
'price' => (float)$optionValue['price'],
|
||||
'qty' => $optionValue['quantity']
|
||||
'price' => (float)$this->getOptionPrice($optionValue),
|
||||
'qty' => $optionValue['quantity'],
|
||||
'weight' => round($this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
foreach ($offers as $optionKey => $optionAttr) {
|
||||
foreach ($notRequiredOption['product_option_value'] as $optionValue) {
|
||||
foreach($offers as $optionKey => $optionAttr) {
|
||||
foreach($notRequiredOption['product_option_value'] as $optionValue) {
|
||||
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
|
||||
'price' => $optionAttr['price'] + (float)$optionValue['price'],
|
||||
'price' => $optionAttr['price'] + (float)$this->getOptionPrice($optionValue),
|
||||
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
|
||||
$optionValue['quantity'] : $optionAttr['qty']
|
||||
$optionValue['quantity'] : $optionAttr['qty'],
|
||||
'weight' => round($optionAttr['weight'] + $this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($offers)) {
|
||||
if(empty($offers)) {
|
||||
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
|
||||
}
|
||||
|
||||
|
@ -147,29 +202,54 @@ class Retailcrm {
|
|||
}
|
||||
|
||||
/**
|
||||
* Filter result array
|
||||
* @param array $option
|
||||
*
|
||||
* @param $haystack
|
||||
*
|
||||
* @return mixed
|
||||
* @return float
|
||||
*/
|
||||
public static function filterRecursive($haystack)
|
||||
{
|
||||
foreach ($haystack as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$haystack[$key] = self::filterRecursive($haystack[$key]);
|
||||
}
|
||||
if (is_null($haystack[$key])
|
||||
|| $haystack[$key] === ''
|
||||
|| (is_array($haystack[$key]) && count($haystack[$key]) == 0)
|
||||
) {
|
||||
unset($haystack[$key]);
|
||||
} elseif (!is_array($value)) {
|
||||
$haystack[$key] = trim($value);
|
||||
}
|
||||
private function getWeightOption($option) {
|
||||
if ($option['weight_prefix'] === '-') {
|
||||
return $option['weight'] * -1;
|
||||
}
|
||||
|
||||
return $haystack;
|
||||
return $option['weight'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $optionValue
|
||||
* @return float|int|mixed
|
||||
*/
|
||||
private function getOptionPrice($optionValue) {
|
||||
if ($optionValue['price_prefix'] === '-') {
|
||||
return $optionValue['price'] * -1;
|
||||
}
|
||||
|
||||
return $optionValue['price'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getCurrencyForIcml() {
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
if (isset($setting[$this->getModuleTitle() . '_currency'])
|
||||
&& $this->currency->has($setting[$this->getModuleTitle() . '_currency'])
|
||||
) {
|
||||
return $setting[$this->getModuleTitle() . '_currency'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function useServicesForIcml()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
return $setting['module_retailcrm_icml_service_enabled'] ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -178,10 +258,10 @@ class Retailcrm {
|
|||
public function getLenghtForIcml() {
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
$setting = $this->model_setting_setting->getSetting(self::MODULE);
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
if (isset($setting[self::MODULE . '_lenght'])) {
|
||||
return $setting[self::MODULE . '_lenght'];
|
||||
if (isset($setting[$this->getModuleTitle() . '_lenght'])) {
|
||||
return $setting[$this->getModuleTitle() . '_lenght'];
|
||||
}
|
||||
|
||||
return false;
|
||||
|
|
58
tests/3/TestCase.php
Normal file
58
tests/3/TestCase.php
Normal file
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
class TestCase extends \Tests\OpenCartTest {
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$this->setSetting(
|
||||
$this->retailcrm->getModuleTitle(),
|
||||
array(
|
||||
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
|
||||
$this->retailcrm->getModuleTitle() . '_order_number' => 1,
|
||||
$this->retailcrm->getModuleTitle() . '_status' => array(
|
||||
1 => 'new'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_delivery' => array(
|
||||
'flat.flat' => 'flat'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_payment' => array(
|
||||
'cod' => 'cod'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_special_1' => 'special1',
|
||||
$this->retailcrm->getModuleTitle() . '_special_2' => 'special2',
|
||||
$this->retailcrm->getModuleTitle() . '_special_3' => 'special3',
|
||||
$this->retailcrm->getModuleTitle() . '_collector' => array(
|
||||
'site_key' => 'RC-XXXXXXXXXX-X',
|
||||
'custom_form' => 1,
|
||||
'custom' => array(
|
||||
'name' => 'Name',
|
||||
'email' => 'Email',
|
||||
'phone' => 'Phone',
|
||||
),
|
||||
'form_capture' => 1,
|
||||
'period' => 1
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
protected function setSetting($code, $data, $store_id = 0) {
|
||||
$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (substr($key, 0, strlen($code)) == $code) {
|
||||
if (!is_array($value)) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
|
||||
} else {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function tearDown()
|
||||
{
|
||||
}
|
||||
}
|
261
tests/RoboFile.php
Normal file
261
tests/RoboFile.php
Normal file
|
@ -0,0 +1,261 @@
|
|||
<?php
|
||||
|
||||
require_once(__DIR__.'/../vendor/autoload.php');
|
||||
|
||||
class RoboFile extends \Robo\Tasks
|
||||
{
|
||||
use \Robo\Task\Development\loadTasks;
|
||||
use \Robo\Common\TaskIO;
|
||||
|
||||
const OPENCART_DOWNLOAD_URL = [
|
||||
'3.0.1.2' => 'https://github.com/opencart/opencart/releases/download/3.0.1.2/3.0.1.2-opencart.zip',
|
||||
'3.0.2.0' => 'https://github.com/opencart/opencart/releases/download/3.0.2.0/3.0.2.0-OpenCart.zip',
|
||||
'3.0.3.4' => 'https://github.com/opencart/opencart/releases/download/3.0.3.4/opencart-3.0.3.4-core-pre.zip'
|
||||
];
|
||||
|
||||
const OPENCART_ROOT_DIR = [
|
||||
'3.0.3.4' => 'opencart-3.0.3.4/upload'
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $opencart_config;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $server_port = 80;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $server_url = 'http://localhost';
|
||||
|
||||
private $root_dir = __DIR__ . '/../';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
if ($_ENV) {
|
||||
foreach ($_ENV as $option => $value) {
|
||||
if (substr($option, 0, 3) === 'OC_') {
|
||||
$option = strtolower(substr($option, 3));
|
||||
$this->opencart_config[$option] = $value;
|
||||
} elseif ($option === 'SERVER_PORT') {
|
||||
$this->server_port = (int) $value;
|
||||
} elseif ($option === 'SERVER_URL') {
|
||||
$this->server_url = $value;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$this->opencart_config = [
|
||||
'db_hostname' => getenv('OC_DB_HOSTNAME'),
|
||||
'db_username' => getenv('OC_DB_USERNAME'),
|
||||
'db_password' => getenv('OC_DB_PASSWORD'),
|
||||
'db_database' => getenv('OC_DB_DATABASE'),
|
||||
'db_driver' => getenv('OC_DB_DRIVER'),
|
||||
'username' => getenv('OC_USERNAME'),
|
||||
'password' => getenv('OC_PASSWORD'),
|
||||
'email' => getenv('OC_EMAIL')
|
||||
];
|
||||
}
|
||||
|
||||
$this->opencart_config['http_server'] = $this->server_url.':'.$this->server_port.'/';
|
||||
|
||||
$required = array('db_username', 'password', 'email');
|
||||
$missing = array();
|
||||
foreach ($required as $config) {
|
||||
if (empty($this->opencart_config[$config])) {
|
||||
$missing[] = 'OC_'.strtoupper($config);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($missing)) {
|
||||
$this->printTaskError("<error> Missing ".implode(', ', $missing));
|
||||
$this->printTaskError("<error> See .env.sample ");
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
public function opencartInstall()
|
||||
{
|
||||
$startUp = 'admin/controller/startup/test_startup.php';
|
||||
$startUpTo = 'admin/controller/startup/test_startup.php';
|
||||
$version = getenv('OPENCART');
|
||||
$ocZip = sprintf('/tmp/opencart-%s.zip', $version);
|
||||
|
||||
$this->taskDeleteDir($this->root_dir . 'www')->run();
|
||||
|
||||
file_put_contents($ocZip, file_get_contents($this->getOpencartDownloadUrl($version)));
|
||||
|
||||
$this->_exec(sprintf('unzip %s -d /tmp/opencart', $ocZip));
|
||||
$this->taskFileSystemStack()
|
||||
->mirror(
|
||||
$this->getOpencartRootDir($version),
|
||||
$this->root_dir . 'www'
|
||||
)
|
||||
->copy(
|
||||
$this->root_dir . 'vendor/beyondit/opencart-test-suite/src/upload/system/config/test-config.php',
|
||||
$this->root_dir . 'www/system/config/test-config.php'
|
||||
)
|
||||
->copy(
|
||||
$this->root_dir . 'vendor/beyondit/opencart-test-suite/src/upload/' . $startUp,
|
||||
$this->root_dir . 'www/' . $startUpTo
|
||||
)
|
||||
->chmod($this->root_dir . 'www', 0777, 0000, true)
|
||||
->run();
|
||||
|
||||
if (getenv('TEST_SUITE') === '3') {
|
||||
$this->taskFileSystemStack()->copy(
|
||||
$this->root_dir . 'vendor/beyondit/opencart-test-suite/src/upload/system/library/session/test.php',
|
||||
$this->root_dir . 'www/system/library/session/test.php'
|
||||
)->run();
|
||||
}
|
||||
|
||||
// Openbay was removed in 3.0.3.6
|
||||
// Unfortunately, those configs from test suite still require it.
|
||||
if (
|
||||
'3.0.3.4' === getenv('OPENCART') ||
|
||||
version_compare(getenv('OPENCART'), '3.0.3.6', '>=')
|
||||
) {
|
||||
$testConfigFile = $this->root_dir . 'www/system/config/test-config.php';
|
||||
$testStartupFile = $this->root_dir . 'www/' . $startUpTo;
|
||||
$testConfig = file_get_contents($testConfigFile);
|
||||
$testStartup = file_get_contents($testStartupFile);
|
||||
|
||||
$testConfig = str_ireplace("'openbay'", '', $testConfig);
|
||||
$testStartup = str_ireplace('$this->registry->set(\'openbay\', new Openbay($this->registry));', '', $testStartup);
|
||||
|
||||
file_put_contents($testConfigFile, $testConfig);
|
||||
file_put_contents($testStartupFile, $testStartup);
|
||||
}
|
||||
|
||||
// Create new database, drop if exists already
|
||||
try {
|
||||
$conn = new PDO("mysql:host=".$this->opencart_config['db_hostname'], $this->opencart_config['db_username'], $this->opencart_config['db_password']);
|
||||
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$conn->exec("DROP DATABASE IF EXISTS `" . $this->opencart_config['db_database'] . "`");
|
||||
$conn->exec("CREATE DATABASE `" . $this->opencart_config['db_database'] . "`");
|
||||
}
|
||||
catch(PDOException $e)
|
||||
{
|
||||
$this->printTaskError($e->getMessage());
|
||||
$this->printTaskError("<error> Could not connect to database...");
|
||||
}
|
||||
|
||||
if (version_compare(getenv('OPENCART'), '3.0.2.0', '<=')) {
|
||||
$install_code = file_get_contents($this->root_dir . 'www/install/cli_install.php');
|
||||
$storage = <<<EOF
|
||||
define('DIR_MODIFICATION', DIR_SYSTEM . 'modification/');
|
||||
define('DIR_STORAGE', DIR_SYSTEM . 'storage/');
|
||||
|
||||
EOF;
|
||||
|
||||
file_put_contents(
|
||||
$this->root_dir . 'www/install/cli_install.php',
|
||||
str_replace("define('DIR_MODIFICATION', DIR_SYSTEM . 'modification/');", $storage, $install_code)
|
||||
);
|
||||
}
|
||||
|
||||
$install = $this->taskExec('php')->arg($this->root_dir . 'www/install/cli_install.php')->arg('install');
|
||||
foreach ($this->opencart_config as $option => $value) {
|
||||
$install->option($option, $value);
|
||||
}
|
||||
$install->run();
|
||||
$this->taskDeleteDir($this->root_dir . 'www/install')->run();
|
||||
|
||||
$this->restoreSampleData($conn);
|
||||
|
||||
$conn = null;
|
||||
}
|
||||
|
||||
public function opencartRun()
|
||||
{
|
||||
$this->taskServer($this->server_port)
|
||||
->dir($this->root_dir . 'www')
|
||||
->run();
|
||||
}
|
||||
|
||||
public function projectDeploy()
|
||||
{
|
||||
$this->taskFileSystemStack()
|
||||
->mirror($this->root_dir . 'src/upload', $this->root_dir . 'www')
|
||||
// ->copy('src/install.xml','www/system/install.ocmod.xml') if exist modification for OCMOD
|
||||
->run();
|
||||
}
|
||||
|
||||
public function projectWatch()
|
||||
{
|
||||
$this->projectDeploy();
|
||||
|
||||
$this->taskWatch()
|
||||
->monitor($this->root_dir . 'composer.json', function () {
|
||||
$this->taskComposerUpdate()->run();
|
||||
$this->projectDeploy();
|
||||
})->monitor($this->root_dir . 'src/', function () {
|
||||
$this->projectDeploy();
|
||||
})->run();
|
||||
}
|
||||
|
||||
public function projectPackage()
|
||||
{
|
||||
$this->taskDeleteDir('target')->run();
|
||||
$this->taskFileSystemStack()->mkdir('target')->run();
|
||||
|
||||
$zip = new ZipArchive();
|
||||
$filename = "target/build.ocmod.zip";
|
||||
|
||||
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
|
||||
$this->printTaskError("<error> Could not create ZipArchive");
|
||||
exit();
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator("src", \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST
|
||||
);
|
||||
foreach ($iterator as $file) {
|
||||
if ($file->isFile() && $file->isReadable()) {
|
||||
$zip->addFile($file->getPathname(),substr($file->getPathname(),4));
|
||||
}
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
}
|
||||
|
||||
private function getOpencartDownloadUrl(string $version): string
|
||||
{
|
||||
if (version_compare($version, '3.0.1.1', '<=')) {
|
||||
return sprintf('https://github.com/opencart/opencart/releases/download/%s/%s-compiled.zip', $version, $version);
|
||||
}
|
||||
|
||||
if (array_key_exists($version, self::OPENCART_DOWNLOAD_URL)) {
|
||||
return self::OPENCART_DOWNLOAD_URL[$version];
|
||||
}
|
||||
|
||||
return sprintf('https://github.com/opencart/opencart/releases/download/%s/opencart-%s.zip', $version, $version);
|
||||
}
|
||||
|
||||
private function getOpencartRootDir(string $version): string
|
||||
{
|
||||
if (array_key_exists($version, self::OPENCART_ROOT_DIR)) {
|
||||
return '/tmp/opencart/' . self::OPENCART_ROOT_DIR[$version];
|
||||
}
|
||||
|
||||
return '/tmp/opencart/upload';
|
||||
}
|
||||
|
||||
private function restoreSampleData($conn)
|
||||
{
|
||||
$sql = file_get_contents($this->root_dir . 'tests/opencart_sample_data_3.sql');
|
||||
|
||||
$conn->exec("USE " . $this->opencart_config['db_database']);
|
||||
|
||||
foreach (explode(";\n", $sql) as $sql) {
|
||||
$sql = trim($sql);
|
||||
|
||||
if ($sql) {
|
||||
$conn->exec($sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,8 +1,8 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ControllerRetailcrmAdminTest extends OpenCartTest
|
||||
class ControllerRetailcrmAdminTest extends TestCase
|
||||
{
|
||||
const MODULE_TITLE = 'retailcrm';
|
||||
|
||||
|
@ -10,7 +10,7 @@ class ControllerRetailcrmAdminTest extends OpenCartTest
|
|||
{
|
||||
parent::setUp();
|
||||
|
||||
$query = $this->db->query("SELECT permission from " . DB_PREFIX . "user_group WHERE name = 'Administrator'");
|
||||
$query = $this->db->query("SELECT permission from ".DB_PREFIX."user_group WHERE name = 'Administrator'");
|
||||
$permissions = json_decode($query->row['permission'],true);
|
||||
|
||||
if (!in_array('extension/module/retailcrm', $permissions['access'])) {
|
||||
|
@ -18,23 +18,86 @@ class ControllerRetailcrmAdminTest extends OpenCartTest
|
|||
$this->db->query("UPDATE ".DB_PREFIX."user_group SET permission='".$this->db->escape(json_encode($permissions))."' WHERE name = 'Administrator'");
|
||||
}
|
||||
|
||||
$this->retailcrm = $this->getMockBuilder('\retailcrm\retailcrm')
|
||||
$this->retailcrm = $this->getMockBuilder('\retailcrm\Retailcrm')
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
}
|
||||
|
||||
public function testIndex()
|
||||
public function testController()
|
||||
{
|
||||
$this->login('admin', 'admin');
|
||||
$response = $this->dispatchAction('extension/module/retailcrm');
|
||||
|
||||
$response = $this->dispatchAction('extension/module/retailcrm');
|
||||
$this->assertRegExp('/Connection settings/', $response->getOutput());
|
||||
|
||||
$response = $this->dispatchAction('extension/module/retailcrm/icml');
|
||||
|
||||
$this->assertRegExp('/Connection settings/', $response->getOutput());
|
||||
$this->assertFileExists(DIR_SYSTEM . '../' . 'retailcrm.xml');
|
||||
|
||||
$response = $this->dispatchAction('extension/module/retailcrm/install_collector');
|
||||
$this->assertRegExp('/Connection settings/', $response->getOutput());
|
||||
|
||||
$response = $this->dispatchAction('extension/module/retailcrm/uninstall_collector');
|
||||
$this->assertRegExp('/Connection settings/', $response->getOutput());
|
||||
}
|
||||
|
||||
public function testIcml()
|
||||
public function testGetAvailableTypes()
|
||||
{
|
||||
$this->login('admin', 'admin');
|
||||
$this->dispatchAction('extension/module/retailcrm/icml');
|
||||
$this->assertFileExists(DIR_SYSTEM . '../' . 'retailcrm.xml');
|
||||
$data = $this->getDataForTestAvailableTypes();
|
||||
$sites = end($data['site']);
|
||||
$types = $data['types'];
|
||||
|
||||
$retailCrm = new ControllerExtensionModuleRetailcrm(self::$registry);
|
||||
$class = new ReflectionClass($retailCrm);
|
||||
$method = $class->getMethod('getAvailableTypes');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$result = $method->invokeArgs($retailCrm, [$sites, $types]);
|
||||
|
||||
$this->assertNotEmpty($result['opencart']);
|
||||
$this->assertNotEmpty($result['retailcrm']);
|
||||
$this->assertCount(2, $result['retailcrm']);
|
||||
$this->assertNotEmpty($result['retailcrm']['test1']['code']);
|
||||
$this->assertNotEmpty($result['retailcrm']['test4']['code']);
|
||||
}
|
||||
|
||||
private function getDataForTestAvailableTypes(): array
|
||||
{
|
||||
return [
|
||||
'site' => [
|
||||
'opencart' => [
|
||||
'code' => 'opencart',
|
||||
'name' => 'OpenCart'
|
||||
]
|
||||
],
|
||||
'types' => [
|
||||
'opencart' => [
|
||||
'test'
|
||||
],
|
||||
'retailcrm' => [
|
||||
'test1' => [
|
||||
'active' => true,
|
||||
'sites' => [],
|
||||
'code' => 'test1'
|
||||
],
|
||||
'test2' => [
|
||||
'active' => false,
|
||||
'sites' => [],
|
||||
'code' => 'test2'
|
||||
],
|
||||
'test3' => [
|
||||
'active' => true,
|
||||
'sites' => ['otherSite'],
|
||||
'code' => 'test3'
|
||||
],
|
||||
'test4' => [
|
||||
'active' => true,
|
||||
'sites' => ['cms1', 'cms2', 'opencart'],
|
||||
'code' => 'test4'
|
||||
]
|
||||
]
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
44
tests/admin/ModelRetailcrmCustomerAdminTest.php
Normal file
44
tests/admin/ModelRetailcrmCustomerAdminTest.php
Normal file
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmCustomerAdminTest extends TestCase
|
||||
{
|
||||
private $customerModel;
|
||||
private $apiClientMock;
|
||||
|
||||
const CUSTOMER_ID = 1;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->customerModel = $this->loadModel('extension/retailcrm/customer');
|
||||
|
||||
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'customersUpload',
|
||||
'customersEdit'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
self::$registry->set(\RetailcrmProxy::class, $this->apiClientMock);
|
||||
}
|
||||
|
||||
public function testUploadToCrm()
|
||||
{
|
||||
$customerModel = $this->loadModel('customer/customer');
|
||||
$customers = $customerModel->getCustomers();
|
||||
|
||||
$customersSend = $this->customerModel->uploadToCrm($customers, $this->apiClientMock);
|
||||
$customer = $customersSend[0][0];
|
||||
|
||||
$this->assertInternalType('array', $customersSend);
|
||||
$this->assertInternalType('array', $customersSend[0]);
|
||||
$this->assertArrayHasKey('externalId', $customer);
|
||||
$this->assertArrayHasKey('firstName', $customer);
|
||||
$this->assertArrayHasKey('lastName', $customer);
|
||||
$this->assertArrayHasKey('email', $customer);
|
||||
}
|
||||
}
|
27
tests/admin/ModelRetailcrmEventAdminTest.php
Normal file
27
tests/admin/ModelRetailcrmEventAdminTest.php
Normal file
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmEventAdminTest extends TestCase
|
||||
{
|
||||
const CODE = 'test';
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$eventModel = $this->loadModel('setting/event');
|
||||
$eventModel->addEvent(self::CODE, 'test', 'test');
|
||||
}
|
||||
|
||||
public function testGetEvent()
|
||||
{
|
||||
$eventModel = $this->loadModel('extension/retailcrm/event');
|
||||
$event = $eventModel->getEventByCode(self::CODE);
|
||||
|
||||
$this->assertNotEmpty($event);
|
||||
$this->assertEquals(self::CODE, $event['code']);
|
||||
$this->assertEquals('test', $event['trigger']);
|
||||
$this->assertEquals('test', $event['action']);
|
||||
}
|
||||
}
|
|
@ -1,12 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmOrderAdminTest extends OpenCartTest
|
||||
class ModelRetailcrmOrderAdminTest extends TestCase
|
||||
{
|
||||
public function testOrderModel()
|
||||
private $orderModel;
|
||||
private $apiClientMock;
|
||||
private $settingModel;
|
||||
|
||||
const CUSTOMER_ID = 1;
|
||||
const ORDER_WITH_CUST_ID = 1;
|
||||
const ORDER_ID = 2;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
$this->assertTrue(true);
|
||||
// todo test
|
||||
parent::setUp();
|
||||
|
||||
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'ordersUpload',
|
||||
'customersList',
|
||||
'ordersCreate',
|
||||
'ordersPaymentCreate',
|
||||
'customersCreate'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
self::$registry->set(\RetailcrmProxy::class, $this->apiClientMock);
|
||||
$this->orderModel = $this->loadModel('extension/retailcrm/order');
|
||||
|
||||
$this->settingModel = $this->loadModel('setting/setting');
|
||||
}
|
||||
|
||||
public function testUploadToCrm()
|
||||
{
|
||||
$saleOrderModel = $this->loadModel('sale/order');
|
||||
$orders = $saleOrderModel->getOrders();
|
||||
$fullOrders = array();
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$fullOrder = $saleOrderModel->getOrder($order['order_id']);
|
||||
|
||||
$fullOrder['totals'] = $saleOrderModel->getOrderTotals($order['order_id']);
|
||||
$fullOrder['products'] = $saleOrderModel->getOrderProducts($order['order_id']);
|
||||
|
||||
foreach($fullOrder['products'] as $key => $product) {
|
||||
$fullOrder['products'][$key]['option'] = $saleOrderModel->getOrderOptions($product['order_id'], $product['order_product_id']);
|
||||
}
|
||||
|
||||
$fullOrders[] = $fullOrder;
|
||||
}
|
||||
|
||||
$chunkedOrders = $this->orderModel->uploadToCrm($fullOrders);
|
||||
|
||||
$order = $chunkedOrders[0][0];
|
||||
|
||||
$this->assertInternalType('array', $chunkedOrders);
|
||||
$this->assertInternalType('array', $chunkedOrders[0]);
|
||||
$this->assertNotEmpty($chunkedOrders[0]);
|
||||
$this->assertArrayHasKey('externalId', $order);
|
||||
$this->assertArrayHasKey('number', $order);
|
||||
$this->assertArrayHasKey('firstName', $order);
|
||||
$this->assertArrayHasKey('lastName', $order);
|
||||
$this->assertArrayHasKey('email', $order);
|
||||
$this->assertArrayHasKey('phone', $order);
|
||||
$this->assertArrayHasKey('createdAt', $order);
|
||||
$this->assertArrayHasKey('delivery', $order);
|
||||
$this->assertArrayHasKey('status', $order);
|
||||
$this->assertArrayHasKey('items', $order);
|
||||
$this->assertArrayHasKey('payments', $order);
|
||||
$this->assertNotEmpty($order['payments']);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmPricesAdminTest extends OpenCartTest
|
||||
class ModelRetailcrmPricesAdminTest extends TestCase
|
||||
{
|
||||
private $pricesModel;
|
||||
private $apiClientMock;
|
||||
|
@ -19,32 +19,38 @@ class ModelRetailcrmPricesAdminTest extends OpenCartTest
|
|||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'storePricesUpload',
|
||||
'sitesList'
|
||||
'sitesList',
|
||||
'isSuccessful'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
$this->settingModel = $this->loadModel('setting/setting');
|
||||
$this->retailcrm = new \Retailcrm\Retailcrm(self::$registry);
|
||||
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
|
||||
|
||||
$this->settingModel->editSetting(
|
||||
\Retailcrm\Retailcrm::MODULE,
|
||||
$this->retailcrm->getModuleTitle(),
|
||||
array(
|
||||
\Retailcrm\Retailcrm::MODULE . '_apiversion' => 'v5',
|
||||
\Retailcrm\Retailcrm::MODULE . '_special_1' => 'special1',
|
||||
\Retailcrm\Retailcrm::MODULE . '_special_2' => 'special2',
|
||||
\Retailcrm\Retailcrm::MODULE . '_special_3' => 'special3'
|
||||
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
|
||||
$this->retailcrm->getModuleTitle() . '_special_1' => 'special1',
|
||||
$this->retailcrm->getModuleTitle() . '_special_2' => 'special2',
|
||||
$this->retailcrm->getModuleTitle() . '_special_3' => 'special3'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function testUploadPrices()
|
||||
{
|
||||
$response = new \RetailcrmApiResponse(200, json_encode($this->getSites()));
|
||||
$this->apiClientMock->expects($this->any())->method('sitesList')->willReturn($response);
|
||||
$response = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
$this->sites()
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('sitesList')->willReturn($response);
|
||||
$productModel = $this->loadModel('catalog/product');
|
||||
$products = $productModel->getProducts();
|
||||
$prices = $this->pricesModel->uploadPrices($products, $this->apiClientMock, $this->retailcrm);
|
||||
$prices = $this->pricesModel->uploadPrices($products, $this->apiClientMock);
|
||||
$price = $prices[0][0];
|
||||
|
||||
$this->assertInternalType('array', $prices);
|
||||
|
@ -52,26 +58,39 @@ class ModelRetailcrmPricesAdminTest extends OpenCartTest
|
|||
$this->assertInternalType('array', $price);
|
||||
$this->assertArrayHasKey('externalId', $price);
|
||||
$this->assertArrayHasKey('site', $price);
|
||||
$this->assertSame('test_site', $price['site']);
|
||||
$this->assertArrayHasKey('prices', $price);
|
||||
$this->assertInternalType('array', $price['prices']);
|
||||
$this->assertSame('special1', $price['prices'][0]['code']);
|
||||
$this->assertSame('special2', $price['prices'][1]['code']);
|
||||
$this->assertSame('special3', $price['prices'][2]['code']);
|
||||
$this->assertEquals('special1', $price['prices'][0]['code']);
|
||||
$this->assertEquals('special2', $price['prices'][1]['code']);
|
||||
$this->assertEquals('special3', $price['prices'][2]['code']);
|
||||
$this->assertFalse($price['prices'][0]['remove']);
|
||||
$this->assertFalse($price['prices'][1]['remove']);
|
||||
$this->assertNotFalse($price['prices'][1]['remove']);
|
||||
$this->assertNotFalse($price['prices'][2]['remove']);
|
||||
}
|
||||
|
||||
private function getSites()
|
||||
{
|
||||
private function sites(){
|
||||
return array(
|
||||
'success' => true,
|
||||
'sites' => array(
|
||||
array(
|
||||
'code' => 'test_site'
|
||||
"success"=> true,
|
||||
"sites"=> array(
|
||||
"opencart"=> array(
|
||||
"name"=> "site",
|
||||
"url"=> "http://site.ru",
|
||||
"code"=> "site",
|
||||
"defaultForCrm"=> false,
|
||||
"ymlUrl"=> "http://site.ru/retailcrm.xml",
|
||||
"loadFromYml"=> false,
|
||||
"catalogUpdatedAt"=> "2019-02-08 13:30:37",
|
||||
"catalogLoadingAt"=> "2019-02-11 09:12:18",
|
||||
"contragent"=> array(
|
||||
"contragentType"=> "legal-entity",
|
||||
"legalName"=> "code",
|
||||
"code"=> "code",
|
||||
"countryIso"=> "RU",
|
||||
"vatRate"=> "",
|
||||
),
|
||||
"countryIso"=> "",
|
||||
)
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,14 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
class ModelRetailcrmProductsAdminTest extends OpenCartTest
|
||||
{
|
||||
public function testGetProductOptions()
|
||||
{
|
||||
$model = $this->loadModel('extension/retailcrm/products');
|
||||
$options = $model->getProductOptions(42);
|
||||
|
||||
$this->assertNotEmpty($options);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ControllerDaemonCollectorExtensionAnalyticsCatalogTest extends TestCase {
|
||||
public function testIndex() {
|
||||
$data = $this->load->controller('extension/analytics/daemon_collector');
|
||||
|
||||
$this->assertContains('RC-XXXXXXXXXX-X', $data);
|
||||
}
|
||||
}
|
|
@ -1,14 +1,14 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ControllerRetailcrmApiCatalogTest extends OpenCartTest
|
||||
class ControllerRetailcrmApiCatalogTest extends TestCase
|
||||
{
|
||||
private $apiKey;
|
||||
private $retailcrm;
|
||||
private $username;
|
||||
|
||||
const ORDER_ID = 1;
|
||||
const USERNAME = 'Default';
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
|
@ -17,18 +17,18 @@ class ControllerRetailcrmApiCatalogTest extends OpenCartTest
|
|||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE api_id = 1");
|
||||
$api = $query->row;
|
||||
$this->apiKey = $api['key'];
|
||||
$this->username = $api['username'];
|
||||
$this->retailcrm = new \Retailcrm\Retailcrm(self::$registry);
|
||||
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
|
||||
|
||||
$this->setSetting(
|
||||
\Retailcrm\Retailcrm::MODULE,
|
||||
$this->retailcrm->getModuleTitle(),
|
||||
array(
|
||||
\Retailcrm\Retailcrm::MODULE . '_country' => array(1),
|
||||
$this->retailcrm->getModuleTitle() . '_country' => array(1),
|
||||
)
|
||||
);
|
||||
|
||||
if (isset($this->request->get['key'])) {
|
||||
if (isset($this->request->get['key']) && isset($this->request->get['username'])) {
|
||||
unset($this->request->get['key']);
|
||||
unset($this->request->get['username']);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -40,8 +40,7 @@ class ControllerRetailcrmApiCatalogTest extends OpenCartTest
|
|||
$this->assertEquals('Not found api key', $data->error);
|
||||
|
||||
$this->request->get['key'] = $this->apiKey;
|
||||
$this->request->get['username'] = $this->username;
|
||||
|
||||
$this->request->get['username'] = static::USERNAME;
|
||||
$response = $this->dispatchAction('api/retailcrm/getDeliveryTypes');
|
||||
$data = json_decode($response->getOutput());
|
||||
|
||||
|
@ -56,24 +55,10 @@ class ControllerRetailcrmApiCatalogTest extends OpenCartTest
|
|||
$this->assertEquals('Not found api key', $data->error);
|
||||
|
||||
$this->request->get['key'] = $this->apiKey;
|
||||
$this->request->get['username'] = $this->username;
|
||||
$this->request->get['username'] = static::USERNAME;
|
||||
$response = $this->dispatchAction('api/retailcrm/addOrderHistory');
|
||||
$data = json_decode($response->getOutput());
|
||||
|
||||
$this->assertEquals('Not found data', $data->error);
|
||||
}
|
||||
|
||||
protected function setSetting($code, $data, $store_id = 0) {
|
||||
$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (substr($key, 0, strlen($code)) == $code) {
|
||||
if (!is_array($value)) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
|
||||
} else {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,307 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmOrderCatalogTest extends OpenCartTest
|
||||
class ModelRetailcrmOrderCatalogTest extends TestCase
|
||||
{
|
||||
public function testGetOrderStatus()
|
||||
{
|
||||
$model = $this->loadModel('extension/retailcrm/order');
|
||||
$status_id = $model->getOrderStatusId(1);
|
||||
private $orderModel;
|
||||
private $apiClientMock;
|
||||
private $retailcrm;
|
||||
|
||||
$this->assertNotEmpty($status_id);
|
||||
$this->assertNotNull($status_id);
|
||||
const CUSTOMER_ID = 1;
|
||||
const ORDER_WITH_CUST_ID = 1;
|
||||
const ORDER_ID = 2;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->orderModel = $this->loadModel('extension/retailcrm/order');
|
||||
|
||||
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'ordersCreate',
|
||||
'ordersEdit',
|
||||
'ordersGet',
|
||||
'ordersPaymentEdit',
|
||||
'customersList',
|
||||
'customersCreate'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
|
||||
|
||||
$this->setSetting(
|
||||
$this->retailcrm->getModuleTitle(),
|
||||
array(
|
||||
$this->retailcrm->getModuleTitle() . '_apiversion' => 'v5',
|
||||
$this->retailcrm->getModuleTitle() . '_order_number' => 1,
|
||||
$this->retailcrm->getModuleTitle() . '_status' => array(
|
||||
1 => 'new'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_delivery' => array(
|
||||
'flat.flat' => 'flat'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_payment' => array(
|
||||
'cod' => 'cod'
|
||||
),
|
||||
$this->retailcrm->getModuleTitle() . '_special_1' => 'special1',
|
||||
$this->retailcrm->getModuleTitle() . '_special_2' => 'special2',
|
||||
$this->retailcrm->getModuleTitle() . '_special_3' => 'special3'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function testCreateOrderWithCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_WITH_CUST_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$orderProcess = $this->orderModel->processOrder($order);
|
||||
$successResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'id' => 1,
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$orderCreateErrorResponse = new \RetailcrmApiResponse(
|
||||
400,
|
||||
json_encode(
|
||||
array(
|
||||
'errors' => array (
|
||||
'customer.externalId' => "Customer with externalId=1 not found.",
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('customersCreate')->willReturn($successResponse);
|
||||
$this->apiClientMock->expects($this->any())->method('ordersCreate')->will(
|
||||
$this->onConsecutiveCalls($orderCreateErrorResponse, $successResponse)
|
||||
);
|
||||
|
||||
$orderSend = $this->orderModel->sendToCrm($orderProcess, $this->apiClientMock, $order);
|
||||
|
||||
$this->assertArrayHasKey('status', $orderSend);
|
||||
$this->assertEquals('new', $orderSend['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderSend);
|
||||
$this->assertArrayHasKey('number', $orderSend);
|
||||
$this->assertArrayHasKey('firstName', $orderSend);
|
||||
$this->assertEquals('Test', $orderSend['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderSend);
|
||||
$this->assertEquals('Test', $orderSend['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderSend);
|
||||
$this->assertEquals('test@mail.ru', $orderSend['email']);
|
||||
$this->assertArrayHasKey('phone', $orderSend);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderSend['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderSend);
|
||||
$this->assertArrayHasKey('delivery', $orderSend);
|
||||
$this->assertInternalType('array', $orderSend['delivery']);
|
||||
$this->assertEquals('flat', $orderSend['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderSend['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderSend['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderSend['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderSend);
|
||||
|
||||
foreach($orderSend['items'] as $item) {
|
||||
$this->assertArrayHasKey('priceType', $item);
|
||||
$this->assertEquals('special1', $item['priceType']['code']);
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('customerComment', $orderSend);
|
||||
$this->assertArrayHasKey('customer', $orderSend);
|
||||
$this->assertArrayHasKey('externalId', $orderSend['customer']);
|
||||
$this->assertEquals(self::CUSTOMER_ID, $orderSend['customer']['externalId']);
|
||||
$this->assertEquals(1, $orderSend['customer']['id']);
|
||||
$this->assertArrayHasKey('payments', $orderSend);
|
||||
$this->assertEquals('cod', $orderSend['payments'][0]['type']);
|
||||
$this->assertNotEmpty($orderSend['payments']);
|
||||
}
|
||||
|
||||
public function testEditOrderWithCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_WITH_CUST_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$orderEditResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'id' => 1
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$ordersGetResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'order' => $this->getOrder($order_id)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$orderEditErrorResponse = new \RetailcrmApiResponse(
|
||||
400,
|
||||
json_encode(
|
||||
array(
|
||||
'errors' => array (
|
||||
'customer.externalId' => "Customer with externalId=1 not found.",
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('ordersGet')->willReturn($ordersGetResponse);
|
||||
$this->apiClientMock->expects($this->any())->method('customersCreate')->willReturn($orderEditResponse);
|
||||
$this->apiClientMock->expects($this->any())->method('ordersEdit')->will(
|
||||
$this->onConsecutiveCalls($orderEditErrorResponse, $orderEditResponse)
|
||||
);
|
||||
|
||||
$orderProcess = $this->orderModel->processOrder($order);
|
||||
$orderSend = $this->orderModel->sendToCrm($orderProcess, $this->apiClientMock, $order, false);
|
||||
|
||||
$this->assertArrayHasKey('status', $orderSend);
|
||||
$this->assertEquals('new', $orderSend['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderSend);
|
||||
$this->assertArrayHasKey('number', $orderSend);
|
||||
$this->assertArrayHasKey('firstName', $orderSend);
|
||||
$this->assertEquals('Test', $orderSend['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderSend);
|
||||
$this->assertEquals('Test', $orderSend['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderSend);
|
||||
$this->assertEquals('test@mail.ru', $orderSend['email']);
|
||||
$this->assertArrayHasKey('phone', $orderSend);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderSend['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderSend);
|
||||
$this->assertArrayHasKey('delivery', $orderSend);
|
||||
$this->assertInternalType('array', $orderSend['delivery']);
|
||||
$this->assertEquals('flat', $orderSend['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderSend['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderSend['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderSend['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderSend);
|
||||
$this->assertEquals(1, $orderSend['customer']['id']);
|
||||
|
||||
foreach($orderSend['items'] as $item) {
|
||||
$this->assertArrayHasKey('priceType', $item);
|
||||
$this->assertEquals('special1', $item['priceType']['code']);
|
||||
}
|
||||
|
||||
$this->assertArrayHasKey('customerComment', $orderSend);
|
||||
}
|
||||
|
||||
public function testOrderCreateWithoutCustomerTest()
|
||||
{
|
||||
$order_id = self::ORDER_ID;
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach($order['products'] as $key => $product) {
|
||||
$order['products'][$key]['option'] = $orderAccountModel->getOrderOptions($product['order_id'], $product['order_product_id']);
|
||||
}
|
||||
|
||||
$responseCustomerCreate = new \RetailcrmApiResponse(
|
||||
201,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'id' => 1
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$responseCustomerList = new \RetailcrmApiResponse(
|
||||
201,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
"pagination"=> [
|
||||
"limit"=>20,
|
||||
"totalCount"=> 0,
|
||||
"currentPage"=> 1,
|
||||
"totalPageCount"=> 0
|
||||
],
|
||||
"customers"=> []
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('customersList')->willReturn($responseCustomerList);
|
||||
$this->apiClientMock->expects($this->any())->method('customersCreate')->willReturn($responseCustomerCreate);
|
||||
$orderProcess = $this->orderModel->processOrder($order);
|
||||
$orderSend = $this->orderModel->sendToCrm($orderProcess, $this->apiClientMock, $order);
|
||||
|
||||
$this->assertArrayHasKey('customer', $orderSend);
|
||||
$this->assertArrayNotHasKey('externalId', $orderSend['customer']);
|
||||
$this->assertArrayHasKey('id', $orderSend['customer']);
|
||||
$this->assertEquals(1, $orderSend['customer']['id']);
|
||||
|
||||
foreach($orderSend['items'] as $item) {
|
||||
$this->assertArrayNotHasKey('priceType', $item);
|
||||
}
|
||||
}
|
||||
|
||||
protected function setSetting($code, $data, $store_id = 0) {
|
||||
$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (substr($key, 0, strlen($code)) == $code) {
|
||||
if (!is_array($value)) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
|
||||
} else {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function getOrder($id)
|
||||
{
|
||||
return array(
|
||||
'payments' => array(
|
||||
array(
|
||||
'id' => 1,
|
||||
'status' => 'not-paid',
|
||||
'type' => 'cod',
|
||||
'externalId' => $id,
|
||||
'amount' => '100'
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,14 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
class ModelRetailcrmProductsCatalogTest extends OpenCartTest
|
||||
{
|
||||
public function testGetProductOptions()
|
||||
{
|
||||
$model = $this->loadModel('extension/retailcrm/products');
|
||||
$options = $model->getProductOptions(42);
|
||||
|
||||
$this->assertNotEmpty($options);
|
||||
}
|
||||
}
|
|
@ -1,47 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
class CustomerRetailcrmLibraryTest extends OpenCartTest
|
||||
{
|
||||
private $customer;
|
||||
private $apiClientMock;
|
||||
|
||||
const CUSTOMER_ID = 1;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'customersCreate',
|
||||
'customersEdit'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
$retailcrm = new \Retailcrm\Retailcrm(self::$registry);
|
||||
$this->customer = $retailcrm->createObject(\Retailcrm\Customer::class);
|
||||
}
|
||||
|
||||
public function testPrepareCustomer()
|
||||
{
|
||||
$customerModel = $this->loadModel('account/customer');
|
||||
$customer = $customerModel->getCustomer(self::CUSTOMER_ID);
|
||||
|
||||
$this->customer->prepare($customer);
|
||||
$customerSend = $this->customer->getData();
|
||||
|
||||
$this->assertArrayHasKey('externalId', $customerSend);
|
||||
$this->assertEquals(self::CUSTOMER_ID, $customerSend['externalId']);
|
||||
$this->assertArrayHasKey('firstName', $customerSend);
|
||||
$this->assertEquals('Test', $customerSend['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $customerSend);
|
||||
$this->assertEquals('Test', $customerSend['lastName']);
|
||||
$this->assertArrayHasKey('email', $customerSend);
|
||||
$this->assertEquals('test@mail.ru', $customerSend['email']);
|
||||
$this->assertArrayHasKey('phones', $customerSend);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $customerSend['phones'][0]['number']);
|
||||
}
|
||||
}
|
|
@ -1,306 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
class OrderRetailcrmLibraryTest extends OpenCartTest
|
||||
{
|
||||
private $order;
|
||||
private $apiClientMock;
|
||||
private $retailcrm;
|
||||
|
||||
const CUSTOMER_ID = 1;
|
||||
const ORDER_WITH_CUST_ID = 1;
|
||||
const ORDER_ID = 2;
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(array(
|
||||
'ordersCreate',
|
||||
'ordersEdit',
|
||||
'ordersGet',
|
||||
'ordersPaymentEdit',
|
||||
'customersList'
|
||||
))
|
||||
->getMock();
|
||||
|
||||
$this->retailcrm = new \Retailcrm\Retailcrm(self::$registry);
|
||||
|
||||
$this->order = $this->retailcrm->createObject(\Retailcrm\Order::class);
|
||||
|
||||
$this->setSetting(
|
||||
\Retailcrm\Retailcrm::MODULE,
|
||||
array(
|
||||
\Retailcrm\Retailcrm::MODULE . '_apiversion' => 'v5',
|
||||
\Retailcrm\Retailcrm::MODULE . '_order_number' => 1,
|
||||
\Retailcrm\Retailcrm::MODULE . '_status' => array(
|
||||
1 => 'new'
|
||||
),
|
||||
\Retailcrm\Retailcrm::MODULE . '_delivery' => array(
|
||||
'flat.flat' => 'flat'
|
||||
),
|
||||
\Retailcrm\Retailcrm::MODULE . '_payment' => array(
|
||||
'cod' => 'cod'
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function testPrepareCreateOrderWithCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_WITH_CUST_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$this->order->prepare($order);
|
||||
$orderPrepare = $this->order->getData();
|
||||
|
||||
$this->assertArrayHasKey('status', $orderPrepare);
|
||||
$this->assertEquals('new', $orderPrepare['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare);
|
||||
$this->assertArrayHasKey('number', $orderPrepare);
|
||||
$this->assertArrayHasKey('firstName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderPrepare);
|
||||
$this->assertEquals('test@mail.ru', $orderPrepare['email']);
|
||||
$this->assertArrayHasKey('phone', $orderPrepare);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderPrepare['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderPrepare);
|
||||
$this->assertArrayHasKey('delivery', $orderPrepare);
|
||||
$this->assertInternalType('array', $orderPrepare['delivery']);
|
||||
$this->assertEquals('flat', $orderPrepare['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderPrepare['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderPrepare['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderPrepare['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderPrepare);
|
||||
$this->assertArrayHasKey('customer', $orderPrepare);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare['customer']);
|
||||
$this->assertEquals(self::CUSTOMER_ID, $orderPrepare['customer']['externalId']);
|
||||
$this->assertArrayHasKey('payments', $orderPrepare);
|
||||
$this->assertEquals('cod', $orderPrepare['payments'][0]['type']);
|
||||
$this->assertNotEmpty($orderPrepare['payments']);
|
||||
}
|
||||
|
||||
public function testPrepareEditOrderWithCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_WITH_CUST_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$orderEditResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'id' => 1
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$ordersGetResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'order' => $this->getOrder($order_id)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('ordersEdit')->willReturn($orderEditResponse);
|
||||
$this->apiClientMock->expects($this->any())->method('ordersGet')->willReturn($ordersGetResponse);
|
||||
$this->order->prepare($order);
|
||||
$orderPrepare = $this->order->getData();
|
||||
|
||||
$this->assertArrayHasKey('status', $orderPrepare);
|
||||
$this->assertEquals('new', $orderPrepare['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare);
|
||||
$this->assertArrayHasKey('number', $orderPrepare);
|
||||
$this->assertArrayHasKey('firstName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderPrepare);
|
||||
$this->assertEquals('test@mail.ru', $orderPrepare['email']);
|
||||
$this->assertArrayHasKey('phone', $orderPrepare);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderPrepare['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderPrepare);
|
||||
$this->assertArrayHasKey('delivery', $orderPrepare);
|
||||
$this->assertInternalType('array', $orderPrepare['delivery']);
|
||||
$this->assertEquals('flat', $orderPrepare['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderPrepare['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderPrepare['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderPrepare['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderPrepare);
|
||||
$this->assertArrayHasKey('customer', $orderPrepare);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare['customer']);
|
||||
$this->assertEquals(self::CUSTOMER_ID, $orderPrepare['customer']['externalId']);
|
||||
}
|
||||
|
||||
public function testPrepareCreateOrderWithoutCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$this->order->prepare($order);
|
||||
$orderPrepare = $this->order->getData();
|
||||
|
||||
$this->assertArrayHasKey('status', $orderPrepare);
|
||||
$this->assertEquals('new', $orderPrepare['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare);
|
||||
$this->assertArrayHasKey('number', $orderPrepare);
|
||||
$this->assertArrayHasKey('firstName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderPrepare);
|
||||
$this->assertEquals('test@mail.ru', $orderPrepare['email']);
|
||||
$this->assertArrayHasKey('phone', $orderPrepare);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderPrepare['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderPrepare);
|
||||
$this->assertArrayHasKey('delivery', $orderPrepare);
|
||||
$this->assertInternalType('array', $orderPrepare['delivery']);
|
||||
$this->assertEquals('flat', $orderPrepare['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderPrepare['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderPrepare['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderPrepare['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderPrepare);
|
||||
$this->assertArrayNotHasKey('customer', $orderPrepare);
|
||||
$this->assertArrayHasKey('payments', $orderPrepare);
|
||||
$this->assertEquals('cod', $orderPrepare['payments'][0]['type']);
|
||||
$this->assertNotEmpty($orderPrepare['payments']);
|
||||
}
|
||||
|
||||
public function testPrepareEditOrderWithoutCustomer()
|
||||
{
|
||||
$orderCheckoutModel = $this->loadModel('checkout/order');
|
||||
$orderAccountModel = $this->loadModel('account/order');
|
||||
$order_id = self::ORDER_ID;
|
||||
$order = $orderCheckoutModel->getOrder($order_id);
|
||||
$order['products'] = $orderAccountModel->getOrderProducts($order_id);
|
||||
$order['totals'] = $orderAccountModel->getOrderTotals($order_id);
|
||||
|
||||
foreach ($order['products'] as $key => $product) {
|
||||
$productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']);
|
||||
|
||||
if (!empty($productOptions)) {
|
||||
$order['products'][$key]['option'] = $productOptions;
|
||||
}
|
||||
}
|
||||
|
||||
$orderEditResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'id' => 1
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$ordersGetResponse = new \RetailcrmApiResponse(
|
||||
200,
|
||||
json_encode(
|
||||
array(
|
||||
'success' => true,
|
||||
'order' => $this->getOrder($order_id)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiClientMock->expects($this->any())->method('ordersEdit')->willReturn($orderEditResponse);
|
||||
$this->apiClientMock->expects($this->any())->method('ordersGet')->willReturn($ordersGetResponse);
|
||||
$this->order->prepare($order);
|
||||
$orderPrepare = $this->order->getData();
|
||||
|
||||
$this->assertArrayHasKey('status', $orderPrepare);
|
||||
$this->assertEquals('new', $orderPrepare['status']);
|
||||
$this->assertArrayHasKey('externalId', $orderPrepare);
|
||||
$this->assertArrayHasKey('number', $orderPrepare);
|
||||
$this->assertArrayHasKey('firstName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['firstName']);
|
||||
$this->assertArrayHasKey('lastName', $orderPrepare);
|
||||
$this->assertEquals('Test', $orderPrepare['lastName']);
|
||||
$this->assertArrayHasKey('email', $orderPrepare);
|
||||
$this->assertEquals('test@mail.ru', $orderPrepare['email']);
|
||||
$this->assertArrayHasKey('phone', $orderPrepare);
|
||||
$this->assertEquals('+7 (000) 000-00-00', $orderPrepare['phone']);
|
||||
$this->assertArrayHasKey('createdAt', $orderPrepare);
|
||||
$this->assertArrayHasKey('delivery', $orderPrepare);
|
||||
$this->assertInternalType('array', $orderPrepare['delivery']);
|
||||
$this->assertEquals('flat', $orderPrepare['delivery']['code']);
|
||||
$this->assertEquals('Test', $orderPrepare['delivery']['address']['city']);
|
||||
$this->assertEquals('Rostov-na-Donu', $orderPrepare['delivery']['address']['region']);
|
||||
$this->assertEquals('111111', $orderPrepare['delivery']['address']['index']);
|
||||
$this->assertArrayHasKey('items', $orderPrepare);
|
||||
$this->assertArrayNotHasKey('customer', $orderPrepare);
|
||||
}
|
||||
|
||||
protected function setSetting($code, $data, $store_id = 0) {
|
||||
$this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'");
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if (substr($key, 0, strlen($code)) == $code) {
|
||||
if (!is_array($value)) {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
|
||||
} else {
|
||||
$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function getOrder($id)
|
||||
{
|
||||
return array(
|
||||
'payments' => array(
|
||||
array(
|
||||
'id' => 1,
|
||||
'status' => 'not-paid',
|
||||
'type' => 'cod',
|
||||
'externalId' => $id,
|
||||
'amount' => '100'
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,6 +1,9 @@
|
|||
TRUNCATE TABLE `oc_customer`;
|
||||
INSERT INTO `oc_customer` (`customer_id`, `customer_group_id`, `store_id`, `language_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `password`, `salt`, `cart`, `wishlist`, `newsletter`, `address_id`, `custom_field`, `ip`, `status`, `safe`, `token`, `code`, `date_added`) VALUES ('1', '1', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', 'ed3798da75d6cdd695e99e87a60d587a10aa95ff', '51TalnrgH', '', '', '0', '1', '', '172.21.0.1', '1', '0', '', '', '2018-06-07 13:50:08');
|
||||
|
||||
TRUNCATE TABLE `oc_address`;
|
||||
INSERT INTO `oc_address` (`address_id`, `customer_id`, `firstname`, `lastname`, `company`, `address_1`, `address_2`, `city`, `postcode`, `country_id`, `zone_id`, `custom_field`) values (1, 1, 'Test', 'Test', '', 'Address 1', '', 'City', '111111', '176', '99', '');
|
||||
|
||||
TRUNCATE TABLE `oc_customer_activity`;
|
||||
TRUNCATE TABLE `oc_customer_group`;
|
||||
INSERT INTO `oc_customer_group` (`customer_group_id`, `approval`, `sort_order`) VALUES ('1', '0', '1');
|
||||
|
@ -24,8 +27,8 @@ TRUNCATE TABLE `oc_customer_transaction`;
|
|||
TRUNCATE TABLE `oc_customer_wishlist`;
|
||||
TRUNCATE TABLE `oc_order`;
|
||||
|
||||
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('1', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '1', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', '', '106.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:51:10', '2018-06-07 13:51:23');
|
||||
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('2', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '[]', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', '', '85.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:53:50', '2018-06-07 13:54:00');
|
||||
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('1', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '1', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', 'test comment', '106.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:51:10', '2018-06-07 13:51:23');
|
||||
INSERT INTO `oc_order` (`order_id`, `invoice_no`, `invoice_prefix`, `store_id`, `store_name`, `store_url`, `customer_id`, `customer_group_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `custom_field`, `payment_firstname`, `payment_lastname`, `payment_company`, `payment_address_1`, `payment_address_2`, `payment_city`, `payment_postcode`, `payment_country`, `payment_country_id`, `payment_zone`, `payment_zone_id`, `payment_address_format`, `payment_custom_field`, `payment_method`, `payment_code`, `shipping_firstname`, `shipping_lastname`, `shipping_company`, `shipping_address_1`, `shipping_address_2`, `shipping_city`, `shipping_postcode`, `shipping_country`, `shipping_country_id`, `shipping_zone`, `shipping_zone_id`, `shipping_address_format`, `shipping_custom_field`, `shipping_method`, `shipping_code`, `comment`, `total`, `order_status_id`, `affiliate_id`, `commission`, `marketing_id`, `tracking`, `language_id`, `currency_id`, `currency_code`, `currency_value`, `ip`, `forwarded_ip`, `user_agent`, `accept_language`, `date_added`, `date_modified`) VALUES ('2', '0', 'INV-2016-00', '0', 'Opencart', 'http://localhost:8000/', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', '[]', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Cash on delivery', 'cod', 'Test', 'Test', '', 'Address', 'Address 2', 'Test', '111111', 'Russian Federation', '176', 'Rostov-na-Donu', '99', '', '[]', 'Flat Rate', 'flat.flat', 'test comment', '85.0000', '1', '0', '0.0000', '0', '', '1', '1', 'USD', '1.00000000', '172.21.0.1', '', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36', 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', '2018-06-07 13:53:50', '2018-06-07 13:54:00');
|
||||
|
||||
TRUNCATE TABLE `oc_order_history`;
|
||||
INSERT INTO `oc_order_history` (`order_history_id`, `order_id`, `order_status_id`, `notify`, `comment`, `date_added`) VALUES ('19', '2', '1', '0', '', '2018-06-07 13:54:00');
|
||||
|
@ -42,6 +45,7 @@ INSERT INTO `oc_order_product` (`order_product_id`, `order_id`, `product_id`, `n
|
|||
TRUNCATE TABLE `oc_order_recurring`;
|
||||
TRUNCATE TABLE `oc_order_recurring_transaction`;
|
||||
TRUNCATE TABLE `oc_order_total`;
|
||||
|
||||
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('162', '1', 'shipping', 'Flat Rate', '5.0000', '3');
|
||||
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('161', '1', 'sub_total', 'Sub-Total', '101.0000', '1');
|
||||
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('164', '2', 'sub_total', 'Sub-Total', '80.0000', '1');
|
||||
|
@ -49,5 +53,6 @@ INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `va
|
|||
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('163', '1', 'total', 'Total', '106.0000', '9');
|
||||
INSERT INTO `oc_order_total` (`order_total_id`, `order_id`, `code`, `title`, `value`, `sort_order`) VALUES ('166', '2', 'total', 'Total', '85.0000', '9');
|
||||
INSERT INTO `oc_product_special` (`product_id`, `customer_group_id`, `priority`, `price`,`date_start`, `date_end`) values ('42', '2', '1', '110.000', CURDATE(), ADDDATE(CURDATE(),INTERVAL 10 DAY));
|
||||
INSERT INTO `oc_product_special` (`product_id`, `customer_group_id`, `priority`, `price`,`date_start`, `date_end`) values ('40', '1', '1', '50.000', CURDATE(), ADDDATE(CURDATE(),INTERVAL 10 DAY));
|
||||
|
||||
TRUNCATE TABLE `oc_order_voucher`;
|
||||
TRUNCATE TABLE `oc_order_voucher`;
|
41
tests/system/RetailcrmTest.php
Normal file
41
tests/system/RetailcrmTest.php
Normal file
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class RetailcrmTest extends TestCase {
|
||||
|
||||
public function testGetOrderManager() {
|
||||
$retailcrm = new retailcrm\Retailcrm(static::$registry);
|
||||
|
||||
$proxy = $this->getMockBuilder(\RetailcrmProxy::class)
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
|
||||
static::$registry->set(\RetailcrmProxy::class, $proxy);
|
||||
$manager = $retailcrm->getOrderManager();
|
||||
|
||||
$this->assertInstanceOf(\retailcrm\service\OrderManager::class, $manager);
|
||||
}
|
||||
|
||||
public function testGetWeightOption() {
|
||||
$retailCrm = new \retailcrm\Retailcrm(self::$registry);
|
||||
|
||||
$reflection = new ReflectionClass($retailCrm);
|
||||
$reflectionMethod = $reflection->getMethod('getWeightOption');
|
||||
$reflectionMethod->setAccessible('true');
|
||||
|
||||
$result = $reflectionMethod->invokeArgs(
|
||||
$retailCrm,
|
||||
[['weight_prefix' => '+', 'weight' => 5]]
|
||||
);
|
||||
|
||||
$this->assertEquals(5, $result);
|
||||
|
||||
$result = $reflectionMethod->invokeArgs(
|
||||
$retailCrm,
|
||||
[['weight_prefix' => '-', 'weight' => 5]]
|
||||
);
|
||||
|
||||
$this->assertEquals(-5, $result);;
|
||||
}
|
||||
}
|
14
tests/system/lib/ModelsProviderAdminTest.php
Normal file
14
tests/system/lib/ModelsProviderAdminTest.php
Normal file
|
@ -0,0 +1,14 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelsProviderAdminTest extends TestCase {
|
||||
public function testAdminIncludeDependencies() {
|
||||
// TODO should be run with "processIsolation", but with that not working asserting
|
||||
// $provider = new \retailcrm\ModelsProvider(static::$registry);
|
||||
//
|
||||
// $provider->includeDependencies();
|
||||
//
|
||||
// $this->assertNotEmpty($this->model_sale_order);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue