mirror of
https://github.com/retailcrm/opencart-module.git
synced 2025-04-05 06:13:38 +03:00
Compare commits
323 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 | ||
|
30a2600b7b | ||
|
fe5a2abcba | ||
|
4174195128 | ||
|
57c2ca99c9 | ||
|
86064c775f | ||
|
8b8350a290 | ||
|
761bffef76 | ||
|
6b1cdd5d42 | ||
|
d08519f673 | ||
|
caa6a03b14 | ||
|
c3120a723d | ||
|
7b05d975a4 | ||
|
93641e82ef | ||
|
5cd191b6a4 | ||
|
a829cb8f17 | ||
|
9eecfcffb8 | ||
|
7151814da8 | ||
|
6506dc716f | ||
|
4ba6f6ce83 | ||
|
1440c9fdbf | ||
|
0dcededd62 | ||
|
2c4306dad1 | ||
|
26a6a0731c | ||
|
a9c8a96101 | ||
|
f006561d3e | ||
|
c49070ea6f | ||
|
c454db172f | ||
|
65459af91b | ||
|
b6d04fe04d | ||
|
003a2e5797 | ||
|
97a75c1950 | ||
|
1e71be6b7a | ||
|
bf5a5b9e15 | ||
|
68f11d3197 | ||
|
9535f2de8e | ||
|
51404a5533 | ||
|
680e1c28fe | ||
|
afc2c9156c | ||
|
ef86e4579e | ||
|
68636d50f6 | ||
|
2ddc8b50d1 | ||
|
6875bc5f61 | ||
|
c526a07ea1 | ||
|
cdc1c9cf6b | ||
|
0e32063eb6 | ||
|
45fde808b7 | ||
|
55c458dcac | ||
|
e69c4c11d9 | ||
|
73ea249145 | ||
|
3841072727 | ||
|
14049caf67 | ||
|
9f74543988 | ||
|
3d3cbd715b | ||
|
0185de6dc3 | ||
|
05a47a90b5 | ||
|
626d3a1763 | ||
|
2b2dbc4a48 | ||
|
9245f35b83 | ||
|
82d93de94b | ||
|
1190fec934 | ||
|
0797b9b7f1 | ||
|
1052781689 | ||
|
fec2c3495c | ||
|
4890619c9a | ||
|
cbbfc67cd8 | ||
|
5b7b2c3c36 | ||
|
71537c7482 | ||
|
9949e0fcea | ||
|
0aff088a69 | ||
|
12cc1c620a | ||
|
dca2b67a5b | ||
|
84b851d79b | ||
|
b1f0835b9c | ||
|
647d5e8427 | ||
|
1484071122 | ||
|
9146ebd2f6 | ||
|
19ceeae2b0 | ||
|
a1cd3aa6b7 | ||
|
c51e4a35a4 | ||
|
d75366274a | ||
|
7d97895729 | ||
|
276024a5e5 | ||
|
07a04ecfca | ||
|
5bc88cc118 | ||
|
ac98d0fc0e | ||
|
06932a7540 | ||
|
c43e901170 | ||
|
d860f6203c | ||
|
80c96f4981 | ||
|
95152eebd7 | ||
|
1ffbd61162 | ||
|
47e205b988 | ||
|
00f273ff3c | ||
|
3c2f9fe4e1 | ||
|
93b4c0e9d7 | ||
|
bb2896aefe | ||
|
bcd319df05 | ||
|
6a9b2a7e59 | ||
|
d308996fed | ||
|
6c6baaec71 | ||
|
82e6d62076 | ||
|
c724392c36 | ||
|
b84739162c | ||
|
25158bc2c2 | ||
|
eb1d80304e | ||
|
707a3a1783 | ||
|
0c4d2a577e | ||
|
a84925fd19 | ||
|
f92d6aaf54 | ||
|
c5f1194bca | ||
|
be14df7c7a | ||
|
83fb02bf09 | ||
|
fd3793b812 | ||
|
617ee4491c | ||
|
6605472329 | ||
|
3be4ac76a9 | ||
|
cbbf80bb44 | ||
|
3e70d2efad | ||
|
9d9218cf77 | ||
|
e21486e7b2 | ||
|
10459281f7 | ||
|
a9f257b058 | ||
|
e429fb9915 | ||
|
3dc8ae3245 | ||
|
b4c386b069 | ||
|
43a8304aa9 | ||
|
54e8807c2c | ||
|
74993334c5 | ||
|
fcfe1ea641 | ||
|
82e3a4334b | ||
|
f55240d759 | ||
|
da2e185204 | ||
|
185d28f2b6 | ||
|
7156caed81 |
126 changed files with 14214 additions and 3410 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
|
10
.gitignore
vendored
Normal file
10
.gitignore
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
/nbproject
|
||||
*.idea
|
||||
*.settings
|
||||
*.buildpath
|
||||
*.project
|
||||
/vendor
|
||||
/www
|
||||
/bin
|
||||
.env
|
||||
composer.lock
|
182
CHANGELOG.md
Normal file
182
CHANGELOG.md
Normal file
|
@ -0,0 +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
|
||||
* 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
|
||||
* 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
|
||||
* 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
|
||||
* 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
|
||||
* 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
|
||||
* 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
|
||||
* Added the ability to work on 3 API versions (v3, v4, v5)
|
||||
* Added compatibility with Opencart 3.0
|
39
Changelog.md
39
Changelog.md
|
@ -1,39 +0,0 @@
|
|||
Changelog
|
||||
=========
|
||||
|
||||
####v0.3.0
|
||||
|
||||
* Расширена библиотека клиента
|
||||
* Добавлена возможность кастомизации моделей заказа через vqmod
|
||||
* Устранены мелкие баги, проведен рефакторинг кода.
|
||||
|
||||
|
||||
####v0.2.0
|
||||
|
||||
Общие изменения
|
||||
|
||||
* Код приведен в состоянии совместимости с PHP 5.2
|
||||
* Убрана необходимость собирать пакет через composer
|
||||
* Библиотека api-client-php обновлена до последней версии и добавлена в стандартную поставку
|
||||
* Переименованы методы, пути и значения ключей конфигурации в связи с ребрендингом
|
||||
* Временая метка последнего запуска получения истории перенесена в таблицу конфигурации БД
|
||||
|
||||
Выгрузка каталога (ICML)
|
||||
|
||||
* Генерация обновлена в соответствии с последними измениями формата файла выгрузки
|
||||
* Генерация вынесена в отдельный класс
|
||||
* Добавлена возможность добавлять подкатегории
|
||||
* Скорректировано указание активности офера
|
||||
* Убрана генерация размера офера вследствие кастомизации этого параметра в разных магазинах
|
||||
|
||||
####v0.1.1
|
||||
* Устранена ошибка редактирования, при которой терялась часть данных при получении истории из CRM
|
||||
* Оптимизирован код получения и обработки истории заказов
|
||||
* Актуализированы переводы
|
||||
|
||||
####v.0.1
|
||||
* Реализован интерфейс настроек модуля
|
||||
* Реализована отправка данных о заказе/клиенте в CRM
|
||||
* Реализована выгрузка каталога (cron only)
|
||||
* Реализовано получение данных о заказах, сделанных на стороне CRM (cron only)
|
||||
|
4
LICENSE
4
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
|
||||
|
@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
THE SOFTWARE
|
49
Makefile
Normal file
49
Makefile
Normal file
|
@ -0,0 +1,49 @@
|
|||
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
|
||||
|
||||
build_archive:
|
||||
zip -r $(ARCHIVE_NAME) ./src/*
|
||||
|
||||
send_to_ftp:
|
||||
curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)
|
||||
|
||||
delete_archive:
|
||||
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
|
98
README.md
98
README.md
|
@ -1,96 +1,74 @@
|
|||
[](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 with [retailCRM](http://retailcrm.pro)
|
||||
This module allows to integrate CMS Opencart >= 2.3 with [RetailCRM](https://retailcrm.pro).
|
||||
|
||||
### Previous versions:
|
||||
|
||||
[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)
|
||||
|
||||
#### 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
|
||||
|
||||
#### Export orders to retailCRM (for opencart 1.5.x, for version 2.x this step is unnecessary)
|
||||
|
||||
##### VQmod
|
||||
|
||||
Copy _retailcrm_create_order.xml_ into _/path/to/site/root/vqmod/xml_.
|
||||
|
||||
For VQmod cache renewal you may need to delete files _/path/to/site/root/vqmod/vqcache/vq2-admin_model_sale_order.php_ & _/path/to/site/root/vqmod/vqcache/vq2-catalog_model_checkout_order.php_
|
||||
|
||||
##### Manual setup
|
||||
|
||||
In the file:
|
||||
|
||||
```
|
||||
/catalog/model/checkout/order.php
|
||||
```
|
||||
|
||||
add theese lines into addOrder method right before return statement:
|
||||
|
||||
```php
|
||||
$this->load->model('retailcrm/order');
|
||||
$this->model_retailcrm_order->sendToCrm($data, $order_id);
|
||||
```
|
||||
|
||||
In the file:
|
||||
|
||||
```
|
||||
/admin/model/sale/order.php
|
||||
```
|
||||
|
||||
add theese lines into addOrder & editOrder methods right before return statement:
|
||||
|
||||
```php
|
||||
if (!isset($data['fromApi'])) {
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if (!empty($data['order_status_id'])) {
|
||||
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->load->model('retailcrm/order');
|
||||
if (isset ($order_query)) {
|
||||
$this->model_retailcrm_order->changeInCrm($data, $order_id);
|
||||
} else {
|
||||
$this->model_retailcrm_order->sendToCrm($data, $order_id);
|
||||
}
|
||||
}
|
||||
```
|
||||
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/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/export.php >> /path/to/opencart/system/logs/cronjob_export.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
|
||||
|
||||
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.
|
||||
|
|
99
README.ru.md
99
README.ru.md
|
@ -1,99 +0,0 @@
|
|||
Opencart module
|
||||
===============
|
||||
|
||||
Модуль интеграции CMS Openacart c [RetailCRM](http://retailcrm.ru)
|
||||
|
||||
#### Модуль позволяет:
|
||||
|
||||
* Экспортировать в CRM данные о заказах и клиентах и получать обратно изменения по этим данным
|
||||
* Синхронизировать справочники (способы доставки и оплаты, статусы заказов и т.п.)
|
||||
* Выгружать каталог товаров в формате [ICML](http://www.retailcrm.ru/docs/Developers/ICML)
|
||||
|
||||
#### Установка
|
||||
|
||||
Установите модуль скопировав необходимые файлы в корень сайта
|
||||
|
||||
```
|
||||
unzip master.zip
|
||||
cp -r opencart-module/* /path/to/site/root
|
||||
```
|
||||
|
||||
#### Активируйте модуль
|
||||
|
||||
В списке модулей нажмите "Установить"
|
||||
|
||||
#### Настройте параметры интеграции
|
||||
|
||||
На странице настроек модуля укажите URL Вашей CRM и ключ авторизации, после сохранения этих данных укажите соответствия справочников типов доставок, оплат и статусов заказа.
|
||||
|
||||
|
||||
#### Выгрузка новых заказов в CRM (для версии opencart 1.5.x.x, для версии 2.0 и старше не требуется)
|
||||
|
||||
##### VQmod
|
||||
|
||||
Скопируйте файл _retailcrm_create_order.xml_ в _/path/to/site/root/vqmod/xml_.
|
||||
|
||||
Для обновления кеша VQmod может потрбоваться удалить файлы _/path/to/site/root/vqmod/vqcache/vq2-admin_model_sale_order.php_ и _/path/to/site/root/vqmod/vqcache/vq2-catalog_model_checkout_order.php_
|
||||
|
||||
##### Ручная установка
|
||||
|
||||
В файле:
|
||||
|
||||
```
|
||||
/catalog/model/checkout/order.php
|
||||
```
|
||||
|
||||
Добавьте следующие строки в метод addOrder непосредственно перед языковой конструкцией return:
|
||||
|
||||
```php
|
||||
$this->load->model('retailcrm/order');
|
||||
$this->model_retailcrm_order->sendToCrm($data, $order_id);
|
||||
```
|
||||
|
||||
В файле:
|
||||
|
||||
```
|
||||
/admin/model/sale/order.php
|
||||
```
|
||||
|
||||
Добавьте следующие строки в методы addOrder и editOrder в самом конце каждого метода:
|
||||
|
||||
```php
|
||||
if (!isset($data['fromApi'])) {
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if (!empty($data['order_status_id'])) {
|
||||
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->load->model('retailcrm/order');
|
||||
if (isset ($order_query)) {
|
||||
$this->model_retailcrm_order->changeInCrm($data, $order_id);
|
||||
} else {
|
||||
$this->model_retailcrm_order->sendToCrm($data, $order_id);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Получение измений из CRM
|
||||
|
||||
Для получения изменений и новых данных добавьте в cron следующую запись:
|
||||
|
||||
```
|
||||
*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/logs/cronjob_history.log 2>&1
|
||||
```
|
||||
|
||||
#### Настройка экспорта каталога
|
||||
|
||||
Для периодической выгрузки каталога добавьте в cron следующую запись:
|
||||
|
||||
```
|
||||
* */4 * * * /usr/bin/php /path/to/opencart/system/cron/export.php >> /path/to/opencart/system/logs/cronjob_export.log 2>&1
|
||||
```
|
||||
|
||||
В настройках CRM установите путь к файлу выгрузки
|
||||
|
||||
```
|
||||
http://youropencartsite.com/retailcrm.xml
|
||||
```
|
1
VERSION
Normal file
1
VERSION
Normal file
|
@ -0,0 +1 @@
|
|||
4.1.19
|
|
@ -1,321 +0,0 @@
|
|||
<?php
|
||||
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.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/ApiVersion3
|
||||
*/
|
||||
class ControllerModuleRetailcrm extends Controller
|
||||
{
|
||||
private $_error = array();
|
||||
protected $log, $statuses, $payments, $deliveryTypes, $retailcrm;
|
||||
public $children, $template;
|
||||
|
||||
/**
|
||||
* Install method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function install()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$this->model_setting_setting
|
||||
->editSetting('retailcrm', array('retailcrm_status' => 1));
|
||||
|
||||
if (version_compare(VERSION, '2.0.1.0', '>')) {
|
||||
$this->load->model('extension/event');
|
||||
|
||||
$this->model_extension_event
|
||||
->addEvent(
|
||||
'retailcrm',
|
||||
'post.order.add',
|
||||
'module/retailcrm/order_create'
|
||||
);
|
||||
|
||||
$this->model_extension_event
|
||||
->addEvent(
|
||||
'retailcrm',
|
||||
'post.order.history.add',
|
||||
'module/retailcrm/order_edit'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function uninstall()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$this->model_setting_setting
|
||||
->editSetting('retailcrm', array('retailcrm_status' => 0));
|
||||
|
||||
if (version_compare(VERSION, '2.0.1.0', '>')) {
|
||||
$this->load->model('extension/event');
|
||||
$this->model_extension_event->deleteEvent('retailcrm');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup page
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
|
||||
$this->load->model('setting/setting');
|
||||
if (version_compare(VERSION, '2.0.1.0', '>')) {
|
||||
$this->load->model('extension/module');
|
||||
}
|
||||
$this->load->model('retailcrm/references');
|
||||
$this->load->language('module/retailcrm');
|
||||
$this->document->setTitle($this->language->get('heading_title'));
|
||||
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
|
||||
|
||||
if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
|
||||
$this->model_setting_setting->editSetting(
|
||||
'retailcrm',
|
||||
$this->request->post
|
||||
);
|
||||
|
||||
$this->session->data['success'] = $this->language->get('text_success');
|
||||
$redirect = $this->url->link(
|
||||
'module/retailcrm', 'token=' . $this->session->data['token'],
|
||||
'SSL'
|
||||
);
|
||||
|
||||
if (version_compare(VERSION, '2.0.1.0', '<')) {
|
||||
$this->redirect($redirect);
|
||||
} else {
|
||||
$this->response->redirect($redirect);
|
||||
}
|
||||
}
|
||||
|
||||
$text_strings = array(
|
||||
'heading_title',
|
||||
'text_enabled',
|
||||
'text_disabled',
|
||||
'button_save',
|
||||
'button_cancel',
|
||||
'text_notice',
|
||||
'retailcrm_title',
|
||||
'retailcrm_url',
|
||||
'retailcrm_apikey',
|
||||
'retailcrm_base_settings',
|
||||
'retailcrm_dict_settings',
|
||||
'retailcrm_dict_delivery',
|
||||
'retailcrm_dict_status',
|
||||
'retailcrm_dict_payment',
|
||||
);
|
||||
|
||||
if (version_compare(VERSION, '2.0.1.0', '<')) {
|
||||
$_data = &$this->data;
|
||||
$this->load->model('setting/extension');
|
||||
} else {
|
||||
$this->load->model('extension/extension');
|
||||
$_data = &$data;
|
||||
}
|
||||
|
||||
foreach ($text_strings as $text) {
|
||||
$_data[$text] = $this->language->get($text);
|
||||
}
|
||||
|
||||
$_data['retailcrm_errors'] = array();
|
||||
$_data['saved_settings'] = $this->model_setting_setting
|
||||
->getSetting('retailcrm');
|
||||
|
||||
$url = isset($_data['saved_settings']['retailcrm_url'])
|
||||
? $_data['saved_settings']['retailcrm_url']
|
||||
: null;
|
||||
$key = isset($_data['saved_settings']['retailcrm_apikey'])
|
||||
? $_data['saved_settings']['retailcrm_apikey']
|
||||
: null;
|
||||
|
||||
if (!empty($url) && !empty($key)) {
|
||||
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$url,
|
||||
$key,
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$_data['delivery'] = $this->model_retailcrm_references
|
||||
->getDeliveryTypes();
|
||||
$_data['statuses'] = $this->model_retailcrm_references
|
||||
->getOrderStatuses();
|
||||
$_data['payments'] = $this->model_retailcrm_references
|
||||
->getPaymentTypes();
|
||||
|
||||
}
|
||||
|
||||
$config_data = array(
|
||||
'retailcrm_status'
|
||||
);
|
||||
|
||||
foreach ($config_data as $conf) {
|
||||
if (isset($this->request->post[$conf])) {
|
||||
$_data[$conf] = $this->request->post[$conf];
|
||||
} else {
|
||||
$_data[$conf] = $this->config->get($conf);
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($this->error['warning'])) {
|
||||
$_data['error_warning'] = $this->error['warning'];
|
||||
} else {
|
||||
$_data['error_warning'] = '';
|
||||
}
|
||||
|
||||
$_data['breadcrumbs'] = array();
|
||||
|
||||
$_data['breadcrumbs'][] = array(
|
||||
'text' => $this->language->get('text_home'),
|
||||
'href' => $this->url->link(
|
||||
'common/home',
|
||||
'token=' . $this->session->data['token'], 'SSL'
|
||||
),
|
||||
'separator' => false
|
||||
);
|
||||
|
||||
$_data['breadcrumbs'][] = array(
|
||||
'text' => $this->language->get('text_module'),
|
||||
'href' => $this->url->link(
|
||||
'extension/module',
|
||||
'token=' . $this->session->data['token'], 'SSL'
|
||||
),
|
||||
'separator' => ' :: '
|
||||
);
|
||||
|
||||
$_data['breadcrumbs'][] = array(
|
||||
'text' => $this->language->get('retailcrm_title'),
|
||||
'href' => $this->url->link(
|
||||
'module/retailcrm',
|
||||
'token=' . $this->session->data['token'], 'SSL'
|
||||
),
|
||||
'separator' => ' :: '
|
||||
);
|
||||
|
||||
$_data['action'] = $this->url->link(
|
||||
'module/retailcrm',
|
||||
'token=' . $this->session->data['token'], 'SSL'
|
||||
);
|
||||
|
||||
$_data['cancel'] = $this->url->link(
|
||||
'extension/module',
|
||||
'token=' . $this->session->data['token'], 'SSL'
|
||||
);
|
||||
|
||||
$_data['modules'] = array();
|
||||
|
||||
if (isset($this->request->post['retailcrm_module'])) {
|
||||
$_data['modules'] = $this->request->post['retailcrm_module'];
|
||||
} elseif ($this->config->get('retailcrm_module')) {
|
||||
$_data['modules'] = $this->config->get('retailcrm_module');
|
||||
}
|
||||
|
||||
$this->load->model('design/layout');
|
||||
$_data['layouts'] = $this->model_design_layout->getLayouts();
|
||||
|
||||
if (version_compare(VERSION, '2.0.1.0', '<')) {
|
||||
$this->template = 'module/retailcrm.1.x.tpl';
|
||||
$this->children = array(
|
||||
'common/header',
|
||||
'common/footer',
|
||||
);
|
||||
|
||||
$this->response->setOutput($this->render());
|
||||
} else {
|
||||
$_data['header'] = $this->load->controller('common/header');
|
||||
$_data['column_left'] = $this->load->controller('common/column_left');
|
||||
$_data['footer'] = $this->load->controller('common/footer');
|
||||
|
||||
$this->response->setOutput(
|
||||
$this->load->view('module/retailcrm.2.x.tpl', $_data)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* History method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function history()
|
||||
{
|
||||
if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/history.php')) {
|
||||
$this->load->model('retailcrm/custom/history');
|
||||
$this->model_retailcrm_custom_history->request();
|
||||
} else {
|
||||
$this->load->model('retailcrm/history');
|
||||
$this->model_retailcrm_history->request();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ICML generation
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function icml()
|
||||
{
|
||||
if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/icml.php')) {
|
||||
$this->load->model('retailcrm/custom/icml');
|
||||
$this->model_retailcrm_custom_icml->generateICML();
|
||||
} else {
|
||||
$this->load->model('retailcrm/icml');
|
||||
$this->model_retailcrm_icml->generateICML();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create order on event
|
||||
*
|
||||
* @param int $order_id order identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function order_create($order_id)
|
||||
{
|
||||
$this->load->model('checkout/order');
|
||||
$this->load->model('account/order');
|
||||
|
||||
$data = $this->model_checkout_order->getOrder($order_id);
|
||||
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
|
||||
|
||||
if (!isset($data['fromApi'])) {
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting('retailcrm');
|
||||
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
|
||||
|
||||
$this->load->model('retailcrm/order');
|
||||
$this->model_retailcrm_order->sendToCrm($data, $data['order_id']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function validate()
|
||||
{
|
||||
if (!$this->user->hasPermission('modify', 'module/retailcrm')) {
|
||||
$this->_error['warning'] = $this->language->get('error_permission');
|
||||
}
|
||||
|
||||
if (!$this->_error) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Modules';
|
||||
$_['text_success'] = 'Setting saved';
|
||||
$_['text_notice'] = 'Warning! Timezone in CRM & your shop must be equal, you must setup it here:';
|
||||
$_['retailcrm_base_settings'] = 'Connection settings';
|
||||
$_['retailcrm_dict_settings'] = 'Dictionary settings';
|
||||
|
||||
$_['retailcrm_url'] = 'RetailCRM URL';
|
||||
$_['retailcrm_apikey'] = 'RetailCRM API Key';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Shipment methods';
|
||||
$_['retailcrm_dict_status'] = 'Order statuses';
|
||||
$_['retailcrm_dict_payment'] = 'Payment methods';
|
||||
|
||||
$_['column_total'] = 'Total';
|
||||
$_['product_summ'] = 'Amount';
|
||||
|
||||
$_['article'] = 'SKU';
|
||||
$_['color'] = 'Color';
|
||||
$_['weight'] = 'Weight';
|
||||
$_['size'] = 'Size';
|
||||
|
||||
// Errors
|
||||
$_['error_permission'] = 'Warning! You do not have permission to modify module';
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Модули';
|
||||
$_['text_success'] = 'Настройки успешно сохранены';
|
||||
$_['text_notice'] = 'Внимание! Часовой пояс в CRM должен совпадать с часовым поясом в магазине, настроки часового пояса CRM можно задать по адресу:';
|
||||
$_['retailcrm_base_settings'] = 'Настройки соединения';
|
||||
$_['retailcrm_dict_settings'] = 'Настройки соответствия справочников';
|
||||
|
||||
$_['retailcrm_url'] = 'Адрес RetailCRM';
|
||||
$_['retailcrm_apikey'] = 'Api ключ RetailCRM';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Способы доставки';
|
||||
$_['retailcrm_dict_status'] = 'Статусы';
|
||||
$_['retailcrm_dict_payment'] = 'Способы оплаты';
|
||||
|
||||
$_['column_total'] = 'Итого';
|
||||
$_['product_summ'] = 'Сумма';
|
||||
|
||||
$_['article'] = 'Артикул';
|
||||
$_['color'] = 'Цвет';
|
||||
$_['weight'] = 'Вес';
|
||||
$_['size'] = 'Размер';
|
||||
|
||||
// Errors
|
||||
$_['error_permission'] = 'У вас недостаточно прав на изменение настроек модуля';
|
||||
|
|
@ -1,458 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelRetailcrmHistory extends Model
|
||||
{
|
||||
protected $createResult;
|
||||
|
||||
private $opencartApiClient;
|
||||
|
||||
public function request()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('setting/store');
|
||||
if(version_compare(VERSION, '2.0.0', '>=')) {
|
||||
$this->load->model('user/api');
|
||||
}
|
||||
$this->load->model('sale/order');
|
||||
if (version_compare(VERSION, '2.1.0.0', '>=')) {
|
||||
$this->load->model('customer/customer');
|
||||
} else {
|
||||
$this->load->model('sale/customer');
|
||||
}
|
||||
$this->load->model('retailcrm/references');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('localisation/zone');
|
||||
|
||||
$this->load->language('module/retailcrm');
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
$history = $this->model_setting_setting->getSetting('retailcrm_history');
|
||||
$settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
|
||||
|
||||
$url = isset($settings['retailcrm_url']) ? $settings['retailcrm_url'] : null;
|
||||
$key = isset($settings['retailcrm_apikey']) ? $settings['retailcrm_apikey'] : null;
|
||||
|
||||
if (empty($url) || empty($key)) {
|
||||
$this->log->addNotice('You need to configure retailcrm module first.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if(version_compare(VERSION, '2.0.0', '>=')) {
|
||||
$this->opencartApiClient = new OpencartApiClient($this->registry);
|
||||
}
|
||||
|
||||
$crm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$lastRun = !empty($history['retailcrm_history'])
|
||||
? new DateTime($history['retailcrm_history'])
|
||||
: new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))));
|
||||
|
||||
$orders = $crm->ordersHistory($lastRun);
|
||||
$generatedAt = $orders['generatedAt'];
|
||||
|
||||
$this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total');
|
||||
$this->totalSettings = $this->model_setting_setting->getSetting('total');
|
||||
$this->shippingSettings = $this->model_setting_setting->getSetting('shipping');
|
||||
|
||||
$this->delivery = array_flip($settings['retailcrm_delivery']);
|
||||
$this->payment = array_flip($settings['retailcrm_payment']);
|
||||
$this->status = array_flip($settings['retailcrm_status']);
|
||||
|
||||
$this->ocPayment = $this->model_retailcrm_references
|
||||
->getOpercartPaymentTypes();
|
||||
|
||||
$this->ocDelivery = $this->model_retailcrm_references
|
||||
->getOpercartDeliveryTypes();
|
||||
|
||||
$this->zones = $this->model_localisation_zone->getZones();
|
||||
|
||||
$updatedOrders = array();
|
||||
$newOrders = array();
|
||||
|
||||
foreach ($orders['orders'] as $order) {
|
||||
|
||||
if (isset($order['deleted'])) continue;
|
||||
|
||||
if (isset($order['externalId'])) {
|
||||
$updatedOrders[] = $order['id'];
|
||||
} else {
|
||||
$newOrders[] = $order['id'];
|
||||
}
|
||||
}
|
||||
|
||||
unset($orders);
|
||||
|
||||
if (!empty($newOrders)) {
|
||||
$orders = $crm->ordersList($filter = array('ids' => $newOrders));
|
||||
if ($orders) {
|
||||
$this->createResult = $this->createOrders($orders['orders']);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($updatedOrders)) {
|
||||
$orders = $crm->ordersList($filter = array('ids' => $updatedOrders));
|
||||
if ($orders) {
|
||||
$this->updateOrders($orders['orders']);
|
||||
}
|
||||
}
|
||||
|
||||
$this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt));
|
||||
|
||||
if (!empty($this->createResult['customers'])) {
|
||||
$crm->customersFixExternalIds($this->createResult['customers']);
|
||||
}
|
||||
|
||||
if (!empty($this->createResult['orders'])) {
|
||||
$crm->ordersFixExternalIds($this->createResult['orders']);
|
||||
}
|
||||
}
|
||||
|
||||
protected function updateOrders($orders)
|
||||
{
|
||||
foreach ($orders as $order) {
|
||||
$store = $this->config->get('config_store_id');
|
||||
|
||||
$data = array();
|
||||
|
||||
$data['store_id'] = $store == null ? 0 : $store;
|
||||
$data['customer'] = $order['firstName'];
|
||||
$data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0;
|
||||
$data['customer_group_id'] = 1;
|
||||
$data['firstname'] = $order['firstName'];
|
||||
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$data['email'] = $order['email'];
|
||||
$data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : '';
|
||||
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
|
||||
$data['fax'] = '';
|
||||
|
||||
$data['payment_address'] = '0';
|
||||
$data['payment_firstname'] = $order['firstName'];
|
||||
$data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$data['payment_address_1'] = isset($order['customer']['address']) ? $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'];
|
||||
|
||||
$region = '';
|
||||
|
||||
if (is_int($order['delivery']['address']['region'])) {
|
||||
$region = $order['delivery']['address']['region'];
|
||||
} else {
|
||||
foreach ($this->zones as $zone) {
|
||||
if ($order['delivery']['address']['region'] == $zone['name']) {
|
||||
$region = $zone['zone_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0;
|
||||
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region;
|
||||
|
||||
$data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0;
|
||||
$data['shipping_zone_id'] = $region;
|
||||
|
||||
$data['shipping_address'] = '0';
|
||||
$data['shipping_firstname'] = $order['firstName'];
|
||||
$data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$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'] = $this->delivery[$order['delivery']['code']];
|
||||
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
|
||||
$data['shipping_code'] = $this->delivery[$order['delivery']['code']];
|
||||
|
||||
$data['payment'] = $this->payment[$order['paymentType']];
|
||||
$data['payment_method'] = $this->ocPayment[$data['payment']];
|
||||
$data['payment_code'] = $this->payment[$order['paymentType']];
|
||||
|
||||
// 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();
|
||||
|
||||
foreach ($order['items'] as $item) {
|
||||
$product = $this->model_catalog_product->getProduct($item['offer']['externalId']);
|
||||
$data['order_product'][] = array(
|
||||
'product_id' => $item['offer']['externalId'],
|
||||
'name' => $item['offer']['name'],
|
||||
'quantity' => $item['quantity'],
|
||||
'price' => $item['initialPrice'],
|
||||
'total' => $item['initialPrice'] * $item['quantity'],
|
||||
'model' => $product['model'],
|
||||
|
||||
// this data will not retrive from crm
|
||||
'order_product_id' => '',
|
||||
'tax' => 0,
|
||||
'reward' => 0
|
||||
);
|
||||
}
|
||||
|
||||
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
|
||||
|
||||
$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' => $this->ocDelivery[$data['shipping_code']],
|
||||
'value' => $deliveryCost,
|
||||
'text' => $deliveryCost,
|
||||
'sort_order' => $this->shippingSettings['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['total_sort_order']
|
||||
)
|
||||
);
|
||||
|
||||
$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'];
|
||||
}
|
||||
|
||||
if(version_compare(VERSION, '2.0.0', '>=')) {
|
||||
$this->opencartApiClient->editOrder($order['externalId'], $data);
|
||||
} else {
|
||||
$this->model_sale_order->editOrder($order['externalId'], $data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function createOrders($orders)
|
||||
{
|
||||
$customersIdsFix = array();
|
||||
$ordersIdsFix = array();
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$store = $this->config->get('config_store_id');
|
||||
|
||||
$customer_id = (!empty($order['customer']['externalId']))
|
||||
? $order['customer']['externalId']
|
||||
: 0;
|
||||
|
||||
$data = array();
|
||||
|
||||
if ($customer_id == 0) {
|
||||
$cData = array(
|
||||
'store_id' => 0,
|
||||
'customer_group_id' => '1',
|
||||
'firstname' => $order['firstName'],
|
||||
'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ',
|
||||
'email' => $order['email'],
|
||||
'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ',
|
||||
'fax' => '',
|
||||
'newsletter' => 0,
|
||||
'password' => 'tmppass',
|
||||
'status' => 1,
|
||||
'address' => array(
|
||||
array(
|
||||
'firstname' => $order['firstName'],
|
||||
'lastname' => (!empty($order['lastName'])) ? $order['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' => '0',
|
||||
'country_id' => 0
|
||||
)
|
||||
),
|
||||
);
|
||||
|
||||
if (version_compare(VERSION, '2.1.0.0', '>=')) {
|
||||
$this->model_customer_customer->addCustomer($cData);
|
||||
} else {
|
||||
$this->model_sale_customer->addCustomer($cData);
|
||||
}
|
||||
|
||||
if (!empty($order['email'])) {
|
||||
if (version_compare(VERSION, '2.1.0.0', '>=')) {
|
||||
$tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']);
|
||||
} else {
|
||||
$tryToFind = $this->model_sale_customer->getCustomerByEmail($order['email']);
|
||||
}
|
||||
$customer_id = $tryToFind['customer_id'];
|
||||
} else {
|
||||
if (version_compare(VERSION, '2.1.0.0', '>=')) {
|
||||
$last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1));
|
||||
} else {
|
||||
$last = $this->model_sale_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1));
|
||||
}
|
||||
$customer_id = $last[0]['customer_id'];
|
||||
}
|
||||
|
||||
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id);
|
||||
}
|
||||
|
||||
$data['store_id'] = $store == null ? 0 : $store;
|
||||
$data['customer'] = $order['firstName'];
|
||||
$data['customer_id'] = $customer_id;
|
||||
$data['customer_group_id'] = 1;
|
||||
$data['firstname'] = $order['firstName'];
|
||||
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$data['email'] = $order['email'];
|
||||
$data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' ';
|
||||
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
|
||||
$data['fax'] = '';
|
||||
$data['payment_address'] = '0';
|
||||
$data['payment_firstname'] = $order['firstName'];
|
||||
$data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$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'];
|
||||
|
||||
$region = '';
|
||||
|
||||
if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) {
|
||||
$region = $order['delivery']['address']['region'];
|
||||
} else {
|
||||
foreach ($this->zones as $zone) {
|
||||
if ($order['delivery']['address']['region'] == $zone['name']) {
|
||||
$region = $zone['zone_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0;
|
||||
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region;
|
||||
$data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0;
|
||||
$data['shipping_zone_id'] = $region;
|
||||
$data['shipping_address'] = '0';
|
||||
$data['shipping_firstname'] = $order['firstName'];
|
||||
$data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
|
||||
$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'] = $this->delivery[$order['delivery']['code']];
|
||||
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
|
||||
$data['shipping_code'] = $this->delivery[$order['delivery']['code']];
|
||||
$data['payment'] = $this->payment[$order['paymentType']];
|
||||
$data['payment_method'] = $this->ocPayment[$data['payment']];
|
||||
$data['payment_code'] = $this->payment[$order['paymentType']];
|
||||
|
||||
// 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();
|
||||
|
||||
foreach ($order['items'] as $item) {
|
||||
$product = $this->model_catalog_product->getProduct($item['offer']['externalId']);
|
||||
$data['order_product'][] = array(
|
||||
'product_id' => $item['offer']['externalId'],
|
||||
'name' => $item['offer']['name'],
|
||||
'quantity' => $item['quantity'],
|
||||
'price' => $item['initialPrice'],
|
||||
'total' => $item['initialPrice'] * $item['quantity'],
|
||||
'model' => $product['model'],
|
||||
|
||||
// this data will not retrive from crm
|
||||
'order_product_id' => '',
|
||||
'tax' => 0,
|
||||
'reward' => 0
|
||||
);
|
||||
}
|
||||
|
||||
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
|
||||
|
||||
$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' => $this->ocDelivery[$data['shipping_code']],
|
||||
'value' => $deliveryCost,
|
||||
'text' => $deliveryCost,
|
||||
'sort_order' => $this->shippingSettings['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['total_sort_order']
|
||||
)
|
||||
);
|
||||
|
||||
$data['fromApi'] = true;
|
||||
$data['order_status_id'] = 1;
|
||||
|
||||
if(version_compare(VERSION, '2.0.0', '>=')) {
|
||||
$this->opencartApiClient->addOrder($data);
|
||||
} else {
|
||||
$this->model_sale_order->addOrder($data);
|
||||
}
|
||||
|
||||
$last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0));
|
||||
|
||||
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']);
|
||||
}
|
||||
|
||||
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
|
||||
}
|
||||
}
|
|
@ -1,217 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelRetailcrmIcml extends Model
|
||||
{
|
||||
protected $shop;
|
||||
protected $file;
|
||||
protected $properties;
|
||||
protected $params;
|
||||
protected $dd;
|
||||
protected $eCategories;
|
||||
protected $eOffers;
|
||||
|
||||
public function generateICML()
|
||||
{
|
||||
$this->load->language('module/retailcrm');
|
||||
$this->load->model('catalog/category');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('catalog/manufacturer');
|
||||
|
||||
$string = '<?xml version="1.0" encoding="UTF-8"?>
|
||||
<yml_catalog date="'.date('Y-m-d H:i:s').'">
|
||||
<shop>
|
||||
<name>'.$this->config->get('config_name').'</name>
|
||||
<categories/>
|
||||
<offers/>
|
||||
</shop>
|
||||
</yml_catalog>
|
||||
';
|
||||
|
||||
$xml = new SimpleXMLElement(
|
||||
$string,
|
||||
LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
|
||||
);
|
||||
|
||||
$this->dd = new DOMDocument();
|
||||
$this->dd->preserveWhiteSpace = false;
|
||||
$this->dd->formatOutput = true;
|
||||
$this->dd->loadXML($xml->asXML());
|
||||
|
||||
$this->eCategories = $this->dd
|
||||
->getElementsByTagName('categories')->item(0);
|
||||
$this->eOffers = $this->dd
|
||||
->getElementsByTagName('offers')->item(0);
|
||||
|
||||
$this->addCategories();
|
||||
$this->addOffers();
|
||||
|
||||
$this->dd->saveXML();
|
||||
|
||||
$downloadPath = DIR_SYSTEM . '/../';
|
||||
|
||||
if (!file_exists($downloadPath)) {
|
||||
mkdir($downloadPath, 0755);
|
||||
}
|
||||
|
||||
$this->dd->save($downloadPath . 'retailcrm.xml');
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private function addCategories()
|
||||
{
|
||||
$categories = $this->model_catalog_category->getCategories(array());
|
||||
foreach($categories as $category) {
|
||||
$category = $this->model_catalog_category->getCategory($category['category_id']);
|
||||
|
||||
$e = $this->eCategories->appendChild(
|
||||
$this->dd->createElement(
|
||||
'category', $category['name']
|
||||
)
|
||||
);
|
||||
|
||||
$e->setAttribute('id', $category['category_id']);
|
||||
|
||||
if ($category['parent_id'] > 0) {
|
||||
$e->setAttribute('parentId', $category['parent_id']);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function addOffers()
|
||||
{
|
||||
$offerManufacturers = array();
|
||||
|
||||
$manufacturers = $this->model_catalog_manufacturer
|
||||
->getManufacturers(array());
|
||||
|
||||
foreach ($manufacturers as $manufacturer) {
|
||||
$offerManufacturers[
|
||||
$manufacturer['manufacturer_id']
|
||||
] = $manufacturer['name'];
|
||||
}
|
||||
|
||||
$products = $this->model_catalog_product->getProducts(array());
|
||||
|
||||
foreach ($products as $offer) {
|
||||
|
||||
$e = $this->eOffers->appendChild($this->dd->createElement('offer'));
|
||||
$e->setAttribute('id', $offer['product_id']);
|
||||
$e->setAttribute('productId', $offer['product_id']);
|
||||
$e->setAttribute('quantity', $offer['quantity']);
|
||||
|
||||
/**
|
||||
* Offer activity
|
||||
*/
|
||||
$activity = $offer['status'] == 1 ? 'Y' : 'N';
|
||||
$e->appendChild(
|
||||
$this->dd->createElement('productActivity')
|
||||
)->appendChild(
|
||||
$this->dd->createTextNode($activity)
|
||||
);
|
||||
|
||||
/**
|
||||
* Offer categories
|
||||
*/
|
||||
$categories = $this->model_catalog_product
|
||||
->getProductCategories($offer['product_id']);
|
||||
|
||||
if (!empty($categories)) {
|
||||
foreach ($categories as $category) {
|
||||
$e->appendChild($this->dd->createElement('categoryId'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode($category)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Name & price
|
||||
*/
|
||||
$e->appendChild($this->dd->createElement('name'))
|
||||
->appendChild($this->dd->createTextNode($offer['name']));
|
||||
$e->appendChild($this->dd->createElement('productName'))
|
||||
->appendChild($this->dd->createTextNode($offer['name']));
|
||||
$e->appendChild($this->dd->createElement('price'))
|
||||
->appendChild($this->dd->createTextNode($offer['price']));
|
||||
|
||||
/**
|
||||
* Vendor
|
||||
*/
|
||||
if ($offer['manufacturer_id'] != 0) {
|
||||
$e->appendChild($this->dd->createElement('vendor'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode(
|
||||
$offerManufacturers[$offer['manufacturer_id']]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
if ($offer['image']) {
|
||||
$image = $this->generateImage($offer['image']);
|
||||
$e->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'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode(
|
||||
$this->url->link(
|
||||
'product/product&product_id=' . $offer['product_id']
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
if ($offer['sku']) {
|
||||
$sku = $this->dd->createElement('param');
|
||||
$sku->setAttribute('code', 'article');
|
||||
$sku->setAttribute('name', $this->language->get('article'));
|
||||
$sku->appendChild($this->dd->createTextNode($offer['sku']));
|
||||
$e->appendChild($sku);
|
||||
}
|
||||
|
||||
if ($offer['weight'] != '') {
|
||||
$weight = $this->dd->createElement('param');
|
||||
$weight->setAttribute('code', 'weight');
|
||||
$weight->setAttribute('name', $this->language->get('weight'));
|
||||
$weightValue = (isset($offer['weight_class']))
|
||||
? round($offer['weight'], 3) . ' ' . $offer['weight_class']
|
||||
: round($offer['weight'], 3)
|
||||
;
|
||||
$weight->appendChild($this->dd->createTextNode($weightValue));
|
||||
$e->appendChild($weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $image
|
||||
* @return mixed
|
||||
*/
|
||||
private function generateImage($image)
|
||||
{
|
||||
$this->load->model('tool/image');
|
||||
|
||||
return $this->model_tool_image->resize(
|
||||
$image,
|
||||
$this->config->get('config_image_product_width'),
|
||||
$this->config->get('config_image_product_height')
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,174 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelRetailcrmOrder extends Model {
|
||||
|
||||
public function sendToCrm($order_data, $order_id)
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$order = array();
|
||||
|
||||
$customers = $this->retailcrm->customersList(
|
||||
array(
|
||||
'name' => $order_data['telephone'],
|
||||
'email' => $order_data['email']
|
||||
),
|
||||
1,
|
||||
100
|
||||
);
|
||||
|
||||
foreach($customers['customers'] as $customer) {
|
||||
$order['customer']['id'] = $customer['id'];
|
||||
}
|
||||
|
||||
unset($customers);
|
||||
|
||||
$order['externalId'] = $order_id;
|
||||
$order['firstName'] = $order_data['firstname'];
|
||||
$order['lastName'] = $order_data['lastname'];
|
||||
$order['email'] = $order_data['email'];
|
||||
$order['phone'] = $order_data['telephone'];
|
||||
$order['customerComment'] = $order_data['comment'];
|
||||
|
||||
$deliveryCost = 0;
|
||||
$altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : "";
|
||||
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ;
|
||||
|
||||
if (!empty($orderTotals)) {
|
||||
foreach ($orderTotals as $totals) {
|
||||
if ($totals['code'] == 'shipping') {
|
||||
$deliveryCost = $totals['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$order['createdAt'] = date('Y-m-d H:i:s');
|
||||
|
||||
$payment_code = $order_data['payment_code'];
|
||||
$order['paymentType'] = $settings['retailcrm_payment'][$payment_code];
|
||||
|
||||
$delivery_code = $order_data['shipping_code'];
|
||||
$order['delivery'] = array(
|
||||
'code' => $settings['retailcrm_delivery'][$delivery_code],
|
||||
'cost' => $deliveryCost,
|
||||
'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'],
|
||||
(isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '',
|
||||
$order_data['shipping_city'],
|
||||
$order_data['shipping_address_1'],
|
||||
$order_data['shipping_address_2']
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
|
||||
|
||||
foreach ($orderProducts as $product) {
|
||||
$order['items'][] = array(
|
||||
'productId' => $product['product_id'],
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->retailcrm->ordersCreate($order);
|
||||
}
|
||||
}
|
||||
|
||||
public function changeInCrm($order_data, $order_id)
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$order = array();
|
||||
|
||||
$payment_code = $order_data['payment_code'];
|
||||
$delivery_code = $order_data['shipping_code'];
|
||||
|
||||
$order['externalId'] = $order_id;
|
||||
$order['firstName'] = $order_data['firstname'];
|
||||
$order['lastName'] = $order_data['lastname'];
|
||||
$order['email'] = $order_data['email'];
|
||||
$order['phone'] = $order_data['telephone'];
|
||||
$order['customerComment'] = $order_data['comment'];
|
||||
|
||||
$deliveryCost = 0;
|
||||
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
|
||||
|
||||
foreach ($orderTotals as $totals) {
|
||||
if ($totals['code'] == 'shipping') {
|
||||
$deliveryCost = $totals['value'];
|
||||
}
|
||||
}
|
||||
|
||||
$order['createdAt'] = date('Y-m-d H:i:s');
|
||||
$order['paymentType'] = $settings['retailcrm_payment'][$payment_code];
|
||||
|
||||
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
|
||||
|
||||
$order['delivery'] = array(
|
||||
'code' => $settings['retailcrm_delivery'][$delivery_code],
|
||||
'cost' => $deliveryCost,
|
||||
'address' => array(
|
||||
'index' => $order_data['shipping_postcode'],
|
||||
'city' => $order_data['shipping_city'],
|
||||
'country' => $order_data['shipping_country_id'],
|
||||
'region' => $order_data['shipping_zone_id'],
|
||||
'text' => implode(', ', array(
|
||||
$order_data['shipping_postcode'],
|
||||
$country,
|
||||
$order_data['shipping_city'],
|
||||
$order_data['shipping_address_1'],
|
||||
$order_data['shipping_address_2']
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
|
||||
|
||||
foreach ($orderProducts as $product) {
|
||||
$order['items'][] = array(
|
||||
'productId' => $product['product_id'],
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->retailcrm->ordersEdit($order);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,138 +0,0 @@
|
|||
<?php
|
||||
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
class ModelRetailcrmReferences extends Model
|
||||
{
|
||||
protected $retailcrm;
|
||||
|
||||
public function getDeliveryTypes()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartDeliveryTypes(),
|
||||
'retailcrm' => $this->getApiDeliveryTypes()
|
||||
);
|
||||
}
|
||||
|
||||
public function getOrderStatuses()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartOrderStatuses(),
|
||||
'retailcrm' => $this->getApiOrderStatuses()
|
||||
);
|
||||
}
|
||||
|
||||
public function getPaymentTypes()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartPaymentTypes(),
|
||||
'retailcrm' => $this->getApiPaymentTypes()
|
||||
);
|
||||
}
|
||||
|
||||
public function getOpercartDeliveryTypes()
|
||||
{
|
||||
$deliveryMethods = array();
|
||||
$files = glob(DIR_APPLICATION . 'controller/shipping/*.php');
|
||||
|
||||
if ($files) {
|
||||
foreach ($files as $file) {
|
||||
$extension = basename($file, '.php');
|
||||
|
||||
$this->load->language('shipping/' . $extension);
|
||||
|
||||
if ($this->config->get($extension . '_status')) {
|
||||
$deliveryMethods[$extension.'.'.$extension] = strip_tags(
|
||||
$this->language->get('heading_title')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $deliveryMethods;
|
||||
}
|
||||
|
||||
public function getOpercartOrderStatuses()
|
||||
{
|
||||
$this->load->model('localisation/order_status');
|
||||
|
||||
return $this->model_localisation_order_status
|
||||
->getOrderStatuses(array());
|
||||
}
|
||||
|
||||
public function getOpercartPaymentTypes()
|
||||
{
|
||||
$paymentTypes = array();
|
||||
$files = glob(DIR_APPLICATION . 'controller/payment/*.php');
|
||||
|
||||
if ($files) {
|
||||
foreach ($files as $file) {
|
||||
$extension = basename($file, '.php');
|
||||
|
||||
$this->load->language('payment/' . $extension);
|
||||
|
||||
if ($this->config->get($extension . '_status')) {
|
||||
$paymentTypes[$extension] = strip_tags(
|
||||
$this->language->get('heading_title')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $paymentTypes;
|
||||
}
|
||||
|
||||
public function getApiDeliveryTypes()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$response = $this->retailcrm->deliveryTypesList();
|
||||
|
||||
return ($response === false) ? array() : $response->deliveryTypes;
|
||||
}
|
||||
}
|
||||
|
||||
public function getApiOrderStatuses()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$response = $this->retailcrm->statusesList();
|
||||
|
||||
return ($response === false) ? array() : $response->statuses;
|
||||
}
|
||||
}
|
||||
|
||||
public function getApiPaymentTypes()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$response = $this->retailcrm->paymentTypesList();
|
||||
|
||||
return ($response === false) ? array() : $response->paymentTypes;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
.retailcrm_unit {margin-bottom: 10px;}
|
||||
.retailcrm_unit input {width: 30%;}
|
|
@ -1,99 +0,0 @@
|
|||
<?php echo $header; ?>
|
||||
|
||||
<div id="content">
|
||||
<div class="breadcrumb">
|
||||
<?php foreach ($breadcrumbs as $breadcrumb): ?>
|
||||
<?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php if ($error_warning) : ?>
|
||||
<div class="warning"><?php echo $error_warning; ?></div>
|
||||
<?php endif; ?>
|
||||
<?php if (isset($saved_settings['retailcrm_url'])): ?>
|
||||
<div class="success">
|
||||
<?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="box">
|
||||
<div class="heading">
|
||||
<h1><img src="view/image/module.png" alt="" /> <?php echo $heading_title; ?></h1>
|
||||
<div class="buttons"><a onclick="$('#form').submit();" class="button"><span><?php echo $button_save; ?></span></a><a onclick="location = '<?php echo $cancel; ?>';" class="button"><span><?php echo $button_cancel; ?></span></a></div>
|
||||
</div>
|
||||
<div class="content">
|
||||
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form">
|
||||
<input type="hidden" name="retailcrm_status" value="1">
|
||||
|
||||
<h3><?php echo $retailcrm_base_settings; ?></h3>
|
||||
<div class="retailcrm_unit">
|
||||
<label for="retailcrm_url"><?php echo $retailcrm_url; ?></label><br>
|
||||
<input id="retailcrm_url" type="text" name="retailcrm_url" value="<?php if (isset($saved_settings['retailcrm_url'])): echo $saved_settings['retailcrm_url']; endif; ?>">
|
||||
</div>
|
||||
<div class="retailcrm_unit">
|
||||
<label for="retailcrm_apikey"><?php echo $retailcrm_apikey; ?></label><br>
|
||||
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>">
|
||||
</div>
|
||||
|
||||
<?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: ?>
|
||||
<h3><?php echo $retailcrm_dict_settings; ?></h3>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_delivery; ?></h4>
|
||||
<?php foreach ($delivery['opencart'] as $key => $value): ?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_delivery_<?php echo $key; ?>" name="retailcrm_delivery[<?php echo $key; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_delivery_<?php echo $key; ?>"><?php echo $value; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_status; ?></h4>
|
||||
<?php foreach ($statuses['opencart'] as $status): ?>
|
||||
<?php $uid = $status['order_status_id']?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_status_<?php echo $uid; ?>" name="retailcrm_status[<?php echo $uid; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_status_<?php echo $status['order_status_id']; ?>"><?php echo $status['name']; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_payment; ?></h4>
|
||||
<?php foreach ($payments['opencart'] as $key => $value): ?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_payment_<?php echo $key; ?>" name="retailcrm_payment[<?php echo $key; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_payment_<?php echo $key; ?>"><?php echo $value; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php endif; ?>
|
||||
|
||||
<?php endif; ?>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<?php echo $footer; ?>
|
|
@ -1,110 +0,0 @@
|
|||
<?php echo $header; ?>
|
||||
<?php echo $column_left;?>
|
||||
|
||||
<div id="content">
|
||||
<div class="page-header">
|
||||
<div class="container-fluid">
|
||||
<div class="pull-right">
|
||||
<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">
|
||||
<input type="hidden" name="retailcrm_status" value="1">
|
||||
|
||||
<h3><?php echo $retailcrm_base_settings; ?></h3>
|
||||
<div class="retailcrm_unit">
|
||||
<label for="retailcrm_url"><?php echo $retailcrm_url; ?></label><br>
|
||||
<input id="retailcrm_url" type="text" name="retailcrm_url" value="<?php if (isset($saved_settings['retailcrm_url'])): echo $saved_settings['retailcrm_url']; endif; ?>">
|
||||
</div>
|
||||
<div class="retailcrm_unit">
|
||||
<label for="retailcrm_apikey"><?php echo $retailcrm_apikey; ?></label><br>
|
||||
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>">
|
||||
</div>
|
||||
|
||||
<?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: ?>
|
||||
<h3><?php echo $retailcrm_dict_settings; ?></h3>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_delivery; ?></h4>
|
||||
<?php foreach ($delivery['opencart'] as $key => $value): ?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_delivery_<?php echo $key; ?>" name="retailcrm_delivery[<?php echo $key; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_delivery_<?php echo $key; ?>"><?php echo $value; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_status; ?></h4>
|
||||
<?php foreach ($statuses['opencart'] as $status): ?>
|
||||
<?php $uid = $status['order_status_id']?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_status_<?php echo $uid; ?>" name="retailcrm_status[<?php echo $uid; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_status_<?php echo $status['order_status_id']; ?>"><?php echo $status['name']; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<h4><?php echo $retailcrm_dict_payment; ?></h4>
|
||||
<?php foreach ($payments['opencart'] as $key => $value): ?>
|
||||
<div class="retailcrm_unit">
|
||||
<select id="retailcrm_payment_<?php echo $key; ?>" name="retailcrm_payment[<?php echo $key; ?>]" >
|
||||
<?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>
|
||||
<label for="retailcrm_payment_<?php echo $key; ?>"><?php echo $value; ?></label>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?php endif; ?>
|
||||
|
||||
<?php endif; ?>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php echo $footer; ?>
|
|
@ -1,73 +0,0 @@
|
|||
<?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/ApiVersion3
|
||||
*/
|
||||
class ControllerModuleRetailcrm extends Controller
|
||||
{
|
||||
/**
|
||||
* Create order on event
|
||||
*
|
||||
* @param int $order_id order identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function order_create($order_id)
|
||||
{
|
||||
$this->load->model('checkout/order');
|
||||
$this->load->model('account/order');
|
||||
|
||||
$data = $this->model_checkout_order->getOrder($order_id);
|
||||
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
|
||||
|
||||
if (!isset($data['fromApi'])) {
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting('retailcrm');
|
||||
if ($data['order_status_id'] > 0) {
|
||||
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
|
||||
}
|
||||
|
||||
$data['totals'][] = array(
|
||||
'code' => 'shipping',
|
||||
'value' => $this->session->data['shipping_method']['cost']
|
||||
);
|
||||
|
||||
$this->load->model('retailcrm/order');
|
||||
$this->model_retailcrm_order->sendToCrm($data, $data['order_id']);
|
||||
}
|
||||
}
|
||||
|
||||
public function order_edit($order_id) {
|
||||
$this->load->model('checkout/order');
|
||||
$this->load->model('account/order');
|
||||
|
||||
$data = $this->model_checkout_order->getOrder($order_id);
|
||||
|
||||
if($data['order_status_id'] == 0) return;
|
||||
|
||||
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
|
||||
|
||||
if (!isset($data['fromApi'])) {
|
||||
$this->load->model('setting/setting');
|
||||
$status = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if ($data['order_status_id'] > 0) {
|
||||
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
|
||||
}
|
||||
|
||||
$data['totals'][] = array(
|
||||
'code' => 'shipping',
|
||||
'value' => isset($this->session->data['shipping_method']) ? $this->session->data['shipping_method']['cost'] : ''
|
||||
);
|
||||
|
||||
$this->load->model('retailcrm/order');
|
||||
$this->model_retailcrm_order->changeInCrm($data, $data['order_id']);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,186 +0,0 @@
|
|||
<?php
|
||||
|
||||
class ModelRetailcrmOrder extends Model {
|
||||
|
||||
public function sendToCrm($order_data, $order_id)
|
||||
{
|
||||
if(isset($this->request->post['fromApi'])) return;
|
||||
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$order = array();
|
||||
|
||||
$customers = $this->retailcrm->customersList(
|
||||
array(
|
||||
'name' => $order_data['telephone'],
|
||||
'email' => $order_data['email']
|
||||
),
|
||||
1,
|
||||
100
|
||||
);
|
||||
|
||||
foreach($customers['customers'] as $customer) {
|
||||
$order['customer']['id'] = $customer['id'];
|
||||
}
|
||||
|
||||
unset($customers);
|
||||
|
||||
$order['externalId'] = $order_id;
|
||||
$order['firstName'] = $order_data['firstname'];
|
||||
$order['lastName'] = $order_data['lastname'];
|
||||
$order['email'] = $order_data['email'];
|
||||
$order['phone'] = $order_data['telephone'];
|
||||
$order['customerComment'] = $order_data['comment'];
|
||||
|
||||
$deliveryCost = 0;
|
||||
$altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : "";
|
||||
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ;
|
||||
|
||||
if (!empty($orderTotals)) {
|
||||
foreach ($orderTotals as $totals) {
|
||||
if ($totals['code'] == 'shipping') {
|
||||
$deliveryCost = $totals['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$order['createdAt'] = date('Y-m-d H:i:s');
|
||||
|
||||
$payment_code = $order_data['payment_code'];
|
||||
$order['paymentType'] = $settings['retailcrm_payment'][$payment_code];
|
||||
|
||||
// Совместимость с 1.5.5, когда этот метод вызывается из model/checkout/order->createOrder(), а не из controller/module/retailcrm->order_create()
|
||||
if(!isset($order_data['shipping_iso_code_2']) && isset($order_data['shipping_country_id'])) {
|
||||
$this->load->model('localisation/country');
|
||||
$shipping_country = $this->model_localisation_country->getCountry($order_data['shipping_country_id']);
|
||||
$order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2'];
|
||||
}
|
||||
|
||||
|
||||
$delivery_code = $order_data['shipping_code'];
|
||||
$order['delivery'] = array(
|
||||
'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '',
|
||||
'cost' => $deliveryCost,
|
||||
'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'],
|
||||
(isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '',
|
||||
$order_data['shipping_city'],
|
||||
$order_data['shipping_address_1'],
|
||||
$order_data['shipping_address_2']
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
|
||||
|
||||
foreach ($orderProducts as $product) {
|
||||
$order['items'][] = array(
|
||||
'productId' => $product['product_id'],
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->retailcrm->ordersCreate($order);
|
||||
}
|
||||
}
|
||||
|
||||
public function changeInCrm($order_data, $order_id)
|
||||
{
|
||||
if(isset($this->request->post['fromApi'])) return;
|
||||
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
|
||||
if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) {
|
||||
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
|
||||
|
||||
$this->retailcrm = new RetailcrmProxy(
|
||||
$settings['retailcrm_url'],
|
||||
$settings['retailcrm_apikey'],
|
||||
DIR_SYSTEM . 'logs/retailcrm.log'
|
||||
);
|
||||
|
||||
$order = array();
|
||||
|
||||
$payment_code = $order_data['payment_code'];
|
||||
$delivery_code = $order_data['shipping_code'];
|
||||
|
||||
$order['externalId'] = $order_id;
|
||||
$order['firstName'] = $order_data['firstname'];
|
||||
$order['lastName'] = $order_data['lastname'];
|
||||
$order['email'] = $order_data['email'];
|
||||
$order['phone'] = $order_data['telephone'];
|
||||
$order['customerComment'] = $order_data['comment'];
|
||||
|
||||
$deliveryCost = 0;
|
||||
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
|
||||
|
||||
foreach ($orderTotals as $totals) {
|
||||
if ($totals['code'] == 'shipping') {
|
||||
$deliveryCost = $totals['value'];
|
||||
}
|
||||
}
|
||||
|
||||
$order['createdAt'] = date('Y-m-d H:i:s');
|
||||
$order['paymentType'] = $settings['retailcrm_payment'][$payment_code];
|
||||
|
||||
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
|
||||
|
||||
$order['delivery'] = array(
|
||||
'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '',
|
||||
'cost' => $deliveryCost,
|
||||
'address' => array(
|
||||
'index' => $order_data['shipping_postcode'],
|
||||
'city' => $order_data['shipping_city'],
|
||||
'country' => $order_data['shipping_country_id'],
|
||||
'region' => $order_data['shipping_zone_id'],
|
||||
'text' => implode(', ', array(
|
||||
$order_data['shipping_postcode'],
|
||||
$country,
|
||||
$order_data['shipping_city'],
|
||||
$order_data['shipping_address_1'],
|
||||
$order_data['shipping_address_2']
|
||||
))
|
||||
)
|
||||
);
|
||||
|
||||
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
|
||||
|
||||
foreach ($orderProducts as $product) {
|
||||
$order['items'][] = array(
|
||||
'productId' => $product['product_id'],
|
||||
'productName' => $product['name'],
|
||||
'initialPrice' => $product['price'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
}
|
||||
|
||||
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
|
||||
$order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']];
|
||||
}
|
||||
|
||||
$this->retailcrm->ordersEdit($order);
|
||||
}
|
||||
}
|
||||
}
|
38
composer.json
Normal file
38
composer.json
Normal file
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"name": "retailcrm/opencart-module",
|
||||
"description": "Integration module for Opencart & RetailCRM",
|
||||
"license": "GPL-3.0",
|
||||
"type": "project",
|
||||
"authors": [
|
||||
{
|
||||
"name": "RetailDriverLLC",
|
||||
"email": "support@retailcrm.pro"
|
||||
}
|
||||
],
|
||||
"config": {
|
||||
"bin-dir": "bin/",
|
||||
"preferred-install": "source"
|
||||
},
|
||||
"extra": {
|
||||
"opencart-dir" : "www"
|
||||
},
|
||||
"scripts" : {
|
||||
"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-admin",
|
||||
"@test-catalog",
|
||||
"@test-system"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
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"
|
41
phpunit.xml.dist
Normal file
41
phpunit.xml.dist
Normal file
|
@ -0,0 +1,41 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit backupGlobals="false"
|
||||
backupStaticAttributes="false"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
convertErrorsToExceptions="true"
|
||||
convertNoticesToExceptions="true"
|
||||
convertWarningsToExceptions="true"
|
||||
processIsolation="false"
|
||||
stopOnFailure="false"
|
||||
syntaxCheck="false">
|
||||
<testsuites>
|
||||
<testsuite name="catalog-tests">
|
||||
<directory suffix="CatalogTest.php">./tests/catalog/</directory>
|
||||
</testsuite>
|
||||
<testsuite name="admin-tests">
|
||||
<directory suffix="AdminTest.php">./tests/admin/</directory>
|
||||
</testsuite>
|
||||
<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:80/" />
|
||||
<env name="TEST_CONFIG" value="test-config" />
|
||||
</php>
|
||||
<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>
|
989
src/upload/admin/controller/extension/module/retailcrm.php
Normal file
989
src/upload/admin/controller/extension/module/retailcrm.php
Normal file
|
@ -0,0 +1,989 @@
|
|||
<?php
|
||||
|
||||
use retailcrm\Retailcrm;
|
||||
|
||||
class ControllerExtensionModuleRetailcrm extends Controller
|
||||
{
|
||||
private $_error = [];
|
||||
protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle;
|
||||
public $children, $template;
|
||||
|
||||
public function __construct($registry)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->tokenTitle = $this->retailcrm->getTokenTitle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Install method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function install()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
$this->model_setting_setting->editSetting(
|
||||
$this->moduleTitle,
|
||||
[
|
||||
$this->moduleTitle . '_status' => 1,
|
||||
$this->moduleTitle . '_country' => [$this->config->get('config_country_id')]
|
||||
]
|
||||
);
|
||||
|
||||
$this->addEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function uninstall()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm_setting');
|
||||
|
||||
if (!empty($settings)) {
|
||||
$clientId = $settings['retailcrm_setting_client_id'];
|
||||
|
||||
$this->integrationModule(
|
||||
$this->retailcrm->getApiClient(
|
||||
$settings['retailcrm_setting_url'],
|
||||
$settings['retailcrm_setting_key']
|
||||
),
|
||||
$clientId,
|
||||
false
|
||||
);
|
||||
|
||||
$this->uninstall_collector();
|
||||
$this->model_setting_setting->editSetting(
|
||||
$this->moduleTitle,
|
||||
[$this->moduleTitle . '_status' => 0]
|
||||
);
|
||||
}
|
||||
|
||||
$this->model_setting_setting->deleteSetting('retailcrm_history');
|
||||
$this->model_setting_setting->deleteSetting('retailcrm_setting');
|
||||
$this->deleteEvents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Install Demon Collector method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function install_collector()
|
||||
{
|
||||
$collector = $this->getCollectorTitle();
|
||||
$this->loadModels();
|
||||
$this->load->model('setting/setting');
|
||||
$this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector');
|
||||
$this->model_setting_setting->editSetting($collector, [$collector . '_status' => 1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall Demon Collector method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function uninstall_collector()
|
||||
{
|
||||
$collector = $this->getCollectorTitle();
|
||||
$this->loadModels();
|
||||
$this->load->model('setting/setting');
|
||||
$this->model_setting_setting->editSetting($collector, [$collector . '_status' => 0]);
|
||||
$this->{'model_' . $this->modelExtension}->uninstall('analytics', 'daemon_collector');
|
||||
}
|
||||
|
||||
/**
|
||||
* Install OnlineConsultant method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function install_consultant()
|
||||
{
|
||||
$consultant = $this->getConsultantTitle();
|
||||
$this->loadModels();
|
||||
$this->load->model('setting/setting');
|
||||
$this->{'model_' . $this->modelExtension}->install('analytics', 'online_consultant');
|
||||
$this->model_setting_setting->editSetting($consultant, [$consultant . '_status' => 1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstall OnlineConsultant method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function uninstall_consultant()
|
||||
{
|
||||
$consultant = $this->getConsultantTitle();
|
||||
$this->loadModels();
|
||||
$this->load->model('setting/setting');
|
||||
$this->model_setting_setting->editSetting($consultant, [$consultant . '_status' => 0]);
|
||||
$this->{'model_' . $this->modelExtension}->uninstall('analytics', 'online_consultant');
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup page
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$this->loadModels();
|
||||
$this->load->model('localisation/country');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('extension/retailcrm/references');
|
||||
$this->load->model('localisation/currency');
|
||||
$this->load->model('customer/customer_group');
|
||||
$this->load->model('localisation/length_class');
|
||||
$this->load->language('extension/module/retailcrm');
|
||||
$this->document->setTitle($this->language->get('heading_title'));
|
||||
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
|
||||
|
||||
$collector = $this->getCollectorTitle();
|
||||
$consultant = $this->getConsultantTitle();
|
||||
$history_setting = $this->model_setting_setting->getSetting('retailcrm_history');
|
||||
|
||||
if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
|
||||
if ($this->checkEvents() === false) {
|
||||
$this->deleteEvents();
|
||||
$this->addEvents();
|
||||
}
|
||||
|
||||
$analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics');
|
||||
|
||||
if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1
|
||||
&& !in_array($collector, $analytics)
|
||||
) {
|
||||
$this->install_collector();
|
||||
} elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0
|
||||
&& in_array($collector, $analytics)
|
||||
) {
|
||||
$this->uninstall_collector();
|
||||
}
|
||||
|
||||
if ($this->request->post[$this->moduleTitle . '_online_consultant_active'] == 1) {
|
||||
$this->install_consultant();
|
||||
} elseif ($this->request->post[$this->moduleTitle . '_online_consultant_active'] == 0) {
|
||||
$this->uninstall_consultant();
|
||||
}
|
||||
|
||||
if (parse_url($this->request->post[$this->moduleTitle . '_url'])) {
|
||||
$crm_url = parse_url($this->request->post[$this->moduleTitle . '_url'], PHP_URL_HOST);
|
||||
$this->request->post[$this->moduleTitle . '_url'] = 'https://' . $crm_url;
|
||||
}
|
||||
|
||||
if (isset($this->request->post[$this->moduleTitle . '_custom_field_active'])
|
||||
&& $this->request->post[$this->moduleTitle . '_custom_field_active'] == 0
|
||||
) {
|
||||
unset($this->request->post[$this->moduleTitle . '_custom_field']);
|
||||
}
|
||||
|
||||
$this->model_setting_setting->editSetting(
|
||||
$this->moduleTitle,
|
||||
$this->request->post
|
||||
);
|
||||
|
||||
if (
|
||||
!isset($history_setting['retailcrm_history_orders'])
|
||||
&& !isset($history_setting['retailcrm_history_customers'])
|
||||
) {
|
||||
$api = $this->retailcrm->getApiClient(
|
||||
$this->request->post[$this->moduleTitle . '_url'],
|
||||
$this->request->post[$this->moduleTitle . '_apikey']
|
||||
);
|
||||
|
||||
$this->model_setting_setting->editSetting(
|
||||
'retailcrm_history',
|
||||
[
|
||||
'retailcrm_history_orders' => $this->getHistorySinceId($api, 'ordersHistory'),
|
||||
'retailcrm_history_customers' => $this->getHistorySinceId($api, 'customersHistory'),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$retailcrm_setting = $this->model_setting_setting->getSetting('retailcrm_setting');
|
||||
|
||||
if (!$retailcrm_setting) {
|
||||
$clientId = uniqid();
|
||||
$api = $this->retailcrm->getApiClient(
|
||||
$this->request->post[$this->moduleTitle . '_url'],
|
||||
$this->request->post[$this->moduleTitle . '_apikey']
|
||||
);
|
||||
|
||||
$result = $this->integrationModule(
|
||||
$api,
|
||||
$clientId
|
||||
);
|
||||
|
||||
if ($result === true) {
|
||||
$this->model_setting_setting->editSetting(
|
||||
'retailcrm_setting',
|
||||
[
|
||||
'retailcrm_setting_active_in_crm' => true,
|
||||
'retailcrm_setting_client_id' => $clientId,
|
||||
'retailcrm_setting_url' => $this->request->post[$this->moduleTitle . '_url'],
|
||||
'retailcrm_setting_key' => $this->request->post[$this->moduleTitle . '_apikey']
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->session->data['success'] = $this->language->get('text_success');
|
||||
$redirect = $this->url->link(
|
||||
'extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle],
|
||||
'SSL'
|
||||
);
|
||||
|
||||
$this->response->redirect($redirect);
|
||||
}
|
||||
|
||||
$text_strings = [
|
||||
'heading_title',
|
||||
'text_enabled',
|
||||
'text_disabled',
|
||||
'button_save',
|
||||
'button_cancel',
|
||||
'text_notice',
|
||||
'retailcrm_title',
|
||||
'retailcrm_url',
|
||||
'retailcrm_apikey',
|
||||
'retailcrm_base_settings',
|
||||
'retailcrm_dict_settings',
|
||||
'retailcrm_dict_delivery',
|
||||
'retailcrm_dict_status',
|
||||
'retailcrm_dict_payment',
|
||||
'retailcrm_countries_settings',
|
||||
'text_success_export',
|
||||
'text_success_export_order',
|
||||
'text_button_export',
|
||||
'text_button_export_order',
|
||||
'text_button_catalog',
|
||||
'text_success_catalog',
|
||||
'retailcrm_upload_order',
|
||||
'text_error_order',
|
||||
'text_error_order_id',
|
||||
'daemon_collector',
|
||||
'general_tab_text',
|
||||
'references_tab_text',
|
||||
'collector_tab_text',
|
||||
'consultant_tab_text',
|
||||
'logs_tab_text',
|
||||
'text_yes',
|
||||
'text_no',
|
||||
'collector_site_key',
|
||||
'text_collector_activity',
|
||||
'text_collector_form_capture',
|
||||
'text_collector_period',
|
||||
'text_label_promo',
|
||||
'text_label_send',
|
||||
'collector_custom_text',
|
||||
'text_require',
|
||||
'custom_fields_tab_text',
|
||||
'text_error_custom_field',
|
||||
'text_error_cf_opencart',
|
||||
'text_error_cf_retailcrm',
|
||||
'retailcrm_dict_custom_fields',
|
||||
'text_payment',
|
||||
'text_shipping',
|
||||
'retailcrm_dict_default',
|
||||
'text_custom_field_activity',
|
||||
'text_orders_custom_fields',
|
||||
'text_customers_custom_fields',
|
||||
'text_confirm_log',
|
||||
'text_error_delivery',
|
||||
'retailcrm_missing_status',
|
||||
'special_price_settings',
|
||||
'special_price',
|
||||
'order_number',
|
||||
'text_order_number',
|
||||
'summ_around',
|
||||
'text_summ_around',
|
||||
'icml_settings',
|
||||
'icml_service_enabled_label',
|
||||
'icml_service_description',
|
||||
'text_currency_label',
|
||||
'status_changes',
|
||||
'text_status_changes',
|
||||
'text_lenght',
|
||||
'text_lenght_label',
|
||||
'corporate_enabled_label',
|
||||
'entry_code',
|
||||
'entry_status',
|
||||
'text_retailcrm_discount',
|
||||
'text_retailcrm_label_discount',
|
||||
'default_retailcrm_label_discount',
|
||||
'sum_payment',
|
||||
'text_sum_payment',
|
||||
];
|
||||
|
||||
$_data = &$data;
|
||||
|
||||
$_data['module_version'] = Retailcrm::VERSION_MODULE;
|
||||
|
||||
foreach ($text_strings as $text) {
|
||||
$_data[$text] = $this->language->get($text);
|
||||
}
|
||||
|
||||
$_data['currencies'] = $this->model_localisation_currency->getCurrencies(0);
|
||||
$_data['retailcrm_errors'] = [];
|
||||
$_data['saved_settings'] = $this->model_setting_setting
|
||||
->getSetting($this->moduleTitle);
|
||||
|
||||
$url = $_data['saved_settings'][$this->moduleTitle . '_url'] ?? null;
|
||||
$key = $_data['saved_settings'][$this->moduleTitle . '_apikey'] ?? null;
|
||||
|
||||
if (!empty($url) && !empty($key)) {
|
||||
$this->validate($url, $key);
|
||||
|
||||
$site = $this->model_extension_retailcrm_references->getApiSite();
|
||||
$_data['delivery'] = $this->getAvailableTypes(
|
||||
$site,
|
||||
$this->model_extension_retailcrm_references->getDeliveryTypes()
|
||||
);
|
||||
$_data['payments'] = $this->getAvailableTypes(
|
||||
$site,
|
||||
$this->model_extension_retailcrm_references->getPaymentTypes()
|
||||
);
|
||||
$_data['statuses'] = $this->model_extension_retailcrm_references
|
||||
->getOrderStatuses();
|
||||
$_data['customFields'] = $this->model_extension_retailcrm_references
|
||||
->getCustomFields();
|
||||
|
||||
$_data['lenghts'] = $this->model_localisation_length_class->getLengthClasses();
|
||||
$_data['priceTypes'] = $this->model_extension_retailcrm_references
|
||||
->getPriceTypes();
|
||||
$_data['customerGroups'] = $this->model_customer_customer_group->getCustomerGroups();
|
||||
}
|
||||
|
||||
$config_data = [$this->moduleTitle . '_status'];
|
||||
|
||||
foreach ($config_data as $conf) {
|
||||
if (isset($this->request->post[$conf])) {
|
||||
$_data[$conf] = $this->request->post[$conf];
|
||||
} else {
|
||||
$_data[$conf] = $this->config->get($conf);
|
||||
}
|
||||
}
|
||||
|
||||
$_data['error_warning'] = $this->_error['warning'] ?? '';
|
||||
$_data['breadcrumbs'] = [];
|
||||
|
||||
$_data['breadcrumbs'][] = [
|
||||
'text' => $this->language->get('text_home'),
|
||||
'href' => $this->url->link(
|
||||
'common/dashboard',
|
||||
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
|
||||
),
|
||||
'separator' => false
|
||||
];
|
||||
|
||||
$_data['breadcrumbs'][] = [
|
||||
'text' => $this->language->get('text_module'),
|
||||
'href' => $this->url->link(
|
||||
'extension/extension',
|
||||
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
|
||||
),
|
||||
'separator' => ' :: '
|
||||
];
|
||||
|
||||
$_data['breadcrumbs'][] = [
|
||||
'text' => $this->language->get('retailcrm_title'),
|
||||
'href' => $this->url->link(
|
||||
'extension/module/retailcrm',
|
||||
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
|
||||
),
|
||||
'separator' => ' :: '
|
||||
];
|
||||
|
||||
$_data['action'] = $this->url->link(
|
||||
'extension/module/retailcrm',
|
||||
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
|
||||
);
|
||||
|
||||
$_data['cancel'] = $this->url->link(
|
||||
version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension',
|
||||
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
|
||||
);
|
||||
|
||||
$_data['modules'] = [];
|
||||
|
||||
if (isset($this->request->post['retailcrm_module'])) {
|
||||
$_data['modules'] = $this->request->post['retailcrm_module'];
|
||||
} elseif ($this->config->get('retailcrm_module')) {
|
||||
$_data['modules'] = $this->config->get('retailcrm_module');
|
||||
}
|
||||
|
||||
$this->load->model('design/layout');
|
||||
$_data['layouts'] = $this->model_design_layout->getLayouts();
|
||||
|
||||
$_data['header'] = $this->load->controller('common/header');
|
||||
$_data['column_left'] = $this->load->controller('common/column_left');
|
||||
$_data['footer'] = $this->load->controller('common/footer');
|
||||
$_data['countries'] = $this->model_localisation_country->getCountries();
|
||||
$_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG;
|
||||
$_data[$this->tokenTitle] = $this->request->get[$this->tokenTitle];
|
||||
|
||||
if(file_exists(DIR_SYSTEM . '/cron/export_done')) {
|
||||
$_data['export_file'] = false;
|
||||
} else {
|
||||
$_data['export_file'] = true;
|
||||
}
|
||||
|
||||
$collectorFields = [
|
||||
'name' => $this->language->get('field_name'),
|
||||
'email' => $this->language->get('field_email'),
|
||||
'phone' => $this->language->get('field_phone')
|
||||
];
|
||||
|
||||
$_data['collectorFields'] = $collectorFields;
|
||||
|
||||
$retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log') ? DIR_SYSTEM . 'storage/logs/retailcrm.log' : false;
|
||||
$ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log') ? DIR_SYSTEM . 'storage/logs/opencartapi.log' : false;
|
||||
|
||||
if ($this->checkLogFile($retailcrmLog) !== false) {
|
||||
$_data['logs']['retailcrm_log'] = $this->checkLogFile($retailcrmLog);
|
||||
} else {
|
||||
$_data['logs']['retailcrm_error'] = $this->language->get('text_error_log');
|
||||
}
|
||||
|
||||
if ($this->checkLogFile($ocApiLog) !== false) {
|
||||
$_data['logs']['oc_api_log'] = $this->checkLogFile($ocApiLog);
|
||||
} else {
|
||||
$_data['logs']['oc_error'] = $this->language->get('text_error_log');
|
||||
}
|
||||
|
||||
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
|
||||
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
|
||||
$_data['button_clear'] = $this->language->get('button_clear');
|
||||
|
||||
$this->response->setOutput(
|
||||
$this->load->view('extension/module/retailcrm', $_data)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* History method
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function history()
|
||||
{
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4_5.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/history/v4_5');
|
||||
$this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient());
|
||||
} else {
|
||||
$this->load->model('extension/retailcrm/history');
|
||||
$this->model_extension_retailcrm_history->request($this->retailcrm->getApiClient());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ICML generation
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function icml()
|
||||
{
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/icml.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/icml');
|
||||
$this->model_extension_retailcrm_custom_icml->generateICML();
|
||||
} else {
|
||||
$this->load->model('extension/retailcrm/icml');
|
||||
$this->model_extension_retailcrm_icml->generateICML();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update customer on event
|
||||
*
|
||||
* @param string $route
|
||||
* @param int $customer customer identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function customer_edit($route, $customer)
|
||||
{
|
||||
$this->load->model('localisation/country');
|
||||
$this->load->model('localisation/zone');
|
||||
$this->load->model('customer/customer');
|
||||
|
||||
$customerId = $customer[0];
|
||||
$customer = $customer[1];
|
||||
unset($customer);
|
||||
|
||||
$customer = $this->model_customer_customer->getCustomer($customerId);
|
||||
$address = $this->model_customer_customer->getAddress($customer['address_id']);
|
||||
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
$customer_manager->editCustomer($customer, $address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export single order
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function exportOrder() {
|
||||
$order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : '';
|
||||
$data = $this->model_sale_order->getOrder($order_id);
|
||||
$products = $this->model_sale_order->getOrderProducts($order_id);
|
||||
$totals = $this->model_sale_order->getOrderTotals($order_id);
|
||||
|
||||
foreach ($products as $key => $product) {
|
||||
$products[$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']);
|
||||
}
|
||||
|
||||
if (!isset($data['fromApi'])) {
|
||||
$status = $this->model_setting_setting->getSetting($this->moduleTitle);
|
||||
$data['order_status'] = $status[$this->moduleTitle . '_status'][$data['order_status_id']];
|
||||
|
||||
$order_manager = $this->retailcrm->getOrderManager();
|
||||
$response = $order_manager->createOrder($data, $products, $totals);
|
||||
|
||||
if ($response) {
|
||||
if (!$response->isSuccessful()) {
|
||||
if (isset($response['errors'])) {
|
||||
$error = implode("\n", $response['errors']);
|
||||
} else {
|
||||
$error = $response->getErrorMsg();
|
||||
}
|
||||
|
||||
$this->response->setOutput(
|
||||
json_encode(
|
||||
['status_code' => $response->getStatusCode(), 'error_msg' => $error],
|
||||
JSON_THROW_ON_ERROR
|
||||
)
|
||||
);
|
||||
} else {
|
||||
$this->response->setOutput(json_encode(['status_code' => $response->getStatusCode()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export orders
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function export()
|
||||
{
|
||||
$this->load->model('extension/retailcrm/customer');
|
||||
$this->load->model('extension/retailcrm/order');
|
||||
|
||||
$customers = $this->model_customer_customer->getCustomers();
|
||||
$this->model_extension_retailcrm_customer->uploadToCrm($customers, $this->retailcrm->getApiClient());
|
||||
$orders = $this->model_sale_order->getOrders();
|
||||
|
||||
$fullOrders = [];
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$fullOrder = $this->model_sale_order->getOrder($order['order_id']);
|
||||
|
||||
$fullOrder['totals'] = $this->model_sale_order->getOrderTotals($order['order_id']);
|
||||
$fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']);
|
||||
|
||||
foreach($fullOrder['products'] as $key => $product) {
|
||||
$fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']);
|
||||
}
|
||||
|
||||
$fullOrders[] = $fullOrder;
|
||||
}
|
||||
|
||||
$this->model_extension_retailcrm_order->uploadToCrm($fullOrders, $this->retailcrm->getApiClient());
|
||||
fopen(DIR_SYSTEM . '/cron/export_done', "x");
|
||||
}
|
||||
|
||||
/**
|
||||
* Promotional price upload
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function prices()
|
||||
{
|
||||
$this->load->model('catalog/product');
|
||||
$products = $this->model_catalog_product->getProducts();
|
||||
|
||||
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) {
|
||||
$this->load->model('extension/retailcrm/custom/prices');
|
||||
$this->model_extension_retailcrm_custom_prices->uploadPrices($products, $this->retailcrm->getApiClient());
|
||||
} else {
|
||||
$this->load->model('extension/retailcrm/prices');
|
||||
$this->model_extension_retailcrm_prices->uploadPrices($products, $this->retailcrm->getApiClient());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function validate($apiUrl = null, $apiKey = null)
|
||||
{
|
||||
$warningMessage = '';
|
||||
|
||||
$apiUrl = $this->request->post[$this->moduleTitle . '_url'] ?? $apiUrl;
|
||||
$apiKey = $this->request->post[$this->moduleTitle . '_apikey'] ?? $apiKey;
|
||||
|
||||
try {
|
||||
if ( !empty($apiUrl) && !empty($apiKey)) {
|
||||
$apiClient = $this->retailcrm->getApiClient($apiUrl, $apiKey);
|
||||
$response = $apiClient->sitesList();
|
||||
|
||||
if (empty($response['sites']) || !$response->isSuccessful()) {
|
||||
$warningMessage = 'text_error_api_key';
|
||||
} elseif (count($response['sites']) > 1) {
|
||||
$warningMessage = 'text_error_api_key_site';
|
||||
} else {
|
||||
$site = current($response['sites']);
|
||||
|
||||
if ($this->config->get('config_currency') !== $site['currency']) {
|
||||
$warningMessage = 'text_error_api_key_currency';
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) {
|
||||
$this->_error['warning'] = $this->language->get('error_permission');
|
||||
}
|
||||
|
||||
if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) &&
|
||||
$this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) {
|
||||
$customField = $this->request->post[$this->moduleTitle . '_collector']['custom'];
|
||||
|
||||
if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) {
|
||||
$this->_error['fields'] = $this->language->get('text_error_collector_fields');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$warningMessage = 'text_error_api_empty';
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$warningMessage = sprintf(
|
||||
'An error has occurred! In file: %s, on line: %s. Error message: %s',
|
||||
$exception->getFile(), $exception->getLine(), $exception->getMessage()
|
||||
);
|
||||
}
|
||||
|
||||
if ('' !== $warningMessage) {
|
||||
$this->_error['warning'] = $this->language->get($warningMessage);
|
||||
}
|
||||
|
||||
return empty($this->_error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear retailcrm log file
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clear_retailcrm()
|
||||
{
|
||||
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
|
||||
$file = DIR_LOGS . 'retailcrm.log';
|
||||
|
||||
$handle = fopen($file, 'w+');
|
||||
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear opencart API log file
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clear_opencart()
|
||||
{
|
||||
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
|
||||
$file = DIR_LOGS . 'opencartapi.log';
|
||||
|
||||
$handle = fopen($file, 'w+');
|
||||
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Method for load models
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function loadModels()
|
||||
{
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$this->load->model('extension/event');
|
||||
$this->load->model('extension/extension');
|
||||
// $this->load->model('extension/module');
|
||||
|
||||
$this->modelEvent = 'extension_event';
|
||||
$this->modelExtension = 'extension_extension';
|
||||
// $this->modelModule = 'extension_module';
|
||||
} else {
|
||||
$this->load->model('setting/event');
|
||||
$this->load->model('setting/extension');
|
||||
// $this->load->model('setting/module');
|
||||
|
||||
$this->modelEvent = 'setting_event';
|
||||
$this->modelExtension = 'setting_extension';
|
||||
// $this->modelModule = 'setting_module';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get collector module name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getCollectorTitle()
|
||||
{
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$title = 'daemon_collector';
|
||||
} else {
|
||||
$title = 'analytics_daemon_collector';
|
||||
}
|
||||
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get consultant module name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getConsultantTitle()
|
||||
{
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$title = 'online_consultant';
|
||||
} else {
|
||||
$title = 'analytics_online_consultant';
|
||||
}
|
||||
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check file size
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function checkLogFile($file)
|
||||
{
|
||||
$logs = '';
|
||||
|
||||
if ($file === false) {
|
||||
return $logs;
|
||||
}
|
||||
|
||||
if (filesize($file) < 2097152) {
|
||||
$logs .= file_get_contents($file, FILE_USE_INCLUDE_PATH, null);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $logs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add events to db
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function addEvents()
|
||||
{
|
||||
$this->loadModels();
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/checkout/order/addOrder/after',
|
||||
'extension/module/retailcrm/order_create'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/checkout/order/addOrderHistory/after',
|
||||
'extension/module/retailcrm/order_edit'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/account/customer/addCustomer/after',
|
||||
'extension/module/retailcrm/customer_create'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/account/customer/editCustomer/after',
|
||||
'extension/module/retailcrm/customer_edit'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/account/customer/editNewsletter/after',
|
||||
'extension/module/retailcrm/customer_edit_newsletter'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/account/address/editAddress/after',
|
||||
'extension/module/retailcrm/customer_edit'
|
||||
);
|
||||
|
||||
$this->{'model_' . $this->modelEvent}
|
||||
->addEvent(
|
||||
$this->moduleTitle,
|
||||
'admin/model/customer/customer/editCustomer/after',
|
||||
'extension/module/retailcrm/customer_edit'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check events in db
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
private function checkEvents()
|
||||
{
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$events = $this->{'model_' . $this->modelEvent}->getEvent(
|
||||
$this->moduleTitle,
|
||||
'catalog/model/checkout/order/addOrder/after',
|
||||
'extension/module/retailcrm/order_create'
|
||||
);
|
||||
} else {
|
||||
$this->load->model('extension/retailcrm/event');
|
||||
$events = $this->model_extension_retailcrm_event->getEventByCode($this->moduleTitle);
|
||||
}
|
||||
|
||||
if (!empty($events)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete events from db
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function deleteEvents()
|
||||
{
|
||||
$this->loadModels();
|
||||
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$this->{'model_' . $this->modelEvent}->deleteEvent($this->moduleTitle);
|
||||
} else {
|
||||
$this->{'model_' . $this->modelEvent}->deleteEventByCode($this->moduleTitle);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate/deactivate module in marketplace RetailCRM
|
||||
*
|
||||
* @param \RetailcrmProxy $apiClient
|
||||
* @param string $clientId
|
||||
* @param boolean $active
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
private function integrationModule($apiClient, $clientId, $active = true)
|
||||
{
|
||||
$scheme = isset($this->request->server['HTTPS']) ? 'https://' : 'http://';
|
||||
$logo = 'https://s3.eu-central-1.amazonaws.com/retailcrm-billing/images/5af48736c6a0c-opencart-seeklogo.com.svg';
|
||||
$integrationCode = 'opencart';
|
||||
$name = 'Opencart';
|
||||
$accountUrl = $scheme . $this->request->server['HTTP_HOST'] . '/admin';
|
||||
|
||||
$configuration = [
|
||||
'clientId' => $clientId,
|
||||
'code' => $integrationCode . '-' . $clientId,
|
||||
'integrationCode' => $integrationCode,
|
||||
'active' => $active,
|
||||
'name' => $name,
|
||||
'logo' => $logo,
|
||||
'accountUrl' => $accountUrl,
|
||||
];
|
||||
|
||||
$response = $apiClient->integrationModulesEdit($configuration);
|
||||
|
||||
if (!$response) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function getHistorySinceId($api, $method)
|
||||
{
|
||||
$lastSinceId = 0;
|
||||
$startDate = new DateTime('-1 days');
|
||||
$historyResponse = $api->$method(['startDate' => $startDate->format('Y-m-d H:i:s')]);
|
||||
|
||||
if (
|
||||
!$historyResponse instanceof ApiResponse
|
||||
|| !$historyResponse->isSuccessful()
|
||||
|| empty($historyResponse['history'])
|
||||
|| empty($historyResponse['pagination'])
|
||||
) {
|
||||
return $lastSinceId;
|
||||
}
|
||||
|
||||
$startPage = $historyResponse['pagination']['currentPage'];
|
||||
$lastPage = $historyResponse['pagination']['totalPageCount'];
|
||||
|
||||
for ($startPage; $startPage <= $lastPage; ++$startPage) {
|
||||
if ($historyResponse instanceof ApiResponse && !empty($historyResponse['history'])) {
|
||||
$history = $historyResponse['history'];
|
||||
$lastSinceId = end($history)['id'];
|
||||
$historyResponse = $api->$method(['sinceId' => $lastSinceId]);
|
||||
}
|
||||
}
|
||||
|
||||
return $lastSinceId;
|
||||
}
|
||||
|
||||
private function getAvailableTypes($availableSite, $types)
|
||||
{
|
||||
$result['opencart'] = $types['opencart'];
|
||||
$result['retailcrm'] = [];
|
||||
|
||||
if (empty($availableSite)) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
foreach ($types['retailcrm'] as $codeKey => $type) {
|
||||
if ($type['active'] !== true) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!empty($type['sites']) && !in_array($availableSite['code'], $type['sites'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result['retailcrm'][$codeKey] = $type;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
107
src/upload/admin/language/en-gb/extension/module/retailcrm.php
Normal file
107
src/upload/admin/language/en-gb/extension/module/retailcrm.php
Normal file
|
@ -0,0 +1,107 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Modules';
|
||||
$_['text_success'] = 'Settings are saved successfully';
|
||||
$_['text_notice'] = 'Attention! Time zone in CRM should be the same as the time zone of the store, the time zone is set up at';
|
||||
$_['retailcrm_base_settings'] = 'Connection settings';
|
||||
$_['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_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';
|
||||
$_['text_button_export_order'] = 'Upload the order';
|
||||
$_['text_button_catalog'] = 'Upload the catalogue';
|
||||
$_['text_button_clear'] = 'Clear';
|
||||
$_['text_success_catalog'] = 'Catalogue is uploaded successfully';
|
||||
$_['text_error_order'] = 'Error! Order is not uploaded!';
|
||||
$_['text_error_order_id'] = 'Error! Enter the correct order number!';
|
||||
$_['text_collector_activity'] = 'Use Daemon Collector';
|
||||
$_['text_custom_field_activity'] = 'Transfer custom fields';
|
||||
$_['text_collector_form_capture']= 'Show a capture form';
|
||||
$_['text_collector_period'] = 'Frequency of the form popping up (in minutes)';
|
||||
$_['text_label_promo'] = 'Form header text';
|
||||
$_['text_label_send'] = 'Button text';
|
||||
$_['field_name'] = 'Name';
|
||||
$_['field_email'] = 'E-mail';
|
||||
$_['field_phone'] = 'Phone';
|
||||
$_['text_require'] = 'Required for filling in';
|
||||
$_['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_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_save'] = 'Error when saving settings';
|
||||
$_['text_error_log'] = 'Log size is more than 2MB';
|
||||
$_['text_error_delivery'] = 'Delivery types are not found';
|
||||
$_['text_confirm_log'] = 'Are you sure that you want to clear the log?';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Delivery types';
|
||||
$_['retailcrm_dict_status'] = 'Statuses';
|
||||
$_['retailcrm_dict_payment'] = 'Payment methods';
|
||||
$_['retailcrm_dict_custom_fields'] = 'Configuration of custom fields';
|
||||
$_['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';
|
||||
$_['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';
|
||||
$_['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';
|
108
src/upload/admin/language/es-es/extension/module/retailcrm.php
Normal file
108
src/upload/admin/language/es-es/extension/module/retailcrm.php
Normal file
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Módulos';
|
||||
$_['text_success'] = 'Ajustes guardados correctamente';
|
||||
$_['text_notice'] = '¡Atención! La zona horaria de CRM debe coincidir con la zona horaria de la tienda, la configuración de la zona horaria de CRM se puede establecer en:';
|
||||
$_['retailcrm_base_settings'] = 'Ajustes de conexión';
|
||||
$_['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_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';
|
||||
|
||||
$_['text_success_export'] = 'Los pedidos y los clientes han sido exportados con éxito';
|
||||
$_['text_success_export_order'] = 'El pedido ha sido exportado con éxito';
|
||||
$_['text_button_export'] = 'Exportar a todos los pedidos y clientes';
|
||||
$_['text_button_export_order'] = 'Exportar pedidos';
|
||||
$_['text_button_catalog'] = 'Exportar catálogo';
|
||||
$_['text_button_clear'] = 'Limpiar';
|
||||
$_['text_success_catalog'] = 'El catálogo ha sido exportado con éxito';
|
||||
$_['text_error_order'] = '¡Error! ¡El pedido no se ha exportado!';
|
||||
$_['text_error_order_id'] = '¡Error! ¡Introduzca el número del pedido correcto!';
|
||||
$_['text_collector_activity'] = 'Usar Daemon Collector';
|
||||
$_['text_custom_field_activity'] = 'Transmitir campos personalizados';
|
||||
$_['text_collector_form_capture']= 'Mostrar el formulario de captura';
|
||||
$_['text_collector_period'] = 'Frecuencia de la oleada del formulario (en minutos)';
|
||||
$_['text_label_promo'] = 'Texto del título del formulario';
|
||||
$_['text_label_send'] = 'Texto del botón';
|
||||
$_['field_name'] = 'Nombre';
|
||||
$_['field_email'] = 'Email';
|
||||
$_['field_phone'] = 'Teléfono';
|
||||
$_['text_require'] = 'Necesario para rellenar';
|
||||
$_['text_payment'] = 'Pago';
|
||||
$_['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_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_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_confirm_log'] = '¿Estás seguro de que quieres borrar el registro?';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Métodos de envío';
|
||||
$_['retailcrm_dict_status'] = 'Estados';
|
||||
$_['retailcrm_dict_payment'] = 'Métodos de pago';
|
||||
$_['retailcrm_dict_custom_fields'] = 'Configurar campos personalizados';
|
||||
$_['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';
|
||||
$_['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';
|
||||
$_['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';
|
109
src/upload/admin/language/ru-ru/extension/module/retailcrm.php
Normal file
109
src/upload/admin/language/ru-ru/extension/module/retailcrm.php
Normal file
|
@ -0,0 +1,109 @@
|
|||
<?php
|
||||
|
||||
// Heading Goes here:
|
||||
$_['heading_title'] = 'RetailCRM';
|
||||
$_['retailcrm_title'] = 'RetailCRM';
|
||||
|
||||
// Text
|
||||
$_['text_module'] = 'Модули';
|
||||
$_['text_success'] = 'Настройки успешно сохранены';
|
||||
$_['text_notice'] = 'Внимание! Часовой пояс в CRM должен совпадать с часовым поясом в магазине, настроки часового пояса CRM можно задать по адресу:';
|
||||
$_['retailcrm_base_settings'] = 'Настройки соединения';
|
||||
$_['retailcrm_dict_settings'] = 'Настройки соответствия справочников';
|
||||
$_['retailcrm_countries_settings'] = 'Настройка торговых зон';
|
||||
$_['retailcrm_upload_order'] = 'Выгрузка одного заказа';
|
||||
$_['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_url'] = 'Адрес RetailCRM';
|
||||
$_['retailcrm_apikey'] = 'Api ключ RetailCRM';
|
||||
$_['corporate_enabled_label'] = 'Поддержка корпоративных клиентов';
|
||||
$_['collector_site_key'] = 'Ключ сайта';
|
||||
$_['special_price_settings'] = 'Настройка выгрузки акционной цены';
|
||||
$_['special_price'] = 'Тип цены, в который будет выгружаться цена по акции';
|
||||
|
||||
$_['text_success_export'] = 'Заказы и клиенты успешно выгружены';
|
||||
$_['text_success_export_order'] = 'Заказ успешно выгружен';
|
||||
$_['text_button_export'] = 'Выгрузить все заказы и клиентов';
|
||||
$_['text_button_export_order'] = 'Выгрузить заказ';
|
||||
$_['text_button_catalog'] = 'Выгрузить каталог';
|
||||
$_['text_button_clear'] = 'Очистить';
|
||||
$_['text_success_catalog'] = 'Каталог успешно выгружен';
|
||||
$_['text_error_order'] = 'Ошибка! Заказ не выгружен!';
|
||||
$_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!';
|
||||
$_['text_collector_activity'] = 'Использовать Демон Collector';
|
||||
$_['text_custom_field_activity'] = 'Передавать кастомые поля';
|
||||
$_['text_collector_form_capture']= 'Показывать форму захвата';
|
||||
$_['text_collector_period'] = 'Периодичность всплывания формы (в минутах)';
|
||||
$_['text_label_promo'] = 'Текст заголовка формы';
|
||||
$_['text_label_send'] = 'Текст кнопки';
|
||||
$_['field_name'] = 'Имя';
|
||||
$_['field_email'] = 'Email';
|
||||
$_['field_phone'] = 'Телефон';
|
||||
$_['text_require'] = 'Обязательно для заполнения';
|
||||
$_['text_payment'] = 'Оплата';
|
||||
$_['text_shipping'] = 'Доставка';
|
||||
$_['text_orders_custom_fields'] = 'Кастомные поля заказов';
|
||||
$_['text_customers_custom_fields'] = 'Кастомные поля клиентов';
|
||||
$_['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';
|
||||
$_['text_error_save'] = 'Ошибка сохранения настроек';
|
||||
$_['text_error_log'] = 'Размер лога более 2MB';
|
||||
$_['text_error_delivery'] = 'Не найдены типы доставки';
|
||||
$_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?';
|
||||
|
||||
$_['retailcrm_dict_delivery'] = 'Способы доставки';
|
||||
$_['retailcrm_dict_status'] = 'Статусы';
|
||||
$_['retailcrm_dict_payment'] = 'Способы оплаты';
|
||||
$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей';
|
||||
$_['retailcrm_dict_default'] = 'По умолчанию';
|
||||
$_['retailcrm_missing_status'] = 'Статус пропавших заказов';
|
||||
|
||||
$_['order_number'] = 'Номер заказа';
|
||||
$_['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'] = 'Вес';
|
||||
$_['size'] = 'Размер';
|
||||
|
||||
$_['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;
|
||||
}
|
||||
}
|
341
src/upload/admin/model/extension/retailcrm/history.php
Normal file
341
src/upload/admin/model/extension/retailcrm/history.php
Normal file
|
@ -0,0 +1,341 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmHistory extends Model {
|
||||
protected $createResult;
|
||||
protected $settings;
|
||||
protected $moduleTitle;
|
||||
protected $opencartApiClient;
|
||||
|
||||
private $orders_history;
|
||||
private $customers_history;
|
||||
private $data_repository;
|
||||
|
||||
public function __construct($registry) {
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$this->opencartApiClient = $this->retailcrm->getOcApiClient($registry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting changes from RetailCRM
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function request($retailcrmApiClient) {
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->model('setting/store');
|
||||
$this->load->model('user/api');
|
||||
$this->load->model('sale/order');
|
||||
$this->load->model('customer/customer');
|
||||
$this->load->model('extension/retailcrm/references');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('catalog/option');
|
||||
$this->load->model('localisation/zone');
|
||||
|
||||
$this->load->language('extension/module/retailcrm');
|
||||
|
||||
$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[$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'] ?? 0;
|
||||
$sinceIdCustomers = $history['retailcrm_history_customers'] ?? 0;
|
||||
$packsOrders = $retailcrmApiClient->ordersHistory(['sinceId' => $sinceIdOrders]);
|
||||
$packsCustomers = $retailcrmApiClient->customersHistory(['sinceId' => $sinceIdCustomers]);
|
||||
|
||||
if (!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0
|
||||
&& !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ordersHistory = $packsOrders->history;
|
||||
$customersHistory = $packsCustomers->history;
|
||||
$lastChangeOrders = $ordersHistory ? end($ordersHistory) : null;
|
||||
$lastChangeCustomers = $customersHistory ? end($customersHistory) : null;
|
||||
|
||||
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->status = array_flip($settings[$this->moduleTitle . '_status']);
|
||||
|
||||
foreach ($orders as $order) {
|
||||
if (isset($order['deleted'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($order['externalId'])) {
|
||||
$updatedOrders[] = $order['id'];
|
||||
} else {
|
||||
$newOrders[] = $order['id'];
|
||||
}
|
||||
}
|
||||
|
||||
unset($orders);
|
||||
|
||||
$updateCustomers = [];
|
||||
|
||||
foreach ($customers as $customer) {
|
||||
if (isset($customer['deleted'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($customer['externalId'])) {
|
||||
$updateCustomers[] = $customer['id'];
|
||||
}
|
||||
}
|
||||
|
||||
unset($customers);
|
||||
|
||||
if (!empty($updateCustomers)) {
|
||||
$customers = $retailcrmApiClient->customersList(['ids' => $updateCustomers]);
|
||||
if ($customers) {
|
||||
$this->updateCustomers($customers['customers']);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($newOrders)) {
|
||||
$orders = $retailcrmApiClient->ordersList(['ids' => $newOrders]);
|
||||
if ($orders) {
|
||||
$this->createResult = $this->createOrders($orders['orders'], $retailcrmApiClient);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($updatedOrders)) {
|
||||
$orders = $retailcrmApiClient->ordersList(['ids' => $updatedOrders]);
|
||||
|
||||
if ($orders) {
|
||||
$this->updateOrders($orders['orders'], $retailcrmApiClient);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($this->createResult['customers'])) {
|
||||
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
|
||||
}
|
||||
|
||||
if (!empty($this->createResult['orders'])) {
|
||||
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create orders from history
|
||||
*
|
||||
* @param array $orders
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function createOrders($orders, $retailcrmApiClient) {
|
||||
$customersIdsFix = array();
|
||||
$ordersIdsFix = array();
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$data = array();
|
||||
$corporateAddress = array();
|
||||
|
||||
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($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);
|
||||
|
||||
$customersIdsFix[] = 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;
|
||||
|
||||
$data['order_status_id'] = 1;
|
||||
|
||||
$order_id = $this->data_repository->addOrder($data);
|
||||
|
||||
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
|
||||
}
|
||||
|
||||
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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']);
|
||||
|
||||
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($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();
|
||||
}
|
||||
}
|
401
src/upload/admin/model/extension/retailcrm/icml.php
Normal file
401
src/upload/admin/model/extension/retailcrm/icml.php
Normal file
|
@ -0,0 +1,401 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmIcml extends Model
|
||||
{
|
||||
protected $shop;
|
||||
protected $file;
|
||||
protected $properties;
|
||||
protected $params;
|
||||
protected $dd;
|
||||
protected $eCategories;
|
||||
protected $eOffers;
|
||||
|
||||
private $options;
|
||||
private $optionValues;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param Registry $registry
|
||||
*/
|
||||
public function __construct($registry)
|
||||
{
|
||||
parent::__construct($registry);
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$this->load->model('localisation/weight_class');
|
||||
}
|
||||
|
||||
public function generateICML()
|
||||
{
|
||||
$this->load->language('extension/module/retailcrm');
|
||||
$this->load->model('catalog/category');
|
||||
$this->load->model('catalog/product');
|
||||
$this->load->model('catalog/option');
|
||||
$this->load->model('catalog/manufacturer');
|
||||
$this->load->model('localisation/length_class');
|
||||
|
||||
$string = '<?xml version="1.0" encoding="UTF-8"?>
|
||||
<yml_catalog date="'.date('Y-m-d H:i:s').'">
|
||||
<shop>
|
||||
<name>'.$this->config->get('config_name').'</name>
|
||||
<categories/>
|
||||
<offers/>
|
||||
</shop>
|
||||
</yml_catalog>
|
||||
';
|
||||
|
||||
$xml = new SimpleXMLElement(
|
||||
$string,
|
||||
LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
|
||||
);
|
||||
|
||||
$this->dd = new DOMDocument();
|
||||
$this->dd->preserveWhiteSpace = false;
|
||||
$this->dd->formatOutput = true;
|
||||
$this->dd->loadXML($xml->asXML());
|
||||
|
||||
$this->eCategories = $this->dd
|
||||
->getElementsByTagName('categories')->item(0);
|
||||
$this->eOffers = $this->dd
|
||||
->getElementsByTagName('offers')->item(0);
|
||||
|
||||
$this->addCategories();
|
||||
$this->addOffers();
|
||||
|
||||
$this->dd->saveXML();
|
||||
|
||||
$downloadPath = DIR_SYSTEM . '/../';
|
||||
|
||||
if (!file_exists($downloadPath)) {
|
||||
mkdir($downloadPath, 0755);
|
||||
}
|
||||
|
||||
$this->dd->save($downloadPath . 'retailcrm.xml');
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private function addCategories()
|
||||
{
|
||||
$categories = $this->model_catalog_category->getCategories([]);
|
||||
foreach ($categories as $category) {
|
||||
$category = $this->model_catalog_category->getCategory($category['category_id']);
|
||||
|
||||
$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']);
|
||||
|
||||
if ($category['parent_id'] > 0) {
|
||||
$e->setAttribute('parentId', $category['parent_id']);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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();
|
||||
$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) {
|
||||
$defaultLenght = $lenght;
|
||||
}
|
||||
}
|
||||
|
||||
$manufacturers = $this->model_catalog_manufacturer
|
||||
->getManufacturers([]);
|
||||
|
||||
foreach ($manufacturers as $manufacturer) {
|
||||
$offerManufacturers[$manufacturer['manufacturer_id']] = $manufacturer['name'];
|
||||
}
|
||||
|
||||
$products = $this->model_catalog_product->getProducts([]);
|
||||
|
||||
foreach ($products as $product) {
|
||||
$offers = $this->retailcrm->getOffers($product);
|
||||
|
||||
foreach ($offers as $optionsString => $optionsValues) {
|
||||
$optionsString = explode('_', $optionsString);
|
||||
$options = [];
|
||||
|
||||
foreach($optionsString as $optionString) {
|
||||
$option = explode('-', $optionString);
|
||||
$optionIds = explode(':', $option[0]);
|
||||
|
||||
if ($optionString != '0:0-0') {
|
||||
$optionData = $this->getOptionData($optionIds[1], $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 = [];
|
||||
|
||||
foreach($options as $optionKey => $optionData) {
|
||||
$offerId[] = $optionKey.'-'.$optionData['value_id'];
|
||||
}
|
||||
|
||||
$offerId = implode('_', $offerId);
|
||||
$catalog = $this->eOffers->appendChild($this->dd->createElement('offer'));
|
||||
|
||||
if (!empty($offerId)) {
|
||||
$catalog->setAttribute('id', $product['product_id'] . '#' . $offerId);
|
||||
$catalog->setAttribute('productId', $product['product_id']);
|
||||
$catalog->setAttribute('quantity', $optionsValues['qty']);
|
||||
} else {
|
||||
$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';
|
||||
$catalog->appendChild(
|
||||
$this->dd->createElement('productActivity')
|
||||
)->appendChild(
|
||||
$this->dd->createTextNode($activity)
|
||||
);
|
||||
/**
|
||||
* Offer categories
|
||||
*/
|
||||
$categories = $this->model_catalog_product
|
||||
->getProductCategories($product['product_id']);
|
||||
if (!empty($categories)) {
|
||||
foreach ($categories as $category) {
|
||||
$catalog->appendChild($this->dd->createElement('categoryId'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode($category)
|
||||
);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Name & price
|
||||
*/
|
||||
$catalog->appendChild($this->dd->createElement('productName'))
|
||||
->appendChild($this->dd->createTextNode($product['name']));
|
||||
if (!empty($options)) {
|
||||
$optionsString = [];
|
||||
foreach($options as $option) {
|
||||
$optionsString[] = $option['name'].': '.$option['value'];
|
||||
}
|
||||
$optionsString = ' ('.implode(', ', $optionsString).')';
|
||||
$catalog->appendChild($this->dd->createElement('name'))
|
||||
->appendChild($this->dd->createTextNode($product['name'].$optionsString));
|
||||
} else {
|
||||
$catalog->appendChild($this->dd->createElement('name'))
|
||||
->appendChild($this->dd->createTextNode($product['name']));
|
||||
}
|
||||
|
||||
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) {
|
||||
$catalog->appendChild($this->dd->createElement('vendor'))
|
||||
->appendChild(
|
||||
$this->dd->createTextNode(
|
||||
$offerManufacturers[$product['manufacturer_id']]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dimensions
|
||||
*/
|
||||
if ((!empty($product['length']) && $product['length'] > 0) &&
|
||||
(!empty($product['width']) && $product['width'] > 0)
|
||||
&& !empty($product['height']))
|
||||
{
|
||||
$lenghtArray = $this->model_localisation_length_class->getLengthClass($product['length_class_id']);
|
||||
|
||||
if ($defaultLenght['length_class_id'] != $lenghtArray['length_class_id']) {
|
||||
$productLength = $product['length'] / $lenghtArray['value'];
|
||||
$productWidth = $product['width'] / $lenghtArray['value'];
|
||||
$productHeight = $product['height'] / $lenghtArray['value'];
|
||||
} else {
|
||||
$productLength = $product['length'];
|
||||
$productWidth = $product['width'];
|
||||
$productHeight = $product['height'];
|
||||
}
|
||||
|
||||
if ($defaultLenght['length_class_id'] != $settingLenght && $settingLenght) {
|
||||
$unit = $this->model_localisation_length_class->getLengthClass($settingLenght);
|
||||
$productLength = $productLength * $unit['value'];
|
||||
$productWidth = $productWidth * $unit['value'];
|
||||
$productHeight = $productHeight * $unit['value'];
|
||||
}
|
||||
|
||||
$dimensions = sprintf(
|
||||
'%01.3f/%01.3f/%01.3f',
|
||||
$productLength,
|
||||
$productWidth,
|
||||
$productHeight
|
||||
);
|
||||
|
||||
$catalog->appendChild($this->dd->createElement('dimensions'))
|
||||
->appendChild($this->dd->createTextNode($dimensions));
|
||||
}
|
||||
|
||||
/**
|
||||
* Image
|
||||
*/
|
||||
if ($product['image']) {
|
||||
$image = $this->generateImage($product['image']);
|
||||
$catalog->appendChild($this->dd->createElement('picture'))
|
||||
->appendChild($this->dd->createTextNode($image));
|
||||
}
|
||||
/**
|
||||
* 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'],
|
||||
'',
|
||||
(bool) $this->config->get('config_secure')
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// Options
|
||||
if (!empty($options)) {
|
||||
foreach($options as $optionKey => $optionData) {
|
||||
$param = $this->dd->createElement('param');
|
||||
$param->setAttribute('code', $optionData['option_id']);
|
||||
$param->setAttribute('name', $optionData['name']);
|
||||
$param->appendChild($this->dd->createTextNode($optionData['value']));
|
||||
$catalog->appendChild($param);
|
||||
}
|
||||
}
|
||||
if ($product['sku']) {
|
||||
$sku = $this->dd->createElement('param');
|
||||
$sku->setAttribute('code', 'article');
|
||||
$sku->setAttribute('name', $this->language->get('article'));
|
||||
$sku->appendChild($this->dd->createTextNode($product['sku']));
|
||||
$catalog->appendChild($sku);
|
||||
}
|
||||
if ($product['weight'] != '') {
|
||||
$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));
|
||||
$catalog->appendChild($weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $image
|
||||
* @return mixed
|
||||
*/
|
||||
private function generateImage($image)
|
||||
{
|
||||
$this->load->model('tool/image');
|
||||
|
||||
$currentTheme = $this->config->get('config_theme');
|
||||
$width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200;
|
||||
$height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200;
|
||||
|
||||
return $this->model_tool_image->resize(
|
||||
$image,
|
||||
$width,
|
||||
$height
|
||||
);
|
||||
}
|
||||
|
||||
private function getOptionData($optionId, $optionValueId) {
|
||||
if (!empty($this->options[$optionId])) {
|
||||
$option = $this->options[$optionId];
|
||||
} else {
|
||||
$option = $this->model_catalog_option->getOption($optionId);
|
||||
$this->options[$optionId] = $option;
|
||||
}
|
||||
|
||||
if (!empty($this->optionValues[$optionValueId])) {
|
||||
$optionValue = $this->optionValues[$optionValueId];
|
||||
} else {
|
||||
$optionValue = $this->model_catalog_option->getOptionValue($optionValueId);
|
||||
$this->optionValues[$optionValueId] = $optionValue;
|
||||
}
|
||||
|
||||
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'];
|
||||
}
|
||||
}
|
29
src/upload/admin/model/extension/retailcrm/order.php
Normal file
29
src/upload/admin/model/extension/retailcrm/order.php
Normal file
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmOrder extends Model {
|
||||
/**
|
||||
* Upload orders to CRM
|
||||
*
|
||||
* @param array $orders
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function uploadToCrm($orders)
|
||||
{
|
||||
$ordersToCrm = array();
|
||||
/** @var OrderManager $order_manager */
|
||||
$order_manager = $this->retailcrm->getOrderManager();
|
||||
|
||||
foreach ($orders as $order) {
|
||||
$ordersToCrm[] = $order_manager->prepareOrder($order, $order['products'], $order['totals']);
|
||||
}
|
||||
|
||||
$chunkedOrders = array_chunk($ordersToCrm, 50);
|
||||
|
||||
foreach($chunkedOrders as $ordersPart) {
|
||||
$order_manager->uploadOrders($ordersPart);
|
||||
}
|
||||
|
||||
return $chunkedOrders;
|
||||
}
|
||||
}
|
262
src/upload/admin/model/extension/retailcrm/prices.php
Normal file
262
src/upload/admin/model/extension/retailcrm/prices.php
Normal file
|
@ -0,0 +1,262 @@
|
|||
<?php
|
||||
|
||||
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 $retailcrmApiClient
|
||||
* @return mixed bool | array
|
||||
*/
|
||||
public function uploadPrices($products, $retailcrmApiClient)
|
||||
{
|
||||
$prices = $this->getPrices($products, $retailcrmApiClient);
|
||||
|
||||
if ($retailcrmApiClient === false || !$prices) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$pricesUpload = array_chunk($prices, 250);
|
||||
|
||||
foreach ($pricesUpload as $priceUpload) {
|
||||
$retailcrmApiClient->storePricesUpload($priceUpload);
|
||||
}
|
||||
|
||||
return $pricesUpload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get prices
|
||||
*
|
||||
* @param array $products
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getPrices($products, $retailcrmApiClient)
|
||||
{
|
||||
$prices = array();
|
||||
$site = $this->getSite($retailcrmApiClient);
|
||||
|
||||
foreach ($products as $product) {
|
||||
$specials = $this->model_catalog_product->getProductSpecials($product['product_id']);
|
||||
|
||||
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 = array_merge($prices, $this->getPriceRequest($product, $site, $productPrice));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return $prices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get prices for request
|
||||
*
|
||||
* @param $product
|
||||
* @param $site
|
||||
* @param $productPrice
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getPriceRequest($product, $site, $productPrice)
|
||||
{
|
||||
$offers = $this->retailcrm->getOffers($product);
|
||||
$pricesProducts = array();
|
||||
|
||||
foreach ($offers as $optionsString => $optionsValues) {
|
||||
$optionsString = explode('_', $optionsString);
|
||||
$options = array();
|
||||
|
||||
foreach($optionsString as $optionString) {
|
||||
$option = explode('-', $optionString);
|
||||
$optionIds = explode(':', $option[0]);
|
||||
|
||||
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]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ksort($options);
|
||||
|
||||
$offerId = array();
|
||||
|
||||
foreach($options as $optionKey => $optionData) {
|
||||
$offerId[] = $optionKey.'-'.$optionData['value_id'];
|
||||
}
|
||||
|
||||
$offerId = implode('_', $offerId);
|
||||
$price = array();
|
||||
|
||||
foreach($productPrice as $k => $v) {
|
||||
if (isset($v['price']) && ($v['price'] + $optionsValues['price'] == 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($this->settings[$this->moduleTitle . '_special_' . $k])) {
|
||||
$price[] = array(
|
||||
'code' => $this->settings[$this->moduleTitle . '_special_' . $k],
|
||||
'price' => !$v['remove'] ? $v['price'] + $optionsValues['price'] : 0,
|
||||
'remove' => $v['remove']
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$pricesProducts[] = array(
|
||||
'externalId' => $offerId ? $product['product_id'] . '#' . $offerId : $product['product_id'],
|
||||
'site' => $site,
|
||||
'prices' => $price
|
||||
);
|
||||
}
|
||||
|
||||
return $pricesProducts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get actual special
|
||||
*
|
||||
* @param array $specials
|
||||
*
|
||||
* @return array $productPrice
|
||||
*/
|
||||
private function getSpecialPrice($specials)
|
||||
{
|
||||
$date = date('Y-m-d');
|
||||
$always = '0000-00-00';
|
||||
$productPrice = array();
|
||||
|
||||
foreach ($specials as $special) {
|
||||
if (($special['date_start'] == $always && $special['date_end'] == $always)
|
||||
|| ($special['date_start'] <= $date && $special['date_end'] >= $date)
|
||||
) {
|
||||
if ((isset($groupId) && $groupId == $special['customer_group_id']) || !isset($groupId)) {
|
||||
if ((isset($priority) && $priority > $special['priority'])
|
||||
|| !isset($priority)
|
||||
) {
|
||||
$productPrice[$special['customer_group_id']]['price'] = $special['price'];
|
||||
$productPrice[$special['customer_group_id']]['remove'] = false;
|
||||
$groupId = $special['customer_group_id'];
|
||||
$priority = $special['priority'];
|
||||
}
|
||||
} else {
|
||||
$productPrice[$special['customer_group_id']]['price'] = $special['price'];
|
||||
$productPrice[$special['customer_group_id']]['remove'] = false;
|
||||
$groupId = $special['customer_group_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$customerGroups = $this->model_customer_customer_group->getCustomerGroups();
|
||||
|
||||
foreach ($customerGroups as $customerGroup) {
|
||||
if (!isset($productPrice[$customerGroup['customer_group_id']])){
|
||||
$productPrice[$customerGroup['customer_group_id']]['remove'] = true;
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
*
|
||||
* @param int $optionId
|
||||
* @param int $optionValueId
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function getOptionData($optionId, $optionValueId) {
|
||||
if (!empty($this->options[$optionId])) {
|
||||
$option = $this->options[$optionId];
|
||||
} else {
|
||||
$option = $this->model_catalog_option->getOption($optionId);
|
||||
$this->options[$optionId] = $option;
|
||||
}
|
||||
|
||||
if (!empty($this->optionValues[$optionValueId])) {
|
||||
$optionValue = $this->optionValues[$optionValueId];
|
||||
} else {
|
||||
$optionValue = $this->model_catalog_option->getOptionValue($optionValueId);
|
||||
$this->optionValues[$optionValueId] = $optionValue;
|
||||
}
|
||||
|
||||
return array(
|
||||
'optionName' => $option['name'],
|
||||
'optionValue' => $optionValue['name']
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get site
|
||||
*
|
||||
* @param \RetailcrmProxy $retailcrmApiClient
|
||||
*
|
||||
* @return mixed boolean | string
|
||||
*/
|
||||
private function getSite($retailcrmApiClient)
|
||||
{
|
||||
$response = $retailcrmApiClient->sitesList();
|
||||
|
||||
if ($response && $response->isSuccessful()) {
|
||||
$sites = $response->sites;
|
||||
$site = end($sites);
|
||||
|
||||
return $site['code'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
244
src/upload/admin/model/extension/retailcrm/references.php
Normal file
244
src/upload/admin/model/extension/retailcrm/references.php
Normal file
|
@ -0,0 +1,244 @@
|
|||
<?php
|
||||
|
||||
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()
|
||||
{
|
||||
$this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry);
|
||||
|
||||
return $this->opencartApiClient->getDeliveryTypes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all delivery types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDeliveryTypes()
|
||||
{
|
||||
$this->load->model('setting/store');
|
||||
|
||||
return array(
|
||||
'opencart' => $this->getOpercartDeliveryTypes(),
|
||||
'retailcrm' => $this->getApiDeliveryTypes()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all statuses
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOrderStatuses()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartOrderStatuses(),
|
||||
'retailcrm' => $this->getApiOrderStatuses()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all payment types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getPaymentTypes()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpercartPaymentTypes(),
|
||||
'retailcrm' => $this->getApiPaymentTypes()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all custom fields
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCustomFields()
|
||||
{
|
||||
return array(
|
||||
'opencart' => $this->getOpencartCustomFields(),
|
||||
'retailcrm' => $this->getApiCustomFields()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get opencart order statuses
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOpercartOrderStatuses()
|
||||
{
|
||||
$this->load->model('localisation/order_status');
|
||||
|
||||
return $this->model_localisation_order_status
|
||||
->getOrderStatuses(array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get opencart payment types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOpercartPaymentTypes()
|
||||
{
|
||||
$paymentTypes = array();
|
||||
$files = glob(DIR_APPLICATION . 'controller/extension/payment/*.php');
|
||||
|
||||
if ($files) {
|
||||
foreach ($files as $file) {
|
||||
$extension = basename($file, '.php');
|
||||
|
||||
$this->load->language('extension/payment/' . $extension);
|
||||
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$configStatus = $extension . '_status';
|
||||
} else {
|
||||
$configStatus = 'payment_' . $extension . '_status';
|
||||
}
|
||||
|
||||
if ($this->config->get($configStatus)) {
|
||||
$paymentTypes[$extension] = strip_tags(
|
||||
$this->language->get('heading_title')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $paymentTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get opencart custom fields
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getOpencartCustomFields()
|
||||
{
|
||||
$this->load->model('customer/custom_field');
|
||||
|
||||
return $this->model_customer_custom_field->getCustomFields();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM delivery types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiDeliveryTypes()
|
||||
{
|
||||
$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()
|
||||
{
|
||||
$response = $this->retailcrmApiClient->statusesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->statuses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM payment types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiPaymentTypes()
|
||||
{
|
||||
$response = $this->retailcrmApiClient->paymentTypesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM custom fields
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getApiCustomFields()
|
||||
{
|
||||
$customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer'));
|
||||
$orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order'));
|
||||
if (!$customers || !$orders) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
|
||||
$customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
|
||||
|
||||
if (!$customFieldsCustomers && !$customFieldsOrders) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get RetailCRM price types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getPriceTypes()
|
||||
{
|
||||
$response = $this->retailcrmApiClient->priceTypesList();
|
||||
if (!$response) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return (!$response->isSuccessful()) ? array() : $response->priceTypes;
|
||||
}
|
||||
}
|
11
src/upload/admin/view/stylesheet/retailcrm.css
Normal file
11
src/upload/admin/view/stylesheet/retailcrm.css
Normal file
|
@ -0,0 +1,11 @@
|
|||
.retailcrm_unit {margin-bottom: 10px;}
|
||||
.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;}
|
||||
|
||||
.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>
|
||||
|
770
src/upload/admin/view/template/extension/module/retailcrm.twig
Normal file
770
src/upload/admin/view/template/extension/module/retailcrm.twig
Normal file
|
@ -0,0 +1,770 @@
|
|||
{{ header }} {{ column_left }}
|
||||
<div id="content">
|
||||
<div class="page-header">
|
||||
<div class="container-fluid">
|
||||
<div class="pull-right">
|
||||
{% if export_file %}
|
||||
<button type="button" id="export" data-toggle="tooltip" title="{{ text_button_export }}" class="btn btn-success"><i class="fa fa-download"></i></button>
|
||||
{% endif %}
|
||||
<button type="button" id="icml" data-toggle="tooltip" title="{{ text_button_catalog }}" class="btn btn-success"><i class="fa fa-file-text-o"></i></button>
|
||||
<button type="submit" form="form-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button>
|
||||
<a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a></div>
|
||||
<h1>{{ heading_title }} {{ module_version }}</h1>
|
||||
<ul class="breadcrumb">
|
||||
{% for breadcrumb in breadcrumbs %}
|
||||
<li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="container-fluid">
|
||||
{% if error_warning %}
|
||||
<div class="alert alert-danger">
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
<i class="fa fa-exclamation-circle"></i> {{ error_warning }}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if saved_settings.module_retailcrm_url is defined %}
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
{{ text_notice }}
|
||||
<a href="{{ saved_settings.module_retailcrm_url }}/admin/settings#t-main">{{ saved_settings.module_retailcrm_url }}/admin/settings#t-main</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-body">
|
||||
<form action="{{ action }}" method="post" enctype="multipart/form-data" id="form-module" class="form-horizontal">
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="active"><a href="#tab-general" data-toggle="tab">{{ general_tab_text }}</a></li>
|
||||
{% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %}
|
||||
<li><a href="#tab-references" data-toggle="tab">{{ references_tab_text }}</a></li>
|
||||
<li><a href="#tab-collector" data-toggle="tab">{{ collector_tab_text }}</a></li>
|
||||
<li><a href="#tab-consultant" data-toggle="tab">{{ consultant_tab_text }}</a></li>
|
||||
<li><a href="#tab-custom_fields" data-toggle="tab"> {{ custom_fields_tab_text }} </a></li>
|
||||
<li><a href="#tab-logs" data-toggle="tab">{{ logs_tab_text }}</a></li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
<div class="tab-content">
|
||||
<div class="tab-pane active" id="tab-general">
|
||||
<input type="hidden" name="module_retailcrm_status" value="1">
|
||||
<fieldset>
|
||||
<legend>{{ retailcrm_base_settings }}</legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_url">{{ retailcrm_url }}</label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input class="form-control" id="retailcrm_url" type="text" name="module_retailcrm_url" value="{% if saved_settings.module_retailcrm_url is defined %}{{ saved_settings.module_retailcrm_url }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit retailcrm_disable_border">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_apikey">{{ retailcrm_apikey }}</label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input class="form-control" id="retailcrm_apikey" type="text" name="module_retailcrm_apikey" value="{% if saved_settings.module_retailcrm_apikey is defined %}{{ saved_settings.module_retailcrm_apikey }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_corporate_enabled">{{ corporate_enabled_label }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_corporate_enabled" value="1"
|
||||
{% if saved_settings.module_retailcrm_corporate_enabled is defined and saved_settings.module_retailcrm_corporate_enabled == 1 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_corporate_enabled" value="0"
|
||||
{% if saved_settings.module_retailcrm_corporate_enabled is not defined or saved_settings.module_retailcrm_corporate_enabled == 0 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ 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;">
|
||||
{% for country in countries %}
|
||||
<div class="checkbox">
|
||||
<label>
|
||||
<input type="checkbox" name="module_retailcrm_country[]" value="{{ country.country_id }}" {% if saved_settings.module_retailcrm_country is defined and country.country_id in saved_settings.module_retailcrm_country %} {{ 'checked' }} {% endif %}">
|
||||
{{ country.name }}
|
||||
</label>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ icml_settings }}</legend>
|
||||
<div class="form-group retailcrm_unit retailcrm_disable_border">
|
||||
<label class="col-sm-2 control-label question-mark" for="module_retailcrm_icml_service_enabled" title="{{ icml_service_description }}">{{ icml_service_enabled_label }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_icml_service_enabled" value="1"
|
||||
{% if saved_settings.module_retailcrm_icml_service_enabled is defined and saved_settings.module_retailcrm_icml_service_enabled == 1 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_icml_service_enabled" value="0"
|
||||
{% if saved_settings.module_retailcrm_icml_service_enabled is not defined or saved_settings.module_retailcrm_icml_service_enabled == 0 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit retailcrm_disable_border">
|
||||
<label class="col-sm-2 control-label">{{ text_currency_label }}</label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="module_retailcrm_currency" name="module_retailcrm_currency" class="form-control">
|
||||
{% for currency in currencies %}
|
||||
{% if currency.status == 1 %}
|
||||
<option value="{{ currency.code }}" {% if saved_settings.module_retailcrm_currency is defined and saved_settings.module_retailcrm_currency == currency.code %} selected="selected" {% endif %}>
|
||||
{{ currency.title }}
|
||||
</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group retailcrm_unit retailcrm_disable_border">
|
||||
<label class="col-sm-2 control-label">{{ text_lenght_label }}</label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="module_retailcrm_lenght" name="module_retailcrm_lenght" class="form-control">
|
||||
{% for lenght in lenghts %}
|
||||
<option value="{{ lenght.length_class_id }}" {% if saved_settings.module_retailcrm_lenght is defined and saved_settings.module_retailcrm_lenght == lenght.length_class_id %} selected="selected" {% endif %}>
|
||||
{{ lenght.title }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ status_changes }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_status_changes">{{ text_status_changes }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_status_changes" value="1"
|
||||
{% if saved_settings.module_retailcrm_status_changes is defined and saved_settings.module_retailcrm_status_changes == 1 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_status_changes" value="0"
|
||||
{% if saved_settings.module_retailcrm_status_changes is not defined or saved_settings.module_retailcrm_status_changes == 0 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
{% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %}
|
||||
{% if retailcrm_errors|length %}
|
||||
{% for retailcrm_error in retailcrm_errors %}
|
||||
<div class="warning">{{ retailcrm_error }}</div>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<fieldset>
|
||||
<legend>{{ retailcrm_upload_order }}</legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
<label class="col-sm-2 control-label">{{ 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" data-toggle="tooltip" title="{{ text_button_export_order }}" class="btn btn-success"><i class="fa fa-download"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ special_price_settings }}</legend>
|
||||
<div class="form-group retailcrm_unit">
|
||||
{% for customerGroup in customerGroups %}
|
||||
{% set cud = customerGroup.customer_group_id %}
|
||||
<div class="row retailcrm_unit">
|
||||
<label class="col-sm-2 control-label" for="opencart_customer_group_{{ cud }}">{{ customerGroup.name }}</label>
|
||||
<div class="col-md-4 col-sm-10">
|
||||
<select id="module_retailcrm_special_{{ cud }}" name="module_retailcrm_special_{{ cud }}" class="form-control">
|
||||
<option value="" {% if saved_settings['module_retailcrm_special_'~cud] is not defined or saved_settings['module_retailcrm_special_'~cud] is empty %}selected{% endif %}>---</option>
|
||||
{% for priceType in priceTypes %}
|
||||
{% if priceType.active == true and priceType.default == false%}
|
||||
<option value ="{{ priceType.code }}" {% if saved_settings['module_retailcrm_special_'~cud] is defined and priceType.code == saved_settings['module_retailcrm_special_'~cud] %} selected="selected" {% endif %}>
|
||||
{{ priceType.name }}
|
||||
</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ order_number }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" class="col-sm-2 control-label" for="module_retailcrm_order_number">{{ text_order_number }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_order_number" value="1"
|
||||
{% if saved_settings.module_retailcrm_order_number is defined and saved_settings.module_retailcrm_order_number == 1 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_order_number" value="0"
|
||||
{% if saved_settings.module_retailcrm_order_number is not defined or saved_settings.module_retailcrm_order_number == 0 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ summ_around }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" class="col-sm-2 control-label" for="module_retailcrm_summ_around">{{ text_summ_around }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_summ_around" value="1"
|
||||
{% if saved_settings.module_retailcrm_summ_around is defined and saved_settings.module_retailcrm_summ_around == 1 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_summ_around" value="0"
|
||||
{% if saved_settings.module_retailcrm_summ_around is not defined or saved_settings.module_retailcrm_summ_around == 0 %}
|
||||
checked
|
||||
{% endif %} />
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ text_retailcrm_discount }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="label_discount">{{ text_retailcrm_label_discount }}</label>
|
||||
<div class="col-lg-4 col-md-6 col-sm-10">
|
||||
<input name="module_retailcrm_label_discount" id="label_discount" class="form-control" value="{% if saved_settings.module_retailcrm_label_discount is defined %}{{ saved_settings.module_retailcrm_label_discount }}{% else %}{{ default_retailcrm_label_discount }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ sum_payment }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_sum_payment">{{ text_sum_payment }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label radio-inline">
|
||||
<input type="radio" name="module_retailcrm_sum_payment" value="1"
|
||||
{% if saved_settings.module_retailcrm_sum_payment is defined and saved_settings.module_retailcrm_sum_payment == 1 %}
|
||||
checked
|
||||
{% endif %} >
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label radio-inline">
|
||||
<input type="radio" name="module_retailcrm_sum_payment" value="0"
|
||||
{% if saved_settings.module_retailcrm_sum_payment is not defined or saved_settings.module_retailcrm_sum_payment == 0 %}
|
||||
checked
|
||||
{% endif %} >
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-references">
|
||||
<fieldset>
|
||||
<legend>{{ retailcrm_dict_settings }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label"> {{ retailcrm_dict_delivery }}</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
{% if delivery.opencart is not empty %}
|
||||
{% for value in delivery.opencart %}
|
||||
<div class="col-sm-12" style="margin-bottom:10px;">
|
||||
<div class="pm">{{ value.title ~ ':' }}</div>
|
||||
{% for key, val in value %}
|
||||
{% if key != 'title' %}
|
||||
<div class="form-group retailcrm_unit">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_delivery_{{ val.code }}" name="module_retailcrm_delivery[{{ val.code }}]" class="form-control">
|
||||
{% for k, v in delivery.retailcrm %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_delivery[key] is defined and v.code == saved_settings.module_retailcrm_delivery[key] %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_pm_{{ val.code }}">{{ val.title }}</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
{{ text_error_delivery }}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ retailcrm_dict_status }}</label>
|
||||
<div class="col-sm-10">
|
||||
{% for status in statuses.opencart %}
|
||||
{% set 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_{{ uid }}" name="module_retailcrm_status[{{ status.order_status_id }}]" class="form-control">
|
||||
{% for k, v in statuses.retailcrm %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_status[uid] is defined and v.code == saved_settings.module_retailcrm_status[uid] %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_status_{{ status.order_status_id }} ">{{ status.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ retailcrm_dict_payment }}</label>
|
||||
<div class="col-sm-10">
|
||||
{% for key, value in payments.opencart %}
|
||||
<div class="row retailcrm_unit">
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<select id="retailcrm_payment_{{ key }}" name="module_retailcrm_payment[{{ key }}]" class="form-control">
|
||||
{% for k, v in payments.retailcrm %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_payment[key] is defined and v.code == saved_settings.module_retailcrm_payment[key] %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="control-label" for="retailcrm_payment_{{ key }}">{{ value }}</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ 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="module_retailcrm_default_payment" name="module_retailcrm_default_payment" class="form-control">
|
||||
{% for k, v in payments.opencart %}
|
||||
<option value="{{ k }}" {% if saved_settings.module_retailcrm_default_payment is defined and k == saved_settings.module_retailcrm_default_payment %} selected="selected" {% endif %}>
|
||||
{{ v }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_default_payment">{{ 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="module_retailcrm_default_shipping" name="module_retailcrm_default_shipping" class="form-control">
|
||||
{% for key, value in delivery.opencart %}
|
||||
<optgroup label="{{ value.title }}">
|
||||
{% for k, v in value %}
|
||||
{% if k != 'title' %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_default_shipping is defined and v.code == saved_settings.module_retailcrm_default_shipping %} selected="selected" {% endif %}>
|
||||
{{ v.title }}
|
||||
</option>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</optgroup>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-4 col-md-6 col-sm-6">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_default_shipping">{{ text_shipping }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ 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="module_retailcrm_missing_status" class="form-control">
|
||||
<option></option>
|
||||
{% for k, v in statuses.retailcrm %}
|
||||
<option value="{{ k }}" {% if saved_settings.module_retailcrm_missing_status is defined and k == saved_settings.module_retailcrm_missing_status %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-collector">
|
||||
<fieldset>
|
||||
<legend>{{ daemon_collector }}</legend>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector_active" class="col-md-4">{{ text_collector_activity }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector_active" value="1" {% if saved_settings.module_retailcrm_collector_active is defined and
|
||||
saved_settings.module_retailcrm_collector_active == 1 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector_active" value="0" {% if not saved_settings.module_retailcrm_collector_active or
|
||||
saved_settings.module_retailcrm_collector_active == 0 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4">{{ collector_site_key }}</label>
|
||||
<div class="col-sm-4">
|
||||
<input class="form-control" id="retailcrm_collector_site_key" type="text" name="module_retailcrm_collector[site_key]" value="{% if saved_settings.module_retailcrm_collector.site_key is defined %}{{ saved_settings.module_retailcrm_collector.site_key }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4">{{ text_collector_form_capture }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector[form_capture]" value="1" {% if saved_settings.module_retailcrm_collector.form_capture is defined and
|
||||
saved_settings.module_retailcrm_collector.form_capture == 1 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector[form_capture]" value="0" {% if saved_settings.module_retailcrm_collector.form_capture is not defined or
|
||||
saved_settings.module_retailcrm_collector.form_capture == 0 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_collector_period }}</label>
|
||||
<div class="col-sm-2">
|
||||
<input class="form-control" id="module_retailcrm_collector_period" type="text" name="module_retailcrm_collector[period]" value="{% if saved_settings.module_retailcrm_collector.period is defined %}{{ saved_settings.module_retailcrm_collector.period }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_promo }}</label>
|
||||
<div class="col-sm-4">
|
||||
<input class="form-control" id="module_retailcrm_collector[]" type="text" name="module_retailcrm_collector[label_promo]" value="{% if saved_settings.module_retailcrm_collector.label_promo is defined %}{{ saved_settings.module_retailcrm_collector.label_promo }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_send }}</label>
|
||||
<div class="col-sm-4">
|
||||
<input class="form-control" id="module_retailcrm_collector_label_send" type="text" name="module_retailcrm_collector[label_send]" value="{% if saved_settings.module_retailcrm_collector.label_send is defined %}{{ saved_settings.module_retailcrm_collector.label_send }}{% endif %}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ collector_custom_text }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector[custom_form]" value="1" {% if saved_settings.module_retailcrm_collector.custom_form is defined and
|
||||
saved_settings.module_retailcrm_collector.custom_form == 1 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_collector[custom_form]" value="0" {% if saved_settings.module_retailcrm_collector.custom_form is not defined or
|
||||
saved_settings.module_retailcrm_collector.custom_form == 0 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
{% for field, label in collectorFields %}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_collector">{{ label }}</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
<div class="col-md-4 col-sm-6">
|
||||
<input class="form-control" id="module_retailcrm_collector" type="text" name="module_retailcrm_collector[custom][{{ field }}]" value="{% if saved_settings.module_retailcrm_collector.custom[field] is defined %} {{ saved_settings.module_retailcrm_collector.custom[field] }} {% endif %}">
|
||||
</div>
|
||||
<div class="col-md-8 col-sm-6" style="margin-top: 8px;">
|
||||
<input input style="margin-top: 0; vertical-align: middle;" type="checkbox" name="module_retailcrm_collector[require][{{ field }}_require]" value="1" {% if saved_settings.module_retailcrm_collector.require[field ~'_require'] %} checked {% endif %}>
|
||||
<label style="margin-bottom: 0; vertical-align: middle; margin-left: 5px;" for="retailcrm_collector">{{ text_require }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-consultant">
|
||||
<legend>{{ consultant_tab_text }}</legend>
|
||||
<fieldset>
|
||||
{# online cosultant #}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="input-code">{{ entry_code }}</label>
|
||||
<div class="col-sm-10">
|
||||
<textarea name="module_retailcrm_online_consultant_code" rows="5" placeholder="{{ entry_code }}" id="retailcrm_entry_code" class="form-control">
|
||||
{% if saved_settings.module_retailcrm_online_consultant_code is defined %}
|
||||
{{ saved_settings.module_retailcrm_online_consultant_code }}{% endif %}
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_online_consultant_active" class="col-md-4">{{ entry_status }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_online_consultant_active" value="1" {% if saved_settings.module_retailcrm_online_consultant_active is defined and
|
||||
saved_settings.module_retailcrm_online_consultant_active == 1 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="control-label" class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_online_consultant_active" value="0" {% if not saved_settings.module_retailcrm_online_consultant_active or
|
||||
saved_settings.module_retailcrm_online_consultant_active == 0 %} {{ 'checked' }}
|
||||
{% endif %}>
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="tab-pane" id="tab-custom_fields">
|
||||
<fieldset>
|
||||
<legend>{{ retailcrm_dict_custom_fields }}</legend>
|
||||
{% if customFields.retailcrm is not empty and customFields.opencart is not empty %}
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label" for="retailcrm_custom_field_active">{{ text_custom_field_activity }}</label>
|
||||
<div class="col-sm-10">
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_custom_field_active" value="1" {% if saved_settings.module_retailcrm_custom_field_active is defined and
|
||||
saved_settings.module_retailcrm_custom_field_active == 1 %}
|
||||
checked {% endif %} >
|
||||
{{ text_yes }}
|
||||
</label>
|
||||
<label class="radio-inline">
|
||||
<input type="radio" name="module_retailcrm_custom_field_active" value="0" {% if saved_settings.module_retailcrm_custom_field_active is not defined or
|
||||
saved_settings.module_retailcrm_custom_field_active == 0 %}
|
||||
checked {% endif %} >
|
||||
{{ text_no }}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ text_customers_custom_fields }}</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
{% for customField in customFields.opencart %}
|
||||
<div class="col-sm-12" style="margin-bottom:5px;">
|
||||
<div class="row">
|
||||
{% set fid = 'c_' ~ customField.custom_field_id %}
|
||||
<div class="col-sm-4">
|
||||
<select class="form-control" id="module_retailcrm_custom_field_{{ fid }}" name="module_retailcrm_custom_field[{{ fid }}]" >
|
||||
{% for v in customFields.retailcrm.customers %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_custom_field[fid] is defined and v.code == saved_settings.module_retailcrm_custom_field[fid] %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<label style="padding-top: 9px;" for="module_retailcrm_custom_field_{{ fid }}">{{ customField.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="col-sm-2 control-label">{{ text_orders_custom_fields }}</label>
|
||||
<div class="col-sm-10">
|
||||
<div class="row">
|
||||
{% for customField in customFields.opencart %}
|
||||
<div class="col-sm-12" style="margin-bottom:5px;">
|
||||
<div class="row">
|
||||
{% set fid = 'o_' ~ customField.custom_field_id %}
|
||||
<div class="col-sm-4">
|
||||
<select class="form-control" id="module_retailcrm_custom_field_{{ fid }}" name="module_retailcrm_custom_field[{{ fid }}]" >
|
||||
{% for v in customFields.retailcrm.orders %}
|
||||
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_custom_field[fid] is defined and v.code == saved_settings.module_retailcrm_custom_field[fid] %} selected="selected" {% endif %}>
|
||||
{{ v.name }}
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<label style="padding-top: 9px;" for="module_retailcrm_custom_field_{{ fid }}">{{ customField.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% elseif customFields.retailcrm is empty and customFields.opencart is empty %}
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
{{ text_error_custom_field }}
|
||||
</div>
|
||||
{% elseif customFields.retailcrm is empty %}
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
{{ text_error_cf_retailcrm }}
|
||||
</div>
|
||||
{% elseif customFields.opencart is empty %}
|
||||
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
{{ text_error_cf_opencart }}
|
||||
</div>
|
||||
{% 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('{{ text_confirm_log }}') ? location.href='{{ clear_retailcrm }}' : false;" data-toggle="tooltip" title="{{ button_clear }}" class="btn btn-danger"><i class="fa fa-eraser"></i></a>
|
||||
</div>
|
||||
{% if logs.retailcrm_log is defined %}
|
||||
<div class="row">
|
||||
<div class="col-sm-12">
|
||||
<textarea wrap="off" rows="15" readonly class="form-control">{{ logs.retailcrm_log }}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
{% elseif logs.retailcrm_error is defined %}
|
||||
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ logs.retailcrm_error }}
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Opencart API error log</legend>
|
||||
<div class="retailcrm_unit">
|
||||
<a onclick="confirm('{{ text_confirm_log }}') ? location.href='{{ clear_opencart }}' : false;" data-toggle="tooltip" title="{{ button_clear }}" class="btn btn-danger"><i class="fa fa-eraser"></i></a>
|
||||
</div>
|
||||
{% if logs.oc_api_log is defined %}
|
||||
<div class="row">
|
||||
<div class="col-sm-12">
|
||||
<textarea wrap="off" rows="15" readonly class="form-control">{{ logs.oc_api_log }}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
{% elseif logs.oc_error is defined %}
|
||||
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ logs.oc_error }}
|
||||
<button type="button" class="close" data-dismiss="alert">×</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</fieldset>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{ footer }}
|
||||
|
||||
<script type="text/javascript">
|
||||
var token = '{{ user_token }}';
|
||||
$('#icml').on('click', function() {
|
||||
$.ajax({
|
||||
url: '{{ catalog }}' + 'admin/index.php?route=extension/module/retailcrm/icml&user_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> {{ text_success_catalog }}</div>');
|
||||
$('#icml').button('reset');
|
||||
},
|
||||
error: function(){
|
||||
alert('error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$('#export').on('click', function() {
|
||||
$.ajax({
|
||||
url: '{{ catalog }}' + 'admin/index.php?route=extension/module/retailcrm/export&user_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> {{ 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: '{{ catalog }}' + 'admin/index.php?route=extension/module/retailcrm/exportOrder&user_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>{{ 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>{{ 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> {{ text_error_order_id }}</div>');
|
||||
$('#export_order').button('reset');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
191
src/upload/catalog/controller/api/retailcrm.php
Normal file
191
src/upload/catalog/controller/api/retailcrm.php
Normal file
|
@ -0,0 +1,191 @@
|
|||
<?php
|
||||
|
||||
class ControllerApiRetailcrm extends Controller
|
||||
{
|
||||
public function getDeliveryTypes()
|
||||
{
|
||||
$api = $this->auth();
|
||||
|
||||
if (isset($api['error'])) {
|
||||
$response = $api;
|
||||
} else {
|
||||
$this->load->model('localisation/country');
|
||||
$this->load->model('setting/setting');
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$setting = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
|
||||
$response = array();
|
||||
|
||||
if (isset($setting[$moduleTitle . '_country']) && $setting[$moduleTitle . '_country']) {
|
||||
foreach ($setting[$moduleTitle . '_country'] as $country) {
|
||||
$response = $this->mergeDeliveryTypes($country, $response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($this->request->server['HTTP_ORIGIN'])) {
|
||||
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
|
||||
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
|
||||
$this->response->addHeader('Access-Control-Max-Age: 1000');
|
||||
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
|
||||
}
|
||||
|
||||
$this->response->addHeader('Content-Type: application/json');
|
||||
$this->response->setOutput(json_encode($response));
|
||||
}
|
||||
|
||||
public function addOrderHistory()
|
||||
{
|
||||
$api = $this->auth();
|
||||
|
||||
if (isset($api['error'])) {
|
||||
$response = $api;
|
||||
} elseif (!isset($this->request->post['order_id']) || !isset($this->request->post['order_status_id'])) {
|
||||
$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);
|
||||
}
|
||||
|
||||
if (isset($this->request->server['HTTP_ORIGIN'])) {
|
||||
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
|
||||
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
|
||||
$this->response->addHeader('Access-Control-Max-Age: 1000');
|
||||
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
|
||||
}
|
||||
|
||||
$this->response->addHeader('Content-Type: application/json');
|
||||
$this->response->setOutput(json_encode($response));
|
||||
}
|
||||
|
||||
protected function getDeliveryTypesByZones($country_id)
|
||||
{
|
||||
$this->loadModels();
|
||||
$this->load->model('localisation/zone');
|
||||
$this->load->model('localisation/country');
|
||||
|
||||
$shippingModules = $this->{'model_' . $this->modelExtension}->getExtensions('shipping');
|
||||
$zones = $this->model_localisation_zone->getZonesByCountryId($country_id);
|
||||
$country = $this->model_localisation_country->getCountry($country_id);
|
||||
$quote_data = array();
|
||||
|
||||
foreach ($zones as $zone) {
|
||||
$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'] ?? '',
|
||||
'zone_code' => $zone['code'],
|
||||
'postcode' => '',
|
||||
'city' => ''
|
||||
);
|
||||
|
||||
foreach ($shippingModules as $shippingModule) {
|
||||
$this->load->model('extension/shipping/' . $shippingModule['code']);
|
||||
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$shippingCode = $shippingModule['code'];
|
||||
} else {
|
||||
$shippingCode = 'shipping_' . $shippingModule['code'];
|
||||
}
|
||||
|
||||
if ($this->config->get($shippingCode . '_status')) {
|
||||
if ($shippingCode == 'free') {
|
||||
$free_total = $this->config->get('free_total');
|
||||
|
||||
if ($free_total > 0) {
|
||||
$this->config->set('free_total', 0);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) {
|
||||
$quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address);
|
||||
} else {
|
||||
$this->load->language('extension/shipping/' . $shippingModule['code']);
|
||||
|
||||
$quote_data[] = array(
|
||||
'code' => $shippingModule['code'],
|
||||
'title' => $this->language->get('text_title'),
|
||||
'quote' => array(
|
||||
array(
|
||||
'code' => $shippingModule['code'],
|
||||
'title' => $this->language->get('text_title')
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$deliveryTypes = array();
|
||||
|
||||
foreach ($quote_data as $shipping) {
|
||||
foreach ($shipping['quote'] as $shippingMethod) {
|
||||
$deliveryTypes[$shipping['code']]['title'] = $shipping['title'];
|
||||
$deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod;
|
||||
}
|
||||
}
|
||||
|
||||
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'])
|
||||
|| !$this->request->get['key']
|
||||
) {
|
||||
return array('error' => 'Not found api 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;
|
||||
}
|
||||
}
|
||||
|
||||
return array('error' => 'Invalid api key');
|
||||
}
|
||||
|
||||
private function loadModels()
|
||||
{
|
||||
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';
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,92 @@
|
|||
<?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($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;
|
||||
$customForm = '';
|
||||
|
||||
if (isset($setting['custom']) && $setting['custom_form'] == 1) {
|
||||
$customForm = "'fields': {";
|
||||
$cntEmpty = 0;
|
||||
|
||||
foreach ($setting['custom'] as $field => $label) {
|
||||
if (empty($label)) {
|
||||
$cntEmpty += 1;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($setting['require'][$field . '_require'])) {
|
||||
$customForm .= "\n\t'$field': { required: true, label: '$label' },";
|
||||
} else {
|
||||
$customForm .= "\n\t'$field': { label: '$label' },";
|
||||
}
|
||||
}
|
||||
$customForm .= "\n\t},";
|
||||
|
||||
if ($cntEmpty == count($setting['custom'])) $customForm = '';
|
||||
}
|
||||
|
||||
if (isset($setting['form_capture']) && $setting['form_capture'] == 1) {
|
||||
|
||||
if (!empty($setting['period']) && is_numeric($setting['period'])) {
|
||||
|
||||
if ($labelPromo != null || $labelSend != null){
|
||||
$captureForm = "_rc('require', 'capture-form', {
|
||||
'period': " . $setting['period'] . ",
|
||||
" . $customForm . "
|
||||
labelPromo: '" . $labelPromo . "',
|
||||
labelSend: '" . $labelSend . "'
|
||||
});";
|
||||
} else {
|
||||
$captureForm = "_rc('require', 'capture-form', {
|
||||
'period': " . $settings[$moduleTitle . '_collector']['period'] . ",
|
||||
" . $customForm . "
|
||||
});";
|
||||
}
|
||||
} elseif ($labelPromo != null || $labelSend != null) {
|
||||
$captureForm = "_rc('require', 'capture-form', {
|
||||
" . $customForm . "
|
||||
labelPromo: '" . $labelPromo . "',
|
||||
labelSend: '" . $labelSend . "'
|
||||
});";
|
||||
} elseif (isset($setting['custom'])){
|
||||
$captureForm = "_rc('require', 'capture-form', {
|
||||
" . $customForm . "
|
||||
});";
|
||||
} else {
|
||||
$captureForm = "_rc('require', 'capture-form');";
|
||||
}
|
||||
} else {
|
||||
$captureForm = "";
|
||||
}
|
||||
|
||||
if (!$customer) {
|
||||
$initClient = "_rc('create', '" . $siteCode . "');";
|
||||
} else {
|
||||
$initClient = "_rc('create', '" . $siteCode . "', {
|
||||
" . $customer . "
|
||||
});";
|
||||
}
|
||||
|
||||
$js = "<script type=\"text/javascript\">
|
||||
(function(_,r,e,t,a,i,l){_['retailCRMObject']=a;_[a]=_[a]||function(){(_[a].q=_[a].q||[]).push(arguments)};_[a].l=1*new Date();l=r.getElementsByTagName(e)[0];i=r.createElement(e);i.async=!0;i.src=t;l.parentNode.insertBefore(i,l)})(window,document,'script','https://collector.retailcrm.pro/w.js','_rc');"
|
||||
. $initClient . $captureForm .
|
||||
"_rc('send', 'pageView');
|
||||
</script>";
|
||||
|
||||
return html_entity_decode($js, ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
}
|
|
@ -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');
|
||||
}
|
||||
}
|
177
src/upload/catalog/controller/extension/module/retailcrm.php
Normal file
177
src/upload/catalog/controller/extension/module/retailcrm.php
Normal file
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
|
||||
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 $trigger
|
||||
* @param array $data
|
||||
* @param int $order_id order identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function order_create($trigger, $data, $order_id = null) {
|
||||
if (\retailcrm\Retailcrm::$history_run === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$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();
|
||||
|
||||
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 $trigger
|
||||
* @param array $parameter2
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function order_edit($trigger, $parameter2 = null) {
|
||||
if (\retailcrm\Retailcrm::$history_run === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order_id = $parameter2[0];
|
||||
|
||||
$this->load->library('retailcrm/retailcrm');
|
||||
|
||||
$moduleTitle = $this->retailcrm->getModuleTitle();
|
||||
$data = $this->model_checkout_order->getOrder($order_id);
|
||||
|
||||
if ($data['order_status_id'] == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$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 int $customerId customer identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public function customer_edit_newsletter($parameter1, $parameter2, $parameter3)
|
||||
{
|
||||
$customerId = $this->customer->getId();
|
||||
$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->changeInCrm($customer, $this->retailcrmApiClient);
|
||||
} else {
|
||||
$customer_manager = $this->retailcrm->getCustomerManager();
|
||||
$customer_manager->editCustomerNewsLetter($customer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update customer on event
|
||||
*
|
||||
* @param int $customerId customer identificator
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
11
src/upload/catalog/model/extension/retailcrm/api.php
Normal file
11
src/upload/catalog/model/extension/retailcrm/api.php
Normal file
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmApi extends Model
|
||||
{
|
||||
public function login($username, $key)
|
||||
{
|
||||
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE `username` = '" . $this->db->escape($username) . "' AND `key` = '" . $this->db->escape($key) . "' AND status = '1'");
|
||||
|
||||
return $query->row;
|
||||
}
|
||||
}
|
449
src/upload/catalog/model/extension/retailcrm/order.php
Normal file
449
src/upload/catalog/model/extension/retailcrm/order.php
Normal file
|
@ -0,0 +1,449 @@
|
|||
<?php
|
||||
|
||||
class ModelExtensionRetailcrmOrder extends Model {
|
||||
protected $settings;
|
||||
protected $moduleTitle;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
|
@ -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
|
||||
{
|
||||
}
|
23
src/upload/system/library/retailcrm/base.php
Normal file
23
src/upload/system/library/retailcrm/base.php
Normal file
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm;
|
||||
|
||||
/**
|
||||
* Class Base
|
||||
*
|
||||
* @property \Loader load
|
||||
* @property \DB db
|
||||
* @property \Config config
|
||||
* @property \Language language
|
||||
*/
|
||||
abstract class Base {
|
||||
protected $registry;
|
||||
|
||||
public function __construct(\Registry $registry) {
|
||||
$this->registry = $registry;
|
||||
}
|
||||
|
||||
public function __get($name) {
|
||||
return $this->registry->get($name);
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
4
src/upload/system/library/retailcrm/cron/.htaccess
Normal file
4
src/upload/system/library/retailcrm/cron/.htaccess
Normal file
|
@ -0,0 +1,4 @@
|
|||
<Files *.*>
|
||||
Allow from all
|
||||
Satisfy any
|
||||
</Files>
|
70
system/cron/dispatch.php → src/upload/system/library/retailcrm/cron/dispatch.php
Executable file → Normal file
70
system/cron/dispatch.php → src/upload/system/library/retailcrm/cron/dispatch.php
Executable file → Normal file
|
@ -1,5 +1,8 @@
|
|||
<?php
|
||||
|
||||
$_SERVER['HTTPS'] = 'off';
|
||||
$_SERVER['SERVER_PORT'] = 80;
|
||||
|
||||
// Ensure $cli_action is set
|
||||
if (!isset($cli_action)) {
|
||||
echo 'ERROR: $cli_action must be set in calling script.';
|
||||
|
@ -8,16 +11,18 @@ if (!isset($cli_action)) {
|
|||
}
|
||||
|
||||
// Version
|
||||
$version = '1.5.6';
|
||||
$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])) {
|
||||
|
||||
if (isset($versionMatches[1])) {
|
||||
$version = $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')) {
|
||||
|
@ -31,10 +36,12 @@ if (!defined('DIR_APPLICATION')) {
|
|||
require_once(DIR_SYSTEM . 'startup.php');
|
||||
|
||||
// Application Classes
|
||||
require_once(DIR_SYSTEM . 'library/currency.php');
|
||||
require_once(DIR_SYSTEM . 'library/user.php');
|
||||
require_once(DIR_SYSTEM . 'library/weight.php');
|
||||
require_once(DIR_SYSTEM . 'library/length.php');
|
||||
require_once(DIR_SYSTEM . 'library/cart/currency.php');
|
||||
require_once(DIR_SYSTEM . 'library/cart/user.php');
|
||||
require_once(DIR_SYSTEM . 'library/cart/weight.php');
|
||||
require_once(DIR_SYSTEM . 'library/cart/length.php');
|
||||
|
||||
|
||||
|
||||
// Registry
|
||||
$registry = new Registry();
|
||||
|
@ -45,6 +52,12 @@ $registry->set('load', $loader);
|
|||
|
||||
// Config
|
||||
$config = new Config();
|
||||
|
||||
if (version_compare(VERSION, '3.0', '>=')) {
|
||||
$config->load('default');
|
||||
$config->load('catalog');
|
||||
}
|
||||
|
||||
$registry->set('config', $config);
|
||||
|
||||
// Database
|
||||
|
@ -58,7 +71,7 @@ foreach ($query->rows as $setting) {
|
|||
if (!$setting['serialized']) {
|
||||
$config->set($setting['key'], $setting['value']);
|
||||
} else {
|
||||
$config->set($setting['key'], unserialize($setting['value']));
|
||||
$config->set($setting['key'], json_decode($setting['value']), true);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -70,6 +83,12 @@ $registry->set('url', $url);
|
|||
$log = new Log($config->get('config_error_filename'));
|
||||
$registry->set('log', $log);
|
||||
|
||||
|
||||
// Event
|
||||
$event = new Event($registry);
|
||||
$registry->set('event', $event);
|
||||
|
||||
|
||||
function error_handler($errno, $errstr, $errfile, $errline) {
|
||||
global $log, $config;
|
||||
|
||||
|
@ -101,6 +120,7 @@ function error_handler($errno, $errstr, $errfile, $errline) {
|
|||
|
||||
return true;
|
||||
}
|
||||
|
||||
set_error_handler('error_handler');
|
||||
$request = new Request();
|
||||
$registry->set('request', $request);
|
||||
|
@ -111,7 +131,13 @@ $cache = new Cache('file');
|
|||
$registry->set('cache', $cache);
|
||||
|
||||
$registry->set('response', $response);
|
||||
$session = new Session();
|
||||
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$session = new Session();
|
||||
} else {
|
||||
$session = new Session($config->get('session_engine'), $registry);
|
||||
}
|
||||
|
||||
$registry->set('session', $session);
|
||||
|
||||
$languages = array();
|
||||
|
@ -122,7 +148,13 @@ 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 {
|
||||
|
@ -133,12 +165,18 @@ $registry->set('language', $language);
|
|||
$document = new Document();
|
||||
$registry->set('document', $document);
|
||||
|
||||
$registry->set('currency', new Currency($registry));
|
||||
$registry->set('weight', new Weight($registry));
|
||||
$registry->set('length', new Length($registry));
|
||||
$registry->set('user', new User($registry));
|
||||
|
||||
$controller = new Front($registry);
|
||||
$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));
|
||||
|
||||
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/export.php
Normal file
3
src/upload/system/library/retailcrm/cron/export.php
Normal file
|
@ -0,0 +1,3 @@
|
|||
<?php
|
||||
$cli_action = 'extension/module/retailcrm/export';
|
||||
require_once('dispatch.php');
|
3
src/upload/system/library/retailcrm/cron/history.php
Normal file
3
src/upload/system/library/retailcrm/cron/history.php
Normal file
|
@ -0,0 +1,3 @@
|
|||
<?php
|
||||
$cli_action = 'extension/module/retailcrm/history';
|
||||
require_once('dispatch.php');
|
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');
|
||||
|
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,182 @@
|
|||
<?php
|
||||
|
||||
class OpencartApiClient {
|
||||
|
||||
private $opencartStoreId = 0;
|
||||
private $cookieFileName;
|
||||
private $registry;
|
||||
private $apiToken;
|
||||
|
||||
/* Совместимость с объектами ОС, например $this->model_module_name */
|
||||
public function __get($name) {
|
||||
return $this->registry->get($name);
|
||||
}
|
||||
|
||||
public function __construct(Registry &$registry) {
|
||||
$this->registry = $registry;
|
||||
$moduleTitle = $this->getModuleTitle();
|
||||
$settings = $this->model_setting_setting->getSetting($moduleTitle);
|
||||
$this->cookieFileName = $settings[$moduleTitle . '_apikey'];
|
||||
|
||||
$this->auth();
|
||||
}
|
||||
|
||||
private function getCookieValue($cookieName) {
|
||||
if (!file_exists(DIR_APPLICATION . $this->cookieFileName . '.txt')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cookieFile = file_get_contents(DIR_APPLICATION . $this->cookieFileName . '.txt');
|
||||
$cookieFile = explode("\n", $cookieFile);
|
||||
|
||||
$cookies = array();
|
||||
foreach ($cookieFile as $line) {
|
||||
if (empty($line) OR $line[0] == '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = explode("\t", $line);
|
||||
$cookies[$params[5]] = $params[6];
|
||||
}
|
||||
|
||||
if (isset($cookies[$cookieName])) {
|
||||
return $cookies[$cookieName];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function request($method, $getParams, $postParams) {
|
||||
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
|
||||
|
||||
if ($this->apiToken !== false) {
|
||||
if (version_compare(VERSION, '3.0', '<')) {
|
||||
$getParams['key'] = $this->apiToken['key'];
|
||||
} else {
|
||||
$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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$postParams['fromApi'] = true;
|
||||
|
||||
if ($opencartStoreInfo) {
|
||||
$url = $opencartStoreInfo['ssl'];
|
||||
} else {
|
||||
$url = HTTPS_CATALOG;
|
||||
}
|
||||
|
||||
$curl = curl_init();
|
||||
|
||||
// Set SSL if required
|
||||
if (substr($url, 0, 5) == 'https') {
|
||||
curl_setopt($curl, CURLOPT_PORT, 443);
|
||||
}
|
||||
|
||||
curl_setopt($curl, CURLOPT_HEADER, false);
|
||||
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($curl, CURLOPT_FORBID_REUSE, false);
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($curl, CURLOPT_URL, $url . 'index.php?route=api/' . $method . (!empty($getParams) ? '&' . http_build_query($getParams) : ''));
|
||||
|
||||
curl_setopt($curl, CURLOPT_POST, true);
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams));
|
||||
|
||||
curl_setopt($curl, CURLOPT_COOKIEFILE, DIR_APPLICATION . $this->cookieFileName . '.txt');
|
||||
curl_setopt($curl, CURLOPT_COOKIEJAR, DIR_APPLICATION . $this->cookieFileName . '.txt');
|
||||
|
||||
$json = json_decode(curl_exec($curl), true);
|
||||
|
||||
curl_close($curl);
|
||||
|
||||
if (!$json && json_last_error() !== JSON_ERROR_NONE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isset($json['error'])) {
|
||||
if (is_array($json['error'])) {
|
||||
foreach ($json['error'] as $error) {
|
||||
error_log(date('Y-m-d H:i:s') . " @ " . "[$method]" . ' - ' . $error . "\n", 3, DIR_LOGS . "opencartapi.log");
|
||||
}
|
||||
} else {
|
||||
error_log(date('Y-m-d H:i:s') . " @ " . "[$method]" . ' - ' . $json['error'] . "\n", 3, DIR_LOGS . "opencartapi.log");
|
||||
}
|
||||
} else {
|
||||
return $json;
|
||||
}
|
||||
}
|
||||
|
||||
private function auth() {
|
||||
$this->load->model('user/api');
|
||||
|
||||
$apiUsers = $this->model_user_api->getApis();
|
||||
|
||||
$api = array();
|
||||
|
||||
foreach ($apiUsers as $apiUser) {
|
||||
if($apiUser['status'] == 1) {
|
||||
$api = $apiUser;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($api['api_id'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isset($api) && !empty($api)) {
|
||||
$this->apiToken = $api;
|
||||
} else {
|
||||
$this->apiToken = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get delivery types
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getDeliveryTypes()
|
||||
{
|
||||
return $this->request('retailcrm/getDeliveryTypes', array(), array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add history order
|
||||
*
|
||||
* @param int $order_id
|
||||
* @param int $order_status_id
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addHistory($order_id, $order_status_id)
|
||||
{
|
||||
$this->request('retailcrm/addOrderHistory', array(), array('order_id' => $order_id, 'order_status_id' => $order_status_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get module name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getModuleTitle()
|
||||
{
|
||||
if (version_compare(VERSION, '3.0', '<')){
|
||||
$title = 'retailcrm';
|
||||
} else {
|
||||
$title = 'module_retailcrm';
|
||||
}
|
||||
|
||||
return $title;
|
||||
}
|
||||
}
|
2996
src/upload/system/library/retailcrm/lib/api/RetailcrmApiClient5.php
Normal file
2996
src/upload/system/library/retailcrm/lib/api/RetailcrmApiClient5.php
Normal file
File diff suppressed because it is too large
Load diff
|
@ -1,7 +1,5 @@
|
|||
<?php
|
||||
/**
|
||||
* Response from retailCRM API
|
||||
*/
|
||||
|
||||
class RetailcrmApiResponse implements ArrayAccess
|
||||
{
|
||||
// HTTP response status code
|
||||
|
@ -10,6 +8,14 @@ class RetailcrmApiResponse implements ArrayAccess
|
|||
// response assoc array
|
||||
protected $response;
|
||||
|
||||
/**
|
||||
* ApiResponse constructor.
|
||||
*
|
||||
* @param int $statusCode HTTP status code
|
||||
* @param mixed $responseBody HTTP body
|
||||
*
|
||||
* @throws InvalidJsonException
|
||||
*/
|
||||
public function __construct($statusCode, $responseBody = null)
|
||||
{
|
||||
$this->statusCode = (int) $statusCode;
|
||||
|
@ -51,7 +57,11 @@ class RetailcrmApiResponse implements ArrayAccess
|
|||
/**
|
||||
* Allow to access for the property throw class method
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $name method name
|
||||
* @param mixed $arguments method parameters
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __call($name, $arguments)
|
||||
|
@ -60,7 +70,7 @@ class RetailcrmApiResponse implements ArrayAccess
|
|||
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
|
||||
|
||||
if (!isset($this->response[$propertyName])) {
|
||||
throw new InvalidArgumentException("Method \"$name\" not found");
|
||||
throw new \InvalidArgumentException("Method \"$name\" not found");
|
||||
}
|
||||
|
||||
return $this->response[$propertyName];
|
||||
|
@ -69,37 +79,53 @@ class RetailcrmApiResponse implements ArrayAccess
|
|||
/**
|
||||
* Allow to access for the property throw object property
|
||||
*
|
||||
* @param string $name
|
||||
* @param string $name property name
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if (!isset($this->response[$name])) {
|
||||
throw new InvalidArgumentException("Property \"$name\" not found");
|
||||
throw new \InvalidArgumentException("Property \"$name\" not found");
|
||||
}
|
||||
|
||||
return $this->response[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* @param mixed $value
|
||||
* Offset set
|
||||
*
|
||||
* @param mixed $offset offset
|
||||
* @param mixed $value value
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
throw new BadMethodCallException('This activity not allowed');
|
||||
throw new \BadMethodCallException('This activity not allowed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* Offset unset
|
||||
*
|
||||
* @param mixed $offset offset
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
throw new BadMethodCallException('This call not allowed');
|
||||
throw new \BadMethodCallException('This call not allowed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* Check offset
|
||||
*
|
||||
* @param mixed $offset offset
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($offset)
|
||||
|
@ -108,13 +134,18 @@ class RetailcrmApiResponse implements ArrayAccess
|
|||
}
|
||||
|
||||
/**
|
||||
* @param mixed $offset
|
||||
* Get offset
|
||||
*
|
||||
* @param mixed $offset offset
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
if (!isset($this->response[$offset])) {
|
||||
throw new InvalidArgumentException("Property \"$offset\" not found");
|
||||
throw new \InvalidArgumentException("Property \"$offset\" not found");
|
||||
}
|
||||
|
||||
return $this->response[$offset];
|
|
@ -0,0 +1,133 @@
|
|||
<?php
|
||||
|
||||
class RetailcrmHistoryHelper {
|
||||
public static function assemblyOrder($orderHistory)
|
||||
{
|
||||
if (file_exists(__DIR__ . '/objects.xml')) {
|
||||
$objects = simplexml_load_file(__DIR__ . '/objects.xml');
|
||||
foreach($objects->fields->field as $object) {
|
||||
$fields[(string)$object["group"]][(string)$object["id"]] = (string)$object;
|
||||
}
|
||||
}
|
||||
$orders = array();
|
||||
foreach ($orderHistory as $change) {
|
||||
$change['order'] = self::removeEmpty($change['order']);
|
||||
if(isset($change['order']['items']) && $change['order']['items']) {
|
||||
$items = array();
|
||||
foreach($change['order']['items'] as $item) {
|
||||
if(isset($change['created'])) {
|
||||
$item['create'] = 1;
|
||||
}
|
||||
$items[$item['id']] = $item;
|
||||
}
|
||||
$change['order']['items'] = $items;
|
||||
}
|
||||
|
||||
if(isset($change['order']['contragent']['contragentType']) && $change['order']['contragent']['contragentType']) {
|
||||
$change['order']['contragentType'] = $change['order']['contragent']['contragentType'];
|
||||
unset($change['order']['contragent']);
|
||||
}
|
||||
|
||||
if(!empty($orders) && isset($orders[$change['order']['id']])) {
|
||||
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
|
||||
} else {
|
||||
$orders[$change['order']['id']] = $change['order'];
|
||||
}
|
||||
|
||||
if(isset($change['item']) && $change['item']) {
|
||||
if(isset($orders[$change['order']['id']]['items'][$change['item']['id']])) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
|
||||
} else {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
|
||||
}
|
||||
|
||||
if (empty($change['oldValue'])
|
||||
&& $change['field'] == 'order_product'
|
||||
) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true;
|
||||
}
|
||||
|
||||
if (empty($change['newValue'])
|
||||
&& $change['field'] == 'order_product'
|
||||
) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true;
|
||||
}
|
||||
|
||||
if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create'])
|
||||
&& isset($fields['item'][$change['field']])
|
||||
&& $fields['item'][$change['field']]
|
||||
) {
|
||||
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
|
||||
}
|
||||
} else {
|
||||
if(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']] == 'service'){
|
||||
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
|
||||
} elseif(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']]) {
|
||||
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
|
||||
} elseif(isset($fields['orderAddress'][$change['field']]) && $fields['orderAddress'][$change['field']]){
|
||||
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
|
||||
} elseif(isset($fields['integrationDelivery'][$change['field']]) && $fields['integrationDelivery'][$change['field']]) {
|
||||
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
|
||||
} elseif(isset($fields['customerContragent'][$change['field']]) && $fields['customerContragent'][$change['field']]) {
|
||||
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
|
||||
} elseif(strripos($change['field'], 'custom_') !== false) {
|
||||
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
|
||||
} elseif(isset($fields['order'][$change['field']]) && $fields['order'][$change['field']]) {
|
||||
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
|
||||
}
|
||||
|
||||
if(isset($change['created'])) {
|
||||
$orders[$change['order']['id']]['create'] = 1;
|
||||
}
|
||||
|
||||
if(isset($change['deleted'])) {
|
||||
$orders[$change['order']['id']]['deleted'] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $orders;
|
||||
}
|
||||
|
||||
public static function assemblyCustomer($customerHistory)
|
||||
{
|
||||
$customers = array();
|
||||
foreach ($customerHistory as $change) {
|
||||
$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']);
|
||||
} else {
|
||||
$customers[$change['customer']['id']] = $change['customer'];
|
||||
}
|
||||
}
|
||||
|
||||
return $customers;
|
||||
}
|
||||
|
||||
public static function newValue($value)
|
||||
{
|
||||
if(isset($value['code'])) {
|
||||
return $value['code'];
|
||||
} else {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
public static function removeEmpty($inputArray)
|
||||
{
|
||||
$outputArray = array();
|
||||
if (!empty($inputArray)) {
|
||||
foreach ($inputArray as $key => $element) {
|
||||
if(!empty($element) || $element === 0 || $element === '0'){
|
||||
if (is_array($element)) {
|
||||
$element = self::removeEmpty($element);
|
||||
}
|
||||
$outputArray[$key] = $element;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $outputArray;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,109 @@
|
|||
<?php
|
||||
|
||||
use retailcrm\Retailcrm;
|
||||
|
||||
class RetailcrmHttpClient
|
||||
{
|
||||
const METHOD_GET = 'GET';
|
||||
const METHOD_POST = 'POST';
|
||||
|
||||
protected $url;
|
||||
protected $defaultParameters;
|
||||
|
||||
/**
|
||||
* Client constructor.
|
||||
*
|
||||
* @param string $url api url
|
||||
* @param array $defaultParameters array of parameters
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function __construct($url, array $defaultParameters = array())
|
||||
{
|
||||
if (false === stripos($url, 'https://')) {
|
||||
throw new \InvalidArgumentException(
|
||||
'API schema requires HTTPS protocol'
|
||||
);
|
||||
}
|
||||
|
||||
$this->url = $url;
|
||||
$this->defaultParameters = $defaultParameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make HTTP request
|
||||
*
|
||||
* @param string $path request url
|
||||
* @param string $method (default: 'GET')
|
||||
* @param array $parameters (default: array())
|
||||
*
|
||||
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @throws CurlException
|
||||
* @throws InvalidJsonException
|
||||
*
|
||||
* @return ApiResponse
|
||||
*/
|
||||
public function makeRequest(
|
||||
$path,
|
||||
$method,
|
||||
array $parameters = []
|
||||
) {
|
||||
$allowedMethods = [self::METHOD_GET, self::METHOD_POST];
|
||||
|
||||
if (!in_array($method, $allowedMethods, false)) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf(
|
||||
'Method "%s" is not valid. Allowed methods are %s',
|
||||
$method,
|
||||
implode(', ', $allowedMethods)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
$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;
|
||||
|
||||
if (self::METHOD_GET === $method && count($parameters)) {
|
||||
$url .= '?' . http_build_query($parameters, '', '&');
|
||||
}
|
||||
|
||||
$curlHandler = curl_init();
|
||||
curl_setopt($curlHandler, CURLOPT_URL, $url);
|
||||
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
|
||||
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
|
||||
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
|
||||
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
|
||||
|
||||
if (self::METHOD_POST === $method) {
|
||||
curl_setopt($curlHandler, CURLOPT_POST, true);
|
||||
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
|
||||
}
|
||||
|
||||
$responseBody = curl_exec($curlHandler);
|
||||
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
|
||||
$errno = curl_errno($curlHandler);
|
||||
$error = curl_error($curlHandler);
|
||||
|
||||
curl_close($curlHandler);
|
||||
|
||||
if ($errno) {
|
||||
throw new CurlException($error, $errno);
|
||||
}
|
||||
|
||||
return new RetailcrmApiResponse($statusCode, $responseBody);
|
||||
}
|
||||
}
|
|
@ -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'];
|
||||
}
|
||||
}
|
107
src/upload/system/library/retailcrm/objects.xml
Normal file
107
src/upload/system/library/retailcrm/objects.xml
Normal file
|
@ -0,0 +1,107 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<options>
|
||||
<fields>
|
||||
<field id="id" group="customer">id</field>
|
||||
<field id="first_name" group="customer">firstName</field>
|
||||
<field id="last_name" group="customer">lastName</field>
|
||||
<field id="patronymic" group="customer">patronymic</field>
|
||||
<field id="email" group="customer">email</field>
|
||||
<field id="birthday" group="customer">birthday</field>
|
||||
<field id="phones" group="customer">phones</field>
|
||||
<field id="manager" group="customer">manager</field>
|
||||
<field id="commentary" group="customer">commentary</field>
|
||||
<field id="external_id" group="customer">externalId</field>
|
||||
<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>
|
||||
<field id="address.region" group="customerAddress">region</field>
|
||||
<field id="address.city" group="customerAddress">city</field>
|
||||
<field id="address.street" group="customerAddress">street</field>
|
||||
<field id="address.building" group="customerAddress">building</field>
|
||||
<field id="address.house" group="customerAddress">house</field>
|
||||
<field id="address.block" group="customerAddress">block</field>
|
||||
<field id="address.flat" group="customerAddress">flat</field>
|
||||
<field id="address.floor" group="customerAddress">floor</field>
|
||||
<field id="address.intercom_code" group="customerAddress">intercomCode</field>
|
||||
<field id="address.metro" group="customerAddress">metro</field>
|
||||
<field id="address.notes" group="customerAddress">notes</field>
|
||||
|
||||
<field id="contragent.contragent_type" group="customerContragent">contragentType</field>
|
||||
<field id="contragent.legal_name" group="customerContragent">legalName</field>
|
||||
<field id="contragent.legal_address" group="customerContragent">legalAddress</field>
|
||||
<field id="contragent.certificate_number" group="customerContragent">certificateNumber</field>
|
||||
<field id="contragent.certificate_date" group="customerContragent">certificateDate</field>
|
||||
<field id="contragent.bank" group="customerContragent">bank</field>
|
||||
<field id="contragent.bank_address" group="customerContragent">bankAddress</field>
|
||||
<field id="contragent.corr_account" group="customerContragent">corrAccount</field>
|
||||
<field id="contragent.bank_account" group="customerContragent">bankAccount</field>
|
||||
|
||||
<field id="id" group="order">id</field>
|
||||
<field id="created_at" group="order">createdAt</field>
|
||||
<field id="order_type" group="order">orderType</field>
|
||||
<field id="order_method" group="order">orderMethod</field>
|
||||
<field id="site" group="order">site</field>
|
||||
<field id="status" group="order">status</field>
|
||||
<field id="manager" group="order">manager</field>
|
||||
<field id="first_name" group="order">firstName</field>
|
||||
<field id="last_name" group="order">lastName</field>
|
||||
<field id="patronymic" group="order">patronymic</field>
|
||||
<field id="phone" group="order">phone</field>
|
||||
<field id="additional_phone" group="order">additionalPhone</field>
|
||||
<field id="email" group="order">email</field>
|
||||
<field id="payment_type" group="order">paymentType</field>
|
||||
<field id="payment_status" group="order">paymentStatus</field>
|
||||
<field id="discount" group="order">discount</field>
|
||||
<field id="discount_percent" group="order">discountPercent</field>
|
||||
<field id="prepay_sum" group="order">prepaySum</field>
|
||||
<field id="customer_comment" group="order">customerComment</field>
|
||||
<field id="manager_comment" group="order">managerComment</field>
|
||||
<field id="shipment_store" group="order">shipmentStore</field>
|
||||
<field id="shipment_date" group="order">shipmentDate</field>
|
||||
<field id="shipped" group="order">shipped</field>
|
||||
<!--<field id="order_product" group="order">item</field>-->
|
||||
<field id="payment" group="order">payment</field>
|
||||
<field id="payments.amount" group="order">amount</field>
|
||||
<field id="payments.paid_at" group="order">paidAt</field>
|
||||
<field id="payments.comment" group="order">comment</field>
|
||||
<field id="payments.type" group="order">type</field>
|
||||
<field id="payments.status" group="order">status</field>
|
||||
|
||||
<field id="order_product.id" group="item">id</field>
|
||||
<field id="order_product.initial_price" group="item">initialPrice</field>
|
||||
<field id="order_product.discount" group="item">discount</field>
|
||||
<field id="order_product.discount_percent" group="item">discountPercent</field>
|
||||
<field id="order_product.quantity" group="item">quantity</field>
|
||||
<field id="order_product.status" group="item">status</field>
|
||||
<field id="order_product.summ" group="item">summ</field>
|
||||
|
||||
<field id="delivery_type" group="delivery">code</field>
|
||||
<field id="delivery_service" group="delivery">service</field>
|
||||
<field id="delivery_date" group="delivery">date</field>
|
||||
<field id="delivery_time" group="delivery">time</field>
|
||||
<field id="delivery_cost" group="delivery">cost</field>
|
||||
<field id="delivery_net_cost" group="delivery">netCost</field>
|
||||
|
||||
<field id="delivery_address.country" group="orderAddress">country</field>
|
||||
<field id="delivery_address.index" group="orderAddress">index</field>
|
||||
<field id="delivery_address.region" group="orderAddress">region</field>
|
||||
<field id="delivery_address.city" group="orderAddress">city</field>
|
||||
<field id="delivery_address.street" group="orderAddress">street</field>
|
||||
<field id="delivery_address.building" group="orderAddress">building</field>
|
||||
<field id="delivery_address.house" group="orderAddress">house</field>
|
||||
<field id="delivery_address.block" group="orderAddress">block</field>
|
||||
<field id="delivery_address.flat" group="orderAddress">flat</field>
|
||||
<field id="delivery_address.floor" group="orderAddress">floor</field>
|
||||
<field id="delivery_address.intercom_code" group="orderAddress">intercomCode</field>
|
||||
<field id="delivery_address.metro" group="orderAddress">metro</field>
|
||||
<field id="delivery_address.notes" group="orderAddress">notes</field>
|
||||
|
||||
<field id="integration_delivery_data.status" group="integrationDelivery">status</field>
|
||||
<field id="integration_delivery_data.track_number" group="integrationDelivery">trackNumber</field>
|
||||
<field id="integration_delivery_data.courier" group="integrationDelivery">courier</field>
|
||||
</fields>
|
||||
</options>
|
269
src/upload/system/library/retailcrm/retailcrm.php
Normal file
269
src/upload/system/library/retailcrm/retailcrm.php
Normal file
|
@ -0,0 +1,269 @@
|
|||
<?php
|
||||
|
||||
namespace retailcrm;
|
||||
|
||||
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;
|
||||
|
||||
/** @var bool */
|
||||
public static $history_run = false;
|
||||
|
||||
|
||||
|
||||
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 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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get api client object
|
||||
*
|
||||
* @param string $apiUrl (default = null)
|
||||
* @param string $apiKey (default = null)
|
||||
*
|
||||
* @return mixed object | boolean
|
||||
*/
|
||||
public function getApiClient($apiUrl = null, $apiKey = null) {
|
||||
if (!$this->registry->has('RetailcrmProxy')) {
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
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 || !$apiKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->registry->set(
|
||||
'RetailcrmProxy',
|
||||
new \RetailcrmProxy($apiUrl, $apiKey)
|
||||
);
|
||||
}
|
||||
|
||||
return $this->registry->get('RetailcrmProxy');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get opencart api client
|
||||
*
|
||||
* @param object $registry
|
||||
*
|
||||
* @return \OpencartApiClient
|
||||
*/
|
||||
public function getOcApiClient($registry) {
|
||||
return new \OpencartApiClient($registry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
// Handle & sort mandatory options
|
||||
foreach($options as $option) {
|
||||
if(in_array($option['type'], $offerOptions)) {
|
||||
if($option['required']) {
|
||||
$requiredOptions[] = $option;
|
||||
} else {
|
||||
$notRequiredOptions[] = $option;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$offers = array();
|
||||
|
||||
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)$this->getOptionPrice($optionValue),
|
||||
'qty' => $optionValue['quantity'],
|
||||
'weight' => round($this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
foreach($offers as $optionKey => $optionAttr) {
|
||||
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
|
||||
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)$this->getOptionPrice($optionValue),
|
||||
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
|
||||
$optionValue['quantity'] : $optionAttr['qty'],
|
||||
'weight' => round($optionAttr['weight'] + $this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)$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) {
|
||||
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
|
||||
'price' => $optionAttr['price'] + (float)$this->getOptionPrice($optionValue),
|
||||
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
|
||||
$optionValue['quantity'] : $optionAttr['qty'],
|
||||
'weight' => round($optionAttr['weight'] + $this->getWeightOption($optionValue), 3)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(empty($offers)) {
|
||||
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
|
||||
}
|
||||
|
||||
return $offers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $option
|
||||
*
|
||||
* @return float
|
||||
*/
|
||||
private function getWeightOption($option) {
|
||||
if ($option['weight_prefix'] === '-') {
|
||||
return $option['weight'] * -1;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getLenghtForIcml() {
|
||||
$this->load->model('setting/setting');
|
||||
|
||||
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
|
||||
|
||||
if (isset($setting[$this->getModuleTitle() . '_lenght'])) {
|
||||
return $setting[$this->getModuleTitle() . '_lenght'];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
<?php
|
||||
$cli_action = 'module/retailcrm/icml';
|
||||
require_once('dispatch.php');
|
|
@ -1,2 +0,0 @@
|
|||
<?php
|
||||
echo $_SERVER['REMOTE_ADDR'];
|
|
@ -1,3 +0,0 @@
|
|||
<?php
|
||||
$cli_action = 'module/retailcrm/history';
|
||||
require_once('dispatch.php');
|
|
@ -1,316 +0,0 @@
|
|||
<?php
|
||||
|
||||
class OpencartApiClient {
|
||||
|
||||
private $opencartStoreId = 0;
|
||||
private $cookieFileName;
|
||||
private $registry;
|
||||
private $apiToken;
|
||||
|
||||
/* Совместимость с объектами ОС, например $this->model_module_name */
|
||||
public function __get($name) {
|
||||
return $this->registry->get($name);
|
||||
}
|
||||
|
||||
public function __construct(Registry &$registry) {
|
||||
$this->registry = $registry;
|
||||
|
||||
$settings = $this->model_setting_setting->getSetting('retailcrm');
|
||||
$this->cookieFileName = $settings['retailcrm_apikey'];
|
||||
|
||||
$this->auth();
|
||||
}
|
||||
|
||||
private function getCookieValue($cookieName) {
|
||||
$cookieFile = file_get_contents(DIR_APPLICATION . '/' . $this->cookieFileName . '.txt');
|
||||
$cookieFile = explode("\n", $cookieFile);
|
||||
|
||||
$cookies = array();
|
||||
foreach($cookieFile as $line) {
|
||||
if(empty($line) OR $line{0} == '#')
|
||||
continue;
|
||||
|
||||
$params = explode("\t", $line);
|
||||
$cookies[$params[5]] = $params[6];
|
||||
}
|
||||
|
||||
if(isset($cookies[$cookieName]))
|
||||
return $cookies[$cookieName];
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function request($method, $getParams, $postParams) {
|
||||
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
|
||||
|
||||
if(version_compare(VERSION, '2.1.0', '>=') && !empty($this->apiToken)) {
|
||||
$getParams['token'] = $this->apiToken;
|
||||
}
|
||||
|
||||
$postParams['fromApi'] = true;
|
||||
|
||||
if ($opencartStoreInfo) {
|
||||
$url = $opencartStoreInfo['ssl'];
|
||||
} else {
|
||||
$url = HTTPS_CATALOG;
|
||||
}
|
||||
|
||||
$curl = curl_init();
|
||||
|
||||
// Set SSL if required
|
||||
if (substr($url, 0, 5) == 'https') {
|
||||
curl_setopt($curl, CURLOPT_PORT, 443);
|
||||
}
|
||||
|
||||
curl_setopt($curl, CURLOPT_HEADER, false);
|
||||
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($curl, CURLOPT_FORBID_REUSE, false);
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($curl, CURLOPT_URL, $url . 'index.php?route=api/' . $method . (!empty($getParams) ? '&' . http_build_query($getParams) : ''));
|
||||
|
||||
curl_setopt($curl, CURLOPT_POST, true);
|
||||
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams));
|
||||
|
||||
curl_setopt($curl, CURLOPT_COOKIEFILE, DIR_APPLICATION . '/' . $this->cookieFileName . '.txt');
|
||||
curl_setopt($curl, CURLOPT_COOKIEJAR, DIR_APPLICATION . '/' . $this->cookieFileName . '.txt');
|
||||
|
||||
$json = json_decode(curl_exec($curl), true);
|
||||
|
||||
curl_close($curl);
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
private function auth() {
|
||||
$apiUsers = $this->model_user_api->getApis();
|
||||
|
||||
$api = array();
|
||||
foreach ($apiUsers as $apiUser) {
|
||||
if($apiUser['status'] == 1) {
|
||||
if(version_compare(VERSION, '2.1.0', '>=')) {
|
||||
$api = array(
|
||||
'api_id' => $apiUser['api_id'],
|
||||
'key' => $apiUser['key']
|
||||
);
|
||||
} else {
|
||||
$api = array(
|
||||
'api_id' => $apiUser['api_id'],
|
||||
'username' => $apiUser['username'],
|
||||
'password' => $apiUser['password']
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(!isset($api['api_id']))
|
||||
return false;
|
||||
|
||||
if(version_compare(VERSION, '2.1.0', '>=')) {
|
||||
$alreadyBinded = false;
|
||||
|
||||
$innerIp = $this->getInnerIpAddr();
|
||||
$apiIps = $this->model_user_api->getApiIps($api['api_id']);
|
||||
foreach($apiIps as $apiIp) {
|
||||
if($apiIp['ip'] == $innerIp)
|
||||
$alreadyBinded = true;
|
||||
}
|
||||
|
||||
if(!$alreadyBinded) {
|
||||
$this->model_user_api->addApiIp($api['api_id'], $innerIp);
|
||||
}
|
||||
}
|
||||
|
||||
$apiAnswer = $this->request('login', array(), $apiUser);
|
||||
|
||||
if(version_compare(VERSION, '2.1.0', '>=')) {
|
||||
$this->apiToken = $apiAnswer['token'];
|
||||
}
|
||||
|
||||
return $apiAnswer;
|
||||
}
|
||||
|
||||
public function editOrder($order_id, $data) {
|
||||
$data['telephone'] = trim($data['telephone']);
|
||||
$customer = array(
|
||||
'currency' => isset($data['currency']) ? $data['currency'] : '',
|
||||
'customer' => $data['customer'],
|
||||
'customer_id' => $data['customer_id'],
|
||||
'customer_group_id' => $data['customer_group_id'],
|
||||
'firstname' => $data['firstname'],
|
||||
'lastname' => $data['lastname'],
|
||||
'email' => $data['email'],
|
||||
'telephone' => !empty($data['telephone']) ? $data['telephone'] : '0000',
|
||||
'fax' => $data['fax'],
|
||||
);
|
||||
$this->request('customer', array(), $customer);
|
||||
|
||||
$products = array();
|
||||
foreach ($data['order_product'] as $order_product) {
|
||||
$products[] = array(
|
||||
'product_id' => $order_product['product_id'],
|
||||
'quantity' => $order_product['quantity']
|
||||
);
|
||||
}
|
||||
$this->request('cart/add', array(), array('product' => $products));
|
||||
|
||||
$payment_address = array(
|
||||
'payment_address' => $data['payment_address'],
|
||||
'firstname' => $data['payment_firstname'],
|
||||
'lastname' => $data['payment_lastname'],
|
||||
'company' => $data['payment_company'],
|
||||
'address_1'=> $data['payment_address_1'],
|
||||
'address_2' => $data['payment_address_2'],
|
||||
'city' => !empty($data['payment_city']) ? $data['payment_city'] : 'none',
|
||||
'postcode' => $data['payment_postcode'],
|
||||
'country_id' => $data['payment_country_id'],
|
||||
'zone_id' => !empty($data['payment_zone_id']) ? $data['payment_zone_id'] : 0,
|
||||
);
|
||||
$this->request('payment/address', array(), $payment_address);
|
||||
|
||||
$this->request('payment/methods', array(), array());
|
||||
$payment_method = array(
|
||||
'payment_method' => $data['payment_code']
|
||||
);
|
||||
$this->request('payment/method', array(), $payment_method);
|
||||
|
||||
$shipping_address = array(
|
||||
'shipping_address' => $data['shipping_address'],
|
||||
'firstname' => $data['shipping_firstname'],
|
||||
'lastname' => $data['shipping_lastname'],
|
||||
'company' => $data['shipping_company'],
|
||||
'address_1' => $data['shipping_address_1'],
|
||||
'address_2' => $data['shipping_address_2'],
|
||||
'city' => !empty($data['shipping_city']) ? $data['shipping_city'] : 'none',
|
||||
'postcode' => $data['shipping_postcode'],
|
||||
'country_id' => $data['shipping_country_id'],
|
||||
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
|
||||
);
|
||||
$this->request('shipping/address', array(), $shipping_address);
|
||||
|
||||
$this->request('shipping/methods', array(), array());
|
||||
$shipping_method = array(
|
||||
'shipping_method' => $data['shipping_code']
|
||||
);
|
||||
$this->request('shipping/method', array(), $shipping_method);
|
||||
|
||||
$order = array(
|
||||
'shipping_method' => $data['shipping_code'],
|
||||
'payment_method' => $data['payment_code'],
|
||||
'order_status_id' => $data['order_status_id'],
|
||||
'comment' => $data['comment'],
|
||||
'affiliate_id' => $data['affiliate_id'],
|
||||
);
|
||||
$this->request('order/edit', array('order_id' => $order_id), $order);
|
||||
}
|
||||
|
||||
public function addOrder($data) {
|
||||
$currency = $this->getCookieValue('currency');
|
||||
if($currency) {
|
||||
$a = $this->request('currency', array(), array('currency' => $currency));
|
||||
}
|
||||
|
||||
$customer = array(
|
||||
'store_id' => $data['store_id'],
|
||||
'currency' => $currency != false ? $currency : '',
|
||||
'customer' => $data['customer'],
|
||||
'customer_id' => $data['customer_id'],
|
||||
'customer_group_id' => $data['customer_group_id'],
|
||||
'firstname' => $data['firstname'],
|
||||
'lastname' => $data['lastname'],
|
||||
'email' => $data['email'],
|
||||
'telephone' => $data['telephone'],
|
||||
'fax' => $data['fax'],
|
||||
);
|
||||
$this->request('customer', array(), $customer);
|
||||
|
||||
$products = array();
|
||||
foreach($data['order_product'] as $product) {
|
||||
$product = array(
|
||||
'product_id' => $product['product_id'],
|
||||
'quantity' => $product['quantity'],
|
||||
);
|
||||
$products[] = $product;
|
||||
}
|
||||
$this->request('cart/add', array(), array('product' => $products));
|
||||
|
||||
$payment_address = array(
|
||||
'payment_address' => $data['payment_address'],
|
||||
'firstname' => $data['payment_firstname'],
|
||||
'lastname' => $data['payment_lastname'],
|
||||
'company' => $data['payment_company'],
|
||||
'address_1' => $data['payment_address_1'],
|
||||
'address_2' => $data['payment_address_2'],
|
||||
'city' => $data['payment_city'],
|
||||
'postcode' => $data['payment_postcode'],
|
||||
'country_id' => $data['payment_country_id'],
|
||||
'zone_id' => $data['payment_zone_id'],
|
||||
);
|
||||
$this->request('payment/address', array(), $payment_address);
|
||||
|
||||
$shipping_address = array(
|
||||
'shipping_address' => $data['shipping_address'],
|
||||
'firstname' => $data['shipping_firstname'],
|
||||
'lastname' => $data['shipping_lastname'],
|
||||
'company' => $data['shipping_company'],
|
||||
'address_1' => $data['shipping_address_1'],
|
||||
'address_2' => $data['shipping_address_2'],
|
||||
'city' => $data['shipping_city'],
|
||||
'postcode' => $data['shipping_postcode'],
|
||||
'country_id' => $data['shipping_country_id'],
|
||||
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
|
||||
);
|
||||
$this->request('shipping/address', array(), $shipping_address);
|
||||
|
||||
$this->request('shipping/methods', array(), array());
|
||||
$shipping_method = array(
|
||||
'shipping_method' => $data['shipping_code']
|
||||
);
|
||||
$this->request('shipping/method', array(), $shipping_method);
|
||||
|
||||
$this->request('payment/methods', array(), array());
|
||||
$payment_method = array(
|
||||
'payment_method' => $data['payment_code']
|
||||
);
|
||||
$this->request('payment/method', array(), $payment_method);
|
||||
|
||||
$order = array(
|
||||
'shipping_method' => $data['shipping_code'],
|
||||
'payment_method' => $data['payment_code'],
|
||||
'order_status_id' => $data['order_status_id'],
|
||||
'comment' => $data['comment'],
|
||||
'affiliate_id' => $data['affiliate_id'],
|
||||
);
|
||||
$this->request('order/add', array(), $order);
|
||||
}
|
||||
|
||||
private function getInnerIpAddr() {
|
||||
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
|
||||
|
||||
if ($opencartStoreInfo) {
|
||||
$url = $opencartStoreInfo['ssl'];
|
||||
} else {
|
||||
$url = HTTPS_CATALOG;
|
||||
}
|
||||
|
||||
$curl = curl_init();
|
||||
|
||||
// Set SSL if required
|
||||
if (substr($url, 0, 5) == 'https') {
|
||||
curl_setopt($curl, CURLOPT_PORT, 443);
|
||||
}
|
||||
|
||||
curl_setopt($curl, CURLOPT_HEADER, false);
|
||||
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($curl, CURLOPT_FORBID_REUSE, false);
|
||||
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($curl, CURLOPT_URL, $url . 'system/cron/getmyip.php');
|
||||
|
||||
return curl_exec($curl);
|
||||
}
|
||||
}
|
|
@ -1,811 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* retailCRM API client class
|
||||
*/
|
||||
class RetailcrmApiClient
|
||||
{
|
||||
const VERSION = 'v3';
|
||||
|
||||
protected $client;
|
||||
|
||||
/**
|
||||
* Site code
|
||||
*/
|
||||
protected $siteCode;
|
||||
|
||||
/**
|
||||
* Client creating
|
||||
*
|
||||
* @param string $url
|
||||
* @param string $apiKey
|
||||
* @param string $site
|
||||
* @return mixed
|
||||
*/
|
||||
public function __construct($url, $apiKey, $site = null)
|
||||
{
|
||||
if ('/' != substr($url, strlen($url) - 1, 1)) {
|
||||
$url .= '/';
|
||||
}
|
||||
|
||||
$url = $url . 'api/' . self::VERSION;
|
||||
|
||||
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
|
||||
$this->siteCode = $site;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a order
|
||||
*
|
||||
* @param array $order
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersCreate(array $order, $site = null)
|
||||
{
|
||||
if (!sizeof($order)) {
|
||||
throw new InvalidArgumentException('Parameter `order` must contains a data');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/orders/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
|
||||
'order' => json_encode($order)
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a order
|
||||
*
|
||||
* @param array $order
|
||||
* @param string $by
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersEdit(array $order, $by = 'externalId', $site = null)
|
||||
{
|
||||
if (!sizeof($order)) {
|
||||
throw new InvalidArgumentException('Parameter `order` must contains a data');
|
||||
}
|
||||
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
if (!isset($order[$by])) {
|
||||
throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by));
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/orders/" . $order[$by] . "/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, array(
|
||||
'order' => json_encode($order),
|
||||
'by' => $by,
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload array of the orders
|
||||
*
|
||||
* @param array $orders
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersUpload(array $orders, $site = null)
|
||||
{
|
||||
if (!sizeof($orders)) {
|
||||
throw new InvalidArgumentException('Parameter `orders` must contains array of the orders');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/orders/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
|
||||
'orders' => json_encode($orders),
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get order by id or externalId
|
||||
*
|
||||
* @param string $id
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersGet($id, $by = 'externalId', $site = null)
|
||||
{
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
return $this->client->makeRequest("/orders/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array(
|
||||
'by' => $by
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a orders history
|
||||
*
|
||||
* @param DateTime $startDate (default: null)
|
||||
* @param DateTime $endDate (default: null)
|
||||
* @param int $limit (default: 100)
|
||||
* @param int $offset (default: 0)
|
||||
* @param bool $skipMyChanges (default: true)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersHistory(
|
||||
DateTime $startDate = null,
|
||||
DateTime $endDate = null,
|
||||
$limit = 100,
|
||||
$offset = 0,
|
||||
$skipMyChanges = true
|
||||
) {
|
||||
$parameters = array();
|
||||
|
||||
if ($startDate) {
|
||||
$parameters['startDate'] = $startDate->format('Y-m-d H:i:s');
|
||||
}
|
||||
if ($endDate) {
|
||||
$parameters['endDate'] = $endDate->format('Y-m-d H:i:s');
|
||||
}
|
||||
if ($limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
if ($offset) {
|
||||
$parameters['offset'] = (int) $offset;
|
||||
}
|
||||
if ($skipMyChanges) {
|
||||
$parameters['skipMyChanges'] = (bool) $skipMyChanges;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest('/orders/history', RetailcrmHttpClient::METHOD_GET, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns filtered orders list
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersList(array $filter = array(), $page = null, $limit = null)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (sizeof($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest('/orders', RetailcrmHttpClient::METHOD_GET, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns statuses of the orders
|
||||
*
|
||||
* @param array $ids (default: array())
|
||||
* @param array $externalIds (default: array())
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersStatuses(array $ids = array(), array $externalIds = array())
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (sizeof($ids)) {
|
||||
$parameters['ids'] = $ids;
|
||||
}
|
||||
if (sizeof($externalIds)) {
|
||||
$parameters['externalIds'] = $externalIds;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest('/orders/statuses', RetailcrmHttpClient::METHOD_GET, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save order IDs' (id and externalId) association in the CRM
|
||||
*
|
||||
* @param array $ids
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersFixExternalIds(array $ids)
|
||||
{
|
||||
if (!sizeof($ids)) {
|
||||
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/orders/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array(
|
||||
'orders' => json_encode($ids),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get orders assembly history
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (sizeof($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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a customer
|
||||
*
|
||||
* @param array $customer
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersCreate(array $customer, $site = null)
|
||||
{
|
||||
if (!sizeof($customer)) {
|
||||
throw new InvalidArgumentException('Parameter `customer` must contains a data');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/customers/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
|
||||
'customer' => json_encode($customer)
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit a customer
|
||||
*
|
||||
* @param array $customer
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersEdit(array $customer, $by = 'externalId', $site = null)
|
||||
{
|
||||
if (!sizeof($customer)) {
|
||||
throw new InvalidArgumentException('Parameter `customer` must contains a data');
|
||||
}
|
||||
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
if (!isset($customer[$by])) {
|
||||
throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by));
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/customers/" . $customer[$by] . "/edit",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite(
|
||||
$site,
|
||||
array(
|
||||
'customer' => json_encode($customer),
|
||||
'by' => $by
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload array of the customers
|
||||
*
|
||||
* @param array $customers
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersUpload(array $customers, $site = null)
|
||||
{
|
||||
if (!sizeof($customers)) {
|
||||
throw new InvalidArgumentException('Parameter `customers` must contains array of the customers');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/customers/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
|
||||
'customers' => json_encode($customers),
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get customer by id or externalId
|
||||
*
|
||||
* @param string $id
|
||||
* @param string $by (default: 'externalId')
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersGet($id, $by = 'externalId', $site = null)
|
||||
{
|
||||
$this->checkIdParameter($by);
|
||||
|
||||
return $this->client->makeRequest("/customers/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array(
|
||||
'by' => $by
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns filtered customers list
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersList(array $filter = array(), $page = null, $limit = null)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (sizeof($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest('/customers', RetailcrmHttpClient::METHOD_GET, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save customer IDs' (id and externalId) association in the CRM
|
||||
*
|
||||
* @param array $ids
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function customersFixExternalIds(array $ids)
|
||||
{
|
||||
if (!sizeof($ids)) {
|
||||
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest("/customers/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array(
|
||||
'customers' => json_encode($ids),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get purchace prices & stock balance
|
||||
*
|
||||
* @param array $filter (default: array())
|
||||
* @param int $page (default: null)
|
||||
* @param int $limit (default: null)
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null)
|
||||
{
|
||||
$parameters = array();
|
||||
|
||||
if (sizeof($filter)) {
|
||||
$parameters['filter'] = $filter;
|
||||
}
|
||||
if (null !== $page) {
|
||||
$parameters['page'] = (int) $page;
|
||||
}
|
||||
if (null !== $limit) {
|
||||
$parameters['limit'] = (int) $limit;
|
||||
}
|
||||
|
||||
return $this->client->makeRequest('/store/inventories', RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, $parameters));
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload store inventories
|
||||
*
|
||||
* @param array $offers
|
||||
* @param string $site (default: null)
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function storeInventoriesUpload(array $offers, $site = null)
|
||||
{
|
||||
if (!sizeof($offers)) {
|
||||
throw new InvalidArgumentException('Parameter `offers` must contains array of the customers');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
"/store/inventories/upload",
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
$this->fillSite($site, array('offers' => json_encode($offers)))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns deliveryServices list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function deliveryServicesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/delivery-services', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns deliveryTypes list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function deliveryTypesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/delivery-types', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns orderMethods list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function orderMethodsList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/order-methods', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns orderTypes list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function orderTypesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/order-types', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns paymentStatuses list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function paymentStatusesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/payment-statuses', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns paymentTypes list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function paymentTypesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/payment-types', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns productStatuses list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function productStatusesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/product-statuses', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns statusGroups list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function statusGroupsList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/status-groups', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns statuses list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function statusesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/statuses', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns sites list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function sitesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/sites', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns stores list
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function storesList()
|
||||
{
|
||||
return $this->client->makeRequest('/reference/stores', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit deliveryService
|
||||
*
|
||||
* @param array $data delivery service data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function deliveryServicesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/delivery-services/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'deliveryService' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit deliveryType
|
||||
*
|
||||
* @param array $data delivery type data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function deliveryTypesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/delivery-types/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'deliveryType' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit orderMethod
|
||||
*
|
||||
* @param array $data order method data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function orderMethodsEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/order-methods/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'orderMethod' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit orderType
|
||||
*
|
||||
* @param array $data order type data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function orderTypesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/order-types/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'orderType' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit paymentStatus
|
||||
*
|
||||
* @param array $data payment status data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function paymentStatusesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/payment-statuses/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'paymentStatus' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit paymentType
|
||||
*
|
||||
* @param array $data payment type data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function paymentTypesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/payment-types/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'paymentType' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit productStatus
|
||||
*
|
||||
* @param array $data product status data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function productStatusesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/product-statuses/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'productStatus' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit order status
|
||||
*
|
||||
* @param array $data status data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function statusesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/statuses/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'status' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit site
|
||||
*
|
||||
* @param array $data site data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function sitesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/sites/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'site' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit store
|
||||
*
|
||||
* @param array $data site data
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function storesEdit(array $data)
|
||||
{
|
||||
if (!isset($data['code'])) {
|
||||
throw new InvalidArgumentException('Data must contain "code" parameter.');
|
||||
}
|
||||
|
||||
if (!isset($data['name'])) {
|
||||
throw new InvalidArgumentException('Data must contain "name" parameter.');
|
||||
}
|
||||
|
||||
return $this->client->makeRequest(
|
||||
'/reference/stores/' . $data['code'] . '/edit',
|
||||
RetailcrmHttpClient::METHOD_POST,
|
||||
array(
|
||||
'store' => json_encode($data)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update CRM basic statistic
|
||||
*
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function statisticUpdate()
|
||||
{
|
||||
return $this->client->makeRequest('/statistic/update', RetailcrmHttpClient::METHOD_GET);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return current site
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSite()
|
||||
{
|
||||
return $this->siteCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set site
|
||||
*
|
||||
* @param string $site
|
||||
* @return void
|
||||
*/
|
||||
public function setSite($site)
|
||||
{
|
||||
$this->siteCode = $site;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check ID parameter
|
||||
*
|
||||
* @param string $by
|
||||
* @return bool
|
||||
*/
|
||||
protected function checkIdParameter($by)
|
||||
{
|
||||
$allowedForBy = array('externalId', 'id');
|
||||
if (!in_array($by, $allowedForBy)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Value "%s" for parameter "by" is not valid. Allowed values are %s.',
|
||||
$by,
|
||||
implode(', ', $allowedForBy)
|
||||
));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill params by site value
|
||||
*
|
||||
* @param string $site
|
||||
* @param array $params
|
||||
* @return array
|
||||
*/
|
||||
protected function fillSite($site, array $params)
|
||||
{
|
||||
if ($site) {
|
||||
$params['site'] = $site;
|
||||
} elseif ($this->siteCode) {
|
||||
$params['site'] = $this->siteCode;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
}
|
|
@ -1,113 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* HTTP client
|
||||
*/
|
||||
class RetailcrmHttpClient
|
||||
{
|
||||
const METHOD_GET = 'GET';
|
||||
const METHOD_POST = 'POST';
|
||||
|
||||
protected $url;
|
||||
protected $defaultParameters;
|
||||
protected $retry;
|
||||
|
||||
public function __construct($url, array $defaultParameters = array())
|
||||
{
|
||||
if (false === stripos($url, 'https://')) {
|
||||
throw new InvalidArgumentException('API schema requires HTTPS protocol');
|
||||
}
|
||||
|
||||
$this->url = $url;
|
||||
$this->defaultParameters = $defaultParameters;
|
||||
$this->retry = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make HTTP request
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $method (default: 'GET')
|
||||
* @param array $parameters (default: array())
|
||||
* @param int $timeout
|
||||
* @param bool $verify
|
||||
* @param bool $debug
|
||||
* @return RetailcrmApiResponse
|
||||
*/
|
||||
public function makeRequest(
|
||||
$path,
|
||||
$method,
|
||||
array $parameters = array(),
|
||||
$timeout = 30,
|
||||
$verify = false,
|
||||
$debug = false
|
||||
) {
|
||||
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
|
||||
if (!in_array($method, $allowedMethods)) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'Method "%s" is not valid. Allowed methods are %s',
|
||||
$method,
|
||||
implode(', ', $allowedMethods)
|
||||
));
|
||||
}
|
||||
|
||||
$parameters = array_merge($this->defaultParameters, $parameters);
|
||||
|
||||
$url = $this->url . $path;
|
||||
|
||||
if (self::METHOD_GET === $method && sizeof($parameters)) {
|
||||
$url .= '?' . http_build_query($parameters, '', '&');
|
||||
}
|
||||
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
|
||||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
|
||||
curl_setopt($ch, CURLOPT_FAILONERROR, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $verify);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $verify);
|
||||
|
||||
if (!$debug) {
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout);
|
||||
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout);
|
||||
} else {
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT_MS, (int) $timeout + ($this->retry * 2000));
|
||||
}
|
||||
|
||||
if (self::METHOD_POST === $method) {
|
||||
curl_setopt($ch, CURLOPT_POST, true);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
|
||||
}
|
||||
|
||||
$responseBody = curl_exec($ch);
|
||||
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
|
||||
curl_close($ch);
|
||||
|
||||
if ($errno && in_array($errno, array(6, 7, 28, 34, 35)) && $this->retry < 3) {
|
||||
$errno = null;
|
||||
$error = null;
|
||||
$this->retry += 1;
|
||||
$this->makeRequest(
|
||||
$path,
|
||||
$method,
|
||||
$parameters,
|
||||
$timeout,
|
||||
$verify,
|
||||
$debug
|
||||
);
|
||||
}
|
||||
|
||||
if ($errno) {
|
||||
throw new CurlException($error, $errno);
|
||||
}
|
||||
|
||||
return new RetailcrmApiResponse($statusCode, $responseBody);
|
||||
}
|
||||
|
||||
public function getRetry()
|
||||
{
|
||||
return $this->retry;
|
||||
}
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Class RequestProxy
|
||||
* @package RetailCrm\Component
|
||||
*/
|
||||
class RetailcrmProxy
|
||||
{
|
||||
|
||||
private $api;
|
||||
private $log;
|
||||
|
||||
public function __construct($url, $key, $log)
|
||||
{
|
||||
$this->api = new RetailcrmApiClient($url, $key);
|
||||
$this->log = $log;
|
||||
}
|
||||
|
||||
public function __call($method, $arguments)
|
||||
{
|
||||
try {
|
||||
$response = call_user_func_array(array($this->api, $method), $arguments);
|
||||
|
||||
if (!$response->isSuccessful()) {
|
||||
error_log("[$method] " . $response->getErrorMsg() . "\n", 3, $this->log);
|
||||
if (isset($response['errors'])) {
|
||||
$error = implode("\n", $response['errors']);
|
||||
error_log($error . "\n", 3, $this->log);
|
||||
}
|
||||
$response = false;
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (CurlException $e) {
|
||||
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log);
|
||||
return false;
|
||||
} catch (InvalidJsonException $e) {
|
||||
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
103
tests/admin/ControllerRetailcrmAdminTest.php
Normal file
103
tests/admin/ControllerRetailcrmAdminTest.php
Normal file
|
@ -0,0 +1,103 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ControllerRetailcrmAdminTest extends TestCase
|
||||
{
|
||||
const MODULE_TITLE = 'retailcrm';
|
||||
|
||||
public function setUp()
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$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'])) {
|
||||
$permissions['access'][] = 'extension/module/retailcrm';
|
||||
$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')
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
}
|
||||
|
||||
public function testController()
|
||||
{
|
||||
$this->login('admin', 'admin');
|
||||
|
||||
$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 testGetAvailableTypes()
|
||||
{
|
||||
$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']);
|
||||
}
|
||||
}
|
75
tests/admin/ModelRetailcrmOrderAdminTest.php
Normal file
75
tests/admin/ModelRetailcrmOrderAdminTest.php
Normal file
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
|
||||
|
||||
class ModelRetailcrmOrderAdminTest extends TestCase
|
||||
{
|
||||
private $orderModel;
|
||||
private $apiClientMock;
|
||||
private $settingModel;
|
||||
|
||||
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(
|
||||
'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']);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue