Compare commits
4 Commits
ccee5f9f56
...
feature/ma
Author | SHA1 | Date | |
---|---|---|---|
47679cd4e4 | |||
0f8db5a3f8 | |||
c38e89d3f1 | |||
307f2ac7d7 |
@ -2,15 +2,15 @@ FROM php:8.4-cli
|
|||||||
|
|
||||||
ENV TZ "${TZ}"
|
ENV TZ "${TZ}"
|
||||||
ENV APP_NAME "${APP_NAME}"
|
ENV APP_NAME "${APP_NAME}"
|
||||||
ENV API_URL "${API_URL}"
|
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends cron rsyslog nano && rm -r /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y --no-install-recommends cron rsyslog nano beanstalkd \
|
||||||
|
&& rm -r /var/lib/apt/lists/*
|
||||||
|
|
||||||
RUN pecl install xdebug-3.4.2 \
|
RUN pecl install xdebug-3.4.2 \
|
||||||
&& docker-php-ext-enable xdebug \
|
&& docker-php-ext-enable xdebug \
|
||||||
&& echo $TZ > /etc/timezone
|
&& echo $TZ > /etc/timezone
|
||||||
|
|
||||||
COPY --chmod=550 ./cli/entrypoint /root/entrypoint
|
COPY --chmod=550 ./cli/start_command /root/start_command
|
||||||
|
|
||||||
COPY ./php-errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
|
COPY ./php-errors.ini /usr/local/etc/php/conf.d/docker-php-errors.ini
|
||||||
COPY ./php-timezone.ini /usr/local/etc/php/conf.d/docker-php-timezone.ini
|
COPY ./php-timezone.ini /usr/local/etc/php/conf.d/docker-php-timezone.ini
|
||||||
@ -19,4 +19,4 @@ WORKDIR /code/bin
|
|||||||
|
|
||||||
COPY --chmod=644 ./cli/crontab /var/spool/cron/crontabs/root
|
COPY --chmod=644 ./cli/crontab /var/spool/cron/crontabs/root
|
||||||
|
|
||||||
CMD [ "/root/entrypoint" ]
|
CMD [ "/root/start_command" ]
|
||||||
|
@ -3,7 +3,7 @@ FROM php:8.4-fpm
|
|||||||
ENV TZ=America/Santiago
|
ENV TZ=America/Santiago
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends libzip-dev libicu-dev git \
|
RUN apt-get update && apt-get install -y --no-install-recommends libzip-dev libicu-dev git \
|
||||||
libpng-dev unzip tzdata libxml2-dev \
|
libpng-dev unzip tzdata libxml2-dev beanstalkd \
|
||||||
&& rm -r /var/lib/apt/lists/* \
|
&& rm -r /var/lib/apt/lists/* \
|
||||||
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath dom \
|
&& docker-php-ext-install pdo pdo_mysql zip intl gd bcmath dom \
|
||||||
&& pecl install xdebug-3.4.2 \
|
&& pecl install xdebug-3.4.2 \
|
||||||
|
0
app/bin/console
Normal file → Executable file
0
app/bin/console
Normal file → Executable file
0
app/bin/integration_tests
Normal file → Executable file
0
app/bin/integration_tests
Normal file → Executable file
0
app/bin/performance_tests
Normal file → Executable file
0
app/bin/performance_tests
Normal file → Executable file
0
app/bin/unit_tests
Normal file → Executable file
0
app/bin/unit_tests
Normal file → Executable file
10
app/common/Ideal/Service/Repository.php
Normal file
10
app/common/Ideal/Service/Repository.php
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Common\Ideal\Service;
|
||||||
|
|
||||||
|
use Incoviba\Common\Define;
|
||||||
|
use Incoviba\Common\Ideal;
|
||||||
|
|
||||||
|
abstract class Repository extends Ideal\Service
|
||||||
|
{
|
||||||
|
abstract public function getRepository(): Define\Repository;
|
||||||
|
}
|
@ -64,10 +64,10 @@ class Select extends Ideal\Query implements Define\Query\Select
|
|||||||
public function having(array|string $conditions): Select
|
public function having(array|string $conditions): Select
|
||||||
{
|
{
|
||||||
if (is_string($conditions)) {
|
if (is_string($conditions)) {
|
||||||
return $this->addCondition($conditions);
|
return $this->addHaving($conditions);
|
||||||
}
|
}
|
||||||
foreach ($conditions as $condition) {
|
foreach ($conditions as $condition) {
|
||||||
$this->addCondition($condition);
|
$this->addHaving($condition);
|
||||||
}
|
}
|
||||||
return $this;
|
return $this;
|
||||||
}
|
}
|
||||||
|
@ -8,11 +8,13 @@
|
|||||||
"ext-gd": "*",
|
"ext-gd": "*",
|
||||||
"ext-openssl": "*",
|
"ext-openssl": "*",
|
||||||
"ext-pdo": "*",
|
"ext-pdo": "*",
|
||||||
|
"ext-sockets": "*",
|
||||||
"berrnd/slim-blade-view": "^1",
|
"berrnd/slim-blade-view": "^1",
|
||||||
"guzzlehttp/guzzle": "^7",
|
"guzzlehttp/guzzle": "^7",
|
||||||
"monolog/monolog": "^3",
|
"monolog/monolog": "^3",
|
||||||
"nyholm/psr7": "^1",
|
"nyholm/psr7": "^1",
|
||||||
"nyholm/psr7-server": "^1",
|
"nyholm/psr7-server": "^1",
|
||||||
|
"pda/pheanstalk": "^7.0",
|
||||||
"php-di/php-di": "^7",
|
"php-di/php-di": "^7",
|
||||||
"php-di/slim-bridge": "^3",
|
"php-di/slim-bridge": "^3",
|
||||||
"phpoffice/phpspreadsheet": "^3",
|
"phpoffice/phpspreadsheet": "^3",
|
||||||
|
496
app/fcgi.conf
Normal file
496
app/fcgi.conf
Normal file
@ -0,0 +1,496 @@
|
|||||||
|
; Start a new pool named 'www'.
|
||||||
|
; the variable $pool can be used in any directive and will be replaced by the
|
||||||
|
; pool name ('www' here)
|
||||||
|
[fcgi]
|
||||||
|
|
||||||
|
; Per pool prefix
|
||||||
|
; It only applies on the following directives:
|
||||||
|
; - 'access.log'
|
||||||
|
; - 'slowlog'
|
||||||
|
; - 'listen' (unixsocket)
|
||||||
|
; - 'chroot'
|
||||||
|
; - 'chdir'
|
||||||
|
; - 'php_values'
|
||||||
|
; - 'php_admin_values'
|
||||||
|
; When not set, the global prefix (or NONE) applies instead.
|
||||||
|
; Note: This directive can also be relative to the global prefix.
|
||||||
|
; Default Value: none
|
||||||
|
;prefix = /path/to/pools/$pool
|
||||||
|
|
||||||
|
; Unix user/group of the child processes. This can be used only if the master
|
||||||
|
; process running user is root. It is set after the child process is created.
|
||||||
|
; The user and group can be specified either by their name or by their numeric
|
||||||
|
; IDs.
|
||||||
|
; Note: If the user is root, the executable needs to be started with
|
||||||
|
; --allow-to-run-as-root option to work.
|
||||||
|
; Default Values: The user is set to master process running user by default.
|
||||||
|
; If the group is not set, the user's group is used.
|
||||||
|
user = www-data
|
||||||
|
group = www-data
|
||||||
|
|
||||||
|
; The address on which to accept FastCGI requests.
|
||||||
|
; Valid syntaxes are:
|
||||||
|
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
|
||||||
|
; a specific port;
|
||||||
|
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
|
||||||
|
; a specific port;
|
||||||
|
; 'port' - to listen on a TCP socket to all addresses
|
||||||
|
; (IPv6 and IPv4-mapped) on a specific port;
|
||||||
|
; '/path/to/unix/socket' - to listen on a unix socket.
|
||||||
|
; Note: This value is mandatory.
|
||||||
|
;listen = 127.0.0.1:9000
|
||||||
|
listen = 9090
|
||||||
|
|
||||||
|
; Set listen(2) backlog.
|
||||||
|
; Default Value: 511 (-1 on Linux, FreeBSD and OpenBSD)
|
||||||
|
;listen.backlog = 511
|
||||||
|
|
||||||
|
; Set permissions for unix socket, if one is used. In Linux, read/write
|
||||||
|
; permissions must be set in order to allow connections from a web server. Many
|
||||||
|
; BSD-derived systems allow connections regardless of permissions. The owner
|
||||||
|
; and group can be specified either by name or by their numeric IDs.
|
||||||
|
; Default Values: Owner is set to the master process running user. If the group
|
||||||
|
; is not set, the owner's group is used. Mode is set to 0660.
|
||||||
|
;listen.owner = www-data
|
||||||
|
;listen.group = www-data
|
||||||
|
;listen.mode = 0660
|
||||||
|
|
||||||
|
; When POSIX Access Control Lists are supported you can set them using
|
||||||
|
; these options, value is a comma separated list of user/group names.
|
||||||
|
; When set, listen.owner and listen.group are ignored
|
||||||
|
;listen.acl_users =
|
||||||
|
;listen.acl_groups =
|
||||||
|
|
||||||
|
; List of addresses (IPv4/IPv6) of FastCGI clients which are allowed to connect.
|
||||||
|
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
|
||||||
|
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
|
||||||
|
; must be separated by a comma. If this value is left blank, connections will be
|
||||||
|
; accepted from any ip address.
|
||||||
|
; Default Value: any
|
||||||
|
;listen.allowed_clients = 127.0.0.1
|
||||||
|
|
||||||
|
; Set the associated the route table (FIB). FreeBSD only
|
||||||
|
; Default Value: -1
|
||||||
|
;listen.setfib = 1
|
||||||
|
|
||||||
|
; Specify the nice(2) priority to apply to the pool processes (only if set)
|
||||||
|
; The value can vary from -19 (highest priority) to 20 (lower priority)
|
||||||
|
; Note: - It will only work if the FPM master process is launched as root
|
||||||
|
; - The pool processes will inherit the master process priority
|
||||||
|
; unless it specified otherwise
|
||||||
|
; Default Value: no set
|
||||||
|
; process.priority = -19
|
||||||
|
|
||||||
|
; Set the process dumpable flag (PR_SET_DUMPABLE prctl for Linux or
|
||||||
|
; PROC_TRACE_CTL procctl for FreeBSD) even if the process user
|
||||||
|
; or group is different than the master process user. It allows to create process
|
||||||
|
; core dump and ptrace the process for the pool user.
|
||||||
|
; Default Value: no
|
||||||
|
; process.dumpable = yes
|
||||||
|
|
||||||
|
; Choose how the process manager will control the number of child processes.
|
||||||
|
; Possible Values:
|
||||||
|
; static - a fixed number (pm.max_children) of child processes;
|
||||||
|
; dynamic - the number of child processes are set dynamically based on the
|
||||||
|
; following directives. With this process management, there will be
|
||||||
|
; always at least 1 children.
|
||||||
|
; pm.max_children - the maximum number of children that can
|
||||||
|
; be alive at the same time.
|
||||||
|
; pm.start_servers - the number of children created on startup.
|
||||||
|
; pm.min_spare_servers - the minimum number of children in 'idle'
|
||||||
|
; state (waiting to process). If the number
|
||||||
|
; of 'idle' processes is less than this
|
||||||
|
; number then some children will be created.
|
||||||
|
; pm.max_spare_servers - the maximum number of children in 'idle'
|
||||||
|
; state (waiting to process). If the number
|
||||||
|
; of 'idle' processes is greater than this
|
||||||
|
; number then some children will be killed.
|
||||||
|
; pm.max_spawn_rate - the maximum number of rate to spawn child
|
||||||
|
; processes at once.
|
||||||
|
; ondemand - no children are created at startup. Children will be forked when
|
||||||
|
; new requests will connect. The following parameter are used:
|
||||||
|
; pm.max_children - the maximum number of children that
|
||||||
|
; can be alive at the same time.
|
||||||
|
; pm.process_idle_timeout - The number of seconds after which
|
||||||
|
; an idle process will be killed.
|
||||||
|
; Note: This value is mandatory.
|
||||||
|
pm = ondemand
|
||||||
|
|
||||||
|
; The number of child processes to be created when pm is set to 'static' and the
|
||||||
|
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
|
||||||
|
; This value sets the limit on the number of simultaneous requests that will be
|
||||||
|
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
|
||||||
|
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
|
||||||
|
; CGI. The below defaults are based on a server without much resources. Don't
|
||||||
|
; forget to tweak pm.* to fit your needs.
|
||||||
|
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
|
||||||
|
; Note: This value is mandatory.
|
||||||
|
pm.max_children = 2
|
||||||
|
|
||||||
|
; The number of child processes created on startup.
|
||||||
|
; Note: Used only when pm is set to 'dynamic'
|
||||||
|
; Default Value: (min_spare_servers + max_spare_servers) / 2
|
||||||
|
;pm.start_servers = 2
|
||||||
|
|
||||||
|
; The desired minimum number of idle server processes.
|
||||||
|
; Note: Used only when pm is set to 'dynamic'
|
||||||
|
; Note: Mandatory when pm is set to 'dynamic'
|
||||||
|
;pm.min_spare_servers = 1
|
||||||
|
|
||||||
|
; The desired maximum number of idle server processes.
|
||||||
|
; Note: Used only when pm is set to 'dynamic'
|
||||||
|
; Note: Mandatory when pm is set to 'dynamic'
|
||||||
|
;pm.max_spare_servers = 3
|
||||||
|
|
||||||
|
; The number of rate to spawn child processes at once.
|
||||||
|
; Note: Used only when pm is set to 'dynamic'
|
||||||
|
; Note: Mandatory when pm is set to 'dynamic'
|
||||||
|
; Default Value: 32
|
||||||
|
;pm.max_spawn_rate = 32
|
||||||
|
|
||||||
|
; The number of seconds after which an idle process will be killed.
|
||||||
|
; Note: Used only when pm is set to 'ondemand'
|
||||||
|
; Default Value: 10s
|
||||||
|
;pm.process_idle_timeout = 10s;
|
||||||
|
pm.process_idle_timeout = 10s
|
||||||
|
|
||||||
|
; The number of requests each child process should execute before respawning.
|
||||||
|
; This can be useful to work around memory leaks in 3rd party libraries. For
|
||||||
|
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
|
||||||
|
; Default Value: 0
|
||||||
|
;pm.max_requests = 500
|
||||||
|
|
||||||
|
; The URI to view the FPM status page. If this value is not set, no URI will be
|
||||||
|
; recognized as a status page. It shows the following information:
|
||||||
|
; pool - the name of the pool;
|
||||||
|
; process manager - static, dynamic or ondemand;
|
||||||
|
; start time - the date and time FPM has started;
|
||||||
|
; start since - number of seconds since FPM has started;
|
||||||
|
; accepted conn - the number of request accepted by the pool;
|
||||||
|
; listen queue - the number of request in the queue of pending
|
||||||
|
; connections (see backlog in listen(2));
|
||||||
|
; max listen queue - the maximum number of requests in the queue
|
||||||
|
; of pending connections since FPM has started;
|
||||||
|
; listen queue len - the size of the socket queue of pending connections;
|
||||||
|
; idle processes - the number of idle processes;
|
||||||
|
; active processes - the number of active processes;
|
||||||
|
; total processes - the number of idle + active processes;
|
||||||
|
; max active processes - the maximum number of active processes since FPM
|
||||||
|
; has started;
|
||||||
|
; max children reached - number of times, the process limit has been reached,
|
||||||
|
; when pm tries to start more children (works only for
|
||||||
|
; pm 'dynamic' and 'ondemand');
|
||||||
|
; Value are updated in real time.
|
||||||
|
; Example output:
|
||||||
|
; pool: www
|
||||||
|
; process manager: static
|
||||||
|
; start time: 01/Jul/2011:17:53:49 +0200
|
||||||
|
; start since: 62636
|
||||||
|
; accepted conn: 190460
|
||||||
|
; listen queue: 0
|
||||||
|
; max listen queue: 1
|
||||||
|
; listen queue len: 42
|
||||||
|
; idle processes: 4
|
||||||
|
; active processes: 11
|
||||||
|
; total processes: 15
|
||||||
|
; max active processes: 12
|
||||||
|
; max children reached: 0
|
||||||
|
;
|
||||||
|
; By default the status page output is formatted as text/plain. Passing either
|
||||||
|
; 'html', 'xml' or 'json' in the query string will return the corresponding
|
||||||
|
; output syntax. Example:
|
||||||
|
; http://www.foo.bar/status
|
||||||
|
; http://www.foo.bar/status?json
|
||||||
|
; http://www.foo.bar/status?html
|
||||||
|
; http://www.foo.bar/status?xml
|
||||||
|
;
|
||||||
|
; By default the status page only outputs short status. Passing 'full' in the
|
||||||
|
; query string will also return status for each pool process.
|
||||||
|
; Example:
|
||||||
|
; http://www.foo.bar/status?full
|
||||||
|
; http://www.foo.bar/status?json&full
|
||||||
|
; http://www.foo.bar/status?html&full
|
||||||
|
; http://www.foo.bar/status?xml&full
|
||||||
|
; The Full status returns for each process:
|
||||||
|
; pid - the PID of the process;
|
||||||
|
; state - the state of the process (Idle, Running, ...);
|
||||||
|
; start time - the date and time the process has started;
|
||||||
|
; start since - the number of seconds since the process has started;
|
||||||
|
; requests - the number of requests the process has served;
|
||||||
|
; request duration - the duration in µs of the requests;
|
||||||
|
; request method - the request method (GET, POST, ...);
|
||||||
|
; request URI - the request URI with the query string;
|
||||||
|
; content length - the content length of the request (only with POST);
|
||||||
|
; user - the user (PHP_AUTH_USER) (or '-' if not set);
|
||||||
|
; script - the main script called (or '-' if not set);
|
||||||
|
; last request cpu - the %cpu the last request consumed
|
||||||
|
; it's always 0 if the process is not in Idle state
|
||||||
|
; because CPU calculation is done when the request
|
||||||
|
; processing has terminated;
|
||||||
|
; last request memory - the max amount of memory the last request consumed
|
||||||
|
; it's always 0 if the process is not in Idle state
|
||||||
|
; because memory calculation is done when the request
|
||||||
|
; processing has terminated;
|
||||||
|
; If the process is in Idle state, then information is related to the
|
||||||
|
; last request the process has served. Otherwise information is related to
|
||||||
|
; the current request being served.
|
||||||
|
; Example output:
|
||||||
|
; ************************
|
||||||
|
; pid: 31330
|
||||||
|
; state: Running
|
||||||
|
; start time: 01/Jul/2011:17:53:49 +0200
|
||||||
|
; start since: 63087
|
||||||
|
; requests: 12808
|
||||||
|
; request duration: 1250261
|
||||||
|
; request method: GET
|
||||||
|
; request URI: /test_mem.php?N=10000
|
||||||
|
; content length: 0
|
||||||
|
; user: -
|
||||||
|
; script: /home/fat/web/docs/php/test_mem.php
|
||||||
|
; last request cpu: 0.00
|
||||||
|
; last request memory: 0
|
||||||
|
;
|
||||||
|
; Note: There is a real-time FPM status monitoring sample web page available
|
||||||
|
; It's available in: /usr/local/share/php/fpm/status.html
|
||||||
|
;
|
||||||
|
; Note: The value must start with a leading slash (/). The value can be
|
||||||
|
; anything, but it may not be a good idea to use the .php extension or it
|
||||||
|
; may conflict with a real PHP file.
|
||||||
|
; Default Value: not set
|
||||||
|
;pm.status_path = /status
|
||||||
|
|
||||||
|
; The address on which to accept FastCGI status request. This creates a new
|
||||||
|
; invisible pool that can handle requests independently. This is useful
|
||||||
|
; if the main pool is busy with long running requests because it is still possible
|
||||||
|
; to get the status before finishing the long running requests.
|
||||||
|
;
|
||||||
|
; Valid syntaxes are:
|
||||||
|
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
|
||||||
|
; a specific port;
|
||||||
|
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
|
||||||
|
; a specific port;
|
||||||
|
; 'port' - to listen on a TCP socket to all addresses
|
||||||
|
; (IPv6 and IPv4-mapped) on a specific port;
|
||||||
|
; '/path/to/unix/socket' - to listen on a unix socket.
|
||||||
|
; Default Value: value of the listen option
|
||||||
|
;pm.status_listen = 127.0.0.1:9001
|
||||||
|
|
||||||
|
; The ping URI to call the monitoring page of FPM. If this value is not set, no
|
||||||
|
; URI will be recognized as a ping page. This could be used to test from outside
|
||||||
|
; that FPM is alive and responding, or to
|
||||||
|
; - create a graph of FPM availability (rrd or such);
|
||||||
|
; - remove a server from a group if it is not responding (load balancing);
|
||||||
|
; - trigger alerts for the operating team (24/7).
|
||||||
|
; Note: The value must start with a leading slash (/). The value can be
|
||||||
|
; anything, but it may not be a good idea to use the .php extension or it
|
||||||
|
; may conflict with a real PHP file.
|
||||||
|
; Default Value: not set
|
||||||
|
;ping.path = /ping
|
||||||
|
|
||||||
|
; This directive may be used to customize the response of a ping request. The
|
||||||
|
; response is formatted as text/plain with a 200 response code.
|
||||||
|
; Default Value: pong
|
||||||
|
;ping.response = pong
|
||||||
|
|
||||||
|
; The access log file
|
||||||
|
; Default: not set
|
||||||
|
;access.log = log/$pool.access.log
|
||||||
|
access.log = /proc/self/fd/2
|
||||||
|
|
||||||
|
; The access log format.
|
||||||
|
; The following syntax is allowed
|
||||||
|
; %%: the '%' character
|
||||||
|
; %C: %CPU used by the request
|
||||||
|
; it can accept the following format:
|
||||||
|
; - %{user}C for user CPU only
|
||||||
|
; - %{system}C for system CPU only
|
||||||
|
; - %{total}C for user + system CPU (default)
|
||||||
|
; %d: time taken to serve the request
|
||||||
|
; it can accept the following format:
|
||||||
|
; - %{seconds}d (default)
|
||||||
|
; - %{milliseconds}d
|
||||||
|
; - %{milli}d
|
||||||
|
; - %{microseconds}d
|
||||||
|
; - %{micro}d
|
||||||
|
; %e: an environment variable (same as $_ENV or $_SERVER)
|
||||||
|
; it must be associated with embraces to specify the name of the env
|
||||||
|
; variable. Some examples:
|
||||||
|
; - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
|
||||||
|
; - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
|
||||||
|
; %f: script filename
|
||||||
|
; %l: content-length of the request (for POST request only)
|
||||||
|
; %m: request method
|
||||||
|
; %M: peak of memory allocated by PHP
|
||||||
|
; it can accept the following format:
|
||||||
|
; - %{bytes}M (default)
|
||||||
|
; - %{kilobytes}M
|
||||||
|
; - %{kilo}M
|
||||||
|
; - %{megabytes}M
|
||||||
|
; - %{mega}M
|
||||||
|
; %n: pool name
|
||||||
|
; %o: output header
|
||||||
|
; it must be associated with embraces to specify the name of the header:
|
||||||
|
; - %{Content-Type}o
|
||||||
|
; - %{X-Powered-By}o
|
||||||
|
; - %{Transfert-Encoding}o
|
||||||
|
; - ....
|
||||||
|
; %p: PID of the child that serviced the request
|
||||||
|
; %P: PID of the parent of the child that serviced the request
|
||||||
|
; %q: the query string
|
||||||
|
; %Q: the '?' character if query string exists
|
||||||
|
; %r: the request URI (without the query string, see %q and %Q)
|
||||||
|
; %R: remote IP address
|
||||||
|
; %s: status (response code)
|
||||||
|
; %t: server time the request was received
|
||||||
|
; it can accept a strftime(3) format:
|
||||||
|
; %d/%b/%Y:%H:%M:%S %z (default)
|
||||||
|
; The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
|
||||||
|
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
|
||||||
|
; %T: time the log has been written (the request has finished)
|
||||||
|
; it can accept a strftime(3) format:
|
||||||
|
; %d/%b/%Y:%H:%M:%S %z (default)
|
||||||
|
; The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
|
||||||
|
; e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
|
||||||
|
; %u: basic auth user if specified in Authorization header
|
||||||
|
;
|
||||||
|
; Default: "%R - %u %t \"%m %r\" %s"
|
||||||
|
;access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{milli}d %{kilo}M %C%%"
|
||||||
|
|
||||||
|
; A list of request_uri values which should be filtered from the access log.
|
||||||
|
;
|
||||||
|
; As a security precaution, this setting will be ignored if:
|
||||||
|
; - the request method is not GET or HEAD; or
|
||||||
|
; - there is a request body; or
|
||||||
|
; - there are query parameters; or
|
||||||
|
; - the response code is outwith the successful range of 200 to 299
|
||||||
|
;
|
||||||
|
; Note: The paths are matched against the output of the access.format tag "%r".
|
||||||
|
; On common configurations, this may look more like SCRIPT_NAME than the
|
||||||
|
; expected pre-rewrite URI.
|
||||||
|
;
|
||||||
|
; Default Value: not set
|
||||||
|
;access.suppress_path[] = /ping
|
||||||
|
;access.suppress_path[] = /health_check.php
|
||||||
|
|
||||||
|
; The log file for slow requests
|
||||||
|
; Default Value: not set
|
||||||
|
; Note: slowlog is mandatory if request_slowlog_timeout is set
|
||||||
|
;slowlog = log/$pool.log.slow
|
||||||
|
|
||||||
|
; The timeout for serving a single request after which a PHP backtrace will be
|
||||||
|
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
|
||||||
|
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
|
||||||
|
; Default Value: 0
|
||||||
|
;request_slowlog_timeout = 0
|
||||||
|
|
||||||
|
; Depth of slow log stack trace.
|
||||||
|
; Default Value: 20
|
||||||
|
;request_slowlog_trace_depth = 20
|
||||||
|
|
||||||
|
; The timeout for serving a single request after which the worker process will
|
||||||
|
; be killed. This option should be used when the 'max_execution_time' ini option
|
||||||
|
; does not stop script execution for some reason. A value of '0' means 'off'.
|
||||||
|
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
|
||||||
|
; Default Value: 0
|
||||||
|
;request_terminate_timeout = 0
|
||||||
|
|
||||||
|
; The timeout set by 'request_terminate_timeout' ini option is not engaged after
|
||||||
|
; application calls 'fastcgi_finish_request' or when application has finished and
|
||||||
|
; shutdown functions are being called (registered via register_shutdown_function).
|
||||||
|
; This option will enable timeout limit to be applied unconditionally
|
||||||
|
; even in such cases.
|
||||||
|
; Default Value: no
|
||||||
|
;request_terminate_timeout_track_finished = no
|
||||||
|
|
||||||
|
; Set open file descriptor rlimit.
|
||||||
|
; Default Value: system defined value
|
||||||
|
;rlimit_files = 1024
|
||||||
|
|
||||||
|
; Set max core size rlimit.
|
||||||
|
; Possible Values: 'unlimited' or an integer greater or equal to 0
|
||||||
|
; Default Value: system defined value
|
||||||
|
;rlimit_core = 0
|
||||||
|
|
||||||
|
; Chroot to this directory at the start. This value must be defined as an
|
||||||
|
; absolute path. When this value is not set, chroot is not used.
|
||||||
|
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
|
||||||
|
; of its subdirectories. If the pool prefix is not set, the global prefix
|
||||||
|
; will be used instead.
|
||||||
|
; Note: chrooting is a great security feature and should be used whenever
|
||||||
|
; possible. However, all PHP paths will be relative to the chroot
|
||||||
|
; (error_log, sessions.save_path, ...).
|
||||||
|
; Default Value: not set
|
||||||
|
;chroot =
|
||||||
|
|
||||||
|
; Chdir to this directory at the start.
|
||||||
|
; Note: relative path can be used.
|
||||||
|
; Default Value: current directory or / when chroot
|
||||||
|
;chdir = /var/www
|
||||||
|
|
||||||
|
; Redirect worker stdout and stderr into main error log. If not set, stdout and
|
||||||
|
; stderr will be redirected to /dev/null according to FastCGI specs.
|
||||||
|
; Note: on highloaded environment, this can cause some delay in the page
|
||||||
|
; process time (several ms).
|
||||||
|
; Default Value: no
|
||||||
|
;catch_workers_output = yes
|
||||||
|
catch_workers_output = yes
|
||||||
|
|
||||||
|
; Decorate worker output with prefix and suffix containing information about
|
||||||
|
; the child that writes to the log and if stdout or stderr is used as well as
|
||||||
|
; log level and time. This options is used only if catch_workers_output is yes.
|
||||||
|
; Settings to "no" will output data as written to the stdout or stderr.
|
||||||
|
; Default value: yes
|
||||||
|
;decorate_workers_output = no
|
||||||
|
decorate_workers_output = no
|
||||||
|
|
||||||
|
; Clear environment in FPM workers
|
||||||
|
; Prevents arbitrary environment variables from reaching FPM worker processes
|
||||||
|
; by clearing the environment in workers before env vars specified in this
|
||||||
|
; pool configuration are added.
|
||||||
|
; Setting to "no" will make all environment variables available to PHP code
|
||||||
|
; via getenv(), $_ENV and $_SERVER.
|
||||||
|
; Default Value: yes
|
||||||
|
;clear_env = no
|
||||||
|
clear_env = no
|
||||||
|
|
||||||
|
; Limits the extensions of the main script FPM will allow to parse. This can
|
||||||
|
; prevent configuration mistakes on the web server side. You should only limit
|
||||||
|
; FPM to .php extensions to prevent malicious users to use other extensions to
|
||||||
|
; execute php code.
|
||||||
|
; Note: set an empty value to allow all extensions.
|
||||||
|
; Default Value: .php
|
||||||
|
;security.limit_extensions = .php .php3 .php4 .php5 .php7
|
||||||
|
|
||||||
|
; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
|
||||||
|
; the current environment.
|
||||||
|
; Default Value: clean env
|
||||||
|
;env[HOSTNAME] = $HOSTNAME
|
||||||
|
;env[PATH] = /usr/local/bin:/usr/bin:/bin
|
||||||
|
;env[TMP] = /tmp
|
||||||
|
;env[TMPDIR] = /tmp
|
||||||
|
;env[TEMP] = /tmp
|
||||||
|
|
||||||
|
; Additional php.ini defines, specific to this pool of workers. These settings
|
||||||
|
; overwrite the values previously defined in the php.ini. The directives are the
|
||||||
|
; same as the PHP SAPI:
|
||||||
|
; php_value/php_flag - you can set classic ini defines which can
|
||||||
|
; be overwritten from PHP call 'ini_set'.
|
||||||
|
; php_admin_value/php_admin_flag - these directives won't be overwritten by
|
||||||
|
; PHP call 'ini_set'
|
||||||
|
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.
|
||||||
|
|
||||||
|
; Defining 'extension' will load the corresponding shared extension from
|
||||||
|
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
|
||||||
|
; overwrite previously defined php.ini values, but will append the new value
|
||||||
|
; instead.
|
||||||
|
|
||||||
|
; Note: path INI options can be relative and will be expanded with the prefix
|
||||||
|
; (pool, global or /usr/local)
|
||||||
|
|
||||||
|
; Default Value: nothing is defined by default except the values in php.ini and
|
||||||
|
; specified at startup with the -d argument
|
||||||
|
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
|
||||||
|
;php_flag[display_errors] = off
|
||||||
|
;php_admin_value[error_log] = /var/log/fpm-php.www.log
|
||||||
|
;php_admin_flag[log_errors] = on
|
||||||
|
;php_admin_value[memory_limit] = 32M
|
@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Phinx\Migration\AbstractMigration;
|
||||||
|
|
||||||
|
final class CreateTokuAccounts extends AbstractMigration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Change Method.
|
||||||
|
*
|
||||||
|
* Write your reversible migrations using this method.
|
||||||
|
*
|
||||||
|
* More information on writing migrations is available here:
|
||||||
|
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
|
||||||
|
*
|
||||||
|
* Remember to call "create()" or "update()" and NOT "save()" when working
|
||||||
|
* with the Table class.
|
||||||
|
*/
|
||||||
|
public function change(): void
|
||||||
|
{
|
||||||
|
$this->execute('SET unique_checks=0; SET foreign_key_checks=0;');
|
||||||
|
|
||||||
|
$this->table('toku_accounts')
|
||||||
|
->addColumn('sociedad_rut', 'integer', ['limit' => 8, 'signed' => false, 'null' => false])
|
||||||
|
->addColumn('toku_id', 'string', ['length' => 255, 'null' => false])
|
||||||
|
->addColumn('account_key', 'string', ['length' => 255, 'null' => false])
|
||||||
|
->addColumn('enabled', 'boolean', ['default' => true])
|
||||||
|
->addTimestamps()
|
||||||
|
#->addForeignKey('sociedad_rut', 'inmobiliaria', 'rut', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
|
||||||
|
->addIndex(['toku_id'], ['unique' => true])
|
||||||
|
->create();
|
||||||
|
|
||||||
|
$this->execute('SET unique_checks=1; SET foreign_key_checks=1;');
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use Phinx\Migration\AbstractMigration;
|
||||||
|
|
||||||
|
final class ChangeTelefonoSizeInPropietario extends AbstractMigration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Change Method.
|
||||||
|
*
|
||||||
|
* Write your reversible migrations using this method.
|
||||||
|
*
|
||||||
|
* More information on writing migrations is available here:
|
||||||
|
* https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
|
||||||
|
*
|
||||||
|
* Remember to call "create()" or "update()" and NOT "save()" when working
|
||||||
|
* with the Table class.
|
||||||
|
*/
|
||||||
|
public function change(): void
|
||||||
|
{
|
||||||
|
$this->table('propietario')
|
||||||
|
->changeColumn('telefono', 'biginteger', ['null' => true, 'signed' => false, 'default' => null])
|
||||||
|
->update();
|
||||||
|
}
|
||||||
|
}
|
1
app/resources/routes/api/external/toku.php
vendored
1
app/resources/routes/api/external/toku.php
vendored
@ -7,4 +7,5 @@ $app->group('/toku', function($app) {
|
|||||||
$app->get('/test[/]', [Toku::class, 'test']);
|
$app->get('/test[/]', [Toku::class, 'test']);
|
||||||
$app->delete('/reset[/]', [Toku::class, 'reset']);
|
$app->delete('/reset[/]', [Toku::class, 'reset']);
|
||||||
$app->post('/enqueue[/]', [Toku::class, 'enqueue']);
|
$app->post('/enqueue[/]', [Toku::class, 'enqueue']);
|
||||||
|
$app->post('/update[/{type}[/]]', [Toku::class, 'update']);
|
||||||
});
|
});
|
||||||
|
@ -2,9 +2,9 @@
|
|||||||
use Incoviba\Controller\API\Queues;
|
use Incoviba\Controller\API\Queues;
|
||||||
|
|
||||||
$app->group('/queue', function($app) {
|
$app->group('/queue', function($app) {
|
||||||
$app->get('/jobs[/]', [Queues::class, 'jobs']);
|
#$app->get('/jobs[/]', [Queues::class, 'jobs']);
|
||||||
$app->group('/run', function($app) {
|
$app->group('/run', function($app) {
|
||||||
$app->get('/{job_id:[0-9]+}[/]', [Queues::class, 'run']);
|
#$app->get('/{job_id:[0-9]+}[/]', [Queues::class, 'run']);
|
||||||
$app->get('[/]', Queues::class);
|
$app->get('[/]', Queues::class);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -156,7 +156,7 @@
|
|||||||
<script>
|
<script>
|
||||||
const regiones = [
|
const regiones = [
|
||||||
@foreach ($regiones as $region)
|
@foreach ($regiones as $region)
|
||||||
'<div class="item" data-value="{{$region->id}}">{{$region->descripcion}}</div>',
|
'<div class="item" data-value="{{$region->id}}">{{$region->numeral}} - {{$region->descripcion}}</div>',
|
||||||
@endforeach
|
@endforeach
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -54,22 +54,23 @@
|
|||||||
}
|
}
|
||||||
$(document).ready(() => {
|
$(document).ready(() => {
|
||||||
const url = '{{$urls->api}}/ventas/pago/{{$venta->resciliacion()->id}}'
|
const url = '{{$urls->api}}/ventas/pago/{{$venta->resciliacion()->id}}'
|
||||||
let old = new Date({{$venta->resciliacion()?->fecha->format('Y') ?? date('Y')}},
|
let old = new Date(Date.parse('{{$venta->resciliacion()?->fecha->format('Y-m-d') ?? $venta->currentEstado()->fecha->format('Y-m-d') ?? $venta->fecha->format('Y-m-d')}}') + 24 * 60 * 60 * 1000)
|
||||||
{{$venta->resciliacion()?->fecha->format('n') ?? date('n')}}-1, {{$venta->resciliacion()?->fecha->format('j') ?? date('j')}})
|
|
||||||
calendar_date_options['initialDate'] = old
|
calendar_date_options['initialDate'] = old
|
||||||
calendar_date_options['onChange'] = function(date, text, mode) {
|
calendar_date_options['onChange'] = function(date, text, mode) {
|
||||||
if (date.getTime() === old.getTime()) {
|
if (date.getTime() === old.getTime()) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const body = new FormData()
|
const body = new FormData()
|
||||||
body.set('fecha', date.toISOString())
|
const fecha = new Date(date.getTime())
|
||||||
|
fecha.setDate(fecha.getDate() - 1)
|
||||||
|
body.set('fecha', fecha.toISOString())
|
||||||
$('#loading-spinner-fecha').show()
|
$('#loading-spinner-fecha').show()
|
||||||
APIClient.fetch(url, {method: 'post', body}).then(response => {
|
APIClient.fetch(url, {method: 'post', body}).then(response => {
|
||||||
$('#loading-spinner-fecha').hide()
|
$('#loading-spinner-fecha').hide()
|
||||||
if (!response) {
|
if (!response) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
old = date
|
old = new Date(date.getTime())
|
||||||
alertResponse('Fecha cambiada correctamente.')
|
alertResponse('Fecha cambiada correctamente.')
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -6,15 +6,26 @@
|
|||||||
|
|
||||||
@section('venta_content')
|
@section('venta_content')
|
||||||
<div class="ui list">
|
<div class="ui list">
|
||||||
<div class="item">
|
@if (isset($venta->formaPago()->pie))
|
||||||
<div class="header">Valor Pagado</div>
|
<div class="item">
|
||||||
<div class="content">
|
<div class="header">Valor Pagado</div>
|
||||||
{{$format->pesos($venta->formaPago()->pie->pagado('pesos'))}}
|
<div class="content">
|
||||||
<div class="ui left pointing small label">
|
{{$format->pesos($venta->formaPago()->pie->pagado('pesos'))}}
|
||||||
{{$format->number($venta->formaPago()->pie->pagado() / $venta->valor * 100)}}% de la venta
|
<div class="ui left pointing small label">
|
||||||
|
{{$format->number($venta->formaPago()->pie->pagado() / $venta->valor * 100)}}% de la venta
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
@else
|
||||||
|
<div class="item">
|
||||||
|
<div class="ui compact warning message">
|
||||||
|
<div class="content">
|
||||||
|
<i class="exclamation triangle icon"></i>
|
||||||
|
No tiene valor pagado
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
<div class="item">
|
<div class="item">
|
||||||
<div class="header">
|
<div class="header">
|
||||||
Multa Estandar
|
Multa Estandar
|
||||||
|
@ -116,7 +116,18 @@ return [
|
|||||||
->registerSub($container->get(Incoviba\Service\Contabilidad\Cartola\BCI\Mes::class));
|
->registerSub($container->get(Incoviba\Service\Contabilidad\Cartola\BCI\Mes::class));
|
||||||
},
|
},
|
||||||
'TokuClient' => function(ContainerInterface $container) {
|
'TokuClient' => function(ContainerInterface $container) {
|
||||||
|
$logger = $container->get('externalLogger');
|
||||||
|
$stack = GuzzleHttp\HandlerStack::create();
|
||||||
|
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($logger) {
|
||||||
|
$logger->info('Toku Request', [
|
||||||
|
'method' => $request->getMethod(),
|
||||||
|
'uri' => (string) $request->getUri(),
|
||||||
|
'headers' => $request->getHeaders(),
|
||||||
|
'body' => $request->getBody()->getContents(),
|
||||||
|
]);
|
||||||
|
}));
|
||||||
return new GuzzleHttp\Client([
|
return new GuzzleHttp\Client([
|
||||||
|
'handler' => $stack,
|
||||||
'base_uri' => $container->get('TOKU_URL'),
|
'base_uri' => $container->get('TOKU_URL'),
|
||||||
'headers' => [
|
'headers' => [
|
||||||
'x-api-key' => $container->get('TOKU_TOKEN'),
|
'x-api-key' => $container->get('TOKU_TOKEN'),
|
||||||
@ -162,6 +173,16 @@ return [
|
|||||||
->register('subscription', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Subscription::class))
|
->register('subscription', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Subscription::class))
|
||||||
->register('invoice', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Invoice::class));
|
->register('invoice', $container->get(Incoviba\Service\Venta\MediosPago\Toku\Invoice::class));
|
||||||
},
|
},
|
||||||
|
Pheanstalk\Pheanstalk::class => function(ContainerInterface $container) {
|
||||||
|
return Pheanstalk\Pheanstalk::create(
|
||||||
|
$container->get('BEANSTALKD_HOST'),
|
||||||
|
$container->has('BEANSTALKD_PORT') ? $container->get('BEANSTALKD_PORT') : 11300
|
||||||
|
);
|
||||||
|
},
|
||||||
|
Incoviba\Service\MQTT::class => function(ContainerInterface $container) {
|
||||||
|
return new Incoviba\Service\MQTT()
|
||||||
|
->register('default', $container->get(Incoviba\Service\MQTT\Pheanstalk::class));
|
||||||
|
},
|
||||||
Incoviba\Service\Queue::class => function(ContainerInterface $container) {
|
Incoviba\Service\Queue::class => function(ContainerInterface $container) {
|
||||||
return new Incoviba\Service\Queue(
|
return new Incoviba\Service\Queue(
|
||||||
$container->get(Psr\Log\LoggerInterface::class),
|
$container->get(Psr\Log\LoggerInterface::class),
|
||||||
|
@ -22,20 +22,4 @@ class Queues extends Ideal\Controller
|
|||||||
}
|
}
|
||||||
return $this->withJson($response, $output);
|
return $this->withJson($response, $output);
|
||||||
}
|
}
|
||||||
public function jobs(ServerRequestInterface $request, ResponseInterface $response,
|
|
||||||
Service\Queue $queueService): ResponseInterface
|
|
||||||
{
|
|
||||||
$output = [
|
|
||||||
'jobs' => array_column($queueService->getPendingJobs(), 'id')
|
|
||||||
];
|
|
||||||
return $this->withJson($response, $output);
|
|
||||||
}
|
|
||||||
public function run(ServerRequestInterface $request, ResponseInterface $response, Service\Queue $queueService,
|
|
||||||
int $job_id): ResponseInterface
|
|
||||||
{
|
|
||||||
if ($queueService->runJob($job_id, $request)) {
|
|
||||||
return $response->withStatus(200);
|
|
||||||
}
|
|
||||||
return $response->withStatus(422);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -146,4 +146,25 @@ class Toku extends Controller
|
|||||||
}
|
}
|
||||||
return $this->withJson($response, $output);
|
return $this->withJson($response, $output);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function update(ServerRequestInterface $request, ResponseInterface $response,
|
||||||
|
Service\Venta\MediosPago\Toku $tokuService, ?string $type = null): ResponseInterface
|
||||||
|
{
|
||||||
|
$body = $request->getBody()->getContents();
|
||||||
|
$input = json_decode($body, true);
|
||||||
|
$output = [
|
||||||
|
'type' => $type,
|
||||||
|
'input' => $input,
|
||||||
|
'output' => [],
|
||||||
|
'success' => false
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
$output['output'] = $tokuService->update($input, $type);
|
||||||
|
$output['success'] = true;
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->logger->error($exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->withJson($response, $output);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,6 +4,9 @@ namespace Incoviba\Controller;
|
|||||||
use Incoviba\Common\Alias\View;
|
use Incoviba\Common\Alias\View;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||||
|
use Incoviba\Exception\ServiceAction\Create;
|
||||||
|
use Incoviba\Exception\ServiceAction\Read;
|
||||||
|
use Incoviba\Exception\ServiceAction\Update;
|
||||||
use Incoviba\Model;
|
use Incoviba\Model;
|
||||||
use Incoviba\Repository;
|
use Incoviba\Repository;
|
||||||
use Incoviba\Service;
|
use Incoviba\Service;
|
||||||
@ -142,9 +145,24 @@ class Ventas
|
|||||||
return $view->render($response, 'ventas.desistir', compact('venta'));
|
return $view->render($response, 'ventas.desistir', compact('venta'));
|
||||||
}
|
}
|
||||||
public function desistida(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
|
public function desistida(ServerRequestInterface $request, ResponseInterface $response, Service\Venta $ventaService,
|
||||||
|
Service\Venta\Pago $pagoService,
|
||||||
View $view, int $venta_id): ResponseInterface
|
View $view, int $venta_id): ResponseInterface
|
||||||
{
|
{
|
||||||
$venta = $ventaService->getById($venta_id);
|
try {
|
||||||
|
$venta = $ventaService->getById($venta_id);
|
||||||
|
} catch (Read) {
|
||||||
|
return $view->render($response->withStatus(404), 'not_found');
|
||||||
|
}
|
||||||
|
if ($venta->resciliacion() === null) {
|
||||||
|
$pagoData = [
|
||||||
|
'fecha' => $venta->currentEstado()->fecha->format('Y-m-d'),
|
||||||
|
'valor' => 0
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
$pago = $pagoService->add($pagoData);
|
||||||
|
$venta = $ventaService->edit($venta, ['resciliacion' => $pago->id]);
|
||||||
|
} catch (Create | Update) {}
|
||||||
|
}
|
||||||
return $view->render($response, 'ventas.desistida', compact('venta'));
|
return $view->render($response, 'ventas.desistida', compact('venta'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
18
app/src/Exception/MQTT.php
Normal file
18
app/src/Exception/MQTT.php
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
abstract class MQTT extends Exception
|
||||||
|
{
|
||||||
|
public function __construct($message = "", $code = 0, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$baseCode = 700;
|
||||||
|
$code = $baseCode + $code;
|
||||||
|
if ($message == "") {
|
||||||
|
$message = "MQTT Exception";
|
||||||
|
}
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
18
app/src/Exception/MQTT/MissingClient.php
Normal file
18
app/src/Exception/MQTT/MissingClient.php
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class MissingClient extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $host = '', ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = 'Missing MQTT client';
|
||||||
|
if ($host !== '') {
|
||||||
|
$message = "{$message} for host {$host}";
|
||||||
|
}
|
||||||
|
$code = 1;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
app/src/Exception/MQTT/MissingJob.php
Normal file
15
app/src/Exception/MQTT/MissingJob.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class MissingJob extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = 'Missing MQTT job';
|
||||||
|
$code = 10;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
app/src/Exception/MQTT/RemoveJob.php
Normal file
15
app/src/Exception/MQTT/RemoveJob.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class RemoveJob extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(int $jobId, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Could not remove job {$jobId}";
|
||||||
|
$code = 13;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
app/src/Exception/MQTT/SetJob.php
Normal file
15
app/src/Exception/MQTT/SetJob.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class SetJob extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $payload, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Could not set job with {$payload}";
|
||||||
|
$code = 11;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
@ -7,12 +7,14 @@ class Job extends Ideal\Model
|
|||||||
{
|
{
|
||||||
public array $configuration;
|
public array $configuration;
|
||||||
public bool $executed = false;
|
public bool $executed = false;
|
||||||
|
public int $retries = 0;
|
||||||
|
|
||||||
protected function jsonComplement(): array
|
protected function jsonComplement(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'configuration' => $this->configuration,
|
'configuration' => $this->configuration,
|
||||||
'executed' => $this->executed
|
'executed' => $this->executed,
|
||||||
|
'retries' => $this->retries
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,149 +1,135 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service;
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
|
use DateInvalidTimeZoneException;
|
||||||
|
use DateMalformedStringException;
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateTimeZone;
|
use DateTimeZone;
|
||||||
use InvalidArgumentException;
|
|
||||||
use OutOfRangeException;
|
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Predis\Connection\ConnectionException;
|
|
||||||
use Incoviba\Common\Ideal;
|
use Incoviba\Common\Ideal;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyRedis;
|
use Incoviba\Exception\MQTT as MQTTException;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
use Incoviba\Exception\ServiceAction\{Create, Delete, Read, Update};
|
||||||
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
|
|
||||||
use Incoviba\Repository;
|
|
||||||
use Incoviba\Model;
|
use Incoviba\Model;
|
||||||
|
use Incoviba\Repository;
|
||||||
|
|
||||||
class Job extends Ideal\Service
|
class Job extends Ideal\Service
|
||||||
{
|
{
|
||||||
public function __construct(LoggerInterface $logger, protected Redis $redisService,
|
public function __construct(LoggerInterface $logger, protected MQTT $mqttService,
|
||||||
protected Repository\Job $jobRepository)
|
protected Repository\Job $jobRepository)
|
||||||
{
|
{
|
||||||
parent::__construct($logger);
|
parent::__construct($logger);
|
||||||
}
|
}
|
||||||
protected string $redisKey = 'jobs';
|
|
||||||
|
|
||||||
public function getPending(null|string|array $orderBy = null): array
|
public function isPending(): bool
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$jobs = $this->redisService->get($this->redisKey);
|
return $this->mqttService->exists();
|
||||||
if ($jobs === null) {
|
} catch (MQTTException $exception) {
|
||||||
return [];
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
}
|
return false;
|
||||||
$jobs = json_decode($jobs, true);
|
|
||||||
if ($orderBy !== null) {
|
|
||||||
uksort($jobs, function($a, $b) use ($orderBy) {
|
|
||||||
return $a[$orderBy] <=> $b[$orderBy];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return array_map([$this, 'load'], $jobs);
|
|
||||||
} catch (ConnectionException | EmptyRedis) {
|
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param int $id
|
|
||||||
* @return Model\Job
|
* @return Model\Job
|
||||||
* @throws Read
|
* @throws Read
|
||||||
*/
|
*/
|
||||||
public function getPendingById(int $id): Model\Job
|
public function get(): Model\Job
|
||||||
{
|
{
|
||||||
$jobs = $this->getJobs();
|
|
||||||
try {
|
try {
|
||||||
$idx = $this->findJob($jobs, $id);
|
return $this->load(json_decode($this->mqttService->get(), true));
|
||||||
} catch (EmptyResult $exception) {
|
} catch (MQTTException $exception) {
|
||||||
$exception = new OutOfRangeException('Job not found', count($jobs), $exception);
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
throw new Read(__CLASS__, $exception);
|
throw new Read(__CLASS__, $exception);
|
||||||
}
|
}
|
||||||
return $this->load($jobs[$idx]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $configuration
|
* @param array $configuration
|
||||||
* @return Model\Job
|
* @return Model\Job
|
||||||
* @throws Read
|
* @throws Create
|
||||||
*/
|
*/
|
||||||
public function add(array $configuration): Model\Job
|
public function add(array $configuration): Model\Job
|
||||||
{
|
{
|
||||||
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
try {
|
||||||
|
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||||
|
} catch (DateMalformedStringException | DateInvalidTimeZoneException $exception) {
|
||||||
|
$this->logger->warning($exception->getMessage(), ['exception' => $exception]);
|
||||||
|
$now = new DateTimeImmutable();
|
||||||
|
}
|
||||||
$data = [
|
$data = [
|
||||||
'id' => $now->format('Uu'),
|
'id' => $now->format('Uu'),
|
||||||
'configuration' => $configuration,
|
'configuration' => $configuration,
|
||||||
'executed' => false,
|
'executed' => false,
|
||||||
'created_at' => $now->format('Y-m-d H:i:s'),
|
'created_at' => $now->format('Y-m-d H:i:s'),
|
||||||
'updated_at' => null
|
'updated_at' => null,
|
||||||
|
'retries' => 0
|
||||||
];
|
];
|
||||||
$jobs = [];
|
|
||||||
try {
|
try {
|
||||||
$jobs = $this->redisService->get($this->redisKey);
|
$this->mqttService->set(json_encode($data));
|
||||||
if ($jobs !== null) {
|
} catch (MQTTException $exception) {
|
||||||
$jobs = json_decode($jobs, true);
|
throw new Create(__CLASS__, $exception);
|
||||||
}
|
}
|
||||||
} catch (EmptyRedis) {}
|
|
||||||
$jobs []= $data;
|
|
||||||
$this->redisService->set($this->redisKey, json_encode($jobs), -1);
|
|
||||||
return $this->load($data);
|
return $this->load($data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Model\Job $job
|
* @param Model\Job $job
|
||||||
* @return bool
|
* @return void
|
||||||
* @throws Read
|
* @throws Update
|
||||||
*/
|
*/
|
||||||
public function execute(Model\Job $job): bool
|
public function update(Model\Job $job): void
|
||||||
{
|
{
|
||||||
$jobs = $this->getJobs();
|
|
||||||
try {
|
try {
|
||||||
$idx = $this->findJob($jobs, $job->id);
|
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||||
} catch (EmptyResult $exception) {
|
} catch (DateMalformedStringException | DateInvalidTimeZoneException) {
|
||||||
$exception = new OutOfRangeException('Job not found', count($jobs), $exception);
|
$now = new DateTimeImmutable();
|
||||||
throw new Read(__CLASS__, $exception);
|
}
|
||||||
|
$data = json_decode(json_encode($job), true);
|
||||||
|
$data['updated_at'] = $now->format('Y-m-d H:i:s');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->mqttService->update(json_encode($data));
|
||||||
|
} catch (MQTTException $exception) {
|
||||||
|
throw new Update(__CLASS__, $exception);
|
||||||
}
|
}
|
||||||
unset($jobs[$idx]);
|
|
||||||
$this->redisService->set($this->redisKey, json_encode(array_values($jobs)), -1);
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return array
|
* @param Model\Job $job
|
||||||
* @throws Read
|
* @throws Delete
|
||||||
*/
|
*/
|
||||||
protected function getJobs(): array
|
public function remove(Model\Job $job): void
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$jobs = $this->redisService->get($this->redisKey);
|
$this->mqttService->remove();
|
||||||
} catch (EmptyRedis $exception) {
|
} catch (MQTTException $exception) {
|
||||||
throw new Read(__CLASS__, $exception);
|
throw new Delete(__CLASS__, $exception);
|
||||||
}
|
}
|
||||||
if ($jobs === null) {
|
|
||||||
$exception = new InvalidArgumentException("Redis Key {$this->redisKey} not found");
|
|
||||||
throw new Read(__CLASS__, $exception);
|
|
||||||
}
|
|
||||||
return json_decode($jobs, true);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $jobs
|
* @param Model\Job $job
|
||||||
* @param int $id
|
* @return bool
|
||||||
* @return int
|
|
||||||
* @throws EmptyResult
|
|
||||||
*/
|
*/
|
||||||
protected function findJob(array $jobs, int $id): int
|
public function execute(Model\Job $job): bool
|
||||||
{
|
{
|
||||||
$idx = array_find_key($jobs, function($job) use ($id) {
|
try {
|
||||||
return (int) $job['id'] === $id;
|
$this->mqttService->remove();
|
||||||
});
|
return true;
|
||||||
if ($idx === null) {
|
} catch (MQTTException $exception) {
|
||||||
throw new EmptyResult("SELECT * FROM jobs WHERE id = ?");
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
return $idx;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function load(array $data, ?int $id = null): Model\Job
|
protected function load(array $data, ?int $id = null): Model\Job
|
||||||
{
|
{
|
||||||
$job = new Model\Job();
|
$job = new Model\Job();
|
||||||
$job->id = $id ?? $data['id'] ?? null;
|
$job->id = $id ?? $data['id'] ?? null;
|
||||||
$job->configuration = $data['configuration'] ?? [];
|
$job->configuration = $data['configuration'] ?? [];
|
||||||
$job->executed = $data['executed'] ?? false;
|
$job->executed = $data['executed'] ?? false;
|
||||||
|
$job->retries = $data['retries'] ?? 0;
|
||||||
return $job;
|
return $job;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -167,8 +167,13 @@ class Login
|
|||||||
try {
|
try {
|
||||||
$login = $this->repository->fetchActiveByUser($user->id);
|
$login = $this->repository->fetchActiveByUser($user->id);
|
||||||
$this->logout($login->user);
|
$this->logout($login->user);
|
||||||
} catch (PDOException | EmptyResult $exception) {
|
} catch (EmptyResult $exception) {
|
||||||
error_log($exception, 3, '/logs/exception.log');
|
$message []= "No logins for user {$user->name}";
|
||||||
|
$message []= $exception->getMessage();
|
||||||
|
$message []= $exception->getTraceAsString();
|
||||||
|
error_log(implode(PHP_EOL, $message).PHP_EOL, 3, '/logs/login-exception.log');
|
||||||
|
} catch (PDOException $exception) {
|
||||||
|
error_log($exception.PHP_EOL, 3, '/logs/login-exception.log');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -185,7 +190,7 @@ class Login
|
|||||||
$this->saveCookie($selector, $token, $login->dateTime->add(new DateInterval("PT{$this->max_login_time}H")));
|
$this->saveCookie($selector, $token, $login->dateTime->add(new DateInterval("PT{$this->max_login_time}H")));
|
||||||
return true;
|
return true;
|
||||||
} catch (PDOException | Exception $exception) {
|
} catch (PDOException | Exception $exception) {
|
||||||
error_log($exception, 3, '/logs/exception.log');
|
error_log($exception.PHP_EOL, 3, '/logs/login-exception.log');
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
102
app/src/Service/MQTT.php
Normal file
102
app/src/Service/MQTT.php
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
|
use Incoviba\Exception\MQTT as MQTTException;
|
||||||
|
use Incoviba\Service\MQTT\MQTTInterface;
|
||||||
|
|
||||||
|
class MQTT implements MQTTInterface
|
||||||
|
{
|
||||||
|
protected array $clients = [];
|
||||||
|
public function register(string $name, MQTTInterface $client): self
|
||||||
|
{
|
||||||
|
$this->clients[$name] = $client;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
public function clientExists(string $name): bool
|
||||||
|
{
|
||||||
|
return isset($this->clients[$name]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $name
|
||||||
|
* @return MQTTInterface
|
||||||
|
* @throws MQTTException/MissingClient
|
||||||
|
*/
|
||||||
|
public function getClient(?string $name = null): MQTTInterface
|
||||||
|
{
|
||||||
|
if ($name === null) {
|
||||||
|
$name = array_keys($this->clients)[0];
|
||||||
|
}
|
||||||
|
if (!$this->clientExists($name)) {
|
||||||
|
throw new MQTTException\MissingClient($name);
|
||||||
|
}
|
||||||
|
return $this->clients[$name];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $host
|
||||||
|
* @return bool
|
||||||
|
* @throws MQTTException/MissingClient
|
||||||
|
* @throws MQTTException/MissingJob
|
||||||
|
*/
|
||||||
|
public function exists(?string $host = null): bool
|
||||||
|
{
|
||||||
|
$client = $this->getClient($host);
|
||||||
|
return $client->exists();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $host
|
||||||
|
* @return string
|
||||||
|
* @throws MQTTException/MissingClient
|
||||||
|
* @throws MQTTException/MissingJob
|
||||||
|
*/
|
||||||
|
public function get(?string $host = null): string
|
||||||
|
{
|
||||||
|
$client = $this->getClient($host);
|
||||||
|
return $client->get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $value
|
||||||
|
* @param int $delay
|
||||||
|
* @param string|null $host
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException/MissingClient
|
||||||
|
* @throws MQTTException/SetJob
|
||||||
|
*/
|
||||||
|
public function set(string $value, int $delay = 0, ?string $host = null): self
|
||||||
|
{
|
||||||
|
$client = $this->getClient($host);
|
||||||
|
$client->set($value, $delay);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $host
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException/MissingJob
|
||||||
|
* @throws MQTTException/RemoveJob
|
||||||
|
*/
|
||||||
|
public function remove(?int $jobId = null, ?string $host = null): self
|
||||||
|
{
|
||||||
|
$this->getClient($host)->remove($jobId);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $newPayload
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $host
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException/MissingJob
|
||||||
|
* @throws MQTTException/RemoveJob
|
||||||
|
* @throws MQTTException/SetJob
|
||||||
|
*/
|
||||||
|
public function update(string $newPayload, ?int $jobId = null, ?string $host = null): self
|
||||||
|
{
|
||||||
|
$this->getClient($host)->update($newPayload, $jobId);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
111
app/src/Service/MQTT/Beanstalkd.php
Normal file
111
app/src/Service/MQTT/Beanstalkd.php
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Incoviba\Exception\MQTT\MissingJob;
|
||||||
|
use Incoviba\Exception\MQTT\RemoveJob;
|
||||||
|
use Incoviba\Exception\MQTT\SetJob;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use xobotyi\beansclient;
|
||||||
|
use xobotyi\beansclient\Exception\ClientException;
|
||||||
|
use xobotyi\beansclient\Exception\CommandException;
|
||||||
|
use xobotyi\beansclient\Exception\JobException;
|
||||||
|
|
||||||
|
class Beanstalkd implements MQTTInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @throws JobException
|
||||||
|
* @throws ClientException
|
||||||
|
* @throws CommandException
|
||||||
|
*/
|
||||||
|
public function __construct(protected LoggerInterface $logger, protected beansclient\BeansClient $client,
|
||||||
|
protected string $tube = 'default', protected int $ttr = beansclient\BeansClient::DEFAULT_TTR,
|
||||||
|
protected int $priority = 1)
|
||||||
|
{
|
||||||
|
$this->client->watchTube($this->tube);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exists(): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$stats = $this->client->statsTube($this->tube);
|
||||||
|
return $stats['current-jobs-ready'] > 0;
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ?beansclient\Job $currentJob = null;
|
||||||
|
public function get(): string
|
||||||
|
{
|
||||||
|
if (!$this->exists()) {
|
||||||
|
throw new MissingJob();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$job = $this->client->watchTube($this->tube)->reserve();
|
||||||
|
$this->currentJob = $job;
|
||||||
|
return $job->payload;
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
|
throw new MissingJob($exception);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $value
|
||||||
|
* @param int $delay
|
||||||
|
* @return $this
|
||||||
|
* @throws SetJob
|
||||||
|
*/
|
||||||
|
public function set(string $value, int $delay = 0): self
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$this->client->useTube($this->tube)->put($value, $this->priority, $delay, $this->ttr ?? 0);
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['payload' => $value, 'delay' => $delay, 'exception' => $exception]);
|
||||||
|
throw new SetJob($value, $exception);
|
||||||
|
}
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $newPayload
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return self
|
||||||
|
* @throws RemoveJob
|
||||||
|
* @throws SetJob
|
||||||
|
*/
|
||||||
|
public function update(string $newPayload, ?int $jobId = null): self
|
||||||
|
{
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJob->id;
|
||||||
|
}
|
||||||
|
return $this->remove($jobId)
|
||||||
|
->set($newPayload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return $this
|
||||||
|
* @throws RemoveJob
|
||||||
|
*/
|
||||||
|
public function remove(?int $jobId = null): self
|
||||||
|
{
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJob->id;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!$this->client->useTube($this->tube)->delete($jobId)) {
|
||||||
|
throw new JobException("Failed to delete job {$jobId}");
|
||||||
|
}
|
||||||
|
if ($this->currentJob !== null && $this->currentJob->id === $jobId) {
|
||||||
|
$this->currentJob = null;
|
||||||
|
}
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['jobId' => $jobId, 'exception' => $exception]);
|
||||||
|
throw new RemoveJob($jobId, $exception);
|
||||||
|
}
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
25
app/src/Service/MQTT/MQTTInterface.php
Normal file
25
app/src/Service/MQTT/MQTTInterface.php
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
use Incoviba\Exception\MQTT\MissingJob;
|
||||||
|
|
||||||
|
interface MQTTInterface {
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function exists(): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
* @throws MissingJob
|
||||||
|
*/
|
||||||
|
public function get(): string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $value
|
||||||
|
* @param int $delay
|
||||||
|
* @return self
|
||||||
|
*/
|
||||||
|
public function set(string $value, int $delay = 0): self;
|
||||||
|
public function remove(?int $jobId = null): self;
|
||||||
|
}
|
59
app/src/Service/MQTT/Pheanstalk.php
Normal file
59
app/src/Service/MQTT/Pheanstalk.php
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
use Incoviba\Common\Ideal\Service;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Pheanstalk as PBA;
|
||||||
|
|
||||||
|
class Pheanstalk extends Service implements MQTTInterface
|
||||||
|
{
|
||||||
|
const string DEFAULT_TUBE = 'default';
|
||||||
|
const int DEFAULT_TTR = 60;
|
||||||
|
const int DEFAULT_PRIORITY = 1_024;
|
||||||
|
|
||||||
|
public function __construct(LoggerInterface $logger, protected PBA\Pheanstalk $client, string $tubeName = self::DEFAULT_TUBE)
|
||||||
|
{
|
||||||
|
parent::__construct($logger);
|
||||||
|
$this->tube = new PBA\Values\TubeName($tubeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected PBA\Values\TubeName $tube;
|
||||||
|
|
||||||
|
public function set(string $value, int $delay = 0): self
|
||||||
|
{
|
||||||
|
$this->client->useTube($this->tube);
|
||||||
|
$this->client->put($value, self::DEFAULT_PRIORITY, $delay, self::DEFAULT_TTR);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
public function exists(): bool
|
||||||
|
{
|
||||||
|
$stats = $this->client->statsTube($this->tube);
|
||||||
|
return $stats->currentJobsReady > 0;
|
||||||
|
}
|
||||||
|
protected int $currentJobId;
|
||||||
|
public function get(): string
|
||||||
|
{
|
||||||
|
$this->client->useTube($this->tube);
|
||||||
|
$job = $this->client->reserve();
|
||||||
|
$this->currentJobId = $job->getId();
|
||||||
|
return $job->getData();
|
||||||
|
}
|
||||||
|
public function update(string $newPayload, ?int $jobId = null): self
|
||||||
|
{
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJobId;
|
||||||
|
}
|
||||||
|
$this->remove($jobId);
|
||||||
|
$this->set($newPayload);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
public function remove(?int $jobId = null): self
|
||||||
|
{
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJobId;
|
||||||
|
}
|
||||||
|
$this->client->useTube($this->tube);
|
||||||
|
$this->client->delete(new PBA\Values\JobId($jobId));
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
@ -5,12 +5,14 @@ use Exception;
|
|||||||
use Psr\Http\Message\RequestInterface;
|
use Psr\Http\Message\RequestInterface;
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Incoviba\Common\Ideal;
|
use Incoviba\Common\Ideal;
|
||||||
use Incoviba\Exception\ServiceAction\{Create, Read};
|
use Incoviba\Exception\ServiceAction\{Create, Delete, Read, Update};
|
||||||
use Incoviba\Service;
|
use Incoviba\Service;
|
||||||
|
use Incoviba\Model;
|
||||||
|
|
||||||
class Queue extends Ideal\Service
|
class Queue extends Ideal\Service
|
||||||
{
|
{
|
||||||
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker)
|
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker,
|
||||||
|
protected int $maxRetries = 5)
|
||||||
{
|
{
|
||||||
parent::__construct($logger);
|
parent::__construct($logger);
|
||||||
$this->register('default', $defaultWorker);
|
$this->register('default', $defaultWorker);
|
||||||
@ -28,7 +30,7 @@ class Queue extends Ideal\Service
|
|||||||
try {
|
try {
|
||||||
$this->jobService->add($configuration);
|
$this->jobService->add($configuration);
|
||||||
return true;
|
return true;
|
||||||
} catch (Read $exception) {
|
} catch (Create $exception) {
|
||||||
$final = new Exception("Could not enqueue job", 0, $exception);
|
$final = new Exception("Could not enqueue job", 0, $exception);
|
||||||
$this->logger->warning($final);
|
$this->logger->warning($final);
|
||||||
return false;
|
return false;
|
||||||
@ -39,22 +41,8 @@ class Queue extends Ideal\Service
|
|||||||
return $this->enqueue($configuration);
|
return $this->enqueue($configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function runJob(Model\Job $job, ?RequestInterface $request = null): bool
|
||||||
* @return array
|
|
||||||
*/
|
|
||||||
public function getPendingJobs(): array
|
|
||||||
{
|
{
|
||||||
return $this->jobService->getPending();
|
|
||||||
}
|
|
||||||
public function runJob(int $job_id, ?RequestInterface $request = null): bool
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$job = $this->jobService->getPendingById($job_id);
|
|
||||||
} catch (Read $exception) {
|
|
||||||
$this->logger->debug($exception);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$type = 'default';
|
$type = 'default';
|
||||||
if (isset($job->configuration['type'])) {
|
if (isset($job->configuration['type'])) {
|
||||||
$type = strtolower($job->configuration['type']);
|
$type = strtolower($job->configuration['type']);
|
||||||
@ -70,36 +58,57 @@ class Queue extends Ideal\Service
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (!$worker->execute($job)) {
|
if (!$worker->execute($job)) {
|
||||||
$this->logger->debug("Could not execute job {$job_id}");
|
$this->logger->debug("Could not execute job {$job->id}");
|
||||||
|
$job->retries++;
|
||||||
|
$this->jobService->update($job);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!$this->jobService->execute($job)) {
|
if (!$this->jobService->execute($job)) {
|
||||||
$this->logger->debug("Could not remove job {$job_id}");
|
$this->logger->debug("Could not remove job {$job->id}");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} catch (Exception $exception) {
|
} catch (Exception $exception) {
|
||||||
$final = new Exception("Could not run job", 0, $exception);
|
$this->logger->warning("Could not run job {$job->id}", ['exception' => $exception]);
|
||||||
$this->logger->warning($final);
|
$job->retries++;
|
||||||
|
try {
|
||||||
|
$this->jobService->update($job);
|
||||||
|
} catch (Update $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
public function run(?RequestInterface $request = null): bool
|
public function run(?RequestInterface $request = null): bool
|
||||||
{
|
{
|
||||||
$jobs = $this->jobService->getPending();
|
if (!$this->jobService->isPending()) {
|
||||||
if (count($jobs) === 0) {
|
|
||||||
$this->logger->debug("No pending jobs");
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
$errors = [];
|
$job = $this->jobService->get();
|
||||||
foreach ($jobs as $job) {
|
} catch (Read $exception) {
|
||||||
try {
|
$this->logger->error($exception->getMessage(), ['exception' => $exception]);
|
||||||
$this->runJob($job->id, $request);
|
return false;
|
||||||
} catch (Exception) {
|
|
||||||
$errors []= $job->id;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return count($errors) === 0;
|
if ($job->retries >= $this->maxRetries) {
|
||||||
|
try {
|
||||||
|
$this->jobService->remove($job);
|
||||||
|
} catch (Delete $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$this->runJob($job, $request);
|
||||||
|
} catch (Exception) {
|
||||||
|
$job->retries ++;
|
||||||
|
try {
|
||||||
|
$this->jobService->update($job);
|
||||||
|
} catch (Update $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['job' => $job, 'exception' => $exception]);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ namespace Incoviba\Service;
|
|||||||
use DateTimeInterface;
|
use DateTimeInterface;
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateMalformedStringException;
|
use DateMalformedStringException;
|
||||||
use function PHPUnit\Framework\countOf;
|
use Incoviba\Service\Valor\Phone;
|
||||||
|
|
||||||
class Valor
|
class Valor
|
||||||
{
|
{
|
||||||
@ -40,6 +40,14 @@ class Valor
|
|||||||
}
|
}
|
||||||
return $value / $this->ufService->get($date);
|
return $value / $this->ufService->get($date);
|
||||||
}
|
}
|
||||||
|
public function phone(): Phone
|
||||||
|
{
|
||||||
|
return new Phone();
|
||||||
|
}
|
||||||
|
public function telefono(): Phone
|
||||||
|
{
|
||||||
|
return $this->phone();
|
||||||
|
}
|
||||||
|
|
||||||
protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface
|
protected function getDateTime(null|string|DateTimeInterface $date): DateTimeInterface
|
||||||
{
|
{
|
||||||
|
28
app/src/Service/Valor/Phone.php
Normal file
28
app/src/Service/Valor/Phone.php
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\Valor;
|
||||||
|
|
||||||
|
class Phone
|
||||||
|
{
|
||||||
|
public function toDatabase(?string $phone): ?int
|
||||||
|
{
|
||||||
|
if ($phone === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (int) str_replace([' ', '+'], '', $phone) ?? null;
|
||||||
|
}
|
||||||
|
public function toDisplay(?int $phone): ?string
|
||||||
|
{
|
||||||
|
if ($phone === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
$parts = preg_split('/(?=<country>\d{2})?(?=<area>\d)(?=<first>\d{4})(?=<last>\d{4})/', $phone);
|
||||||
|
$output = [];
|
||||||
|
if (array_key_exists('country', $parts)) {
|
||||||
|
$output [] = "+{$parts[0]}";
|
||||||
|
}
|
||||||
|
$output [] = $parts[1] ?? '';
|
||||||
|
$output [] = $parts[2] ?? '';
|
||||||
|
$output [] = $parts[3] ?? '';
|
||||||
|
return implode(' ', $output);
|
||||||
|
}
|
||||||
|
}
|
@ -1,10 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service;
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
use Exception;
|
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateMalformedStringException;
|
use DateMalformedStringException;
|
||||||
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
|
use Incoviba\Exception\ServiceAction\{Create, Read, Update};
|
||||||
|
use Incoviba\Common\Define;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Incoviba\Common\Ideal\Service;
|
use Incoviba\Common\Ideal\Service;
|
||||||
@ -12,7 +12,7 @@ use Incoviba\Common\Implement;
|
|||||||
use Incoviba\Repository;
|
use Incoviba\Repository;
|
||||||
use Incoviba\Model;
|
use Incoviba\Model;
|
||||||
|
|
||||||
class Venta extends Service
|
class Venta extends Service\Repository
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
LoggerInterface $logger,
|
LoggerInterface $logger,
|
||||||
@ -189,6 +189,11 @@ class Venta extends Service
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function getRepository(): Define\Repository
|
||||||
|
{
|
||||||
|
return $this->ventaRepository;
|
||||||
|
}
|
||||||
|
|
||||||
protected function process(Model\Venta $venta): Model\Venta
|
protected function process(Model\Venta $venta): Model\Venta
|
||||||
{
|
{
|
||||||
if ($venta->uf === 0.0) {
|
if ($venta->uf === 0.0) {
|
||||||
|
@ -76,15 +76,24 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
|||||||
* @param array $data
|
* @param array $data
|
||||||
* @param array $validStatus
|
* @param array $validStatus
|
||||||
* @param array $invalidStatus
|
* @param array $invalidStatus
|
||||||
|
* @param string|null $accountKey
|
||||||
* @return bool
|
* @return bool
|
||||||
* @throws EmptyResponse
|
* @throws EmptyResponse
|
||||||
*/
|
*/
|
||||||
protected function sendAdd(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
|
protected function sendAdd(string $request_uri, array $data, array $validStatus, array $invalidStatus, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$params = $this->mapParams($data);
|
$params = $this->mapParams($data);
|
||||||
$this->logger->info('Send Add', ['uri' => $request_uri, 'params' => $params]);
|
$this->logger->info('Send Add', ['uri' => $request_uri, 'params' => $params]);
|
||||||
try {
|
try {
|
||||||
$response = $this->client->post($request_uri, ['json' => $params]);
|
$options = [
|
||||||
|
'json' => $params
|
||||||
|
];
|
||||||
|
if ($accountKey !== null) {
|
||||||
|
$options['headers'] = [
|
||||||
|
'X-Account-Key' => $accountKey
|
||||||
|
];
|
||||||
|
}
|
||||||
|
$response = $this->client->post($request_uri, $options);
|
||||||
} catch (ClientExceptionInterface $exception) {
|
} catch (ClientExceptionInterface $exception) {
|
||||||
throw new EmptyResponse($request_uri, $exception);
|
throw new EmptyResponse($request_uri, $exception);
|
||||||
}
|
}
|
||||||
@ -111,14 +120,23 @@ abstract class AbstractEndPoint extends LoggerEnabled implements EndPoint
|
|||||||
* @param array $data
|
* @param array $data
|
||||||
* @param array $validStatus
|
* @param array $validStatus
|
||||||
* @param array $invalidStatus
|
* @param array $invalidStatus
|
||||||
|
* @param string|null $accountKey
|
||||||
* @return bool
|
* @return bool
|
||||||
* @throws EmptyResponse
|
* @throws EmptyResponse
|
||||||
*/
|
*/
|
||||||
protected function sendEdit(string $request_uri, array $data, array $validStatus, array $invalidStatus): bool
|
protected function sendEdit(string $request_uri, array $data, array $validStatus, array $invalidStatus, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$params = $this->mapParams($data);
|
$params = $this->mapParams($data);
|
||||||
try {
|
try {
|
||||||
$response = $this->client->put($request_uri, ['json' => $params]);
|
$options = [
|
||||||
|
'json' => $params
|
||||||
|
];
|
||||||
|
if ($accountKey !== null) {
|
||||||
|
$options['headers'] = [
|
||||||
|
'X-Account-Key' => $accountKey
|
||||||
|
];
|
||||||
|
}
|
||||||
|
$response = $this->client->put($request_uri, $options);
|
||||||
} catch (ClientExceptionInterface $exception) {
|
} catch (ClientExceptionInterface $exception) {
|
||||||
throw new EmptyResponse($request_uri, $exception);
|
throw new EmptyResponse($request_uri, $exception);
|
||||||
}
|
}
|
||||||
|
@ -28,18 +28,20 @@ interface EndPoint
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $data
|
* @param array $data
|
||||||
|
* @param string|null $accountKey
|
||||||
* @return bool
|
* @return bool
|
||||||
* @throws EmptyResponse
|
* @throws EmptyResponse
|
||||||
*/
|
*/
|
||||||
public function add(array $data): bool;
|
public function add(array $data, ?string $accountKey = null): bool;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $id
|
* @param string $id
|
||||||
* @param array $data
|
* @param array $data
|
||||||
|
* @param string|null $accountKey
|
||||||
* @return bool
|
* @return bool
|
||||||
* @throws EmptyResponse
|
* @throws EmptyResponse
|
||||||
*/
|
*/
|
||||||
public function edit(string $id, array $data): bool;
|
public function edit(string $id, array $data, ?string $accountKey = null): bool;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $id
|
* @param string $id
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service\Venta\MediosPago;
|
namespace Incoviba\Service\Venta\MediosPago;
|
||||||
|
|
||||||
|
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||||
use InvalidArgumentException;
|
use InvalidArgumentException;
|
||||||
use PDO;
|
use PDO;
|
||||||
|
use PDOException;
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Incoviba\Common\Define\Connection;
|
use Incoviba\Common\Define\Connection;
|
||||||
use Incoviba\Common\Ideal;
|
use Incoviba\Common\Ideal;
|
||||||
@ -80,13 +82,18 @@ class Toku extends Ideal\Service
|
|||||||
try {
|
try {
|
||||||
return $this->subscription->getById($venta->id);
|
return $this->subscription->getById($venta->id);
|
||||||
} catch (InvalidResult $exception) {
|
} catch (InvalidResult $exception) {
|
||||||
|
$inmobiliaria = $venta->proyecto()->inmobiliaria();
|
||||||
|
$accountKey = null;
|
||||||
|
try {
|
||||||
|
$accountKey = $this->getAccountKey($inmobiliaria->rut);
|
||||||
|
} catch (EmptyResult) {}
|
||||||
$subscriptionData = [
|
$subscriptionData = [
|
||||||
'customer' => $customer['toku_id'],
|
'customer' => $customer['toku_id'],
|
||||||
'product_id' => $venta->id,
|
'product_id' => $venta->id,
|
||||||
'venta' => $venta
|
'venta' => $venta
|
||||||
];
|
];
|
||||||
try {
|
try {
|
||||||
if (!$this->subscription->add($subscriptionData)) {
|
if (!$this->subscription->add($subscriptionData, $accountKey)) {
|
||||||
throw new InvalidResult("Could not save Subscription for Venta {$venta->id}", 409, $exception);
|
throw new InvalidResult("Could not save Subscription for Venta {$venta->id}", 409, $exception);
|
||||||
}
|
}
|
||||||
} catch (EmptyResponse $exception) {
|
} catch (EmptyResponse $exception) {
|
||||||
@ -95,7 +102,6 @@ class Toku extends Ideal\Service
|
|||||||
return $this->subscription->getById($venta->id);
|
return $this->subscription->getById($venta->id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Model\Venta $venta
|
* @param Model\Venta $venta
|
||||||
* @param array $cuotas_ids
|
* @param array $cuotas_ids
|
||||||
@ -115,6 +121,12 @@ class Toku extends Ideal\Service
|
|||||||
});
|
});
|
||||||
} catch (EmptyResponse) {}
|
} catch (EmptyResponse) {}
|
||||||
|
|
||||||
|
$inmobiliaria = $venta->proyecto()->inmobiliaria();
|
||||||
|
$accountKey = null;
|
||||||
|
try {
|
||||||
|
$accountKey = $this->getAccountKey($inmobiliaria->rut);
|
||||||
|
} catch (EmptyResult) {}
|
||||||
|
|
||||||
$invoices = [];
|
$invoices = [];
|
||||||
$errors = [];
|
$errors = [];
|
||||||
foreach ($venta->formaPago()->pie->cuotas() as $cuota) {
|
foreach ($venta->formaPago()->pie->cuotas() as $cuota) {
|
||||||
@ -142,7 +154,7 @@ class Toku extends Ideal\Service
|
|||||||
'cuota' => $cuota,
|
'cuota' => $cuota,
|
||||||
'venta' => $venta
|
'venta' => $venta
|
||||||
];
|
];
|
||||||
if (!$this->invoice->add($invoiceData)) {
|
if (!$this->invoice->add($invoiceData, $accountKey)) {
|
||||||
throw new EmptyResponse("Could not add Invoice for Cuota {$cuota->id}", $exception);
|
throw new EmptyResponse("Could not add Invoice for Cuota {$cuota->id}", $exception);
|
||||||
}
|
}
|
||||||
$invoices []= $this->invoice->getById($cuota->id);
|
$invoices []= $this->invoice->getById($cuota->id);
|
||||||
@ -290,6 +302,95 @@ class Toku extends Ideal\Service
|
|||||||
return $queues;
|
return $queues;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function update(array $ids, ?string $type = null): array
|
||||||
|
{
|
||||||
|
if ($type === null) {
|
||||||
|
$types = [
|
||||||
|
'customers',
|
||||||
|
'subscriptions',
|
||||||
|
'invoices'
|
||||||
|
];
|
||||||
|
$results = [];
|
||||||
|
foreach ($types as $type) {
|
||||||
|
$results[$type] = $this->update($ids[$type], $type);
|
||||||
|
}
|
||||||
|
return $results;
|
||||||
|
}
|
||||||
|
$results = [];
|
||||||
|
switch ($type) {
|
||||||
|
case 'subscriptions':
|
||||||
|
try {
|
||||||
|
$results['subscription'] = $this->subscription->update($ids);
|
||||||
|
} catch (EmptyResult | EmptyResponse $exception) {
|
||||||
|
$this->logger->error($exception);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'invoices':
|
||||||
|
try {
|
||||||
|
$results['invoice'] = $this->invoice->updateAll($ids);
|
||||||
|
} catch (EmptyResult $exception) {
|
||||||
|
$this->logger->error($exception);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return $results;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ServerRequestInterface $request
|
||||||
|
* @param array $tokenConfig
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function validateToken(ServerRequestInterface $request, array $tokenConfig): bool
|
||||||
|
{
|
||||||
|
if (!$request->hasHeader('User-Agent') or !str_starts_with($request->getHeaderLine('User-Agent'), 'Toku-Webhooks')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!$request->hasHeader('X-Datadog-Tags') or !$request->hasHeader('Tracestate')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!$request->hasHeader('Toku-Signature')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tokuSignature = $request->getHeaderLine('Toku-Signature');
|
||||||
|
try {
|
||||||
|
list($timestamp, $signature) = array_map(function($elem) {
|
||||||
|
return explode('=', $elem)[1];
|
||||||
|
}, explode(',', $tokuSignature));
|
||||||
|
$body = $request->getBody()->getContents();
|
||||||
|
$json = json_decode($body, true);
|
||||||
|
if (!is_array($json)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!array_key_exists('id', $json)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$eventId = $json['id'];
|
||||||
|
$eventType = $json['event_type'];
|
||||||
|
|
||||||
|
$query = $this->connection->getQueryBuilder()
|
||||||
|
->select('secret')
|
||||||
|
->from('toku_webhooks')
|
||||||
|
->where('enabled = ? AND JSON_SEARCH(events, "one", ?) IS NOT NULL');
|
||||||
|
$params = [true, $eventType];
|
||||||
|
$statement = $this->connection->prepare($query);
|
||||||
|
$statement->execute($params);
|
||||||
|
$results = $statement->fetchAll(PDO::FETCH_COLUMN);
|
||||||
|
if (count($results) === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (array_any($results, fn($secret) => $this->hmac->validate($timestamp, $signature, $eventId, $secret))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Throwable $throwable) {
|
||||||
|
$this->logger->error($throwable);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param array $request
|
* @param array $request
|
||||||
* @return bool
|
* @return bool
|
||||||
@ -406,54 +507,20 @@ class Toku extends Ideal\Service
|
|||||||
$data['date'] = $data['transaction_date'];
|
$data['date'] = $data['transaction_date'];
|
||||||
return $data;
|
return $data;
|
||||||
}
|
}
|
||||||
|
protected function getAccountKey(int $sociedad_rut): string
|
||||||
public function validateToken(ServerRequestInterface $request, array $tokenConfig): bool
|
|
||||||
{
|
{
|
||||||
if (!$request->hasHeader('User-Agent') or !str_starts_with($request->getHeaderLine('User-Agent'), 'Toku-Webhooks')) {
|
$query = $this->connection->getQueryBuilder()
|
||||||
return false;
|
->select('account_key')
|
||||||
}
|
->from('toku_accounts')
|
||||||
if (!$request->hasHeader('X-Datadog-Tags') or !$request->hasHeader('Tracestate')) {
|
->where('enabled = ? AND sociedad_rut = ?');
|
||||||
return false;
|
$params = [true, $sociedad_rut];
|
||||||
}
|
|
||||||
if (!$request->hasHeader('Toku-Signature')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tokuSignature = $request->getHeaderLine('Toku-Signature');
|
|
||||||
try {
|
try {
|
||||||
list($timestamp, $signature) = array_map(function($elem) {
|
|
||||||
return explode('=', $elem)[1];
|
|
||||||
}, explode(',', $tokuSignature));
|
|
||||||
$body = $request->getBody()->getContents();
|
|
||||||
$json = json_decode($body, true);
|
|
||||||
if (!is_array($json)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (!array_key_exists('id', $json)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
$eventId = $json['id'];
|
|
||||||
$eventType = $json['event_type'];
|
|
||||||
|
|
||||||
$query = $this->connection->getQueryBuilder()
|
|
||||||
->select('secret')
|
|
||||||
->from('toku_webhooks')
|
|
||||||
->where('enabled = ? AND JSON_SEARCH(events, "one", ?) IS NOT NULL');
|
|
||||||
$params = [true, $eventType];
|
|
||||||
$statement = $this->connection->prepare($query);
|
$statement = $this->connection->prepare($query);
|
||||||
$statement->execute($params);
|
$statement->execute($params);
|
||||||
$results = $statement->fetchAll(PDO::FETCH_COLUMN);
|
return $statement->fetchColumn();
|
||||||
if (count($results) === 0) {
|
} catch (PDOException $exception) {
|
||||||
return false;
|
$this->logger->error($exception);
|
||||||
}
|
throw new EmptyResult($query, $exception);
|
||||||
|
|
||||||
if (array_any($results, fn($secret) => $this->hmac->validate($timestamp, $signature, $eventId, $secret))) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Throwable $throwable) {
|
|
||||||
$this->logger->error($throwable);
|
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -29,15 +29,15 @@ class Customer extends AbstractEndPoint
|
|||||||
$request_uri = "/customers/{$id}";
|
$request_uri = "/customers/{$id}";
|
||||||
return $this->sendGet($request_uri, [200], [404, 422]);
|
return $this->sendGet($request_uri, [200], [404, 422]);
|
||||||
}
|
}
|
||||||
public function add(array $data): bool
|
public function add(array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = "/customers";
|
$request_uri = "/customers";
|
||||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 422]);
|
return $this->sendAdd($request_uri, $data, [200, 201], [400, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function edit(string $id, array $data): bool
|
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = "customers/{$id}";
|
$request_uri = "customers/{$id}";
|
||||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 422]);
|
return $this->sendEdit($request_uri, $data, [200], [400, 404, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function delete(string $id): void
|
public function delete(string $id): void
|
||||||
{
|
{
|
||||||
|
@ -4,6 +4,7 @@ namespace Incoviba\Service\Venta\MediosPago\Toku;
|
|||||||
use DateMalformedStringException;
|
use DateMalformedStringException;
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateTimeZone;
|
use DateTimeZone;
|
||||||
|
use PDO;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
use Psr\Http\Client\ClientInterface;
|
use Psr\Http\Client\ClientInterface;
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
@ -39,15 +40,15 @@ class Invoice extends AbstractEndPoint
|
|||||||
$request_uri = "/invoices/{$id}";
|
$request_uri = "/invoices/{$id}";
|
||||||
return $this->sendGet($request_uri, [200], [404]);
|
return $this->sendGet($request_uri, [200], [404]);
|
||||||
}
|
}
|
||||||
public function add(array $data): bool
|
public function add(array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = "/invoices";
|
$request_uri = "/invoices";
|
||||||
return $this->sendAdd($request_uri, $data, [200, 201], [400, 409, 422]);
|
return $this->sendAdd($request_uri, $data, [200, 201], [400, 409, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function edit(string $id, array $data): bool
|
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = "/invoices/{$id}";
|
$request_uri = "/invoices/{$id}";
|
||||||
return $this->sendEdit($request_uri, $data, [200], [400, 404, 409, 422]);
|
return $this->sendEdit($request_uri, $data, [200], [400, 404, 409, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function delete(string $id): void
|
public function delete(string $id): void
|
||||||
{
|
{
|
||||||
@ -199,6 +200,41 @@ class Invoice extends AbstractEndPoint
|
|||||||
return $this->pagoService->depositar($invoice->cuota->pago, $date);
|
return $this->pagoService->depositar($invoice->cuota->pago, $date);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $idsData
|
||||||
|
* @return array
|
||||||
|
* @throws EmptyResult
|
||||||
|
*/
|
||||||
|
public function updateAll(array $idsData): array
|
||||||
|
{
|
||||||
|
$tokuIds = array_column($idsData, 'toku_id');
|
||||||
|
$oldIds = array_column($idsData, 'product_id');
|
||||||
|
|
||||||
|
$placeholders = array_map(fn($id) => "id{$id}", array_keys($oldIds));
|
||||||
|
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||||
|
$query = $this->pagoService->getRepository()->getConnection()->getQueryBuilder()
|
||||||
|
->select('pago.id, CONCAT_WS("-", unidad.descripcion, CONCAT_WS("-", propietario.rut, propietario.dv)) AS old_pid')
|
||||||
|
->from('pago')
|
||||||
|
->joined('JOIN cuota ON cuota.pago = pago.id')
|
||||||
|
->joined('JOIN venta ON venta.pie = cuota.pie')
|
||||||
|
->joined('JOIN propietario ON propietario.rut = venta.propietario')
|
||||||
|
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
|
||||||
|
->joined('JOIN unidad ON pu.unidad = unidad.id')
|
||||||
|
->having("old_pid IN ({$placeholdersString})");
|
||||||
|
$values = array_combine($placeholders, $oldIds);
|
||||||
|
try {
|
||||||
|
$statement = $this->pagoService->getRepository()->getConnection()->execute($query, $values);
|
||||||
|
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $exception) {
|
||||||
|
$this->logger->error($exception);
|
||||||
|
throw new EmptyResult($query, $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$ids = array_column($results, 'pago.id');
|
||||||
|
$newIds = array_combine($ids, $tokuIds);
|
||||||
|
return array_map(fn($id) => ['product_id' => $id, 'toku_id' => $newIds[$id]], $ids);
|
||||||
|
}
|
||||||
|
|
||||||
public function save(array $data): bool
|
public function save(array $data): bool
|
||||||
{
|
{
|
||||||
return $this->doSave($this->invoiceRepository, $data);
|
return $this->doSave($this->invoiceRepository, $data);
|
||||||
@ -215,7 +251,7 @@ class Invoice extends AbstractEndPoint
|
|||||||
{
|
{
|
||||||
$paramsMap = [
|
$paramsMap = [
|
||||||
'customer' => 'customer',
|
'customer' => 'customer',
|
||||||
'product_id' => 'product_id',
|
'product_id' => 'cuota_id',
|
||||||
'due_date' => 'fecha',
|
'due_date' => 'fecha',
|
||||||
'subscription' => 'subscription',
|
'subscription' => 'subscription',
|
||||||
'amount' => 'valor',
|
'amount' => 'valor',
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service\Venta\MediosPago\Toku;
|
namespace Incoviba\Service\Venta\MediosPago\Toku;
|
||||||
|
|
||||||
|
use PDO;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
use Psr\Http\Client\ClientInterface;
|
use Psr\Http\Client\ClientInterface;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
use Incoviba\Common\Implement\Exception\EmptyResponse;
|
||||||
@ -34,15 +35,15 @@ class Subscription extends AbstractEndPoint
|
|||||||
$request_uri = "/subscriptions/{$id}";
|
$request_uri = "/subscriptions/{$id}";
|
||||||
return $this->sendGet($request_uri, [200], [401, 404, 422]);
|
return $this->sendGet($request_uri, [200], [401, 404, 422]);
|
||||||
}
|
}
|
||||||
public function add(array $data): bool
|
public function add(array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = '/subscriptions';
|
$request_uri = '/subscriptions';
|
||||||
return $this->sendAdd($request_uri, $data, [200, 201], [401, 404, 409, 422]);
|
return $this->sendAdd($request_uri, $data, [200, 201], [401, 404, 409, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function edit(string $id, array $data): bool
|
public function edit(string $id, array $data, ?string $accountKey = null): bool
|
||||||
{
|
{
|
||||||
$request_uri = "/subscriptions/{$id}";
|
$request_uri = "/subscriptions/{$id}";
|
||||||
return $this->sendEdit($request_uri, $data, [200], [401, 404, 409, 422]);
|
return $this->sendEdit($request_uri, $data, [200], [401, 404, 409, 422], $accountKey);
|
||||||
}
|
}
|
||||||
public function delete(string $id): void
|
public function delete(string $id): void
|
||||||
{
|
{
|
||||||
@ -111,6 +112,101 @@ class Subscription extends AbstractEndPoint
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $idsData
|
||||||
|
* @return array
|
||||||
|
* @throws EmptyResult
|
||||||
|
* @throws EmptyResponse
|
||||||
|
*/
|
||||||
|
public function update(array $idsData): array
|
||||||
|
{
|
||||||
|
$tokuIds = array_column($idsData, 'toku_id');
|
||||||
|
$oldPids = array_column($idsData, 'product_id');
|
||||||
|
|
||||||
|
$placeholders = array_map(fn($id) => "id{$id}", array_keys($oldPids));
|
||||||
|
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||||
|
$query = $this->ventaService->getRepository()->getConnection()->getQueryBuilder()
|
||||||
|
->select('venta.id, CONCAT_WS("-", unidad.descripcion, CONCAT_WS("-", propietario.rut, propietario.dv)) AS old_pid')
|
||||||
|
->from('venta')
|
||||||
|
->joined('JOIN propietario ON propietario.rut = venta.propietario')
|
||||||
|
->joined('JOIN propiedad_unidad pu ON pu.propiedad = venta.propiedad')
|
||||||
|
->joined('JOIN unidad ON pu.unidad = unidad.id')
|
||||||
|
->having("old_pid IN ({$placeholdersString})");
|
||||||
|
$values = array_combine($placeholders, $oldPids);
|
||||||
|
try {
|
||||||
|
$statement = $this->ventaService->getRepository()->getConnection()->execute($query, $values);
|
||||||
|
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), [
|
||||||
|
'query' => $query,
|
||||||
|
'values' => $values,
|
||||||
|
'ids' => $idsData,
|
||||||
|
'exception' => $exception]);
|
||||||
|
throw new EmptyResult($query, $exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
$accountKeys = $this->getAccountKey(array_column($results, 'id'));
|
||||||
|
|
||||||
|
$newPids = [];
|
||||||
|
$keys = [];
|
||||||
|
foreach ($results as $result) {
|
||||||
|
$idx = array_search($result['old_pid'], $oldPids);
|
||||||
|
$newPids[$idx] = $result['id'];
|
||||||
|
if (array_key_exists($result['id'], $accountKeys)) {
|
||||||
|
$keys[$idx] = $accountKeys[$result['id']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$output = [];
|
||||||
|
foreach ($tokuIds as $idx => $tokuId) {
|
||||||
|
if (!isset($newPids[$idx])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$data = [
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
if (!$this->edit($tokuId, $data, array_key_exists($idx, $keys) ? $keys[$idx] : null)) {
|
||||||
|
$this->logger->error('Error while updating Toku', [
|
||||||
|
'toku_id' => $tokuId,
|
||||||
|
'old_pid' => $oldPids[$idx],
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null]);
|
||||||
|
$output[] = [
|
||||||
|
'toku_id' => $tokuId,
|
||||||
|
'old_pid' => $oldPids[$idx],
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||||
|
'error' => 'Error while updating Toku'
|
||||||
|
];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} catch (EmptyResponse $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), [
|
||||||
|
'toku_id' => $tokuId,
|
||||||
|
'old_pid' => $oldPids[$idx],
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||||
|
'exception' => $exception]);
|
||||||
|
$output[] = [
|
||||||
|
'toku_id' => $tokuId,
|
||||||
|
'old_pid' => $oldPids[$idx],
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null,
|
||||||
|
'error' => $exception->getMessage()
|
||||||
|
];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$output[] = [
|
||||||
|
'toku_id' => $tokuId,
|
||||||
|
'old_pid' => $oldPids[$idx],
|
||||||
|
'product_id' => $newPids[$idx],
|
||||||
|
'account_key' => array_key_exists($idx, $keys) ? $keys[$idx] : null
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $output;
|
||||||
|
}
|
||||||
|
|
||||||
public function save(array $data): bool
|
public function save(array $data): bool
|
||||||
{
|
{
|
||||||
return $this->doSave($this->subscriptionRepsitory, $data);
|
return $this->doSave($this->subscriptionRepsitory, $data);
|
||||||
@ -133,11 +229,11 @@ class Subscription extends AbstractEndPoint
|
|||||||
if ($ref === null) {
|
if ($ref === null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if ($ref === 'pieValor') {
|
if ($ref === 'pieValor' and array_key_exists('venta', $data)) {
|
||||||
$params[$key] = $data['venta']->formaPago()?->pie?->valor ?? 0;
|
$params[$key] = $data['venta']?->formaPago()?->pie?->valor ?? 0;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if ($ref === 'datosVenta') {
|
if ($ref === 'datosVenta' and array_key_exists('venta', $data)) {
|
||||||
$params[$key] = $this->datosVenta($data['venta']);
|
$params[$key] = $this->datosVenta($data['venta']);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -169,4 +265,38 @@ class Subscription extends AbstractEndPoint
|
|||||||
'Unidades' => $venta->propiedad()->summary()
|
'Unidades' => $venta->propiedad()->summary()
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $ventaIds
|
||||||
|
* @return array
|
||||||
|
* @throws EmptyResult
|
||||||
|
*/
|
||||||
|
protected function getAccountKey(array $ventaIds): array
|
||||||
|
{
|
||||||
|
$placeholders = array_map(fn($id) => "id{$id}", array_keys($ventaIds));
|
||||||
|
$placeholdersString = implode(', ', array_map(fn($id) => ":{$id}", $placeholders));
|
||||||
|
$query = $this->ventaService->getRepository()->getConnection()->getQueryBuilder()
|
||||||
|
->select('account_key, venta.id AS venta_id')
|
||||||
|
->from('toku_accounts')
|
||||||
|
->joined('JOIN proyecto ON proyecto.inmobiliaria = toku_accounts.sociedad_rut')
|
||||||
|
->joined('JOIN proyecto_tipo_unidad ptu ON ptu.proyecto = proyecto.id')
|
||||||
|
->joined('JOIN unidad ON unidad.pt = ptu.id')
|
||||||
|
->joined('JOIN propiedad_unidad pu ON pu.unidad = unidad.id')
|
||||||
|
->joined('JOIN venta ON venta.propiedad = pu.propiedad')
|
||||||
|
->where("venta.id IN ({$placeholdersString}) AND toku_accounts.enabled = 1");
|
||||||
|
$values = array_combine($placeholders, $ventaIds);
|
||||||
|
try {
|
||||||
|
$statement = $this->ventaService->getRepository()->getConnection()->execute($query, $values);
|
||||||
|
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), [
|
||||||
|
'query' => $query,
|
||||||
|
'values' => $values,
|
||||||
|
'exception' => $exception]);
|
||||||
|
throw new EmptyResult($query, $exception);
|
||||||
|
}
|
||||||
|
$keys = array_column($results, 'account_key');
|
||||||
|
$ids = array_column($results, 'venta_id');
|
||||||
|
return array_combine($ids, $keys);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,25 +4,37 @@ namespace Incoviba\Service\Venta;
|
|||||||
use DateTimeInterface;
|
use DateTimeInterface;
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateMalformedStringException;
|
use DateMalformedStringException;
|
||||||
|
use Incoviba\Common\Define;
|
||||||
use Incoviba\Exception\ServiceAction\Create;
|
use Incoviba\Exception\ServiceAction\Create;
|
||||||
use Incoviba\Exception\ServiceAction\Read;
|
use Incoviba\Exception\ServiceAction\Read;
|
||||||
use Incoviba\Exception\ServiceAction\Update;
|
use Incoviba\Exception\ServiceAction\Update;
|
||||||
use PDOException;
|
use PDOException;
|
||||||
|
use Incoviba\Common\Ideal;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||||
use Incoviba\Repository;
|
use Incoviba\Repository;
|
||||||
use Incoviba\Model;
|
use Incoviba\Model;
|
||||||
use Incoviba\Service;
|
use Incoviba\Service;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
|
||||||
class Pago
|
class Pago extends Ideal\Service\Repository
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
|
LoggerInterface $logger,
|
||||||
protected Repository\Venta\Pago $pagoRepository,
|
protected Repository\Venta\Pago $pagoRepository,
|
||||||
protected Repository\Venta\EstadoPago $estadoPagoRepository,
|
protected Repository\Venta\EstadoPago $estadoPagoRepository,
|
||||||
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
|
protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository,
|
||||||
protected Service\UF $ufService,
|
protected Service\UF $ufService,
|
||||||
protected Service\Valor $valorService,
|
protected Service\Valor $valorService,
|
||||||
protected Service\Queue $queueService
|
protected Service\Queue $queueService
|
||||||
) {}
|
)
|
||||||
|
{
|
||||||
|
parent::__construct($logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getRepository(): Define\Repository
|
||||||
|
{
|
||||||
|
return $this->pagoRepository;
|
||||||
|
}
|
||||||
|
|
||||||
public function depositar(Model\Venta\Pago $pago, DateTimeInterface $fecha): bool
|
public function depositar(Model\Venta\Pago $pago, DateTimeInterface $fecha): bool
|
||||||
{
|
{
|
||||||
|
@ -1,22 +1,24 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service\Venta;
|
namespace Incoviba\Service\Venta;
|
||||||
|
|
||||||
|
use PDOException;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
use Incoviba\Common\Ideal\Service;
|
use Incoviba\Common\Ideal\Service;
|
||||||
use Incoviba\Common\Implement\Exception\EmptyResult;
|
use Incoviba\Common\Implement\Exception\EmptyResult;
|
||||||
use Incoviba\Exception\ServiceAction\Create;
|
use Incoviba\Exception\ServiceAction\Create;
|
||||||
use Incoviba\Exception\ServiceAction\Read;
|
use Incoviba\Exception\ServiceAction\Read;
|
||||||
use Incoviba\Exception\ServiceAction\Update;
|
use Incoviba\Exception\ServiceAction\Update;
|
||||||
use Incoviba\Repository;
|
|
||||||
use Incoviba\Model;
|
use Incoviba\Model;
|
||||||
use PDOException;
|
use Incoviba\Repository;
|
||||||
use Psr\Log\LoggerInterface;
|
use Incoviba\Service\Valor;
|
||||||
|
|
||||||
class Propietario extends Service
|
class Propietario extends Service
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
LoggerInterface $logger,
|
LoggerInterface $logger,
|
||||||
protected Repository\Venta\Propietario $propietarioRepository,
|
protected Repository\Venta\Propietario $propietarioRepository,
|
||||||
protected Repository\Direccion $direccionRepository
|
protected Repository\Direccion $direccionRepository,
|
||||||
|
protected Valor $valorService
|
||||||
) {
|
) {
|
||||||
parent::__construct($logger);
|
parent::__construct($logger);
|
||||||
}
|
}
|
||||||
@ -49,6 +51,9 @@ class Propietario extends Service
|
|||||||
$data['direccion'] = $direccion->id;
|
$data['direccion'] = $direccion->id;
|
||||||
}
|
}
|
||||||
$filteredData = $this->propietarioRepository->filterData($data);
|
$filteredData = $this->propietarioRepository->filterData($data);
|
||||||
|
if (array_key_exists('telefono', $filteredData)) {
|
||||||
|
$filteredData['telefono'] = $this->valorService->telefono()->toDatabase($filteredData['telefono']);
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return $this->propietarioRepository->edit($propietario, $filteredData);
|
return $this->propietarioRepository->edit($propietario, $filteredData);
|
||||||
} catch (PDOException | EmptyResult $exception) {
|
} catch (PDOException | EmptyResult $exception) {
|
||||||
@ -85,6 +90,10 @@ class Propietario extends Service
|
|||||||
]);
|
]);
|
||||||
$filtered_data = array_intersect_key($data, $fields);
|
$filtered_data = array_intersect_key($data, $fields);
|
||||||
|
|
||||||
|
if (array_key_exists('telefono', $filtered_data)) {
|
||||||
|
$filtered_data['telefono'] = $this->valorService->telefono()->toDatabase($filtered_data['telefono']);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$propietario = $this->propietarioRepository->fetchById($data['rut']);
|
$propietario = $this->propietarioRepository->fetchById($data['rut']);
|
||||||
$edits = [];
|
$edits = [];
|
||||||
@ -95,6 +104,7 @@ class Propietario extends Service
|
|||||||
} catch (EmptyResult) {
|
} catch (EmptyResult) {
|
||||||
try {
|
try {
|
||||||
$propietario = $this->propietarioRepository->create($filtered_data);
|
$propietario = $this->propietarioRepository->create($filtered_data);
|
||||||
|
$this->logger->info('Propietario', ['propietario' => $propietario]);
|
||||||
$propietario = $this->propietarioRepository->save($propietario);
|
$propietario = $this->propietarioRepository->save($propietario);
|
||||||
} catch (PDOException $exception) {
|
} catch (PDOException $exception) {
|
||||||
throw new Create(__CLASS__, $exception);
|
throw new Create(__CLASS__, $exception);
|
||||||
|
101
app/tests/unit/src/Service/MQTT/BeanstalkdTest.php
Normal file
101
app/tests/unit/src/Service/MQTT/BeanstalkdTest.php
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Test\Service\MQTT;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use xobotyi\beansclient\BeansClient;
|
||||||
|
use xobotyi\beansclient\Connection;
|
||||||
|
use xobotyi\beansclient\Exception\JobException;
|
||||||
|
use xobotyi\beansclient\Job;
|
||||||
|
use Incoviba\Exception\MQTT\MissingJob;
|
||||||
|
use Incoviba\Service\MQTT\Beanstalkd;
|
||||||
|
|
||||||
|
class BeanstalkdTest extends TestCase
|
||||||
|
{
|
||||||
|
protected LoggerInterface $logger;
|
||||||
|
protected BeansClient $client;
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
$this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
|
||||||
|
$this->client = $this->getMockBuilder(BeansClient::class)->disableOriginalConstructor()->getMock();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testExists(): void
|
||||||
|
{
|
||||||
|
$stats = ['current-jobs-ready' => 1];
|
||||||
|
$this->client->method('watchTube')->willReturn($this->client);
|
||||||
|
$this->client->method('statsTube')->willReturn($stats);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$this->assertTrue($service->exists());
|
||||||
|
}
|
||||||
|
public function testNotExists(): void
|
||||||
|
{
|
||||||
|
$stats = ['current-jobs-ready' => 0];
|
||||||
|
$this->client->method('watchTube')->willReturn($this->client);
|
||||||
|
$this->client->method('statsTube')->willReturn($stats);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$this->assertFalse($service->exists());
|
||||||
|
}
|
||||||
|
public function testGet(): void
|
||||||
|
{
|
||||||
|
$jobData = [
|
||||||
|
'id' => 1,
|
||||||
|
'configuration' => [
|
||||||
|
'type' => 'service',
|
||||||
|
],
|
||||||
|
'created_at' => '2020-01-01 00:00:00',
|
||||||
|
];
|
||||||
|
$connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$connection->method('isActive')->willReturn(true);
|
||||||
|
$this->client->method('getConnection')->willReturn($connection);
|
||||||
|
$this->client->method('watchTube')->willReturn($this->client);
|
||||||
|
$this->client->method('statsTube')->willReturn(['current-jobs-ready' => 1]);
|
||||||
|
$job = new Job($this->client, 1, 'ready', json_encode($jobData));
|
||||||
|
$this->client->method('reserve')->willReturn($job);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$this->assertEquals(json_encode($jobData), $service->get());
|
||||||
|
}
|
||||||
|
public function testGetException(): void
|
||||||
|
{
|
||||||
|
$this->client->method('watchTube')->willReturn($this->client);
|
||||||
|
$this->client->method('statsTube')->willReturn(['current-jobs-ready' => 0]);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$this->expectException(MissingJob::class);
|
||||||
|
$service->get();
|
||||||
|
|
||||||
|
$this->client->method('statsTube')->willReturn(['current-jobs-ready' => 1]);
|
||||||
|
$exception = new JobException();
|
||||||
|
$this->client->method('reserve')->willThrowException($exception);
|
||||||
|
$this->expectException(MissingJob::class);
|
||||||
|
$service->get();
|
||||||
|
}
|
||||||
|
public function testSet(): void
|
||||||
|
{
|
||||||
|
$this->client->method('useTube')->willReturn($this->client);
|
||||||
|
$this->client->method('put');
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$service->set('test');
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
public function testSetException(): void
|
||||||
|
{
|
||||||
|
$this->client->method('useTube')->willReturn($this->client);
|
||||||
|
$exception = new JobException();
|
||||||
|
$this->client->method('put')->willThrowException($exception);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$service->set('test');
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
public function testRemove(): void
|
||||||
|
{
|
||||||
|
$this->client->method('useTube')->willReturn($this->client);
|
||||||
|
$this->client->method('delete')->willReturn(true);
|
||||||
|
$service = new Beanstalkd($this->logger, $this->client);
|
||||||
|
$service->remove(1);
|
||||||
|
$this->assertTrue(true);
|
||||||
|
|
||||||
|
$this->client->method('delete')->willReturn(false);
|
||||||
|
$service->remove(1);
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
69
app/tests/unit/src/Service/MQTTTest.php
Normal file
69
app/tests/unit/src/Service/MQTTTest.php
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Test\Service;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use xobotyi\beansclient\BeansClient;
|
||||||
|
use Incoviba\Exception\MQTT\MissingClient;
|
||||||
|
use Incoviba\Service\MQTT;
|
||||||
|
use Incoviba\Service\MQTT\Beanstalkd;
|
||||||
|
|
||||||
|
class MQTTTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testRegisterAndClientExistsAndGet(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$beanstalkd = $this->getMockBuilder(Beanstalkd::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$this->assertTrue($mqtt->clientExists('beanstalkd'));
|
||||||
|
}
|
||||||
|
public function testGetClient(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$client = $this->getMockBuilder(BeansClient::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$beanstalkd = new Beanstalkd($logger, $client);
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$this->assertEquals($beanstalkd, $mqtt->getClient('beanstalkd'));
|
||||||
|
}
|
||||||
|
public function testGetClientException(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$this->expectException(MissingClient::class);
|
||||||
|
$mqtt->getClient('test');
|
||||||
|
}
|
||||||
|
public function testExists(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$beanstalkd = $this->getMockBuilder(Beanstalkd::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$beanstalkd->method('exists')->willReturn(true);
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$this->assertTrue($mqtt->exists('beanstalkd'));
|
||||||
|
}
|
||||||
|
public function testGet(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$beanstalkd = $this->getMockBuilder(Beanstalkd::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$beanstalkd->method('get')->willReturn('test');
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$this->assertEquals('test', $mqtt->get('beanstalkd'));
|
||||||
|
}
|
||||||
|
public function testSet(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$beanstalkd = $this->getMockBuilder(Beanstalkd::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$beanstalkd->method('set');
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$mqtt->set('test', 0, 'beanstalkd');
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
public function testRemove(): void
|
||||||
|
{
|
||||||
|
$mqtt = new MQTT();
|
||||||
|
$beanstalkd = $this->getMockBuilder(Beanstalkd::class)->disableOriginalConstructor()->getMock();
|
||||||
|
$beanstalkd->method('remove');
|
||||||
|
$mqtt->register('beanstalkd', $beanstalkd);
|
||||||
|
$mqtt->remove(0, 'beanstalkd');
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
66
app/tests/unit/src/Service/QueueTest.php
Normal file
66
app/tests/unit/src/Service/QueueTest.php
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Test\Service;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
use Incoviba\Service\Job;
|
||||||
|
use Incoviba\Service\Queue;
|
||||||
|
use Incoviba\Service\Worker;
|
||||||
|
use Incoviba\Model;
|
||||||
|
|
||||||
|
class QueueTest extends TestCase
|
||||||
|
{
|
||||||
|
protected LoggerInterface $logger;
|
||||||
|
protected Job $jobService;
|
||||||
|
protected Worker $defaultWorker;
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
$this->logger = $this->getMockBuilder(LoggerInterface::class)
|
||||||
|
->disableOriginalConstructor()
|
||||||
|
->getMock();
|
||||||
|
$this->jobService = $this->getMockBuilder(Job::class)
|
||||||
|
->disableOriginalConstructor()
|
||||||
|
->getMock();
|
||||||
|
$this->defaultWorker = $this->getMockBuilder(Worker::class)
|
||||||
|
->disableOriginalConstructor()
|
||||||
|
->getMock();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRegister(): void
|
||||||
|
{
|
||||||
|
$queue = new Queue($this->logger, $this->jobService, $this->defaultWorker);
|
||||||
|
$worker = $this->getMockBuilder(Worker::class)
|
||||||
|
->disableOriginalConstructor()
|
||||||
|
->getMock();
|
||||||
|
$queue->register('test', $worker);
|
||||||
|
$this->assertTrue(true);
|
||||||
|
}
|
||||||
|
public function testEnqueue(): void
|
||||||
|
{
|
||||||
|
$queue = new Queue($this->logger, $this->jobService, $this->defaultWorker);
|
||||||
|
$jobData = ['test' => 'test'];
|
||||||
|
$result = $queue->enqueue($jobData);
|
||||||
|
$this->assertTrue($result);
|
||||||
|
|
||||||
|
$result = $queue->push($jobData);
|
||||||
|
$this->assertTrue($result);
|
||||||
|
}
|
||||||
|
public function testRun(): void
|
||||||
|
{
|
||||||
|
$queue = new Queue($this->logger, $this->jobService, $this->defaultWorker);
|
||||||
|
$result = $queue->run();
|
||||||
|
$this->assertTrue($result);
|
||||||
|
|
||||||
|
|
||||||
|
$jobData = [
|
||||||
|
'type' => 'test',
|
||||||
|
];
|
||||||
|
$job = new Model\Job();
|
||||||
|
$job->id = 1;
|
||||||
|
$job->configuration = $jobData;
|
||||||
|
$this->jobService->method('isPending')->willReturn(true);
|
||||||
|
$this->jobService->method('get')->willReturn($job);
|
||||||
|
$result = $queue->run();
|
||||||
|
$this->assertTrue($result);
|
||||||
|
}
|
||||||
|
}
|
2
app/www-ext.conf
Normal file
2
app/www-ext.conf
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
[www]
|
||||||
|
pm.max_children = 8
|
@ -2,4 +2,4 @@
|
|||||||
|
|
||||||
. /etc/profile
|
. /etc/profile
|
||||||
|
|
||||||
/usr/local/bin/php /code/bin/index.php "$@"
|
/usr/local/bin/php /code/bin/index.php "$@"
|
||||||
|
@ -11,3 +11,12 @@ try {
|
|||||||
} catch (Exception $exception) {
|
} catch (Exception $exception) {
|
||||||
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->notice($exception);
|
$app->getContainer()->get(Psr\Log\LoggerInterface::class)->notice($exception);
|
||||||
}
|
}
|
||||||
|
register_shutdown_function(function() {
|
||||||
|
$error = error_get_last();
|
||||||
|
|
||||||
|
$fatal_errors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
|
||||||
|
if ($error !== null and in_array($error['type'], $fatal_errors, true)) {
|
||||||
|
error_log(json_encode($error).PHP_EOL,3, '/logs/fatal.log');
|
||||||
|
}
|
||||||
|
error_clear_last();
|
||||||
|
});
|
||||||
|
@ -2,10 +2,12 @@
|
|||||||
"name": "incoviba/cli",
|
"name": "incoviba/cli",
|
||||||
"type": "project",
|
"type": "project",
|
||||||
"require": {
|
"require": {
|
||||||
|
"ext-sockets": "*",
|
||||||
"dragonmantank/cron-expression": "^3.4",
|
"dragonmantank/cron-expression": "^3.4",
|
||||||
"guzzlehttp/guzzle": "^7.8",
|
"guzzlehttp/guzzle": "^7.8",
|
||||||
"hollodotme/fast-cgi-client": "^3.1",
|
"hollodotme/fast-cgi-client": "^3.1",
|
||||||
"monolog/monolog": "^3.5",
|
"monolog/monolog": "^3.5",
|
||||||
|
"pda/pheanstalk": "^7.0",
|
||||||
"php-di/php-di": "^7.0",
|
"php-di/php-di": "^7.0",
|
||||||
"predis/predis": "^3.0",
|
"predis/predis": "^3.0",
|
||||||
"symfony/console": "^6.3"
|
"symfony/console": "^6.3"
|
||||||
|
@ -7,5 +7,5 @@
|
|||||||
0 2 * * * /code/bin/incoviba money:uf >> /logs/commands 2>&1
|
0 2 * * * /code/bin/incoviba money:uf >> /logs/commands 2>&1
|
||||||
0 2 * * * /code/bin/incoviba money:uf:update >> /logs/commands 2>&1
|
0 2 * * * /code/bin/incoviba money:uf:update >> /logs/commands 2>&1
|
||||||
0 2 1 * * /code/bin/incoviba money:ipc >> /logs/commands 2>&1
|
0 2 1 * * /code/bin/incoviba money:ipc >> /logs/commands 2>&1
|
||||||
*/2 * * * * /code/bin/incoviba queue >> /logs/commands 2>&1
|
*/1 * * * * /code/bin/incoviba queue >> /logs/commands 2>&1
|
||||||
#0 3 * * * /code/bin/incoviba external:services >> /logs/commands 2>&1
|
0 3 * * * /code/bin/incoviba external:services >> /logs/commands 2>&1
|
||||||
|
21
cli/entrypoint
Normal file → Executable file
21
cli/entrypoint
Normal file → Executable file
@ -1,6 +1,19 @@
|
|||||||
#/usr/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
printenv >> /etc/environment
|
if [[ $# -gt 0 ]]
|
||||||
|
then
|
||||||
|
if [[ "$1" = "bash" || "$1" = "sh" || "$1" = "zsh" || "$1" = "/bin/bash" ]]
|
||||||
|
then
|
||||||
|
CMD=$1
|
||||||
|
shift
|
||||||
|
if [[ $# -gt 0 ]]
|
||||||
|
then
|
||||||
|
$CMD -c "$@"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
$CMD
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
#cron -f -L 11
|
/code/bin/incoviba "$@"
|
||||||
/code/bin/incoviba loop
|
|
||||||
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Full::class));
|
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Comunas::class));
|
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\BaseLoop::class));
|
|
@ -1,4 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Money\UF::class));
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Money\IPC::class));
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Money\UF\Update::class));
|
|
@ -1,9 +0,0 @@
|
|||||||
<?php
|
|
||||||
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'proyectos']);
|
|
||||||
$files = new FilesystemIterator($folder);
|
|
||||||
foreach ($files as $file) {
|
|
||||||
if ($file->isDir()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
include_once $file->getRealPath();
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Proyectos\Activos::class));
|
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Queue::class));
|
|
@ -1,9 +0,0 @@
|
|||||||
<?php
|
|
||||||
$folder = implode(DIRECTORY_SEPARATOR, [__DIR__, 'ventas']);
|
|
||||||
$files = new FilesystemIterator($folder);
|
|
||||||
foreach ($files as $file) {
|
|
||||||
if ($file->isDir()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
include_once $file->getRealPath();
|
|
||||||
}
|
|
@ -1,2 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Ventas\Cierres\Vigentes::class));
|
|
@ -1,4 +0,0 @@
|
|||||||
<?php
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Ventas\Cuotas\Hoy::class));
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Ventas\Cuotas\Pendientes::class));
|
|
||||||
$app->add($app->getContainer()->get(Incoviba\Command\Ventas\Cuotas\PorVencer::class));
|
|
@ -1,13 +1,3 @@
|
|||||||
<?php
|
<?php
|
||||||
/*function loadCommands(&$app): void {
|
|
||||||
$files = new FilesystemIterator($app->getContainer()->get('folders')->commands);
|
|
||||||
foreach ($files as $file) {
|
|
||||||
if ($file->isDir()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
include_once $file->getRealPath();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
loadCommands($app);*/
|
|
||||||
$app->setCommandLoader($app->getContainer()->get(Symfony\Component\Console\CommandLoader\CommandLoaderInterface::class));
|
$app->setCommandLoader($app->getContainer()->get(Symfony\Component\Console\CommandLoader\CommandLoaderInterface::class));
|
||||||
$app->setDefaultCommand('run:full');
|
$app->setDefaultCommand('loop');
|
||||||
|
@ -1,23 +1,26 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
use Psr\Container\ContainerInterface;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'commands' => function() {
|
'commands' => function(ContainerInterface $container) {
|
||||||
return [
|
$service = $container->get(Incoviba\Service\Commands::class);
|
||||||
'loop' => Incoviba\Command\BaseLoop::class,
|
if ($container->has('folders')) {
|
||||||
'comunas' => Incoviba\Command\Comunas::class,
|
$folders = $container->get('folders');
|
||||||
'contabilidad:cartolas:update' => Incoviba\Command\Contabilidad\Cartolas\Update::class,
|
if (is_array($folders)) {
|
||||||
'money:ipc' => Incoviba\Command\Money\IPC::class,
|
if (array_key_exists('commands', $folders)) {
|
||||||
'money:uf' => Incoviba\Command\Money\UF::class,
|
$service->baseCommandsPath = $folders['commands'];
|
||||||
'money:uf:update' => Incoviba\Command\Money\UF\Update::class,
|
}
|
||||||
'proyectos:activos' => Incoviba\Command\Proyectos\Activos::class,
|
} elseif (isset($folders->commands)) {
|
||||||
'run:full' => Incoviba\Command\Full::class,
|
$service->baseCommandsPath = $folders->commands;
|
||||||
'ventas:cierres:vigentes' => Incoviba\Command\Ventas\Cierres\Vigentes::class,
|
}
|
||||||
'ventas:cuotas:hoy' => Incoviba\Command\Ventas\Cuotas\Hoy::class,
|
}
|
||||||
'ventas:cuotas:pendientes' => Incoviba\Command\Ventas\Cuotas\Pendientes::class,
|
if ($container->has('skip_commands')) {
|
||||||
'ventas:cuotas:vencer' => Incoviba\Command\Ventas\Cuotas\PorVencer::class,
|
$service->skipCommands = $container->get('skip_commands');
|
||||||
'queue' => Incoviba\Command\Queue::class,
|
}
|
||||||
'external:services' => Incoviba\Command\ExternalServices::class,
|
if ($container->has('skipCommands')) {
|
||||||
'external:toku:reset' => Incoviba\Command\Ventas\MedioPagos\Toku\Reset::class,
|
$service->skipCommands = $container->get('skipCommands');
|
||||||
'external:toku:enqueue' => Incoviba\Command\Ventas\MedioPagos\Toku\Enqueue::class
|
}
|
||||||
];
|
return $service->getCommandsList();
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
@ -6,10 +6,6 @@ return [
|
|||||||
$arr['base'],
|
$arr['base'],
|
||||||
'resources'
|
'resources'
|
||||||
]);
|
]);
|
||||||
$arr['commands'] = implode(DIRECTORY_SEPARATOR, [
|
|
||||||
$arr['resources'],
|
|
||||||
'commands'
|
|
||||||
]);
|
|
||||||
$arr['cache'] = implode(DIRECTORY_SEPARATOR, [
|
$arr['cache'] = implode(DIRECTORY_SEPARATOR, [
|
||||||
$arr['base'],
|
$arr['base'],
|
||||||
'cache'
|
'cache'
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
use Psr\Container\ContainerInterface;
|
use Psr\Container\ContainerInterface;
|
||||||
|
|
||||||
return [
|
return [
|
||||||
DateTimeZone::class => function (ContainerInterface $container) {
|
DateTimeZone::class => function(ContainerInterface $container) {
|
||||||
return new DateTimeZone($container->get('TZ') ?? 'America/Santiago');
|
return new DateTimeZone($container->get('TZ') ?? 'America/Santiago');
|
||||||
},
|
},
|
||||||
'loopFrequency' => 60
|
'loopFrequency' => 60
|
||||||
|
@ -3,8 +3,9 @@ use Psr\Container\ContainerInterface;
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
Incoviba\Service\Login::class => function(ContainerInterface $container) {
|
Incoviba\Service\Login::class => function(ContainerInterface $container) {
|
||||||
|
$uri = $container->has('API_URL') ? $container->get('API_URL') : 'http://proxy/api';
|
||||||
$client = new GuzzleHttp\Client([
|
$client = new GuzzleHttp\Client([
|
||||||
'base_uri' => $container->has('API_URL') ? $container->get('API_URL') : 'http://proxy/api',
|
'base_uri' => $uri,
|
||||||
'headers' => [
|
'headers' => [
|
||||||
'Authorization' => [
|
'Authorization' => [
|
||||||
'Bearer ' . md5($container->get('API_KEY'))
|
'Bearer ' . md5($container->get('API_KEY'))
|
||||||
@ -16,7 +17,8 @@ return [
|
|||||||
$container->get(Psr\Log\LoggerInterface::class),
|
$container->get(Psr\Log\LoggerInterface::class),
|
||||||
implode(DIRECTORY_SEPARATOR, [$container->get('folders')->cache, 'token']),
|
implode(DIRECTORY_SEPARATOR, [$container->get('folders')->cache, 'token']),
|
||||||
$container->get('API_USERNAME'),
|
$container->get('API_USERNAME'),
|
||||||
$container->get('API_PASSWORD')
|
$container->get('API_PASSWORD'),
|
||||||
|
$container->get('API_KEY')
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
GuzzleHttp\HandlerStack::class => function(ContainerInterface $container) {
|
GuzzleHttp\HandlerStack::class => function(ContainerInterface $container) {
|
||||||
@ -24,7 +26,7 @@ return [
|
|||||||
$stack->setHandler($container->get(GuzzleHttp\Handler\CurlHandler::class));
|
$stack->setHandler($container->get(GuzzleHttp\Handler\CurlHandler::class));
|
||||||
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($container) {
|
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($container) {
|
||||||
$login = $container->get(Incoviba\Service\Login::class);
|
$login = $container->get(Incoviba\Service\Login::class);
|
||||||
return $request->withHeader('Authorization', "Bearer {$login->getKey($container->get('API_KEY'))}");
|
return $request->withHeader('Authorization', "Bearer {$login->getKey()}");
|
||||||
}));
|
}));
|
||||||
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($container) {
|
$stack->push(GuzzleHttp\Middleware::mapRequest(function(Psr\Http\Message\RequestInterface $request) use ($container) {
|
||||||
if (!$request->hasHeader('Authorization')) {
|
if (!$request->hasHeader('Authorization')) {
|
||||||
@ -41,10 +43,13 @@ return [
|
|||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
Incoviba\Service\FastCGI::class => function(ContainerInterface $container) {
|
Incoviba\Service\FastCGI::class => function(ContainerInterface $container) {
|
||||||
return new Incoviba\Service\FastCGI(
|
$fcgi = new Incoviba\Service\FastCGI(
|
||||||
|
$container->get(Incoviba\Service\Login::class),
|
||||||
$container->has('SOCKET_HOST') ? $container->get('SOCKET_HOST') : 'web',
|
$container->has('SOCKET_HOST') ? $container->get('SOCKET_HOST') : 'web',
|
||||||
$container->has('SOCKET_PORT') ? $container->get('SOCKET_PORT') : 9000,
|
$container->has('SOCKET_PORT') ? $container->get('SOCKET_PORT') : 9090,
|
||||||
$container->has('SOCKET_ROOT') ? $container->get('SOCKET_ROOT') : '/code/public/index.php'
|
$container->has('SOCKET_ROOT') ? $container->get('SOCKET_ROOT') : '/code/public/index.php'
|
||||||
);
|
);
|
||||||
|
$fcgi->setLogger($container->get(Psr\Log\LoggerInterface::class));
|
||||||
|
return $fcgi;
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
@ -19,5 +19,13 @@ return [
|
|||||||
$container->get(DateTimeZone::class),
|
$container->get(DateTimeZone::class),
|
||||||
$container->get('loopFrequency'),
|
$container->get('loopFrequency'),
|
||||||
);
|
);
|
||||||
|
},
|
||||||
|
Incoviba\Command\Queue::class => function(ContainerInterface $container) {
|
||||||
|
return new Incoviba\Command\Queue(
|
||||||
|
$container->get(Psr\Http\Client\ClientInterface::class),
|
||||||
|
$container->get('QueueLogger'),
|
||||||
|
$container->get(Incoviba\Service\Job::class),
|
||||||
|
$container->get(DateTimeZone::class)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
@ -64,27 +64,63 @@ return [
|
|||||||
], $container->get(DateTimeZone::class));
|
], $container->get(DateTimeZone::class));
|
||||||
},
|
},
|
||||||
'LoopLogger' => function(ContainerInterface $container) {
|
'LoopLogger' => function(ContainerInterface $container) {
|
||||||
return new Monolog\Logger('loop', [
|
$handlers = [
|
||||||
new Monolog\Handler\FilterHandler(
|
'warning' => new Monolog\Handler\FilterHandler(
|
||||||
($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development')
|
new Monolog\Handler\RotatingFileHandler('/logs/loop-error.log', 10),
|
||||||
? new Monolog\Handler\StreamHandler('/logs/loop-error.log')
|
|
||||||
: new Monolog\Handler\RotatingFileHandler('/logs/loop-error.log', 10),
|
|
||||||
Monolog\Level::Warning
|
Monolog\Level::Warning
|
||||||
),
|
),
|
||||||
new Monolog\Handler\FilterHandler(
|
'notice' => new Monolog\Handler\FilterHandler(
|
||||||
($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development')
|
new Monolog\Handler\RotatingFileHandler('/logs/loop.log', 10),
|
||||||
? new Monolog\Handler\StreamHandler('/logs/loop.log')
|
|
||||||
: new Monolog\Handler\RotatingFileHandler('/logs/loop.log', 10),
|
|
||||||
Monolog\Level::Notice,
|
Monolog\Level::Notice,
|
||||||
Monolog\Level::Notice
|
Monolog\Level::Notice
|
||||||
),
|
),
|
||||||
new Monolog\Handler\FilterHandler(
|
'debug' => new Monolog\Handler\FilterHandler(
|
||||||
($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development')
|
new Monolog\Handler\RotatingFileHandler('/logs/loop-debug.log', 10),
|
||||||
? new Monolog\Handler\StreamHandler('/logs/loop-debug.log')
|
|
||||||
: new Monolog\Handler\RotatingFileHandler('/logs/loop-debug.log', 10),
|
|
||||||
Monolog\Level::Debug,
|
Monolog\Level::Debug,
|
||||||
Monolog\Level::Debug
|
Monolog\Level::Debug
|
||||||
)
|
)
|
||||||
], [], $container->get(DateTimeZone::class));
|
];
|
||||||
|
if ($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development') {
|
||||||
|
$handlers['warning'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/loop-error.log'),
|
||||||
|
Monolog\Level::Warning);
|
||||||
|
$handlers['notice'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/loop.log'),
|
||||||
|
Monolog\Level::Notice, Monolog\Level::Notice);
|
||||||
|
$handlers['debug'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/loop-debug.log'),
|
||||||
|
Monolog\Level::Debug, Monolog\Level::Debug);
|
||||||
|
}
|
||||||
|
return new Monolog\Logger('loop', $handlers, [], $container->get(DateTimeZone::class));
|
||||||
|
},
|
||||||
|
'QueueLogger' => function(ContainerInterface $container) {
|
||||||
|
$handlers = [
|
||||||
|
'warning' => new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\RotatingFileHandler('/logs/queue-error.log', 10),
|
||||||
|
Monolog\Level::Warning
|
||||||
|
),
|
||||||
|
'notice' => new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\RotatingFileHandler('/logs/queue.log', 10),
|
||||||
|
Monolog\Level::Notice,
|
||||||
|
Monolog\Level::Notice
|
||||||
|
),
|
||||||
|
'debug' => new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\RotatingFileHandler('/logs/queue-debug.log', 10),
|
||||||
|
Monolog\Level::Debug,
|
||||||
|
Monolog\Level::Debug
|
||||||
|
)
|
||||||
|
];
|
||||||
|
if ($container->has('ENVIRONMENT') and $container->get('ENVIRONMENT') === 'development') {
|
||||||
|
$handlers['warning'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/queue-error.log'),
|
||||||
|
Monolog\Level::Warning);
|
||||||
|
$handlers['notice'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/queue.log'),
|
||||||
|
Monolog\Level::Notice, Monolog\Level::Notice);
|
||||||
|
$handlers['debug'] = new Monolog\Handler\FilterHandler(
|
||||||
|
new Monolog\Handler\StreamHandler('/logs/queue-debug.log'),
|
||||||
|
Monolog\Level::Debug, Monolog\Level::Debug);
|
||||||
|
}
|
||||||
|
return new Monolog\Logger('queue', $handlers, [], $container->get(DateTimeZone::class));
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
@ -16,4 +16,15 @@ return [
|
|||||||
}
|
}
|
||||||
return new Predis\Client($options);
|
return new Predis\Client($options);
|
||||||
},
|
},
|
||||||
|
Pheanstalk\Pheanstalk::class => function(ContainerInterface $container) {
|
||||||
|
return Pheanstalk\Pheanstalk::create(
|
||||||
|
$container->get('BEANSTALKD_HOST'),
|
||||||
|
$container->has('BEANSTALKD_PORT') ? $container->get('BEANSTALKD_PORT') : 11300
|
||||||
|
);
|
||||||
|
},
|
||||||
|
Incoviba\Service\MQTT\MQTTInterface::class => function(ContainerInterface $container) {
|
||||||
|
$service = new Incoviba\Service\MQTT($container->get(Psr\Log\LoggerInterface::class));
|
||||||
|
$service->register('default', $container->get(Incoviba\Service\MQTT\Pheanstalk::class));
|
||||||
|
return $service;
|
||||||
|
}
|
||||||
];
|
];
|
||||||
|
@ -37,6 +37,8 @@ class BaseLoop extends Console\Command\Command
|
|||||||
foreach ($commands as $command) {
|
foreach ($commands as $command) {
|
||||||
$this->runCommand($input, $output, $command);
|
$this->runCommand($input, $output, $command);
|
||||||
}
|
}
|
||||||
|
unset($commands);
|
||||||
|
memory_reset_peak_usage();
|
||||||
$this->waitNextTimeout($output, $start);
|
$this->waitNextTimeout($output, $start);
|
||||||
}
|
}
|
||||||
return self::SUCCESS;
|
return self::SUCCESS;
|
||||||
|
@ -10,7 +10,7 @@ use Incoviba\Common\Alias;
|
|||||||
)]
|
)]
|
||||||
class ExternalServices extends Alias\Command
|
class ExternalServices extends Alias\Command
|
||||||
{
|
{
|
||||||
protected function configure()
|
protected function configure(): void
|
||||||
{
|
{
|
||||||
$this->addOption('update', 'u', Console\Input\InputOption::VALUE_NONE, 'Update');
|
$this->addOption('update', 'u', Console\Input\InputOption::VALUE_NONE, 'Update');
|
||||||
}
|
}
|
||||||
|
67
cli/src/Command/Job/Run.php
Normal file
67
cli/src/Command/Job/Run.php
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Command\Job;
|
||||||
|
|
||||||
|
use DateMalformedStringException;
|
||||||
|
use DateTimeImmutable;
|
||||||
|
use DateTimeZone;
|
||||||
|
use Incoviba\Exception\Client\FastCGI as FastCGIException;
|
||||||
|
use Incoviba\Service;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Symfony\Component\Console;
|
||||||
|
|
||||||
|
#[Console\Attribute\AsCommand(name: 'jobs:run', description: 'Run job')]
|
||||||
|
class Run extends Console\Command\Command
|
||||||
|
{
|
||||||
|
public function __construct(protected Service\FastCGI $fastcgi, protected LoggerInterface $logger,
|
||||||
|
protected Service\Job $jobService,
|
||||||
|
protected DateTimeZone $timeZone, ?string $name = null)
|
||||||
|
{
|
||||||
|
parent::__construct($name);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$now = new DateTimeImmutable('now', $this->timeZone);
|
||||||
|
} catch (DateMalformedStringException) {
|
||||||
|
$now = new DateTimeImmutable();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->jobService->getPending() === 0) {
|
||||||
|
$output->writeln("[{$now->format('Y-m-d H:i:s e')}] No pending jobs to run.");
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$output->writeln("[{$now->format('Y-m-d H:i:s e')}] Running Ready Job...");
|
||||||
|
$this->runJob();
|
||||||
|
return $this->getResponses();
|
||||||
|
}
|
||||||
|
protected function runJob(): bool
|
||||||
|
{
|
||||||
|
$uri = "/api/queue/run";
|
||||||
|
|
||||||
|
try {
|
||||||
|
$this->fastcgi->get($uri);
|
||||||
|
return true;
|
||||||
|
} catch (FastCGIException $exception) {
|
||||||
|
$this->logger->error($exception->getMessage(), ['uri' => $uri, 'exception' =>$exception]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
protected function getResponses(): int
|
||||||
|
{
|
||||||
|
$result = self::SUCCESS;
|
||||||
|
$responses = $this->fastcgi->awaitResponses();
|
||||||
|
foreach ($responses as $response) {
|
||||||
|
if ($response->getError() !== '') {
|
||||||
|
$this->logger->error("Error running job", [
|
||||||
|
'error' => $response->getError(),
|
||||||
|
'body' => $response->getBody(),
|
||||||
|
'headers' => $response->getHeaders(),
|
||||||
|
]);
|
||||||
|
$result = self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
@ -3,14 +3,12 @@ namespace Incoviba\Command;
|
|||||||
|
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
use DateTimeZone;
|
use DateTimeZone;
|
||||||
use Psr\Http\Client\ClientExceptionInterface;
|
|
||||||
use Psr\Http\Client\ClientInterface;
|
use Psr\Http\Client\ClientInterface;
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Symfony\Component\Console;
|
use Symfony\Component\Console;
|
||||||
use Incoviba\Service\FastCGI;
|
|
||||||
use Incoviba\Service\Job;
|
use Incoviba\Service\Job;
|
||||||
use Incoviba\Common\Alias\Command;
|
use Incoviba\Common\Alias\Command;
|
||||||
use Incoviba\Exception\Client\FastCGI as FastCGIException;
|
use Throwable;
|
||||||
|
|
||||||
#[Console\Attribute\AsCommand(
|
#[Console\Attribute\AsCommand(
|
||||||
name: 'queue',
|
name: 'queue',
|
||||||
@ -21,7 +19,8 @@ class Queue extends Command
|
|||||||
public function __construct(ClientInterface $client, LoggerInterface $logger,
|
public function __construct(ClientInterface $client, LoggerInterface $logger,
|
||||||
protected Job $jobService,
|
protected Job $jobService,
|
||||||
protected DateTimeZone $timezone,
|
protected DateTimeZone $timezone,
|
||||||
protected FastCGI $fastcgi,
|
protected string $baseCommand = '/code/bin/incoviba',
|
||||||
|
protected int $batchSize = 10,
|
||||||
?string $name = null)
|
?string $name = null)
|
||||||
{
|
{
|
||||||
parent::__construct($client, $logger, $name);
|
parent::__construct($client, $logger, $name);
|
||||||
@ -30,58 +29,53 @@ class Queue extends Command
|
|||||||
public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
||||||
{
|
{
|
||||||
$this->logger->debug("Running {$this->getName()}");
|
$this->logger->debug("Running {$this->getName()}");
|
||||||
$io = new Console\Style\SymfonyStyle($input, $output);
|
$this->sections = [
|
||||||
|
'top' => $output->section(),
|
||||||
|
'bottom' => $output->section(),
|
||||||
|
];
|
||||||
|
$io = new Console\Style\SymfonyStyle($input, $this->sections['top']);
|
||||||
$now = new DateTimeImmutable('now', $this->timezone);
|
$now = new DateTimeImmutable('now', $this->timezone);
|
||||||
$io->title("[{$now->format('Y-m-d H:i:s e')}] Running Queue...");
|
|
||||||
|
|
||||||
$jobs = $this->getJobs($output);
|
if ($this->jobService->getPending() === 0) {
|
||||||
if (count($jobs) === 0) {
|
$io->success("[{$now->format('Y-m-d H:i:s e')}] Queue is empty");
|
||||||
$this->logger->debug("No jobs to run");
|
|
||||||
return Console\Command\Command::SUCCESS;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->runJobs($output, $jobs);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getJobs(Console\Output\OutputInterface $output): array
|
|
||||||
{
|
|
||||||
$this->logger->debug("Getting jobs");
|
|
||||||
$jobs = $this->jobService->getPending();
|
|
||||||
return array_column($jobs, 'id');
|
|
||||||
}
|
|
||||||
protected function runJobs(Console\Output\OutputInterface $output, array $jobs): int
|
|
||||||
{
|
|
||||||
$errors = 0;
|
|
||||||
foreach ($jobs as $job) {
|
|
||||||
if ($this->runJob($output, $job) === Console\Command\Command::FAILURE) {
|
|
||||||
$this->logger->error("Error running job: {$job}");
|
|
||||||
$errors ++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$responses = $this->fastcgi->awaitResponses();
|
|
||||||
foreach ($responses as $response) {
|
|
||||||
if ((int) floor($response->getStatusCode() / 100) !== 2) {
|
|
||||||
$this->logger->error("Error running job", [
|
|
||||||
'status' => $response->getStatusCode(),
|
|
||||||
'body' => $response->getBody()->getContents(),
|
|
||||||
'headers' => $response->getHeaders(),
|
|
||||||
]);
|
|
||||||
$errors ++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $errors === 0 ? Console\Command\Command::SUCCESS : Console\Command\Command::FAILURE;
|
|
||||||
}
|
|
||||||
protected function runJob(Console\Output\OutputInterface $output, int $job_id): int
|
|
||||||
{
|
|
||||||
$uri = "/api/queue/run/{$job_id}";
|
|
||||||
$output->writeln("GET {$uri}");
|
|
||||||
|
|
||||||
try {
|
|
||||||
$this->fastcgi->get($uri);
|
|
||||||
return self::SUCCESS;
|
return self::SUCCESS;
|
||||||
} catch (FastCGIException $exception) {
|
}
|
||||||
$this->logger->error($exception->getMessage(), ['uri' => $uri, 'exception' =>$exception]);
|
|
||||||
|
$io->title("[{$now->format('Y-m-d H:i:s e')}] Running Queue...");
|
||||||
|
$results = [];
|
||||||
|
for ($i = 0; $i < $this->batchSize; $i++) {
|
||||||
|
if ($this->jobService->getPending() === 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$results []= $this->runJob();
|
||||||
|
}
|
||||||
|
return count(array_filter($results, fn ($result) => $result === self::FAILURE)) === 0 ? self::SUCCESS : self::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected array $sections;
|
||||||
|
protected array $outputs = [];
|
||||||
|
protected function runJob(): int
|
||||||
|
{
|
||||||
|
$baseCommand = "{$this->baseCommand} jobs:run";
|
||||||
|
$command = "{$baseCommand}";
|
||||||
|
try {
|
||||||
|
exec($command, $output, $resultCode);
|
||||||
|
$this->outputs []= $output;
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->logger->error("Failed to run command", [
|
||||||
|
'command' => $command,
|
||||||
|
'exception' => $exception
|
||||||
|
]);
|
||||||
return self::FAILURE;
|
return self::FAILURE;
|
||||||
}
|
}
|
||||||
|
if ($resultCode !== 0) {
|
||||||
|
$this->logger->error("Failed to run command", [
|
||||||
|
'command' => $command,
|
||||||
|
'result_code' => $resultCode
|
||||||
|
]);
|
||||||
|
return self::FAILURE;
|
||||||
|
} else {
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
22
cli/src/Command/Queue/Pending.php
Normal file
22
cli/src/Command/Queue/Pending.php
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Command\Queue;
|
||||||
|
|
||||||
|
use Incoviba\Service;
|
||||||
|
use Symfony\Component\Console;
|
||||||
|
|
||||||
|
#[Console\Attribute\AsCommand(name: 'queue:pending', description: 'List pending jobs in queue')]
|
||||||
|
class Pending extends Console\Command\Command
|
||||||
|
{
|
||||||
|
public function __construct(protected Service\Job $jobService, ?string $name = null)
|
||||||
|
{
|
||||||
|
parent::__construct($name);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
||||||
|
{
|
||||||
|
$jobCount = $this->jobService->getPending();
|
||||||
|
$output->writeln("Found {$jobCount} pending jobs");
|
||||||
|
|
||||||
|
return self::SUCCESS;
|
||||||
|
}
|
||||||
|
}
|
121
cli/src/Command/Queue/Push.php
Normal file
121
cli/src/Command/Queue/Push.php
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Command\Queue;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Symfony\Component\Console;
|
||||||
|
use Incoviba\Service;
|
||||||
|
|
||||||
|
#[Console\Attribute\AsCommand(name: 'queue:push', description: 'Push a job to the queue')]
|
||||||
|
class Push extends Console\Command\Command
|
||||||
|
{
|
||||||
|
public function __construct(protected LoggerInterface $logger, protected Service\Job $jobService, ?string $name = null)
|
||||||
|
{
|
||||||
|
parent::__construct($name);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function configure(): void
|
||||||
|
{
|
||||||
|
$this->addOption('configurations', 'c', Console\Input\InputOption::VALUE_REQUIRED | Console\Input\InputOption::VALUE_IS_ARRAY, 'Job configuration options array, each job configuration must be in valid JSON format');
|
||||||
|
$this->addOption('files', 'f', Console\Input\InputOption::VALUE_REQUIRED | Console\Input\InputOption::VALUE_IS_ARRAY, 'Paths to jobs configurations files with JSON array content');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
|
||||||
|
{
|
||||||
|
$io = new Console\Style\SymfonyStyle($input, $output);
|
||||||
|
$io->title("Pushing job");
|
||||||
|
|
||||||
|
$configurations = $this->getConfigurations($input);
|
||||||
|
if (count($configurations) === 0) {
|
||||||
|
$io->error('Missing configurations');
|
||||||
|
return self::FAILURE;
|
||||||
|
}
|
||||||
|
$result = self::SUCCESS;
|
||||||
|
foreach ($configurations as $configuration) {
|
||||||
|
if (!json_validate($configuration)) {
|
||||||
|
$io->error("Invalid JSON: {$configuration}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$configuration = json_decode($configuration, true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$job = $this->jobService->push($configuration);
|
||||||
|
$io->success("Job pushed with ID {$job['id']}");
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$io->error($exception->getMessage());
|
||||||
|
$result = self::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getConfigurations(Console\Input\InputInterface $input): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
...$this->getFilesConfigurations($input),
|
||||||
|
...$this->getOptionConfigurations($input),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
protected function getFilesConfigurations(Console\Input\InputInterface $input): array
|
||||||
|
{
|
||||||
|
$configurations = [];
|
||||||
|
$files = $input->getOption('files');
|
||||||
|
if ($files === null) {
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
foreach ($files as $filePath) {
|
||||||
|
if (!file_exists($filePath)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$configurations = array_merge($configurations, $this->getFileConfigurations($filePath));
|
||||||
|
}
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
protected function getFileConfigurations(string $filePath): array
|
||||||
|
{
|
||||||
|
$configurations = [];
|
||||||
|
if (!file_exists($filePath)) {
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
$json = file_get_contents($filePath);
|
||||||
|
if (!json_validate($json)) {
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
$tmp = json_decode($json, true);
|
||||||
|
foreach ($tmp as $config) {
|
||||||
|
try {
|
||||||
|
$configurations []= $this->processConfiguration(json_encode($config));
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->logger->warning($exception->getMessage(), ['exception' => $exception, 'config' => $config]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
protected function getOptionConfigurations(Console\Input\InputInterface $input): array
|
||||||
|
{
|
||||||
|
$configurations = [];
|
||||||
|
$configOptions = $input->getOption('configurations');
|
||||||
|
if ($configOptions === null) {
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
foreach ($configOptions as $config) {
|
||||||
|
try {
|
||||||
|
$configurations []= $this->processConfiguration($config);
|
||||||
|
} catch (Throwable $exception) {
|
||||||
|
$this->logger->warning($exception->getMessage(), ['exception' => $exception, 'config' => $config]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $configurations;
|
||||||
|
}
|
||||||
|
protected function processConfiguration(string $configuration): string
|
||||||
|
{
|
||||||
|
$json = json_decode($configuration, true);
|
||||||
|
if (!array_key_exists('type', $json) and !array_key_exists('configuration', $json)) {
|
||||||
|
throw new Console\Exception\InvalidArgumentException('Missing type or configuration key in JSON');
|
||||||
|
}
|
||||||
|
if (array_key_exists('type', $json)) {
|
||||||
|
return json_encode($json);
|
||||||
|
}
|
||||||
|
return json_encode($json['configuration']);
|
||||||
|
}
|
||||||
|
}
|
@ -7,7 +7,7 @@ use Psr\Http\Client\ClientExceptionInterface;
|
|||||||
|
|
||||||
class FastCGI implements ClientExceptionInterface
|
class FastCGI implements ClientExceptionInterface
|
||||||
{
|
{
|
||||||
public function __construct(protected ?Throwable $previous) {}
|
public function __construct(protected ?Throwable $previous = null) {}
|
||||||
|
|
||||||
public function getMessage(): string
|
public function getMessage(): string
|
||||||
{
|
{
|
||||||
|
18
cli/src/Exception/MQTT.php
Normal file
18
cli/src/Exception/MQTT.php
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
abstract class MQTT extends Exception
|
||||||
|
{
|
||||||
|
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$baseCode = 700;
|
||||||
|
$code = $baseCode + $code;
|
||||||
|
if ($message == "") {
|
||||||
|
$message = "MQTT Exception";
|
||||||
|
}
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
cli/src/Exception/MQTT/Create.php
Normal file
15
cli/src/Exception/MQTT/Create.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class Create extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $tube = '', string $payload = '', ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Unable to create MQTT message: {$payload} in tube {$tube}";
|
||||||
|
$code = 11;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
cli/src/Exception/MQTT/Delete.php
Normal file
15
cli/src/Exception/MQTT/Delete.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class Delete extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $tube, int $jobId, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Could not delete job {$jobId} in tube {$tube}";
|
||||||
|
$code = 13;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
15
cli/src/Exception/MQTT/Read.php
Normal file
15
cli/src/Exception/MQTT/Read.php
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class Read extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $tube, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Error reading from tube {$tube}";
|
||||||
|
$code = 10;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
14
cli/src/Exception/MQTT/UnknownTransport.php
Normal file
14
cli/src/Exception/MQTT/UnknownTransport.php
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class UnknownTransport extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $transportName, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$message = "Unknown transport {$transportName}";
|
||||||
|
parent::__construct($message, 1, $previous);
|
||||||
|
}
|
||||||
|
}
|
16
cli/src/Exception/MQTT/Update.php
Normal file
16
cli/src/Exception/MQTT/Update.php
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
use Throwable;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class Update extends MQTT
|
||||||
|
{
|
||||||
|
public function __construct(string $tube, string $payload, ?int $jobId = null, ?Throwable $previous = null)
|
||||||
|
{
|
||||||
|
$jobString = $jobId !== null ? " with jobId {$jobId}" : '';
|
||||||
|
$message = "Could not update job{$jobString} with {$payload} in tube {$tube}";
|
||||||
|
$code = 12;
|
||||||
|
parent::__construct($message, $code, $previous);
|
||||||
|
}
|
||||||
|
}
|
9
cli/src/Service.php
Normal file
9
cli/src/Service.php
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
|
||||||
|
abstract class Service
|
||||||
|
{
|
||||||
|
public function __construct(protected LoggerInterface $logger) {}
|
||||||
|
}
|
51
cli/src/Service/Commands.php
Normal file
51
cli/src/Service/Commands.php
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
|
use RecursiveDirectoryIterator;
|
||||||
|
use RecursiveIteratorIterator;
|
||||||
|
use ReflectionClass;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Symfony\Component\Console\Attribute\AsCommand;
|
||||||
|
|
||||||
|
class Commands
|
||||||
|
{
|
||||||
|
public function __construct(protected LoggerInterface $logger, public ?string $baseCommandsPath = null, public array $skipCommands = [])
|
||||||
|
{
|
||||||
|
if ($this->baseCommandsPath === null) {
|
||||||
|
$this->baseCommandsPath = implode(DIRECTORY_SEPARATOR, [
|
||||||
|
dirname(__DIR__, 1),
|
||||||
|
'Command'
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
$this->baseCommandsPath = realpath($this->baseCommandsPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCommandsList(): array
|
||||||
|
{
|
||||||
|
$commands = [];
|
||||||
|
$files = new RecursiveIteratorIterator((new RecursiveDirectoryIterator($this->baseCommandsPath)));
|
||||||
|
foreach ($files as $file) {
|
||||||
|
if ($file->isDir()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$basename = ltrim(str_replace(DIRECTORY_SEPARATOR, "\\",
|
||||||
|
str_replace([$this->baseCommandsPath, '.php'], '', $file->getRealPath())), "\\");
|
||||||
|
$namespace = "Incoviba\\Command";
|
||||||
|
$class = "{$namespace}\\{$basename}";
|
||||||
|
if (!class_exists($class)) {
|
||||||
|
$this->logger->error("Class {$class} not found");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$ref = new ReflectionClass($class);
|
||||||
|
$commandData = $ref->getAttributes(AsCommand::class)[0];
|
||||||
|
$commandName = $commandData->getArguments()['name'];
|
||||||
|
|
||||||
|
if (in_array($commandName, $this->skipCommands) or in_array($class, $this->skipCommands)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$commands[$commandName] = $class;
|
||||||
|
}
|
||||||
|
return $commands;
|
||||||
|
}
|
||||||
|
}
|
@ -8,20 +8,22 @@ use Incoviba\Exception\Client\FastCGI as FastCGIException;
|
|||||||
|
|
||||||
class FastCGI implements LoggerAwareInterface
|
class FastCGI implements LoggerAwareInterface
|
||||||
{
|
{
|
||||||
public function __construct(protected string $hostname, protected int $port,
|
public function __construct(protected Login $loginService, protected string $hostname, protected int $port,
|
||||||
protected string $documentRoot,
|
protected string $documentRoot,
|
||||||
|
protected int $maxRequests = 50,
|
||||||
protected int $connectionTimeout = 5000, protected int $readTimeout = 5000)
|
protected int $connectionTimeout = 5000, protected int $readTimeout = 5000)
|
||||||
{
|
{
|
||||||
$this->client = new FCGI\Client();
|
$this->client = new FCGI\Client();
|
||||||
}
|
}
|
||||||
|
|
||||||
public LoggerInterface $logger {
|
public LoggerInterface $logger;
|
||||||
get {
|
public function getLogger(): LoggerInterface
|
||||||
|
{
|
||||||
return $this->logger;
|
return $this->logger;
|
||||||
}
|
}
|
||||||
set(LoggerInterface $logger) {
|
public function setLogger(LoggerInterface $logger): void
|
||||||
$this->logger = $logger;
|
{
|
||||||
}
|
$this->logger = $logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected FCGI\Client $client;
|
protected FCGI\Client $client;
|
||||||
@ -39,9 +41,13 @@ class FastCGI implements LoggerAwareInterface
|
|||||||
*/
|
*/
|
||||||
public function sendRequest(FCGI\Interfaces\ProvidesRequestData $request): self
|
public function sendRequest(FCGI\Interfaces\ProvidesRequestData $request): self
|
||||||
{
|
{
|
||||||
|
if (count($this->socketIds) >= $this->maxRequests) {
|
||||||
|
throw new FastCGIException();
|
||||||
|
}
|
||||||
if (!isset($this->socket)) {
|
if (!isset($this->socket)) {
|
||||||
$this->connect();
|
$this->connect();
|
||||||
}
|
}
|
||||||
|
$request = $this->setHeaders($request);
|
||||||
try {
|
try {
|
||||||
$this->socketIds []= $this->client->sendAsyncRequest($this->socket, $request);
|
$this->socketIds []= $this->client->sendAsyncRequest($this->socket, $request);
|
||||||
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
|
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
|
||||||
@ -57,16 +63,31 @@ class FastCGI implements LoggerAwareInterface
|
|||||||
public function awaitResponses(): array
|
public function awaitResponses(): array
|
||||||
{
|
{
|
||||||
$responses = [];
|
$responses = [];
|
||||||
|
$repeats = 0;
|
||||||
|
|
||||||
|
$maxRepeats = min(count($this->socketIds), $this->maxRequests);
|
||||||
|
|
||||||
while ($this->client->hasUnhandledResponses()) {
|
while ($this->client->hasUnhandledResponses()) {
|
||||||
|
if ($repeats >= $maxRepeats) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
|
$readySocketIds = $this->client->getSocketIdsHavingResponse();
|
||||||
$readyResponses = $this->client->readReadyResponses(3000);
|
$readyResponses = $this->client->readReadyResponses(3000);
|
||||||
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
|
} catch (FCGI\Exceptions\FastCGIClientException $exception) {
|
||||||
$this->logger->error($exception->getMessage());
|
$this->logger->error($exception->getMessage());
|
||||||
|
$repeats ++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
foreach ($readyResponses as $response) {
|
foreach ($readyResponses as $response) {
|
||||||
$responses []= $response;
|
$responses []= $response;
|
||||||
|
$repeats ++;
|
||||||
}
|
}
|
||||||
|
$this->socketIds = array_diff($this->socketIds, $readySocketIds);
|
||||||
|
}
|
||||||
|
if ($this->client->hasUnhandledResponses()) {
|
||||||
|
$this->logger->error("Unhandled responses");
|
||||||
|
return array_merge($responses, $this->awaitResponses());
|
||||||
}
|
}
|
||||||
return $responses;
|
return $responses;
|
||||||
}
|
}
|
||||||
@ -96,4 +117,11 @@ class FastCGI implements LoggerAwareInterface
|
|||||||
$request->setRequestUri($uri);
|
$request->setRequestUri($uri);
|
||||||
return $this->sendRequest($request);
|
return $this->sendRequest($request);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function setHeaders(FCGI\Interfaces\ProvidesRequestData $request): FCGI\Interfaces\ProvidesRequestData
|
||||||
|
{
|
||||||
|
$apiKey = $this->loginService->getKey();
|
||||||
|
$request->setCustomVar('HTTP_AUTHORIZATION', "Bearer {$apiKey}");
|
||||||
|
return $request;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,26 +1,49 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace Incoviba\Service;
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
use Exception;
|
use DateInvalidTimeZoneException;
|
||||||
|
use DateMalformedStringException;
|
||||||
|
use DateTimeImmutable;
|
||||||
|
use DateTimeZone;
|
||||||
use Psr\Log\LoggerInterface;
|
use Psr\Log\LoggerInterface;
|
||||||
use Predis\Connection\ConnectionException;
|
use Incoviba\Exception\MQTT as MQTTException;
|
||||||
|
use Incoviba\Service\MQTT\MQTTInterface;
|
||||||
|
|
||||||
class Job
|
class Job
|
||||||
{
|
{
|
||||||
public function __construct(protected LoggerInterface $logger, protected Redis $redisService)
|
public function __construct(protected LoggerInterface $logger, protected MQTTInterface $mqttService) {}
|
||||||
{
|
|
||||||
$this->redisKey = 'jobs';
|
|
||||||
}
|
|
||||||
protected string $redisKey;
|
protected string $redisKey;
|
||||||
|
|
||||||
public function getPending(): array
|
public function getPending(): int
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
$jobs = $this->redisService->get($this->redisKey);
|
return $this->mqttService->pending();
|
||||||
return json_decode($jobs, true);
|
} catch (MQTTException $exception) {
|
||||||
} catch (ConnectionException|Exception $exception) {
|
$this->logger->warning($exception->getMessage(), ['exception' => $exception]);
|
||||||
$this->logger->warning($exception);
|
return 0;
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function push(array $jobConfiguration): array
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$now = (new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago')));
|
||||||
|
} catch (DateMalformedStringException | DateInvalidTimeZoneException) {
|
||||||
|
$now = new DateTimeImmutable();
|
||||||
|
}
|
||||||
|
$data = [
|
||||||
|
'id' => $now->format('Uu'),
|
||||||
|
'configuration' => $jobConfiguration,
|
||||||
|
'executed' => false,
|
||||||
|
'created_at' => $now->format('Y-m-d H:i:s'),
|
||||||
|
'updated_at' => null,
|
||||||
|
'retries' => 0
|
||||||
|
];
|
||||||
|
try {
|
||||||
|
$this->mqttService->set(json_encode($data));
|
||||||
|
} catch (MQTTException $exception) {
|
||||||
|
$this->logger->warning($exception->getMessage(), ['exception' => $exception]);
|
||||||
|
}
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,7 +10,7 @@ class Login
|
|||||||
{
|
{
|
||||||
public function __construct(protected ClientInterface $client, protected LoggerInterface $logger,
|
public function __construct(protected ClientInterface $client, protected LoggerInterface $logger,
|
||||||
protected string $tokenFilename,
|
protected string $tokenFilename,
|
||||||
protected string $username, protected string $password) {}
|
protected string $username, protected string $password, protected string $apiKey) {}
|
||||||
|
|
||||||
public function login(): string
|
public function login(): string
|
||||||
{
|
{
|
||||||
@ -84,8 +84,11 @@ class Login
|
|||||||
}
|
}
|
||||||
return $response->getStatusCode() === 200;
|
return $response->getStatusCode() === 200;
|
||||||
}
|
}
|
||||||
public function getKey(string $apiKey, string $separator = 'g'): string
|
public function getKey(?string $apiKey = null, string $separator = 'g'): string
|
||||||
{
|
{
|
||||||
|
if ($apiKey === null) {
|
||||||
|
$apiKey = $this->apiKey;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
$savedToken = $this->retrieveToken();
|
$savedToken = $this->retrieveToken();
|
||||||
$token = implode('', [md5($apiKey), $separator, $savedToken]);
|
$token = implode('', [md5($apiKey), $separator, $savedToken]);
|
||||||
|
124
cli/src/Service/MQTT.php
Normal file
124
cli/src/Service/MQTT.php
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
|
use Incoviba\Exception\MQTT as MQTTException;
|
||||||
|
use Incoviba\Service;
|
||||||
|
use Incoviba\Service\MQTT\MQTTInterface;
|
||||||
|
|
||||||
|
class MQTT extends Service implements MQTTInterface
|
||||||
|
{
|
||||||
|
protected array $transports = [];
|
||||||
|
public function register(string $name, MQTTInterface $transport): self
|
||||||
|
{
|
||||||
|
$this->transports[$name] = $transport;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $payload
|
||||||
|
* @param int $delay
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Create
|
||||||
|
*/
|
||||||
|
public function set(string $payload, int $delay = 0, ?string $transportName = null): self
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
$transport->set($payload, $delay);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return int
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Read
|
||||||
|
*/
|
||||||
|
public function pending(?string $transportName = null): int
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
return $transport->pending();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return bool
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Read
|
||||||
|
*/
|
||||||
|
public function exists(?int $jobId = null, ?string $transportName = null): bool
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
return $transport->exists($jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return string
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Read
|
||||||
|
*/
|
||||||
|
public function get(?int $jobId = null, ?string $transportName = null): string
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
return $transport->get($jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $newPayload
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Update
|
||||||
|
*/
|
||||||
|
public function update(string $newPayload, ?int $jobId = null, ?string $transportName = null): self
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
$transport->update($newPayload, $jobId);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return $this
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
* @throws MQTTException\Delete
|
||||||
|
*/
|
||||||
|
public function remove(?int $jobId = null, ?string $transportName = null): self
|
||||||
|
{
|
||||||
|
$transport = $this->getTransport($transportName);
|
||||||
|
$transport->remove($jobId);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string|null $transportName
|
||||||
|
* @return mixed
|
||||||
|
* @throws MQTTException\UnknownTransport
|
||||||
|
*/
|
||||||
|
protected function getTransport(?string $transportName): mixed
|
||||||
|
{
|
||||||
|
if (count($this->transports) === 0) {
|
||||||
|
throw new MQTTException\UnknownTransport('');
|
||||||
|
}
|
||||||
|
if ($transportName === null) {
|
||||||
|
if (array_key_exists('default', $this->transports)) {
|
||||||
|
$transportName = 'default';
|
||||||
|
} else {
|
||||||
|
$transportName = array_keys($this->transports)[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!array_key_exists($transportName, $this->transports)) {
|
||||||
|
if ($transportName === null) {
|
||||||
|
$transportName = '';
|
||||||
|
}
|
||||||
|
throw new MQTTException\UnknownTransport($transportName);
|
||||||
|
}
|
||||||
|
return $this->transports[$transportName];
|
||||||
|
}
|
||||||
|
}
|
127
cli/src/Service/MQTT/Beanstalkd.php
Normal file
127
cli/src/Service/MQTT/Beanstalkd.php
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use xobotyi\beansclient;
|
||||||
|
use Incoviba\Service;
|
||||||
|
use Incoviba\Exception\MQTT;
|
||||||
|
|
||||||
|
class Beanstalkd extends Service implements MQTTInterface
|
||||||
|
{
|
||||||
|
const string DEFAULT_TUBE = 'default';
|
||||||
|
const int DEFAULT_TTR = 30;
|
||||||
|
const int DEFAULT_PRIORITY = 1_024;
|
||||||
|
|
||||||
|
public function __construct(LoggerInterface $logger, protected beansclient\Client $client,
|
||||||
|
protected string $tube = self::DEFAULT_TUBE,
|
||||||
|
protected int $ttr = self::DEFAULT_TTR,
|
||||||
|
protected int $priority = self::DEFAULT_PRIORITY)
|
||||||
|
{
|
||||||
|
parent::__construct($logger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $payload
|
||||||
|
* @param int $delay
|
||||||
|
* @return self
|
||||||
|
* @throws MQTT\Create
|
||||||
|
*/
|
||||||
|
public function set(string $payload, int $delay = 60): self
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$this->client->put($payload, $this->ttr, $this->priority, $delay);
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
throw new MQTT\Create($this->tube, $payload, $exception);
|
||||||
|
}
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return int
|
||||||
|
* @throws MQTT\Read
|
||||||
|
*/
|
||||||
|
public function pending(): int
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$stats = $this->client
|
||||||
|
->statsTube($this->tube);
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
throw new MQTT\Read($this->tube, $exception);
|
||||||
|
}
|
||||||
|
if (!array_key_exists('current-jobs-ready', $stats)) {
|
||||||
|
throw new MQTT\Read($this->tube);
|
||||||
|
}
|
||||||
|
return $stats['current-jobs-ready'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return bool
|
||||||
|
* @throws MQTT\Read
|
||||||
|
*/
|
||||||
|
public function exists(?int $jobId = null): bool
|
||||||
|
{
|
||||||
|
return $this->pending() > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected int $currentJobId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return string
|
||||||
|
* @throws MQTT\Read
|
||||||
|
*/
|
||||||
|
public function get(?int $jobId = null): string
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
if ($jobId !== null) {
|
||||||
|
$job = (object) $this->client
|
||||||
|
->reserveJob($jobId);
|
||||||
|
} else {
|
||||||
|
$job = (object) $this->client
|
||||||
|
->reserve();
|
||||||
|
}
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
throw new MQTT\Read($this->tube, $exception);
|
||||||
|
}
|
||||||
|
$this->currentJobId = $job->id;
|
||||||
|
return $job->payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $newPayload
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return self
|
||||||
|
* @throws MQTT\Update
|
||||||
|
*/
|
||||||
|
public function update(string $newPayload, ?int $jobId = null): self
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$this->remove($jobId);
|
||||||
|
$this->set($newPayload);
|
||||||
|
} catch (MQTT\Delete | MQTT\Create $exception) {
|
||||||
|
throw new MQTT\Update($this->tube, $newPayload, $jobId, $exception);
|
||||||
|
}
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int|null $jobId
|
||||||
|
* @return self
|
||||||
|
* @throws MQTT\Delete
|
||||||
|
*/
|
||||||
|
public function remove(?int $jobId = null): self
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJobId;
|
||||||
|
}
|
||||||
|
$this->client
|
||||||
|
->delete($jobId);
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
throw new MQTT\Delete($this->tube, $jobId, $exception);
|
||||||
|
}
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
12
cli/src/Service/MQTT/MQTTInterface.php
Normal file
12
cli/src/Service/MQTT/MQTTInterface.php
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
interface MQTTInterface
|
||||||
|
{
|
||||||
|
public function set(string $payload, int $delay = 0): self;
|
||||||
|
public function pending(): int;
|
||||||
|
public function exists(?int $jobId = null): bool;
|
||||||
|
public function get(?int $jobId = null): string;
|
||||||
|
public function update(string $newPayload, ?int $jobId = null): self;
|
||||||
|
public function remove(?int $jobId = null): self;
|
||||||
|
}
|
65
cli/src/Service/MQTT/Pheanstalk.php
Normal file
65
cli/src/Service/MQTT/Pheanstalk.php
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service\MQTT;
|
||||||
|
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Pheanstalk as PBA;
|
||||||
|
use Incoviba\Service;
|
||||||
|
|
||||||
|
class Pheanstalk extends Service implements MQTTInterface
|
||||||
|
{
|
||||||
|
public function __construct(LoggerInterface $logger, protected PBA\Pheanstalk $client, string $tubeName = 'default')
|
||||||
|
{
|
||||||
|
parent::__construct($logger);
|
||||||
|
$this->tube = new PBA\Values\TubeName($tubeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected PBA\Values\TubeName $tube;
|
||||||
|
|
||||||
|
public function set(string $payload, int $delay = 0): self
|
||||||
|
{
|
||||||
|
$this->client->useTube($this->tube);
|
||||||
|
$this->client->put($payload, $delay);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function pending(): int
|
||||||
|
{
|
||||||
|
$stats = $this->client->statsTube($this->tube);
|
||||||
|
return $stats->currentJobsReady;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exists(?int $jobId = null): bool
|
||||||
|
{
|
||||||
|
return $this->pending() > 0;
|
||||||
|
}
|
||||||
|
protected int $currentJobId;
|
||||||
|
public function get(?int $jobId = null): string
|
||||||
|
{
|
||||||
|
$this->client->watch($this->tube);
|
||||||
|
if ($jobId !== null) {
|
||||||
|
$jobId = new PBA\Values\JobId($jobId);
|
||||||
|
$job = $this->client->reserveJob($jobId);
|
||||||
|
} else {
|
||||||
|
$job = $this->client->reserve();
|
||||||
|
}
|
||||||
|
$this->currentJobId = $job->getId();
|
||||||
|
return $job->getData();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(string $newPayload, ?int $jobId = null): self
|
||||||
|
{
|
||||||
|
$this->remove($jobId);
|
||||||
|
$this->set($newPayload);
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function remove(?int $jobId = null): self
|
||||||
|
{
|
||||||
|
if ($jobId === null) {
|
||||||
|
$jobId = $this->currentJobId;
|
||||||
|
}
|
||||||
|
$this->client->watch($this->tube);
|
||||||
|
$this->client->delete(new PBA\Values\JobId($jobId));
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
@ -12,14 +12,18 @@ class Redis
|
|||||||
/**
|
/**
|
||||||
* @param string $name
|
* @param string $name
|
||||||
* @return string|null
|
* @return string|null
|
||||||
* @throws Exception|ConnectionException
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
public function get(string $name): ?string
|
public function get(string $name): ?string
|
||||||
{
|
{
|
||||||
if (!$this->client->exists($name)) {
|
if (!$this->client->exists($name)) {
|
||||||
throw new Exception($name);
|
throw new Exception($name);
|
||||||
}
|
}
|
||||||
return $this->client->get($name);
|
try {
|
||||||
|
return $this->client->get($name);
|
||||||
|
} catch (ConnectionException $exception) {
|
||||||
|
throw new Exception($exception->getMessage(), $exception->getCode(), $exception);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -27,7 +31,6 @@ class Redis
|
|||||||
* @param mixed $value
|
* @param mixed $value
|
||||||
* @param int $expirationTTL
|
* @param int $expirationTTL
|
||||||
* @return void
|
* @return void
|
||||||
* @throws ConnectionException
|
|
||||||
*/
|
*/
|
||||||
public function set(string $name, mixed $value, int $expirationTTL = 60 * 60 * 24): void
|
public function set(string $name, mixed $value, int $expirationTTL = 60 * 60 * 24): void
|
||||||
{
|
{
|
||||||
|
@ -20,7 +20,7 @@ class Schedule
|
|||||||
$commands = [];
|
$commands = [];
|
||||||
foreach ($schedule as $line) {
|
foreach ($schedule as $line) {
|
||||||
$line = trim($line);
|
$line = trim($line);
|
||||||
if (trim($line) === '' or str_starts_with('#', $line)) {
|
if (trim($line) === '' or str_starts_with($line, '#')) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
|
85
cli/src/Service/SystemInfo.php
Normal file
85
cli/src/Service/SystemInfo.php
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
<?php
|
||||||
|
namespace Incoviba\Service;
|
||||||
|
|
||||||
|
class SystemInfo
|
||||||
|
{
|
||||||
|
public function getAllInfo(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'memory' => [
|
||||||
|
'usage' => $this->getMemoryUsage(),
|
||||||
|
'peak' => $this->getPeakMemoryUsage()
|
||||||
|
],
|
||||||
|
'cpu' => [
|
||||||
|
'usage' => $this->getCpuUsage(),
|
||||||
|
'last_15minutes' => $this->getCpuUsageLast15minutes(),
|
||||||
|
'cores' => $this->getCpuCores()
|
||||||
|
]
|
||||||
|
];
|
||||||
|
}
|
||||||
|
public function get(string $name): int|null|float
|
||||||
|
{
|
||||||
|
return match ($name) {
|
||||||
|
'memory' => $this->getMemoryUsage(),
|
||||||
|
'peak_memory' => $this->getPeakMemoryUsage(),
|
||||||
|
'cpu' => $this->getCpuUsage(),
|
||||||
|
'cpu_last_15minutes' => $this->getCpuUsageLast15minutes(),
|
||||||
|
'cpu_cores' => $this->getCpuCores(),
|
||||||
|
default => null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public function getMemoryUsage(): float
|
||||||
|
{
|
||||||
|
return memory_get_usage(true);
|
||||||
|
}
|
||||||
|
public function getPeakMemoryUsage(): float
|
||||||
|
{
|
||||||
|
return memory_get_peak_usage(true);
|
||||||
|
}
|
||||||
|
public function getCpuUsage(): float
|
||||||
|
{
|
||||||
|
return $this->getCpuLoad()[0];
|
||||||
|
}
|
||||||
|
public function getCpuUsageLast15minutes(): float
|
||||||
|
{
|
||||||
|
return $this->getCpuLoad()[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected array $cpuLoad;
|
||||||
|
protected function getCpuLoad(): array
|
||||||
|
{
|
||||||
|
if (isset($this->cpuLoad)) {
|
||||||
|
$load = sys_getloadavg();
|
||||||
|
$cores = $this->getCpuCores();
|
||||||
|
array_walk($load, function (&$value) use ($cores) {
|
||||||
|
$value = $value / $cores;
|
||||||
|
});
|
||||||
|
$this->cpuLoad = $load;
|
||||||
|
unset($load);
|
||||||
|
}
|
||||||
|
return $this->cpuLoad;
|
||||||
|
}
|
||||||
|
protected function getCpuCores(): int
|
||||||
|
{
|
||||||
|
$cpu_cores = 1;
|
||||||
|
if (is_file('/proc/cpuinfo')) {
|
||||||
|
$cpuinfo = file('/proc/cpuinfo');
|
||||||
|
preg_match_all('/^processor/m', $cpuinfo, $matches);
|
||||||
|
$cpu_cores = count($matches[0]);
|
||||||
|
}
|
||||||
|
return $cpu_cores;
|
||||||
|
}
|
||||||
|
public function formatMemoryUsage(float $usage, string $unit = 'MB'): string
|
||||||
|
{
|
||||||
|
$sizeFactor = match ($unit) {
|
||||||
|
'MB' => 1024 * 1024,
|
||||||
|
'GB' => 1024 * 1024 * 1024,
|
||||||
|
default => 1
|
||||||
|
};
|
||||||
|
return number_format($usage / $sizeFactor, 2) . " {$unit}";
|
||||||
|
}
|
||||||
|
public function formatCpuLoad(float $load): string
|
||||||
|
{
|
||||||
|
return number_format($load * 100, 2) . '%';
|
||||||
|
}
|
||||||
|
}
|
5
cli/start_command
Executable file
5
cli/start_command
Executable file
@ -0,0 +1,5 @@
|
|||||||
|
#!/usr/bin/bash
|
||||||
|
|
||||||
|
printenv >> /etc/environment
|
||||||
|
|
||||||
|
/code/bin/incoviba
|
@ -25,6 +25,8 @@ services:
|
|||||||
- ./.key.env
|
- ./.key.env
|
||||||
volumes:
|
volumes:
|
||||||
- ${APP_PATH:-.}/:/code
|
- ${APP_PATH:-.}/:/code
|
||||||
|
- ${APP_PATH:-.}/fcgi.conf:/usr/local/etc/php-fpm.d/fcgi.conf
|
||||||
|
- ${APP_PATH:-.}/fcgi.conf:/usr/local/etc/php-fpm.d/www-extra.conf
|
||||||
- ./logs/php:/logs
|
- ./logs/php:/logs
|
||||||
|
|
||||||
db:
|
db:
|
||||||
@ -69,6 +71,7 @@ services:
|
|||||||
- ./logs:/logs
|
- ./logs:/logs
|
||||||
ports:
|
ports:
|
||||||
- "8084:80"
|
- "8084:80"
|
||||||
|
|
||||||
cli:
|
cli:
|
||||||
profiles:
|
profiles:
|
||||||
- cli
|
- cli
|
||||||
@ -78,6 +81,7 @@ services:
|
|||||||
image: php:incoviba-cli
|
image: php:incoviba-cli
|
||||||
container_name: incoviba_cli
|
container_name: incoviba_cli
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
entrypoint: [ "/code/entrypoint" ]
|
||||||
env_file:
|
env_file:
|
||||||
- ${CLI_PATH:-.}/.env
|
- ${CLI_PATH:-.}/.env
|
||||||
- ./.key.env
|
- ./.key.env
|
||||||
|
21
mqtt.compose.yml
Normal file
21
mqtt.compose.yml
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
services:
|
||||||
|
mqtt:
|
||||||
|
profiles:
|
||||||
|
- mqtt
|
||||||
|
container_name: incoviba_mqtt
|
||||||
|
image: maateen/docker-beanstalkd
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- incoviba_mqtt:/var/lib/beanstalkd
|
||||||
|
|
||||||
|
mqtt-admin:
|
||||||
|
profiles:
|
||||||
|
- mqtt
|
||||||
|
container_name: incoviba_mqtt_admin
|
||||||
|
image: mitulislam/beanstalkd-aurora:latest
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "8093:3000"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
incoviba_mqtt: {}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user